---
title: CLI
description: vgpu CLI commands, arguments, flags, and exit codes.
---

# CLI



The vgpu CLI provides command-line tooling for working with vgpu. Use it to validate WGSL shaders, query the vgpu documentation, inspect canonical example source, serve those same docs and examples over MCP, diagnose your local GPU environment, and set up the native runtime for Node.js workflows.

## Installation and usage

The CLI ships with the `vgpu` package, so no separate installation is required. Run any command with `npx vgpu`:

```bash
npx vgpu <command> [args] [flags]
npx vgpu --help
npx vgpu --version
```

The `examples` commands never execute fetched code.

## Command inventory

| Command                     | Dispatcher description                                                |
| --------------------------- | --------------------------------------------------------------------- |
| `check`                     | Validate and reflect a WGSL file as JSON                              |
| `docs`                      | Explore bundled VGPU documentation                                    |
| `examples`                  | Inspect canonical gallery source (never executes code)                |
| `mcp`                       | Serve documentation and examples as MCP tools over stdio              |
| `snapshot`                  | Compare the representative GPU pixel snapshot                         |
| `install-dawn`              | Download and verify the portable Node Dawn prebuild                   |
| `install-software-renderer` | Download and verify the portable CPU renderer                         |
| `doctor`                    | Verify this machine can render headless (JSON verdict + fixes)        |
| `native`                    | Show native Metal tooling help and dispatch to the optional companion |

## native

Native tooling compiles WGSL for application-owned Metal code. Its command dispatcher loads the
optional `@vgpu/native` companion only for native operations; other vgpu commands and native help
do not load the compiler.

<Callout type="warn">
  Warning: Native tooling is under development. The dispatcher, help, `native doctor`,
  `native check`, `native build`, and `native verify` are tested using real local tarballs installed offline with
  dependency install scripts disabled; build coverage publishes to an initially absent destination.
  An external Swift consumer executes the published compute and render programs on this host.
  Install the optional `@vgpu/native` beta at the same exact RC version as `vgpu`.
  Pin versions and validate your build environment; a broad release compatibility matrix is not qualified.
</Callout>

```bash
npx vgpu native --help
npx vgpu native check --help
```

The command surface is `doctor`, `check`, `build`, and `verify`. Project commands accept
`--config <file>` and default to `./vgpu.native.json` without searching parent directories. Native
execution uses Node.js 22. An absent or incompatible companion fails with a diagnostic, not a
successful no-op.

See [Build and verify a Metal package](/docs/native/macos/metal/tooling/build) for the command contract,
exit codes, and current implementation boundaries. `vgpu native doctor` checks the Metal build
toolchain; it is separate from the headless Node.js rendering checks performed by `vgpu doctor`.

## check

The `vgpu check` command validates a WGSL file without running it. On success it prints the shader's reflection data as JSON; on failure it reports the validation errors and exits non-zero. Use it to catch shader problems early, in your editor, pre-commit hooks, or CI.

```text
Usage: vgpu check <file.wgsl> [--require-validation]
```

| Flag                   | Argument |
| ---------------------- | -------- |
| `--require-validation` | none     |

Device-backed WGSL validation runs in `resolveShader`'s default `"auto"` mode: when this machine has a WebGPU device, invalid WGSL fails the command; when it does not, `check` warns once on stderr and still reports reflection. Pass `--require-validation` (or set `VGPU_VALIDATE=require`) to fail instead of degrading — useful in CI, where a missing device would otherwise silently reduce `check` to a parse-and-reflect pass. The JSON payload includes a `validation` object (`{ mode, attempted, ok, skipped? }`) describing exactly what ran, and error payloads carry `fix`/`where` when the underlying error provides them.

A failing device check never costs you the rest of the document: when validation rejects the shader (or, under `--require-validation`, when no device could be acquired), `check` still prints the full payload — `diagnostics`, `reflection` and `wgsl` — and reports the failure as `validation.error` (`{ code, message, fix?, where?, ... }`) with `ok: false`, exiting 1. So the JSON contract is the same whether or not the machine running `check` has a WebGPU device; only `validation` differs. Resolution failures (a missing import, a module that declares bindings, an invalid `VGPU_VALIDATE`) remain hard errors: they print a single error object on stderr with no payload.

```bash
npx vgpu check ./shaders/main.wgsl
npx vgpu check ./shaders/main.wgsl --require-validation
VGPU_VALIDATE=require npx vgpu check ./shaders/main.wgsl
```

## docs

The `vgpu docs` commands let you explore the vgpu documentation from the terminal. The full corpus — API reference and guides — ships inside the package, so every query runs locally and works offline. Use `ls` to browse the documentation tree, `cat` to print a page or symbol, `grep` to search across content, and `find` to look up the page to read next by name, keyword, or phrase.

```text
Usage: vgpu docs <command> [args] [flags]

Start here: vgpu docs cat getting-started.md   (the guide for using the latest API correctly)

Commands:
  ls [path]                  List packages or docs under a virtual path
  cat <path|symbol>          Print docs by virtual path or unique symbol
  grep [-i] [--package <pkg>] <pattern>
                             Search docs content; case-sensitive unless -i is used
  find <query>               Find symbols and docs paths by substring
  path <symbol|path>         Resolve a symbol or virtual path for shell usage
  symbols                    List indexed symbols
  help                       Show this help

Examples:
  vgpu docs cat getting-started.md
  vgpu docs ls /guides
  vgpu docs ls
  vgpu docs cat /@vgpu/core/Buffer.docs.md
  vgpu docs grep -i --package @vgpu/wgsl minify
  vgpu docs path Buffer
```

### docs cat

```bash
npx vgpu docs cat <path|symbol>
npx vgpu docs cat /@vgpu/core/Buffer.docs.md
```

### docs find

```bash
npx vgpu docs find <query>
npx vgpu docs find buffer
npx vgpu docs find "wgsl loader"
```

Every whitespace-separated word in the query must match, so multi-word phrases
narrow the result instead of returning nothing. `find` looks at symbol names,
doc paths, page titles, and the search keywords a page declares; only when that
finds nothing does it fall back to searching page bodies, which is what makes
prose (`"typescript wgsl import"`) and error codes
(`VGPU-WGSL-PKG-NOTFOUND`) resolve to a page. Use `grep` when you want every
content match with its line, and `find` when you want the page to read next.
Results are ranked best-match-first and capped at 20; a truncated response ends
with a line telling you how many matches were hidden so you can add a word.

### docs grep

```bash
npx vgpu docs grep [-i] [--package <pkg>] <pattern>
npx vgpu docs grep -i --package @vgpu/wgsl minify
```

| Flag        | Argument |
| ----------- | -------- |
| `-i`        | none     |
| `--package` | `<pkg>`  |

### docs help

```bash
npx vgpu docs help
npx vgpu docs --help
```

### docs ls

```bash
npx vgpu docs ls [path]
npx vgpu docs ls /guides
```

### docs path

```bash
npx vgpu docs path <symbol|path>
npx vgpu docs path Buffer
```

### docs symbols

```bash
npx vgpu docs symbols
```

## doctor

The `vgpu doctor` command verifies that the current machine can render headless with vgpu. It runs its checks end to end — including a real render unless you pass `--no-render` — and prints a JSON verdict with suggested fixes. The command exits `0` when the environment is healthy and non-zero when it is not.

```text
Usage: vgpu doctor [--no-render] [--pretty]

Diagnose whether this machine can render headless with vgpu/node. JSON is written by default.
```

| Flag          | Argument |
| ------------- | -------- |
| `--no-render` | none     |
| `--pretty`    | none     |

```bash
npx vgpu doctor
npx vgpu doctor --no-render
npx vgpu doctor --pretty
```

## examples

The `vgpu examples` commands let you search and inspect the source code of the vgpu example gallery without cloning the repository. Use `search` to find examples, `show` to list an example's files and metadata, `cat` to print a single file, and `pull` to copy an example's complete source into a local directory.

```text
vgpu examples — inspect canonical gallery source (never executes code)

Official origin: https://vgpu.sh

Usage:
  vgpu examples search <query> [--any] [--limit <n>] [--revision <sha256>] [--offline] [--pretty]
  vgpu examples show <id> [--revision <sha256>] [--offline] [--pretty]
  vgpu examples cat <id> <path> [--revision <sha256>] [--offline] [--json]
  vgpu examples pull <id> --out <directory> [--revision <sha256>] [--offline] [--force] [--pretty]
  vgpu examples cache path
  vgpu examples cache clear

Canonical agent invocation: npx vgpu examples ...
```

### examples search

```bash
npx vgpu examples search <query>
npx vgpu examples search "raymarching hdr" --any --limit 10 --pretty
```

| Flag         | Argument or range                             |
| ------------ | --------------------------------------------- |
| `--any`      | none                                          |
| `--limit`    | integer `<n>` from `1` to `100`; default `20` |
| `--revision` | lowercase `<sha256>`                          |
| `--offline`  | none                                          |
| `--pretty`   | none                                          |

### examples show

```bash
npx vgpu examples show <id>
npx vgpu examples show raymarched-fractal --pretty
```

| Flag         | Argument             |
| ------------ | -------------------- |
| `--revision` | lowercase `<sha256>` |
| `--offline`  | none                 |
| `--pretty`   | none                 |

### examples cat

```bash
npx vgpu examples cat <id> <path>
npx vgpu examples cat raymarched-fractal renderer.ts
npx vgpu examples cat raymarched-fractal renderer.ts --json
```

| Flag         | Argument             |
| ------------ | -------------------- |
| `--revision` | lowercase `<sha256>` |
| `--offline`  | none                 |
| `--json`     | none                 |

### examples pull

```bash
npx vgpu examples pull <id> --out <directory>
npx vgpu examples pull raymarched-fractal --out ./fractal --pretty
```

| Flag         | Argument               |
| ------------ | ---------------------- |
| `--out`      | required `<directory>` |
| `--revision` | lowercase `<sha256>`   |
| `--offline`  | none                   |
| `--force`    | none                   |
| `--pretty`   | none                   |

### examples cache

```bash
npx vgpu examples cache path
npx vgpu examples cache clear
```

### Revision and offline fields

| Input or output  | Value                                                         |
| ---------------- | ------------------------------------------------------------- |
| `--revision`     | Immutable lowercase SHA-256 revision                          |
| `--offline`      | No network requests; requires previously verified cached data |
| `lastVerifiedAt` | Included in applicable structured offline results             |

### Exit codes

| Code | Error class                                           |
| ---- | ----------------------------------------------------- |
| `0`  | success                                               |
| `2`  | `VGPU-EXAMPLES-USAGE`                                 |
| `3`  | `VGPU-EXAMPLES-NOT-FOUND`                             |
| `4`  | `VGPU-EXAMPLES-NETWORK`                               |
| `5`  | `VGPU-EXAMPLES-INTEGRITY` and incompatible API errors |
| `6`  | `VGPU-EXAMPLES-DESTINATION-EXISTS`                    |
| `7`  | `VGPU-EXAMPLES-FILESYSTEM`                            |

## mcp

VGPU exposes the existing docs and examples behavior as two typed MCP tools:

* `docs` supports `search`, `read`, `resolve`, `list`, `grep`, and `symbols` operations against the documentation bundled with the package.
* `examples` supports `search`, `show`, and `read`. On Linux and macOS, the local stdio transport also supports `download`.

Both `read` operations are paginated for transport-safe responses. They accept an optional UTF-16 `offset` and `limit`; `limit` defaults to and cannot exceed 65,536 code units. When more content remains, structured output includes `truncated: true` and the `nextOffset` to request.

Use the public, read-only Streamable HTTP endpoint when an agent only needs to inspect content:

```text
https://vgpu.sh/api/mcp
```

The hosted endpoint is stateless and implements the modern MCP 2026-07-28 transport. Configure clients for automatic or modern protocol negotiation; legacy session-based HTTP is intentionally rejected because a request may be served by any deployment instance. The endpoint is also advertised at `https://vgpu.sh/.well-known/mcp.json`.

Start the stdio server without filesystem writes when an agent is running locally:

```bash
npx vgpu mcp
```

Bare stdio exposes the same read-only operations as HTTP. To enable `download` on Linux or macOS, explicitly select its output boundary in one of three ways:

```bash
# Project-scoped clients that launch the server from the project directory
npx vgpu mcp --project-from-cwd

# A fixed project directory
npx vgpu mcp --output-dir /absolute/path/to/project

# A host-managed environment
VGPU_MCP_OUTPUT_DIR=/absolute/path/to/project npx vgpu mcp
```

`--output-dir` and `VGPU_MCP_OUTPUT_DIR` must name an existing absolute directory; VGPU canonicalizes it before serving. An explicit CLI selector overrides the environment variable, and `--output-dir` cannot be combined with `--project-from-cwd`. Without one of these configurations, `download` is omitted from the tool schema.

The agent supplies a normalized relative destination beneath that boundary:

```json
{
  "operation": "download",
  "id": "gradient",
  "destination": "examples/gradient"
}
```

Absolute destinations, dot segments, encoded paths, backslashes, control characters, the boundary directory itself, and existing destinations are rejected. Successful structured output reports the canonical absolute `destination`. VGPU coordinates concurrent VGPU writers with a lock and never exposes the human-operated `vgpu examples pull --force` behavior through MCP. Node does not expose a portable atomic no-replace rename for directories, so another process with write access to the output directory must not concurrently claim the same destination during final publication.

Use project-scoped Claude Code (`.mcp.json`) or Cursor (`.cursor/mcp.json`) configuration with `--project-from-cwd` only when that client launches the command from the project directory:

```json
{
  "mcpServers": {
    "vgpu": {
      "command": "npx",
      "args": ["-y", "vgpu", "mcp", "--project-from-cwd"]
    }
  }
}
```

Codex can use the same project-scoped pattern in `.codex/config.toml` when Codex launches the MCP process from the active workspace; omitting `cwd` preserves that inherited working directory:

```toml
[mcp_servers.vgpu]
command = "npx"
args = ["-y", "vgpu", "mcp", "--project-from-cwd"]
```

For global MCP configuration, use a fixed `--output-dir` or set `VGPU_MCP_OUTPUT_DIR` in the server environment. Claude Code and Codex MCP configurations load inside Conductor. Cursor reads `.cursor/mcp.json` only after you open the Conductor workspace in Cursor. Conductor does not define a separate MCP format. There is no cross-editor MCP convention that safely grants a local server write access to whichever workspace is currently active, so VGPU does not infer one. On Windows, the stdio server remains read-only even when an output boundary is configured because the CLI cannot provide the same safe publication guarantees there.

## install-dawn

The `vgpu install-dawn` command downloads and verifies the portable Dawn prebuild, the native WebGPU implementation vgpu uses to render in Node.js. Run it when `vgpu doctor` reports a missing Dawn runtime.

```text
Usage: vgpu install-dawn

Download and verify the portable Dawn binary for this platform.
Honors GH_TOKEN/GITHUB_TOKEN and VGPU_CACHE_DIR.
```

```bash
npx vgpu install-dawn
```

## install-software-renderer

The `vgpu install-software-renderer` command downloads and verifies a portable CPU renderer. Use it on machines without a usable GPU — such as CI runners or headless servers — so vgpu can still render.

```text
Usage: vgpu install-software-renderer

Download and sha256-verify the portable CPU software renderer for this platform.
Honors VGPU_CACHE_DIR.
```

```bash
npx vgpu install-software-renderer
```

## snapshot

The `vgpu snapshot` command is an internal self-test used by vgpu's own CI: it renders a scene built into the CLI inside the Docker GPU harness (`VGPU_DOCKER_TEST=1`) and compares the pixels against a committed baseline to catch toolchain regressions. To verify that your machine is set up correctly, use `vgpu doctor` instead.

```text
Usage: vgpu snapshot [--ci] [--update] [--baseline <path>]
```

`VGPU_DOCKER_TEST=1` is required.

| Flag         | Argument |
| ------------ | -------- |
| `--ci`       | none     |
| `--update`   | none     |
| `--baseline` | `<path>` |

```bash
VGPU_DOCKER_TEST=1 npx vgpu snapshot --ci
VGPU_DOCKER_TEST=1 npx vgpu snapshot --update
VGPU_DOCKER_TEST=1 npx vgpu snapshot --baseline <path>
```

## Global options

| Flag        | Shorthand | Output                |
| ----------- | --------- | --------------------- |
| `--help`    | `-h`      | CLI help              |
| `--version` | `-v`      | installed CLI version |

```bash
npx vgpu --help
npx vgpu --version
```


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: vgpu Examples API
description: Read-only, tokenless discovery for versioned vgpu example manifests and source artifacts.
---

# vgpu Examples API



The examples API is the machine-readable source behind the vgpu examples workflow. Coding agents should prefer the stateless, read-only MCP endpoint at `https://vgpu.sh/api/mcp` with automatic or modern protocol negotiation; use `npx vgpu mcp --project-from-cwd` or an absolute `--output-dir` when the agent also needs to download an example. The MCP and CLI surfaces both reuse the compatibility checks and integrity verification described here.

## Discovery

Start with `GET /.well-known/vgpu-examples.json`. It lists supported contracts and links to the mutable latest pointer. The API requires no token or other authentication.

The complete OpenAPI 3.1 description is available at [`/openapi.json`](https://vgpu.sh/openapi.json).

```bash
curl https://vgpu.sh/.well-known/vgpu-examples.json
curl https://vgpu.sh/api/examples/v1/latest.json
```

The latest pointer names an immutable revision and provides the SHA-256 digest of its index. Follow its `indexUrl`; do not construct a revision URL from an unvalidated value.

## Indexes and manifests

An immutable index lists examples and links each one to a manifest. A manifest contains metadata plus a `files` array. Every file entry is a hypermedia link with its raw artifact URL, byte size, content type, and SHA-256 digest.

Raw artifact paths may contain slashes and are intentionally not modeled as a conventional OpenAPI path parameter. Follow the `url` returned in the manifest rather than assembling a path yourself.

## Caching and integrity

Discovery and latest-pointer responses use short, revalidated caches. Revision indexes, manifests, and raw source artifacts are immutable and may be cached for one year. All successful artifact responses include an `ETag`; send it in `If-None-Match` to receive `304 Not Modified` when appropriate.

Before using downloaded content, verify the index, manifest, aggregate, and file SHA-256 values. The preferred CLI workflow performs these checks automatically.

## Methods and CORS

Every API resource supports `GET`, `HEAD`, and `OPTIONS`. `HEAD` returns the same status and headers as `GET` without a body. `OPTIONS` returns the public CORS policy. Cross-origin reads are allowed without credentials, and conditional requests may send `If-None-Match`.

`POST`, `PUT`, `PATCH`, and `DELETE` return `405 Method Not Allowed` with `Allow: GET, HEAD, OPTIONS`. The API is read-only.

## Errors

Errors keep a stable JSON envelope:

```json
{
  "error": {
    "code": "VGPU-EXAMPLES-NOT-FOUND",
    "message": "Artifact not found"
  }
}
```

`404` means the requested immutable revision or artifact does not exist. Rediscover from `/.well-known/vgpu-examples.json` and follow its current links. `405` means the method is unsupported. `500` uses the opaque `VGPU-EXAMPLES-STORAGE` code; retry later rather than treating it as a missing example. The frozen wire body intentionally contains no deployment-specific recovery details.

## CLI workflow

Use the CLI to list, inspect, and copy examples without hand-implementing this protocol:

```bash
npx vgpu examples
npx vgpu examples search gradient
npx vgpu examples show gradient
npx vgpu examples pull gradient --out ./gradient
```

See the [CLI reference](/docs/cli) for command options and exit codes.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: vgpu Docs
description: Build WebGPU applications for browsers and Node.js, and explore WGSL integration with native Metal code.
---

# vgpu Docs



vgpu is a TypeScript library for building WebGPU applications with one composable API. Write modular WGSL once, then use the same shaders for interactive canvases, headless rendering, images, video, and automated tests. The Native section documents the in-development WGSL-to-Metal workflow; its complete installed toolchain is not published yet.

## How to use these docs

* [Get started](/docs/get-started) — install vgpu and render your first frame.
* [Learn the concepts](/docs/concepts) — understand GPUs, targets, frames, effects, and adapters.
* [Integrate WGSL with native Metal](/docs/native) — generate a self-contained Swift shader package for application-owned Metal code.
* [Explore the examples](/examples) — see live WebGPU demos and inspect their source.
* [Explore the guides](/docs/guides) — solve specific problems involving integrations, performance, testing, and shader authoring.
* [Browse the API reference](/docs/reference) — look up packages, types, and functions.

Using a coding agent? Run `npx vgpu` to give it access to the docs, verified examples, validation tools, and runtime diagnostics.

## Tools and workflows

* [CLI](/docs/cli) — explore documentation, inspect examples, validate WGSL, and diagnose the runtime.
* [MCP](/docs/mcp) — connect agents to VGPU documentation and verified examples.
* [ML](/docs/ml) — run ONNX models alongside vgpu on a shared `GPUDevice`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: MCP
description: Set up VGPU MCP in coding agents to search documentation, inspect verified examples, and opt into scoped local downloads.
---

# MCP



Connect coding agents directly to VGPU documentation and verified examples through the [Model Context Protocol](https://modelcontextprotocol.io). Start with the hosted HTTP server for a read-only setup that requires no authentication or installation. Use local stdio when an agent needs package-versioned docs, an offline examples cache, or explicitly scoped example downloads.

## Quick setup

Use `add-mcp` to detect installed MCP clients and add the hosted VGPU server globally:

```bash
npx -y add-mcp https://vgpu.sh/api/mcp -g
```

Remove `-g` to configure clients for the current project instead. The installer lets you review its detected clients before writing their configuration. No VGPU account or authorization flow is required.

## What is VGPU MCP?

VGPU MCP is the official agent interface for the same documentation and verified example source exposed by the VGPU website and CLI. It gives an agent typed tools to:

* Search documentation by concept and read the matching guide or API reference.
* Resolve API symbols without guessing their package or documentation path.
* Find examples by topic, inspect their manifests, and read individual source files.
* Download a verified example only when a local server has been given an explicit output boundary.

VGPU offers two transports. Hosted HTTP is public, stateless, and read-only. Local stdio runs from the `vgpu` npm package and can additionally use the verified local cache or enable confined filesystem writes.

## Hosted HTTP

The recommended server for searching and reading content is:

```text
https://vgpu.sh/api/mcp
```

This hosted endpoint follows the latest stable release published on vgpu.sh. It is not version-matched to a project's dependency; use local stdio when the documentation must match an installed package or prerelease.

| Setting        | Value                                  |
| -------------- | -------------------------------------- |
| Name           | `vgpu`                                 |
| Transport      | Streamable HTTP                        |
| Authentication | None                                   |
| Access         | Read-only                              |
| Protocol       | Modern MCP `2026-07-28`                |
| Discovery      | `https://vgpu.sh/.well-known/mcp.json` |

Use automatic protocol negotiation when the client offers it. The endpoint is stateless and intentionally rejects legacy session-based HTTP because requests may be served by different deployment instances.

Hosted HTTP never writes to disk and does not expose the local-only `download` operation or `offline` input.

## Connect manually

Use the hosted URL in any client that supports modern Streamable HTTP. These are common configurations.

### Claude Code

```bash
claude mcp add --transport http vgpu https://vgpu.sh/api/mcp
```

Start a new Claude Code session or run `/mcp` to confirm that the `vgpu` server and its two tools are available.

### Codex CLI

```bash
codex mcp add vgpu --url https://vgpu.sh/api/mcp
codex mcp list
```

### Cursor

Add the server to a project-specific `.cursor/mcp.json` or your global Cursor MCP configuration:

```json
{
  "mcpServers": {
    "vgpu": {
      "url": "https://vgpu.sh/api/mcp"
    }
  }
}
```

### Other clients

In clients that provide an **Add MCP server** or **Add custom connector** form, use:

| Field          | Value                     |
| -------------- | ------------------------- |
| Name           | `vgpu`                    |
| URL            | `https://vgpu.sh/api/mcp` |
| Transport      | Streamable HTTP           |
| Authentication | None                      |

Client commands and settings screens can change. If a client asks for a protocol version, choose automatic negotiation or modern MCP rather than legacy session-based HTTP.

## Try it

After connecting, ask the agent naturally. For example:

* “Search the VGPU docs for render pipelines and summarize the setup.”
* “Resolve the API reference for the texture type used by VGPU.”
* “Find examples related to gradients and show me the files in the best match.”
* “Read the main source file from the `gradient` example and explain how it works.”

The agent can compose operations. A typical documentation flow is `search` or `resolve`, followed by `read`. A typical example flow is `search`, `show` to inspect the manifest, and then `read` for selected files.

## Tools

### `docs`

Search and navigate the canonical VGPU documentation corpus.

| Operation | Purpose                                                      | Main input                     |
| --------- | ------------------------------------------------------------ | ------------------------------ |
| `search`  | Find relevant documents by concept                           | `query`                        |
| `resolve` | Resolve a symbol or documentation target                     | `target`                       |
| `list`    | Browse packages and virtual documentation paths              | `path`, default `/`            |
| `grep`    | Find an exact pattern with optional package and case filters | `pattern`                      |
| `symbols` | Search or list indexed API symbols                           | optional `query` and `package` |
| `read`    | Read a resolved guide or API document                        | `target`                       |

### `examples`

Search and inspect canonical examples without executing their code.

| Operation  | Purpose                                                       | Main input                                               |
| ---------- | ------------------------------------------------------------- | -------------------------------------------------------- |
| `search`   | Find examples by topic                                        | `query`                                                  |
| `show`     | Inspect an example manifest and its file list                 | `id`                                                     |
| `read`     | Read one verified file from an example                        | `id` and `path`                                          |
| `download` | Publish a verified example beneath an approved local boundary | `id` and relative `destination`; scoped local stdio only |

Example operations can pin an immutable lowercase SHA-256 `revision`. On local stdio, `search`, `show`, and `read` also accept `offline: true` to prohibit network access and use only previously verified cache entries.

Both `read` operations accept an optional UTF-16 `offset` and `limit`; `limit` defaults to and cannot exceed 65,536 code units. When more content remains, the structured result includes `truncated: true` and `nextOffset`. Pass that value as the next `offset` to continue reading.

Tool failures return bounded structured errors with stable VGPU error codes. Example manifests and files retain the same compatibility and SHA-256 integrity verification used by the human CLI.

## Local stdio

Run the read-only local server from the public `vgpu` package:

```bash
npx -y vgpu mcp
```

For Claude Code, Cursor, and clients that use the common JSON shape, configure the command instead of a URL:

```json
{
  "mcpServers": {
    "vgpu": {
      "command": "npx",
      "args": ["-y", "vgpu", "mcp"]
    }
  }
}
```

Codex uses TOML:

```toml
[mcp_servers.vgpu]
command = "npx"
args = ["-y", "vgpu", "mcp"]
```

Bare stdio does not advertise `download`. It serves documentation bundled with that installed VGPU package and, unlike hosted HTTP, can read from the verified examples cache with `offline: true`.

## Enable local downloads

Filesystem writes are opt-in and supported only on Linux and macOS. Select one output boundary when starting the server:

```bash
# The MCP host launches the process from the active project
npx -y vgpu mcp --project-from-cwd

# A fixed project
npx -y vgpu mcp --output-dir /absolute/path/to/project

# A host-managed environment
VGPU_MCP_OUTPUT_DIR=/absolute/path/to/project npx -y vgpu mcp
```

`--output-dir` and `VGPU_MCP_OUTPUT_DIR` must name an existing absolute directory. VGPU resolves symlinks and canonicalizes that boundary before starting. An explicit CLI selector overrides the environment variable, and `--output-dir` cannot be combined with `--project-from-cwd`.

The agent supplies a normalized relative destination beneath the selected boundary:

```json
{
  "operation": "download",
  "id": "gradient",
  "destination": "examples/gradient"
}
```

VGPU returns the canonical absolute destination after publication. It rejects absolute or encoded agent paths, dot segments, backslashes, control characters, symlink ancestors, the boundary itself, and existing destinations before repository access. MCP never exposes the human CLI's `--force` behavior.

Use `--project-from-cwd` only when the MCP host launches the command from the active project directory. For a global configuration, prefer a fixed `--output-dir` or `VGPU_MCP_OUTPUT_DIR`. Codex configurations should omit `cwd` when they are meant to inherit the active workspace. Conductor inherits the selected host's Claude Code, Codex, or Cursor MCP configuration; it does not define another MCP format. MCP does not provide a portable workspace-root authorization boundary, so VGPU never infers one.

On Windows, local stdio remains read-only even when an output boundary is configured. This allows one shared cross-platform configuration without advertising a filesystem operation the CLI cannot publish with the same guarantees.

## Security

* Verify that remote configurations use the official `https://vgpu.sh/api/mcp` endpoint. No token or authentication header is required.
* Hosted HTTP is read-only. It cannot execute example source, access your filesystem, or publish example directories.
* Local stdio does not publish into a project unless its user-controlled startup command selects an output boundary. The agent can choose only a new relative descendant within that boundary.
* Keep human confirmation enabled for filesystem tool calls when your MCP client supports it, and review generated code before running it.
* Example downloads verify their manifest and file hashes, coordinate cooperating writers with a lock, and clean up failed or cancelled staging directories.

Node.js does not expose a portable atomic no-replace rename for directories. Do not let another process concurrently claim the exact same destination during the final publication step.

## Troubleshooting

| Symptom                                       | What to check                                                                                                                                                       |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The client cannot connect to hosted HTTP      | Confirm the exact URL and select automatic or modern protocol negotiation; legacy session-based HTTP is rejected.                                                   |
| The server is connected but tools are missing | Reload or restart the client, then confirm both `docs` and `examples` appear in its MCP tool list.                                                                  |
| `download` is missing                         | Use local stdio on Linux or macOS and configure `--project-from-cwd`, `--output-dir`, or `VGPU_MCP_OUTPUT_DIR`. Hosted HTTP, bare stdio, and Windows are read-only. |
| `offline` is rejected                         | Use local stdio. Hosted HTTP reads deployed artifacts and intentionally omits the local-cache option.                                                               |
| A read result is truncated                    | Call the same `read` operation again with the returned `nextOffset`.                                                                                                |
| A destination is rejected                     | Choose a new normalized relative directory without `.`, `..`, backslashes, encoded separators, or an existing path.                                                 |

## Choose a transport

| Need                                           | Recommended setup                              |
| ---------------------------------------------- | ---------------------------------------------- |
| Search and read docs or examples               | Hosted HTTP at `https://vgpu.sh/api/mcp`       |
| Use VGPU docs matching an installed package    | Bare local stdio                               |
| Work from a previously verified examples cache | Bare local stdio with `offline: true`          |
| Download into the active project               | Local stdio with `--project-from-cwd`          |
| Download into a fixed project                  | Local stdio with `--output-dir /absolute/path` |

See the [CLI reference](/docs/cli#mcp) for the complete command syntax.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Compilation
description: Pipelines compile lazily on first use; pre-warm them during load so the first frame doesn't hitch.
---

# Compilation



Pipelines compile lazily: the first `draw()` against a new target pays the pipeline creation cost, and that cost lands inside your frame. WebGPU keys pipelines by shader *and* render signature — the tuple of color formats, depth format, and sample count — so the same WGSL rendering into a canvas and into an MSAA target means two compilations. `compile()` moves that work into load time.

Pipeline compilation is separate from shader preparation. A `.wgsl` import through the `@vgpu/wgsl` loader already carries its reflection, so `draw(gpu)` and `effect(gpu)` validate that metadata synchronously when you create them and never parse WGSL; the native shader module and pipeline are what `compile()` warms.

## Pre-warming with a target

For an existing offscreen target, `await draw.compile(target)` and `await effect.compile(target)` warm exactly that signature and resolve back to the same object:

```wgsl
// ocean.wgsl
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, 0.8, 1.0);
}
```

```wgsl
// triangle.wgsl
struct Out { @builtin(position) position: vec4f }

@vertex fn vs_main(@builtin(vertex_index) vi: u32) -> Out {
  var pts = array<vec2f, 3>(vec2f(-0.5, -0.5), vec2f(0.5, -0.5), vec2f(0.0, 0.5));
  var out: Out;
  out.position = vec4f(pts[vi], 0.0, 1.0);
  return out;
}

@fragment fn fs_main() -> @location(0) vec4f {
  return vec4f(1.0, 0.4, 0.2, 1.0);
}
```

```ts
import { init, draw, effect, target } from "vgpu";
import oceanShader from "./ocean.wgsl"; // fragment-only effect
import triangleShader from "./triangle.wgsl"; // vs_main + fs_main, three hardcoded vertices

const gpu = await init();
const offscreen = target(gpu, { size: [512, 512] });

// ---cut---
const ocean = effect(gpu, oceanShader);
const tri = draw(gpu, { shader: triangleShader });

await Promise.all([ocean.compile(offscreen), tri.compile(offscreen)]);
tri.draw(offscreen);
ocean.draw(offscreen);
```

The pipelines are cached per signature at the device level, so those first `draw()` calls — and every draw after them — just encode work.

## Pre-warming for a canvas surface

A live surface works the same way, during loading and outside any frame. Pass it to `compile()`, then render through `frame()` or `frameLoop()`:

```ts
import { init, effect, frameLoop, surface } from "vgpu";
import oceanShader from "./ocean.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;

// ---cut---
const canvasSurface = surface(gpu, canvas);
const ocean = effect(gpu, oceanShader);

await ocean.compile(canvasSurface); // no frame needed — no canvas texture is acquired

frameLoop(gpu, (currentFrame) => {
  currentFrame.pass(canvasSurface, (pass) => pass.draw(ocean)); // drawing stays inside the frame
});
```

`compile(canvasSurface)` reads the surface's configured render signature — its `format`, including an explicit `surface(..., { format })` override, plus the depth format and sample count it was created with. A plain `surface(gpu, canvas)` has no depth attachment and a sample count of 1. It does not acquire the current canvas texture, read or allocate attachments, resize the canvas, notify `onResize` listeners, or submit work. `compileSync(canvasSurface)` and `draw(gpu, { targets: [canvasSurface] })` prepare the same pipeline synchronously.

A surface created with `depth` or `msaa` reports those in its signature, so the same call warms the exact pipeline its passes need:

```ts
import { init, effect, frameLoop, surface } from "vgpu";
import oceanShader from "./ocean.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const ocean = effect(gpu, oceanShader);

// ---cut---
const sceneSurface = surface(gpu, canvas, { depth: true, msaa: true });

await ocean.compile(sceneSurface); // warms format + "depth24plus" + 4 samples

frameLoop(gpu, (currentFrame) => {
  currentFrame.pass(sceneSurface, ocean);
});
```

Prefer `compile(surface)` once the surface exists: it cannot drift from the surface's real depth format and sample count. The signature excludes size, so resizing the surface keeps every pipeline compiled for it. Compiling against the surface or against the equivalent signature — `{ colors: [canvasSurface.format] }` for a plain surface, `{ colors: [sceneSurface.format], depth: "depth24plus", sampleCount: 4 }` for the one above — warms the same cached pipeline.

<Callout type="warn">
  Warning: Preparation is not drawing. A one-shot `ocean.draw(canvasSurface)` outside a frame still throws `VGPU-SURFACE-NOT-IN-FRAME`; encode surface draws inside `frame(gpu, ...)` or `frameLoop(gpu, ...)`. Compiling against a disposed surface throws `VGPU-SURFACE-DISPOSED` — create a live surface first.
</Callout>

## Compiling without a target

Sometimes the target doesn't exist yet. Pass a signature object instead: `colors` is required, `depth` and `sampleCount` are optional. For a future canvas surface using the default format, query `navigator.gpu.getPreferredCanvasFormat()` rather than assuming a format:

```ts
import { init, effect, frame, surface } from "vgpu";
import oceanShader from "./ocean.wgsl";

const gpu = await init();
const ocean = effect(gpu, oceanShader);

// ---cut---
const format = navigator.gpu.getPreferredCanvasFormat();
await ocean.compile({ colors: [format] });

// Later, surface() selects the same preferred format by default.
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);
frame(gpu, (frame) => frame.pass(canvasSurface, ocean));
```

Once the surface exists, pass it directly — `await ocean.compile(canvasSurface)` — as in the previous section. Use a signature only when you prepare before the surface is created.

The signature must match the actual target's color formats, depth format, and sample count. The surface in this example is created without `depth` or `msaa`, so it has no depth attachment and a sample count of 1, and the signature omits both optional fields. For a surface created with `{ depth: true, msaa: true }`, add `depth: "depth24plus", sampleCount: 4`. For offscreen targets, use their configured formats and include depth/MSAA when enabled, or pass the existing target or surface directly to `compile()`.

<Callout type="info">
  Good to know: `getPreferredCanvasFormat()` returns the system's preferred `rgba8unorm` or `bgra8unorm` canvas texture format. Compiling a different valid signature can succeed, but it doesn't warm the pipeline needed by the actual target: the first render still compiles that pipeline lazily.
</Callout>

## `compileSync()`

`compileSync(target)` is the blocking twin: same cache, same signatures, but it creates the pipeline right now. Use it in tools and tests where jank doesn't matter. If an async `compile()` for the same signature is in flight, the synchronous result wins and the pending promise resolves with it.

```wgsl
// grid.wgsl
@vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
  var pts = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
  return vec4f(pts[vi], 0.0, 1.0);
}

@fragment fn fs_main() -> @location(0) vec4f {
  return vec4f(0.1, 0.4, 0.7, 1.0);
}
```

```ts
import { init, draw, target } from "vgpu";
import gridShader from "./grid.wgsl"; // fullscreen-triangle vs_main + flat fs_main

const gpu = await init();
const offscreen = target(gpu, { size: [2048, 2048], depth: true });
const grid = draw(gpu, { shader: gridShader });

grid.compileSync(offscreen);
```

## Errors

A failed `compile()` rejects its promise — the error belongs to the call site, so catch it where you scheduled the warm-up:

```ts
import { init, draw } from "vgpu";
import triangleShader from "./triangle.wgsl";

const gpu = await init();
const tri = draw(gpu, { shader: triangleShader });

try {
  await tri.compile({ colors: [navigator.gpu.getPreferredCanvasFormat()] });
} catch (error) {
  console.error('Pipeline failed to compile', error);
}
```

The lazy path is different: since `draw()` returns immediately, a pipeline that fails to compile on first use reports through [`gpu.onError`](/docs/reference/vgpu/gpu#onerror), and `gpu.settled()` lets tests wait for those deliveries. Pre-warmed or not, the failure never lands twice.

## Disposing while a compile is pending

Compiled pipelines belong to the device-wide cache, not to the draw that requested them. Two draws or effects with the same shader and options compiling for the same signature share one compilation and one pipeline. [`dispose()`](/docs/reference/vgpu/draw#draw) retires only its own owner, so it never cancels or poisons that shared work:

```ts
import { init, effect, VGPUError } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const oceanSource = prepareShader(`
  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return vec4f(uv, 0.8, 1.0);
  }
`);

// ---cut---
const signature = { colors: [navigator.gpu.getPreferredCanvasFormat()] };
const preview = effect(gpu, oceanSource, { label: "preview" });
const ocean = effect(gpu, oceanSource, { label: "ocean" });

const previewReady = preview.compile(signature).catch((error: unknown) => {
  if (error instanceof VGPUError && error.code === "VGPU-DRAW-DISPOSED") return; // retired on purpose
  throw error;
});
const oceanReady = ocean.compile(signature); // shares the preview's pipeline compilation

preview.dispose(); // the preview closed before its pipeline was ready
await Promise.all([previewReady, oceanReady]); // ocean resolves; its pipeline stays cached
```

The pending `preview.compile()` is not rejected at `dispose()`. It settles when the shared compilation does, then rejects with `VGPU-DRAW-DISPOSED` at `preview.compile` — whether the pipeline compiled or failed — and is not reported again through `gpu.onError`. `ocean.compile()` resolves or fails exactly as it would have without the disposal. A disposed compute behaves the same way with `VGPU-COMPUTE-DISPOSED`. After `dispose()`, a new `compile()` or `compileSync()` on that owner throws synchronously; create a new draw, effect, or compute instead.

## Render bundles

Recording a [bundle](/docs/concepts/render-bundles) needs every pipeline immediately, so anything you didn't pre-warm compiles synchronously at record time. See [compilation at record time](/docs/concepts/render-bundles#compilation-at-record-time) for that flow.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Context
description: init() creates the Gpu context; every surface, target, effect, and frame is created from it.
---

# Context



Everything in vgpu starts from one call. `init()` requests the WebGPU adapter and device and returns a [`Gpu`](/docs/reference/vgpu/gpu#gpu) context. Every other object — surfaces, targets, effects, draws, frames — is created from that context, so all of them share one device.

```wgsl
// gradient.wgsl
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, 0.4, 1.0);
}
```

```ts
import { init, effect, surface, target } from "vgpu";
import gradientShader from "./gradient.wgsl"; // prepared at build time by the @vgpu/wgsl loader

const gpu = await init();

const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas); // the canvas you render into
const colorTarget = target(gpu, { size: [256, 256] }); // an offscreen texture
const gradient = effect(gpu, gradientShader);

// Render the gradient onto the canvas once
gradient.draw(canvasSurface);
```

## Create resources once, draw every frame

Create the context, surface, and effects once, up front. Each `draw()` renders immediately; rendering should encode work, not rebuild long-lived resources every tick.

The expensive objects — context, surface, effect — live outside your render code and are reused by every draw. What changes per frame is data, not resources.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Draws
description: draw(gpu, opts) renders geometry with custom vertex buffers — you write the vertex stage, geometry(gpu, ...) supplies the buffers.
---

# Draws



A [`Draw`](/docs/reference/vgpu/draw#draw) renders geometry with custom vertex buffers: you write both the vertex and the fragment stage, and a geometry supplies the buffers. If you want to render a full-screen shader instead, use an [Effect](/docs/concepts/effects).

## Draw a geometry

`geometry(gpu, geometry)` turns geometry from `vgpu/scene` into vertex and index buffers. Your vertex shader declares the attributes it consumes — `@location(0) position`, `@location(1) normal` — and the geometry feeds them.

```wgsl
// cube.wgsl
struct Camera { viewProjection: mat4x4f }
struct Model { model: mat4x4f }
@group(0) @binding(0) var<uniform> camera: Camera;
@group(0) @binding(1) var<uniform> model: Model;

struct VertexOut { @builtin(position) position: vec4f, @location(0) normal: vec3f }

@vertex fn vs_main(@location(0) position: vec3f, @location(1) normal: vec3f) -> VertexOut {
  var out: VertexOut;
  out.position = camera.viewProjection * model.model * vec4f(position, 1.0);
  out.normal = normal;
  return out;
}

@fragment fn fs_main(@location(0) normal: vec3f) -> @location(0) vec4f {
  let light = max(dot(normalize(normal), normalize(vec3f(1.0, 1.0, 1.0))), 0.15);
  return vec4f(vec3f(0.2, 0.5, 1.0) * light, 1.0);
}
```

```ts
import { init, draw, geometry, target } from "vgpu";

const gpu = await init();

// ---cut---
import { box, composeMatrix, orbitRig, perspective, rigPose, viewMatrices } from "vgpu/scene";
import cubeShader from "./cube.wgsl";

const colorTarget = target(gpu, { size: [1280, 720], depth: true });
const rig = orbitRig({ yaw: 0.59, pitch: 0.51, distance: 4.12 });
const pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const projection = perspective({ fov: 45, near: 0.1, far: 100 }, 16 / 9, new Float32Array(16));
const camera = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
viewMatrices(rigPose(rig, pose), projection, camera);
const model = composeMatrix({}, new Float32Array(16));

const cube = draw(gpu, { shader: cubeShader, geometry: geometry(gpu, box({ size: 1 })) });
cube.set({
  camera: { viewProjection: camera.viewProjection },
  model: { model },
});

cube.draw(colorTarget);
```

Everything works like the rest of vgpu: bindings come from the reflection the `@vgpu/wgsl` loader prepared for `cube.wgsl` at build time, `set()` writes uniforms by name, and the draw renders one-shot into any target. Pipelines are compiled per target format and cached, so the same `Draw` can render into different targets. See [Compilation](/docs/concepts/compilation) to pre-warm each signature before the first draw.

The shader chooses the camera's group and binding. `cube.set({ camera: { viewProjection } })` connects the matrix by the WGSL variable name; scene utilities do not reserve a group or inject uniforms. `set()` copies the values at the time of the call, so call it again after changing a matrix. See [Scene composition](/docs/guides/scene-composition) for hierarchies, external camera state, and instances. For shared instance streams, declare the complete attribute layout in each consuming vertex entry, including inputs unused by a particular pass.

Three details specific to geometry:

* For depth-tested 3D presented directly to the canvas, use `surface(gpu, canvas, { depth: true, msaa: true })`. Use an offscreen `target(gpu, { depth: true })` when another pass needs to sample the scene image; [Two-pass rendering](/docs/guides/two-pass-rendering) shows both paths. Deep scenes fight z-fighting with reversed-Z: `depth: { compare: "greater" }` on the draw, `clearDepth: 0` on the pass.
* A closed geometry like this box never shows its back faces — add `cull: "back"` to the draw and skip roughly half the fragment work.
* `GeometryLike` is an open interface: `geometry(gpu)` builds one from `vgpu/scene` geometry, but you can also pass your own `GPUBuffer`s and vertex layouts. See the [reference](/docs/reference/vgpu/draw#geometrylike).

## No geometry? You spawn triangles

Leave `geometry` out and the draw runs with no buffers at all: `vertices` defaults to `3`, so every instance is one triangle whose corners you position from `@builtin(vertex_index)`. Combined with `instances`, that spawns a particle system from nothing:

```wgsl
// smoke.wgsl
struct Params { time: f32 }
@group(0) @binding(0) var<uniform> params: Params;

struct Out { @builtin(position) position: vec4f, @location(0) fade: f32 }

@vertex fn vs_main(@builtin(vertex_index) v: u32, @builtin(instance_index) i: u32) -> Out {
  var corners = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(0.0, 1.5));
  let seed = fract(sin(f32(i) * 12.9898) * 43758.5453);
  let life = fract(seed + params.time * 0.05);          // 0 -> 1, then respawn
  let center = vec2f(seed * 2.0 - 1.0, life * 2.2 - 1.1); // drifts upward
  let size = 0.01 + life * 0.04;                          // grows as it rises

  var out: Out;
  out.position = vec4f(center + corners[v] * size, 0.0, 1.0);
  out.fade = 1.0 - life;
  return out;
}

@fragment fn fs_main(@location(0) fade: f32) -> @location(0) vec4f {
  return vec4f(vec3f(0.35) * fade, 1.0); // dims into the dark background
}
```

```ts
import { init, draw, surface } from "vgpu";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);

// ---cut---
import smokeShader from "./smoke.wgsl";

const smoke = draw(gpu, { shader: smokeShader, instances: 10_000 });

smoke.set({ params: { time: 2.5 } }); // drive with clock(gpu).time in a frame loop
smoke.draw(canvasSurface);
```

One draw call, 10,000 smoke puffs, zero buffers — each particle derives its position, size, and fade from `instance_index` and `time`. Counts can also change per call: `smoke.draw({ target: surface, instances: 500 })`.

See it live: the [instanced rendering example](/examples/instanced-rendering) drives a 125k-cube lattice from a single instance stream.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Effects
description: An effect is a full-screen fragment shader; chain effects by binding a target as another effect's input.
---

# Effects



An [`Effect`](/docs/reference/vgpu/effect#effect) is a full-screen fragment shader created with `effect(gpu, shader)`. Its pipeline compiles lazily on first use; call `await effect.compile(target)` during load if you want to pre-warm it. See [Compilation](/docs/concepts/compilation) for the full pre-warm flow. Every draw fills the whole target — you only write the fragment.

`shader` is a prepared [`ShaderSource`](/docs/reference/wgsl/resolved-shader) — WGSL plus the reflection vgpu reads bindings from. Keep static shaders in `.wgsl` files and import them through the `@vgpu/wgsl` loader ([Next.js and other bundlers](/docs/guides/nextjs)), which prepares them at build time so the browser never loads the WGSL parser. A raw WGSL string throws `VGPU-SHADER-SOURCE-UNPREPARED`; wrap WGSL you build at runtime in `prepareShader()` from `@vgpu/wgsl/prepare` once per source change.

Effects chain through targets: render one effect into an offscreen [`Target`](/docs/reference/vgpu/target#target), then bind that target as a texture input of the next effect with `set()`.

The `uv` varying comes from the fullscreen vertex stage `effect(gpu)` supplies when your shader declares no `@vertex` entry. It is top-origin: `(0, 0)` is the
top-left corner and `v` grows downward — the same convention as WebGPU texture
coordinates, `@builtin(position)`, and `target.color.read({ mipLevel: 0, region: "all" })`. Sampling any texture
with this `uv` needs no flip: a pass that samples `src` at `uv` reproduces the
image exactly. If you are porting a WebGL or Shadertoy shader that assumes
`v` grows upward, invert once at the boundary (`1.0 - uv.y`) and keep
everything else flip-free.

```wgsl
// scene.wgsl
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, 1.0, 1.0);
}
```

```wgsl
// post.wgsl — reads the scene texture and inverts its colors
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let base = textureSampleLevel(src, samp, uv, 0.0);
  return vec4f(1.0 - base.rgb, 1.0);
}
```

```ts
import { init, effect, frame, sampler, surface, target } from "vgpu";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);

// ---cut---
import sceneShader from "./scene.wgsl";
import postShader from "./post.wgsl";

const scene = target(gpu, { size: [1280, 720] });

const sceneEffect = effect(gpu, sceneShader);
const post = effect(gpu, postShader);
post.set({
  src: scene,
  samp: sampler(gpu, { minFilter: 'linear', magFilter: 'linear' }),
}); // the offscreen result becomes the post input

frame(gpu, (currentFrame) => {
  currentFrame.pass(scene, sceneEffect); // render the scene offscreen
  currentFrame.pass(canvasSurface, post); // invert it onto the canvas
});
```

Reach for `textureLoad` only when you need exact texels or an unfilterable
format — for ordinary sampling, a filtering sampler is simpler and faster.

`post.set(...)` exposes the offscreen result and filtering sampler to WGSL as bindings named `src` and `samp`. Both passes encode into one [`frame(gpu)`](/docs/reference/vgpu/frame#framerunner) and submit once, in pass order, so the canvas pass reads the finished scene. Surface passes always go through a frame; a one-shot `post.draw(canvasSurface)` outside one throws `VGPU-SURFACE-NOT-IN-FRAME`.

## Updating bindings

You can update bindings at any time by using `.set`.

`set()` validates and packs the new values on the CPU every time you call it —
there is no change detection. The upload happens when an operation uses the
values: each frame pass captures them when it encodes the effect. Match your
calls to how often values actually change: constants once at creation, size-
and resolution-class uniforms at init and on resize, and per-frame calls only
for genuinely dynamic values like time or pointer input. Rebinding the same
resources is free — bind groups are cached by resource identity — so this rule
is purely about avoiding redundant work.

```wgsl
// pulse.wgsl
struct Params { time: f32, width: f32, height: f32 }
@group(0) @binding(0) var<uniform> params: Params;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let glow = sin(params.time) * 0.5 + 0.5;
  return vec4f(uv.x, uv.y, glow, 1.0);
}
```

```ts
import { clock, init, effect, frameLoop, surface } from "vgpu";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);

// ---cut---
import pulseShader from "./pulse.wgsl";

const pulse = effect(gpu, pulseShader, {
  // initial uniform defaults
  set: {
    params: {
      time: 0,
      width: canvasSurface.size[0],
      height: canvasSurface.size[1]
    }
  },
});

const time = clock(gpu);
frameLoop(gpu, (currentFrame) => {
  // update uniforms before drawing
  pulse.set({
    params: {
      time: time.time,
    },
  });
  currentFrame.pass(canvasSurface, pulse); // this pass captures the new time
});
```

You should also only update uniforms when they need to change, for example, react to canvas size changes:

```ts
import { clock, init, effect, surface } from "vgpu";
import pulseShader from "./pulse.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);
const pulse = effect(gpu, pulseShader, { set: { params: { time: 0, width: canvasSurface.size[0], height: canvasSurface.size[1] } } });

// ---cut---
const unsubscribe = canvasSurface.onResize(({ width, height }) => {
  pulse.set({ params: { width, height } }); // partial update: time keeps its value
});
```

`onResize()` fires the callback once immediately with the current size, then again on every resize. It returns an `unsubscribe` function — call it when you tear the effect down.

## Different values in one frame

Each pass captures the effect's uniform values when it encodes the effect, so
a later `set()` in the same frame changes only the passes encoded after it.
One effect can run a horizontal and a vertical blur back to back:

```ts
import { init, effect, frame, sampler, surface, target } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);
const sceneTarget = target(gpu, { size: [512, 512] });
const horizontalTarget = target(gpu, { size: [512, 512] });
const linear = sampler(gpu, { minFilter: "linear", magFilter: "linear" });

// ---cut---
const blur = effect(gpu, prepareShader(`
  struct Params { direction: vec2f }
  @group(0) @binding(0) var<uniform> params: Params;
  @group(0) @binding(1) var src: texture_2d<f32>;
  @group(0) @binding(2) var samp: sampler;

  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    let texel = params.direction / vec2f(textureDimensions(src));
    let sum = textureSampleLevel(src, samp, uv - texel, 0.0)
      + textureSampleLevel(src, samp, uv, 0.0)
      + textureSampleLevel(src, samp, uv + texel, 0.0);
    return vec4f(sum.rgb / 3.0, 1.0);
  }
`), { set: { samp: linear } });

frame(gpu, (currentFrame) => {
  blur.set({ params: { direction: [1, 0] }, src: sceneTarget });
  currentFrame.pass(horizontalTarget, blur); // captures the horizontal direction
  blur.set({ params: { direction: [0, 1] }, src: horizontalTarget });
  currentFrame.pass(canvasSurface, blur); // captures the vertical direction
});
```

The first pass keeps `direction: [1, 0]` even though the second `set()` runs
before the frame submits. Storage buffers and render bundles are the
exception: they read live buffer contents, so a `set()` on an effect recorded
in a bundle reaches every later replay.

## Tear an effect down

You do not have to release an effect. One you stop referencing is collected
eventually, like any JavaScript object, and bundles that recorded it keep
replaying. Call [`effect.dispose()`](/docs/reference/vgpu/effect#effect) when you
want to retire it at a known point — unmounting a component, or swapping a
post-processing chain. Stop everything that still calls the effect first,
then dispose it:

```ts
import { clock, init, effect, frameLoop, surface } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);
const pulse = effect(gpu, prepareShader(`
  struct Params { time: f32, width: f32, height: f32 }
  @group(0) @binding(0) var<uniform> params: Params;

  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return vec4f(uv, sin(params.time) * 0.5 + 0.5, 1.0);
  }
`), { label: "pulse", set: { params: { time: 0, width: canvasSurface.size[0], height: canvasSurface.size[1] } } });

// ---cut---
const unsubscribe = canvasSurface.onResize(({ width, height }) => {
  pulse.set({ params: { width, height } });
});
const time = clock(gpu);
const loop = frameLoop(gpu, (currentFrame) => {
  pulse.set({ params: { time: time.time } });
  currentFrame.pass(canvasSurface, pulse);
});

function unmount(): void {
  loop.stop(); // no more frames draw the effect
  unsubscribe(); // no more resize callbacks call set()
  pulse.dispose(); // then retire the effect
}
```

`dispose()` is synchronous and idempotent, and it never destroys what the
effect borrowed: the surface, sampled targets and textures, buffers, and
samplers stay yours, and the compiled pipeline stays cached for other effects
built from the same shader. Work already encoded keeps the values it captured.

<Callout type="warn">
  Warning: After `dispose()`, every other call on the effect — `set()`, `draw()`, `compile()`, `gpu`, or drawing it in a pass — throws `VGPU-DRAW-DISPOSED`, the same code a disposed [`Draw`](/docs/reference/vgpu/draw#draw) uses. Unsubscribe the resize callback before disposing, or its next call throws. A bundle that recorded the effect throws `VGPU-R3-BUNDLE-STALE` on replay; record its replacement with a new effect.
</Callout>


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Frames
description: frame(gpu, cb) encodes your passes and submits once; frameLoop(gpu, cb) drives animation.
---

# Frames



A frame is one unit of GPU work. Inside it you open render passes with explicit targets and compute passes that dispatch prepared kernels. Everything is encoded into one command encoder, and vgpu submits it once when the callback returns — which is why the callback is synchronous.

## Render a single frame

[`frame(gpu)`](/docs/reference/vgpu/frame#framerunner) runs synchronously and renders immediately — every pass inside is encoded into one command encoder and submitted once. That single submit is what the frame is for:

```wgsl
// pulse.wgsl
struct Params { time: f32 }
@group(0) @binding(0) var<uniform> params: Params;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, sin(params.time) * 0.5 + 0.5, 1.0);
}
```

```wgsl
// post.wgsl
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let base = textureSampleLevel(src, samp, uv, 0.0);
  return vec4f(1.0 - base.rgb, 1.0);
}
```

```ts
import { init, effect, frame, sampler, surface, target } from "vgpu";
import pulseShader from "./pulse.wgsl";
import postShader from "./post.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
const pulseEffect = effect(gpu, pulseShader, { set: { params: { time: 0 } } });
const postEffect = effect(gpu, postShader);

// ---cut---
const sceneTarget = target(gpu, { size: [canvasTarget.size[0], canvasTarget.size[1]] });
postEffect.set({
  src: sceneTarget,
  samp: sampler(gpu, { minFilter: 'linear', magFilter: 'linear' }),
});

frame(gpu, (currentFrame) => {
  currentFrame.pass(sceneTarget, pulseEffect);
  currentFrame.pass(canvasTarget, postEffect);
}); // two passes, one encoder, one submit
```

One-shot draws like `pulseEffect.draw(canvasTarget)` are the simple default for a single pass. Multi-pass hot paths should use `frame(gpu)` to batch passes into one command encoder and one submit. One-shot draws never join a surrounding frame; inside `frame(gpu)`, always go through `frame.pass()`.

<Callout type="warn">
  Warning: one-shot `draw()` calls do not join a surrounding frame — inside a frame callback they submit on their own immediately. Inside `frame(gpu)`, always draw through `frame.pass()`.
</Callout>

<Callout type="warn">
  Warning: Do not call `frame(gpu)` from inside another frame callback or from a surface resize callback. vgpu throws `VGPU-FRAME-REENTRANT` so command encoders stay ordered and predictable.
</Callout>

## When the callback throws

The callback is all-or-nothing for the frame's command buffer. If it returns, the frame submits once. If it throws, vgpu cancels the frame: nothing it encoded reaches the GPU, the timer and visibility instances it attached release their per-frame retains, and the error reaches you unchanged. A half-encoded frame is never presented by accident.

The guarantee is scoped to the command buffer. The frame clock has already ticked, uniform updates and buffer writes made inside the callback stay applied, and anything submitted on its own from inside the callback (a one-shot `draw()`, a manual frame) has already reached the queue. A canvas the frame already opened a pass on still shows that browser frame, only empty, because the texture was acquired but never drawn into. Errors the GPU reports after a successful submit still arrive through `gpu.onError` and `await gpu.settled()`.

If you called `frame.submit()` yourself before the throw, that work is on the queue and stays there; vgpu just rethrows your error. That is also the way to keep partial work on purpose:

```ts
import { init, frame, target } from "vgpu";
import type { Frame } from "vgpu";

const gpu = await init();
const scene = target(gpu, { size: [64, 64] });
function encode(currentFrame: Frame): void { currentFrame.pass(scene, () => undefined); }

// ---cut---
frame(gpu, (currentFrame) => {
  try {
    encode(currentFrame);
  } catch (error) {
    currentFrame.submit(); // keep what was encoded before the failure
    throw error;
  }
});
```

## Render loops

For animation, use [`frameLoop(gpu)`](/docs/reference/vgpu/frame#framerunner) — it runs your frame every tick:

```ts
import { clock, init, effect, frameLoop, surface } from "vgpu";
import pulseShader from "./pulse.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
const pulseEffect = effect(gpu, pulseShader, { set: { params: { time: 0 } } });

// ---cut---
const time = clock(gpu);
const handle = frameLoop(gpu, (frame) => {
  pulseEffect.set({ params: { time: time.time } }); // update uniforms every tick
  frame.pass(canvasTarget, pulseEffect);
}, { fps: 30 });

handle.stop(); // call it when your component unmounts
```

The loop advances the frame clock — `clock(gpu).time`, `deltaTime` and `frameCount` — and runs surface auto-resize before each tick. The optional `fps` throttles it.

Each tick follows the same rule as `frame(gpu, cb)`: a tick that throws submits nothing for that frame. It also ends the loop, because the error escapes the animation-frame callback where nothing can catch it; the handle is released as if you had called `stop()`. Recover, then start a new `frameLoop(gpu, cb)`.

This is what the same loop looks like by hand with `requestAnimationFrame`:

```ts
import { init, effect, surface } from "vgpu";
import pulseShader from "./pulse.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
const pulseEffect = effect(gpu, pulseShader, { set: { params: { time: 0 } } });

// ---cut---
function tick() {
  pulseEffect.set({ params: { time: performance.now() / 1000 } }); // you own the clock now
  pulseEffect.draw(canvasTarget);
  requestAnimationFrame(tick); // and the scheduling
}
requestAnimationFrame(tick);
```

Both work. `frameLoop(gpu)` is the same loop with the clock, throttling, and resize handling done for you.

See it live: the [fluid example](/examples/fluid) runs a compute-driven simulation with exactly this frame loop shape.

## Compute and render in one submission

Use `f.computePass(pass => pass.dispatch(simulation, workgroups))` between render passes when work depends on their output. Each compute callback can dispatch several kernels, including indirect dispatches. The frame preserves pass order and submits the combined command buffer once. Standalone `simulation.dispatch()` remains an independent submission even if called inside the frame callback.

Prepare pipelines with `await simulation.compile()` before opening a frame. Compute-pass callbacks are synchronous and cannot nest other passes. Cancellation discards both render and compute commands belonging to the frame.

Direct draws and dispatches capture their current managed uniform values, and a `set()` that leaves the packed bytes unchanged keeps the snapshot already captured for later commands in the frame. Captures live in pooled uniform pages that return for reuse once the frame's GPU work completes or the frame is canceled, so frames that repeat the same draws in the same order reuse their bind groups. Storage buffers stay live for GPU-to-GPU dataflow. Explicit host writes, raw resources and render bundles keep their existing buffer semantics; later host writes are not inserted between encoded commands.

## Await before the frame, not inside it

`frame(gpu, cb)` submits the moment the callback returns. An `async` callback returns its promise at the first `await`, so the frame would submit before the rest of the callback encoded anything. Do the asynchronous work — compiling pipelines, loading textures, fetching data — before you call `frame(gpu)` or register `frameLoop(gpu)`, keep the encoding synchronous, and tear down outside the callback. The loop from the previous sections, with its preparation and teardown spelled out:

```wgsl
// simulation.wgsl
@group(0) @binding(0) var<storage, read_write> particles: array<vec4f>;
@compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3u) {
  particles[id.x] += vec4f(0.0, -0.01, 0.0, 0.0);
}
```

```wgsl
// shade.wgsl
@fragment fn fs_main() -> @location(0) vec4f {
  return vec4f(0.1, 0.2, 0.4, 1.0);
}
```

```ts
import { init, compute, effect, frameLoop, storage, surface } from "vgpu";
import shadeShader from "./shade.wgsl";
import simulationShader from "./simulation.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
const particles = storage(gpu, 64 * 16);
const simulation = compute(gpu, simulationShader, { set: { particles } });
const shade = effect(gpu, shadeShader);

// ---cut---
await simulation.compile(); // async preparation, before the loop exists

const handle = frameLoop(gpu, (currentFrame) => {
  currentFrame.computePass((pass) => pass.dispatch(simulation, 1)); // encoding stays synchronous
  currentFrame.pass(canvasTarget, shade);
});

export async function teardown(): Promise<void> {
  handle.stop(); // async teardown runs outside any frame callback
  await gpu.settled();
  gpu.dispose();
}
```

Synchronous block bodies, `void` expressions such as `(currentFrame) => currentFrame.pass(canvasTarget, shade)`, and helpers with a concrete non-Promise return type work — vgpu ignores the returned value. Existing synchronous helpers with those types need no rewrite.

TypeScript rejects a single callback whose inferred return type is a `Promise`, a `PromiseLike`, or a return union containing one:

```ts illustrative
frame(gpu, async (currentFrame) => { // type error: the callback returns Promise<void>
  await simulation.compile();
  currentFrame.computePass((pass) => pass.dispatch(simulation, 1));
});
```

The type check cannot see a return type that was already erased — a callback stored as `FrameLoopCallback`, `(frame: Frame) => unknown`, or `(frame: Frame) => any`, a cast, a return-type-erasing wrapper, or plain JavaScript. A union of callback function types with a void member may also erase its Promise-returning member during inference and compile. In all of these cases, vgpu checks the result at runtime: an object or function with a callable `then` throws `VGPU-ASYNC-FRAME-CALLBACK` before the implicit submit, and the frame is canceled exactly as if the callback had thrown. vgpu observes the promise's rejection without reporting it to `gpu.onError` and never waits for it, so the error is synchronous even for a promise that never settles. In a loop, the offending tick throws with `where: "frameLoop"` and stops the loop like any throwing tick; registering the loop never runs the callback, so `frameLoop(gpu, cb)` itself does not throw.

A forwarding helper whose callback still returns an unresolved generic `R`, including `R extends void`, no longer typechecks: the frame API cannot prove that return synchronous. If the helper intentionally ignores callback returns, accept `FrameLoopCallback` or `(frame: Frame) => void` and pass the callback directly to `frame` or `frameLoop`. The runtime thenable check still sees its actual result; do not wrap the call in a block that discards that result.

Cancellation still covers only the frame's own command buffer. A `frame.submit()` the callback already called stays on the queue, one-shot draws and dispatches have already submitted on their own, and CPU-side changes stay applied. The async continuation also keeps running; anything it tries to encode on the canceled frame throws `VGPU-FRAME-CANCELED`.

<Callout type="warn">
  Warning: Do not hide async frame work behind `void`, a cast, or a wrapper that erases the return type. The runtime check stops the frame from submitting half-encoded, but it cannot make the continuation's work reach the GPU. Await first, then call `frame(gpu)`.
</Callout>

Compute-pass callbacks keep their own check: a `computePass(...)` callback that returns a thenable throws `VGPU-COMPUTE-PASS-ASYNC`.

## When the device is lost

A GPU device can be lost — a driver reset, the GPU process crashing, or the owner of a borrowed device destroying it. When vgpu observes the loss, it stops every running `frameLoop(gpu)` first, then resolves [`gpu.lost`](/docs/reference/vgpu/gpu#gpu). No tick runs after that and none throws, so the loss does not surface as an uncaught error from an animation-frame callback. The gpu is not disposed and nothing recovers on its own: restart on a new gpu from `init()`.

The loop from the previous section, restarted after loss:

```ts
import { init, compute, effect, frameLoop, storage, surface } from "vgpu";
import shadeShader from "./shade.wgsl";
import simulationShader from "./simulation.wgsl";

const canvas = document.querySelector("canvas")!;

// ---cut---
async function start(): Promise<void> {
  const gpu = await init(); // a new device every time
  const canvasTarget = surface(gpu, canvas);
  const particles = storage(gpu, 64 * 16);
  const simulation = compute(gpu, simulationShader, { set: { particles } });
  const shade = effect(gpu, shadeShader);
  await simulation.compile();

  frameLoop(gpu, (currentFrame) => {
    currentFrame.computePass((pass) => pass.dispatch(simulation, 1));
    currentFrame.pass(canvasTarget, shade);
  });

  void gpu.lost
    .then(() => {
      gpu.dispose(); // the loop already stopped; release the old surface and resources
      return start(); // recreate everything on a new gpu and restart the loop
    })
    .catch((error: unknown) => console.error("GPU restart failed", error));
}

await start();
```

Every resource belongs to the gpu that created it, so the restart recreates the surface, storage, and pipelines instead of reusing them. `gpu.lost` never rejects; the `.catch()` is for the restart itself, which can fail when `init()` rejects. Dispose the lost gpu before the new one creates its surface, so the old surface releases the canvas first.

On the lost gpu, `frame(gpu)` and `frameLoop(gpu)` throw `VGPU-DEVICE-LOST` before the frame clock advances or surface auto-resize runs. vgpu does not cancel a manual `frame(gpu)` that was open at the time: its `submit()` throws `VGPU-DEVICE-LOST` rather than silently dropping the work, until `gpu.dispose()` cancels it.

<Callout type="warn">
  Warning: Do not `await gpu.lost` to tear down. It stays pending while the device is healthy and after `gpu.dispose()`, so the teardown would never run. Unmount the same way as before: `handle.stop()`, `await gpu.settled()` when you need submitted work and deliveries to finish, then `gpu.dispose()`.
</Callout>

`gpu.dispose()` is your teardown, not a loss: disposing before vgpu observed any loss leaves `gpu.lost` pending, and disposing a gpu from `initFromDevice(device)` never destroys the borrowed device. The [`Gpu` reference](/docs/reference/vgpu/gpu#gpu) lists every loss-versus-disposal ordering.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Concepts
description: The core ideas behind every vgpu program, in reading order.
---

# Concepts



These ideas cover every vgpu program. Read them in order — each page builds on the previous one.

<Cards>
  <Card title="Context" description="init() creates the Gpu context; every surface, target, effect, and frame is created from it." href="/docs/concepts/context" />

  <Card title="WGSL modules" description="Split shaders into reusable files with import and export; vgpu resolves the graph into ordinary WGSL." href="/docs/concepts/wgsl-modules" />

  <Card title="Draws" description="draw(gpu, opts) renders geometry with custom vertex buffers — you write the vertex stage, geometry(gpu, ...) supplies the buffers." href="/docs/concepts/draws" />

  <Card title="Compilation" description="Pipelines compile lazily on first use; pre-warm them during load so the first frame doesn't hitch." href="/docs/concepts/compilation" />

  <Card title="Effects" description="An effect is a full-screen fragment shader; chain effects by binding a target as another effect's input." href="/docs/concepts/effects" />

  <Card title="Passes" description="A pass composites any number of draws into one target; a single shader can draw directly." href="/docs/concepts/passes" />

  <Card title="Frames" description="frame(gpu, cb) encodes your passes and submits once; frameLoop(gpu, cb) drives animation." href="/docs/concepts/frames" />

  <Card title="Render bundles" description="bundle(gpu, opts, record) records draws once; replaying them each frame skips re-encoding." href="/docs/concepts/render-bundles" />
</Cards>


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Passes
description: A pass composites any number of draws into one target; a single shader can draw directly.
---

# Passes



A pass is a render-pass section inside a frame. It has one target, one clear color, and any number of draw calls. Open a pass by hand when you want to composite multiple draws into the same render target — here, an ocean and a boat rendered straight to the canvas:

```ts
import { init, effect, frame, surface } from "vgpu";
import oceanShader from "./ocean.wgsl"; // fullscreen water gradient
import boatShader from "./boat.wgsl"; // draws only the hull pixels; discards everything else

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);

// ---cut---
const ocean = effect(gpu, oceanShader);
const boat = effect(gpu, boatShader);

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: canvasSurface, clear: [0, 0, 0, 1] }, (pass) => {
    pass.draw(ocean); // fill the canvas with water
    pass.draw(boat); // paint the boat on top — same target
  });
});
```

Both draws share one render pass and one target. Order inside the pass is paint order: the ocean fills the canvas first, then the boat draws on top of it.

<Callout type="info">
  Good to know: [`FramePass.draw()`](/docs/reference/vgpu/frame#framepass) accepts a fullscreen [`Effect`](/docs/reference/vgpu/effect#effect) or an explicit [`Draw`](/docs/reference/vgpu/draw#draw). Use `draw(gpu)` when you need meshes, vertex counts, instancing, or raw bind groups.
</Callout>

## One shader? Draw it directly

Now add postprocessing. The pass is the same — the only change is its target: an offscreen [`Target`](/docs/reference/vgpu/target#target) with the same size as the canvas. Then the postprocessing effect (bound with `set({ src: scene })`) needs no pass ceremony to reach the screen:

```ts
import { init, effect, frame, sampler, surface, target } from "vgpu";
import oceanShader from "./ocean.wgsl";
import boatShader from "./boat.wgsl";
import postShader from "./post.wgsl"; // samples `src` with `samp` and applies a vignette

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);

const ocean = effect(gpu, oceanShader);
const boat = effect(gpu, boatShader);

// ---cut---
const scene = target(gpu, { size: [canvasSurface.size[0], canvasSurface.size[1]] });
const postprocessing = effect(gpu, postShader);
postprocessing.set({
  src: scene,
  samp: sampler(gpu, { minFilter: 'linear', magFilter: 'linear' }),
}); // the offscreen scene becomes the post input

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: scene, clear: [0, 0, 0, 1] }, (pass) => {
    pass.draw(ocean);
    pass.draw(boat);
  });
});

postprocessing.draw(canvasSurface); // rendering an effect creates a pass
```

The one-shot `draw()` runs after the frame has submitted, so the scene is already rendered when postprocessing reads it. Under the hood it creates an encoder, opens a render pass on `canvasSurface`, encodes the draw, and submits — the same GPU work you would write by hand with `frame.pass`.

<Callout type="info">
  Good to know: `frame.pass()` always needs a target. Use a canvas-backed [`Surface`](/docs/reference/vgpu/surface#surface) from `surface(gpu, canvas)` or an offscreen [`Target`](/docs/reference/vgpu/target#target) from `target(gpu, { size })`.
</Callout>

<Callout type="info">
  Good to know: a pass takes more than a target and a clear color. [`FramePassOptions`](/docs/reference/vgpu/frame#framepassoptions) also sets `clearDepth` (`0` for reversed-Z), `clearStencil`, a `viewport` or `scissor` rectangle for split-screen and partial redraws, `depthReadOnly` to depth-test while sampling the depth texture, a `timer` span for GPU timing, and `visibility` for occlusion queries.
</Callout>


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Render bundles
description: bundle(gpu, opts, record) records draws once; replaying them each frame skips re-encoding.
---

# Render bundles



A render loop re-encodes every pipeline, bind group, and draw on every tick — even when nothing changed. A bundle records those commands once; replaying it each frame costs almost nothing.

## Record once, replay every frame

[`bundle(gpu)`](/docs/reference/vgpu/bundle#bundle) records draws against a target and returns a [`Bundle`](/docs/reference/vgpu/bundle#bundle). Replay it inside a pass with `pass.bundles()`:

```wgsl
// animated-ocean.wgsl
struct Params { time: f32 }
@group(0) @binding(0) var<uniform> params: Params;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(0.1, 0.3, sin(params.time + uv.y) * 0.2 + 0.6, 1.0);
}
```

```wgsl
// silhouette-boat.wgsl
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(0.6, 0.4, 0.2, step(distance(uv, vec2f(0.5, 0.6)), 0.1));
}
```

```ts
import { init, bundle, clock, effect, frameLoop, surface } from "vgpu";
import oceanShader from "./animated-ocean.wgsl";
import boatShader from "./silhouette-boat.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
const ocean = effect(gpu, oceanShader, { set: { params: { time: 0 } } });
const boat = effect(gpu, boatShader);

// ---cut---
const scene = bundle(gpu, { target: canvasTarget }, (b) => {
  b.draw(ocean);
  b.draw(boat);
}); // encoded once, right here — no frame needed

const time = clock(gpu);
frameLoop(gpu, (frame) => {
  ocean.set({ params: { time: time.time } }); // uniforms still animate
  frame.pass(canvasTarget, (pass) => pass.bundles(scene)); // replay — no re-encoding
});
```

Record what doesn't change, `set()` what does: the bundle references your buffers, so uniform updates flow through on every replay.

Recording against a live surface works outside a frame, during loading. vgpu reads the surface's configured render signature — its `format`, including an explicit override, resolved depth format, and sample count — and does not acquire a canvas texture, resize the canvas, or submit work. Replay is the part that draws, so it stays inside `frame()` or `frameLoop()`. Recording against a disposed surface throws `VGPU-SURFACE-DISPOSED`.

<Callout type="info">
  Good to know: draws inside a bundle can use different shaders and pipelines. What a bundle freezes is the target's render signature — color formats, depth format, sample count — plus bind groups, not a material or a target size.
</Callout>

## Compilation at record time

`bundle(gpu)` encodes right when you call it, so it needs every pipeline immediately: any draw whose pipeline isn't cached yet for the recording signature compiles synchronously, on the spot. That's the one place vgpu still blocks on pipeline creation — and the reason to [pre-warm](/docs/concepts/compilation) before recording. If one of those synchronous creates fails, the error reports through `gpu.onError`, like any lazy compile.

The `target` option also takes a plain signature, so you can pre-warm and record during load, before the real target exists:

```wgsl
// ocean.wgsl
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(0.1, 0.3, 0.6, 1.0);
}
```

```wgsl
// boat.wgsl
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(0.6, 0.4, 0.2, 1.0);
}
```

```ts
import { init, bundle, effect, frameLoop, surface } from "vgpu";
import oceanShader from "./ocean.wgsl";
import boatShader from "./boat.wgsl";

const gpu = await init();
const ocean = effect(gpu, oceanShader);
const boat = effect(gpu, boatShader);

// ---cut---
const signature = { colors: [navigator.gpu.getPreferredCanvasFormat()] };
await Promise.all([
  ocean.compile(signature),
  boat.compile(signature),
]);

const scene = bundle(gpu, { target: signature }, (b) => {
  b.draw(ocean);
  b.draw(boat);
}); // everything was pre-warmed — recording creates nothing

// Later, surface() selects the same preferred format by default.
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
frameLoop(gpu, (frame) => {
  frame.pass(canvasTarget, (pass) => pass.bundles(scene));
});
```

Bindings must be `set()` before recording — the signature relaxes the target requirement, not the resources. Replay targets must match the recorded color formats, depth format, and sample count exactly; a mismatch throws an error showing both signatures. The preferred-format signature above describes a default surface with no depth and one sample. Include the planned depth format and sample count for depth/MSAA surfaces, and use the configured formats for custom or offscreen targets. Once the surface or target exists, pass it directly instead of a signature: `await ocean.compile(canvasTarget)` followed by `bundle(gpu, { target: canvasTarget }, ...)` pre-warms and records outside any frame, and shares the same cached pipelines as the equivalent signature.

## Mix recorded and dynamic draws

A pass can replay bundles and encode fresh draws side by side:

```wgsl
// cursor.wgsl
struct Params { pos: vec2f }
@group(0) @binding(0) var<uniform> params: Params;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(1.0, 1.0, 1.0, step(distance(uv, params.pos), 0.02));
}
```

```ts
import { init, bundle, clock, effect, frameLoop, surface } from "vgpu";
import oceanShader from "./ocean.wgsl";
import cursorShader from "./cursor.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
const ocean = effect(gpu, oceanShader);
const cursor = effect(gpu, cursorShader, { set: { params: { pos: [0.5, 0.5] } } });
const scene = bundle(gpu, { target: canvasTarget }, (b) => b.draw(ocean));

// ---cut---
frameLoop(gpu, (frame) => {
  frame.pass(canvasTarget, (pass) => {
    pass.bundles(scene); // the static part, replayed
    pass.draw(cursor); // the dynamic part, encoded fresh on top
  });
});
```

Some draws must stay on the dynamic side. Draws that set a `blendConstant` or a `stencil` `ref` cannot be recorded — bundle encoders have no way to set those pass-level values — so encode them with `pass.draw()`. A bundle also cannot replay inside a `depthReadOnly` pass, because bundles always record with writable depth. Indirect draws record fine: the GPU re-reads the argument buffer on every replay.

## Resizes and sampled targets

A bundle matches replay targets by render signature, not size, so drawing onto a resized surface keeps working without recording again:

```ts
import { init, bundle, effect, frameLoop, surface } from "vgpu";
import oceanShader from "./ocean.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
const ocean = effect(gpu, oceanShader);

// ---cut---
const scene = bundle(gpu, { target: canvasTarget }, (b) => b.draw(ocean));

frameLoop(gpu, (frame) => {
  frame.pass(canvasTarget, (pass) => pass.bundles(scene)); // still valid after every resize
});
```

Sampling is different. A bundle freezes its bind groups, so when a texture it samples is replaced — here, an offscreen target resized to follow the canvas — the bundle goes stale and replay throws `VGPU-R3-BUNDLE-STALE`. Record a replacement, swap it in, then dispose the old bundle:

```wgsl
// post.wgsl
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(1.0 - textureSampleLevel(src, samp, uv, 0.0).rgb, 1.0);
}
```

```ts
import { init, bundle, effect, frameLoop, sampler, surface, target, type Bundle } from "vgpu";
import postShader from "./post.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
const sceneTarget = target(gpu, { size: [canvasTarget.size[0], canvasTarget.size[1]] });
const postEffect = effect(gpu, postShader);
postEffect.set({ src: sceneTarget, samp: sampler(gpu, { minFilter: "linear", magFilter: "linear" }) });

// ---cut---
let post: Bundle | undefined;

canvasTarget.onResize(({ width, height }) => {
  sceneTarget.resize([width, height]); // new textures: the bundle sampling the old ones is stale
  const next = bundle(gpu, { target: canvasTarget }, (b) => b.draw(postEffect));
  const previous = post;
  post = next; // swap only after recording succeeded
  previous?.dispose(); // then release the replaced bundle
}); // fires once immediately, so this also records the first bundle

frameLoop(gpu, (frame) => {
  frame.pass(canvasTarget, (pass) => pass.bundles(post!));
});
```

The order matters. If recording throws, `post` still holds the previous bundle and nothing was disposed early. Re-record only for changes like this one, never solely because the destination resized.

## Rebinding during and after recording

A bundle captures the resources bound at each `b.draw()` call. Rebinding a draw between calls inside one recording is deliberate — the bundle records both draws, each with its own resources, and checks all of them at replay. Rebinding after a bundle finished recording stales that bundle, even when the `set()` happens inside another bundle's recording:

```ts
import { init, bundle, effect, frameLoop, surface, target } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);
const leftTarget = target(gpu, { size: [256, 256] });
const rightTarget = target(gpu, { size: [256, 256] });
const preview = effect(gpu, prepareShader(`
  @group(0) @binding(0) var src: texture_2d<f32>;

  @fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {
    return textureLoad(src, vec2i(position.xy) % vec2i(256), 0);
  }
`), { set: { src: leftTarget } });

// ---cut---
const leftOnly = bundle(gpu, { target: canvasTarget }, (b) => b.draw(preview));

const both = bundle(gpu, { target: canvasTarget }, (b) => {
  b.draw(preview); // records leftTarget
  preview.set({ src: rightTarget }); // stales leftOnly; this recording keeps going
  b.draw(preview); // records rightTarget
}); // both watches leftTarget and rightTarget

frameLoop(gpu, (frame) => {
  frame.pass(canvasTarget, (pass) => pass.bundles(both)); // pass.bundles(leftOnly) would throw VGPU-R3-BUNDLE-STALE
});
```

`both` stays valid until `preview` is rebound again, or either captured target is destroyed or replaces its attachment. `leftOnly` went stale at the `set()`, because it recorded `leftTarget` and the draw no longer binds it.

## Let recorded draws go

A bundle does not hold the draws and effects it recorded. It keeps independent snapshots instead — each captured texture, buffer, and target, the attachment of each sampled `Target`, and the geometry it draws — so a draw or effect created only to record a bundle can stay local to the function that records it:

```ts
import { init, bundle, effect, frameLoop, surface, type Bundle, type Gpu, type Surface } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);

// ---cut---
function recordBackdrop(gpu: Gpu, canvasTarget: Surface): Bundle {
  const backdrop = effect(gpu, prepareShader(`
    @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
      return vec4f(0.1, 0.3, 0.6 + uv.y * 0.2, 1.0);
    }
  `));
  return bundle(gpu, { target: canvasTarget, label: "backdrop" }, (b) => b.draw(backdrop));
} // backdrop is unreachable after this returns — the bundle does not need it

const backdropBundle = recordBackdrop(gpu, canvasTarget);
frameLoop(gpu, (frame) => {
  frame.pass(canvasTarget, (pass) => pass.bundles(backdropBundle));
});
```

Collecting the effect does not make the bundle stale. The snapshots still catch later changes on their own: destroying a captured texture, buffer, or target, or replacing a sampled `Target`'s attachment, makes replay throw `VGPU-R3-BUNDLE-STALE`, and destroying recorded geometry makes replay throw that geometry's liveness error. Keep the draw only when you still `set()` its uniforms, rebind it, or draw it outside the bundle — while you hold it, its uniform updates keep reaching every bundle that recorded it.

## Disposing a recorded draw stales its bundles

Letting a draw go and disposing it are different. Collection is silent: the bundle keeps replaying. [`draw.dispose()`](/docs/reference/vgpu/draw#draw) and [`effect.dispose()`](/docs/reference/vgpu/effect#effect) are explicit retirements: every bundle that recorded the draw goes permanently stale — even one whose recording callback is still running — and `pass.bundles()` throws `VGPU-R3-BUNDLE-STALE` naming the disposed draw. Replace the draw and its bundle together:

```ts
import { init, bundle, effect, frameLoop, surface } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasTarget = surface(gpu, canvas);

// ---cut---
let backdrop = effect(gpu, prepareShader(`
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.1, 0.3, 0.6, 1.0); }
`), { label: "dayBackdrop" });
let backdropBundle = bundle(gpu, { target: canvasTarget, label: "day" }, (b) => b.draw(backdrop));

function useNightBackdrop(): void {
  const nextBackdrop = effect(gpu, prepareShader(`
    @fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.02, 0.03, 0.1, 1.0); }
  `), { label: "nightBackdrop" });
  const nextBundle = bundle(gpu, { target: canvasTarget, label: "night" }, (b) => b.draw(nextBackdrop));
  const previousBackdrop = backdrop;
  const previousBundle = backdropBundle;
  backdrop = nextBackdrop;
  backdropBundle = nextBundle; // swap only after recording succeeded
  previousBackdrop.dispose(); // stales the day bundle permanently
  previousBundle.dispose(); // then release that bundle too
}

frameLoop(gpu, (frame) => {
  frame.pass(canvasTarget, (pass) => pass.bundles(backdropBundle));
});
```

Between the two `dispose()` calls, replaying the day bundle would throw `VGPU-R3-BUNDLE-STALE` with `Bundle 'day' is stale: draw 'dayBackdrop' was disposed. Create a new draw/effect and re-record the bundle.` Disposal does not reach native work: commands already encoded still submit, and a `GPURenderBundle` you read from `bundle.gpu` keeps replaying the last uniform contents the draw wrote.

## Release bundles you no longer need

You do not have to release a bundle. The draws and resources a bundle recorded do not keep it alive, so once your code drops its last reference, the bundle is collected eventually like any other object. vgpu makes no promise about when that happens or when the driver frees the native bundle's memory.

Call `dispose()` when you want vgpu's references and registrations released at a known point — replacing a bundle, or tearing down a view. Neither garbage collection nor `dispose()` promises when native WebGPU or the driver reclaims memory:

```ts
import { init, bundle, effect, frame, target } from "vgpu";
import oceanShader from "./ocean.wgsl";

const gpu = await init();
const sceneTarget = target(gpu, { size: [256, 256] });
const ocean = effect(gpu, oceanShader);

// ---cut---
const scene = bundle(gpu, { target: sceneTarget, label: "ocean" }, (b) => b.draw(ocean));

frame(gpu, (currentFrame) => {
  currentFrame.pass(sceneTarget, (pass) => pass.bundles(scene));
  scene.dispose(); // the replay is already encoded — this frame still submits it
});

scene.dispose(); // idempotent: a second call does nothing
console.log(scene.id); // "ocean" — the id stays readable
ocean.draw(sceneTarget); // the effect was borrowed, not destroyed
```

`dispose()` is synchronous. It unregisters the bundle from the draws and resources it watched and drops its snapshots and native handle reference. It never destroys or disposes what the bundle borrowed — draws, effects, geometry, textures, buffers, and targets stay yours.

<Callout type="warn">
  Warning: After `dispose()`, reading `scene.gpu` or replaying the bundle throws `VGPU-BUNDLE-DISPOSED`. Record a new bundle before replaying. In `pass.bundles(a, b)`, one disposed entry means none of the list replays.
</Callout>

Disposal cannot reach what already left the bundle, and neither can collecting the draws it recorded. Work encoded before `dispose()` still runs, and a `GPURenderBundle` you read from `scene.gpu` earlier stays usable for as long as native WebGPU keeps it valid — vgpu cannot revoke it, and only `pass.bundles()` checks staleness, not native replay of that handle. While you hold the recorded draw and have not disposed it, its `set()` uniform updates keep reaching that handle.

A bundle that goes permanently stale — a captured resource was rebound or destroyed, a sampled `Target` replaced its attachment, or a recorded draw was disposed — detaches from its draws and resources on its own, and replay keeps reporting the first cause. A replay on a target with a different signature is not permanent: it throws `VGPU-R3-BUNDLE-STALE` for that call only, and replaying on a matching target afterwards works.

## When not to bother

Recording is not free, and a couple of draws per frame cost almost nothing to encode. Bundles pay off with many draws in a hot loop. The full ladder: `effect.draw(target)` for a single pass, `frame(gpu)` to batch passes into one submit, `bundle(gpu)` to skip re-encoding what never changes.

See it live: the [batch rendering example](/examples/batch-rendering) packs four primitive types into one buffer and replays them from a single bundle.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: WGSL modules
description: Split shaders into reusable WGSL files with import and export; vgpu resolves the graph, preserves entry-point and binding names, removes unused declarations, and can minify the emitted WGSL.
---

# WGSL modules



## Split a shader into modules

With the wgsl loader, you can create reusable shader modules:

```wgsl
// color.wgsl
export fn gradient(uv: vec2f) -> vec3f {
  return vec3f(uv, 0.4);
}
```

Then, import it by name from other wgsl files:

```wgsl
// shader.wgsl
import { gradient } from "./color.wgsl";

@fragment
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(gradient(uv), 1.0);
}
```

Import the entry shader from TypeScript:

```ts
import { effect, init, surface } from "vgpu";
import shader from "./shader.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas");
if (!canvas) throw new Error("Missing canvas");

const output = surface(gpu, canvas);
effect(gpu, shader).draw(output);
```

## Keep resources in the entry module

Imported modules are pure: they cannot declare `@group` or `@binding` resources. A shared module does not own the bind-group layout of every shader that consumes it.

This module is invalid:

```wgsl
// noise.wgsl
struct NoiseConfig {
  seed: f32,
}

// Error: VGPU-RESOLVE-MODULE-BINDING
@group(0) @binding(0) var<uniform> noise_config: NoiseConfig;
```

Export the data shape and behavior instead:

```wgsl
// noise.wgsl
export struct NoiseConfig {
  seed: f32,
}

export fn sample_noise(config: NoiseConfig, uv: vec2f) -> f32 {
  return fract(sin(dot(uv, vec2f(12.9898, 78.233)) + config.seed) * 43758.5453);
}
```

Then declare the resource in the entry shader:

```wgsl
// shader.wgsl
import { NoiseConfig, sample_noise } from "./noise.wgsl";

@group(0) @binding(0) var<uniform> noise_config: NoiseConfig;

@fragment
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  let value = sample_noise(noise_config, uv);
  return vec4f(vec3f(value), 1.0);
}
```

If an imported module declares a resource, resolution fails with `VGPU-RESOLVE-MODULE-BINDING` and points to the declaration that must move.

## Import local and packaged modules

| Import                                   | Use                                                                     |
| ---------------------------------------- | ----------------------------------------------------------------------- |
| `./color.wgsl` or `../shared/color.wgsl` | A module relative to the importing file.                                |
| `@vgpu/wgsl-std/hash`                    | A WGSL module exposed by an installed package.                          |
| `@acme/shaders/noise`                    | A third-party or workspace package whose exports map points to `.wgsl`. |
| `@/shaders/color.wgsl`                   | A root-relative module when `resolveShader()` is given `rootDir`.       |

Package imports resolve through `node_modules` and package `exports` maps. `@vgpu/wgsl-std` ships with vgpu, so its modules can be imported without copying their source:

```wgsl
import { pcg2d, unitFloat } from "@vgpu/wgsl-std/hash";
```

See [Publishing WGSL module packages](/docs/guides/publishing-wgsl-packages) when the reusable module should live in its own npm or workspace package.

## What vgpu does with the graph

For an entry shader, vgpu:

1. resolves every transitive import;
2. checks module syntax and the pure-module rule;
3. gives imported declarations collision-safe private names;
4. keeps entry points, resources, and overrides addressable by their authored names;
5. removes declarations that no entry point can reach;
6. emits one ordinary WGSL program.

This means two modules can export a helper with the same name without colliding, and importing one function from a large library does not ship every unused declaration. Entry-point names such as `fs_main` remain unchanged for pipeline creation.

Module resolution happens during build or setup, never inside the render loop. Bundler integrations return a prepared `ShaderSource` — the finished WGSL plus its reflection — that `effect`, `draw`, and `compute` take directly; direct `resolveShader()` calls return a `ResolvedShader` whose `.wgsl` field is the finished string; pass that result to `prepareShader()` from `@vgpu/wgsl/prepare` once before rendering.

## Configure module resolution

WGSL itself has no standard module system. vgpu adds `import` and `export` while you author a shader, resolves the complete module graph during build or setup, and emits ordinary WGSL before WebGPU sees it.

With the webpack, Turbopack, or Vite integration configured, import only the entry file from TypeScript. The loader follows its WGSL imports and returns one prepared `ShaderSource` object for vgpu.

| Environment                                | Use                                                                         | Read next                                                         |
| ------------------------------------------ | --------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| Next.js, Turbopack, or webpack             | `@vgpu/wgsl/loader-webpack`                                                 | [Using vgpu with Next.js and other bundlers](/docs/guides/nextjs) |
| Vite or Rollup                             | `@vgpu/wgsl/loader-vite`                                                    | [Using vgpu with Next.js and other bundlers](/docs/guides/nextjs) |
| three.js TSL node materials                | `wgslVitePlugin()` from `vgpu/client` plus `tslExports()` from `vgpu/three` | [Use WGSL modules in three.js TSL](/docs/guides/threejs)          |
| Node.js, scripts, tests, or custom tooling | `resolveShader()` from `@vgpu/wgsl/runtime`                                 | [Using vgpu without a bundler](/docs/guides/no-bundler)           |

The loaders register transitive imports with the bundler, so edits to a shared `.wgsl` file participate in watch mode and HMR. Use `resolveShader()` when there is no bundler to read and flatten the files for you.

## Validate the complete shader

Validate the entry file, not each module in isolation:

```bash
npx vgpu check --require-validation ./shader.wgsl
```

`vgpu check` resolves the same graph and reports errors against the authored modules. `--require-validation` also requires a WebGPU device to accept the emitted WGSL.

Bundler loaders resolve imports, enforce module purity, mangle collisions, and remove unused declarations, but they do not perform device-backed WGSL validation. Run `vgpu check --require-validation` in CI or a pre-commit hook when validation must be a gate.

## Common errors

| Error                         | Cause                                                | Fix                                                                     |
| ----------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------- |
| `VGPU-WGSL-IMP-ORDER`         | An import appears after a declaration.               | Move every import to the top of the entry or module.                    |
| `VGPU-WGSL-SYM-NOEXPORT`      | The target module does not export the imported name. | Add `export` to the declaration or correct the import.                  |
| `VGPU-WGSL-IMP-SELF`          | The import graph contains a cycle.                   | Move shared declarations into a lower-level module and break the cycle. |
| `VGPU-RESOLVE-MODULE-BINDING` | An imported module declares a binding.               | Export its struct or helper and declare the resource in the entry.      |
| `VGPU-WGSL-PKG-NOTFOUND`      | A package or exported subpath cannot be resolved.    | Install the package and check its name and `exports` map.               |

The [`resolveShader` reference](/docs/reference/wgsl/resolve-shader#resolvedshader) lists the complete syntax, options, return shape, and diagnostics.

## Next steps

* [Using vgpu with Next.js and other bundlers](/docs/guides/nextjs) — configure `.wgsl` imports and TypeScript types.
* [Use WGSL modules in three.js TSL](/docs/guides/threejs) — turn pure, direct WGSL function exports into callable Three TSL nodes, including with identifier minification.
* [Using vgpu without a bundler](/docs/guides/no-bundler) — resolve an entry graph from Node.js, scripts, or tests.
* [Publishing WGSL module packages](/docs/guides/publishing-wgsl-packages) — expose reusable `.wgsl` modules through an npm package.
* [The default shader workflow](/docs/guides/shader-workflow) — validate, render, inspect, and test shader changes.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Adaptive quality: switch render pipelines on GPU tier, battery, and FPS
description: Start every visitor on the High pipeline, then downgrade once to a cheaper Low pipeline when detect-gpu, the Battery Status API, or presented-frame health says the device cannot hold it. Copy the code from the adaptive-quality example.
---

# Adaptive quality: switch render pipelines on GPU tier, battery, and FPS



A hero or ambient background has to look great on a desktop GPU and still run on a three-year-old phone at 20% battery. Guessing a single budget serves neither. The pattern below is what the vgpu homepage does: render the **High** pipeline first, watch three advisory signals, and if any of them asks for it, build a **Low** pipeline off-screen and swap once.

The complete, tested implementation is the [adaptive quality example](/examples/adaptive-quality). Pull it instead of re-typing it:

```bash
npx -y vgpu examples show adaptive-quality                      # files and metadata
npx -y vgpu examples cat adaptive-quality frame-health.ts       # one file
npx -y vgpu examples pull adaptive-quality --out ./adaptive-quality
```

Through MCP the same files are available with the `examples` tool: `show`, `read`, and (on scoped local stdio) `download`, all with `id: "adaptive-quality"`.

## When to use it

This is a production pattern for a render that is **always on screen and always animating**: a hero background, an ambient scene behind content, a canvas that plays for the whole session. It earns its cost there because a stuttering hero is the first thing every visitor sees, and because the devices that struggle (phones, integrated GPUs, laptops on battery) are the ones you cannot test on your own machine.

It is overkill while the render is still being designed. It adds a second pipeline to keep in sync with the first, a dependency, and a hosting step for the benchmark tables. Do not reach for it when:

* the user is experimenting, prototyping, or iterating on the look of a shader;
* the render is on demand or short-lived (a preview, a thumbnail, an interaction that ends);
* the audience is known to be desktop-only;
* the High pipeline has not been optimized yet. Cheaper High first ([Performance playbook](/docs/guides/performance-playbook)), tiers second.

**For agents:** treat this as something to *offer*, not to add unprompted. When the user asks for a hero or ambient background and mentions production, mobile, "weak devices," or performance, propose it in one sentence and build it if they agree. When they are exploring, leave it out and mention that a Low tier exists for later. If you are unsure, the smallest useful step is `frame-health.ts` plus a DPR drop: it needs no dependency and no second pipeline, and it can grow into the full pattern when the design settles.

## The model in one paragraph

Quality has three parts: the user's **preference** (`auto`, `high`, `low`), the **effective** tier on screen, and the **reason** it is there (`initial`, `forced`, `gpu-tier`, `battery`, `frame-health`). In `auto`, the renderer always starts High. Signals are started only after the first High frame has been presented, every signal is advisory (a failure keeps High), and the only automatic transition is High → Low, once. Nothing ever upgrades on its own, so there is no oscillation and no hysteresis to tune.

## Files to copy

| File in the example     | What it is                                                                      | Depends on your scene? |
| ----------------------- | ------------------------------------------------------------------------------- | ---------------------- |
| `frame-health.ts`       | Pure FPS-health policy over presented frames                                    | No                     |
| `quality-signals.ts`    | GPU tier + battery + frame health → one `onDowngrade(reason)`                   | No                     |
| `quality-controller.ts` | Requested-vs-active tier reconciliation with off-screen prepare and atomic swap | No                     |
| `quality.ts`            | Tier, preference, reason, and per-tier DPR                                      | No                     |
| `scene.ts`              | What High and Low mean for *this* scene                                         | Yes, replace it        |
| `renderer.ts`           | Glue: manual surface sizing, frame loop, arming and disposing signals           | Mostly reusable        |

`frame-health.ts`, `quality-signals.ts`, and `quality-controller.ts` have no imports from the scene. Copy them unchanged, write your own `scene.ts` against the `TierResources` interface, and adapt `renderer.ts`.

## 1. Define what Low means

Low must be a genuinely cheaper pipeline, not just a lower resolution. In the example High is field → HDR target → bright pass → two half-resolution blurs → tone-mapped composite at DPR ≤ 2; Low is the same field shader with a third of the march steps, tone mapping in-shader, straight to the canvas at DPR 1.

Both tiers implement one interface so the controller can build and swap them without knowing anything else:

```ts
import type { Frame } from "vgpu";

type QualityTier = "high" | "low";

interface TierResources {
  /** Allocate and pre-compile everything. Runs while the previous tier keeps rendering. */
  prepare(): Promise<void>;
  destroy(): void;
}

interface Scene extends TierResources {
  readonly tier: QualityTier;
  resize(size: readonly [number, number]): void;
  render(currentFrame: Frame, time: number): void;
}
```

`prepare()` must `await effect.compile(target)` (or `draw.compile(target)`) for every pass against the target it will render into. That is what makes the swap frame hitch-free: by the time Low becomes active, its pipelines already exist. See [Compilation](/docs/guides/concepts-compilation).

## 2. Own the surface size

Each tier picks its own device pixel ratio, so the canvas surface cannot auto-resize. Create it with `autoResize: false` and drive `resize()` yourself from a `ResizeObserver` and the tier's DPR:

```ts
import { init, surface } from "vgpu";

declare const canvas: HTMLCanvasElement;
declare function tierDpr(tier: "high" | "low", devicePixelRatio: number): number;

const gpu = await init();
const output = surface(gpu, canvas, { autoResize: false, dpr: tierDpr("high", window.devicePixelRatio) });

function applySize(tier: "high" | "low") {
  const { width, height } = canvas.getBoundingClientRect();
  const dpr = tierDpr(tier, window.devicePixelRatio || 1);
  output.resize([Math.max(1, Math.round(width * dpr)), Math.max(1, Math.round(height * dpr))]);
}
```

In the example `tierDpr` clamps High to `[1, 2]` and pins Low to `1`. Resize the new tier's own targets from the same size right before the swap, so its first frame is already at the right resolution.

## 3. Reconcile tiers with a controller

`createQualityController({ createTier, onActivate })` keeps a requested tier and an active tier and runs one loop until they match: create the candidate, `await candidate.prepare()`, check that the request has not changed in the meantime (discard the candidate if it has), call `onActivate(tier, candidate)` for the resize, then swap and destroy the previous tier. It exposes `state`, `subscribe`, `setPreference`, and `downgrade(reason)`; `downgrade` is a no-op unless the preference is `auto` and High is requested.

```text
controller = createQualityController({
  createTier: (tier) => createScene(gpu, output, tier),
  onActivate: (tier, scene) => { applySize(tier); scene.resize(output.size); },
});
await controller.ready;             // High is on screen
frameLoop(gpu, (f) => controller.active?.render(f, clock(gpu).time));
```

## 4. Start the signals after the first frame

Detection must cost the first paint nothing. Arm the signals from inside the frame loop, one `requestAnimationFrame` plus a `setTimeout(0)` after the first presented frame, through a dynamic import so neither the signals module nor detect-gpu lands in the initial chunk. detect-gpu is itself a second dynamic `import()` inside `quality-signals.ts`, so its code (\~15 KB gzip) and the vendor benchmark table it fetches are downloaded only after High is already on screen, and only when the preference is `auto`. The initial bundle pays nothing for the feature:

```text
frameLoop(gpu, (f) => {
  controller.active?.render(f, time.time);
  signals?.recordFrame({ deltaMs: time.deltaTime * 1000, active: autoHigh && visible, rendered: true });
  if (autoHigh && !signals && !scheduled) scheduleSignals();   // rAF → setTimeout(0) → import("./quality-signals")
});

signals = createQualitySignals({
  onDowngrade: (reason) => void controller.downgrade(reason),
  benchmarksUrl: "/gpu-benchmarks",   // optional same-origin copy, see below
});
```

Dispose the signals as soon as the state leaves `auto`/High: after a downgrade, or when the user forces a tier. Re-arm them if the preference returns to `auto`.

### GPU tier with detect-gpu

`@pmndrs/detect-gpu` probes WebGL for the renderer string, then fetches one vendor benchmark table and maps it to a tier 0–3. The policy in `gpuTierRequestsLow` is conservative on purpose: request Low for `isMobile`, for `BLOCKLISTED`, and for `BENCHMARK` tiers 0 and 1. `FALLBACK` (unknown GPU) and `BENCHMARK_FETCH_FAILED` keep High, because an unknown desktop GPU is more often new than weak.

The benchmark tables live on detect-gpu's CDN by default. For production, copy `node_modules/@pmndrs/detect-gpu/dist/benchmarks/*.json` into your public directory and pass `benchmarksUrl` so the request is same-origin and pinned to the installed version; the vgpu repo does this in `apps/docs/scripts/prepare-prism-gpu-benchmarks.mjs`. A blocked or failed fetch is logged and ignored.

### Battery

Feature-check `navigator.getBattery` first: it is missing in Safari and Firefox. Request Low when the device is discharging at or below 30% (inclusive), and keep listening to `levelchange` and `chargingchange` so a laptop unplugged mid-session still downgrades. The example's `batteryRequestsLow` is the whole rule.

### Frame health

Do not measure the raw `requestAnimationFrame` rate; measure **presented** frames against the target the workload actually has. `createFrameHealthMonitor()` takes one sample per tick:

| Field       | Meaning                                                                        |
| ----------- | ------------------------------------------------------------------------------ |
| `deltaMs`   | Raw rAF interval, from `clock(gpu).deltaTime * 1000`                           |
| `active`    | The renderer had work, the page is visible, and Auto/High is on screen         |
| `rendered`  | This tick presented a frame (false when a cap or "nothing changed" skipped it) |
| `targetFps` | Optional intentional cap for this tick, for example `30` for an ambient loop   |

It estimates the display refresh rate from a stable median (seeded at 60, never lowered, capped at 90), and asks for Low when presented FPS stays below 80% of the target for two seconds of active time. Gaps over 250 ms (hidden tab, idle) reset the window instead of counting as drops. Call `resetHealth()` after a resize or a swap.

## 5. Show the state

Expose `{ preference, effective, reason }` to the UI and log every decision with structured `console.info`. Users can then see *why* they got Low ("GPU tier", "battery", "FPS drops") and force a tier if they disagree. The example's `index.tsx` renders exactly that: a label and three buttons.

## Anti-patterns

* **Upgrading back automatically.** Presented FPS improves the moment Low is active, which would immediately argue for High again. Only the user moves back up.
* **Importing detect-gpu at module scope.** Its code joins your initial bundle, and its WebGL probe and benchmark fetch compete with your first frame. Import it inside the signals module, which is itself imported after the first frame.
* **Judging FPS against the rAF rate.** A deliberate 30 FPS cap or a 120 Hz display both produce false downgrades. Pass `rendered` honestly and `targetFps` when you cap.
* **Swapping before `prepare()` resolves.** Compiling pipelines on the swap frame is the hitch the whole technique exists to avoid.
* **Calling `getBattery()` without a feature check.** It throws where the API is absent.
* **Letting the surface auto-resize.** It re-reads `devicePixelRatio` each frame and overwrites the Low DPR.

## Testing

All three reusable modules have seams: `createQualitySignals` accepts `navigator`, `loadGpuTier`, `healthMonitor`, and `logger`; `createFrameHealthMonitor` is pure, drive it with synthetic `{ deltaMs, active, rendered }` samples; `createQualityController` takes any `createTier` factory, so fake tiers with deferred `prepare()` prove that stale candidates are discarded and the previous tier is destroyed only after the swap. The example ships `frame-health.test.ts`, `quality-signals.test.ts`, `quality-controller.test.ts`, and `renderer.test.ts` as templates.

## See also

* [Adaptive quality example](/examples/adaptive-quality): the code this guide describes.
* [Compilation](/docs/guides/concepts-compilation): why `prepare()` compiles against the real target.
* [Measuring](/docs/guides/measuring): confirm a pass is expensive before cutting it from Low.
* [Performance playbook](/docs/guides/performance-playbook): default shapes that make High cheaper in the first place.
* [Shipping to production](/docs/guides/shipping-to-production): the pre-PR checklist that decides when to offer a Low tier.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: WebGPU screenshots with agent-browser
description: Use `agent-browser` to verify and capture vgpu previews that run WebGPU on Linux, including containers without a GPU. This complements [Browser testing with Playwright WebGPU](browser-testing.docs.md): use Playwright for API tests and this CDP automation recipe for visual captures.
---

# WebGPU screenshots with agent-browser



## Install and validate the environment

Install `agent-browser` (the verified version is v0.33.0). It automates Chromium through CDP. On Linux or in a container, install Vulkan and virtual-display dependencies before capturing screenshots:

```bash
npm i -g agent-browser@latest
apt-get install -y libvulkan1 mesa-vulkan-drivers xvfb xauth
agent-browser doctor --webgpu --headed
```

`doctor` runs a two-stage render and screenshot probe with a pixel check. In this sandbox, rendering passed with `google swiftshader` and the screenshot passed with `rgb(255,0,0)`.

Do not use headless Chrome without `--webgpu` to verify WebGPU. It does not expose WebGPU by default and can silently produce a black canvas.

## Choose the WebGPU mode

Always use `--webgpu` for the preset. It enables `--enable-unsafe-webgpu` on every platform. On Linux, it also selects software Vulkan through SwiftShader:

```text
--enable-features=Vulkan
--use-angle=vulkan
--use-vulkan=swiftshader
--use-webgpu-adapter=swiftshader
--disable-vulkan-surface
```

SwiftShader does not require a GPU or `/dev/dri`. It is slower than hardware: wait about six seconds and two `requestAnimationFrame` calls before capturing heavy previews, especially `fluid`, `fft-ocean`, and `raymarched-fractal`.

On Linux, headless mode with `--webgpu` renders, but headless Chrome captures the canvas as black; this is an upstream limitation. Add `--headed`. If `DISPLAY` is absent and Xvfb is installed, agent-browser automatically starts a virtual display.

```bash
agent-browser --session vgpu-webgpu --webgpu --headed open http://localhost:3001/preview/gradient
agent-browser --session vgpu-webgpu --webgpu --headed screenshot gradient.png
```

To prefer hardware Vulkan when it is available, override the preset adapters with user arguments; user arguments win over the preset:

```bash
agent-browser --webgpu --args "--use-vulkan=native,--use-webgpu-adapter=default" open http://localhost:3001
```

You can also enable the preset through an environment variable or configuration:

```bash
AGENT_BROWSER_WEBGPU=1 agent-browser --headed open http://localhost:3001
# agent-browser.json: { "webgpu": true }
```

## Capture and validate one preview

Isolate each job in a dedicated session and close it when finished. `screenshot` can succeed even when WebGPU failed and the image is black, so always validate pixels and application state.

```bash
SESSION=vgpu-webgpu
URL=http://localhost:3001/preview/gradient

agent-browser --session "$SESSION" --webgpu --headed open "$URL"
agent-browser --session "$SESSION" --webgpu --headed wait 6000
agent-browser --session "$SESSION" --webgpu --headed eval 'new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))'
agent-browser --session "$SESSION" --webgpu --headed screenshot gradient.png
identify -format '%[fx:standard_deviation]\n' gradient.png
agent-browser --session "$SESSION" close
```

A low or zero standard deviation indicates a uniform or black capture. Also inspect vgpu error overlays: `Preview error`, `WebGPU is not available`, and `No WebGPU adapter was found`.

`agent-browser` does not support `text=` selectors. Use CSS selectors instead; a `text=` attempt can fail silently, which is another reason pixel validation must be the assertion of record.

`agent-browser eval` returns JSON-escaped output. Unescape it before grepping or parsing it:

```bash
META=$(agent-browser --session "$SESSION" --webgpu --headed eval 'JSON.stringify({ text: document.body.innerText, hasCanvas: Boolean(document.querySelector("canvas")), webgpu: Boolean(navigator.gpu) })')
printf '%s' "$META" | sed 's/\\"/"/g' | grep -E 'Preview error|WebGPU is not available|No WebGPU adapter was found'
```

## Capture every vgpu preview

With the documentation server already running from `apps/docs` on port 3001, this recipe rendered and captured all nine `/preview/<slug>` previews in this sweep through SwiftShader. The simplified loop waits for initialization, requires a canvas, captures, and rejects uniform pixels:

```bash
SESSION=vgpu-previews
BASE_URL=http://localhost:3001
for slug in gradient triangle-led-front anti-aliasing black-hole fluid instanced-rendering batch-rendering fft-ocean raymarched-fractal; do
  agent-browser --session "$SESSION" --webgpu --headed open "$BASE_URL/preview/$slug"
  agent-browser --session "$SESSION" --webgpu --headed wait 6000
  agent-browser --session "$SESSION" --webgpu --headed eval 'new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))'
  agent-browser --session "$SESSION" --webgpu --headed eval 'JSON.stringify({hasCanvas:Boolean(document.querySelector("canvas")),webgpu:Boolean(navigator.gpu),text:document.body.innerText})' | sed 's/\\"/"/g' | grep -q '"hasCanvas":true'
  agent-browser --session "$SESSION" --webgpu --headed screenshot "$slug.png"
  identify -format '%[fx:standard_deviation]\n' "$slug.png" | awk '$1 > 50'
done
agent-browser --session "$SESSION" close
```

Do not omit pixel checks or error-overlay checks for individual previews. For a complete automation flow with logs, retries, `navigator.gpu`, and a WebGPU context check, keep this sequence and record console output and errors before closing the session.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Authoring shaders for performance
description: Write WGSL so reflection can build stable layouts. Bindings should be explicit, structs should be host-shareable, and hot paths should avoid per-frame resource identity changes.
---

# Authoring shaders for performance



Layouts mirror what each entry point statically uses, the same way WebGPU's
`layout: 'auto'` behaves: bindings an entry never touches are omitted,
visibility covers only the stages that actually read a binding, and sampled
`f32` textures are declared filterable exactly when the shader samples them
through a filtering sampler (`textureLoad`-only access stays
unfilterable, keeping `rgba32float` readbacks valid). Mismatches fail eagerly
with structured errors — `VGPU-LIMIT-STORAGE-VERTEX`/`-FRAGMENT` when a
storage binding would exceed a device's per-stage limits, and
`VGPU-SET-TEXTURE-FILTERABILITY` when a non-filterable format meets a
filtering sampler — instead of surfacing as native pipeline failures.

## WGSL defaults

```wgsl
struct Globals {
  time: f32,
  mouse: vec2f,
  enabled: u32,
}
@group(0) @binding(0) var<uniform> globals: Globals;
```

* Use `u32` instead of `bool` in host-written uniforms; encode false/true as `0`/`1`.
* Put target resolution in a uniform value sourced from `target.size` or `target.texelSize`.
* Keep imported WGSL modules binding-free. Modules may export structs/functions/constants; entry shaders own `@group/@binding` declarations.
* Prefer storage buffers plus `instances` for many similar particles or sprites.

## JavaScript defaults

```text
const globals = uniforms(gpu, { time: 0, mouse: [0, 0], enabled: 1 });
const draw = draw(gpu, { shader: sceneShader, set: { globals } }); // sceneShader: a prepared .wgsl import
await draw.compile(target);
frameLoop(gpu, (f) => {
  globals.set({ time: clock(gpu).time, mouse });
  f.pass({ target }, (p) => p.draw(draw));
});
```

Use the performance playbook before writing a new shader: bundles for static draws, `compile()` for pre-warm, `draw.group()` for many objects, `uniforms(gpu)` for shared state, ping-pong for iterative effects, and target-owned depth/MSAA.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Browser testing with Playwright WebGPU
description: Browser tests should exercise the same public API users copy: `init()`, `surface(gpu, canvas, opts)`, explicit targets, and deterministic frame submission. Avoid hidden app globals and avoid relying on a continuous loop in assertions.
---

# Browser testing with Playwright WebGPU



```text
import { init } from "vgpu";
import waveShader from "./wave.wgsl"; // prepared at build time by the @vgpu/wgsl loader

export async function renderOnce(canvas: HTMLCanvasElement) {
  const gpu = await init();
  const surface = surface(gpu, canvas, { dpr: 1, autoResize: false });
  const effect = effect(gpu, waveShader, { set: { time: 0, texel: surface.texelSize } });
  frame(gpu, (f) => f.pass({ target: surface, clear: [0, 0, 0, 1] }, (p) => p.draw(effect)));
  return gpu;
}
```

## Test checklist

* Use fixed DPR/size (`dpr: 1`, `autoResize: false`, or explicit `size`) for pixel snapshots.
* Submit with `frame(gpu, ...)` for one deterministic frame, not `requestAnimationFrame` loops.
* Read from explicit surfaces or offscreen targets with `target.color.read({ mipLevel: 0, region: "all" })`.
* Keep WGSL imports pure: modules export helpers only; bindings live in the entry shader. If a module declares a binding, fix `VGPU-RESOLVE-MODULE-BINDING`.
* For headless tests use `vgpu/mock` for deterministic unit tests and `vgpu/node` only when Dawn/WebGPU behavior is under test.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: External ticker
description: Drive the vgpu clock from GSAP, Motion, an XR frame callback or a fixed timestep with clock(gpu).advance(dt).
---

# External ticker



# Driving vgpu with an external ticker — GSAP/Motion/XR

By default vgpu owns the clock: every `frame(gpu)` moves `clock(gpu).time` forward by the wall-clock delta since the last frame, and `frameLoop(gpu, cb)` schedules those frames on `requestAnimationFrame`. That is the right default for a page whose only animation is the render.

It stops being the right default the moment something else already owns the timeline: a GSAP or Motion ticker, an XR session's frame callback, a physics loop with a fixed timestep, or a test that must produce the same pixels twice. Two clocks running side by side drift, and drift shows up as animation that stutters against everything else on the page.

The fix is one call. `clock(gpu).advance(dtSeconds)` moves the vgpu clock forward *now*, and claims that frame's tick: the next `frame(gpu)` counts the frame and runs its passes, but does not advance the clock again. One tick per frame, with the manual one winning.

```ts
import { init, clock, effect, frame, surface } from "vgpu";
import waveShader from "./wave.wgsl";

declare const canvas: HTMLCanvasElement;
declare const gsap: { ticker: { add(cb: (time: number, deltaMs: number) => void): void } };

const gpu = await init();
const canvasSurface = surface(gpu, canvas);
const wave = effect(gpu, waveShader, { set: { params: { time: 0 } } });

// ---cut---
const time = clock(gpu);

// GSAP owns the rAF; vgpu renders inside its tick, on GSAP's delta.
gsap.ticker.add((_total, deltaMs) => {
  time.advance(deltaMs / 1000);          // the clock moves here...
  wave.set({ params: { time: time.time } });
  frame(gpu, (f) => f.pass(canvasSurface, wave)); // ...and not again here
});
```

Note what disappears: there is no `frameLoop(gpu, ...)`. The external ticker is the loop, and `frame(gpu, cb)` is the render — encode, submit, done.

## Motion, XR, and anything else with a delta

Every ticker hands you the same thing under a different name, so the shape never changes:

```ts
import { init, clock, frame } from "vgpu/mock";

const gpu = await init();
const time = clock(gpu);
declare function render(): void;

// ---cut---
// Motion (frame + delta):
//   frame.update(({ delta }) => { time.advance(delta / 1000); render(); });

// WebXR (absolute timestamps, one session frame at a time):
declare const session: { requestAnimationFrame(cb: (timestampMs: number, xrFrame: unknown) => void): number };
let previousMs: number | undefined;
const onXRFrame = (timestampMs: number) => {
  time.advance(previousMs === undefined ? 0 : (timestampMs - previousMs) / 1000);
  previousMs = timestampMs;
  frame(gpu, () => render());
  session.requestAnimationFrame(onXRFrame);
};
session.requestAnimationFrame(onXRFrame);
```

The first XR frame advances by `0`: there is no previous timestamp to measure against, and a made-up first delta is the classic source of a one-frame jump when the headset starts.

## Timescale: slow motion is a multiplication

Because the delta is yours, scaling it is the whole feature — no separate "speed" uniform threaded through every shader, and no second clock:

```ts
import { init, clock, frameLoop } from "vgpu/mock";

const gpu = await init();

// ---cut---
const time = clock(gpu);
let timescale = 1;         // 0 pauses, 0.25 is slow motion, 2 is fast forward
let previousMs = performance.now();

frameLoop(gpu, () => {
  const nowMs = performance.now();
  time.advance(((nowMs - previousMs) / 1000) * timescale);
  previousMs = nowMs;
  // ... render with time.time
});
```

`frameLoop` still schedules the frames; it just no longer decides what a frame is worth. `advance(0)` is legal and is the honest way to pause: the clock stops, frames keep rendering, `frameCount` keeps counting.

## Fixed timestep and determinism

A simulation that must not depend on frame rate advances in fixed steps and renders whatever the accumulator leaves behind:

```ts
import { init, clock, frame, frameLoop } from "vgpu/mock";

const gpu = await init();
declare function step(dt: number): void;
declare function render(): void;

// ---cut---
const time = clock(gpu);
const STEP = 1 / 120;                    // simulate at 120 Hz, render at display rate
let accumulator = 0;
let previousMs = performance.now();

frameLoop(gpu, () => {
  const nowMs = performance.now();
  accumulator += Math.min(0.25, (nowMs - previousMs) / 1000); // clamp: a hidden tab must not spiral
  previousMs = nowMs;

  let advanced = 0;
  while (accumulator >= STEP) {
    step(STEP);
    accumulator -= STEP;
    advanced += STEP;
  }
  time.advance(advanced);                // one advance per frame, however many steps ran
  render();
});
```

The same technique makes headless renders reproducible: drop the wall clock entirely and advance by a constant.

```ts
import { init, clock, effect, frame, target } from "vgpu/mock";
import sceneShader from "./shader.wgsl";

const gpu = await init();
const scene = target(gpu, { size: [64, 64] });
const shader = effect(gpu, sceneShader);

// ---cut---
const time = clock(gpu);
for (let i = 0; i < 90; i++) {
  time.advance(1 / 60);                  // frame 90 always lands on t = 1.5s
  frame(gpu, (f) => f.pass(scene, shader));
}
const pixels = await scene.color.read({ mipLevel: 0, region: "all" });       // same bytes on every machine, every run
void pixels;
```

## Rules of the technique

* **One advance per frame.** `advance()` before `frame()` is the pattern. Calling `advance()` twice before a single frame accumulates both deltas into `time` and leaves `deltaTime` at the last one — usually a bug in the ticker wiring.
* **Mixing is fine.** Skip `advance()` for a frame and that frame falls back to the wall-clock delta, measured from the previous tick. There is no mode to switch.
* **`frameCount` counts frames, not advances.** It only moves inside `frame()` / `frameLoop()`, so it stays a reliable "how many times did we render".
* **`advance()` takes seconds.** Most tickers hand out milliseconds — divide by 1000. Negative or non-finite deltas throw `VGPU-CLOCK-DELTA-INVALID` instead of quietly running time backwards.
* **Read the clock, don't cache the numbers.** `clock(gpu)` returns the same live object every time; `const time = clock(gpu)` outside the loop and `time.time` inside it always reads the current value.

## See also

* [Frames](/docs/guides/concepts-frames) — what `frame(gpu, cb)` and `frameLoop(gpu, cb)` actually do.
* `clock` — the full API of the clock, including its error codes.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Getting started
description: Start with the public `vgpu` package. A program has one `Gpu` context, explicit WGSL bindings, and explicit frames. There are no global uniforms: time comes from the frame clock (`clock(gpu).time`, `.deltaTime`, `.frameCount`) and resolution comes from targets (`target.size`, `target.texelSize`).
---

# Getting started



```wgsl
// gradient.wgsl
struct Params { time: f32, texel: vec2f }
@group(0) @binding(0) var<uniform> params: Params;
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, sin(params.time) * 0.5 + 0.5, 1.0);
}
```

```ts
import { clock, init, effect, frameLoop, surface } from "vgpu";
import gradientShader from "./gradient.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas, { dpr: [1, 2] });
const gradient = effect(gpu, gradientShader, {
  set: { params: { time: 0, texel: canvasSurface.texelSize } },
});

canvasSurface.onResize(() => {
  gradient.set({ params: { texel: canvasSurface.texelSize } });
});

const time = clock(gpu);
frameLoop(gpu, (frame) => {
  gradient.set({ params: { time: time.time } });
  frame.pass(canvasSurface, gradient);
});
```

`effect(gpu)`, `draw(gpu)`, and `compute(gpu)` take a prepared `ShaderSource` — the WGSL plus the reflection vgpu reads bindings from — not a WGSL string. The `@vgpu/wgsl` bundler loader turns `import gradientShader from "./gradient.wgsl"` into one at build time, so the browser never loads the WGSL parser; wire it up with [Using vgpu with Next.js and other bundlers](/docs/guides/nextjs). With no bundler, wrap the WGSL string in `prepareShader()` from `@vgpu/wgsl/prepare` once, before creating the effect, as the headless example below does. Passing a raw string throws `VGPU-SHADER-SOURCE-UNPREPARED`.

Two habits keep this correct as it grows: bindings are set by their WGSL
names — `params` is a struct, so its members nest inside it — and `set()`
writes immediately, so the render loop only writes what actually changes
(`time`); size-class values like `texel` belong in the resize handler.

## Validate with static renders

You do not need a browser — or eyes — to prove a shader right. First, verify
the machine can render at all:

```bash
npx vgpu doctor   # JSON verdict: healthy | unhealthy — each problem with its exact fix
```

`doctor` acquires a real adapter and renders a frame; when something is
missing it prescribes the exact package install or environment variable to
set. Once healthy, render headless and read the pixels back — objective
evidence instead of guesswork:

```ts
import { writeFileSync } from "node:fs";
import { PNG } from "pngjs";
import { init, effect, target } from "vgpu/node";
import { prepareShader } from "@vgpu/wgsl/prepare";

const SHADER = prepareShader(`
  @fragment fn main() -> @location(0) vec4f {
    return vec4f(0.25, 0.5, 0.75, 1.0);
  }
`); // no loader in Node: reflect the WGSL once, up front
const width = 160;
const height = 90;
const gpu = await init();
const colorTarget = target(gpu, { size: [width, height] }); // small targets stay fast, even on CPU
effect(gpu, SHADER).draw(colorTarget);
const pixels = await colorTarget.color.read({ mipLevel: 0, region: "all" });                   // RGBA bytes — assert on them
const png = new PNG({ width, height });               // ...and write a PNG you can open
png.data.set(pixels);
writeFileSync("frame.png", PNG.sync.write(png));
gpu.dispose();                                        // stops Dawn's polling so the process exits
```

Keep the loop tight: render → read → adjust → render. Every visual claim you
make should be backed by pixels you actually read — assert on `pixels` when you
know the expected value, and open `frame.png` when you need to judge
composition. PNG encoding is project-owned: `pngjs` is one option, any encoder
works.

If the shader lives in its own `.wgsl` file instead of a template string — even
without a bundler — resolve it first with `resolveShader()`, then pass the
resolved WGSL to `prepareShader()`:
[Using vgpu without a bundler](/docs/guides/no-bundler).

The full step-by-step playbook — from `vgpu docs` to browser validation — is
[The default workflow for developing shaders with vgpu](/docs/guides/shader-workflow).
When a shader is multi-pass or a user reports a visual bug, do not iterate by
eye: extract the shader's internal values as pixels and diff them against a CPU
reference, following
[Debugging shaders by extracting internal values](/docs/guides/shader-debugging).

## Default choices

* Use `effect(gpu)` for fullscreen fragment work.
* Use `draw(gpu)` for vertex shaders, meshes, storage-driven vertices, instancing, MRT, and depth.
* Use `effect.draw(target)` for simple single-pass draws; use `frame(gpu, (f) => ...)` to batch multi-pass work and `frameLoop(gpu, ...)` for animation.
* Use `set()` for every binding declared in WGSL; missing bindings fail with `VGPU-R1-BINDING-NEVER-SET`.
* Keep plain JS values plain from their first `set()`; if you need user-owned lifetime, pass a resource from the first `set()`.
* Request optional device capabilities at startup with `init({ requiredFeatures: [...] })` — for example `"timestamp-query"` for `timer(gpu)`; a name the adapter lacks fails init with `VGPU-FEATURE-UNSUPPORTED`.

## Where to go next

Read the concept guides in order — each builds on the previous one:

```bash
vgpu docs cat concepts-context.md         # the Gpu context, surfaces, targets
vgpu docs cat concepts-wgsl-modules.md    # split shaders with import and export
vgpu docs cat concepts-draws.md           # draw(), meshes, instancing
vgpu docs cat concepts-compilation.md     # compile() and pipeline warmup
vgpu docs cat concepts-effects.md         # fragment effects and set()
vgpu docs cat concepts-passes.md          # frame.pass and multi-pass work
vgpu docs cat concepts-frames.md          # frame batching and animation loops
vgpu docs cat concepts-render-bundles.md  # record draws once, replay cheap
```

Shipping this inside an app? Shaders in their own `.wgsl` files need a bundler
loader plus one ambient TypeScript declaration, and the canvas has to live in a
client component:

```bash
vgpu docs cat nextjs.md   # Next.js (Turbopack or webpack), Vite, .wgsl types, canvas component
```

Not using a bundler at all — plain Node, a script, or a test runner? Resolve
`.wgsl` files and their imports yourself:

```bash
vgpu docs cat no-bundler.md   # resolveShader(), headless Node rendering, ESM + CommonJS usage
```

Rendering an actual 3D scene rather than a fullscreen effect? Depth lives on an
offscreen target, so the scene needs two passes — the unified recipe:

```bash
vgpu docs cat two-pass-rendering.md   # offscreen depth target -> composite to canvas
```

For performance work and testing:

```bash
vgpu docs cat /guides/performance-model.docs.md
vgpu docs cat /guides/performance-patterns.docs.md
vgpu docs cat browser-testing
```

Finishing, opening a PR, or calling a render done? Run the pre-PR checklist
before you hand it over:

```bash
vgpu docs cat shipping-to-production   # correctness gates, measure, free defaults, propose the rest
```


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Guides
description: Task-oriented guides for using vgpu effectively.
---

# Guides



Task-oriented notes for integrations, performance, browser testing, measurement, and shader authoring.

## General

<Cards>
  <Card title="Getting started" href="/docs/guides/getting-started" />
</Cards>

## Integrations

<Cards>
  <Card title="Use WGSL modules in three.js TSL" href="/docs/guides/threejs" />

  <Card title="Using vgpu with Next.js and other bundlers" href="/docs/guides/nextjs" />

  <Card title="Using vgpu without a bundler" href="/docs/guides/no-bundler" />

  <Card title="External ticker" href="/docs/guides/external-ticker" />
</Cards>

## Performance

<Cards>
  <Card title="Performance model" href="/docs/guides/performance-model" />

  <Card title="Performance patterns" href="/docs/guides/performance-patterns" />

  <Card title="Authoring shaders for performance" href="/docs/guides/authoring-for-perf" />

  <Card title="Measuring" href="/docs/guides/measuring" />

  <Card title="Optimize a pass" href="/docs/guides/optimize-pass" />

  <Card title="Shader diagnostics and fix-its" href="/docs/guides/shader-fix-its" />

  <Card title="Performance playbook: write fast vgpu by default" href="/docs/guides/performance-playbook" />
</Cards>

## Testing

<Cards>
  <Card title="Browser testing with Playwright WebGPU" href="/docs/guides/browser-testing" />
</Cards>

## More guides

<Cards>
  <Card title="WebGPU screenshots with agent-browser" href="/docs/guides/agent-browser-webgpu" />

  <Card title="Publishing WGSL module packages" href="/docs/guides/publishing-wgsl-packages" />

  <Card title="Debugging shaders by extracting internal values" href="/docs/guides/shader-debugging" />

  <Card title="The default workflow for developing shaders with vgpu" href="/docs/guides/shader-workflow" />

  <Card title="Practical texture-format matrix" href="/docs/guides/texture-formats" />

  <Card title="Two-pass rendering: offscreen depth target composited to the canvas" href="/docs/guides/two-pass-rendering" />
</Cards>


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Measuring
description: Measure the thing you intend to optimize: CPU encoding, pipeline warm-up, bind-group churn, target memory, or shader cost. The public API makes those boundaries visible.
---

# Measuring



## CPU encoding vs replay

If the CPU is busy rebuilding the same render pass, compare a direct loop with a bundle:

```text
const staticScene = bundle(gpu, { target }, (b) => staticDraws.forEach((draw) => b.draw(draw)));
frameLoop(gpu, (f) => f.pass({ target }, (p) => p.bundles(staticScene)));
```

## First-frame hitches

If the first visible frame stutters, pre-warm target signatures with `compile()`:

```text
const hdr = target(gpu, { size: [256, 256], format: "rgba16float", depth: true, msaa: true });
const draw = draw(gpu, { shader: sceneShader, mesh }); // sceneShader: a prepared .wgsl import
await draw.compile(hdr);
```

## Binding churn

If allocations or bind-group count grows every frame, switch repeated JS values to in-place `set()`, shared state to `uniforms(gpu)`, or many object uniforms to `UniformPool` + dynamic offsets.

## GPU pass cost

If a pass looks expensive, confirm it on the GPU before optimizing it. CPU time around `frame.pass(...)` measures encoding only — encoders record commands, they do not run them. Mark the pass with a `timer(gpu)` span instead:

```text
const gpu = await init({ requiredFeatures: ["timestamp-query"] });
const timer = timer(gpu);
timer.onResults((spans) => console.log(`shadows ${spans.shadows}ms, main ${spans.main}ms`));
frameLoop(gpu, (f) => {
  f.pass({ target: shadowMap, timer: timer.span("shadows") }, (p) => p.draw(casters));
  f.pass({ target: scene, timer: timer.span("main") }, (p) => p.draw(world));
});
```

Durations arrive through `onResults` in milliseconds, one or two frames after submit; readback never blocks a frame. A span times the whole pass, not individual draws — move suspect work into its own pass to isolate it.

## Correctness before speed

When measuring visual output, render one deterministic `frame(gpu, ...)` into an explicit target and read it back. Do not measure while also resizing, compiling pipelines lazily, or creating temporary targets inside the loop.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Using vgpu with Next.js and other bundlers
description: Add `wgslTurbopackRule()` to Next.js Turbopack or the WGSL loader to webpack and Vite, type `.wgsl` imports for TypeScript, and render a shader from a client component with a canvas.
---

# Using vgpu with Next.js and other bundlers



`effect(gpu, source)`, `draw(gpu, { shader })`, and `compute(gpu, source)` take a prepared `ShaderSource`: the final WGSL plus the reflection the renderer reads instead of parsing WGSL in the browser. The loader is the default way to get one. It prepares every `.wgsl` import at build time — resolving any `import` graph first — so the browser bundle carries prepared data, not the WGSL parser. Without a bundler, see [Use vgpu without a bundler](/docs/guides/no-bundler); for WGSL you generate at runtime, call `prepareShader()` from `@vgpu/wgsl/prepare`.

This guide is the bundler half of [Getting started](/docs/guides/getting-started): install, loader config, TypeScript types for `.wgsl` imports, and the client component that owns the canvas.

New to shader imports? Read [WGSL modules](/docs/concepts/wgsl-modules) first for the `import`/`export` syntax, pure-module rule, and what vgpu emits. This page focuses on wiring that model into a bundler.

## Install

```bash
npm install vgpu @vgpu/wgsl
```

Install `@vgpu/wgsl` at the release your `vgpu` version depends on (`npm ls @vgpu/wgsl` shows it), in the package that owns `next.config.ts`, `vite.config.ts`, or your webpack config. The bundler configs on this page and the `wgsl-types` reference below import or resolve `@vgpu/wgsl/*` subpaths from your app, and pnpm's isolated `node_modules` and Yarn PnP do not expose the copy that `vgpu` installs transitively. It is build tooling: `devDependencies` works when your build environment installs dev dependencies; otherwise use `dependencies`.

WGSL package imports are different. `@vgpu/wgsl-std` (the pure-WGSL standard modules) is a dependency of `vgpu`, so `import { voronoi3d } from "@vgpu/wgsl-std/noise";` inside a `.wgsl` file resolves with no extra install step — under npm, pnpm, and Yarn alike, including pnpm's isolated `node_modules` and Yarn PnP.

A WGSL package import resolves from your project's own `node_modules` first, so a copy you installed yourself always wins, and then next to `@vgpu/wgsl` itself, which is what makes a transitive install of `@vgpu/wgsl-std` work. `VGPU-WGSL-PKG-NOTFOUND` therefore means the package is reachable from neither — install it (`npm install <pkg>`) and check the specifier spelling. Third-party and workspace packages work the same way, including `import { customNoise } from "@packages/shaders";` for a `workspace:*` package in a monorepo: see [Publishing WGSL module packages](/docs/guides/publishing-wgsl-packages) for the full resolution order and the `exports` map a package needs.

## Next.js with Turbopack

Next 16 uses Turbopack for `next dev` and `next build` by default; on Next 15.5, pass `--turbopack` to either command. Add the rule that [`wgslTurbopackRule()`](/docs/reference/wgsl/next) returns as the `"*.wgsl"` entry of the top-level `turbopack.rules`:

```ts
// next.config.ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

const nextConfig = {
  turbopack: {
    rules: {
      "*.wgsl": wgslTurbopackRule(),
    },
  },
};

export default nextConfig;
```

`wgslTurbopackRule()` runs in Node while Next loads the config. It returns a complete rule — the absolute path of the loader from the same `@vgpu/wgsl` installation, `as: "*.js"` so Turbopack treats the output as JavaScript, and a hash of the installed compiler files that keeps restored caches correct (see [Persistent caches and upgrades](#persistent-caches-and-upgrades)). Insert it unchanged; do not edit its `loaders` or `options`.

Pass minification to the helper. `true` strips whitespace and safely shortens identifiers; `{ whitespace: true }` strips whitespace only:

```ts
// next.config.ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

const nextConfig = {
  turbopack: {
    rules: {
      "*.wgsl": wgslTurbopackRule({ minify: true }),
    },
  },
};

export default nextConfig;
```

The helper owns one rule, not your config. Spread the levels you extend so existing rules, settings, and plugin wrappers such as `withMDX(nextConfig)` stay as they are:

```ts
// next.config.ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

const existingConfig = {
  reactStrictMode: true,
  turbopack: {
    rules: {
      "*.svg": {
        loaders: [{ loader: "@svgr/webpack", options: { icon: true } }],
        as: "*.js",
      },
    },
  },
};

const nextConfig = {
  ...existingConfig,
  turbopack: {
    ...existingConfig.turbopack,
    rules: {
      ...existingConfig.turbopack.rules,
      "*.wgsl": wgslTurbopackRule({ minify: true }), // the only new entry
    },
  },
};

export default nextConfig;
```

For a phase-based or async config, call `wgslTurbopackRule()` inside the function you export. Invalid options fail while the config loads: `VGPU-WGSL-NEXT-OPTIONS` names an unknown or mistyped field, and `VGPU-WGSL-MINIFY-IDENTIFIERS` rejects an identifier mode other than `"none"` or `"safe"`.

Requires Next.js 15.5 or newer for the top-level `turbopack` key. Next 15.0–15.2 used `experimental.turbo.rules`, deprecated since. Turbopack runs webpack-compatible loaders through a bridge. On Next 16.3.3, that bridge records files passed to `this.addDependency()`, which is how the loader registers each imported `.wgsl` file — so editing an imported module invalidates its importer — and its own compiler files. The bridge does not implement `this.addBuildDependency()`, and it does not track files a loader merely reads without registering them.

The helper shape is exercised end to end by `examples/next-wgsl` in the vgpu repository.

<Callout type="info">
  Good to know: Next types the rule for you. In a project with Next installed, annotate the config with `NextConfig` (`import type { NextConfig } from "next";`); the returned rule fits the `turbopack.rules` type of both Next 15.5 and Next 16. `@vgpu/wgsl` itself has no dependency on `next`.
</Callout>

## Next.js with webpack

Next 16 uses webpack under `next dev --webpack` / `next build --webpack`; Next 15.5 uses it whenever you omit `--turbopack`. `wgslTurbopackRule()` does not apply here — webpack mode ignores `turbopack.rules`. Push the raw loader from the `webpack` hook for `test: /\.wgsl$/`:

```ts
// next.config.ts
type WebpackConfig = { module?: { rules?: unknown[] } };

const nextConfig = {
  webpack(config: WebpackConfig) {
    config.module ??= {};
    config.module.rules ??= [];
    config.module.rules.push({
      test: /\.wgsl$/,
      loader: "@vgpu/wgsl/loader-webpack",
    });
    return config;
  },
};

export default nextConfig;
```

Keep both blocks when your app runs webpack in one command and Turbopack in another: Next reads `turbopack` only in Turbopack mode and calls `webpack()` only in webpack mode, so the `"*.wgsl"` rule and the hook coexist in one config. In a project that has Next's own types available, annotate with `NextConfig` (`import type { NextConfig } from "next";`) instead of the local `WebpackConfig` alias; the alias above only exists so this snippet compiles on its own.

Add `options: { minify: true }` to the rule for production builds. The loader registers its own compiler files with `this.addBuildDependency()` on every run, so webpack's persistent cache records them as build dependencies of each shader module. Full option reference: `npx vgpu docs cat /@vgpu/wgsl/loader-webpack/index.docs.md`.

## Persistent caches and upgrades

Turbopack and webpack can restore loader output from a persistent cache — `.next/cache` in Next.js, often kept between CI or deployment builds. A cache hit skips the loader entirely, so after you upgrade `@vgpu/wgsl` the cache, not the new loader, decides whether a shader is rebuilt. Old `version: 1` output served from a cache throws `VGPU-SHADER-SOURCE-UNPREPARED` in the renderer.

`wgslTurbopackRule()` handles this before Turbopack looks anything up. Each config evaluation hashes the installed compiler files — `package.json`, the shipped metadata anchor, and every published `dist` JavaScript file — into the rule's options. A changed or rebuilt compiler changes the rule, so Turbopack rebuilds every `.wgsl` module and keeps the rest of the cache; an unchanged installation produces the same rule, so warm builds keep reusing their cached output. Restart `next dev` after upgrading: the identity is computed when Next loads the config, and a running server keeps the compiler it already loaded.

The retained-cache matrix passes on Next 16.3.3. An authentic 0.5.0 build using unchanged `require.resolve("@vgpu/wgsl/loader-webpack")` rebuilt exact v2 because the public resolved target changed. The bare-string rule below stayed on v1, then switching that rule to the helper rebuilt exact v2 with the same cache retained. Stable Next 15.5 cannot enable Turbopack's persistent cache — Next 15.5.25 rejects `experimental.turbopackPersistentCaching: true` with `CanaryOnlyError` when it loads the config — while production builds, config types, and dev edit/delete/recreate recovery pass there.

<Callout type="warn">
  Warning: Upgrading from `@vgpu/wgsl` 0.5.0 with the bare-string rule `loaders: ["@vgpu/wgsl/loader-webpack"]` is not protected. Turbopack keys that rule by its unchanged string, so a cache restored from a 0.5.0 build can keep serving `version: 1` output. Replace the rule with `wgslTurbopackRule()` — the changed rule rebuilds every shader and you keep the cache — or, if you keep a hand-written rule, delete that app's `.next/cache` once after upgrading. Do not disable caching to work around it.
</Callout>

Webpack has a different boundary. Its default filesystem cache treats installed packages under managed `node_modules` as immutable while their package `name@version` is unchanged. The authentic 0.5.0 `require.resolve()` upgrade rebuilt exact v2 with its cache retained because the public resolved target changed, and a separate disposable bare-rule replay rebuilt after the candidate manifest version changed. A bare same-version replacement stayed on v1 even though the new loader registers its compiler files; `addBuildDependency()` does not override the managed-package snapshot. Same-version edits to a workspace symlink did rebuild and recover.

Do not clear webpack's cache for every upgrade. Keep normal package versions and rebuild first. Clear that cache once only when you replace a managed installed package in place without changing its version or resolved loader path, or when verification still shows stale v1 output.

Prebuilt shader assets are outside both mechanisms. JavaScript or JSON shader artifacts that a package or build step generated earlier are imported as ordinary modules, never run through the loader, so regenerate them with matching `@vgpu/wgsl` tooling instead.

To confirm a rebuild, log one imported shader's `version` and `producer`: they print `2` and `"@vgpu/wgsl/prepare-v2"`.

## Vite

```ts
// vite.config.ts — wrap in defineConfig() from "vite" if you want its typing
import { wgslVitePlugin } from "@vgpu/wgsl/loader-vite";

export default { plugins: [wgslVitePlugin()] };
```

## Type `.wgsl` imports in TypeScript

TypeScript does not know what a `.wgsl` module is, so `import shader from "./plasma.wgsl"` fails with `TS2307: Cannot find module` until you add an ambient declaration. `@vgpu/wgsl` ships one — reference it from a `.d.ts` file anywhere in your project (`src/wgsl-env.d.ts` is a good spot):

```text
// src/wgsl-env.d.ts
/// <reference types="@vgpu/wgsl/wgsl-types" />
```

Prefer that one-liner: it stays correct if the emitted shape ever changes. If you would rather declare the module yourself — for example to reuse the exported `ShaderSource` type — put this in `src/wgsl-env.d.ts` instead. It must be the first statement in the file: a `declare module` that follows other code is read as a module augmentation and fails with `TS2664`.

```ts
declare module "*.wgsl" {
  import type { ShaderSource } from "@vgpu/wgsl";
  const source: ShaderSource;
  export default source;
}
```

Either way the default export is a prepared `ShaderSource` object (`{ version: 2, wgsl, reflection, sourceChecksum, producer, functionExports }`), **not** a plain string. Pass it straight to `effect(gpu, source)` or `draw(gpu, { shader: source })` — do not reach into `.wgsl` yourself: a string throws `VGPU-SHADER-SOURCE-UNPREPARED`. Loader artifacts always include `functionExports`, even when the array is empty; integrations such as `vgpu/three` use that metadata to preserve authored function identity through identifier minification. The emitted module never imports the parser. When the bounded compact-emission estimate selects packing, it uses a small parser-free decoder; Vite and webpack can also share independently reachable encoded metadata modules, while Turbopack keeps the encoded table in the shader module and resolves the decoder relative to the loader's own installed package. Final bundler chunking and compression can change the result, so this estimates savings rather than guaranteeing a smaller compressed bundle. Compact and literal forms evaluate to the same full plain object. The decoder and generated metadata assets are private implementation details, not author APIs, and the setup above needs no extra rule or dependency.

<Callout type="warn">
  Warning: Keep the `@vgpu/wgsl` loader and the `vgpu` runtime on matching releases. An artifact from a different format version throws `VGPU-SHADER-SOURCE-VERSION`, and older `version: 1` output throws `VGPU-SHADER-SOURCE-UNPREPARED` — rebuild the app and regenerate prebuilt shader assets after upgrading either package.
</Callout>

## Render it from a client component

WebGPU is browser-only, so the canvas lives in a `"use client"` component and `init()` runs in an effect after mount. Keep the vgpu work in a plain function: it is easier to read, and it is the part worth testing.

```ts
// src/app/plasma.ts
import { clock, effect, frameLoop, init, surface } from "vgpu";
import type { FrameLoopHandle } from "vgpu";
import plasmaShader from "./plasma.wgsl";

/** Starts the render loop on `canvas`; call the returned function to tear it down. */
export function startPlasma(canvas: HTMLCanvasElement): () => void {
  let disposed = false;
  let loop: FrameLoopHandle | undefined;
  let gpu: Awaited<ReturnType<typeof init>> | undefined;

  void (async () => {
    gpu = await init();
    if (disposed) return gpu.dispose();

    const canvasSurface = surface(gpu, canvas, { dpr: [1, 2] });
    const plasma = effect(gpu, plasmaShader, {
      label: "plasma",
      set: { params: { time: 0, texel: canvasSurface.texelSize } },
    });
    canvasSurface.onResize(() => plasma.set({ params: { texel: canvasSurface.texelSize } }));

    const time = clock(gpu);
    loop = frameLoop(gpu, (frame) => {
      plasma.set({ params: { time: time.time } });
      frame.pass(canvasSurface, plasma);
    });
  })();

  return () => {
    disposed = true;
    loop?.stop();
    gpu?.dispose();
  };
}
```

```tsx
// src/app/page.tsx
"use client";

import { useEffect, useRef } from "react";
import { startPlasma } from "./plasma";

export default function Page() {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    return startPlasma(canvas);
  }, []);

  return (
    <main style={{ margin: 0, height: "100vh", overflow: "hidden" }}>
      <canvas ref={canvasRef} style={{ display: "block", width: "100%", height: "100%" }} />
    </main>
  );
}
```

The cleanup function matters in development: React's strict mode mounts effects twice, and without `stop()` plus `dispose()` you leak a device and a render loop per remount.

## Validate before you run the app

**`next build`/`next dev` reflect every `.wgsl` import but never validate it against a WebGPU
device — neither the webpack loader nor the Turbopack path.** The loader/plugin parse and reflect
each module to prepare it: import graphs go through `resolveShader({ validate: false })` (parsing,
purity checks, DCE, mangling, and minification run, but the device-backed check does not), and
leaf files without imports are reflected directly. Parse errors and reflection-detectable layout
errors — for example a `bool` in a uniform struct (`VGPU-WGSL-REFLECT-BOOL-HOST-SHAREABLE`) — fail
the build, including in leaf files that used to ship without reflection. Errors only the native
WGSL compiler or the device detects still pass: there is no
loader/plugin option to opt into device validation, so `next build --webpack` and `next build`
(Turbopack) exit `0` and ship that WGSL. Do not use `next dev`/`next build` as your shader compiler.

The validation gate is `vgpu check --require-validation`, run in CI or as a pre-commit hook. Check
every `.wgsl` file — including pure helper modules — with the CLI, which resolves the same import
graph the loader does, prints the reflection, and actually validates against a WebGPU device:

```bash
npx vgpu check src/app/plasma.wgsl --require-validation
```

Then prove the pixels in Node instead of squinting at a browser tab: [Getting started](/docs/guides/getting-started) shows the headless render-and-read-pixels loop, and [The default workflow for developing shaders with vgpu](/docs/guides/shader-workflow) is the full playbook.

## Troubleshooting

| Symptom                                                                                       | Cause                                                                                                                                         | Fix                                                                                                                                                                                                                                                                                                                                    |
| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TS2307: Cannot find module './x.wgsl'`                                                       | No ambient declaration for `.wgsl`                                                                                                            | Add the `wgsl-env.d.ts` above                                                                                                                                                                                                                                                                                                          |
| `VGPU-WGSL-PKG-NOTFOUND: Package <pkg> was not found`                                         | A WGSL package import is not installed in `node_modules`                                                                                      | `npm install <pkg>`, or fix the specifier                                                                                                                                                                                                                                                                                              |
| `VGPU-WGSL-RUNTIME-IMPORT`                                                                    | The bundler ran the loader synchronously while the WGSL file has top-level imports or a direct `export fn`                                    | Let the loader use async mode (webpack/Turbopack/Vite all do by default)                                                                                                                                                                                                                                                               |
| `VGPU-RESOLVE-MODULE-BINDING`                                                                 | An imported `.wgsl` module declares `@group`/`@binding`                                                                                       | Keep resources in the entry shader; modules export only structs and functions                                                                                                                                                                                                                                                          |
| `Cannot find module '@vgpu/wgsl/next'` (or `ERR_MODULE_NOT_FOUND`) when Next loads the config | `@vgpu/wgsl` is installed only transitively through `vgpu`                                                                                    | Add `@vgpu/wgsl` to the app's own `package.json` at the release your `vgpu` depends on                                                                                                                                                                                                                                                 |
| `VGPU-WGSL-NEXT-OPTIONS` or `VGPU-WGSL-MINIFY-IDENTIFIERS` when Next loads the config         | `wgslTurbopackRule()` received an unknown or mistyped option                                                                                  | Pass only `{ minify?: boolean \| { whitespace?: boolean; identifiers?: "none" \| "safe" } }`                                                                                                                                                                                                                                           |
| `VGPU-WGSL-CACHE-IDENTITY`                                                                    | The installed `@vgpu/wgsl` is missing, unbuilt, or inconsistent, so its compiler files cannot be listed                                       | Reinstall the matching `@vgpu/wgsl` release; in a workspace, build `@vgpu/wgsl` before running Next. The error's `metadata.path` names the file                                                                                                                                                                                        |
| `CanaryOnlyError` for `experimental.turbopackPersistentCaching`                               | Stable Next 15.5 does not support Turbopack persistent caching                                                                                | Remove the flag on Next 15.5, or use Next 16 for restored Turbopack caches                                                                                                                                                                                                                                                             |
| `VGPU-SHADER-SOURCE-UNPREPARED` right after upgrading `@vgpu/wgsl`, with a restored cache     | The cache still serves `version: 1` loader output from 0.5.0                                                                                  | For Turbopack, switch the bare rule to `wgslTurbopackRule()` or delete that app's `.next/cache` once. For webpack, clear only after confirming the upgrade kept the same managed package version and resolved loader path, or the rebuilt artifact is still v1 — see [Persistent caches and upgrades](#persistent-caches-and-upgrades) |
| `VGPU-SHADER-SOURCE-UNPREPARED`                                                               | Passing a raw string — often `source.wgsl` instead of the imported object — or a `version: 1` artifact from an older loader or prebuilt asset | Pass the imported object to `effect(gpu, source)`; rebuild with the current loader and regenerate prebuilt assets, or wrap runtime WGSL in `prepareShader()`                                                                                                                                                                           |
| `VGPU-SHADER-SOURCE-VERSION`                                                                  | The loader or a prebuilt asset comes from a `@vgpu/wgsl` release with a different artifact format than your `vgpu`                            | Align the two package versions and rebuild                                                                                                                                                                                                                                                                                             |
| `VGPU-WGSL-PACKED-METADATA-INVALID` during the build or when a shader module loads            | Loader-generated shader metadata is malformed or came from incompatible `@vgpu/wgsl` loader assets                                            | Rebuild the affected bundle with compatible `@vgpu/wgsl` loader assets, and never import or edit generated metadata requests yourself                                                                                                                                                                                                  |
| Build fails with a `VGPU-WGSL-*` reflection error in a leaf `.wgsl`                           | The loader now reflects every module at build time                                                                                            | Fix the WGSL the diagnostic reports, as you would for a runtime error                                                                                                                                                                                                                                                                  |
| Shader creates but nothing draws                                                              | No `frame.pass`, or the pass targets something that is never presented                                                                        | Render inside `frame`/`frameLoop` with the surface as the pass target                                                                                                                                                                                                                                                                  |

## See also

* [Use WGSL modules in three.js TSL](/docs/guides/threejs) — connect loader-resolved pure WGSL functions to Three TSL node materials with `vgpu/three`
* `npx vgpu docs cat /@vgpu/wgsl/next/index.docs.md` — `wgslTurbopackRule()` options, returned rule, and errors
* `npx vgpu docs cat /@vgpu/wgsl/loader-webpack/index.docs.md` — every loader option
* `npx vgpu docs cat /@vgpu/wgsl/loader-vite/index.docs.md` — the Vite plugin
* `npx vgpu docs cat /@vgpu/wgsl/runtime/resolve-shader.docs.md` — resolving import graphs without a bundler
* `npx vgpu docs cat /@vgpu/wgsl-std/noise/index.docs.md` — WGSL modules you can import by package name
* [Publishing WGSL module packages](/docs/guides/publishing-wgsl-packages) — ship your own `.wgsl` modules as a package, or share them across a monorepo
* [Shipping to production](/docs/guides/shipping-to-production) — the pre-PR checklist: correctness gates, measurements, free performance defaults, and cheaper alternatives to propose


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Using vgpu without a bundler
description: Resolve a `.wgsl` entry file's import graph with `resolveShader()` and render it from Node, a script, or a test — no webpack, Vite, or Turbopack loader required.
---

# Using vgpu without a bundler



`effect(gpu, source)` and `draw(gpu, { shader })` take a prepared `ShaderSource` — WGSL plus its reflection — which a bundler loader normally produces at build time. Without a bundler you produce it yourself. This guide is the no-bundler half of [Getting started](/docs/guides/getting-started): resolve a `.wgsl` entry file — and everything it imports — with `resolveShader()`, prepare the result with `prepareShader()`, then render it headless from Node.

Read [WGSL modules](/docs/concepts/wgsl-modules) first if you need the `import`/`export` syntax, pure-module rule, or an explanation of the flattened output. This guide focuses on resolving that graph without a bundler.

## When you need this

* Your shader lives in its own `.wgsl` file(s) rather than a template string, and you are not running webpack, Vite, or Turbopack.
* Your shader imports WGSL packages (`@vgpu/wgsl-std/noise`, your own workspace package) from a plain script, a Node test, or a CI job.
* You want to render and read pixels back without a browser, the way [Getting started](/docs/guides/getting-started) validates a shader with a static render.

If you *are* shipping this inside a bundler-based app, use the loader instead: [Using vgpu with Next.js and other bundlers](/docs/guides/nextjs). Reading the file with `readFileSync` and passing the text to `prepareShader()` also works — but only while the shader has no `import` of its own; `prepareShader()` throws `VGPU-WGSL-REFLECT-SOURCE-IMPORT` the moment it does, and you need the resolver below.

## Resolve a `.wgsl` entry file

`resolveShader()` reads an entry module from disk, follows its imports (relative, `@/`, and package imports like `@vgpu/wgsl-std/noise`), and emits one finished WGSL string.

Here is the entry file the rest of this page uses — a fullscreen effect with one `params` uniform. `effect()` injects the vertex stage and exposes the interpolated `uv`, so the file only declares a fragment entry point:

```wgsl
// shader.wgsl
struct Params { time: f32 }
@group(0) @binding(0) var<uniform> params: Params;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, abs(sin(params.time)), 1.0);
}
```

Resolve it:

```ts
import { fileURLToPath } from "node:url";
import { resolveShader } from "@vgpu/wgsl/runtime";

const resolved = await resolveShader({
  entry: fileURLToPath(new URL("./shader.wgsl", import.meta.url)),
});

// `resolved.wgsl` is one finished WGSL string — prepare it before effect() or draw({ shader }).
console.log(resolved.wgsl.length, resolved.deps.length);
```

The entry path is resolved on disk and may omit `.wgsl` when a matching file or `index.wgsl` exists. Pass `rootDir` when your modules use `@/foo.wgsl` aliases. Full parameters, the return shape, and every `VGPU-WGSL-*` error code live in the [`resolveShader` reference](/docs/reference/wgsl/resolve-shader#resolvedshader) (`npx vgpu docs cat /@vgpu/wgsl/runtime/resolve-shader.docs.md`).

Validate the same file from the command line before you render it — `vgpu check` runs the same resolver and prints the reflection:

```bash
npx vgpu check shader.wgsl
```

## Render it headless with `vgpu/node`

Combine the resolved shader with `vgpu/node`'s `init` / `target` / `effect` and read the pixels back. This is the static-render recipe from [Getting started](/docs/guides/getting-started), with the shader loaded from disk instead of inlined:

```ts
import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { PNG } from "pngjs";
import { resolveShader } from "@vgpu/wgsl/runtime";
import { prepareShader } from "@vgpu/wgsl/prepare";
import { effect, init, target } from "vgpu/node";

const entry = fileURLToPath(new URL("./shader.wgsl", import.meta.url));
const resolved = await resolveShader({ entry });
const prepared = prepareShader(resolved, entry); // reflect the final WGSL once, keep functionExports

const width = 160;
const height = 90;
const gpu = await init();
const colorTarget = target(gpu, { size: [width, height] });
const shader = effect(gpu, prepared, { set: { params: { time: 0 } } });
shader.draw(colorTarget);

const pixels = await colorTarget.color.read({ mipLevel: 0, region: "all" });   // RGBA bytes — assert on them
const png = new PNG({ width, height });
png.data.set(pixels);
writeFileSync("frame.png", PNG.sync.write(png));
gpu.dispose();                              // stops Dawn's polling so the process exits
```

Nothing about this changes when the shader grows: `resolveShader()` inlines the whole import graph, and `prepareShader()` reflects the one finished string it returns. Pass the `resolved` object rather than `resolved.wgsl` so direct `export fn` metadata carries over; `prepareShader()` reflects the final WGSL again and ignores `resolved.reflection`. Prepare once at startup, not per draw — every call reparses. The prepared artifact is deeply frozen, so the renderer validates it once and reuses the result; prepare a new artifact when the WGSL changes. Animating? Call `shader.set({ params: { time } })` and draw again in a loop, reading the target after each draw.

Rendering an actual 3D scene rather than a fullscreen effect? See [Two-pass rendering](/docs/guides/two-pass-rendering) for the offscreen-depth-target recipe — it composes with this same no-bundler setup.

## `@vgpu/wgsl/runtime` works from ESM and CommonJS

The `./runtime` subpath's `exports` map declares both an `import` and a `require` condition, both pointing at the same ESM file — Node resolves the `require` condition and loads it through its native `require(esm)` support. `resolveShader()` is reachable the same way from either module system, no rename or `"type": "module"` needed:

```ts
// CommonJS entry point — no "type": "module" required
const { resolveShader } = require("@vgpu/wgsl/runtime");
```

```ts
// ES module entry point
import { resolveShader } from "@vgpu/wgsl/runtime";
```

Pick whichever matches how the rest of the script/project is written; both resolve to the same file and behave identically.

## Troubleshooting

| Symptom                           | Cause                                                                              | Fix                                                                                           |
| --------------------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `VGPU-WGSL-RES-NOTFOUND`          | The entry path or an imported module does not exist                                | Fix the path; `entry` is resolved relative to the process, so build it from `import.meta.url` |
| `VGPU-WGSL-PKG-NOTFOUND`          | A WGSL package import is not installed                                             | `npm install <pkg>`, or fix the specifier                                                     |
| `VGPU-RESOLVE-MODULE-BINDING`     | An imported `.wgsl` module declares `@group`/`@binding`                            | Keep resources in the entry shader; modules export only structs and functions                 |
| `VGPU-SHADER-SOURCE-UNPREPARED`   | `resolved.wgsl` or a `readFileSync` string went straight to `effect()` or `draw()` | Wrap it: `prepareShader(resolved, entry)`                                                     |
| `VGPU-WGSL-REFLECT-SOURCE-IMPORT` | `prepareShader()` received WGSL that still has a top-level `import`                | Run `resolveShader()` first and prepare its result                                            |

## See also

* [`resolveShader` reference](/docs/reference/wgsl/resolve-shader#resolvedshader) — full signature, options, and every error code.
* [`prepareShader` reference](/docs/reference/wgsl/prepare#prepareshader) — the prepared artifact, its trust limits, and upgrading v1 assets.
* [Getting started](/docs/guides/getting-started) — the browser-first walkthrough and the static-render recipe this guide extends.
* [Two-pass rendering](/docs/guides/two-pass-rendering) — offscreen depth target plus composite, for 3D scenes rendered this same headless way.
* [Using vgpu with Next.js and other bundlers](/docs/guides/nextjs) — the bundler-loader alternative.
* [Publishing WGSL module packages](/docs/guides/publishing-wgsl-packages) — how package imports inside your `.wgsl` files resolve.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Optimize a pass
description: Optimize one pass by first deciding what changes every frame.
---

# Optimize a pass



## 0. Measure first

Attach a `timer(gpu)` span (requires `init({ requiredFeatures: ["timestamp-query"] })`) and judge every change by the reported GPU milliseconds:

```text
const timer = timer(gpu);
timer.onResults((spans) => console.log(`pass ${spans.pass}ms`));
frameLoop(gpu, (f) => f.pass({ target, timer: timer.span("pass") }, (p) => p.draw(effect)));
```

## 1. Static commands

If the draw list is static, record it once:

```text
const effectBundle = bundle(gpu, { target }, (b) => {
  b.draw(background);
  b.draw(grid);
});
frameLoop(gpu, (f) => f.pass(target, (p) => p.bundles(effectBundle)));
```

## 2. Animated scalar/vector values

Keep the pass object and write values in place:

```text
const effect = effect(gpu, exposureShader, { set: { time: 0, exposure: 1 } }); // a prepared .wgsl import
const time = clock(gpu);
frameLoop(gpu, (f) => {
  effect.set({ time: time.time });
  f.pass(target, effect);
});
```

## 3. Resources that swap

Use ping-pong rather than allocating a new target or storage buffer:

```text
const state = pingPong(gpu, 512, 512, { format: "rgba16float" });
frameLoop(gpu, (f) => {
  step.set({ src: state.read.color });
  f.pass(state.write, step);
  state.swap();
});
```

## 4. Many objects

Use instancing for many copies of the same draw, or use `UniformPool` plus `draw.group()` when every object needs a different uniform block.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Performance model
description: vgpu's public API is organized around stable identities.
---

# Performance model



## Binding ownership

The first `set()` for a binding decides ownership. Plain JS values are lib-owned and can be updated in place; resources are user-owned and their identity is bound directly. Switching ownership triggers `VGPU-R1-OWNERSHIP-FLIP`.

## Identity cache

Bind groups are cached by resource identity. Updating a JS value in place keeps the identity stable; replacing a texture/storage/sampler changes identity and may stale bundles.

## Bundle staleness

Bundles freeze encoded commands and bind groups. Buffer contents may change, and replay targets may resize as long as their render signature matches. Re-record when a sampled resource identity changes; replay reports `VGPU-R3-BUNDLE-STALE`.

## Claimed groups

`draw.group(group, bindGroup)` claims an entire reflected group. vgpu validates the group layout and forbids `set()` into that group. Dynamic offsets are passed at draw time:

```text
p.draw(draw, { offsets: { 1: [offset] } });
```

## Cost model defaults

* Pre-warm pipelines with `await draw.compile(target)`.
* Share globals with `uniforms(gpu)`.
* Use `instances` for repeated geometry.
* Use ping-pong for iterative read/write resources.
* Put depth/MSAA/format on targets, not global state.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Performance patterns
description: This is the quick index. Open `performance-playbook` for copy-paste before/after snippets.
---

# Performance patterns



## Static scene

Use `bundle(gpu, { target }, recorder)` and replay with `p.bundles(bundle)`.

## First-frame stability

Use `await draw.compile(surfaceOrTarget)` so pipeline compilation happens before the transition frame; pass a canvas `surface` or an offscreen `target` explicitly.

## Animated uniforms

Create the pass/draw once and call `.set({ changedValue })`. Do not allocate a new pass or uniform buffer every frame.

## Many objects

Use `instances` when geometry and material are shared. Use `UniformPool` + `draw.group()` + dynamic offsets when each object needs a different uniform block. Skip draws hidden behind occluders with `visibility(gpu)` proxy queries. When a compute pass decides the counts, draw with `indirect` arguments instead of reading them back to the CPU.

## Shared globals

Use one `uniforms(gpu, { time, mouse, camera })` object and bind it into every shader that needs the same struct.

## Iterative effects

Use `pingPong(gpu)` for targets or `pingPongStorage(gpu)` for compute. Do not allocate temporary targets/storage in the loop.

## 3D targets

Create targets with `depth: true` and `msaa: true` when needed; pre-warm those signatures with `await draw.compile(target)`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Performance playbook: write fast vgpu by default
description: This guide is for LLMs and humans writing shaders. Treat these as default shapes, not late-stage optimizations: each **After** snippet is the pattern to copy when the situation matches.
---

# Performance playbook: write fast vgpu by default



## 1. Bundles / replay (`bundle()` + `p.bundles`)

Use when static draws repeat every frame. Bundles freeze commands, bind groups, target formats, sample count, and attachment identity; they do **not** freeze buffer contents.

Before:

```text
frameLoop(gpu, (f) => f.pass({ target: scene }, (p) => {
  p.draw(floor);
  p.draw(walls);
  p.draw(player);
}));
```

After:

```text
const staticScene = bundle(gpu, { target: scene }, (b) => {
  b.draw(floor);
  b.draw(walls);
});
frameLoop(gpu, (f) => f.pass({ target: scene }, (p) => {
  p.bundles(staticScene);
  p.draw(player);
}));
```

Default: bundle static work once and replay with `p.bundles(...)`.

## 2. Pipeline pre-warm (`compile`)

Use before the first visible frame or route transition. This compiles render pipelines for the target color/depth/MSAA signature before the hitch-sensitive frame.

Before:

```text
const cube = draw(gpu, { shader: litShader, geometry: geometry(gpu, box()) });
```

After:

```text
const scene = target(gpu, { size: [256, 256], format: "rgba16float", depth: true, msaa: true });
const cube = draw(gpu, { shader: litShader, geometry: geometry(gpu, box()) });
await cube.compile(scene);
frame(gpu, (f) => f.pass({ target: scene }, (p) => p.draw(cube)));
```

Default: `await draw.compile(target)` for every target signature a draw will hit before the hitch-sensitive frame. `targets: [target]` remains synchronous creation-time sugar when blocking is acceptable.

## 3. Manual group claim + dynamic offsets (`draw.group`)

Use for hundreds or thousands of objects that share one shader and one bind-group layout. `draw.group()` claims a reflected group; offsets travel per draw call.

Before:

```text
for (const obj of objects) {
  cube.set({ model: obj.model });
  p.draw(cube);
}
```

After:

```text
import { UniformPool, type UniformLayout } from "vgpu/core";

type ObjectUniforms = { model: Float32Array };
const objectLayout: UniformLayout<ObjectUniforms> = {
  size: 64,
  bindGroupLayout: cube.layout(1, { dynamicOffsets: true }),
  encode(value, dst, byteOffset) {
    new Float32Array(dst, byteOffset, 16).set(value.model);
  },
};
const pool = new UniformPool(gpu.device, { capacityBytes: 1 << 20 });
const slot = pool.alloc(objectLayout);
cube.group(1, slot.bindGroup);

frameLoop(gpu, (f) => {
  pool.beginFrame(clock(gpu).frameCount);
  f.pass({ target: scene }, (p) => {
    for (const obj of objects) {
      const offset = slot.push({ model: obj.model });
      p.draw(cube, { offsets: { 1: [offset] } });
    }
  });
  pool.endFrame();
});
```

Default: for many per-object uniforms, allocate a `UniformPool` slot with an `encode(...)` function, call `pool.beginFrame(...)`, push values, draw with offsets, then `pool.endFrame()` before the frame submits.

## 4. `set()` in-place

Use for animated JS values. The first `set()` latches ownership: plain JS values are lib-owned and update in place; resources are user-owned and keep their identity.

Before:

```text
const wave = effect(gpu, waveShader, { set: { time: 0, speed: 2 } });
frameLoop(gpu, (frame) => {
  wave.set({ time: clock(gpu).time, speed: 2 });
  frame.pass(target, wave);
});
```

After:

```text
const wave = effect(gpu, waveShader, { set: { time: 0, speed: 2 } });
frameLoop(gpu, (frame) => {
  wave.set({ time: clock(gpu).time });
  frame.pass(target, wave);
});
```

Default: create once; update changing numbers/vectors/structs with `set()`. `set()` validates and packs on every call, and frame captures are still uploaded each frame, so hoist static and resize-class values out of the render loop. For managed uniforms, a `set()` whose packed bytes equal the previous ones does not start a new revision, so later draws in the same frame reuse the snapshot already captured; you never need to compare values or pack buffers yourself. Storage bindings and live uniforms still write on every `set()`.

## 5. Bake static inputs once

Use when a heavy pass produces a texture that does not change every frame.

Before:

```text
frameLoop(gpu, (f) => {
  f.pass({ target: baked }, (p) => p.draw(heavyScene));
  post.set({ src: baked.color, texel: baked.texelSize });
  f.pass({ target: screen }, (p) => p.draw(post));
});
```

After:

```text
frame(gpu, (f) => f.pass({ target: baked }, (p) => p.draw(heavyScene)));
post.set({ src: baked.color, texel: baked.texelSize });
frameLoop(gpu, (f) => f.pass({ target: screen }, (p) => p.draw(post)));
```

Default: if an input is static, bake it outside the loop with one `frame(gpu, ...)`.

## 6. Instancing (`instances`, `vertices`)

Use for N copies of the same geometry. `DrawOptions.instances/vertices/firstInstance` set defaults; `DrawCallOptions.instances/vertices/firstVertex/firstInstance` override per call. `instances: 0` is valid; indexed geometries ignore `vertices` and `firstVertex`.

Before:

```text
for (let i = 0; i < COUNT; i++) {
  particles.set({ particleIndex: i });
  p.draw(particles);
}
```

After:

```text
const particles = draw(gpu, { shader: particleShader, instances: COUNT, vertices: 6 });
await particles.compile(scene);
particles.set({ particleBuffer });
frameLoop(gpu, (f) => f.pass({ target: scene }, (p) => p.draw(particles)));
```

Default: one draw with `instances` beats N draw calls.

## 7. `uniforms(gpu)` shared values

Use when many shaders consume the same time, camera, mouse, or exposure values.

Before:

```text
const time = clock(gpu);
wave.set({ time: time.time, mouse });
blur.set({ time: time.time, mouse });
post.set({ time: time.time, mouse });
```

After:

```text
const globals = uniforms(gpu, { time: 0, mouse: [0, 0] });
const wave = effect(gpu, waveShader, { set: { globals } });
const blur = effect(gpu, blurShader, { set: { globals } });
frameLoop(gpu, (frame) => {
  globals.set({ time: clock(gpu).time, mouse });
  frame.pass(target, (pass) => {
    pass.draw(wave);
    pass.draw(blur);
  });
});
```

Default: shared values belong in one `uniforms(gpu)` object.

## 8. Ping-pong (`pingPong`) without churn + two bundles

Use for iterative effects. Ping-pong keeps two stable identities, so bind-group caches can reuse them.

Before:

```text
frameLoop(gpu, (f) => {
  const tmp = target(gpu, { size: [256, 256], format: "rgba16float" });
  sim.set({ src: previous.color });
  f.pass({ target: tmp }, (p) => p.draw(sim));
  previous = tmp;
});
```

After:

```text
const state = pingPong(gpu, 512, 512, { format: "rgba16float" });
const even = bundle(gpu, { target: state.write }, (b) => { sim.set({ src: state.read.color }); b.draw(sim); });
state.swap();
const odd = bundle(gpu, { target: state.write }, (b) => { sim.set({ src: state.read.color }); b.draw(sim); });
state.swap();
let parity = 0;
frameLoop(gpu, (f) => {
  f.pass({ target: state.write }, (p) => p.bundles(parity === 0 ? even : odd));
  state.swap();
  parity ^= 1;
});
```

Default: create ping-pong resources once; if you bundle, record both parity cases and replay the matching one.

## 9. MSAA/depth in the target

Use for 3D anti-aliasing and depth testing. Resolution, depth, color format, and sample count are target state.

Before:

```text
const scene = target(gpu, { size: [256, 256], format: "rgba8unorm" });
const cube = draw(gpu, { shader: litShader, geometry: geometry(gpu, box()) });
```

After:

```text
const scene = target(gpu, { size: [256, 256], format: "rgba16float", depth: true, msaa: true });
const cube = draw(gpu, { shader: litShader, geometry: geometry(gpu, box()) });
await cube.compile(scene);
frameLoop(gpu, (f) => f.pass({ target: scene, clear: [0, 0, 0, 1] }, (p) => p.draw(cube)));
```

Default: put depth/MSAA on the target; do not invent global render settings.

## 10. Back-face culling (`cull: "back"`)

Use for closed geometries. With the default `cull: "none"`, triangles facing away from the camera still rasterize; culling them drops roughly half of a closed geometry's fragment work.

Before:

```text
const cube = draw(gpu, { shader: litShader, geometry: geometry(gpu, box()) });
```

After:

```text
const cube = draw(gpu, { shader: litShader, geometry: geometry(gpu, box()), cull: "back" });
```

Default: `cull: "back"` for closed geometries. Keep `"none"` for planes, alpha-tested foliage, and anything seen from both sides.

## 11. Occlusion culling (`visibility()`)

Use for many-object scenes with large occluders. Query a cheap proxy — a bounding box — and skip the expensive draw when the GPU confirmed it was hidden.

Before:

```text
f.pass({ target: scene }, (p) => {
  p.draw(world);
  p.draw(statue); // full cost even when a wall hides it
});
```

After:

```text
const vis = visibility(gpu);
const qStatue = vis.query("statue");
frameLoop(gpu, (f) => {
  f.pass({ target: scene, visibility: vis }, (p) => {
    p.draw(world); // occluders first
    p.occlusion(qStatue, statueProxy); // cheap bounding-box proxy
    if (!qStatue.hidden) p.draw(statue);
  });
});
```

Default: draw occluders first, query proxies, condition real draws on `hidden`. Results lag one or two frames and `hidden` stays `false` until a query confirms zero passing samples, so the fallback is always to draw. The pass target needs `depth: true`.

## 12. Indirect draws and dispatches (`indirect`)

Use when the GPU decides the counts — compute-driven particles, culled instance lists. Reading counts back to the CPU stalls on a round-trip; `indirect` keeps them on the GPU.

Before:

```text
const data = await counts.read(); // GPU-to-CPU round-trip, a frame late
p.draw(particles, { instances: decodeCount(data) });
```

After:

```text
const args = storage(gpu, 16, { indirect: true });
emit.dispatch(Math.ceil(COUNT / 64)); // compute writes the draw arguments into `args`
frameLoop(gpu, (f) => f.pass({ target: scene }, (p) => p.draw(particles, { indirect: args })));
```

Default: counts produced on the GPU stay on the GPU. The same option shape drives compute: `sim.dispatch({ indirect: args })`.

## 13. Time passes before optimizing (`timer()`)

Use before reaching for any pattern above. CPU timers see encoding only — encoders record commands, the GPU runs them later — so a "slow pass" verdict needs GPU timestamps.

Before:

```text
const t0 = performance.now();
frame(gpu, (f) => f.pass({ target: scene }, (p) => p.draw(world)));
const ms = performance.now() - t0; // encode + submit time, not GPU cost
```

After:

```text
const gpu = await init({ requiredFeatures: ["timestamp-query"] });
const timer = timer(gpu);
timer.onResults((spans) => console.log(`main ${spans.main}ms`));
frameLoop(gpu, (f) => f.pass({ target: scene, timer: timer.span("main") }, (p) => p.draw(world)));
```

Default: attach `timer.span(name)` to each pass you plan to touch and optimize the worst milliseconds first. Open `measuring` for what else to measure.

## Runtime quality tiers

When the fastest High pipeline still cannot hold its target on every device, add a Low pipeline and switch to it on GPU tier, battery, or presented-FPS health. The technique and its copy-pasteable code are in [Adaptive quality](/docs/guides/adaptive-quality) and the [adaptive quality example](/examples/adaptive-quality).


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Publishing WGSL module packages
description: Ship reusable WGSL modules as an npm package — exports map pointing at .wgsl files, files array, how consumers install and import it, the monorepo workspace:* case, and how to verify resolution with npx vgpu check.
---

# Publishing WGSL module packages



A WGSL module package is an ordinary npm package whose `exports` map points at `.wgsl` files instead of JavaScript. Consumers install it and import from it inside their shaders:

```wgsl
import { customNoise } from '@acme/shaders/noise';

@fragment fn main(@builtin(position) position: vec4f) -> @location(0) vec4f {
  return vec4f(customNoise(position.xy), 0.0, 0.0, 1.0);
}
```

`@vgpu/wgsl-std` is exactly this kind of package — there is nothing private about the mechanism. Publish a package this way when you want to reuse shader code across apps or share it with other teams; use the local-file workflow from [WGSL modules](/docs/concepts/wgsl-modules) when the code lives in the same project.

## The package

Nothing is compiled and nothing is bundled: you publish the `.wgsl` sources.

```json
{
  "name": "@acme/shaders",
  "version": "1.0.0",
  "type": "module",
  "exports": {
    "./noise": "./src/noise/index.wgsl",
    "./color": "./src/color/index.wgsl"
  },
  "files": ["src/**/*.wgsl", "README.md", "LICENSE"]
}
```

| Field     | Why it matters                                                                                                                                                                                                                      |
| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `exports` | The only thing the resolver reads. Each subpath maps to one `.wgsl` file: `"./noise": "./src/noise/index.wgsl"` makes `@acme/shaders/noise` resolve to that file. A subpath that is not listed fails with `VGPU-WGSL-PKG-NOTFOUND`. |
| `files`   | Must include the `.wgsl` sources, or `npm pack` publishes a package with no shaders in it. Verify with `npm pack --dry-run`.                                                                                                        |
| `type`    | Irrelevant to WGSL resolution — set it to match the package's JavaScript, if it has any.                                                                                                                                            |

Supported `exports` shapes:

```json
{
  "exports": {
    ".": "./src/index.wgsl",
    "./noise": "./src/noise/index.wgsl",
    "./shaders/*": "./src/*.wgsl"
  }
}
```

* **String targets** — the normal case.
* **Wildcards** (`"./shaders/*": "./src/*.wgsl"`) — one entry exposes a whole directory.
* **Directory targets** — a target that is a directory resolves to `index.wgsl` inside it, and a target with no extension is tried as `<target>.wgsl` and then `<target>/index.wgsl`.
* **Conditional targets** (`{ "import": ..., "default": ... }`) — the `default` branch is selected and a `VGPU-WGSL-PKG-CONDITIONAL` warning is reported. WGSL has no `import`/`require` distinction, so prefer a plain string target.

Inside the package, modules import each other with relative paths (`import { hash } from './hash.wgsl';`) or with bare specifiers for the package's own dependencies. A dependency you import from WGSL is a real `dependencies` entry:

```json
{
  "name": "@acme/fbm",
  "dependencies": { "@acme/shaders": "^1.0.0" }
}
```

Every module in the package must be pure WGSL: exported functions, structs, constants and type aliases. Bindings (`@group`/`@binding`) in an imported module fail with `VGPU-RESOLVE-MODULE-BINDING` — only the entry shader may declare them, so a package cannot dictate a consumer's bind group layout.

## Consuming it

Install it like any other dependency — no loader configuration is specific to WGSL packages beyond the [normal bundler setup](/docs/guides/nextjs):

```bash
npm install @acme/shaders
```

Then import it from a shader with the bare specifier, as in the example at the top of this page. The specifier is resolved against the *importing file's* project, so the same shader works whether it lives in your app or inside another package.

**Declare what you import.** A package you import from WGSL must be in your own `dependencies`; relying on a transitive copy that npm happened to hoist breaks under pnpm and Yarn PnP, where transitives are not visible to your project.

### Monorepos: workspace packages

A workspace package needs no publishing step. Give the shader package the same `exports` map as above and depend on it from the app with the workspace protocol:

```json
{
  "name": "web",
  "dependencies": { "@packages/shaders": "workspace:*" }
}
```

```wgsl
import { customNoise } from '@packages/shaders';
```

The package manager links `packages/shaders` into `apps/web/node_modules/@packages/shaders`, and resolution follows that symlink — including a second hop when the shader package imports another workspace package. Turborepo, pnpm workspaces, npm workspaces and Yarn workspaces all produce a layout that works.

Editing the shared `.wgsl` file invalidates the consumer's build the same way a local file does: resolved dependencies are reported to the bundler, so HMR and rebuilds see the change with no extra configuration.

## Verify resolution

Run `check` on the *entry* shader — the one with the `@fragment`/`@compute` entry point. It resolves the whole import graph, validates the result, and prints the reflection:

```bash
npx vgpu check ./shaders/main.wgsl
```

A resolution failure exits non-zero and names the package:

| Error                                                                         | Cause                                                                         | Fix                                                                               |
| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `VGPU-WGSL-PKG-NOTFOUND: Package @acme/shaders was not found`                 | The package is not installed in the importing project.                        | `npm install @acme/shaders`, and check the specifier's spelling.                  |
| `VGPU-WGSL-PKG-NOTFOUND: Package export ./fbm was not found in @acme/shaders` | The package is installed but its `exports` map has no such subpath.           | Add the subpath to the package's `exports`, or import an existing one.            |
| `VGPU-WGSL-RES-NOTFOUND: WGSL module … was not found`                         | The `exports` target points at a file the published tarball does not contain. | Add the `.wgsl` glob to `files` and republish; confirm with `npm pack --dry-run`. |
| `VGPU-WGSL-SYM-NOEXPORT`                                                      | The module resolved, but it does not `export` that name.                      | Export it from the package, or fix the imported name.                             |

## How resolution works

Bare specifiers in WGSL are resolved by vgpu, not by the bundler, in this order:

1. **The importing project's `node_modules`**, walking up from the importing file and stopping at its workspace root (a directory with `pnpm-workspace.yaml` or `.git`). A copy in your project therefore always wins over a copy someone else's package brought in, which is what lets you pin or patch a WGSL package.
2. **The same walk from the importing file's real path**, bounded by the workspace root found in step 1 — not by markers along the real path. Under pnpm a package is a symlink into `node_modules/.pnpm`, and its own dependencies sit next to that store entry rather than next to the symlink; resolving the link first is what makes a WGSL package that imports another WGSL package work. Because the boundary comes from step 1, this pass can reach another *spelling* of the same project (the store lives inside it) but never another project: when the real path lands outside the workspace root, the pass is skipped entirely.
3. **Node's resolver, from the importing file, under Yarn PnP only.** PnP keeps packages inside zip archives with no `node_modules` directories to walk, so Yarn's own resolver is asked instead. This requires the PnP runtime to be active in the process doing the resolution, which is the case for `yarn` commands, `yarn node`, and bundlers launched through them; a plain `node script.mjs` in a PnP project has no PnP runtime and reports `VGPU-WGSL-PKG-NOTFOUND`.
4. **`@vgpu/*` packages next to `@vgpu/wgsl` itself**, so `@vgpu/wgsl-std` resolves without a second install even though it reaches your project transitively through `vgpu`. This step is limited to the `@vgpu/` scope: it exists to rescue vgpu's own modules, and must never resolve a third-party specifier that your project did not install.

**`npm link` is not supported for a linked package's own WGSL imports.** A linked package is a symlink to a checkout outside your project, and resolution deliberately stops at your workspace root rather than searching that external tree — otherwise a shader could pick up packages belonging to an unrelated project on the same machine. The linked package itself resolves, and so do its imports if you install them in the linking project; a dependency that exists only next to the external checkout fails with `VGPU-WGSL-PKG-NOTFOUND`. Use a workspace package (above) for local development of a shader package.

Two things do *not* participate in this: `packageMap` and the in-memory `modules` option of `resolveShader()`. When you pass `modules`, there is no filesystem to search, so a bare specifier fails with `VGPU-WGSL-PKG-NOTFOUND` and the fix-it "Map it with packageMap or add the module to modules". Map the package prefix explicitly in that mode.

## Notes

* Keep exported names unlikely to collide: identifiers are namespaced per module during emission, but two packages exporting the same *entry-point* name still conflict in the final shader.
* Ship a `README.md` documenting each subpath and its exported signatures — consumers cannot infer them from types, because there are none.
* Do not publish `.ts` or `.js` wrappers that read the `.wgsl` files at runtime. The point of the `exports` map is that vgpu's resolver, the bundler loaders, and `npx vgpu check` all see the same file.
* **See also:** [Using vgpu with Next.js and other bundlers](/docs/guides/nextjs) for loader and TypeScript setup, [The default workflow for developing shaders](/docs/guides/shader-workflow) for the check/render loop, and [Shader fix-its](/docs/guides/shader-fix-its) for the full error-code list.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Scene composition
description: vgpu/scene composes transforms, hierarchies, instance collections, and cameras on the CPU; vgpu/scene/gpu publishes an instance collection as a vertex stream that your own WGSL reads through @vgpu/wgsl-std/scene helpers.
---

# Scene composition



`vgpu/scene` gives you the CPU half of a 3D scene: transform math, parent/child hierarchies, compact instance collections, and camera state you own. `vgpu/scene/gpu` adds one GPU piece — a bridge that publishes an instance collection as an instanced vertex stream. Everything else stays yours: the WGSL, the lighting, the passes, the render loop, the input handling, and — if you have one — your ECS or physics engine.

Use it when you render meshes with your own shaders and need world matrices, many copies of a mesh, or a camera, without adopting a renderer or a material system. A minimal instanced object looks like this:

```ts
import { draw, frame, geometry, init, target } from "vgpu";
import { box, instances, orbitRig, perspective, rigPose, viewMatrices } from "vgpu/scene";
import { instanceGeometry } from "vgpu/scene/gpu";
import boxShader from "./boxes.wgsl"; // declares `camera` at @group(1) @binding(0)

const gpu = await init();
const sceneTarget = target(gpu, { size: [960, 540], depth: true });

const crates = instances({ capacity: 1, attributes: { size: "float32x3", tint: "float32x4" } });
crates.add({ size: [1, 1, 1], tint: [0.9, 0.5, 0.1, 1] }); // world starts as identity

const crateBridge = instanceGeometry(gpu, crates, { mesh: geometry(gpu, box()) });
const crateDraw = draw(gpu, { shader: boxShader, geometry: crateBridge.geometry, cull: "back" });

const projection = new Float32Array(16);
const pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const matrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
perspective({ fov: 45, near: 0.1, far: 100 }, 960 / 540, projection);
viewMatrices(rigPose(orbitRig({ yaw: 0.6, pitch: 0.4, distance: 4 }), pose), projection, matrices);

crateDraw.set({
  camera: { viewProjection: matrices.viewProjection }, // WGSL binding `camera`, member `viewProjection`
  lighting: { direction: [-0.4, -1, -0.3], ambient: 0.15 },
});
const crateCount = crateBridge.publish(); // CPU records -> instance buffer

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: sceneTarget, clear: [0.05, 0.05, 0.07, 1] }, (pass) => {
    pass.draw(crateDraw, { instances: crateCount });
  });
});
```

Every connection is visible in the code: the collection feeds the bridge, the bridge geometry feeds the draw, the camera matrix reaches the shader through a named `set()`, and the instance count reaches the pass through `instances`. Nothing is injected into your shader, and no bind group is reserved.

## Architecture

### Scope and external math

Scene utilities own hierarchy composition, instance records, camera behavior, mesh recipes, and
their rendering integration. Use a dedicated CPU math library such as `math` for general vector
and quaternion operations, decomposition, interpolation, spatial queries, springs, and noise.
The existing scene transform conveniences remain supported; they are not a growing general math
API. Shader-side WGSL utilities remain separate from this CPU boundary.

External matrices enter through `setWorld`, bound world sources, or packed `setWorlds` batches.
There is no required math-library class or runtime dependency. See
[Using math with scene data](/docs/guides/scene-math) for checked examples, typed-array boundaries,
camera conventions, and copy/publication timing.

### Data flow

The common flow is **local transforms → world matrices → instance records → GPU instance stream → your draw**. Each stage is a separate function call you make, in an order you choose. A system that already has final world matrices — a physics engine, for example — enters directly at the instance records and skips the earlier stages.

```text
local transforms          world matrices             instance records          GPU
────────────────          ──────────────             ────────────────          ───
group().set(...)    ──►   node.worldMatrix     ─┐
                          (lazy, per node)      ├─►  instances(...)      ──►   instanceGeometry(...)
composeMatrix(...)  ──►   evaluateHierarchy()  ─┤    setWorld / setWorlds      .publish()
(your arrays)             (your arrays)         │    bindWorld + syncWorlds     └─► pass.draw(yourDraw, { instances })
physics / ECS  ─────────────────────────────────┘

camera:  orbitRig ─► orbit / pan / dolly ─► smoothRig ─► rigPose ─► Pose ─┐
         Lens ─► zoom ─► perspective / orthographic ─► projection ───────┴─► viewMatrices ─► yourDraw.set({ camera })
```

| Import                 | Contains                                                                                                                                                                                  | Needs a GPU                                  |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| `vgpu/scene`           | Geometry recipes (`box`, `sphere`, …), `geometries`, `degToRad`, `srgb`; transform math; `group` and `SceneNode`; `hierarchyOrder` and `evaluateHierarchy`; `instances`; camera functions | No — plain CPU data and functions            |
| `vgpu/scene/gpu`       | `instanceGeometry`                                                                                                                                                                        | Yes — takes the `gpu` from `init()`          |
| `@vgpu/wgsl-std/scene` | `instanceWorldMatrix`, `transformPosition`, `transformDirection`, `transformNormal`                                                                                                       | Shader-side, pure functions with no bindings |

Each transform has exactly one authority at a time. A node owns its local transform; a bound instance reads its world matrix from a source you provide; an unbound instance holds whatever you last wrote. Copies between stages are explicit calls, so you can always tell which value a stage is reading.

What you own and what vgpu owns:

| You own                                                                                    | vgpu owns                                                                                    |
| ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- |
| Shaders, shading, lighting, materials, blending                                            | The instance vertex buffer created by `instanceGeometry` and its composed `Geometry` wrapper |
| The base mesh passed to `instanceGeometry` (it is borrowed, never destroyed by the bridge) | Validation of every value that crosses into a collection, a camera function, or the bridge   |
| Camera state (`OrbitRig`, `Lens`, `Pose`) and all input handling                           | Nothing about your render loop — there is no scheduler and no implicit update                |
| Local/world arrays for external hierarchies, and their dirty flags                         | The compiled topology token from `hierarchyOrder` (a copy of your parents)                   |
| Stable application IDs for picking, and when to publish                                    | Instance handles (`InstanceId`) and slot packing                                             |

## Conventions

These rules hold for every function in `vgpu/scene` and every helper in `@vgpu/wgsl-std/scene`:

* **Matrices.** `Mat4` is a `Float32Array` with exactly 16 elements, column-major, the same layout as WGSL `mat4x4f`. Translation lives at indices `12, 13, 14`. An affine matrix has the mathematical bottom row `0, 0, 0, 1` at indices `3, 7, 11, 15`.
* **Composition order.** `world = parentWorld * local`. A point is transformed as `world * vec4(position, 1)`.
* **Axes.** Right-handed, +Y up. A camera looks down its local −Z axis.
* **Rotation.** `rotation` is intrinsic XYZ Euler angles in radians. `quaternion` is `[x, y, z, w]`. When both are supplied, `quaternion` wins.
* **Transform defaults.** Position `[0, 0, 0]`, quaternion identity `[0, 0, 0, 1]`, scale `1`. `scale` accepts a number (uniform) or a 3-vector.
* **Inputs and outputs.** Read-only numeric inputs accept any `ArrayLike<number>` (arrays, typed arrays). Functions that produce a matrix or vector write into an `out` you allocate — `Float32Array(16)` for matrices, `Float32Array(3)` or `Float32Array(4)` for vectors. `composeMatrix`, `multiplyMatrices`, `invertAffine`, `localFromWorld`, `rigPose`, `perspective`, and `orthographic` return the `out` they wrote; `viewMatrices` fills both fields of its `out` and returns `void`. Allocate outputs once and reuse them every frame.
* **Aliasing.** Math and camera outputs may overlap their inputs: results are computed in staging before anything is written, so `multiplyMatrices(a, b, a)` is safe. Two outputs of one call cannot share storage — `view`/`viewProjection` in `viewMatrices`, `position`/`quaternion` in `rigPose` — and `smoothRig` rejects any overlap between `current` and `goal`. Hierarchy evaluation is stricter; see [below](#evaluate-a-hierarchy-stored-in-your-own-arrays).
* **Projection depth.** `perspective` and `orthographic` map view-space −Z to WebGPU clip depth `0..1`.
* **Validation happens before writes.** A function that throws has not modified its `out`, its rig, its lens, or its collection — except where a section below says otherwise (bound sources in `syncWorlds`).

Matrices and owned vectors are stored as float32; JavaScript scalar calculations use ordinary numbers. There is no large-coordinate precision support — at 100 000 units from the origin, adjacent float32 values are about `0.008` units apart, so keep the scene near the origin or rebase it yourself. Inversion rejects matrices whose determinant is zero or non-finite, and any result that is not finite in float32; there is no arbitrary epsilon, so small but invertible scales such as `1e-6` are accepted.

## Transform math

```ts illustrative
type Mat4 = Float32Array; // exactly 16 elements

interface TransformValues {
  position?: ArrayLike<number>;   // 3 values, default [0, 0, 0]
  rotation?: ArrayLike<number>;   // 3 values, intrinsic XYZ radians
  quaternion?: ArrayLike<number>; // 4 values [x, y, z, w]; wins over rotation
  scale?: number | ArrayLike<number>; // number or 3 values, default 1
}

function composeMatrix(values: TransformValues, out: Mat4): Mat4;
function multiplyMatrices(a: ArrayLike<number>, b: ArrayLike<number>, out: Mat4): Mat4; // out = a * b
function invertAffine(matrix: ArrayLike<number>, out: Mat4): Mat4;
function localFromWorld(parentWorld: ArrayLike<number>, world: ArrayLike<number>, out: Mat4): Mat4; // inverse(parentWorld) * world
```

`composeMatrix` is a complete composition, not a patch: every omitted field takes its default. It normalizes a nonzero quaternion for the calculation without mutating your array, and rejects a zero-length quaternion.

```ts
import { composeMatrix, localFromWorld, multiplyMatrices } from "vgpu/scene";

const baseLocal = composeMatrix({ position: [0, 0.25, 0], rotation: [0, 0.3, 0] }, new Float32Array(16));
const armLocal = composeMatrix({ position: [0, 0.5, 0], rotation: [0, 0, 0.6] }, new Float32Array(16));

const armWorld = multiplyMatrices(baseLocal, armLocal, new Float32Array(16)); // world = parentWorld * local
const armBack = localFromWorld(baseLocal, armWorld, new Float32Array(16));  // recovers armLocal
```

Math outputs may alias their inputs — `multiplyMatrices(a, b, a)` is safe because the result is computed before anything is written. `invertAffine` and `localFromWorld` throw `VGPU-SPATIAL-SINGULAR` for a singular or non-finite inverse before touching `out`, instead of producing a matrix of zeros or `NaN`.

A matrix can represent shear, which a position/rotation/scale triple cannot. There is no decomposition function: when an external system is matrix-authoritative, keep its matrices as matrices and feed them to `setWorld`/`setWorlds` directly.

## Articulate a few objects with nodes

`group()` creates a `SceneNode`: a transform with a parent and children, and nothing else — no geometry, no material. Use nodes when you have a handful of articulated parts and want world matrices computed for you.

```ts illustrative
function group(options?: NodeOptions): SceneNode;

interface NodeOptions {
  position?: ArrayLike<number>;
  rotation?: ArrayLike<number>;
  quaternion?: ArrayLike<number>;
  scale?: number | ArrayLike<number>;
  label?: string;
  visible?: boolean;
  children?: readonly SceneNode[];
}

declare class SceneNode {
  constructor(kind: "group", options?: NodeOptions);
  readonly kind: "group";
  label: string | undefined;
  visible: boolean;
  set(values: NodeTransformValues): this; // position/rotation/quaternion/scale/label/visible
  lookAt(target: ArrayLike<number>, up?: ArrayLike<number>): this;
  add(...nodes: SceneNode[]): this;
  remove(...nodes: SceneNode[]): this;
  removeFromParent(): this;
  traverse(visit: (node: SceneNode) => void): void;
  readonly parent: SceneNode | null;
  readonly children: readonly SceneNode[];
  readonly position: Float32Array; // borrowed, read-only
  readonly quaternion: Float32Array; // borrowed, read-only
  readonly scale: Float32Array; // borrowed, read-only
  readonly localMatrix: Mat4;   // borrowed, read-only
  readonly worldMatrix: Mat4;   // borrowed, read-only
  readonly worldPosition: Float32Array; // borrowed, read-only
}
```

A three-part arm — base, arm, claw — with the same local values used throughout this guide:

```ts
import { group } from "vgpu/scene";

const claw = group({ label: "claw", position: [0, 1.6, 0] });
const arm = group({ label: "arm", position: [0, 0.5, 0], children: [claw] });
const base = group({ label: "base", position: [0, 0.25, 0], children: [arm] });

function animateArm(time: number) {
  base.set({ rotation: [0, time * 0.3, 0] });
  arm.set({ rotation: [0, 0, Math.sin(time) * 0.6] });
}

animateArm(1.5);
claw.worldPosition; // base * arm * claw, recomputed only because base and arm changed
```

Nodes evaluate lazily: `set()` marks the node and its descendants dirty, and reading `worldMatrix` recomputes only what is stale. The matrix math is the same as `composeMatrix` and `multiplyMatrices`.

Rules for nodes:

* **Write through `set()`.** `position`, `quaternion`, `scale`, `localMatrix`, `worldMatrix`, and `worldPosition` return borrowed arrays with a stable identity. Treat them as read-only: writing into them does not mark the node dirty, so the tree goes stale silently. `set()` updates only the fields you pass; the others keep their values.
* **Reparenting keeps the local transform.** `add()` and `remove()` move a node without adjusting its local values, so its world matrix changes to follow the new parent. There is no keep-world node operation or matrix setter. External matrix-based hierarchies can use `localFromWorld` to calculate a replacement local matrix without decomposing it into node fields.
* **Existing spatial methods remain.** `lookAt(target, up)` points local −Z toward a world-space target and compensates for the parent transform; `up` defaults to `[0, 1, 0]`. A singular parent throws before changing the quaternion. `traverse(visit)` visits the node and its descendants; `removeFromParent()` detaches the node while preserving its local transform.
* **`label` and `visible` are plain flags.** Nothing in vgpu reads them: a bound instance copies only the world matrix. To hide an instance, `remove()` it from its collection.
* **Cycles throw.** `add()` throws `VGPU-SCENE-CYCLE` when a node would become its own ancestor.

Nodes are for articulated parts, not populations. For thousands of objects, use an instance collection directly and keep the hierarchy, if any, in flat arrays.

## Evaluate a hierarchy stored in your own arrays

When an ECS already stores local transforms, evaluate them in place instead of mirroring them as nodes. `hierarchyOrder` compiles a topology once; `evaluateHierarchy` computes world matrices from it.

```ts illustrative
interface HierarchyOrder { readonly size: number } // opaque token

function hierarchyOrder(parents: Int32Array): HierarchyOrder;

interface HierarchyEvaluation {
  order: HierarchyOrder;
  parents: Int32Array;   // n entries
  locals: Float32Array;  // 16 * n
  worlds: Float32Array;  // 16 * n, written
  changed?: Uint8Array;  // n entries, read only
  updated?: Uint8Array;  // n entries, fully overwritten
}

function evaluateHierarchy(input: HierarchyEvaluation): number; // number of world rows recomputed by this call
```

`parents[i]` is the dense row index of row `i`'s parent, or `-1` for a root. Rows can appear in any order and a hierarchy can have several roots. Your entity IDs stay in your ECS; the evaluator only sees row indices.

The same arm as above, as three rows:

```ts
import { composeMatrix, evaluateHierarchy, hierarchyOrder } from "vgpu/scene";

const parents = new Int32Array([-1, 0, 1]); // base is a root, arm's parent is base, claw's parent is arm
const locals = new Float32Array(3 * 16);
const worlds = new Float32Array(3 * 16);
const localRows = [0, 1, 2].map((row) => locals.subarray(row * 16, row * 16 + 16)); // views, created once

composeMatrix({ position: [0, 0.25, 0] }, localRows[0]);
composeMatrix({ position: [0, 0.5, 0] }, localRows[1]);
composeMatrix({ position: [0, 1.6, 0] }, localRows[2]);

const order = hierarchyOrder(parents);
evaluateHierarchy({ order, parents, locals, worlds }); // full evaluation: required once after setup

const changed = new Uint8Array(3);
const armHierarchy = { order, parents, locals, worlds, changed };

function animateArmRows(time: number) {
  composeMatrix({ position: [0, 0.25, 0], rotation: [0, time * 0.3, 0] }, localRows[0]);
  changed[0] = 1;
  composeMatrix({ position: [0, 0.5, 0], rotation: [0, 0, Math.sin(time) * 0.6] }, localRows[1]);
  changed[1] = 1;
  evaluateHierarchy(armHierarchy); // recomputes rows 0, 1 and their descendant, row 2
  changed.fill(0);                 // you clear your flags; the evaluator never does
}
```

How evaluation works:

* **Without `changed`, every row is recomputed.** Do a full evaluation after initialization, after any topology change, and whenever you replace or reset `worlds`. The evaluator keeps no hidden state about your output buffers, so it cannot detect a missing initialization or a local you changed without flagging it.
* **With `changed`, a row is recomputed when its flag is nonzero or its parent was recomputed in this call.** `changed` is never mutated. When `updated` is given, every entry is overwritten: `1` for recomputed rows, `0` for the rest — useful for copying only recomputed rows onward.
* **Topology is compiled and checked.** `hierarchyOrder` validates indices and cycles, copies `parents`, and owns its scratch memory. Every `evaluateHierarchy` compares `parents` with that copy and throws `VGPU-SPATIAL-ORDER` if they differ — rebuild the token with `hierarchyOrder(parents)` after changing any parent.
* **Lengths are exact:** `parents` n, `locals` 16n, `worlds` 16n, `changed` n, `updated` n. Shape, topology, and aliasing are checked before any output is written.
* **Outputs must not overlap.** `worlds` and `updated` may not share bytes with each other or with any input (checked by byte range, not object identity). Read-only inputs may overlap each other.
* **Locals are trusted.** The evaluator assumes finite affine locals and does not scan every component on every call; invalid values propagate into `worlds`. Validate at your import boundary. The instance collection re-validates every world matrix you copy into it.
* **Synchronous and single-threaded.** Do not mutate the arrays concurrently; `SharedArrayBuffer` synchronization is not supported.

Cost: `hierarchyOrder` is O(n) time and memory. Each `evaluateHierarchy` scans all n rows and performs one matrix multiplication per recomputed row. There is no partial traversal of a subtree.

## Store many copies in an instance collection

An instance collection is a fixed-capacity set of records on the CPU. Every record has a world matrix and the attributes you declare. It has no geometry, no material, and no GPU resources; the GPU bridge reads it later.

```ts illustrative
type InstanceFormat =
  | "float32" | "float32x2" | "float32x3" | "float32x4"
  | "sint32" | "sint32x2" | "sint32x3" | "sint32x4"
  | "uint32" | "uint32x2" | "uint32x3" | "uint32x4";
type InstanceAttribute = InstanceFormat | { format: InstanceFormat; default: number | ArrayLike<number> };
type InstanceAttributes = Record<string, InstanceAttribute>;
type InstanceId = number & { readonly __instanceId: unique symbol };

function instances<const A extends InstanceAttributes = {}>(options: {
  capacity: number;
  attributes?: A;
}): InstanceCollection<A>;

interface InstanceCollection<A extends InstanceAttributes = {}> {
  readonly capacity: number;
  readonly count: number;
  add(...args: InstanceAddArgs<A>): InstanceId; // values required when an attribute has no default
  remove(id: InstanceId): void;
  set(id: InstanceId, values: Partial<InstanceValues<A>>): void;
  setWorld(id: InstanceId, world: ArrayLike<number>): void;
  setWorlds(ids: ArrayLike<InstanceId>, worlds: Float32Array, firstRow?: number): void;
  bindWorld(id: InstanceId, source: () => ArrayLike<number>): void;
  unbindWorld(id: InstanceId): void;
  syncWorlds(): number; // number of sources copied
  slotOf(id: InstanceId): number;
  idAt(slot: number): InstanceId;
}
```

Declare attributes once; TypeScript infers what `add()` requires:

```ts
import { instances } from "vgpu/scene";

const markers = instances({
  capacity: 10_000,
  attributes: {
    tint: { format: "float32x4", default: [1, 1, 1, 1] }, // optional in add()
    pickId: "uint32",                                      // required in add(): no default
  },
});

const marker = markers.add({ pickId: 7 });           // tint = [1, 1, 1, 1], world = identity
markers.set(marker, { tint: [1, 0.2, 0.2, 1] });     // partial attribute update
// @ts-expect-error pickId is required; executing this also throws VGPU-INSTANCE-ATTRIBUTE.
markers.add({ tint: [0, 0, 1, 1] });
```

Scalar formats take a `number`; vector formats take an `ArrayLike<number>` of exactly that many components. `float32` values must stay finite after float32 conversion. `sint32`/`uint32` values must be integers inside their 32-bit range.

Layout and capacity:

* **The schema is snapshotted at creation.** Attribute order is declaration order. Mutating the `attributes` object or a `default` array afterwards changes nothing.
* **Names** are unique, non-numeric, and must not be `world0`, `world1`, `world2`, or `world3` — those are reserved for the world matrix columns.
* **Capacity is fixed.** It is a nonnegative integer, `0` included. `add()` on a full collection throws `VGPU-INSTANCE-CAPACITY`. There is no growth: to grow, create a larger collection and bridge, copy your data, re-establish bindings, and update your stored handles and draws.
* **Records start with the identity world matrix.**

### Handles, slots, and removal

`add()` returns an `InstanceId`: an opaque handle specific to this collection, stable while the instance lives, and never silently reused. A removed, stale, or foreign handle throws `VGPU-INSTANCE-HANDLE`. Handles are not persistent or serializable — do not save them.

A slot is the record's current position in the packed buffer; it is what the shader sees as `@builtin(instance_index)`. `remove()` compacts the collection by moving the last record into the removed slot, so slots change and handles do not. `slotOf(id)` and `idAt(slot)` describe the current packing only.

<Callout type="info">
  Good to know: For GPU picking, read a stable application ID from an attribute such as `pickId` rather than `instance_index`. Readbacks arrive frames later, after slots may have moved. Do not recycle your own IDs while a readback is pending — the collection cannot know about it.
</Callout>

### Who writes the world matrix

Each instance has one world authority at a time:

| Authority    | Call                                                              | When to use                                                            |
| ------------ | ----------------------------------------------------------------- | ---------------------------------------------------------------------- |
| Direct write | `setWorld(id, world)`                                             | One-off placement, occasional moves                                    |
| Batch write  | `setWorlds(ids, worlds, firstRow?)`                               | Physics or ECS output: many final world matrices in one `Float32Array` |
| Bound source | `bindWorld(id, () => matrix)` once, then `syncWorlds()` per frame | A node or another object that already owns a world matrix              |

```ts illustrative
armParts.bindWorld(clawId, () => claw.worldMatrix); // once; the collection knows nothing about SceneNode
armParts.syncWorlds();                                // per frame: calls each source once and copies its matrix

armParts.unbindWorld(clawId);                        // keeps the last copied matrix
armParts.setWorld(clawId, physicsWorld);             // a new, explicit authority
```

Rules:

* **Every world write is validated.** `setWorld`, `setWorlds`, and `syncWorlds` check 16 finite values and the exact affine bottom row `0, 0, 0, 1` at indices `3, 7, 11, 15`.
* **`setWorlds` is all-or-nothing.** Row `firstRow + i` of `worlds` goes to `ids[i]`; the ids' slots need not be contiguous. The whole batch is validated first — live handles of this collection, no duplicates, no bound ids, enough rows, every matrix — and nothing is written if any check fails. An empty batch is valid. `firstRow` defaults to `0` and must be a nonnegative integer.
* **Bound instances reject direct world writes.** `setWorld`/`setWorlds` on a bound id throw `VGPU-INSTANCE-BOUND`; call `unbindWorld(id)` first. Binding an already bound id also throws — unbind it before replacing the source. Attributes stay writable with `set()` while bound.
* **`unbindWorld`** validates the handle, then does nothing if the id is already unbound. `remove()` drops the binding. The collection holds your source function, and whatever it captures, until you unbind or remove.
* **Sources are synchronous readers.** During `syncWorlds`, a source must not mutate the collection, call `syncWorlds` again, or publish a bridge — those throw `VGPU-INSTANCE-REENTRANT`. The collection does not keep the returned array and does not compare values.
* **A failing source can leave partial copies.** Sources run in order; if one throws or returns an invalid matrix (`VGPU-INSTANCE-SOURCE`), rows copied before it keep their new values. There is no rollback or retry. Abort that frame (a throw inside the `frameLoop` callback cancels the frame and stops the loop), fix the source, and run a complete `syncWorlds` again.

Cost: `syncWorlds` costs one source call, validation, and a 64-byte copy per bound instance, plus whatever lazy node recomputation the source triggers. `setWorlds` costs validation plus a 64-byte copy per row.

## Drive a camera from state you own

Camera functions operate on plain objects you allocate and keep. The rig and lens operations mutate the state you pass and return it; `rigPose`, `perspective`, and `orthographic` write into the `out` you pass and return it; `viewMatrices` writes into its `out` and returns `void`; `worldPerPixel` returns a number. None of them listen to the DOM, schedule frames, or create nodes.

```ts illustrative
interface OrbitRig { target: Float32Array; pan: Float32Array; yaw: number; pitch: number; distance: number }
interface OrbitRigOptions { target?: ArrayLike<number>; pan?: ArrayLike<number>; yaw?: number; pitch?: number; distance?: number }
interface RigLimits { minPitch?: number; maxPitch?: number; minDistance?: number; maxDistance?: number }
interface Pose { position: Float32Array; quaternion: Float32Array } // world space, lengths 3 and 4
interface Lens { fov: number; near: number; far: number }            // vertical fov in degrees
interface CameraMatrices { view: Mat4; viewProjection: Mat4 }

function orbitRig(initial?: OrbitRigOptions): OrbitRig;
function orbit(rig: OrbitRig, deltaYaw: number, deltaPitch: number, limits?: RigLimits): OrbitRig;
function pan(rig: OrbitRig, right: number, up: number): OrbitRig;
function dolly(rig: OrbitRig, factor: number, limits?: RigLimits): OrbitRig;
function zoom(lens: Lens, factor: number, limits?: { minFov?: number; maxFov?: number }): Lens;
function smoothRig(current: OrbitRig, goal: OrbitRig, dt: number, options: { timeConstant: number }): OrbitRig;
function rigPose(rig: OrbitRig, out: Pose): Pose;
function perspective(lens: Lens, aspect: number, out: Mat4): Mat4;
function orthographic(bounds: { left: number; right: number; bottom: number; top: number; near: number; far: number }, out: Mat4): Mat4;
function viewMatrices(pose: Pose, projection: ArrayLike<number>, out: CameraMatrices): void;
function worldPerPixel(distance: number, lens: Lens, heightPixels: number): number;
```

### The orbit rig

An `OrbitRig` orbits a pivot, `target + pan`. `target` is what the camera follows — set it from your app, an animation, or physics. `pan` is the user's world-space offset from it. Keeping them separate means updating the followed target never erases the user's pan.

| Field      | Default     | Meaning                                                                                                                 |
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------- |
| `target`   | `[0, 0, 0]` | Followed world point. `orbitRig()` copies your input into a new `Float32Array(3)`.                                      |
| `pan`      | `[0, 0, 0]` | User offset in world units, added to `target`.                                                                          |
| `yaw`      | `0`         | Radians around +Y. `0` places the camera on the +Z side of the pivot. Not wrapped, so continuous spins stay continuous. |
| `pitch`    | `0`         | Radians. Positive raises the camera above the pivot. Must stay inside `(-π/2, π/2)`.                                    |
| `distance` | `1`         | World units from the pivot. Must be finite and positive.                                                                |

`rigPose(rig, out)` writes a world-space pose:

* `position = pivot + distance * [cos(pitch) * sin(yaw), sin(pitch), cos(pitch) * cos(yaw)]`
* `quaternion = Ry(yaw) * Rx(-pitch)`, so the camera's −Z axis points at the pivot.

The operations:

* **`orbit(rig, deltaYaw, deltaPitch, limits?)`** adds radians and clamps pitch. Default pitch limits are `±(π/2 − 1e-4)`.
* **`pan(rig, right, up)`** adds world units along the right and up axes of the rig you pass it. Pass the goal rig (see smoothing below), so the pan follows the orientation the user is steering toward.
* **`dolly(rig, factor, limits?)`** multiplies `distance`: a factor above `1` moves away. Default distance limits are `[1e-4, Infinity]`.
* **`zoom(lens, factor, limits?)`** narrows the lens instead of moving the camera: it sets `tan(fov / 2) /= factor`, so a factor above `1` zooms in. Default limits are `minFov: 1e-4` and `maxFov: 180 − 1e-4` degrees.

Factors must be finite and positive — `1` is the neutral value, `0` throws. Limits that are invalid or reversed throw before anything is mutated. `orbit` and `dolly` clamp valid candidates into the limits; when you write rig fields directly, keep `distance` finite and positive and `pitch` inside `(-π/2, π/2)`.

### Smoothing

Keep two rigs: a **goal** that input and following write to, and a **current** that the camera renders from. `smoothRig` moves only `current` toward `goal`:

```ts
import { orbitRig, smoothRig } from "vgpu/scene";

const goal = orbitRig({ yaw: 0.6, pitch: 0.35, distance: 9 });
const current = orbitRig(goal); // a copy — no shared arrays
const smoothing = { timeConstant: 0.15 }; // seconds

smoothRig(current, goal, 1 / 60, smoothing);
```

Each call blends by `k = 1 − exp(−dt / timeConstant)`: linearly for `target`, `pan`, `yaw`, and `pitch`, and logarithmically for `distance`. After `timeConstant` seconds of steady calls, `current` has covered about 63% of a fixed gap.

* `timeConstant: 0` snaps `current` to `goal`, even with `dt = 0` — useful for a paused editor.
* `timeConstant > 0` with `dt = 0` changes nothing.
* `dt` and `timeConstant` must be finite and nonnegative.
* `current` and `goal` must not share or overlap arrays, and `current`'s writable fields must not overlap each other — `VGPU-CAMERA-ALIAS`. Create both with `orbitRig()` to be safe.
* A lens is never smoothed or followed implicitly; zoom it yourself.

Exact frame-rate independence is not promised while the goal itself moves every frame.

### Projection and view matrices

```ts
import { orbitRig, orthographic, perspective, rigPose, viewMatrices } from "vgpu/scene";

const current = orbitRig({ distance: 9 });
const lens = { fov: 50, near: 0.1, far: 200 };
const projection = new Float32Array(16);
const pose = { position: new Float32Array(3), quaternion: new Float32Array([0, 0, 0, 1]) };
const matrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };

perspective(lens, 16 / 9, projection);
viewMatrices(rigPose(current, pose), projection, matrices); // matrices.viewProjection = projection * view

orthographic({ left: -4, right: 4, bottom: -2.25, top: 2.25, near: 0, far: 50 }, projection); // or an orthographic lens
```

* `perspective` requires `0 < fov < 180` (vertical, degrees), `0 < near < far`, all finite, and a finite positive `aspect`.
* `orthographic` requires `left < right`, `bottom < top`, and `0 <= near < far`, all finite. The previous camera allowed flipped bounds (but rejected equal bounds). For a mirrored projection, pass your own projection matrix to `viewMatrices`.
* `viewMatrices` accepts any finite projection matrix, not only the ones above. It requires a finite pose, normalizes a nonzero quaternion for the calculation without mutating the pose, and rejects a zero quaternion.
* A free-fly or physics camera can skip the rig entirely and write `pose.position` and `pose.quaternion` itself.

### Pointer input stays in your app

There is no built-in input adapter. Convert your events into rig deltas, accumulate them, and apply them once per tick. `worldPerPixel(distance, lens, heightPixels)` returns `2 * distance * tan(fov / 2) / heightPixels`, the world size of one pixel at the pivot, so a pan follows the cursor:

```ts
import { orbitRig, worldPerPixel } from "vgpu/scene";

const canvas = document.createElement("canvas");
const goal = orbitRig({ distance: 9 });
const lens = { fov: 50, near: 0.1, far: 200 };
const radiansPerPixel = 0.005;
const input = { yaw: 0, pitch: 0, panRight: 0, panUp: 0, dolly: 1 }; // neutral values

canvas.addEventListener("pointermove", (event) => {
  if (event.buttons !== 1) return;
  if (event.shiftKey) {
    const units = worldPerPixel(goal.distance, lens, canvas.clientHeight); // CSS pixels, like movementX/Y
    input.panRight -= event.movementX * units;
    input.panUp += event.movementY * units;
  } else {
    input.yaw -= event.movementX * radiansPerPixel;
    input.pitch += event.movementY * radiansPerPixel;
  }
});

canvas.addEventListener("wheel", (event) => {
  event.preventDefault();
  input.dolly *= Math.exp(event.deltaY * 0.001); // scroll down moves away
}, { passive: false });
```

`heightPixels` and the deltas must use the same units. Pointer events report CSS pixels, so pass `canvas.clientHeight`, not the physical `canvas.height`.

## Publish instances to the GPU

`instanceGeometry` from `vgpu/scene/gpu` combines a base mesh with an instance vertex stream fed by one collection. It returns a composed `Geometry` you pass to `draw(gpu, { geometry })`.

```ts illustrative
import type { Geometry, Gpu } from "vgpu";
import type { InstanceAttributes, InstanceCollection } from "vgpu/scene";

interface InstanceGeometry {
  readonly geometry: Geometry; // base mesh streams + the instance stream
  publish(): number;           // uploads pending changes, returns the current count
  destroy(): void;
}

function instanceGeometry<A extends InstanceAttributes>(
  gpu: Gpu,
  collection: InstanceCollection<A>,
  options: { mesh: Geometry },
): InstanceGeometry;
```

### The instance stream layout

The instance stream is one vertex buffer with `stepMode: "instance"`, sized to the collection's `capacity` and allocated once. Each record is the 64-byte world matrix followed by your attributes in declaration order, 4-byte aligned:

| Attribute name                         | WGSL input type | Content                                              |
| -------------------------------------- | --------------- | ---------------------------------------------------- |
| `world0` … `world3`                    | `vec4f`         | World matrix columns 0–3 (one vertex attribute each) |
| each `float32` / `float32xN` attribute | `f32` / `vecNf` | Your value                                           |
| each `sint32` / `sint32xN` attribute   | `i32` / `vecNi` | Your value                                           |
| each `uint32` / `uint32xN` attribute   | `u32` / `vecNu` | Your value                                           |

The attributes are matched to vertex shader inputs by name, like any other `geometry(gpu)` attribute. The base mesh keeps its own attributes. `vgpu/scene` recipes pin `position` to `@location(0)`, `normal` to `@location(1)`, and — for recipes that have one — `uv` to `@location(2)`: `box()` supplies only `position` and `normal`, while `sphere()` also supplies `uv`. Pick free locations for the instance inputs in your shader.

<Callout type="warn">
  Warning: Every shader drawn with `bridge.geometry` must declare every instance attribute as a vertex input — `world0..world3` and each custom attribute — even when that shader does not use it. A missing input throws `VGPU-MESH-ATTRIBUTE-UNMATCHED` when the pipeline is created. This applies to every pass that shares the geometry, a depth prepass included. Declare the base mesh attributes too: the explicit-location recipe attributes may be omitted, but a complete declaration keeps every consumer of the bridge consistent.
</Callout>

Creation limits, checked by `instanceGeometry` before it allocates anything and reported as `VGPU-INSTANCE-LAYOUT` with the offending names and the actual versus permitted counts:

* `mesh` must come from the same `gpu`.
* `mesh` must not already have an instance-step buffer, and none of its attribute names may collide with `world0..world3` or your attribute names. Instance attributes are matched by name; choose their locations explicitly in WGSL.
* The total vertex attributes (base mesh + 4 world columns + your attributes) must fit the device's `maxVertexAttributes`. On the WebGPU default of 16, a `box()` mesh (2 attributes) leaves room for 10 custom instance attributes, and a `sphere()` mesh (3 attributes) for 9.
* The composed geometry may have at most 8 vertex buffers (and no more than the device's `maxVertexBuffers`). The instance stride (`64 + 4 × total attribute components`) may be at most 2048 bytes (and no more than `maxVertexBufferArrayStride`), and `capacity × stride` must fit `maxBufferSize`.

A base mesh that is already destroyed fails the factory's layout preflight with `VGPU-INSTANCE-LAYOUT`. Pass a live base mesh to `instanceGeometry`.

There is no storage-buffer variant and no shader injection; the stream reaches your shader only through the vertex inputs you declare.

### Ownership and lifetime

* The bridge owns its instance buffer and the composed `bridge.geometry` wrapper. The base `mesh` stays yours: the bridge borrows its buffers and never destroys them.
* `bridge.destroy()` and `bridge.geometry.destroy()` share one destroyed state and are idempotent. Disposing the `gpu` destroys the bridge too.
* After the bridge, its composed geometry, or the base mesh is destroyed, `publish()`, drawing with `bridge.geometry`, recording it into a render bundle, and replaying a bundle that already contains it all throw `VGPU-INSTANCE-DESTROYED` instead of reading destroyed buffers. This includes draws compiled before the destruction. Create a new bridge on a live base mesh, then recreate the draws and re-record the bundles that used the old one.
* Keep the base mesh alive for as long as any bridge built on it is in use. Destroying the base invalidates its bridges but does not release their instance buffers; call `bridge.destroy()` or dispose the GPU to release those buffers.

### What `publish()` does

`publish()` copies the collection's current CPU records to the instance buffer and returns the collection's `count`. It never calls bound sources, never evaluates nodes or hierarchies, and never touches the camera — run `syncWorlds()`/`setWorlds()` first.

* The first `publish()` of a bridge uploads every active record. A later `publish()` with no changes in between uploads 0 bytes, though it may still scan all records.
* Removals, slot moves, and a shrinking count are tracked, so the buffer always matches the current packing.
* Each bridge keeps its own cursor. Two bridges on the same collection — for example one with a detailed mesh and one with a low-poly proxy mesh — each see every change, and a failed publish on one never consumes the other's pending changes.
* `publish()` during `syncWorlds()` throws `VGPU-INSTANCE-REENTRANT`.

### Ordering contract

The instance buffer is a live resource, not a per-draw snapshot:

1. Update worlds and attributes, then call `publish()`.
2. Encode every pass that draws with this bridge.
3. Do not `publish()` again until the frame holding those passes is submitted — a second publish in the same frame rewrites the buffer the earlier passes read.

Publication queues buffer writes immediately; an exception later in the frame does not undo them. Later frames are ordered by the GPU queue, so publishing at the start of the next frame is safe without waiting for the GPU to go idle. If two passes in one frame need different instance contents, give them separate collections and bridges.

The count comes from `publish()` and reaches the GPU only through the draw call: `pass.draw(boxDraw, { instances: count })`. `0` is valid and draws nothing. The composed geometry has `instanceCount: 0`: omitting the explicit `instances` option also draws nothing. A [render bundle](/docs/concepts/render-bundles) records the count at record time; re-record it whenever the count changes.

## WGSL helpers from `@vgpu/wgsl-std/scene`

`@vgpu/wgsl-std/scene` provides pure functions for the math every instanced shader repeats. They declare no bindings — imported WGSL modules cannot, see [WGSL modules](/docs/concepts/wgsl-modules) — and implement no shading, color, or lighting.

```wgsl
export fn instanceWorldMatrix(world0: vec4f, world1: vec4f, world2: vec4f, world3: vec4f) -> mat4x4f;
export fn transformPosition(world: mat4x4f, position: vec3f) -> vec3f;
export fn transformDirection(world: mat4x4f, direction: vec3f) -> vec3f;
export fn transformNormal(world: mat4x4f, normal: vec3f) -> vec3f;
```

| Helper                | Returns                                                                                                                                                                                                                                                                                    |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `instanceWorldMatrix` | `mat4x4f(world0, world1, world2, world3)` — the columns published by the bridge.                                                                                                                                                                                                           |
| `transformPosition`   | `(world * vec4f(position, 1.0)).xyz` — applies rotation, scale, shear, and translation.                                                                                                                                                                                                    |
| `transformDirection`  | The linear part applied to `direction`, without translation and without normalization.                                                                                                                                                                                                     |
| `transformNormal`     | The normalized inverse-transpose of the linear part applied to `normal` for well-conditioned inputs, including nonuniform scale, shear, and reflections. Returns `vec3f(0.0)` when its guarded `f32` calculations detect a zero normal, linear magnitude, determinant, or cofactor result. |

Only finite affine matrices are supported. The zero guard has no epsilon or rank tolerance: rounding can make singular authoring data produce a nonzero computed determinant and direction. Near-singular matrices and extreme axis ratios can amplify rounding or backend-dependent subnormal behavior; this helper is not symbolic rank detection. Use an exact singular representation such as a zero column when you require the fallback. Handle the `vec3f(0.0)` fallback where you normalize again after interpolation — `safeNormalize3` from `@vgpu/wgsl-std/math` does that with a fallback you choose.

<Callout type="warn">
  Warning: If your shader stretches or deforms the mesh beyond the world matrix — a per-instance `size`, a displacement — pass the complete transform to `transformPosition` and `transformNormal`, or supply an adjusted normal yourself. The helpers cannot see transforms they are not given.
</Callout>

Mirrored instances (negative determinant) get correct normals, but their triangles flip winding on screen. Use `cull: "none"` for a draw that mixes mirrored and unmirrored instances, or `frontFace: "cw"` when every instance is mirrored.

### A complete instanced shader

This shader is used by every example below. `box()` supplies `position` and `normal`; the bridge supplies `world0..world3`, `size`, and `tint`; `lighting` and `camera` are uniforms you set by name.

```wgsl
// boxes.wgsl
import { instanceWorldMatrix, transformNormal, transformPosition } from "@vgpu/wgsl-std/scene";
import { safeNormalize3 } from "@vgpu/wgsl-std/math";

struct Lighting { direction: vec3f, ambient: f32 }
struct CameraData { viewProjection: mat4x4f }

@group(0) @binding(0) var<uniform> lighting: Lighting;
@group(1) @binding(0) var<uniform> camera: CameraData;

struct VertexIn {
  @location(0) position: vec3f, // box() mesh
  @location(1) normal: vec3f,   // box() mesh
  @location(3) world0: vec4f,   // instance stream: world matrix columns
  @location(4) world1: vec4f,
  @location(5) world2: vec4f,
  @location(6) world3: vec4f,
  @location(7) size: vec3f,     // instance attribute "size": "float32x3"
  @location(8) tint: vec4f,     // instance attribute "tint": "float32x4"
}

struct VertexOut {
  @builtin(position) clip: vec4f,
  @location(0) normal: vec3f,
  @location(1) tint: vec4f,
}

@vertex fn vs_main(input: VertexIn) -> VertexOut {
  let world = instanceWorldMatrix(input.world0, input.world1, input.world2, input.world3);
  // box() is a unit cube; `size` stretches it, so the complete transform is world * shape
  let shape = mat4x4f(
    vec4f(input.size.x, 0.0, 0.0, 0.0),
    vec4f(0.0, input.size.y, 0.0, 0.0),
    vec4f(0.0, 0.0, input.size.z, 0.0),
    vec4f(0.0, 0.0, 0.0, 1.0),
  );
  let model = world * shape;

  var out: VertexOut;
  out.clip = camera.viewProjection * vec4f(transformPosition(model, input.position), 1.0);
  out.normal = transformNormal(model, input.normal);
  out.tint = input.tint;
  return out;
}

@fragment fn fs_main(input: VertexOut) -> @location(0) vec4f {
  let normal = safeNormalize3(input.normal, vec3f(0.0, 1.0, 0.0));
  let diffuse = max(dot(normal, normalize(-lighting.direction)), 0.0);
  return vec4f(input.tint.rgb * (lighting.ambient + diffuse), input.tint.a);
}
```

Import it through a bundler loader or `resolveShader()` so the `@vgpu/wgsl-std` imports resolve — see [WGSL modules](/docs/concepts/wgsl-modules).

The vertex inputs match the geometry exactly: every attribute the geometry provides is declared, and nothing else. The matching rules are asymmetric:

* A shader input the geometry does not provide always throws `VGPU-MESH-INPUT-MISSING`.
* A name-matched geometry attribute without a shader input throws `VGPU-MESH-ATTRIBUTE-UNMATCHED`. Every instance attribute (`world0..world3` and your custom attributes) is name-matched, so all of them must be declared.
* Recipe attributes carry an explicit location, so a shader may omit one — a depth-only shader could skip `normal`. Declare the complete set anyway in shaders that share a bridge, so every consumer reads the same stream layout.

This shader is written for `box()`, which supplies only `position` and `normal`. To instance `sphere()` instead, add `@location(2) uv: vec2f` to `VertexIn`; a shader that declares `uv` fails against a `box()` bridge, so give each base mesh its own vertex entry point.

## Connect the camera to your shader by name

The camera matrix is plain CPU data. It reaches the shader only when you pass it to `set()` under the WGSL binding name. The shader author chooses the group and binding; reflection maps the name `camera` to `@group(1) @binding(0)`, so the TypeScript side never repeats the numbers.

```wgsl
// lit.wgsl
struct Lighting { direction: vec3f, ambient: f32 }
struct CameraData { viewProjection: mat4x4f }
@group(0) @binding(0) var<uniform> lighting: Lighting;
@group(1) @binding(0) var<uniform> camera: CameraData;

struct VertexOut { @builtin(position) clip: vec4f, @location(0) normal: vec3f }

@vertex fn vs_main(@location(0) position: vec3f, @location(1) normal: vec3f) -> VertexOut {
  var out: VertexOut;
  out.clip = camera.viewProjection * vec4f(position, 1.0);
  out.normal = normal;
  return out;
}

@fragment fn fs_main(@location(0) normal: vec3f) -> @location(0) vec4f {
  let diffuse = max(dot(normalize(normal), normalize(-lighting.direction)), 0.0);
  return vec4f(vec3f(0.9, 0.5, 0.1) * (lighting.ambient + diffuse), 1.0);
}
```

```ts
import { draw, geometry, init } from "vgpu";
import { box } from "vgpu/scene";
import litShader from "./lit.wgsl";

const gpu = await init();
const viewProjection = new Float32Array(16);

// ---cut---
const cube = draw(gpu, { shader: litShader, geometry: geometry(gpu, box({ size: 1 })) });

// viewProjection is matrices.viewProjection, written by viewMatrices()
cube.set({
  lighting: { direction: [-0.4, -1, -0.3], ambient: 0.15 }, // binding `lighting` -> @group(0) @binding(0)
  camera: { viewProjection },                              // binding `camera` -> @group(1) @binding(0)
});
```

The rules of this connection:

* **Use the full binding name.** `set({ camera: { viewProjection } })` names the binding and its member. `set()` also accepts a bare member name when it is unambiguous, but the full form keeps the wiring readable and stays correct when two structs share a member name.
* **`set()` packs at call time.** Mutating `matrices.viewProjection` afterwards does not update the GPU value. Call `set()` again after every `viewMatrices()` you want the draw to see.
* **Direct draws capture values when encoded.** Inside a frame, `pass.draw()` captures the uniform values current at that moment, so setting a different camera before each of two `pass.draw()` calls renders two views — see [Frames](/docs/concepts/frames).
* **The matrix has no group of its own.** The same `matrices.viewProjection` can feed several draws whose shaders put `camera` in different groups or under different names.
* **Instance data has no bind group.** It travels as vertex inputs; its only connection is `geometry: bridge.geometry` at draw creation plus the matching WGSL inputs.

## The frame, step by step

The executable `examples/by-example-s06-scene/src/composition.ts` and its native tests demonstrate equivalent group, external-hierarchy, and final-world paths using the same shader and two passes.

Both complete examples below render the same scene with the same shader: a three-part arm (base → arm → claw) plus a population of crates, all drawn with one instanced draw call, with an orbit camera that follows the claw. They differ only in where the arm's world matrices come from.

This setup renders the scene into an offscreen depth target and composites it to the canvas, which is where a post-processing pass belongs. If you only present the scene, render it straight to a depth surface instead — see [Render straight to the canvas](#render-straight-to-the-canvas).

Shared setup — targets, the collection, the bridge, the draw, and camera state — is created once:

```wgsl
// present.wgsl
@group(0) @binding(0) var scene: texture_2d<f32>;
@group(0) @binding(1) var sceneSampler: sampler;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return textureSampleLevel(scene, sceneSampler, uv, 0.0);
}
```

```ts
// shared.ts
import { clock, draw, effect, frameLoop, geometry, init, sampler, surface, target, type Frame } from "vgpu";
import { box, composeMatrix, dolly, instances, orbit, orbitRig, pan, perspective, rigPose, smoothRig, viewMatrices, type InstanceId } from "vgpu/scene";
import { instanceGeometry } from "vgpu/scene/gpu";
import boxShader from "./boxes.wgsl";
import presentShader from "./present.wgsl";

export const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);
const sceneTarget = target(gpu, { size: canvasSurface.size, depth: true }); // offscreen, so the present pass can sample it
canvasSurface.onResize(({ width, height }) => sceneTarget.resize([width, height]));
const present = effect(gpu, presentShader, { set: { scene: sceneTarget, sceneSampler: sampler(gpu, { minFilter: "linear", magFilter: "linear" }) } });

// One collection for arm parts and crates: same mesh, same attributes, one draw call.
export const crateCount = 2000;
export const boxes = instances({
  capacity: 3 + crateCount,
  attributes: { size: "float32x3", tint: { format: "float32x4", default: [1, 1, 1, 1] } },
});
export const partIds: InstanceId[] = [
  boxes.add({ size: [1.2, 0.5, 1.2], tint: [0.3, 0.3, 0.35, 1] }), // base
  boxes.add({ size: [0.3, 1.6, 0.3], tint: [0.9, 0.5, 0.1, 1] }),  // arm
  boxes.add({ size: [0.6, 0.2, 0.6] }),                            // claw, default tint
];
export const crateIds: InstanceId[] = Array.from({ length: crateCount }, () => boxes.add({ size: [0.4, 0.4, 0.4], tint: [0.6, 0.45, 0.3, 1] }));

const boxMesh = geometry(gpu, box()); // you own it; the bridge borrows it
const bridge = instanceGeometry(gpu, boxes, { mesh: boxMesh });
const boxDraw = draw(gpu, { shader: boxShader, geometry: bridge.geometry, cull: "back" });
boxDraw.set({ lighting: { direction: [-0.4, -1, -0.3], ambient: 0.15 } }); // constant: set once

// Camera state, allocated once and reused every frame.
export const goal = orbitRig({ yaw: 0.6, pitch: 0.35, distance: 9 });
const current = orbitRig(goal);
const lens = { fov: 50, near: 0.1, far: 200 };
const smoothing = { timeConstant: 0.15 };
const projection = new Float32Array(16);
const pose = { position: new Float32Array(3), quaternion: new Float32Array([0, 0, 0, 1]) };
const matrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };

// Neutral input renders without listeners. Optionally attach the handlers shown above here.
const input = { yaw: 0, pitch: 0, panRight: 0, panUp: 0, dolly: 1 };

export function renderFrame(currentFrame: Frame, dt: number) {
  // 1. Input -> goal rig, once per tick, then reset to neutral values.
  orbit(goal, input.yaw, input.pitch);
  pan(goal, input.panRight, input.panUp);
  dolly(goal, input.dolly);
  Object.assign(input, { yaw: 0, pitch: 0, panRight: 0, panUp: 0, dolly: 1 });

  // 2. Smooth, project, and build the view matrices.
  smoothRig(current, goal, dt, smoothing);
  perspective(lens, sceneTarget.size[0] / sceneTarget.size[1], projection);
  viewMatrices(rigPose(current, pose), projection, matrices);

  // 3. Connect the camera by binding name; set() packs now.
  boxDraw.set({ camera: { viewProjection: matrices.viewProjection } });

  // 4. Publish instance records before encoding any pass that reads them.
  const count = bridge.publish();

  // 5. Encode: the scene into the depth target, then composite to the canvas.
  currentFrame.pass({ target: sceneTarget, clear: [0.05, 0.05, 0.07, 1], clearDepth: 1 }, (pass) => {
    pass.draw(boxDraw, { instances: count });
  });
  currentFrame.pass(canvasSurface, present);
}

export function run(tick: (currentFrame: Frame, time: number, dt: number) => void) {
  const frameClock = clock(gpu);
  return frameLoop(gpu, (currentFrame) => tick(currentFrame, frameClock.time, frameClock.deltaTime));
}

// Example simulation writes final worlds directly. Replace it with your physics engine's output.
export function simulateCrates(time: number, out: Float32Array): void {
  for (let row = 0; row < crateCount; row++) {
    composeMatrix({
      position: [(row % 50 - 25) * 0.7, -0.5 + Math.sin(time + row * 0.1) * 0.1, (Math.floor(row / 50) - 20) * 0.7],
      rotation: [0, time * 0.1, 0],
    }, out.subarray(row * 16, row * 16 + 16));
  }
}
```

The per-frame order is fixed by data dependencies, and every step is a call you can see:

1. Apply input to the goal rig.
2. Update local transforms (nodes or your arrays).
3. Resolve world matrices (lazy node reads, or `evaluateHierarchy`).
4. Copy worlds into the collection (`syncWorlds`, `setWorlds`).
5. Follow: write the goal's `target` from a world position.
6. Smooth the rig, then build the projection and view matrices.
7. `set()` the camera on each draw that uses it.
8. `publish()` each bridge once.
9. Encode the passes with the count from `publish()`.

Steps 1 and 6–9 live in `renderFrame`; steps 2–5 differ per variant.

### Variant A: nodes

```ts illustrative
import { group } from "vgpu/scene";
import { boxes, crateCount, crateIds, goal, partIds, renderFrame, run, simulateCrates } from "./shared.ts";

const claw = group({ position: [0, 1.6, 0] });
const arm = group({ position: [0, 0.5, 0], children: [claw] });
const base = group({ position: [0, 0.25, 0], children: [arm] });

// Bind once: each part's world matrix comes from its node.
[base, arm, claw].forEach((node, index) => boxes.bindWorld(partIds[index], () => node.worldMatrix));

const crateWorlds = new Float32Array(crateCount * 16);

run((currentFrame, time, dt) => {
  base.set({ rotation: [0, time * 0.3, 0] });           // 2. local transforms
  arm.set({ rotation: [0, 0, Math.sin(time) * 0.6] });
  boxes.syncWorlds();                                    // 3 + 4. nodes resolve lazily, 3 matrices copied
  simulateCrates(time, crateWorlds);
  boxes.setWorlds(crateIds, crateWorlds);                // 4. physics output: final worlds, no hierarchy
  goal.target.set(claw.worldPosition);                   // 5. follow the claw; pan is untouched
  renderFrame(currentFrame, dt);
});
```

### Variant B: your own arrays (ECS)

```ts illustrative
import { composeMatrix, evaluateHierarchy, hierarchyOrder } from "vgpu/scene";
import { boxes, crateCount, crateIds, goal, partIds, renderFrame, run, simulateCrates } from "./shared.ts";

const parents = new Int32Array([-1, 0, 1]); // rows: base, arm, claw — same order as partIds
const locals = new Float32Array(3 * 16);
const worlds = new Float32Array(3 * 16);
const localRows = [0, 1, 2].map((row) => locals.subarray(row * 16, row * 16 + 16));
composeMatrix({ position: [0, 0.25, 0] }, localRows[0]);
composeMatrix({ position: [0, 0.5, 0] }, localRows[1]);
composeMatrix({ position: [0, 1.6, 0] }, localRows[2]);

const order = hierarchyOrder(parents);
evaluateHierarchy({ order, parents, locals, worlds }); // full evaluation after setup
const changed = new Uint8Array(3);
const armHierarchy = { order, parents, locals, worlds, changed };

const crateWorlds = new Float32Array(crateCount * 16);

run((currentFrame, time, dt) => {
  composeMatrix({ position: [0, 0.25, 0], rotation: [0, time * 0.3, 0] }, localRows[0]); // 2. locals
  changed[0] = 1;
  composeMatrix({ position: [0, 0.5, 0], rotation: [0, 0, Math.sin(time) * 0.6] }, localRows[1]);
  changed[1] = 1;
  evaluateHierarchy(armHierarchy);                        // 3. rows 0, 1 and descendant 2
  changed.fill(0);
  boxes.setWorlds(partIds, worlds);                       // 4. row i -> partIds[i]
  simulateCrates(time, crateWorlds);
  boxes.setWorlds(crateIds, crateWorlds);                 // 4. physics output skips the evaluator
  goal.target.set(worlds.subarray(2 * 16 + 12, 2 * 16 + 15)); // 5. claw translation, indices 44..46
  renderFrame(currentFrame, dt);
});
```

Both variants copy the same `3 + crateCount` matrices per frame into the same collection and render identically; neither is claimed to be faster. Variant B never creates a node, and a physics engine that already produces final world matrices needs only the `setWorlds` line. The part sizes are instance attributes applied in the shader, so the joints themselves keep unit scale and children are not stretched by their parents.

### Two passes, one bridge

A depth prepass and a color pass can share the bridge. Publish once, then encode both:

```ts illustrative
const count = bridge.publish(); // once per frame, before both passes
depthDraw.set({ camera: { viewProjection: matrices.viewProjection } });
boxDraw.set({ camera: { viewProjection: matrices.viewProjection } });

currentFrame.pass({ target: sceneTarget, clearDepth: 1 }, (pass) => pass.draw(depthDraw, { instances: count }));
currentFrame.pass({ target: sceneTarget, clear: false }, (pass) => pass.draw(boxDraw, { instances: count }));
```

`depthDraw` uses `geometry: bridge.geometry` too, so its shader declares `world0..world3`, `size`, and `tint` even though it ignores `tint`.

### Render straight to the canvas

When nothing samples the rendered scene, the offscreen target and present pass are optional. Create the surface with `depth` — and `msaa` for antialiased edges — and draw the bridge into it directly:

```ts
import { draw, frameLoop, geometry, init, surface } from "vgpu";
import { box, instances, orbitRig, perspective, rigPose, viewMatrices } from "vgpu/scene";
import { instanceGeometry } from "vgpu/scene/gpu";
import boxShader from "./boxes.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;

// ---cut---
const canvasSurface = surface(gpu, canvas, { depth: true, msaa: true }); // owned depth24plus + 4× MSAA

const crates = instances({ capacity: 1, attributes: { size: "float32x3", tint: "float32x4" } });
crates.add({ size: [1, 1, 1], tint: [0.9, 0.5, 0.1, 1] });
const crateBridge = instanceGeometry(gpu, crates, { mesh: geometry(gpu, box()) }); // you still own the mesh
const crateDraw = draw(gpu, { shader: boxShader, geometry: crateBridge.geometry, cull: "back" });
crateDraw.set({ lighting: { direction: [-0.4, -1, -0.3], ambient: 0.15 } });

const rig = orbitRig({ yaw: 0.6, pitch: 0.4, distance: 4 });
const projection = new Float32Array(16);
const pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const matrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };

frameLoop(gpu, (currentFrame) => {
  perspective({ fov: 45, near: 0.1, far: 100 }, canvasSurface.size[0] / canvasSurface.size[1], projection);
  viewMatrices(rigPose(rig, pose), projection, matrices);
  crateDraw.set({ camera: { viewProjection: matrices.viewProjection } }); // set() packs now
  const crateCount = crateBridge.publish(); // before the pass that reads it
  currentFrame.pass({ target: canvasSurface, clear: [0.05, 0.05, 0.07, 1] }, (pass) => {
    pass.draw(crateDraw, { instances: crateCount });
  });
});
```

Only the target changed: the camera, the named `set()` calls, `publish()` before encoding, and the explicit `instances` count are the same as in `renderFrame`. To switch the shared setup over, drop `sceneTarget` and `present`, compute the aspect from `canvasSurface.size`, and encode the single surface pass in step 5. With `msaa`, every surface pass clears, so the depth prepass above needs the offscreen target or a surface without `msaa`. See [`Surface`](/docs/reference/vgpu/surface#surface) for attachment lifetimes and resize.

## Errors and how to fix them

The validation errors listed below are `VGPUError`s with a `code`, a message naming the offending field path, handle, attribute, or count, and a `fix`. Passing an object that was not created by `instances()` as a GPU bridge collection throws a `TypeError`; pass the original collection instead. Validation runs before any mutation unless the row says otherwise.

### Transforms and nodes

| Code                    | When                                                                                                                                           | Fix                                                                                                 |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `VGPU-SCENE-VALUE`      | A transform value has the wrong length, is not finite, or a quaternion has zero length.                                                        | Pass 3 finite numbers for `position`/`rotation`/vector `scale`, 4 for a nonzero `quaternion`.       |
| `VGPU-SCENE-CYCLE`      | `add()` would make a node its own ancestor.                                                                                                    | Remove the node from the ancestor chain first, or add a different node.                             |
| `VGPU-SPATIAL-SIZE`     | A matrix input or `out` does not have exactly 16 elements.                                                                                     | Allocate `new Float32Array(16)`; for packed arrays pass a `subarray(row * 16, row * 16 + 16)` view. |
| `VGPU-SPATIAL-SINGULAR` | `invertAffine`/`localFromWorld` got a matrix with zero or non-finite determinant, or the inverse is not finite in float32. `out` is untouched. | Check for a zero scale or a collapsed axis in the matrix (or parent) you invert.                    |

### Hierarchies

| Code                  | When                                                             | Fix                                                                                         |
| --------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `VGPU-SPATIAL-PARENT` | A parent index is not an integer in `[-1, n)`.                   | Use dense row indices, `-1` for roots.                                                      |
| `VGPU-SPATIAL-CYCLE`  | The parents form a cycle.                                        | Break the cycle; every row must reach a root.                                               |
| `VGPU-SPATIAL-ORDER`  | `parents` no longer matches the copy compiled into `order`.      | Rebuild with `hierarchyOrder(parents)` after changing topology, then run a full evaluation. |
| `VGPU-SPATIAL-SIZE`   | `locals`/`worlds` are not 16n, or `changed`/`updated` are not n. | Size arrays from `order.size`.                                                              |
| `VGPU-SPATIAL-ALIAS`  | `worlds` or `updated` overlaps another output or any input.      | Give each writable array its own buffer.                                                    |

### Instance collections

| Code                      | When                                                                                                                                                                                          | Fix                                                                                                                                                                                                                                         |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `VGPU-INSTANCE-ATTRIBUTE` | Invalid schema (duplicate, numeric, or reserved `world0..world3` name; unknown format), an unknown attribute in `add`/`set`, or a required attribute missing from `add`.                      | Match the declared attribute names; add a `default` to make an attribute optional.                                                                                                                                                          |
| `VGPU-INSTANCE-VALUE`     | An attribute value has the wrong arity, is non-finite in float32, or is a non-integer/out-of-range `sint32`/`uint32`; or a world matrix is not 16 finite values with bottom row `0, 0, 0, 1`. | Fix the value at the path in the message.                                                                                                                                                                                                   |
| `VGPU-INSTANCE-HANDLE`    | A removed, stale, foreign, or forged `InstanceId`.                                                                                                                                            | Use live handles returned by this collection's `add()`; drop handles after `remove()`; do not pass slots as handles.                                                                                                                        |
| `VGPU-INSTANCE-BOUND`     | `setWorld`/`setWorlds` on a bound id, or `bindWorld` on an already bound id.                                                                                                                  | Call `unbindWorld(id)` first.                                                                                                                                                                                                               |
| `VGPU-INSTANCE-CAPACITY`  | `capacity` is not a nonnegative integer, or `add()` on a full collection.                                                                                                                     | Create a larger collection and bridge; capacity never grows.                                                                                                                                                                                |
| `VGPU-INSTANCE-EXHAUSTED` | An identity or revision counter reached its largest safe integer; the message names the counter. Counters never wrap, so a stale handle can never alias a new instance.                       | Stop using the exhausted domain and recreate that application state — for example reload the page or restart the process. The handle counter is shared by all collections, so creating another collection does not fix identity exhaustion. |
| `VGPU-INSTANCE-RANGE`     | `setWorlds` has an invalid `firstRow`, too few rows, or the same id twice; `idAt` got a slot outside `[0, count)`.                                                                            | Pass a nonnegative integer `firstRow` with `worlds.length >= (firstRow + ids.length) * 16`, list each id at most once, and use live slots.                                                                                                  |
| `VGPU-INSTANCE-SOURCE`    | A bound source returned an invalid world matrix. Earlier sources in the same `syncWorlds` may already be copied.                                                                              | Fix the source, abort the frame, and run `syncWorlds()` again.                                                                                                                                                                              |
| `VGPU-INSTANCE-REENTRANT` | A source mutated the collection, called `syncWorlds`, or published a bridge during `syncWorlds`.                                                                                              | Keep sources as pure reads; mutate before or after syncing.                                                                                                                                                                                 |

### Cameras

| Code                | When                                                                                                                                                                                                                                                                                                | Fix                                                                                      |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| `VGPU-CAMERA-VALUE` | A non-finite or out-of-range value: `fov` outside `(0, 180)`, `near`/`far`/`aspect`/bounds out of order, a zero or negative factor, invalid or reversed limits, `pitch` outside `(-π/2, π/2)`, non-positive `distance`, negative `dt`/`timeConstant`, a zero quaternion. Nothing is mutated.        | Pass the value range named in the message; `1` is the neutral factor.                    |
| `VGPU-CAMERA-SIZE`  | A pose vector or output matrix has the wrong length.                                                                                                                                                                                                                                                | `position: Float32Array(3)`, `quaternion: Float32Array(4)`, matrices `Float32Array(16)`. |
| `VGPU-CAMERA-ALIAS` | `smoothRig` got a `current` and `goal` that are the same object or share or overlap arrays, or whose `current` fields overlap each other; or two outputs of one call overlap — `view`/`viewProjection` in `viewMatrices`, `position`/`quaternion` in `rigPose`. Output-to-input overlap is allowed. | Create each rig with `orbitRig()`; give each output field its own array.                 |

### GPU bridge

| Code                      | When                                                                                                                                                                                                                                                                                                                                                     | Fix                                                                                                                                      |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `VGPU-INSTANCE-LAYOUT`    | A destroyed or unrecognized base mesh, base mesh from another `gpu`, base mesh with an instance-step buffer, an attribute name collision, or a limit exceeded (`maxVertexAttributes`, 8 buffers / `maxVertexBuffers`, 2048-byte / `maxVertexBufferArrayStride` stride, `maxBufferSize`). The message lists the names and actual versus permitted counts. | Use a live vertex-only mesh from the same gpu, rename attributes, reduce attribute width or capacity, or split into several collections. |
| `VGPU-INSTANCE-DESTROYED` | `publish()`, a draw, a bundle recording, or a bundle replay after the bridge, its composed geometry, or the base mesh was destroyed.                                                                                                                                                                                                                     | Create a new bridge on a live base mesh, then recreate the affected draws and re-record the affected bundles.                            |
| `VGPU-INSTANCE-REENTRANT` | `publish()` during `syncWorlds()`.                                                                                                                                                                                                                                                                                                                       | Finish syncing, then publish.                                                                                                            |

### Wiring errors from the draw

These come from the existing draw and `set()` validation, and are the usual symptoms of a broken connection between CPU data and your WGSL:

| Code                            | Symptom                                                                                                                                                                  | Fix                                                                                                                                          |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `VGPU-R1-BINDING-NEVER-SET`     | The draw ran before `camera` (or `lighting`) was set. The message names the binding with its `@group`/`@binding`.                                                        | Call `draw.set({ camera: { viewProjection } })` before the first draw.                                                                       |
| `VGPU-RING1-UNSUPPORTED`        | `Binding 'cam' does not exist` — the key passed to `set()` matches no WGSL binding or member.                                                                            | Use the WGSL variable name, e.g. `camera`.                                                                                                   |
| `VGPU-SET-VALUE-INVALID`        | Wrong member name, or a matrix that is not 16 values; the detail gives the value path such as `camera.viewProjection`.                                                   | Pass the reflected struct shape; `mat4x4f` takes 16 numbers.                                                                                 |
| `VGPU-MESH-ATTRIBUTE-UNMATCHED` | The shader does not declare an instance input such as `world2` or `tint`.                                                                                                | Declare every bridge attribute as a vertex input, in every shader drawn with that geometry.                                                  |
| `VGPU-MESH-INPUT-MISSING`       | The shader declares a `@location` input that neither the mesh nor the bridge provides — for example `uv` against a `box()` base, which has only `position` and `normal`. | Remove the input, add the attribute to the collection, or use a base mesh that provides it (`sphere()` has `uv`).                            |
| `VGPU-MESH-FORMAT-MISMATCH`     | An input type does not match its attribute, e.g. `pickId: f32` for a `"uint32"` attribute.                                                                               | Use `f32`/`i32`/`u32` to match `float32`/`sint32`/`uint32`. Pass integer attributes to the fragment stage with `@interpolate(flat, either)`. |
| `VGPU-R1-DRAW-COUNT`            | `instances` is not an integer `>= 0`.                                                                                                                                    | Pass the number returned by `publish()`.                                                                                                     |

## Migrate from the previous `vgpu/scene`

This release revises `vgpu/scene`. Geometry recipes (`box`, `sphere`, `plane`, …), `geometries`, `degToRad`, `srgb`, the geometry types, `group`, and `SceneNode` stay. Mesh nodes, materials, lights, camera nodes, the old `orbit`, and orbit controls are removed in favor of the explicit functions in this guide. There is no deprecated compatibility layer. The [migration lookup](/docs/guides/scene-migration) preserves historical symbol links, and `.changeset/scene-composition-utilities.md` contains the release steps; this table maps every removed export:

| Removed                                                                                                                                                                                                                                                                                               | Replacement                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `scene(options)`                                                                                                                                                                                                                                                                                      | `group(options)` — any node can be a root.                                                                                                                                                                                                                                                                                                                                                                                    |
| `mesh(geometry, material, options)`, `MeshNode`                                                                                                                                                                                                                                                       | `group(options)` for the transform, `geometry(gpu, box())` for buffers, and `draw(gpu, { shader, geometry })` with your WGSL. For many copies, an instance collection with `bindWorld(id, () => node.worldMatrix)`.                                                                                                                                                                                                           |
| `normalMaterial`, `lambertMaterial`, `unlitMaterial`, `shaderMaterial`, and their classes `NormalMaterial`, `LambertMaterial`, `UnlitMaterial`, `ShaderMaterial`, `SceneMaterial`; types `ColorMaterialOptions`, `ColorMaterialValues`, `MaterialBlend`, `SceneMaterialKind`, `ShaderMaterialOptions` | Your fragment stage and `draw(gpu, { blend })`. `lambert` from `@vgpu/wgsl-std/light` covers diffuse lighting.                                                                                                                                                                                                                                                                                                                |
| `ambientLight`, `directionalLight`, `AmbientLight`, `DirectionalLight`, and their option/value types                                                                                                                                                                                                  | A uniform you declare, e.g. `lighting: Lighting`, set with `draw.set({ lighting: { … } })`.                                                                                                                                                                                                                                                                                                                                   |
| `perspectiveCamera`, `PerspectiveCamera`, `PerspectiveCameraOptions`, `PerspectiveCameraValues`                                                                                                                                                                                                       | A `Lens` + `perspective(lens, aspect, out)`, a `Pose` (from `rigPose` or written directly), and `viewMatrices(pose, projection, out)`.                                                                                                                                                                                                                                                                                        |
| `orthographicCamera`, `OrthographicCamera`, `OrthographicCameraOptions`, `OrthographicCameraValues`                                                                                                                                                                                                   | `orthographic(bounds, out)` + `viewMatrices`.                                                                                                                                                                                                                                                                                                                                                                                 |
| `SceneCamera`, `Camera`, `CameraVec3`                                                                                                                                                                                                                                                                 | `CameraMatrices`, `Pose`, `Lens`. `camera.viewProjection` becomes `matrices.viewProjection`.                                                                                                                                                                                                                                                                                                                                  |
| `orbit(time, { radius, height, speed })` (model matrix), `OrbitOptions`                                                                                                                                                                                                                               | `composeMatrix({ position: [Math.cos(angle) * radius, height, Math.sin(angle) * radius], rotation: [0, angle, 0] }, out)` with `angle = time * speed`. The name `orbit` is now the camera function `orbit(rig, deltaYaw, deltaPitch, limits?)`.                                                                                                                                                                               |
| `orbitControls(node, options)`, `OrbitControls`, `OrbitControlsElement`, `OrbitControlsOptions`, `OrbitControlsValues`                                                                                                                                                                                | Your pointer listeners + `orbit`, `pan`, `dolly`, and `smoothRig`. `damping` (already a time constant in seconds) → `smoothRig`'s `timeConstant`; `rotateSpeed` → your radians-per-pixel factor; `zoomSpeed` → the exponent scale in your wheel handler's `dolly` factor; `target` → `orbitRig({ target })`; `distance: { min, max }` → `RigLimits.minDistance`/`maxDistance`; `pitch: { min, max }` → `minPitch`/`maxPitch`. |
| `SceneNodeKind` values `"scene"`, `"mesh"`, `"perspective-camera"`, `"orthographic-camera"`, `"directional-light"`, `"ambient-light"`                                                                                                                                                                 | Only `"group"` remains. Store application-specific classifications separately.                                                                                                                                                                                                                                                                                                                                                |

A fixed camera, before and after:

```ts illustrative
// Before
import { perspectiveCamera } from "vgpu/scene";

const camera = perspectiveCamera({ fov: 45, aspect: 16 / 9, position: [2, 2, 3], target: [0, 0, 0] });
cube.set({ camera: { viewProjection: camera.viewProjection } });
```

```ts
// After
import { orbitRig, perspective, rigPose, viewMatrices } from "vgpu/scene";

const lens = { fov: 45, near: 0.1, far: 100 }; // the old defaults, now explicit
const rig = orbitRig({
  target: [0, 0, 0],
  yaw: Math.atan2(2, 3),                  // atan2(x, z) of the old position
  pitch: Math.atan2(2, Math.hypot(2, 3)), // atan2(y, horizontal distance)
  distance: Math.hypot(2, 2, 3),
});
const projection = perspective(lens, 16 / 9, new Float32Array(16));
const matrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
viewMatrices(rigPose(rig, { position: new Float32Array(3), quaternion: new Float32Array(4) }), projection, matrices);

console.log(matrices.viewProjection); // pass to cube.set({ camera: { viewProjection: matrices.viewProjection } })
```

A camera attached to a transformed parent can remain a `group`. Invert its complete world matrix to preserve the previous camera-node behavior, including parent scale. A `Pose` contains only world position and quaternion; copying a parented node's local quaternion into it would lose the parent transform.

```ts
import { group, invertAffine, multiplyMatrices, perspective } from "vgpu/scene";

const mount = group({ position: [2, 1, 0], rotation: [0, 0.3, 0] });
const cameraNode = group({ position: [0, 0, 5] });
mount.add(cameraNode);
const projection = perspective({ fov: 45, near: 0.1, far: 100 }, 16 / 9, new Float32Array(16));
const view = new Float32Array(16);
const viewProjection = new Float32Array(16);
invertAffine(cameraNode.worldMatrix, view);
multiplyMatrices(projection, view, viewProjection);
// Repeat these two operations and your draw.set({ camera: { viewProjection } }) after changes.
```

The world transform must be invertible; zero scale throws `VGPU-SPATIAL-SINGULAR`.

Behavior differences to check while migrating:

* **Re-`set()` after every camera change.** Old camera objects updated their matrices in place; `set()` has always packed at call time, so call it again after each `viewMatrices()`.
* **`far` must be finite.** The old perspective camera accepted `far: Infinity`; `perspective` requires `0 < near < far`, all finite.
* **Pitch limits are wider.** Old orbit controls clamped to `±(π/2 − 0.01)`; the new default is `±(π/2 − 1e-4)`. Pass `{ minPitch, maxPitch }` to keep the old range.
* **Smoothing is explicit.** The old controls defaulted missing or non-finite delta time to 1/60 second, blended distance linearly, snapped within 1e-6, and returned a changed boolean. `smoothRig` requires explicit finite nonnegative seconds, blends positive distance logarithmically, returns the current rig, and has no epsilon snap or changed boolean. Keep your own settling/render policy.
* **Reuse object matrices.** The old object `orbit` allocated a new matrix; `composeMatrix` writes into your `out`.
* **Input is yours.** Nothing attaches listeners to the canvas anymore; see [Pointer input stays in your app](#pointer-input-stays-in-your-app).
* **Node quaternions are normalized** when composed, matching `composeMatrix`; a zero quaternion throws `VGPU-SCENE-VALUE`.

## What `vgpu/scene` does not do

* No renderer, material or PBR system, lights, or render loop — the helpers supply math; shading is yours.
* No automatic uniforms, reserved bind groups, or generated WGSL interfaces. Every binding is connected by name with `set()`.
* No ECS, scheduler, or imposed scene store; external systems keep their own authority.
* No culling, automatic bounds, heterogeneous batching, GPU compute-owned instances, or storage-buffer instance variant.
* No automatic capacity growth, keep-world reparenting, matrix decomposition, or partial hierarchy traversal.
* No large-coordinate precision beyond float32.

See [Draws](/docs/concepts/draws) for the `draw(gpu)` and `geometry(gpu)` basics this guide builds on, and [Two-pass rendering](/docs/guides/two-pass-rendering) for the depth target and present pass used in the complete example, or a depth [`Surface`](/docs/reference/vgpu/surface#surface) for single-pass rendering.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Using math with scene data
description: Use pmndrs/math for numerical operations and vgpu/scene for hierarchies, instances, cameras, and explicit GPU publication. Pass ordinary matrices across the boundary without a compatibility class.
---

# Using math with scene data



Use [`math` from pmndrs](https://github.com/pmndrs/math) for general numerical operations and
`vgpu/scene` for composing data into a scene. Pass math arrays directly to vgpu's array inputs;
copy vgpu's typed-array outputs into math tuples when reading them back into math. No adapter
class is required. `math` is an optional application dependency, not a vgpu runtime dependency.

## Choose who owns each operation

| Need                                                               | Use                                                                   |
| ------------------------------------------------------------------ | --------------------------------------------------------------------- |
| Vector/quaternion arithmetic, matrix decomposition, interpolation  | `math`                                                                |
| Spatial queries, springs, noise, random values, inverse kinematics | The corresponding `math` subpath, or another specialized library      |
| Parent/child relationships and world propagation                   | `group`, or `hierarchyOrder` and `evaluateHierarchy` over your arrays |
| Instance identity, packed attributes, external world matrices      | `instances`                                                           |
| Orbit/pan/dolly behavior on application-owned camera state         | The composable camera functions in `vgpu/scene`                       |
| Renderable boxes, spheres, and other mesh recipes                  | Geometry recipes in `vgpu/scene`                                      |
| Instance uploads and vertex stream layout                          | `instanceGeometry` from `vgpu/scene/gpu`                              |
| Shader-side transform math                                         | `@vgpu/wgsl-std/scene` in your WGSL                                   |

The existing `composeMatrix`, `multiplyMatrices`, `invertAffine`, `localFromWorld`, projections,
`degToRad`, and `srgb` remain supported conveniences. You can keep using them. Scene utilities do
not aim to provide a complete CPU math API, an ECS, physics, or a material system.

## Pass a math matrix into an instance

Install `math` in the application. These examples are checked against `math@0.1.0`.

```bash
npm install math@0.1.0
```

```ts
import { mat4, quat, type Vec3 } from "math";
import { instances } from "vgpu/scene";

const objects = instances({ capacity: 1 });
const objectId = objects.add();
const position: Vec3 = [2, 0, 0];
const rotation = quat.create(); // identity XYZW quaternion
const scale: Vec3 = [1, 2, 1];
const world = mat4.create(); // math's plain-array Mat4

mat4.fromRotationTranslationScale(world, rotation, position, scale);
objects.setWorld(objectId, world); // validates and copies into the instance record

position[0] = 3;
mat4.fromRotationTranslationScale(world, rotation, position, scale);
objects.setWorld(objectId, world); // repeat the copy after computing a new world
```

`setWorld` accepts `ArrayLike<number>`, so no intermediate `Float32Array` is necessary for this
call. It still copies and stores float32 data. Later changes to `world` have no effect until you
call `setWorld` again. A bound source is another option: `bindWorld(id, () => world)` followed by
`syncWorlds()` each update. Do not also call `setWorld` on a bound instance; unbind it first.

After CPU updates, call your bridge's `publish()` before encoding its consumers, and pass its
returned count to each draw. The complete setup is in [Scene composition](/docs/guides/scene-composition).

## Write local transforms into an external hierarchy

Packed hierarchy arrays must be typed arrays even when you calculate each local matrix with
`math`. Allocate them once and make the representation change explicit:

```ts
import { mat4 } from "math";
import { evaluateHierarchy, hierarchyOrder, instances } from "vgpu/scene";

const parents = new Int32Array([-1, 0]);
const order = hierarchyOrder(parents);
const locals = new Float32Array(32);
const worlds = new Float32Array(32);
const local = mat4.create();

locals.set(local, 0); // root identity
mat4.fromTranslation(local, [0, 2, 0]);
locals.set(local, 16); // child local, copied into row 1
evaluateHierarchy({ order, parents, locals, worlds }); // full initialization

const objects = instances({ capacity: 2 });
const ids = [objects.add(), objects.add()];
objects.setWorlds(ids, worlds);
```

For later updates, rewrite the affected local rows and evaluate again. If you use dirty flags,
mark changed rows yourself and fully evaluate after topology changes or replacing the output
buffer. Hierarchy evaluation trusts matrix values for speed; validate untrusted data before
writing rows. See the [hierarchy contract](/docs/guides/scene-composition#evaluate-a-hierarchy-stored-in-your-own-arrays).

If physics or an ECS already calculates final world matrices, skip vgpu hierarchy evaluation and
pass those worlds to `setWorld` or `setWorlds`. Do not multiply a parent into an already-world-space
matrix again.

## Read a vgpu matrix with math

In `math@0.1.0`, `Mat4` is a fixed-length array tuple. A vgpu `Float32Array` is not assignable to
that type, even though both contain 16 numbers. Copy into a reusable math matrix before calling
its matrix operations; do not cast away the type difference. For example, decompose a world
matrix containing translation, rotation, and positive scale:

```ts
import { mat4, quat, vec3 } from "math";
import { group } from "vgpu/scene";

const node = group({ position: [2, 0, 0], scale: [1, 2, 1] });
const matrix = mat4.create();
const rotation = quat.create();
const position = vec3.create();
const scale = vec3.create();

const world = node.worldMatrix; // borrowed vgpu output: read, do not mutate
for (let i = 0; i < 16; i++) matrix[i] = world[i]!;
mat4.decompose(rotation, position, scale, matrix);
```

Reuse these outputs and repeat the copy after the node changes. For packed hierarchy worlds,
read row `r` from `worlds[r * 16 + i]`. For a vgpu `Pose`, `vec3.fromBuffer(position, pose.position, 0)`
and `quat.fromBuffer(rotation, pose.quaternion, 0)` copy into math tuples. A sheared world matrix
cannot generally round-trip through translation/rotation/scale; preserve the original matrix when
your external system is matrix-authoritative.

## Match camera and matrix conventions

Both libraries use column-major matrices and XYZW quaternions. Keep multiplication order explicit:
`world = parentWorld * local` and `viewProjection = projection * view`.

For a camera managed outside vgpu, you can compute its entire view-projection matrix with `math`:

```ts
import { mat4 } from "math";

const projection = mat4.create();
const view = mat4.create();
const viewProjection = mat4.create();
const cameraUniform = new Float32Array(16);

mat4.perspectiveZO(projection, Math.PI / 4, 960 / 540, 0.1, 100);
mat4.lookAt(view, [0, 0, 8], [0, 0, 0], [0, 1, 0]);
mat4.multiply(viewProjection, projection, view); // math takes out first
cameraUniform.set(viewProjection); // ready for your named uniform .set()
```

Use `perspectiveZO` or `orthoZO` for WebGPU's `0..1` depth range. `math`'s perspective field of
view is in radians; vgpu's `Lens.fov` is in degrees. `math` operations take the output first,
whereas vgpu's transform conveniences take it last. Their validation and failure semantics also
differ: for example, `math`'s matrix inversion returns `null` for a singular matrix; vgpu's
`invertAffine` throws a structured error and leaves its output unchanged.

Alternatively, use vgpu camera behavior to fill a `Pose`, and pass a math projection directly
to `viewMatrices`, whose projection input accepts `ArrayLike<number>`. Keep one authority for camera
pose and one for projection; neither library subscribes to the other's mutations.

The WGSL declaration still chooses its own group and binding. After each camera update, call
your draw's named setter again, for example `drawable.set({ camera: { viewProjection: cameraUniform } })`
when the shader declares `camera.viewProjection`. Nothing in `math` or the scene helpers injects
uniforms or reserves bind groups. See
[Connect the camera to your shader by name](/docs/guides/scene-composition#connect-the-camera-to-your-shader-by-name)
for the explicit binding setup.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Scene API migration
description: Replace the previous vgpu/scene camera, mesh, material, and light API with explicit transforms, external camera state, instances, and application-owned shaders.
---

# Scene API migration



This page explains the previous scene API and its replacements. The names below are historical unless explicitly marked retained. They are not a compatibility API. Follow [Scene composition](/docs/guides/scene-composition#migrate-from-the-previous-vgpu-scene) for complete current examples and the source migration notes in `.changeset/scene-composition-utilities.md` for the release changes.

## Import

Import CPU composition from `vgpu/scene`, the optional GPU bridge from `vgpu/scene/gpu`, and shader helpers from `@vgpu/wgsl-std/scene` inside WGSL. Remove imports of the retired names below.

## Signature

The notable name reuse is `orbit`: it now takes an external rig and angular deltas. Object animation that previously passed time and radius must call `composeMatrix` instead. No renderer or material object is required by the new scene API.

## Parameters

Keep camera FOV in degrees and transform/orbit angles in radians. Supply explicit finite near/far planes and aspect, exact-sized matrices, and independent current/goal rig vectors. See the current [camera reference](/docs/reference/vgpu-scene/camera-state) for validation and defaults.

## Examples

The [composition guide](/docs/guides/scene-composition) shows nodes, external hierarchy arrays, and direct physics worlds feeding the same instance stream. `examples/by-example-s06-scene` contains executable examples and native output checks. In each path, publish instances before encoding passes and repeat named uniform `.set()` after camera matrix changes.

## Notes

Parented cameras use `invertAffine(cameraNode.worldMatrix, view)` followed by `multiplyMatrices(projection, view, viewProjection)` to preserve parent transforms and scale. See the checked migration example in [Scene composition](/docs/guides/scene-composition#migrate-from-the-previous-vgpu-scene).

Unlike the old controls, `smoothRig` requires explicit finite nonnegative delta time, blends distance logarithmically, and returns the current rig without epsilon snapping or a changed boolean. The old object `orbit` allocated its output; `composeMatrix` writes into a reusable matrix.

Bindings remain shader-owned. Existing geometry recipes, `geometries`, `degToRad`, and `srgb` remain available. Legacy material/light objects do not have a new scene equivalent; use your own data and WGSL. The following lookup preserves published documentation links while explaining each replacement.

## Camera

`Camera` is removed. Use `Pose`, `Lens`, and `CameraMatrices` for owned state and `Vec3Like` for vector inputs. The camera world position is `pose.position`; `matrices.viewProjection` reaches WGSL through explicit named `.set()`.

## SceneCamera

`SceneCamera` is removed. Use `Pose`, `Lens`, and `CameraMatrices` for owned state and `Vec3Like` for vector inputs. The camera world position is `pose.position`; `matrices.viewProjection` reaches WGSL through explicit named `.set()`.

## CameraVec3

`CameraVec3` is removed. Use `Pose`, `Lens`, and `CameraMatrices` for owned state and `Vec3Like` for vector inputs. The camera world position is `pose.position`; `matrices.viewProjection` reaches WGSL through explicit named `.set()`.

## Vec3

`Vec3` is retained. See its current [reference](/docs/reference/vgpu-scene/vec3). It no longer depends on the previous camera or scene-tree implementation.

## Mat4

`Mat4` is retained. See its current [reference](/docs/reference/vgpu-scene/transforms). It no longer depends on the previous camera or scene-tree implementation.

## orthographicCamera

`orthographicCamera` is removed. Use `orthographic(bounds, projection)` and `viewMatrices(pose, projection, matrices)`. Bounds must be finite and ordered; `0 <= near < far`.

## OrthographicCameraOptions

`OrthographicCameraOptions` is removed. Use `orthographic(bounds, projection)` and `viewMatrices(pose, projection, matrices)`. Bounds must be finite and ordered; `0 <= near < far`.

## perspectiveCamera

`perspectiveCamera` is removed. Use `Lens`, `Pose`, `perspective(lens, aspect, projection)`, and `viewMatrices`. Supply finite near/far and aspect explicitly, and repack the camera uniform after updates.

## PerspectiveCameraOptions

`PerspectiveCameraOptions` is removed. Use `Lens`, `Pose`, `perspective(lens, aspect, projection)`, and `viewMatrices`. Supply finite near/far and aspect explicitly, and repack the camera uniform after updates.

## orbit

The old time-based object orbit is removed. Use `composeMatrix` with explicit translation and rotation for object animation. The current `orbit(rig, deltaYaw, deltaPitch, limits?)` updates camera state; see [camera functions](/docs/reference/vgpu-scene/camera-state).

## OrbitOptions

The old time-based object orbit is removed. Use `composeMatrix` with explicit translation and rotation for object animation. The current `orbit(rig, deltaYaw, deltaPitch, limits?)` updates camera state; see [camera functions](/docs/reference/vgpu-scene/camera-state).

## PerspectiveCameraValues

`PerspectiveCameraValues` is removed. Use `Lens`, `Pose`, `perspective(lens, aspect, projection)`, and `viewMatrices`. Supply finite near/far and aspect explicitly, and repack the camera uniform after updates.

## OrthographicCameraValues

`OrthographicCameraValues` is removed. Use `orthographic(bounds, projection)` and `viewMatrices(pose, projection, matrices)`. Bounds must be finite and ordered; `0 <= near < far`.

## scene

Replace `scene(options)` with `group(options)`. Any group can be a root; a root has no renderer or material responsibilities.

## group

`group` is retained for material-independent group transforms. Only the `"group"` kind remains; use `.set()` for local updates and treat borrowed arrays as read-only. See [nodes](/docs/reference/vgpu-scene/nodes).

## mesh

Replace the transform with `group` or an externally owned world matrix. Keep GPU geometry and draw/shader state in the application. Use `instances` plus `instanceGeometry` for many copies of a mesh.

## MeshNode

Replace the transform with `group` or an externally owned world matrix. Keep GPU geometry and draw/shader state in the application. Use `instances` plus `instanceGeometry` for many copies of a mesh.

## SceneNode

`SceneNode` is retained for material-independent group transforms. Only the `"group"` kind remains; use `.set()` for local updates and treat borrowed arrays as read-only. See [nodes](/docs/reference/vgpu-scene/nodes).

## NodeOptions

`NodeOptions` is retained for material-independent group transforms. Only the `"group"` kind remains; use `.set()` for local updates and treat borrowed arrays as read-only. See [nodes](/docs/reference/vgpu-scene/nodes).

## NodeTransformValues

`NodeTransformValues` is retained for material-independent group transforms. Only the `"group"` kind remains; use `.set()` for local updates and treat borrowed arrays as read-only. See [nodes](/docs/reference/vgpu-scene/nodes).

## Vec3Like

`Vec3Like` is retained. See its current [reference](/docs/reference/vgpu-scene/transforms). It no longer depends on the previous camera or scene-tree implementation.

## QuatLike

`QuatLike` is retained. See its current [reference](/docs/reference/vgpu-scene/transforms). It no longer depends on the previous camera or scene-tree implementation.

## SceneNodeKind

`SceneNodeKind` is retained for material-independent group transforms. Only the `"group"` kind remains; use `.set()` for local updates and treat borrowed arrays as read-only. See [nodes](/docs/reference/vgpu-scene/nodes).

## unlitMaterial

`unlitMaterial` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## lambertMaterial

`lambertMaterial` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## normalMaterial

`normalMaterial` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## shaderMaterial

`shaderMaterial` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## SceneMaterial

`SceneMaterial` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## ColorMaterialOptions

`ColorMaterialOptions` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## ColorMaterialValues

`ColorMaterialValues` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## MaterialBlend

`MaterialBlend` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## SceneMaterialKind

`SceneMaterialKind` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## ShaderMaterialOptions

`ShaderMaterialOptions` is removed. Define application material data, WGSL shading, named uniforms, and draw pipeline options explicitly. There is no required scene material class or built-in PBR model.

## directionalLight

`directionalLight` is removed. Keep light values in application data and bind them by name to your own WGSL lighting code.

## DirectionalLightOptions

`DirectionalLightOptions` is removed. Keep light values in application data and bind them by name to your own WGSL lighting code.

## DirectionalLightValues

`DirectionalLightValues` is removed. Keep light values in application data and bind them by name to your own WGSL lighting code.

## ambientLight

`ambientLight` is removed. Keep light values in application data and bind them by name to your own WGSL lighting code.

## AmbientLightOptions

`AmbientLightOptions` is removed. Keep light values in application data and bind them by name to your own WGSL lighting code.

## AmbientLightValues

`AmbientLightValues` is removed. Keep light values in application data and bind them by name to your own WGSL lighting code.

## orbitControls

`orbitControls` is removed. Own input listeners and their cleanup in your app, accumulate deltas into a goal `OrbitRig`, and compose `orbit`, `pan`, `dolly`, and `smoothRig`. Use explicit delta time and independent current/goal state.

## OrbitControlsElement

`OrbitControlsElement` is removed. Own input listeners and their cleanup in your app, accumulate deltas into a goal `OrbitRig`, and compose `orbit`, `pan`, `dolly`, and `smoothRig`. Use explicit delta time and independent current/goal state.

## OrbitControlsOptions

`OrbitControlsOptions` is removed. Own input listeners and their cleanup in your app, accumulate deltas into a goal `OrbitRig`, and compose `orbit`, `pan`, `dolly`, and `smoothRig`. Use explicit delta time and independent current/goal state.

## OrbitControlsValues

`OrbitControlsValues` is removed. Own input listeners and their cleanup in your app, accumulate deltas into a goal `OrbitRig`, and compose `orbit`, `pan`, `dolly`, and `smoothRig`. Use explicit delta time and independent current/goal state.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Debugging shaders by extracting internal values
description: A shader has no `console.log`. Its only output is pixels, so make the pixels carry the numbers you need: render the shader's internal values into a tiny target, read them back, and compare them against a CPU reference. Use this methodology by default for any multi-pass or mathematically non-trivial shader, and immediately whenever someone reports a visual bug. Do not iterate by eye — while building the `transmission` example, two rounds of by-eye fixes changed the image without fixing it, and one extraction pass found both root bugs.
---

# Debugging shaders by extracting internal values



## 1. Split the WGSL into pure sub-modules

A debug shader should exercise the WGSL that ships. Keep broadly reused math in a pure module, but tightly coupled one-use math can stay beside the entry point. The current `transmission` example uses both shapes: reusable environment sampling lives in `env-common.wgsl`, while its transmission math stays in `glass.wgsl`.

```wgsl
// glass.wgsl
import { env_lod, sample_env } from "./env-common.wgsl";

fn dielectric_fresnel(ior: f32, facing: f32) -> f32 {
  let f0 = pow((ior - 1.0) / (ior + 1.0), 2.0);
  return f0 + (1.0 - f0) * pow(1.0 - facing, 5.0);
}

fn transmission_lod(roughness: f32, levels: f32) -> f32 {
  return pow(roughness, 0.8) * max(levels - 1.0, 0.0);
}
```

Validate the complete import graph with `npx vgpu check ./apps/docs/examples/transmission/glass.wgsl`.

For a runtime-built `effect(gpu)` debug shader, extract the binding-free prefix from the live entry shader and inline its live helper module:

```ts
import { readFileSync } from "node:fs";

const stripModuleSyntax = (source: string): string =>
  source.replace(/^import .*$/gmu, "").replace(/\bexport\s+/gu, "");

const glass = readFileSync(
  "./apps/docs/examples/transmission/glass.wgsl",
  "utf8"
);
const entryStart = glass.indexOf("\n// The glass bends rays");
if (entryStart < 0) throw new Error("Could not isolate transmission math");

const helpers = [
  readFileSync("./apps/docs/examples/transmission/env-common.wgsl", "utf8"),
  glass.slice(0, entryStart),
]
  .map(stripModuleSyntax)
  .join("\n");
```

`prepareShader()` from `@vgpu/wgsl/prepare` reflects one WGSL string for `effect(gpu)` and rejects remaining imports with `VGPU-WGSL-REFLECT-SOURCE-IMPORT`. The extraction therefore uses the exact shipped math while excluding bindings and entry points.

## 2. Encode internals as pixels

Render an 8×1 or 1×1 target where each pixel is a slot and each channel carries one internal value. Pick an encoding that survives `rgba8unorm` quantization, and keep every value in `[0, 1]`:

| Value                  | Encoding                                                   | Decode                             |
| ---------------------- | ---------------------------------------------------------- | ---------------------------------- |
| weight, Fresnel, alpha | write as-is                                                | `byte / 255`                       |
| LOD level              | `lod / (levels - 1)`                                       | `byte / 255 * (levels - 1)`        |
| direction / normal     | `dir * 0.5 + 0.5`, or `dir * 0.1 + 0.5` for unbounded rays | `(byte / 255 - 0.5) * 2` or `* 10` |
| distance, thickness    | `distance * scale` with a fixed scale                      | `byte / 255 / scale`               |

```ts
import { init, effect, target } from "vgpu/node";
import { prepareShader } from "@vgpu/wgsl/prepare";

// Reuse `helpers` extracted from the shipped shaders in step 1.
declare const helpers: string;

const gpu = await init();
const colorTarget = target(gpu, { size: [8, 1] });

// the debug WGSL is built at runtime, so prepare it once before effect()
const probeShader = prepareShader(`
  ${helpers}
  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    let slot = i32(floor(uv.x * 8.0));
    if (slot == 0) {
      // three Fresnel probes, one per channel
      return vec4f(dielectric_fresnel(1.5, 0.2), dielectric_fresnel(1.5, 0.5), dielectric_fresnel(1.5, 1.0), 1.0);
    }
    // normalized LOD: divide by levels - 1 so full roughness reaches exactly 1.0
    return vec4f(transmission_lod(0.0, 8.0) / 7.0, transmission_lod(0.5, 8.0) / 7.0, transmission_lod(1.0, 8.0) / 7.0, 1.0);
  }
`);
effect(gpu, probeShader).draw(colorTarget);

const pixels = await colorTarget.color.read({ mipLevel: 0, region: "all" });
const slot0 = [...pixels.slice(0, 3)].map((byte) => byte / 255);
console.log(slot0);
gpu.dispose();
```

Give each slot exactly one meaning and comment it. A debug shader nobody can decode is worthless the next day.

## 3. Compare against a CPU reference

Reimplement the same math in TypeScript and diff value by value. The tolerance is **`2 / 255` ≈ 0.0078** — the quantization floor of an `rgba8unorm` target. Write the comparison to JSON so the run leaves evidence behind:

```ts
import { writeFileSync } from "node:fs";

const tolerance = 2 / 255; // rgba8unorm quantization

const fresnel = (ior: number, facing: number): number => {
  const f0 = ((ior - 1) / (ior + 1)) ** 2;
  return f0 + (1 - f0) * (1 - facing) ** 5;
};

export function compare(
  reference: number[],
  pixels: Uint8Array,
  out: string
): boolean {
  const gpu = reference.map((_, index) => pixels[index] / 255);
  const maxError = Math.max(
    ...reference.map((value, index) => Math.abs(value - gpu[index]))
  );
  const pass = maxError <= tolerance;
  writeFileSync(
    out,
    JSON.stringify({ reference, gpu, maxError, tolerance, pass }, null, 2)
  );
  return pass;
}

export const reference = [
  fresnel(1.5, 0.2),
  fresnel(1.5, 0.5),
  fresnel(1.5, 1),
];
```

The original extraction run used while building `transmission` reported `maxError: 0.0019` against `tolerance: 0.0078` across Fresnel, dispersion weights, LOD selection, refracted ray direction, cube-exit distance, and eleven cone samples. `2 / 255` is only the quantization floor for values **stored** in `rgba8unorm`; for a derived or iterative quantity, set the budget from the algorithm's physical epsilon instead — for example, compare a sphere tracer's impact point after N steps over a filtered field against its hit-distance epsilon, not `2 / 255`. Exit non-zero when `pass` is false so the harness works in CI, and keep the JSON next to the PNGs as the evidence for your claim.

## 4. Dump the intermediate render targets

In a multi-pass pipeline the numbers can be right and the image still wrong, because a pass reads the wrong thing. Write **every** intermediate target to a PNG and look at them one by one:

```ts
import { writeFileSync } from "node:fs";
import { PNG } from "pngjs";
import type { Target } from "vgpu";

export async function dump(target: Target, file: string): Promise<void> {
  const [width, height] = target.size;
  const png = new PNG({ width, height });
  png.data.set(await target.color.read({ mipLevel: 0, region: "all" }));
  writeFileSync(file, PNG.sync.write(png));
}
```

### Encode HDR targets before reading

Float targets can be read directly: `target.color.read({ mipLevel: 0, region: "all" })` returns their raw texel bytes, while `target.color.readFloats({ mipLevel: 0, region: "all" })` decodes `rgba16float` and `rgba32float` into a `Float32Array` without clipping HDR values. For a displayable PNG, render an encode pass into a separate `rgba8unorm` target and read that target. Choose an encoding for the quantity: the example maps signed directions with `x * 0.5 + 0.5`; use a fixed range appropriate to distances or radiance instead.

```ts
import { init, effect, sampler, target } from "vgpu/node";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const hdr = target(gpu, { size: [64, 64], format: "rgba16float" });
const encoded = target(gpu, { size: [64, 64], format: "rgba8unorm" });

const encode = effect(
  gpu,
  prepareShader(`
  @group(0) @binding(0) var source: texture_2d<f32>;
  @group(0) @binding(1) var sourceSampler: sampler;

  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    let value = textureSampleLevel(source, sourceSampler, uv, 0.0);
    return vec4f(value.rgb * 0.5 + vec3f(0.5), 1.0); // signed direction -> [0, 1]
  }
`), // no loader in Node: prepare the WGSL once
);
encode
  .set({
    source: hdr,
    sourceSampler: sampler(gpu, { minFilter: "linear", magFilter: "linear" }),
  })
  .draw(encoded);
const pixels = await encoded.color.read({ mipLevel: 0, region: "all" });
gpu.dispose();
```

Dump each level of a blur pyramid (`pyramid-0.png` … `pyramid-7.png`), each G-buffer attachment, and the composite. During the original `transmission` investigation, its then-current pipeline used a back-face G-buffer: those historical dumps showed that the top blur levels were never selected and that exit normals followed the camera ray instead of the refracted ray. The current pipeline no longer has that G-buffer, but the lesson remains: neither bug was obvious in the final image, while both were unmistakable in the intermediates.

## 5. Keep renders deterministic

Evidence is only evidence if it reproduces byte for byte. In debug renders:

* Do not read a clock. Pass time in as a fixed constant, never `Date.now()` or `clock(gpu).time`.
* Use a fixed number of warmup frames before the frame you read, and always the same number.
* Jitter by pixel hash, never by frame index — a stable per-pixel rotation breaks up banding without changing between runs:

```wgsl
// glass.wgsl
/** Stable per-pixel rotation: breaks up rings without temporal noise. */
fn cone_rotation(pixel: vec2f) -> f32 {
  return fract(sin(dot(floor(pixel), vec2f(12.9898, 78.233))) * 43758.5453) * 6.28318531;
}
```

* Keep target sizes fixed and small. Two runs of the same harness must produce identical bytes; if they do not, fix the nondeterminism before debugging anything else.

## 6. When the host has no adapter: the Docker fallback

If `npx vgpu doctor` still fails after applying its own fixes, run the harness inside a container with a software GPU. In the vgpu repository, the development image is:

```bash
docker build -t vgpu-test-dev:ci -f infra/test-docker/Dockerfile.dev .
docker run --rm -v "$PWD:/workspace" -w /workspace -e VGPU_DOCKER_TEST=1 vgpu-test-dev:ci \
  node snippet.mjs
```

Mount an output directory (`-v "$OUT:/out"`) and have the harness write its JSON and PNGs there so the evidence survives the container. This is the vgpu repository's own Vulkan/lavapipe infrastructure. For the repository's exact visual-reference checks, use `pnpm snapshots:check`; it renders the pushed revision in CI's pinned native x64 environment. `pnpm snapshots:update` downloads unapproved candidates for review, never overwriting references automatically. Docker on another CPU architecture is not necessarily pixel-equivalent. Other projects can also use a Linux container with a compatible software Vulkan stack; Xvfb is not required.

## See also

* [The default workflow for developing shaders with vgpu](/docs/guides/shader-workflow) — the eight steps this methodology escalates from.
* [Shader diagnostics and fix-its](/docs/guides/shader-fix-its) — error codes such as `VGPU-RESOLVE-MODULE-BINDING`.
* [Getting started](/docs/guides/getting-started) — the minimal headless render-and-read loop.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Shader diagnostics and fix-its
description: Use these messages as the self-correction map for generated shader code. Prefer fixing the shader/binding shape over suppressing errors.
---

# Shader diagnostics and fix-its



## `VGPU-RESOLVE-MODULE-BINDING`

WGSL modules must be pure helpers. A module may export structs, functions, constants, and types, but it must not declare `@group(...) @binding(...)` variables. Move bindings to the entry shader:

```wgsl
// noise.wgsl
export struct NoiseConfig { seed: u32 }
export fn noise(p: vec2f, cfg: NoiseConfig) -> f32 { return f32(cfg.seed) * 0.0; }
```

```wgsl
// entry.wgsl
import { NoiseConfig, noise } from "./noise.wgsl";
@group(0) @binding(0) var<uniform> cfg: NoiseConfig;
```

## Unprepared shader input: `VGPU-SHADER-SOURCE-UNPREPARED`

`draw`, `effect`, and `compute` take only a prepared `ShaderSource` (`version: 2`), which carries the reflection they read instead of parsing WGSL. They throw this code synchronously for a raw WGSL string or a legacy `{ version: 1, wgsl, functionExports? }` artifact. A `.wgsl` import that arrives as a string — no loader configured, or a raw/URL import — lands here too.

Import static shaders through `@vgpu/wgsl/loader-vite` or `@vgpu/wgsl/loader-webpack` (see [Next.js and other bundlers](/docs/guides/nextjs)); prepare runtime WGSL once per source change with `prepareShader()`:

```ts
import { init, effect } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const tintSource = `@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.9, 0.3, 0.2, 1.0); }`;

// Before: effect(gpu, tintSource) threw VGPU-SHADER-SOURCE-UNPREPARED
const tint = effect(gpu, prepareShader(tintSource)); // prepare once, outside the frame loop
```

Upgrade a stored v1 asset with `prepareShader(legacyAsset, path)`; the object form keeps its `functionExports`.

## Artifact version mismatch: `VGPU-SHADER-SOURCE-VERSION`

The artifact's `version` is an integer vgpu does not support — usually a loader, prebuilt asset, or package from a different `@vgpu/wgsl` release than the `vgpu` runtime. The message names the received version, the supported version (`2`), and — when the artifact has one — its `producer`. Align the `@vgpu/wgsl` and `vgpu` versions, then rebuild the loader output and regenerate prebuilt assets.

## Malformed artifact: `VGPU-SHADER-SOURCE-INVALID`

The shader argument is not a string but is not a valid prepared artifact either: it is not an object, `version` is missing or not an integer, a required field (`wgsl`, `reflection`, `sourceChecksum`, `producer`) is missing, accessor-backed, or malformed, the reflection metadata is inconsistent, or `sourceChecksum` does not match `wgsl`. The structured detail gives the field `path` and the `reason`. `prepareShader()` throws the same code for input it cannot prepare.

Regenerate the artifact with a supported producer — the `@vgpu/wgsl` loaders or `prepareShader()` — and do not hand-write or edit `reflection`, `sourceChecksum`, or `wgsl` after preparation. An import that returns an object without `version` and `wgsl` means the bundler is not running a vgpu loader for `.wgsl`.

## Stage storage limits: `VGPU-LIMIT-STORAGE-VERTEX` / `VGPU-LIMIT-STORAGE-FRAGMENT`

**Symptom:** creating a draw reports that the selected vertex or fragment entry uses more storage buffers than the device grants for that stage.

**Cause:** bindings statically reached by the selected entry point count against `maxStorageBuffersInVertexStage` or `maxStorageBuffersInFragmentStage` (falling back to `maxStorageBuffersPerShaderStage` when a stage-specific property is unavailable). Unused declarations and resources used only by another stage do not count.

**Fix:** if the adapter supports it, request the reported count through `init({ requiredLimits: { maxStorageBuffersInVertexStage: count } })` or the fragment sibling. For vertex data, prefer `geometry(gpu, ...)` vertex streams where possible. Otherwise reduce the number of storage buffers reached by that stage. The error detail includes `stage`, `entryPoint`, `count`, `limit`, and the `{ name, group, binding }` bindings that were counted.

## Missing binding: `VGPU-R1-BINDING-NEVER-SET`

Every reflected binding must be set by name or covered by a claimed group. Do not rely on globals or implicit buffers.

```text
const effect = effect(gpu, postShader); // a prepared .wgsl import
effect.set({ params: { time: clock(gpu).time }, tex: target.color, samp: sampler(gpu) });
```

## Ownership flip: `VGPU-R1-OWNERSHIP-FLIP`

The first `set()` decides ownership. Plain JS values are lib-owned and updated in place. Resources (`Uniform`, storage, textures, samplers, bind groups) are user-owned. Do not switch the same binding from JS value to resource later.

```text
// Pick one from the start:
wave.set({ params: { time: 0 } });     // lib-owned
// or
wave.set({ params: sharedUniform });   // user-owned
```

## Bool host-shareable layouts

Rule of thumb: treat every bool host-shareable uniform as a `u32` in WGSL. WGSL `bool` is not a stable host-shareable uniform field for JS packing. Use `u32` and encode booleans as `0` or `1`.

```wgsl
struct Params { enabled: u32 }
```

## Bundle stale

`VGPU-R3-BUNDLE-STALE` means a bundle was recorded for a different render signature or an old bind-group/resource identity. A bundle survives resizing the target it draws onto when formats/depth/sample count match; re-record after resource identity changes, including sampling a resized target. Plain JS `set()` updates are safe because buffers are written in place.

## Manual bind-group claims

`VGPU-R4-GROUP-CLAIMED`, `VGPU-R4-GROUP-INCOMPATIBLE`, and `VGPU-R4-GROUP-VALIDATION` all point to manual bind-group ownership. Build the bind group with `draw.layout(group)` or `draw.layout(group, { dynamicOffsets: true })`, call `draw.group(group, bindGroup)`, and send dynamic offsets through `p.draw(draw, { offsets })`.

## Compute aliasing

`VGPU-R1-STORAGE-ALIASING` means a writable storage buffer is bound as both source and destination. Use `pingPongStorage(gpu)` and swap after dispatch.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: The default workflow for developing shaders with vgpu
description: Follow these eight steps in order every time you write or change a shader. Each step has one exact command and one thing to check before you move on. Do not skip a step because the shader "looks fine": every claim about pixels must come from pixels you read.
---

# The default workflow for developing shaders with vgpu



## 1. Discover the docs

```bash
npx vgpu docs ls          # top-level paths: /guides plus one entry per package
npx vgpu docs ls /guides  # every guide, by file name
```

The corpus ships inside the package, so it works offline. Subcommands: `ls`, `cat`, `grep`, `find`, `path`, `symbols`. Full reference: `npx vgpu docs cat cli.docs.md`.

## 2. Read getting started

```bash
npx vgpu docs cat getting-started.md
```

`ls /guides` lists the file as `getting-started.docs.md`; both `getting-started.md` and `/guides/getting-started.docs.md` resolve to it. This is the only page that shows the current API end to end — read it before writing any `init()` call.

## 3. Read the concepts you actually need

```bash
npx vgpu docs cat concepts-wgsl-modules.md # import/export, pure modules, resolution
npx vgpu docs cat concepts-effects.md   # fullscreen fragment work and set()
npx vgpu docs cat concepts-passes.md    # frame.pass, multi-pass work
npx vgpu docs cat concepts-frames.md    # frame batching and animation loops
```

Shader split across files: read WGSL modules. Single fullscreen shader: read effects. Anything with more than one target — blur pyramids, G-buffers, transmission — read passes and frames too.

## 4. Validate every WGSL file

```bash
npx vgpu check ./shaders/glass.wgsl
```

The command is `check`, not `wgsl`. It validates without running and prints the shader's reflection as JSON — binding names, groups, entry points — so you can confirm the names you will pass to `set()`. It exits non-zero with the validation errors when the shader is wrong. Run it on every `.wgsl` file, including pure helper modules.

## 5. Verify this machine can render

```bash
npx vgpu doctor --pretty
```

`doctor` acquires a real adapter and renders a real frame, then prints a JSON verdict. When it is unhealthy, apply the fix it prescribes literally — usually `npx vgpu install-software-renderer`, sometimes a `VK_ICD_FILENAMES` export. Re-run until it reports healthy. If it still fails after its own fixes, use the Docker fallback in [Debugging shaders by extracting internal values](/docs/guides/shader-debugging).

## 6. Render a static frame in Node and look at it

Do not open a browser to see whether a shader draws. Render one frame headless, read the pixels, and write a PNG you can open:

```ts
import { writeFileSync } from "node:fs";
import { PNG } from "pngjs";
import { init, effect, target } from "vgpu/node";
import { prepareShader } from "@vgpu/wgsl/prepare";

const width = 320;
const height = 180;
const gpu = await init();
const colorTarget = target(gpu, { size: [width, height] });

const uvShader = prepareShader(`
  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return vec4f(uv, 0.5, 1.0);
  }
`); // no loader in Node: reflect the WGSL once, up front

effect(gpu, uvShader).draw(colorTarget);

const pixels = await colorTarget.color.read({ mipLevel: 0, region: "all" });          // RGBA bytes, row-major, no padding
const png = new PNG({ width, height });
png.data.set(pixels);
writeFileSync("frame.png", PNG.sync.write(png));
gpu.dispose();                                // stops Dawn's polling so the process exits
```

Keep the target small (a few hundred pixels wide) so the loop stays fast on a CPU renderer. Assert on `pixels` when you know the expected value; open the PNG when you need to judge composition. See [Getting started](/docs/guides/getting-started) for the same pattern without PNG encoding.

## 7. Connect it to the browser when the shader ships to a browser

Port the same code to `vgpu` (not `vgpu/node`) with `surface(gpu, canvas, ...)` and drive it from `frameLoop(gpu, ...)`. Move the WGSL into a `.wgsl` file imported through the `@vgpu/wgsl` loader ([Next.js and other bundlers](/docs/guides/nextjs)) so the browser bundle ships prepared data instead of calling `prepareShader()`. Test it the way users run it, with the public API and deterministic frame submission: [Browser testing with Playwright WebGPU](/docs/guides/browser-testing).

## 8. Validate visually with agent-browser

```bash
agent-browser --session shader-check --webgpu --headed open http://localhost:3001/preview/glass
agent-browser --session shader-check --webgpu --headed wait 6000
agent-browser --session shader-check --webgpu --headed screenshot glass.png
agent-browser --session shader-check close
```

On Linux always pass `--webgpu --headed`: headless Chrome captures the canvas as black even when the render succeeded. Always check the pixels of the capture, never just its existence. Full recipe, including error-overlay checks: [WebGPU screenshots with agent-browser](/docs/guides/agent-browser-webgpu).

## Escalate to extraction, never to another guess

Stop iterating by eye and switch to numeric extraction the moment any of these is true:

* the shader is multi-pass, or composes several passes (pyramids, G-buffers, ping-pong);
* the math is non-trivial (refraction, dispersion, LOD selection, importance sampling);
* a user reports a visual bug you cannot reproduce as a single wrong number.

In those cases apply [Debugging shaders by extracting internal values](/docs/guides/shader-debugging) **from the start**, before your first fix attempt. The evidence: while building the `transmission` example, two rounds of by-eye fixes changed the image without fixing it. Encoding the shader's internals as pixels and diffing them against a CPU reference found both root bugs — a clamped blur LOD and a G-buffer storing the wrong ray's surface — in a single pass.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Shipping to production: the pre-PR checklist
description: Read before opening a PR or calling a render done. Gate correctness, measure, adopt the free performance defaults, and offer (never impose) cheaper alternatives with a number behind each one.
---

# Shipping to production: the pre-PR checklist



A render that looks right on the machine it was written on is halfway done. This guide is the last pass before a PR: it orders the checks that already exist in the other guides and says which ones to apply, which ones to propose, and which ones to skip.

## When to run it

Run it when the work is about to leave the author's hands: a PR is being opened, a branch is being handed over, or the user says the render is done and it will be deployed. Skip it, or shrink it to the correctness gates alone, when the user is prototyping, iterating on a look, or the render is throwaway. A perf review of an experiment slows the experiment without making anything ship faster.

**For agents:** do not start this checklist unprompted in the middle of design work. When you detect the finishing moment (the user asks for a PR, a commit message, a review, or says "done"), say in one line that you are running the pre-PR checks, run the gates, apply the free defaults that verify cleanly, and put everything else in a short proposal with a measurement per item. Never rewrite a working render without a number behind the change.

## 1. Correctness gates (always)

These are cheap and non-negotiable.

* **Validate every WGSL module** the change touches, including imports:

  ```bash
  npx -y vgpu check ./src/shaders/scene.wgsl
  ```

  Fix anything it reports using [Shader diagnostics and fix-its](/docs/guides/shader-fix-its) before looking at speed.
* **Run the browser tests** if the project has them, or add one for the new render following [Browser testing](/docs/guides/browser-testing). A render nobody can execute in CI regresses silently.
* **Confirm the frame is deterministic where it claims to be**: `clock(gpu).advance(dt)` for tests and thumbnails, wall clock only in the live loop ([External ticker](/docs/guides/external-ticker)).
* **Check first-frame behavior**: no `VGPU-*` errors in the console on a fresh load, and every `draw`/`effect` compiles against the target it actually renders into ([Compilation](/docs/guides/concepts-compilation)).

## 2. Measure before proposing (always)

One measurement per suspected cost, not a general "it feels slow". [Measuring](/docs/guides/measuring) says which tool answers which question:

| Question                        | Tool                                                                              |
| ------------------------------- | --------------------------------------------------------------------------------- |
| Does the first frame hitch?     | `performance.now()` around the first `frame()`; compare with and without pre-warm |
| Is CPU encoding the cost?       | Time the frame callback; compare a bundled replay                                 |
| Is a pass expensive on the GPU? | `timer(gpu)` spans, one per pass, with `"timestamp-query"`                        |
| Are bind groups churning?       | Count `set()` calls with new resource identities per frame                        |

Write the numbers down. They are the justification for every item in sections 3 and 4, and they go in the PR description.

## 3. Free defaults (apply when verified)

These change no pixels and are mechanical to verify, so apply them when the render matches the pattern and re-run section 1 afterwards. Each one is a Before/After in the [Performance playbook](/docs/guides/performance-playbook).

* **Pre-warm pipelines** with `await draw.compile(target)` for every target signature hit before the first visible frame.
* **Bundle static draws** and replay them with `p.bundles(...)`; re-record only when a sampled resource identity changes.
* **Share globals** through `uniforms(gpu)` instead of setting the same values on every draw.
* **Instance repeated geometry** instead of looping draws.
* **Skip work that did not change**: demand rendering for static scenes, a capped `fps` for ambient loops ([Frames](/docs/guides/concepts-frames)).
* **Keep heavy or optional dependencies out of the initial chunk**: dynamic `import()` after the first presented frame, as [Adaptive quality](/docs/guides/adaptive-quality) does for detect-gpu.

If applying one of these needs a structural change the author did not ask for (claiming bind groups, moving to ping-pong storage, splitting passes), it belongs in section 4 instead.

## 4. Cheaper alternatives (propose, never impose)

These trade something visible or structural for speed. List them in the PR or in the handover with the measurement from section 2 next to each, and let the human choose.

* **Smaller target formats**: `rgba16float` where `rgba32float` is not needed, `r16float` for scalar fields ([Texture-format matrix](/docs/guides/texture-formats)).
* **Lower internal resolution** for post-processing chains: bloom, blur, and SSAO rarely need full resolution.
* **Fewer passes or iterations**: merge a two-pass blur into one when the radius allows, cap iterative solvers.
* **A Low tier** when the render is continuous and always visible (hero, ambient background) and the audience includes phones or laptops on battery. The full pattern is in [Adaptive quality](/docs/guides/adaptive-quality) with its example; the smallest step is a frame-health monitor plus a DPR drop.
* **A static fallback** (poster image, CSS gradient) for `VGPU-RING1-UNSUPPORTED`, when WebGPU itself is unavailable.

Phrase each item as a one-line trade: "bloom at half resolution saves 1.8 ms of a 6.1 ms frame on this GPU; the halo softens slightly." A proposal without a number is an opinion.

## 5. Hand it over

Before opening the PR:

* The PR description lists the measurements from section 2, the defaults applied from section 3, and the alternatives offered from section 4, in that order.
* Thumbnails, snapshots, or screenshots were regenerated if the render changed ([WebGPU screenshots with agent-browser](/docs/guides/agent-browser-webgpu)).
* Anything skipped from this checklist is named, with the reason.

## See also

* [Performance model](/docs/guides/performance-model): why the defaults in section 3 are free.
* [Optimize a pass](/docs/guides/optimize-pass): the per-pass procedure once a measurement points at one.
* [Authoring shaders for performance](/docs/guides/authoring-for-perf): WGSL and JavaScript defaults that keep layouts stable.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Practical texture-format matrix
description: Choose a target format from the operations it must support, not just its channel precision. In vgpu, `format` is passed through to WebGPU for render-target capability; the API rejects a filtering binding for 32-bit float textures unless the device was initialized with `float32-filterable` support. `target.color.read({ mipLevel: 0, region: "all" })` returns raw texel bytes and `target.color.readFloats({ mipLevel: 0, region: "all" })` decodes them to f32 components, so HDR and scalar targets read back directly.
---

# Practical texture-format matrix



## Common color and scalar formats

| Format            | Render target | `sampler` with linear filtering | Readback                     | Practical use                                                                          |
| ----------------- | ------------: | ------------------------------: | ---------------------------- | -------------------------------------------------------------------------------------- |
| `rgba8unorm`      |           Yes |                             Yes | `read()` — 4 bytes/texel     | Default target; screenshots, debug probes, and LDR color.                              |
| `rgba8unorm-srgb` |           Yes |                             Yes | `read()` — 4 bytes/texel     | LDR color encoded as sRGB; do color math in linear space.                              |
| `rgba16float`     |           Yes |                             Yes | `readFloats()` — 4 f32/texel | Filterable HDR color, bloom, and lighting intermediates.                               |
| `rgba32float`     |           Yes |                   No by default | `readFloats()` — 4 f32/texel | Full-precision HDR/data; requires `float32-filterable` to bind to a filtering sampler. |
| `r16float`        |           Yes |                             Yes | `readFloats()` — 1 f32/texel | Filterable scalar data such as a height or distance field.                             |
| `r32float`        |           Yes |                   No by default | `readFloats()` — 1 f32/texel | Full-precision scalar data; requires `float32-filterable` for linear sampling.         |
| `r8unorm`         |           Yes |                             Yes | `read()` — 1 byte/texel      | Compact normalized scalar/mask data.                                                   |

`rg8unorm`, `rg16float`, `rg32float`, and the `bgra8unorm` canvas formats read back too; `read()` always hands back the raw unpadded texel bytes of the format, and `readFloats()` decodes any of them to a `Float32Array` of components (`unorm8` normalized to `[0, 1]`). Depth/stencil, packed (`rgb10a2unorm`, `rg11b10ufloat`), snorm/uint/sint, and compressed formats still throw `VGPU-CORE-UNSUPPORTED-FORMAT`.

“Render target” means the format can be requested through `target(gpu, { format })` as a color attachment in the normal WebGPU profile; use an adapter that supports the requested format and feature set. `rgba32float` is renderable even though it is not linearly filterable by default.

## Reading HDR and scalar targets

`read()` returns `Uint8Array` raw texel bytes for every supported format — 4 bytes per texel for `rgba8unorm`, 8 for `rgba16float`, 16 for `rgba32float` — with row padding removed and BGRA swizzled to RGBA. For anything but 8-bit formats, prefer `readFloats()`, which decodes half/float texels into a `Float32Array` of components and preserves values above `1` and below `0`:

```ts
import { init, target } from "vgpu/node";

const gpu = await init();
const hdr = target(gpu, { size: [256, 256], format: "rgba16float" });
// ...render into hdr...
const floats = await hdr.color.readFloats({ mipLevel: 0, region: "all" }); // 256 * 256 * 4 components, HDR values intact
console.log(floats[0]);
```

An encode pass into an `rgba8unorm` target (mapping values to `[0, 1]`, for example `direction * 0.5 + 0.5`) is still the right tool when the goal is a PNG snapshot or a byte-exact visual diff. See [Debugging shaders by extracting internal values](/docs/guides/shader-debugging) for that recipe. For formats without a readback layout, blit into a supported format first, or write the data into a storage buffer and use `StorageBuffer.read()`.

## Filtering 32-bit float textures

A texture declaration and a sampler must agree. On the default device, bind `rgba32float` and `r32float` with a non-filtering sampler and use `textureLoad`, or select a lower-precision filterable format such as `rgba16float`/`r16float`. If the adapter exposes and the application requests `float32-filterable`, linear sampling becomes valid for the 32-bit float formats.

See also: [Effects](/docs/guides/concepts-effects) for chaining targets, and [Debugging shaders by extracting internal values](/docs/guides/shader-debugging) for readback workflows.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Use WGSL modules in three.js TSL
description: Turn pure functions from vgpu-resolved WGSL modules into callable three.js TSL nodes with the vgpu/three adapter.
---

# Use WGSL modules in three.js TSL



vgpu can resolve a reusable WGSL module graph, and three.js TSL can call WGSL functions from node materials. `tslExports()` connects those pieces without taking ownership of your renderer, scene, materials, or render loop.

Use this integration when you want to author shader logic as portable WGSL modules while three.js continues to own bindings and shader entry points.

## Install

```bash
npm install vgpu three@^0.180.0
npm install --save-dev @types/three@^0.180.0 vite typescript
```

`vgpu` includes its WGSL resolver and bundler loaders, so the application does not need to install `@vgpu/wgsl` separately. The adapter loads Three only when you import `vgpu/three`.

## Configure Vite

<!-- test:three-tsl-vite-config -->

```ts
// vite.config.ts
import { wgslVitePlugin } from "vgpu/client";

export default {
  plugins: [wgslVitePlugin({ minify: true })],
};
```

`minify: true` enables whitespace and safe identifier minification. The loader keeps the authored names needed by `tslExports()` in the complete shader artifact even when the emitted WGSL uses shorter identifiers.

Type `.wgsl` imports through the client entry point:

```text
// src/vgpu-env.d.ts
/// <reference types="vgpu/client" />
```

For webpack and Turbopack configuration, see [Using vgpu with Next.js and other bundlers](/docs/guides/nextjs).

## Export pure WGSL functions

Write ordinary helper functions, then mark only the functions you want JavaScript to address with `export`:

<!-- test:three-tsl-surface-wgsl -->

```wgsl
// surface.wgsl
import { perlin3d } from "@vgpu/wgsl-std/noise/perlin";

fn surfaceField(position: vec3f, timeSeconds: f32) -> f32 {
  let samplePosition = position * 2.0 + vec3f(0.0, 0.0, timeSeconds * 0.1);
  return perlin3d(samplePosition) * 0.5 + 0.5;
}

export fn surfaceColor(position: vec3f, timeSeconds: f32) -> vec3f {
  let value = surfaceField(position, timeSeconds);
  return mix(vec3f(0.04, 0.01, 0.08), vec3f(1.0, 0.25, 0.02), value);
}

export fn surfaceRoughness(position: vec3f, timeSeconds: f32) -> f32 {
  return 0.25 + surfaceField(position, timeSeconds) * 0.55;
}
```

These are library functions, not `@vertex`, `@fragment`, or `@compute` entry points. They receive values through parameters, return a value, and declare no `@group` or `@binding` resources. Three remains responsible for the generated shader stages and bind groups.

A module does not need an import to participate. A leaf containing `export fn` goes through the same resolver path, so the loader removes the author-only `export` marker and records its public function identity.

## Create callable TSL nodes

Pass the complete `.wgsl` import to `tslExports()` and request the authored export names you need:

<!-- test:three-tsl-material -->

```ts
import * as THREE from "three/webgpu";
import type { Node } from "three/webgpu";
import { positionLocal, time } from "three/tsl";
import { tslExports } from "vgpu/three";
import surfaceModule from "./surface.wgsl";

type SurfaceInputs = {
  position: Node;
  timeSeconds: Node | number;
};

type SurfaceExports = {
  surfaceColor: SurfaceInputs;
  surfaceRoughness: SurfaceInputs;
};

const { surfaceColor, surfaceRoughness } = tslExports<SurfaceExports>(
  surfaceModule,
)("surfaceColor", "surfaceRoughness");

const inputs = {
  position: positionLocal,
  timeSeconds: time,
};

const material = new THREE.MeshPhysicalNodeMaterial();
material.colorNode = surfaceColor(inputs);
material.roughnessNode = surfaceRoughness(inputs);
```

Each returned function accepts one object keyed by the authored WGSL parameter names. Values can be Three TSL nodes or JavaScript numbers, matching `wgslFn()`.

Request functions that share a material with one selector call. `tslExports(surfaceModule)` creates one shared `wgsl()` include for the resolved module; its selector creates one small forwarding function for each positional export name.

## Add a manual TypeScript contract

The positional export names give the returned object typed properties, but a normal `.wgsl` import does not carry a file-specific TypeScript signature. By default, each callable therefore accepts any named object of Three nodes or numbers.

Defining a manual contract next to each `tslExports()` call, as in the primary example above, is the recommended practice for application code and examples. TypeScript then checks selected names and input objects against the contract you wrote. For example, omitting `timeSeconds` from the `surfaceColor()` call above becomes a type error.

The contract is a compile-time assertion; TypeScript does not compare it with the WGSL. A contract may describe the complete module while a selector requests only the subset it needs. TypeScript rejects a selected name outside the contract and does not expose unselected keys, but it cannot prove that a contract name exists in the shader. Three's general `Node` type also does not prove WGSL distinctions such as `f32` versus `vec3f`. The shader artifact and Three's shader builder remain the runtime authorities.

Use literal positional names as shown above. If names already live in an array, declare it `as const` and spread it into the selector so TypeScript preserves the exact returned keys. A union-valued name produces a union of possible result objects; narrow it with a property check such as `"surfaceColor" in selected` before calling that property.

## Keep the complete artifact

Pass `surfaceModule`, not `surfaceModule.wgsl`:

```ts
import { tslExports } from "vgpu/three";
import surfaceModule from "./surface.wgsl";

// Correct: keeps exported-function identity produced by the loader.
const { surfaceColor } = tslExports(surfaceModule)("surfaceColor");

// Avoid: this drops the resolver's authored-to-minified references.
const { surfaceColor: broken } = tslExports(surfaceModule.wgsl)("surfaceColor");
```

Identifier minification is fully supported when you pass the full artifact. The resolver records each authored export name, its authored parameter names, and the corresponding declaration name in the minified WGSL. Passing only the emitted string discards those references; that compatibility path is limited to hand-written or legacy WGSL whose identifiers have not changed.

## Export boundaries

Only direct `export fn` declarations in the resolved graph become addressable:

* Private `fn` helpers are included when needed but cannot be requested from a new loader artifact.
* Import aliases affect WGSL call sites; they do not create new public export names.
* Two reachable modules may both directly export the same authored name, but requesting that name is ambiguous. Add one uniquely named forwarding export for the Three-facing API.
* Re-export syntax is not supported.
* Top-level declarations whose names start with `_vgpu_three_` are reserved for the adapter's private forwarding functions.
* Functions must return a value. Void functions, shader entry points, resource-owning modules, and parameter or return forms that Three's `wgslFn()` cannot represent are unsupported.
* Global `enable`, `requires`, and `diagnostic` directives are unsupported because Three emits `wgsl()` includes after its own global declarations. An `@diagnostic(...)` attribute is not a module directive and is not rejected by this check; the adapter's other signature constraints still apply.

## Errors

`tslExports()` throws an error with a stable `code` when it cannot create the requested callable. Match `error.code`; no adapter-specific error class or `instanceof` contract is exported. Import the type-only `TslExportsErrorCode` union from `vgpu/three` when a helper accepts or exhaustively handles these codes.

| Code                                   | Meaning                                                                                                                                   | Fix                                                                                                                                                                                                         |
| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `VGPU-THREE-TSL-EXPORT-NOT-FOUND`      | No surviving direct export has the requested authored name.                                                                               | Fix the name, add `export` to the declaration, or ensure an entry-point graph did not prune it.                                                                                                             |
| `VGPU-THREE-TSL-EXPORT-AMBIGUOUS`      | More than one surviving direct export has that authored name.                                                                             | Add a uniquely named Three-facing forwarding export.                                                                                                                                                        |
| `VGPU-THREE-TSL-SIGNATURE-UNSUPPORTED` | The function cannot be forwarded, or the module contains a global WGSL directive.                                                         | Use a pure value-returning function with `wgslFn()`-compatible parameters and no global `enable`, `requires`, or `diagnostic` directive. `@diagnostic(...)` attributes are distinct from module directives. |
| `VGPU-THREE-TSL-SOURCE-INVALID`        | Export metadata and the emitted WGSL disagree, the final declaration cannot be read, or source uses the private `_vgpu_three_` namespace. | Rename private-namespace declarations or rebuild the WGSL artifact with matching vgpu packages; report the mismatch if it persists.                                                                         |

Errors thrown later by Three while building a material are left unchanged.

## Try the examples

Start with [Three.js WGSL modules](/examples/tsl-exports). Its source is intentionally small: one leaf WGSL module, one direct export, one `tslExports()` call, and one `MeshPhysicalNodeMaterial`.

The advanced [Lava material](/examples/three-tsl) example uses the same adapter for a larger set of material inputs and for functions that pre-bake field volumes.

Both examples keep a manual TypeScript contract beside each `tslExports()` call. Follow that pattern when adding or changing WGSL exports so TypeScript checks selections and input objects against the nearby contract; keep the contract aligned with the shader, which remains the runtime authority.

In a checkout of this repository:

```bash
pnpm --filter @vgpu/example-three-tsl test
pnpm --filter @vgpu/example-three-tsl dev
```

## See also

* [`tslExports` API reference](/docs/reference/vgpu-three/tsl-exports#tslexports) — signature, accepted sources, return value, and error contract.
* [WGSL modules](/docs/concepts/wgsl-modules) — imports, direct exports, purity, mangling, and graph emission.
* [Using vgpu with Next.js and other bundlers](/docs/guides/nextjs) — webpack, Turbopack, Vite, and `.wgsl` TypeScript setup.
* [Three.js WGSL modules](/examples/tsl-exports) — the smallest working adapter example.
* [Lava material](/examples/three-tsl) — a complete material and baking workflow.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Two-pass rendering: offscreen depth target composited to the canvas
description: Render a 3D scene into an offscreen `target(gpu, { depth: true })` and composite it onto the canvas when a later pass must sample the image; plain depth-tested 3D renders in one pass to `surface(gpu, canvas, { depth: true, msaa: true })`.
---

# Two-pass rendering: offscreen depth target composited to the canvas



Two-pass rendering draws the scene into an offscreen target, then draws that target's color onto the canvas with one full-screen effect. Use it when a later pass must sample the rendered scene: post-processing, feedback or history, or reading the image back after it presents.

3D alone does not require two passes. A surface created with `depth` owns a depth attachment, so [Draws](/docs/guides/concepts-draws) depth-test straight into the canvas:

1. **Only presenting the scene?** Render it to `surface(gpu, canvas, { depth: true, msaa: true })` in one pass.
2. **Sampling the scene afterwards?** Render it to an offscreen `target(gpu, { size, depth: true })`, then present that target's color in a second pass.

[Draws](/docs/guides/concepts-draws), [Passes](/docs/guides/concepts-passes), and [Frames](/docs/guides/concepts-frames) each describe one part of this. This guide is the copy-pasteable whole for both paths.

## Render 3D directly to the canvas

```ts
import { draw, frameLoop, geometry, init, surface } from "vgpu";
import { box, composeMatrix, orbitRig, perspective, rigPose, sphere, viewMatrices } from "vgpu/scene";
import objectShader from "./object.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;

// Both objects share shading; vertex entrypoints match their different attribute layouts.
// ---cut---
// One target: the canvas, with an owned depth24plus attachment and 4× MSAA.
const canvasSurface = surface(gpu, canvas, { depth: true, msaa: true });

const rig = orbitRig({ yaw: 0.62, pitch: 0.44, distance: 4.74 });
const pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const projection = new Float32Array(16);
const camera = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
const cubeWorld = composeMatrix({ position: [1, 0, 0] }, new Float32Array(16));
const ballWorld = composeMatrix({
  position: [Math.cos(2.1), 0, Math.sin(2.1)], rotation: [0, 2.1, 0],
}, new Float32Array(16));

const cube = draw(gpu, {
  shader: objectShader, entry: { vertex: "vs_box" },
  geometry: geometry(gpu, box({ size: 1 })), cull: "back",
});
const ball = draw(gpu, {
  shader: objectShader, entry: { vertex: "vs_sphere" },
  geometry: geometry(gpu, sphere({ radius: 0.6 })), cull: "back",
});

canvasSurface.onResize(({ width, height }) => { // fires now, then after every resize
  perspective({ fov: 45, near: 0.1, far: 100 }, width / height, projection);
  viewMatrices(rigPose(rig, pose), projection, camera);
  cube.set({
    camera: { viewProjection: camera.viewProjection },
    model: { model: cubeWorld, color: [0.95, 0.45, 0.2] },
  });
  ball.set({
    camera: { viewProjection: camera.viewProjection },
    model: { model: ballWorld, color: [0.3, 0.6, 1] },
  });
});

frameLoop(gpu, (currentFrame) => {
  currentFrame.pass({ target: canvasSurface, clear: [0.04, 0.05, 0.08, 1] }, (pass) => {
    pass.draw(cube);
    pass.draw(ball); // depth-tested against the cube, whatever the order
  });
});
```

The pass clears depth to `1` by default, the draws keep their default depth state (`write: true`, `compare: "less-equal"`), and the 4-sample color resolves into the canvas texture at the end of the pass. The shader, geometry, camera, and uniforms are all application-owned; the surface owns only its attachments and replaces them on resize.

The surface's depth and MSAA come with pass rules: with `msaa`, every surface pass must clear, because multisample attachments are discarded after each pass (`clear: false` throws `VGPU-PASS-PRESERVE-MSAA`). Encode a frame's draws into one surface pass. See [`Surface`](/docs/reference/vgpu/surface#surface) for attachment lifetimes, resize, and reading a single-sample `surface.depth`.

```wgsl
// object.wgsl
struct Camera { viewProjection: mat4x4f }
struct Model { model: mat4x4f, color: vec3f }
@group(0) @binding(0) var<uniform> camera: Camera;
@group(0) @binding(1) var<uniform> model: Model;

struct VertexOut { @builtin(position) position: vec4f, @location(0) normal: vec3f }

fn vertex(position: vec3f, normal: vec3f) -> VertexOut {
  var out: VertexOut;
  out.position = camera.viewProjection * model.model * vec4f(position, 1.0);
  out.normal = (model.model * vec4f(normal, 0.0)).xyz;
  return out;
}

@vertex fn vs_box(@location(0) position: vec3f, @location(1) normal: vec3f) -> VertexOut {
  return vertex(position, normal);
}

@vertex fn vs_sphere(
  @location(0) position: vec3f,
  @location(1) normal: vec3f,
  @location(2) uv: vec2f,
) -> VertexOut {
  return vertex(position, normal);
}

@fragment fn fs_main(@location(0) normal: vec3f) -> @location(0) vec4f {
  let light = max(dot(normalize(normal), normalize(vec3f(1.0, 1.0, 1.0))), 0.15);
  return vec4f(model.color * light, 1.0);
}
```

```wgsl
// present.wgsl
@group(0) @binding(0) var scene: texture_2d<f32>;
@group(0) @binding(1) var sceneSampler: sampler;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return textureSampleLevel(scene, sceneSampler, uv, 0.0);
}
```

## The recipe

Use two passes whenever a later pass reads the rendered scene as a texture — a post-processing chain, temporal history, or `color.read(...)` after presentation. A surface cannot be an input binding (`VGPU-SURFACE-NOT-BINDABLE`), and its color is the current canvas texture, replaced after each presentation.

```ts
import { draw, effect, frame, geometry, init, sampler, surface, target } from "vgpu";
import { box, composeMatrix, orbitRig, perspective, rigPose, sphere, viewMatrices } from "vgpu/scene";
import objectShader from "./object.wgsl";
import presentShader from "./present.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;

// Both objects share shading; vertex entrypoints match their different attribute layouts.
// Pass 2 reads pass 1's color texture and writes it to the canvas.
// ---cut---
const width = 960;
const height = 540;

// Pass 1 target: offscreen, with depth, and sampleable by later passes — a surface is not.
const scene = target(gpu, { size: [width, height], depth: true });
// Pass 2 target: the canvas the user actually sees.
const canvasSurface = surface(gpu, canvas);

const rig = orbitRig({ yaw: 0.62, pitch: 0.44, distance: 4.74 });
const pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const projection = perspective({ fov: 45, near: 0.1, far: 100 }, width / height, new Float32Array(16));
const camera = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
viewMatrices(rigPose(rig, pose), projection, camera);
const cubeWorld = composeMatrix({ position: [1, 0, 0] }, new Float32Array(16));
const ballWorld = composeMatrix({
  position: [Math.cos(2.1), 0, Math.sin(2.1)], rotation: [0, 2.1, 0],
}, new Float32Array(16));

const cube = draw(gpu, {
  shader: objectShader, entry: { vertex: "vs_box" },
  geometry: geometry(gpu, box({ size: 1 })), cull: "back",
});
cube.set({
  camera: { viewProjection: camera.viewProjection },
  model: { model: cubeWorld, color: [0.95, 0.45, 0.2] },
});

const ball = draw(gpu, {
  shader: objectShader, entry: { vertex: "vs_sphere" },
  geometry: geometry(gpu, sphere({ radius: 0.6 })), cull: "back",
});
ball.set({
  camera: { viewProjection: camera.viewProjection },
  model: { model: ballWorld, color: [0.3, 0.6, 1] },
});

// The present pass is a single full-screen effect bound to the offscreen target.
const present = effect(gpu, presentShader, {
  set: { scene, sceneSampler: sampler(gpu, { minFilter: "linear", magFilter: "linear" }) },
});

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: scene, clear: [0.04, 0.05, 0.08, 1], clearDepth: 1 }, (pass) => {
    pass.draw(cube);
    pass.draw(ball);
  });
  currentFrame.pass(canvasSurface, present);
});
```

Three things are doing the work:

* **`depth: true` on the offscreen target.** Without it the draws have no depth attachment and the two objects paint over each other in submission order. `clearDepth: 1` resets it every frame; use `clearDepth: 0` together with `depth: { compare: "greater" }` on the draw for reversed-Z in deep scenes.
* **Binding the target itself.** `set({ scene })` passes the `Target` where the WGSL declares a `texture_2d<f32>`; vgpu binds its color texture. Pair it with a `sampler(gpu, ...)` for the `sampler` binding.
* **One `frame()`.** Both passes are encoded into one command encoder and submitted once — see [Frames](/docs/guides/concepts-frames). Do not use one-shot `.draw()` calls inside a frame callback; they submit on their own and break the ordering.

Animating? Move the `frame(gpu, ...)` body into [`frameLoop(gpu, ...)`](/docs/guides/concepts-frames) and re-`set()` the model matrices from `clock(gpu).time` each tick. The targets, draws, and the present effect are all created once, outside the loop.

Camera and model matrices are ordinary application-owned arrays. Update them before the frame and call `set()` on each draw that needs the new values; mutation alone does not refresh a uniform. The shader owns both binding declarations. The normal calculation above assumes rotation and uniform scale; for nonuniform scale or shear, use `transformNormal` from `@vgpu/wgsl-std/scene` with the complete world matrix. [Scene composition](/docs/guides/scene-composition) covers that helper and external camera state.

The box supplies `position` and `normal`; the sphere also supplies `uv`. Their vertex entrypoints declare these complete layouts, even though this shader does not use UVs for shading.

## Headless / no-bundler variant

Rendering this from Node, a script, or a test instead of a browser? Everything is identical except that the second target is another offscreen target rather than a canvas surface, and you read the pixels back at the end:

```ts
import { draw, effect, frame, geometry, init, sampler, target } from "vgpu/node";
import { prepareShader } from "@vgpu/wgsl/prepare";
import { box, composeMatrix, orbitRig, perspective, rigPose, viewMatrices } from "vgpu/scene";

const objectShader = prepareShader("/* the same vertex + fragment shader as above */");
const presentShader = prepareShader("/* the same present shader as above */");
const width = 960;
const height = 540;

// ---cut---
const gpu = await init();
const scene = target(gpu, { size: [width, height], depth: true });
const output = target(gpu, { size: [width, height] });   // stands in for the canvas surface

const rig = orbitRig({ yaw: 0.62, pitch: 0.44, distance: 4.74 });
const pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const projection = perspective({ fov: 45, near: 0.1, far: 100 }, width / height, new Float32Array(16));
const camera = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
viewMatrices(rigPose(rig, pose), projection, camera);
const cubeWorld = composeMatrix({ position: [1, 0, 0] }, new Float32Array(16));
const cube = draw(gpu, {
  shader: objectShader, entry: { vertex: "vs_box" },
  geometry: geometry(gpu, box({ size: 1 })), cull: "back",
});
cube.set({
  camera: { viewProjection: camera.viewProjection },
  model: { model: cubeWorld, color: [0.95, 0.45, 0.2] },
});
const present = effect(gpu, presentShader, {
  set: { scene, sceneSampler: sampler(gpu, { minFilter: "linear", magFilter: "linear" }) },
});

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: scene, clear: [0.04, 0.05, 0.08, 1], clearDepth: 1 }, (pass) => {
    pass.draw(cube);
  });
  currentFrame.pass(output, present);
});

const pixels = await output.color.read({ mipLevel: 0, region: "all" });   // RGBA bytes — assert on them, or encode a PNG
gpu.dispose();
```

To load the two shaders from `.wgsl` files instead of inline strings in this setup, resolve them first: [Using vgpu without a bundler](/docs/guides/no-bundler).

## Do you actually need two passes?

* **One full-screen fragment shader, no geometry?** No. Pass the effect to `currentFrame.pass(canvasSurface, effect)` inside `frame(gpu, ...)` or `frameLoop(gpu, ...)` — see [Getting started](/docs/guides/getting-started).
* **Flat 2D geometry with explicit paint order?** No. Open a single pass on the canvas and draw in order, as [Passes](/docs/guides/concepts-passes) shows.
* **3D geometry that occludes itself or another object, only presented?** No. Create the surface with `{ depth: true }` — add `msaa: true` for antialiased edges — and draw in one pass, as [Render 3D directly to the canvas](#render-3d-directly-to-the-canvas) shows.
* **Post-processing, history, or sampling the scene after it renders?** Yes, and the present pass is where it goes: replace `presentShader` with your post effect, which already samples the scene texture.
* **Reading the rendered image back later?** Yes. `surface.color.read(...)` reads only the current canvas texture; render into a `Target` and read `target.color` instead.

## See also

* [`Surface`](/docs/reference/vgpu/surface#surface) — `depth` / `msaa` options, attachment lifetimes, and resize.
* [Draws](/docs/guides/concepts-draws) — why 3D geometry needs a depth attachment, plus `cull` and reversed-Z.
* [Passes](/docs/guides/concepts-passes) — the single-shader present-pass pattern used here.
* [Frames](/docs/guides/concepts-frames) — how `frame()` batches passes into one submit, and `frameLoop()` for animation.
* [Getting started](/docs/guides/getting-started) — the browser-first walkthrough this recipe extends.
* [Using vgpu without a bundler](/docs/guides/no-bundler) — loading the shaders above from `.wgsl` files.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Migrating to 0.5.0
description: Ordered upgrade paths to 0.5.0 from 0.4.x and its release candidates.
---

# Migrating to 0.5.0



This guide targets stable `0.5.0`. Choose the path matching your installed version.
Update `vgpu` and any directly installed `@vgpu/*` packages in its fixed release group to
`0.5.0`; keep the optional `@vgpu/native` companion on the same exact version as `vgpu`.
The native tooling remains beta, with the qualifications described in step 9.

## From the previous stable release

For 0.4.x projects (previous stable: 0.4.1), apply the relevant steps below. Steps 7–8 also affect
WebGPU users without native tooling; valid existing values need no shape change. Step 9 is optional.
The added CLI/MCP guides require no API or command migration; find them with `vgpu docs ls /migrations`.

### 1. Update texture creation descriptors

`texture(gpu, opts)` and `device.createTexture(opts)` accept the same core `TextureOptions` and return
the same `Texture` class. The public factory only adds ownership by `gpu`; core resources still need
their existing explicit lifecycle management. `TextureOptions` and `TextureShape` are re-exported
from `vgpu`, `vgpu/node`, `vgpu/mock` and `vgpu/core`.

#### Explicit kind and usage

In 0.4.x, standalone textures were created through core (`device` is a core `Device`):

```ts illustrative
const lut = device.createTexture({
  size: [32, 32, 32], dimension: "3d", format: "rgba16float",
  usage: ["storage_binding", "texture_binding"],
});
```

After, the same core factory accepts the explicit contract:

```ts illustrative
const lut = device.createTexture({
  kind: "3d", size: [32, 32, 32], format: "rgba16float",
  usage: ["storage_binding", "texture_binding"],
});
```

Core already required `usage`; it now rejects an empty list. Version 0.5.0 also introduces
`texture(gpu, opts)` in the main API, accepting the same options and registering ownership with `gpu`.
It is a new factory, not an existing factory whose defaults changed.

No capabilities are inferred. Add `copy_src` if you read or copy from the texture, `copy_dst` for
uploads/copies into it, and `render_attachment` for rendering into it. Empty usages are rejected.
The same change applies to direct `device.createTexture(...)` and core `pingPong(device, opts)`.

#### Spatial size and layers

| Resource | Creation shape                                           |
| -------- | -------------------------------------------------------- |
| 1D       | `kind: "1d", size: [width]`                              |
| 2D       | `kind: "2d", size: [width, height]`                      |
| 3D       | `kind: "3d", size: [width, height, depth]`               |
| Array    | `kind: "2d-array", size: [width, height], layers: count` |

Before, `[width, height, count]` without a dimension created an array. Now arrays always declare
`kind` and `layers`, and `.size` remains a 2-tuple. Replace `array.size[2]` with `array.layers`.
Volume depth remains `volume.size[2]`. For shape-agnostic code, height is `texture.size[1] ?? 1`.
Use `texture.options.kind` to narrow the options union when working with shape-specific metadata.
`.kind` is semantic; `.dimension` is retained as the derived native dimension (`"2d"` for arrays).

One-layer arrays now retain array default views. Explicit native view dimensions, `cubeView` and
`layerView` remain available. Raw `GPUDevice.createTexture` descriptors are unchanged: continue to
use native `dimension`, extent and usage bit flags at that boundary.

### 2. Separate configuration from immutable resource metadata

Only allocation details have defaults: `mipLevelCount: 1`, `sampleCount: 1`, `viewFormats: []`.
Additional mips allocate storage without generating contents. Standalone MSAA textures do not
allocate or resolve another texture automatically. Alternate compatible view formats require explicit
opt-in; no conversion is performed. Public and core factories expose the same fields.

Descriptors and nested arrays are copied and frozen. Mutating the input object no longer changes
resource metadata or the options used by later pair resizes. Update application configuration separately;
do not mutate `texture.options`, `.size`, `.usage` or `.viewFormats`.

Core preflight rejects malformed shapes, unsupported usage names, invalid mip/sample combinations,
incompatible view formats, exceeded enabled limits and storage formats lacking enabled capabilities.
Native WebGPU remains authoritative for complete per-format and backend validation. These failures
are not silently converted into another allocation or usage set.

### 3. Replace standalone textures instead of resizing them

`Texture.resize()` and its resize-lock machinery are removed. Texture allocation and resource identity
do not change during its lifetime. Replace a standalone texture explicitly:

```ts illustrative
const previous = image;
image = texture(gpu, {
  kind: "2d", size: [width, height], format: "rgba8unorm",
  usage: ["texture_binding", "copy_dst"],
});
post.set({ src: image });
previous.destroy();
```

Re-upload/copy contents as needed; replacement never preserves them implicitly. Destroying a wrapper
invalidates views and bindings. External wrappers never destroy the native resource owned by another
library or swapchain. The obsolete `VGPU-CORE-EXTERNAL-TEXTURE`/`VGPU-CORE-TEXTURE-RESIZE-LOCKED`
resize errors disappear with the method.

Targets retain synchronous `resize(size): void`; core texture pairs retain `resize(size): boolean`.
Each prepares its complete replacement before committing it. Synchronous preparation failure cleans
partial allocations and preserves the old size, attachments/halves, contents and pair parity. Successful
texture-pair replacement resets orientation and discards both halves' contents. Array layers and the
creation format/usage/mip/sample settings stay fixed. An unchanged valid size is a no-op.

These are bounded preparation guarantees: late native GPU errors still use normal device reporting and
do not roll back. Callback errors occur after commit; they do not restore old attachments, and cleanup
and remaining notifications still run. Offscreen targets reject recursive resize from replacement
callbacks and reject all resize calls after destruction. Buffer-pair behavior is outside this checkpoint.

### 4. Rebind replacements and recreate affected bundles

```ts illustrative
// Automatically follows successful Target attachment replacement:
post.set({ src: scene });
scene.resize([width, height]);

// Explicit attachment reference: rebind after replacement:
post.set({ src: scene.color });
scene.resize([width * 2, height * 2]);
post.set({ src: scene.color });

// Core texture pairs also require explicit rebinding after replacement:
if (pair.resize([width, height])) {
  fill.set({ dst: pair.write });
  post.set({ src: pair.read });
  // Reseed before using the new contents.
}
```

Using a destroyed tracked texture in `set`, draw or compute dispatch now fails with
`VGPU-R1-BINDING-DESTROYED`, naming the binding and resource. This includes retained old target
attachments and pair halves. Rebinding a live replacement recovers ordinary rendering. Bundles freeze
their commands/resources: they become `VGPU-R3-BUNDLE-STALE` and must be recorded again, even if
the Draw has since been rebound.

Raw `GPUTextureView`/native bind groups have no tracked parent in this API. Direct native destruction
also bypasses wrapper signals. Native WebGPU remains the validation fallback; no managed-view or raw
view lifetime guarantee is added here.

### 5. Select the attachment, mip and region for readback

Both fields are mandatory. Select the attachment first; `Target.read`, `Target.readFloats`,
`Surface.read` and `Surface.readFloats` have been removed. Buffer reads are unchanged.

```ts illustrative
// Before
const pixels = await output.read();
const values = await volume.readFloats();

// After
const pixels = await output.color.read({ mipLevel: 0, region: "all" });
const values = await volume.readFloats({ mipLevel: 0, region: "all" });
const normals = await gbuffer.colors[1].readFloats({ mipLevel: 0, region: "all" });

// Read a crop from one allocated mip. Coordinates are mip-relative texels.
const crop = await volume.readFloats({
  mipLevel: 1,
  region: { origin: [2, 3, 1], size: [4, 5, 2] },
});
```

`TextureReadOptions` is shared by core and public entrypoints. `region: "all"` means the whole
selected mip, including **every** array layer or 3D slice (previously reads copied only the first slice).
To retain that previous selection, use `region: { origin: [0, 0, 0], size: [width, height, 1] }`.
Width/height/depth shrink at each 3D mip; array layers never shrink. Results are tightly packed:
X fastest, then Y, then Z; no row or slice padding remains.

Declare `copy_src` at creation, including for mocks. Invalid/missing mip or region, non-integer or
out-of-bounds coordinates, missing usage, multisampling and oversized allocations fail before staging
allocation with `VGPU-CORE-TEXTURE-READ-INVALID`. No clipping or implicit resolve occurs; read an
MSAA Target's resolved `.color` attachment instead of its multisampled texture. Allocation checks
cover the device's `maxBufferSize` and a portable host byte limit of `2^32 - 1`; decoded float sizes
are also checked. Read smaller regions when necessary.

Formats and conversion semantics are unchanged: `read` returns raw bytes (BGRA swizzled to RGBA),
`readFloats` widens half/float components and normalizes unorm8 without sRGB decoding. Unsupported
depth, compressed, packed and integer formats still fail with `VGPU-CORE-UNSUPPORTED-FORMAT`.
Mock storage now distinguishes allocated mips and slices; nonzero-mip uploads are supported.

### 6. Provide Vulkan for Node/Linux deployments

Linux now selects Vulkan even when X11 or Wayland is configured. Existing code stays the same:

```ts illustrative
import { init } from "vgpu/node";
const gpu = await init(); // Vulkan on Linux; other platforms retain their existing defaults.
```

If your Linux environment previously depended on automatic OpenGL selection, install a hardware
Vulkan driver or use the existing portable CPU-renderer installer:

```bash
npx vgpu install-software-renderer
```

Auto mode may use that installed renderer if normal discovery fails. It does not silently switch to
OpenGL or download drivers. A missing adapter produces `VGPU-NODE-NO-ADAPTER` with remediation.
An explicit override remains available for legacy uses:

```bash
VGPU_DAWN_FLAGS=backend=opengl node render.mjs
```

That opt-in retains Dawn's restricted-mip-view/storage-write bug (392121637). macOS, Windows,
browser WebGPU and the compatibility feature level are unchanged. For the pinned Linux Vulkan
reference environment and comparison policy, see [Visual snapshots](https://github.com/vercel-labs/vgpu/blob/v0.5.0/docs/visual-snapshots.md).

### 7. Regenerate reflected host layouts and authored module metadata

If you cache reflection or pack buffers yourself, discard metadata produced with
`layoutMode: "naga-standard"`. The replacement is `"wgsl-host-shareable-v1"`, using intrinsic
WGSL alignment, sizes, offsets and strides rather than implicit uniform-only padding.
Read address space from the binding; `HostShareableLayout.addressSpace` has been removed.

```ts illustrative
// Before
const space = binding.layout.addressSpace;
if (binding.layout.layoutMode === "naga-standard") useCachedUniformOffsets();

// After
const space = binding.addressSpace;
if (binding.layout?.layoutMode === "wgsl-host-shareable-v1") {
  useReflectedOffsetsAndStrides(binding.layout);
}
```

Address-space validation does not rewrite layout bytes. Replace implicit uniform padding with
explicit WGSL alignment/size and revalidate. Recompute cached offsets, strides and buffer sizes
before uploads. Custom `f16` packers and byte snapshots now use round-to-nearest, ties-to-even.

Handwritten `WGSLModule` objects require `entryPointDeclarations`: authored names, stages and
spans with 1-based lines/UTF-16 columns and exclusive ends. Use `[]` only without entry points.
Resolver-produced modules already supply these. Captured-source-graph APIs are additive.

### 8. Supply complete, correctly shaped JavaScript-owned binding values

Review initial values and updates passed to `effect`, `draw`, `compute` and shared `uniforms`.
Numeric scalars must be numbers, and `i32`/`u32` must be integers in their respective ranges;
string coercion, integer truncation and wrapping are no longer accepted. Vectors, column-major
matrices and fixed arrays require exact component/element counts in arrays or typed arrays.
Structs require every reflected member, including explicit shader padding, with no unrelated
fields. Select shader fields instead of passing a larger settings object.

```ts illustrative
// WGSL: struct Params { gain: f32, tint: vec3f }
// Before: coercion, short vectors and extra fields were tolerated.
shader.set({ params: { gain: "1", tint: [1], debug: true } });

// After: complete initial value, then a valid partial update.
shader.set({ params: { gain: 1, tint: [1, 0, 0] } });
shader.set({ params: { gain: 0.5 } });
```

Direct struct updates shallow-merge with the existing binding value; shared uniforms deep-merge
plain objects. The resulting candidate must be valid. Initial direct struct values must be
complete; member shorthand instead starts from reflected zero values when no previous value
exists. Preserve partial updates for animation/resizing, and initialize resolution/texel-size
values from the actual render target dimensions.

Invalid candidates throw `VGPU-SET-VALUE-INVALID` with `reason`, `path`, `expected`, `actual`
and, where applicable, scalar `type`. Validation rejection preserves that binding's previous
accepted values, bytes and ownership. Initial shared values are checked when the first shader
adopts their layout, not when `uniforms(...)` is created.

There is **no global atomicity**: `set({ a, b })` can update `a` before `b` fails.
Separate member-shorthand keys are also sequential, even for one binding. Arbitrary GPU
errors do not roll back.

### 9. Opt into the native beta only when generating Swift/Metal packages

Existing WebGPU projects do not need `@vgpu/native`. To adopt the build-time companion,
install matching, exact versions as development dependencies:

```bash
npm install --save-dev --save-exact vgpu@0.5.0 @vgpu/native@0.5.0
```

Replace the empty `@vgpu/native@0.0.1` name reservation with `0.5.0`; it has no API or outputs
to migrate. This beta supersedes intermediate private-companion documentation. Use `vgpu native`
commands, not direct imports of the internal TypeScript generator.

Prepare an Apple Silicon build host with Node.js 22 and Xcode plus its Metal compiler component.
Follow the [native configuration guide](/docs/native/macos/metal/tooling/configuration)
to create `vgpu.native.json`. The package bundles the pinned Tint worker, schemas, helper sources
and license notices; consumers do not build or download Tint at installation.

The worker is ad hoc signed, **not** Developer ID signed or notarized. Validate it in your own
environment without disabling system security. This beta does not qualify Intel GPU support,
a minimum-macOS matrix or general end-user distribution. APIs, generated Swift interfaces,
configuration and toolchain requirements may change; pin versions and review upgrades.
Only generated Swift and compiled Metal resources belong in the consuming app. Node, Tint
and Xcode are build-time requirements, not shipped runtime dependencies.

## From release candidates

### From 0.5.0-rc.0

The texture contract and Vulkan default above already shipped in `0.5.0-rc.0`. If your project
has adopted that RC, **skip steps 1–6** and apply steps 7–8 for reflection and strict host values.
These changes first shipped in `0.5.0-rc.1`, including for browser/WebGPU users. Apply step 9 only if
opting into native generation. If you installed rc.0 without adapting the application, first
complete the applicable texture/Linux steps from the stable-origin path.

The CLI/MCP guides added in rc.1 need no application or command changes. The independent native
bootstrap follows step 9, not the RC0 path.

### From 0.5.0-rc.1

Update package versions to `0.5.0`, including both exact dependencies in step 9 for native users.
No additional API, shader, binding-value or configuration migration is required: stable retains
rc.1's implementation and defaults. Keep already-applied adaptations; if any remain incomplete,
follow your original stable or RC0 path. Native tooling remains beta with the same qualifications;
regenerate and verify output with `0.5.0` so its version metadata matches.

The two published RCs above require no reversals. Run the regression checks below.

## Verification

1. Typecheck the updated project. Confirm descriptors use `kind`, arrays have separate `layers`,
   and texture reads select an attachment plus explicit `mipLevel` and `region`.
2. Exercise resizing and replacement. Recreate raw views and bundles, rebind replacement textures,
   and re-upload contents; confirm no disposed attachment or pair half is reused.
3. Test mip-relative crops and array/volume readback on the target backend. Confirm whether the
   application expects all layers/slices or only the first, and select the region accordingly.
4. On Linux, run the project-local `vgpu doctor` and the application's GPU tests. Verify the selected
   backend and storage writes/readback at nonzero mip levels. Test the installed CPU-renderer fallback
   separately if the deployment relies on it.
5. Typecheck reflection consumers and handwritten `WGSLModule` objects. Recompute host-layout
   fixtures, compare offsets/strides/buffer sizes and check halfway `f16` rounding.
6. Exercise complete values, valid partial updates, wrong vector/matrix/array sizes, missing/extra
   fields and out-of-range integers. Confirm a rejected binding keeps its previous values and
   bytes, and that callers do not assume global atomicity. Run affected render and compute paths.
7. For native opt-in, outside the vgpu checkout run the project-local `vgpu native doctor`,
   `check`, `build` and `verify`. Build a Swift consumer of the output, relocate it and execute
   the intended compute/render programs on the target GPU. Check that the app bundle does not
   contain Tint or a JavaScript runtime introduced by this tooling. Validate your own build/CI
   environment; local qualification is not a clean-OS or broad compatibility claim.

RC adopters should run the same regression checks without repeating already-applied migrations.
Code blocks marked illustrative show partial/historical usage, not standalone typechecked programs.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Migrating to 0.6.0
description: Upgrade from 0.5.0 or earlier 0.6.0 candidates to prepared shaders, explicit scene state and validated resource lifetimes.
---

# Migrating to 0.6.0



This guide targets stable `0.6.0`. Update `vgpu` and any
directly installed packages in its fixed release group to the same version:
`@vgpu/core`, `@vgpu/wgsl`, `@vgpu/wgsl-std`, `@vgpu/adapter-node`,
`@vgpu/adapter-mock`, `@vgpu/render` and the optional `@vgpu/native` companion.

```bash
npm install --save-exact vgpu@0.6.0
# If the app imports WGSL tooling, runtime preparation or WGSL types directly:
npm install --save-exact @vgpu/wgsl@0.6.0
# Only if the project already uses native generation:
npm install --save-dev --save-exact @vgpu/native@0.6.0
```

The native companion remains beta with the same toolchain and platform qualifications as
`0.5.0`. Regenerate and verify native output with the matching version. No new native
configuration or generated Swift API migration is required by this release.

Choose the path matching the version your project actually uses:

| Starting version             | Path to `0.6.0`                                                                                                              |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `0.5.0`                      | Follow the applicable stable-origin steps below. Start with shaders before adapting scene or frame code.                     |
| `0.6.0-rc.0`                 | Follow steps 1 and 6, then the RC verification notes. Keep the other adaptations already completed.                          |
| `0.6.0-rc.1`                 | Update matching packages and rebuild. No additional API migration; verify the encode and index-upload fixes described below. |
| `0.6.0-rc.2`                 | Update matching packages and rebuild. No runtime API or behavior changes since this candidate.                               |
| Earlier stable or `0.5.0` RC | Complete the applicable [0.5.0 migration](/docs/migrations/0.5.0), then follow the `0.5.0` path here.                        |

## From the previous stable release

For projects on `0.5.0`, apply the steps relevant to the APIs they use. Projects on an
older stable first apply the [0.5.0 migration](/docs/migrations/0.5.0), then this guide.
This is a pre-1.0 release with compatibility changes; it is not a drop-in update for
every existing scene or frame callback.

Use this checklist to find the steps that affect your application:

| Existing usage                                                                            | Required review                                                |
| ----------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `draw`, `effect` or `compute` shader inputs; WGSL loaders or cached assets                | Step 1: prepared shaders and a matching loader.                |
| Scene meshes/materials/lights, camera nodes, controls or object `orbit()`                 | Step 2: explicit scene and camera state.                       |
| Multiple entries in a shader, or a `Surface` used as an input binding                     | Step 3: entry selection and offscreen inputs.                  |
| Compute preparation, async frame callbacks or uniforms changed between commands           | Step 4: compilation, synchronous encoding and captured values. |
| Recovery through global frame-loop errors or direct device disposal                       | Step 5: `gpu.lost` and wrapper teardown.                       |
| Binding error handlers, buffer ranges, storage aliases or consumers shared across bundles | Step 6: validation and bundle ownership.                       |
| `canvasMouseTracker`                                                                      | Step 7: explicit coordinate spaces.                            |

The new instance bridge, Surface depth/MSAA and explicit consumer disposal are optional.
Adopt them only where needed; the relevant steps distinguish additions from required changes.

### 1. Prepare shaders before creating renderer consumers

Both `0.5.0` and `0.6.0-rc.0` accepted WGSL strings and v1 loader artifacts.
`draw()`, `effect()` and `compute()` now require prepared `ShaderSource` v2 objects.
Upgrade the loader and renderer together, and declare `@vgpu/wgsl@0.6.0` directly
in any app that imports its tooling or runtime helpers. Isolated package managers do not
make transitive tooling imports available. Build environments must install that dependency.

| Shader source or bundler                                | Upgrade action                                                                                              |
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| Static `.wgsl` through Vite                             | Keep `wgslVitePlugin` and rebuild with the upgraded packages. Pass the import itself, not `.wgsl`.          |
| Static `.wgsl` through webpack                          | Keep `@vgpu/wgsl/loader-webpack` and rebuild with the upgraded packages.                                    |
| Next.js with Turbopack                                  | Replace the handwritten `"*.wgsl"` rule with `wgslTurbopackRule()` from `@vgpu/wgsl/next`, then rebuild.    |
| Prebuilt/committed/third-party JS or JSON shader assets | Regenerate at their source; application loaders do not process assets that bypass them.                     |
| WGSL generated or loaded at runtime                     | Call `prepareShader()` once per source revision, before constructing consumers and outside frame callbacks. |

#### Rebuild static shaders and preserve valid caches

For Turbopack, after installing the upgraded tooling, replace only the WGSL rule and keep
other settings and wrappers. Move existing `minify` options into the helper argument:

```ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

export default {
  turbopack: {
    rules: { "*.wgsl": wgslTurbopackRule() },
  },
};
```

The helper fingerprints the installed compiler in loader options, so a restored `.next/cache`
can remain. Restart `next dev` after compiler upgrades or rebuilds. If retaining the old bare-string
Turbopack rule, clear that app's `.next/cache` once after upgrading instead. The helper configures
Turbopack only: preserve the webpack hook for webpack mode (`next build --webpack` on Next 16,
or omit `--turbopack` on Next 15.5). Stable Next 15.5 does not support Turbopack persistent caching.

Webpack and Vite need no routine cache deletion. Clear the affected cache only if stale v1 output
persists; webpack also needs a one-time clear for an installed managed package replaced in place
at the same version and resolved loader path. Rebuilding the application does not upgrade
prebuilt shader assets that bypass these loaders.

Leaf WGSL files now undergo reflection during the build. Fix reported parse/layout errors,
including host-unshareable `bool` uniform members. Loaders still do not validate against a
GPU device; keep `vgpu check --require-validation` in your validation workflow.

#### Prepare runtime and legacy inputs explicitly

Before:

```ts illustrative
const post = effect(gpu, sourceText);
const scene = draw(gpu, { shader: resolved.wgsl });
```

After:

```ts illustrative
import { prepareShader } from "@vgpu/wgsl/prepare";
import postShader from "./post.wgsl";

const post = effect(gpu, postShader); // prepared by the build-time loader
const dynamic = effect(gpu, prepareShader(sourceText, "dynamic.wgsl"));
const scene = draw(gpu, { shader: prepareShader(resolved, "scene.wgsl") });
const legacy = effect(gpu, prepareShader(legacyAsset, "legacy.wgsl"));
```

Pass the complete `resolveShader()`/`compile()` result or legacy object to preserve
`functionExports`. `compile()` and `reflectSource()` retain their string contracts; their
outputs are not automatically renderer inputs. Native `createShaderModule({ code })` and
`vgpu/three` keep their existing string/legacy contracts.

Runtime preparation includes the parser in that consumer and reparses on every call. Prefer
static `.wgsl` imports for static shaders; they need no browser `prepareShader()` call or
manual metadata decoder configuration. Compact loader output preserves the same v2 contract.

Prepared loader/helper artifacts are deeply frozen. Keep application tags/caches in separate
objects or a `WeakMap`; modifying the artifact throws in strict mode. Rebuild or prepare a new
artifact when source changes, and never hand-edit reflection or checksums. Deeply immutable
artifacts share validation snapshots across consumers/devices. Mutable clones remain accepted
but are revalidated per creation; a shallow spread still shares frozen nested objects.
The checksum detects accidental WGSL replacement, not authenticity or reflection correctness.

Raw strings/v1 artifacts throw `VGPU-SHADER-SOURCE-UNPREPARED`; other integer versions throw
`VGPU-SHADER-SOURCE-VERSION`; malformed or inconsistent data throws `VGPU-SHADER-SOURCE-INVALID`.
Fix the producing toolchain or prepare the original source instead of editing the version field.

### 2. Replace scene object and camera authoring

Geometry recipes, `geometries`, `degToRad`, `srgb`, geometry types, `group` and
`SceneNode` remain. Scene composition now supplies transforms, camera matrices and
instance data to application-owned shaders and draws.

| Previous export or usage                                                                                                                           | Replacement                                                                                                                                   |
| -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `scene()`                                                                                                                                          | `group()` as the root.                                                                                                                        |
| `mesh()`, `MeshNode`                                                                                                                               | A `group` or external world matrix, plus explicit `geometry()` and `draw()`. Use `instances()` and `instanceGeometry()` for repeated objects. |
| `SceneMaterial`, `UnlitMaterial`, `LambertMaterial`, `NormalMaterial`, `ShaderMaterial`, their lowercase factories and material option/value types | Application WGSL, pipeline options and named bindings. There is no replacement material object.                                               |
| `AmbientLight`, `DirectionalLight`, their lowercase factories and option/value types                                                               | Application light data passed to the shader.                                                                                                  |
| `PerspectiveCamera`, `perspectiveCamera` and their option/value types                                                                              | `Lens`, `Pose`, `perspective()` and `viewMatrices()`.                                                                                         |
| `OrthographicCamera`, `orthographicCamera` and their option/value types                                                                            | `orthographic(bounds, out)` and `viewMatrices()`.                                                                                             |
| `Camera`, `SceneCamera`, `CameraVec3`                                                                                                              | `Pose`, `Lens`, `CameraMatrices`, and `Vec3Like` or `ArrayLike<number>`.                                                                      |
| `OrbitControls`, `orbitControls` and their element/option/value types                                                                              | Application input listeners, `orbitRig()`, `orbit()`, `pan()`, `dolly()`, `smoothRig()` and `rigPose()`.                                      |
| `orbit(time, options)`, `OrbitOptions`                                                                                                             | `composeMatrix()` for object animation. The new `orbit(rig, deltaYaw, deltaPitch, limits?)` changes a camera rig.                             |
| Other `SceneNodeKind` values                                                                                                                       | Only `"group"` remains; keep application classifications separately.                                                                          |

#### Keep transforms independent of geometry and materials

Before:

```ts illustrative
const root = scene();
root.add(mesh(box(), normalMaterial(), { position: [1, 0, 0] }));
const model = orbit(time, { radius: 2, height: 0.5, speed: 0.3 });
```

After:

```ts
import { composeMatrix, group, instances } from "vgpu/scene";

const root = group();
const object = group({ position: [1, 0, 0] });
root.add(object);
const objects = instances({ capacity: 100 });
const id = objects.add();
objects.bindWorld(id, () => object.worldMatrix);
object.set({ position: [2, 0, 0] });
objects.syncWorlds();

const model = new Float32Array(16);
function animateObject(time: number) {
  const angle = time * 0.3;
  composeMatrix({
    position: [Math.cos(angle) * 2, 0.5, Math.sin(angle) * 2],
    rotation: [0, angle, 0],
  }, model);
}
```

`composeMatrix()` writes into reusable output; it does not allocate the old orbit matrix.
Keep radius, height and speed in application state, including a zero radius when intended.
Change borrowed node vectors through `.set()` rather than mutating them. Reparenting preserves
the local transform. `visible` remains metadata and does not suppress a draw or instance.
Nonzero quaternions are normalized; zero quaternions and non-finite node values throw
`VGPU-SCENE-VALUE`.

Instance capacity is fixed. Growing it requires a new collection and GPU bridge, copied
application data, restored world bindings and replacement handles/draws. Handles remain stable
only during an instance's lifetime; removal can move dense slots. Keep picking mappings in
application state and do not serialize `InstanceId` values.

External hierarchies can use `hierarchyOrder()` and `evaluateHierarchy()` with finite affine
local matrices. Rebuild the order after changing parents and fully evaluate after topology or
world-output replacement/reset. Dirty flags reduce matrix recomputation, not traversal, and
remain caller-owned. Physics with final world matrices can call `setWorlds()` directly.
If a bound `syncWorlds()` source throws, earlier results may already be copied: abort the frame
and repair/retry or unbind those sources before publishing.

#### Own camera state and repack camera uniforms

Before, a camera object carried projection and view state:

```ts illustrative
const camera = perspectiveCamera({ fov: 45, aspect, position: [2, 2, 3] });
camera.set({ aspect });
drawable.set({ camera: { viewProjection: camera.viewProjection } });
```

After, supply the lens, world pose and output matrices explicitly:

```ts
import { group, perspective, viewMatrices } from "vgpu/scene";

const eye = group({ position: [2, 2, 3] });
const lens = { fov: 45, near: 0.1, far: 100 };
const pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const projection = new Float32Array(16);
const matrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };

function updateCamera(aspect: number) {
  eye.lookAt([0, 0, 0], [0, 1, 0]);
  pose.position.set(eye.worldPosition);
  pose.quaternion.set(eye.quaternion); // eye is unparented: its local pose is world space
  perspective(lens, aspect, projection);
  viewMatrices(pose, projection, matrices);
}
updateCamera(16 / 9);
```

Repeat `drawable.set({ camera: { viewProjection: matrices.viewProjection } })` after every
matrix update. Uniform `.set()` packs immediately; previous calls do not retain live matrix
arrays. The shader owns the resource name and binding location; scene reserves no bind group.

For a parented camera, preserve the full old world transform, including parent scale, by
inverting `cameraNode.worldMatrix` with `invertAffine()` and multiplying projection by view
with `multiplyMatrices()`. A `Pose` contains world position/quaternion only; copying a
parented node's local quaternion loses the parent transform. Zero scale is not invertible
and throws `VGPU-SPATIAL-SINGULAR`.

Choose the old defaults (`near: 0.1`, `far: 100`, `aspect: 1`) explicitly if required.
Perspective requires finite `0 < near < far`, positive finite aspect and FOV in degrees
strictly between 0 and 180. Replace infinite far planes with a finite distance. Orthographic
bounds require finite `left < right`, `bottom < top`, and `0 <= near < far`; formerly accepted
mirrored bounds now throw `VGPU-CAMERA-VALUE`. Supply your own projection to `viewMatrices()`
when a mirrored projection is intentional. Both helpers use right-handed −Z view space and
WebGPU depth 0..1.

For input, create independent goal/current rigs. Apply events to the goal; call
`smoothRig(current, goal, dt, { timeConstant })` with finite nonnegative seconds, then
`rigPose()`. Remove input listeners on teardown. Smoothing uses logarithmic distance,
returns the current rig, and has no epsilon snap or changed boolean. It no longer substitutes
1/60 for missing/non-finite `dt`; implement your own settling policy. A zero time constant
snaps even at zero `dt`; otherwise zero `dt` leaves the current state unchanged. The default
pitch range is ±(π/2−1e−4); pass explicit limits to retain the old ±(π/2−0.01) range.
`dolly()` changes distance; `zoom()` changes the lens.

#### Publish instance data before encoding its consumers

Import `instanceGeometry` from `vgpu/scene/gpu`; it borrows a live, non-instanced mesh from
the same GPU. Declare four world columns and all custom instance attributes in each consuming
vertex entry. A world matrix costs four attributes and 64 bytes per record, in addition to
custom 32-bit attributes. Respect device limits, the eight-buffer limit and 2048-byte stride;
split batches or reduce attributes/capacity on `VGPU-INSTANCE-LAYOUT`.

```ts illustrative
objects.syncWorlds(); // or objects.setWorlds(ids, finalWorlds)
const count = bridge.publish();
drawable.set({ camera: { viewProjection: matrices.viewProjection } });
frame(gpu, f => f.pass(screen, pass => pass.draw(drawable, { instances: count })));
```

`publish()` does not update camera/world sources and returns an explicit count, including zero.
Unchanged publication uploads no instance bytes; separate bridges track uploads independently.
Record the count explicitly in bundles and re-record when it changes. Publish before all passes
that consume those bytes. Do not rewrite a buffer while earlier consumers remain unsubmitted;
distinct per-pass contents require separate buffers. Later queue-ordered frames need no idle wait.

Destroying a bridge destroys its added buffer and composed wrapper, not the borrowed mesh.
Destroying the mesh invalidates dependent draws and bundles. Recreate the bridge/draw and
re-record bundles; raw buffer destruction outside the geometry lifecycle is not tracked.
Ordinary destroyed geometry now fails synchronously with `VGPU-MESH-LAYOUT-INVALID`; bridges
use `VGPU-INSTANCE-DESTROYED`.

WGSL can import `instanceWorldMatrix`, `transformPosition`, `transformDirection` and
`transformNormal` from `@vgpu/wgsl-std/scene`. They introduce no bindings. Use the complete
world/deformation transform: position uses w=1, direction w=0, and normals use normalized
inverse-transpose with reflection sign. Extreme ill-conditioned float32 inputs or backend
subnormal handling can lose direction/sign accuracy; the zero fallback has no epsilon or
symbolic-rank guarantee. See [Scene composition](/docs/guides/scene-composition) for complete setups.

### 3. Choose shader entries and distinguish inputs from presentation

#### Pin shader entries when preserving the previous choice

With multiple entries of one stage, automatic selection now prefers `vs_main`, `fs_main`
or `cs_main`. A single entry can have any name; without the conventional name the first
entry still wins. If `0.5.0` selected an earlier nonconventional entry, name it explicitly:

```ts illustrative
draw(gpu, { shader, entry: { vertex: "previous_vertex", fragment: "previous_fragment" } });
compute(gpu, computeSource, { entry: "previous_kernel" });
effect(gpu, fragmentSource, { entry: { fragment: "previous_fragment" } });
```

Override only affected stages. Selection determines resources and vertex input layouts as well
as execution; compare pixels/readbacks and bind everything the chosen entry uses. Invalid names
or wrong stages throw `VGPU-ENTRY-INVALID`. Effects expose fragment selection only. For an effect
with custom vertices that must avoid `vs_main`, rename the unselected conventional function or
use `draw()` with explicit selections. Fragment-only effects retain the generated fullscreen vertex.

Runtime WGSL string compilation now discovers attributed compute entries, Unicode names and
WGSL whitespace correctly while ignoring comments. Its signature and shader passthrough are
unchanged; corrected metadata requires no new call shape.

#### Replace Surface input bindings with offscreen resources

Passing a `Surface` to a Draw, Effect or Compute binding now throws
`VGPU-SURFACE-NOT-BINDABLE`, both in constructor `set` options and later `.set()` calls.
The surface remains a render destination. Replace a sampled presentation workflow:

```ts illustrative
frame(gpu, f => {
  f.pass(screen, producer);
  consumer.set({ source: screen });
  f.pass(preview, consumer);
});
```

with an offscreen producer and final presentation:

```ts
import { effect, frame, init, surface, target } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const screen = surface(gpu, document.querySelector("canvas")!);
const intermediate = target(gpu, { size: screen.size });
const producer = effect(gpu, prepareShader(`
  @fragment fn main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return vec4f(uv, 0.0, 1.0);
  }
`));
const consumer = effect(gpu, prepareShader(`
  @group(0) @binding(0) var source: texture_2d<f32>;
  @fragment fn main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return textureLoad(source, vec2i(uv * vec2f(textureDimensions(source))), 0);
  }
`), { set: { source: intermediate } });
screen.onResize(({ width, height }) => intermediate.resize([width, height]));
await producer.compile(intermediate);
await consumer.compile(screen);
frame(gpu, f => {
  f.pass(intermediate, producer);
  f.pass(screen, consumer);
});
```

A bound `Target` follows attachment replacement after resize. An explicit `Texture` keeps that
identity: rebind it after replacement. Read intermediate results with
`intermediate.color.read({ mipLevel: 0, region: "all" })`. `surface.color` remains the current
presentation texture; retaining it does not extend its lifetime beyond presentation.

#### Opt into direct depth-tested canvas rendering when useful

Existing surfaces keep no depth attachment and one sample. Existing two-pass offscreen rendering
still works. For direct presentation, `surface(gpu, canvas, { depth: true, msaa: 4 })` adds
`depth24plus` and four samples. `depth` also accepts supported explicit depth-aspect formats;
`msaa: true` also means four samples. No `sampleCount` option is added.

`compile(surface)`, `compileSync(surface)`, Draw constructor `targets`, and bundle recording
can run outside frames using the configured color/depth/sample signature without acquiring a
canvas texture. They honor opt-in depth/MSAA; they are not limited to one sample or no depth.
When supplying an explicit signature, match the actual surface format and attachments; query
the preferred canvas format before creating a surface rather than assuming BGRA/RGBA. Draw
and replay canvas work inside `frame()` or `frameLoop()`.

`surface.depth` is owned and stable until replacement/disposal. MSAA color storage is private
and resolves into the single-sample `surface.color`. To sample depth, bind `surface.depth`
explicitly on a surface without `msaa` and rebind it in `onResize` after replacement. Resize
outside the frame, before encoding attachment consumers. Explicit and automatic layout/DPR
resizes notify listeners after committing replacements;
a listener failure does not undo the resize or prevent other notifications/old-attachment cleanup.
Synchronous allocation failure preserves the previous surface size and attachments. Recursive
resize during replacement notification throws `VGPU-SURFACE-RESIZE-REENTRANT`.

Direct canvas dimension writes between frames reconcile owned attachments before the next frame
callback without public resize notifications. The pass descriptor also reconciles later writes,
but mid-frame changes can invalidate attachments already encoded. Use explicit resize and rebind
when consumers retain depth. Offscreen targets remain useful for sampling, postprocessing,
history and readback; these additions require no rewrite of an existing offscreen workflow.

### 4. Prepare asynchronously, then encode frames synchronously

`compute()` now constructs a lazy pipeline. Call `await simulation.compile()` before rendering
when preparation must finish in advance; the promise rejects compilation failures and resolves
to the same object. `compileSync()` or first dispatch compiles synchronously. Native synchronous
creation failures now throw, and automatic reuse of a failed pipeline throws rather than silently
skipping work. An explicit compile retries. `compile()` after `compileSync()` waits for native
validation, including synchronous takeover of pending asynchronous compilation.

Move awaits out of `frame`, `frameLoop`, equivalent `FrameRunner` methods and compute-pass
callbacks. For example:

```ts illustrative
// Before
frame(gpu, async f => {
  await loadAssets();
  simulation.dispatch(64);
  f.pass(output, display);
});

// After
await loadAssets();
await simulation.compile();
frame(gpu, f => {
  f.computePass(pass => pass.dispatch(simulation, 64));
  f.pass(output, display);
});
```

`simulation.dispatch()` still submits independently, even inside a frame. Use `computePass()`
for ordered render/compute work in one frame submission and cancellation. Passes cannot nest;
do not retain the pass after its callback or submit/cancel before it ends. Dispatch counts must
be finite nonnegative integers within the granted device limit, and workgroup dimensions/product
must fit device limits. Request supported larger limits through `init({ requiredLimits })` or
reduce workgroups; defaults did not increase.

Inferred Promise/PromiseLike returns, unions containing them, and unresolved generic callback
returns fail typechecking. Concrete synchronous returns remain accepted and ignored. For a
forwarder whose contract ignores the result, accept `FrameLoopCallback` or `(frame: Frame) => void`
and pass the callback directly. Do not erase an async continuation with casts or wrappers.
Callbacks typed `void`, `unknown` or `any` can pass types but still throw
`VGPU-ASYNC-FRAME-CALLBACK` if they return a thenable. The open frame is canceled before implicit
submission, and a failing loop stops. Already submitted work and CPU-side continuations are not
rolled back; later encoding through that canceled frame fails with `VGPU-FRAME-CANCELED`.

#### Set each direct operation's uniform values before encoding it

Direct frame draws and dispatches now capture managed uniform values per operation:

```ts illustrative
frame(gpu, f => f.computePass(pass => {
  simulation.set({ dt: 0.01 });
  pass.dispatch(simulation, 64); // captures 0.01
  simulation.set({ dt: 0.02 });
  pass.dispatch(simulation, 64); // captures 0.02
}));
```

If the old application expected the last update to affect every operation, set that common value
before encoding them. Capture covers JS-owned uniform bindings and `uniforms()` used as uniforms.
Storage, shared uniforms adopted as storage, raw buffers, claimed groups and render bundles retain
live buffer contents. Use separate resources for distinct bundle/raw-buffer values in one
submission. Host writes and CPU mutations are outside frame cancellation.

Upload deferral preserves these semantics: `.set()` still validates and packs immediately,
one-shot work uploads pending values when needed, and exposed stable raw buffers are flushed
before exposure and continue receiving immediate updates. No consumer flush call is added.
Identical managed packed bytes now reuse the same frame snapshot, and frame pages/bind groups are pooled. Redundant `.set()` calls remain valid;
storage, bundles and exposed/raw buffers keep live write semantics. No migration is required
for this reuse optimization.

#### Keep completion and error handling separate

Register `gpu.onError` for asynchronous validation/execution failures. `frame.done` and
`gpu.settled()` remain resolve-only completion signals; neither they nor a later storage read
prove that the producer succeeded. `settled()` now also waits for queue work already submitted
when called, so it can take longer; later submissions are outside that snapshot. Calls after
observed loss/disposal retain tracked waits without creating a new queue fence.

For a nonconforming queue whose `onSubmittedWorkDone()` throws synchronously, an already-submitted
standalone dispatch now reports one `VGPU-COMPUTE-VALIDATION` through `gpu.onError` at
`<label>.completion` instead of throwing after submission. Conforming queues require no adaptation.

### 5. Handle device loss explicitly and preserve normal teardown

Use the stable readonly `gpu.lost` promise to detect native loss observed while the wrapper is
active. Every running frame loop stops before its handlers run. The next tick no longer emits
an uncaught loss error, so replace global-error-based recovery. Loss does not dispose resources,
notify `gpu.onError` or automatically recreate the device:

```ts illustrative
void gpu.lost.then(() => {
  gpu.dispose();
  return start(); // init(), recreate resources and restart the loop
}).catch((error: unknown) => console.error("GPU restart failed", error));
```

Dispose the old surface/Gpu before configuring its replacement on the same canvas.
`gpu.lost` never rejects, but recovery code can. Factories, `clock()`, `frame()` and `frameLoop()`
now throw `VGPU-DEVICE-LOST` synchronously after observed loss. An already-open manual frame
remains open; `submit()` throws until normal disposal cancels it. Explicit submit error handling
does not change.

Use `gpu.dispose()` for teardown, including inside a frame callback. Direct core
`gpu.device.dispose()`/`destroy()` during a callback now allows implicit-submit errors to escape
instead of swallowing `VGPU-DEVICE-DISPOSED`; a failing loop stops and rethrows.

Normal unmount remains: stop the loop, await `gpu.settled()` if submitted work/deliveries must
finish, then `gpu.dispose()`. Never await `gpu.lost` for teardown. Disposal before vgpu observes
native loss leaves it pending; disposal after observation preserves its resolved value. Disposing
a wrapper from `initFromDevice()` never destroys the borrowed native device. If its owner destroys
that device while the wrapper is active, loss resolves with `reason: "destroyed"`.

Bundles now release abandoned facade retention automatically. Optional, synchronous, idempotent
`bundle.dispose()` drops references immediately without destroying borrowed resources or revoking
a previously saved native bundle handle. Existing recording/replay calls require no migration.
Continue re-recording when captured resource identities, draw counts or render signatures change;
automatic cleanup does not rebuild stale bundles or promise driver-memory release timing.

### 6. Validate bindings and keep separately replayable bundles independent

Binding `set()` calls on Draw, Effect and Compute now report `VGPU-R1-BINDING-DESTROYED`
for an already-destroyed tracked Buffer, Uniform-like value or provider. Update handlers
that matched `VGPU-BUFFER-DISPOSED` at this boundary; direct Buffer `read()`/`write()`
continue using `VGPU-BUFFER-DISPOSED`.

Raw `GPUBuffer` and `{ buffer, offset?, size? }` bindings are live resources. Their descriptors
are snapshotted by `set()`: call `set()` again after changing a range. Only `undefined` selects
defaults (`offset: 0`, `size: buffer.size - offset`); `null` and numeric strings are invalid.
Use the reflected uniform/storage usage, a nonnegative safe-integer offset aligned to the
granted device limit, and a positive in-bounds size between the reflected minimum and granted
maximum. Storage sizes must be multiples of four. Tracked bindings receive the same checkable
range validation and retain synchronous usage checks.

Invalid usage/ranges now throw `VGPU-R1-BINDING-INCOMPATIBLE-RESOURCE` at `set()` instead
of waiting for native bind-group validation. The rejected binding retains its previous value.
This guarantee applies to that binding, not the whole `set({ a, b })` call: earlier valid
entries may already have been applied when a later entry throws.
Ordinary struct values with numeric fields named `buffer`, `offset` or `size` remain valid.
For compute storage, use separate allocations whenever either binding is writable, including
when one binding is tracked and the other raw. Even disjoint ranges of one allocation produce
`VGPU-R1-STORAGE-ALIASING`; use two allocations or `pingPongStorage()`.

Rebinding a Draw/Effect while recording bundle B now makes an earlier completed bundle A stale.
For separately replayable bundles with different resource identities or claimed groups, keep a
stable consumer per bundle (two consumers for ping-pong directions), or re-record and replace
the old bundle after rebinding. Rebinding between draws within one recording remains supported.

**Known limitation in 0.6.0:** after a partially failed multi-binding `Draw.set({ a, b })`,
a previously recorded bundle may still replay the old `a` reference. Repair the bindings and
explicitly re-record the bundle before replaying it. Automatic retention cleanup does not fix
this pre-existing error-path gap.

Before, a shared consumer could leave an earlier bundle replayable after a later recording:

```ts illustrative
const forward = bundle(gpu, { target: output }, encoder => encoder.draw(shared));
const backward = bundle(gpu, { target: output }, encoder => {
  shared.set(reverseBindings);
  encoder.draw(shared);
});
// Managed replay of forward now throws VGPU-R3-BUNDLE-STALE.
```

After, create two consumers with stable resource identities:

```ts illustrative
const forwardDraw = draw(gpu, { shader, set: forwardBindings });
const backwardDraw = draw(gpu, { shader, set: reverseBindings });
const forward = bundle(gpu, { target: output }, encoder => encoder.draw(forwardDraw));
const backward = bundle(gpu, { target: output }, encoder => encoder.draw(backwardDraw));
```

Optional, synchronous, idempotent `dispose()` on Draw, Effect and Compute releases consumer
state without destroying borrowed resources. Later calls fail with `VGPU-DRAW-DISPOSED`
(Draw/Effect) or `VGPU-COMPUTE-DISPOSED`. Disposing a recording's consumer invalidates its
managed bundles; replace the consumer and re-record before replay. Already encoded commands
and saved native bundle handles are not revoked. Collection without explicit disposal leaves
retained bundles valid through independent resource snapshots; collection timing is unspecified.
Generated compatible texture views are reused, while explicit `Texture.createView()` stays fresh.

Unchanged draws, effects and computes now reuse passing binding checks and static bind-group
keys; draws and effects also reuse derived pipeline keys. No migration is required: binding
changes and tracked resource destruction still invalidate that work, pipeline failures still
surface, and uniform capture, live buffer writes and bundle staleness keep their semantics.

`geometry(gpu, { indices })` now accepts odd-length `Uint16Array` inputs by padding only the
initial upload. Existing valid calls need no changes. The logical index count and writable byte
range exclude padding, and `writeIndices` still requires four-byte alignment: it cannot rewrite
the last index of an odd-length array. If every drawn index must be rewritable, supply an
even-length array and set the intended logical `indexCount` explicitly.

### 7. Select the intended mouse coordinate space

`canvasMouseTracker` from `@vgpu/render/utils` no longer accepts `normalize`, and `position` is no
longer a tuple. Remove the option and choose `position.normalized` or `position.canvasPixels`:

```ts
import { canvasMouseTracker } from "@vgpu/render/utils";

const canvas = document.querySelector("canvas")!;
const pointer = canvasMouseTracker({ canvas, flipY: true });
const [u, v] = pointer.position.normalized;
const [x, y] = pointer.position.canvasPixels;
pointer.dispose();
```

The former default tuple held CSS-offset pixels; `canvasPixels` holds drawing-buffer pixels.
For CSS/DOM positions, multiply `normalized` by `canvas.clientWidth`/`canvas.clientHeight`
and keep the default `flipY: false` for a top-left origin. Keep `flipY: true` for
a bottom-left origin. When interacting with a lower-resolution offscreen target, convert
normalized coordinates to that target's dimensions rather than reusing canvas pixels.

### 8. Keep optional documentation integrations optional

Scene references, numerical-library examples and Blender skill resources add discovery and
authoring guidance without new runtime dependencies or required application changes. Keep your
project's chosen math library; install an optional one only for your own numerical needs.
Preferred-format examples now describe the existing format contract correctly. The functional
Surface preparation/depth changes are consolidated in step 3; no intermediate migration is needed.

## From release candidates

### From `0.6.0-rc.2`

Update the fixed packages together to `0.6.0` and rebuild. No additional API or behavior
migration is required: the stable release retains this candidate's runtime implementation.
Keep its prepared shaders, loader configuration, scene state, frame callbacks and binding
ownership. The multi-binding `Draw.set()` limitation in step 6 still applies.

### From `0.6.0-rc.1`

Update the fixed packages together to `0.6.0` and rebuild. No additional API migration
is required: the encode optimization preserves existing behavior, and the index-upload fix
only accepts inputs that previously failed during creation. Keep the prepared shaders, loader
configuration and binding/lifetime adaptations already completed for `rc.1`. Verify repeated
draws and odd-length indices as described in verification item 9; do not repeat the stable-origin
API rewrites.

### From `0.6.0-rc.0`

For `0.6.0-rc.0`, apply **step 1** (prepared v2 shaders and loader/cache configuration)
and **step 6** (binding errors/ranges, compute aliases and cross-recording bundle ownership).
That published RC emitted v1 artifacts and had no `@vgpu/wgsl/next` helper, so upgrade packages
before importing the helper. Both changes also apply to stable-origin users; no reversal requires
an RC-only repair. The managed-uniform reuse optimization in step 4 requires no adaptation.

Keep the scene, shader-entry selection, Surface, synchronous-frame, device-loss and mouse
adaptations already completed for `rc.0`; do not repeat them or restore removed APIs. Consumer
`dispose()` remains optional. Users of `0.5.0-rc.0` or `0.5.0-rc.1` first complete their applicable
[0.5.0 RC path](/docs/migrations/0.5.0#from-release-candidates), then apply the stable-origin steps
above, retaining already-completed adaptations.

## Verification

1. Typecheck against matching package versions. Rebuild with the restored production cache and
   verify imported shaders have `version: 2`, producer `"@vgpu/wgsl/prepare-v2"`, a string
   `sourceChecksum` and object `reflection`. Render deployed shader consumers without shader-source
   errors or artifact mutation `TypeError`s. Delete/restore a WGSL dependency in watch mode and
   confirm recovery. Keep device validation separate from build-time reflection.
   Find removed scene imports, old `orbit` calls,
   async/unresolved-generic frame callbacks, `normalize` and tuple-valued mouse positions.

2. Exercise object reparenting, explicit camera aspect updates, finite projection bounds, independent
   camera rigs/time steps, zero instances, removals and bridge/mesh destruction. Change a matrix,
   repack its uniform and confirm the next rendered output changes. Verify custom attributes and
   transformed normals on the intended GPU.

3. Compile both automatic and explicitly selected shader entries and compare pixels or compute
   readbacks. Confirm the chosen entry has its inputs and resources. Invalid explicit entries must
   fail with `VGPU-ENTRY-INVALID`.

4. Verify Surface input rejection and an offscreen producer/presentation replacement. Test direct
   surface rendering with default attachments and with depth/MSAA, resize before encoding, rebind
   explicit depth and check stale attachment/bundle handling. Read only current presentation data
   or an owned offscreen texture with explicit mip/region options.

5. On a real GPU, encode multiple operations with distinct managed uniforms and mixed compute/render
   passes; confirm ordering, values and one frame submission. Cancel a frame and confirm its encoded
   work is not submitted. Check live storage, indirect arguments and bundles separately. Await
   compilation; collect `gpu.onError` through completion before assessing execution results.

6. For loss recovery, destroy an externally owned native device wrapped by `initFromDevice()`.
   Confirm `gpu.lost` resolves after loops stop, resources remain undisposed until teardown, and
   recreated resources render on a new GPU. Verify ordinary unmount finishes without awaiting loss.

7. Check pointer alignment when CSS and drawing-buffer dimensions differ, including an upscaled
   offscreen target. For native users, run the installed `vgpu native doctor`, `check`, `build`
   and `verify` and consume the regenerated Swift package on the qualified target platform.

8. Test destroyed-binding diagnostics separately from direct Buffer operations. Reject an invalid
   range and confirm its previous binding remains active; read two valid aligned ranges and compare
   their bytes. Test mixed tracked/raw writable aliases and separate-allocation replacements.
   Record A, rebind during B and verify A becomes stale; verify two stable consumers replay correctly.
   If adopting disposal, check disposed-consumer errors and re-record managed bundles. These checks
   apply to the `rc.0` path as well as stable upgrades.

9. For `rc.0` and `rc.1` upgrades, render repeated unchanged draws, then change a binding, write a live
   buffer, resize a followed target and destroy a tracked resource. Confirm updated pixels and
   the existing destroyed-binding diagnostic. Render an odd-length `Uint16Array` geometry without
   native upload errors, confirm its logical draw count, and check that padding cannot be drawn
   or written through `writeIndices`.

10. For `rc.2` upgrades, verify matching `0.6.0` package versions, rebuild and smoke-test the
    production output. No new migration-specific regression path is introduced. For every origin,
    if a multi-binding `Draw.set()` fails, exercise the repair-and-re-record path from step 6;
    do not assume the call rolled back all bindings or invalidated every affected bundle.

Complete `ts` blocks participate in snippet typechecking. Blocks marked `ts illustrative`
describe historical or partial application code and are not standalone checked programs.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Migrations
description: Versioned upgrade instructions for projects using vgpu.
---

# Migrations



Record your project's current version before upgrading. Read each intervening destination-version guide in ascending version order. Choose the stable or release-candidate starting path that applies to your installed version, then follow the ordered steps and verification. Guides describe the net change to the destination, not a chronological replay of changesets. Packages published before these guides were introduced may not contain them.

Use the CLI from the target project's installed package; do not substitute latest or hosted documentation for a selected RC.

```bash
pnpm exec vgpu docs ls /migrations
```

<!-- Generated from migration release records. Do not edit. -->

## Available guides

* [0.6.0](/docs/migrations/0.6.0) — `vgpu docs cat /migrations/0.6.0.docs.md`
* [0.5.0](/docs/migrations/0.5.0) — `vgpu docs cat /migrations/0.5.0.docs.md`


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: API Reference
description: API reference for vgpu packages, generated from the documentation manifest.
---

# API Reference



Browse generated API docs by topic. Every symbol comes from the docs manifest and deep-links to an anchor on its topic page.

## Start with vgpu

<Card title="vgpu" description="Public API: init, Gpu, effect, draw, compute, frame, bundle, target, ping-pong, and uniforms." href="/docs/reference/vgpu" />

## Packages

{/* Prod (https://vgpu.sh/docs/reference) serves each of these 9 packages as a heading with an
    id="<packageSlug>" anchor (apps/docs/app/docs/reference/page.tsx: `<section id={group.packageSlug}>`),
    and the 19 ported `/packages/<pkg>` redirects in lib/docs-redirects.mjs land on exactly those
    fragments (e.g. /packages/vgpu-adapter-node -> /docs/reference#vgpu-adapter-node). The `id` prop
    below is required so those deep links keep landing on a fragment instead of the bare page. */}

<Cards>
  <Card id="vgpu" title="vgpu" description="Public API: init, Gpu, effect, draw, compute, frame, bundle, target, ping-pong, and uniforms." href="/docs/reference/vgpu" />

  <Card id="vgpu-three" title="vgpu/three" description="Adapters that turn resolved WGSL function exports into callable three.js TSL nodes." href="/docs/reference/vgpu-three" />

  <Card id="vgpu-scene" title="vgpu/scene" description="CPU transforms, groups, external hierarchies, typed instances, camera state, and geometry recipes." href="/docs/reference/vgpu-scene" />

  <Card id="vgpu-scene-gpu" title="vgpu/scene/gpu" description="Publish scene instances as a vertex stream for your own shaders and rendering passes." href="/docs/reference/vgpu-scene-gpu" />

  <Card id="wgsl" title="@vgpu/wgsl" description="WGSL compile-time entry points, runtime resolution, reflection metadata, and bundler loaders." href="/docs/reference/wgsl" />

  <Card id="wgsl-std" title="@vgpu/wgsl-std" description="Standard WGSL modules for color, fullscreen triangles, hashes, and procedural noise." href="/docs/reference/wgsl-std" />

  <Card id="vgpu-core" title="vgpu/core" description="Advanced escape hatches for native WebGPU handles, buffers, textures, bind groups, and structured uniforms." href="/docs/reference/vgpu-core" />

  <Card id="render" title="@vgpu/render" description="Advanced render tooling for inspection, performance measurement, utilities, and mesh editing." href="/docs/reference/render" />

  <Card id="vgpu-adapter-node" title="@vgpu/adapter-node" description="The Node.js WebGPU adapter — createNodeAdapter() and the Dawn binary resolution it wraps." href="/docs/reference/vgpu-adapter-node" />

  <Card id="vgpu-mock" title="vgpu/mock" description="A software Gpu implementation for tests and CI that has no GPU at all." href="/docs/reference/vgpu-mock" />
</Cards>


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Agents
description: Use package-versioned CLI docs, install the thin vgpu skill, or connect through MCP.
---

# Agents



# Agents

vgpu is an agent-first library. Start with the CLI for documentation versioned with the API in your `node_modules`, install the skill to route agents to that local documentation, or connect the hosted MCP server for remote read-only access to the latest stable release.

## Point your agent at the docs

```bash
npx vgpu
```

That's the whole instruction. The command prints its own guide — starting with the agent get-started, `vgpu docs cat getting-started.md` — plus the tools to explore and search every reference page, guide, and error code. Your agent takes it from there.

## Install the skill

```bash
npx skills add vercel-labs/vgpu
```

For agents that support skills, this installs a small, version-independent router. It does not copy the API reference from the repository. Instead, it teaches the agent to inspect the `vgpu` version installed in your project and query the documentation bundled with that package, so the guidance stays aligned with the code you are using.

If a manifest or lockfile selects `vgpu` but dependencies are not installed, the skill restores or invokes that exact selection instead of substituting another version. Only when neither the project nor the user has selected a version does it fall back to the latest stable package. Prerelease documentation is opt-in through an explicitly selected prerelease such as `vgpu@next`.

## Connect the hosted MCP server

Use `add-mcp` to detect installed MCP clients and add the hosted VGPU server globally:

```bash
npx -y add-mcp https://vgpu.sh/api/mcp -g
```

The installer lets you review its detected clients before writing their configuration. The server requires no authentication and gives the agent two read-only tools: `docs` for searching and resolving the VGPU documentation, and `examples` for finding and reading verified example source. The hosted server follows the stable release on vgpu.sh; use the local CLI or local stdio server when you need documentation for an installed prerelease.

If the agent needs to download an example, run `npx -y vgpu mcp --project-from-cwd` locally on Linux or macOS. Filesystem writes remain disabled until you explicitly select an output boundary. See the [MCP reference](/docs/mcp) for hosted HTTP details, local stdio setup, safe download destinations, and editor-specific guidance.

Everything the hosted server exposes is also readable on this site. Package-versioned CLI docs remain authoritative for the exact `vgpu` version installed in a project.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Get started
description: Set up your coding agent and render your first frame with vgpu.
---

# Get started



vgpu is designed to be used with coding agents. Give your agent access to version-matched docs, verified examples, and diagnostics, then choose where to render.

<Cards>
  <Card title="Agents" description="Start here. Run `npx vgpu`, install the vgpu skill, or connect through MCP." href="/docs/get-started/agents" className="col-span-2" />

  <Card title="Web" description="Render a shader to an interactive canvas with Next.js or Vite." href="/docs/get-started/web" />

  <Card title="Node.js" description="Render headlessly, save an image, or run GPU tests without a browser." href="/docs/get-started/node" />
</Cards>

## Next: the concepts

Once you can render on your platform, learn the ideas every vgpu program is built from.

<Cards>
  <Card title="Concepts" description="Context, effects, passes, frames, and render bundles — in reading order." href="/docs/concepts" />
</Cards>


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Node.js
description: Render headless in Node.js through Dawn — save a PNG or assert on pixels in a test.
---

# Node.js



# Node.js

In Node.js, vgpu renders headless through Dawn — the same API, no canvas, no browser. Import `init` from `vgpu/node`, render into an offscreen [`Target`](/docs/reference/vgpu/target#target), and read the pixels back.

## Install

```bash
npm install vgpu
```

On Linux, vgpu resolves a working Dawn binary automatically. When the stock
prebuild matches your system it is used directly; on older-GLIBC hosts vgpu
downloads its own portable Dawn build from GitHub Releases, verified against a
pinned SHA-256, and caches it locally. If your install runs with scripts
disabled (`--ignore-scripts`, pnpm v10 allow-lists), the download happens
lazily on first `init()` instead — or run it yourself:

```bash
npx vgpu install-dawn
```

Before your first render, `npx vgpu doctor` checks the machine end to end — it
acquires an adapter and renders a real frame, and when something is missing it
prints the exact fix as JSON. Run it once before debugging anything else.

<Callout type="info">
  Good to know: no GPU and no driver? `npx vgpu install-software-renderer` sets
  up a portable CPU renderer once; `init()` uses it automatically after that.
</Callout>

Air-gapped or custom environments can point `VGPU_DAWN_BINARY` at a local
binary. When no binary can be resolved, `init()` throws a structured
`VGPU-NODE-PREBUILD-MISSING` error that names the exact reason and fix. See
[`createNodeAdapter`](/docs/reference/vgpu-adapter-node/create-node-adapter) for the
full resolution order.

## Choose an environment

Start every new machine with `npx vgpu doctor`. After that, choose the mode
that matches what the environment is supposed to guarantee:

| Environment                               | Setup                                                                                 | Runtime choice                                                                  |
| ----------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| Local workstation                         | Install the normal GPU driver                                                         | `init()` — use normal system discovery                                          |
| Server or sandbox without a GPU           | Run `npx vgpu install-software-renderer` once                                         | `init()` — use the cached CPU renderer only when normal discovery finds nothing |
| Deterministic screenshots and pixel tests | Cache the software renderer in the CI image                                           | `init({ adapter: "software" })` — force the same Mesa renderer everywhere       |
| GPU-required CI                           | Install the vendor driver                                                             | `init({ adapter: "hardware" })` — fail instead of silently running on CPU       |
| Air-gapped runner                         | Pre-populate the Dawn and software-renderer caches while the image has network access | Select `auto`, `hardware`, or `software` normally at runtime                    |

### Configure it from TypeScript

```ts
import { init } from "vgpu/node";

const gpu = await init();                        // auto: normal adapter first, cached CPU fallback last
const hardware = await init({ adapter: "hardware" }); // require a real GPU
const software = await init({ adapter: "software" }); // force deterministic CPU rendering

console.log(software.adapter);
// { name: "llvmpipe: Mesa 25.0.7 ...", type: "cpu" }
```

`auto` never downloads the software renderer. It uses lavapipe only after you
have explicitly installed it and normal adapter discovery returned nothing.
A working system adapter always wins.

### Override it from CI

Environment overrides win over the TypeScript option and announce themselves
once on stderr, so CI can force a policy without changing application code:

```bash
VGPU_ADAPTER=software node render.mjs  # deterministic CPU pixels
VGPU_ADAPTER=hardware pnpm test        # require a GPU and fail loudly without one
```

Use the SDK option for the project's declared behavior and the environment
variable for temporary CI or debugging intervention. The browser API does not
need this configuration — `import { init } from "vgpu"` continues to let the
browser choose its adapter.

Whichever mode you use, release the device when the process is done:

```ts
try {
  // render, read pixels, write artifacts
  await gpu.settled();
} finally {
  gpu.dispose();
}
```

For loader resolution, distro-specific dependencies, Docker, and lifecycle
details, see [`createNodeDevice`](/docs/reference/vgpu-adapter-node/create-node-device).

## Save a PNG

`target.read()` resolves to the rendered RGBA bytes. Hand them to any PNG encoder — here, `pngjs`:

```ts
import { writeFileSync } from "node:fs";
import { PNG } from "pngjs";
import { init, effect, target } from "vgpu/node";

const gradientSource = `
  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return vec4f(uv, 0.4, 1.0);
  }
`;

const gpu = await init();
const colorTarget = target(gpu, { size: [256, 256] });

effect(gpu, gradientSource).draw(colorTarget);
const pixels = await colorTarget.read(); // RGBA bytes

const png = new PNG({ width: colorTarget.size[0], height: colorTarget.size[1] });
png.data.set(pixels);
writeFileSync("gradient.png", PNG.sync.write(png));
```

## Write a test

The same render runs inside a test. Read the pixels and assert on them:

```ts
import { expect, test } from "vitest";
import { init, effect, target } from "vgpu/node";

const gradientSource = `
  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return vec4f(uv, 0.4, 1.0);
  }
`;

test("gradient renders", async () => {
  const gpu = await init();
  const colorTarget = target(gpu, { size: [64, 64] });

  effect(gpu, gradientSource).draw(colorTarget);
  const pixels = await colorTarget.read();

  // center pixel: blue is the constant 0.4 (~102 of 255), alpha is 1.0
  const center = (32 * 64 + 32) * 4;
  expect(pixels[center + 2]).toBeGreaterThan(95);
  expect(pixels[center + 2]).toBeLessThan(110);
  expect(pixels[center + 3]).toBe(255);
});
```

<Callout type="info">
  Good to know: use `vgpu/mock` for deterministic unit tests that need no GPU; reach for `vgpu/node` when real Dawn/WebGPU behavior is under test.
</Callout>

<Callout type="info">
  Good to know: call `gpu.dispose()` when you are done — it stops Dawn's event
  polling so the process exits on its own instead of hanging.
</Callout>


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Web
description: Install vgpu, render a gradient to a canvas, and load .wgsl files in Next.js or Vite.
---

# Web



# Web

In the browser, vgpu renders with WebGPU straight to a `<canvas>`. Install the package, write a fragment shader, and draw.

## Install

```bash
npm install vgpu
```

## Render a gradient

Create a context, wrap your canvas in a [`Surface`](/docs/reference/vgpu/surface#surface), and draw an effect:

```ts
import { init, effect, surface } from "vgpu";
import gradientSource from "./gradient.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);
const gradient = effect(gpu, gradientSource);

gradient.draw(canvasSurface); // renders immediately
```

```wgsl
// gradient.wgsl
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, 0.4, 1.0);
}
```

The entry shader can import reusable functions, structs, aliases, and constants from other `.wgsl` files. Learn the authoring model and pure-module rule in [WGSL modules](/docs/concepts/wgsl-modules).

## Load .wgsl files in Next.js

Add the loader rule to your Next.js config:

```js
// next.config.mjs
const config = {
  turbopack: {
    rules: {
      "*.wgsl": {
        loaders: ["@vgpu/wgsl/loader-webpack"],
        as: "*.js",
      },
    },
  },
};

export default config;
```

<Callout type="info">
  Good to know: for webpack builds, add the same loader as a module rule: `config.module.rules.push({ test: /\.wgsl$/, use: "@vgpu/wgsl/loader-webpack" })`.
</Callout>

## Load .wgsl files in Vite

Add the plugin from `@vgpu/wgsl/loader-vite`:

```js
// vite.config.js
import { defineConfig } from "vite";
import { wgslVitePlugin } from "@vgpu/wgsl/loader-vite";

export default defineConfig({
  plugins: [wgslVitePlugin()],
});
```

## Type .wgsl imports

Create a `wgsl-env.d.ts` in your project so TypeScript types every `.wgsl` import as a string:

```tsx
/// <reference types="@vgpu/wgsl/wgsl-types" />
```


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Native
description: Compile WGSL modules into a native shader library and generated integration for application-owned Metal code.
---

# Native



Use vgpu's WGSL module system with native GPU code. A build step resolves imports, validates the
selected programs, compiles a shader library, and generates the host-language integration. Your
application keeps control of the platform GPU API.

> Beta: Native tooling is available through the optional `@vgpu/native` companion. The direct Metal guides
> identify the generated APIs exercised by native tests. Those tests do not establish a complete
> release support matrix. Pin matching exact RC versions of `vgpu` and `@vgpu/native`.

## Compile once, use native code

For macOS, the build produces a self-contained Swift package containing generated Swift and a
compiled Metal library. Node.js, Tint, WGSL, and generated Metal source stay on the build machine;
the application does not run a JavaScript renderer or translate WGSL at launch.

The generated types load selected functions on your Metal device and provide the supported
packing and binding helpers. They do not create a device, command queue, pipeline, frame loop,
or view. You can use several programs with different resources and native render state.

## Keep Metal in control

| vgpu provides                                          | The application provides                                        |
| ------------------------------------------------------ | --------------------------------------------------------------- |
| WGSL import resolution and selected-program validation | Shader selection and application logic                          |
| A compiled library and typed function loading          | Metal devices, pipelines, and render state                      |
| Supported uniform packers and checked buffer bindings  | Buffer and texture allocation, data updates, and lifetimes      |
| Binding metadata and prepared internal bytes           | Command encoding, synchronization, submission, and presentation |

This boundary does not require a Swift equivalent of every TypeScript vgpu primitive. Use ordinary
Metal commands before, between, and after generated shader work. Native composition remains
available without going through another renderer abstraction.

One configuration packages all of its selected shader programs together. Use separate configurations
when shader payloads must be distributed independently; choosing fewer Swift symbols does not remove
functions from an already compiled library.

## Start with macOS

Read [macOS](/docs/native/macos) for the current workflow, then
[Render WGSL with Metal](/docs/native/macos/metal/rendering) for a complete draw.

Continue with [uniform packing](/docs/native/macos/metal/uniforms),
[buffer bindings](/docs/native/macos/metal/bindings), or
[compute dispatch](/docs/native/macos/metal/compute/dispatch). Each guide states its supported profile.

macOS and Metal are the initial target. Windows and Vulkan are future work, not available backends.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Quickstart: Browser
description: Copy the model output once into a vgpu-owned buffer, then release the tensor.
---

# Quickstart: Browser



In this quickstart you run an ONNX model with ONNX Runtime Web's WebGPU execution provider and consume its output with vgpu shaders — on one shared `GPUDevice`, without the result ever leaving the GPU.

Prerequisites:

* A browser with WebGPU enabled.
* `onnxruntime-web` in your app — vgpu does not bundle or import ORT.
* A model that runs on the WebGPU execution provider.

Create the ORT session first so ORT owns the device, then pass `ort.env.webgpu.device` to `initFromDevice`. Set `preferredOutputLocation: "gpu-buffer"` so outputs stay on the GPU.

## Browser snapshot

Copy the model output once into a vgpu-owned buffer, then release the tensor:

```ts
import * as ort from "onnxruntime-web/webgpu";
import { initFromDevice } from "vgpu";

declare const modelBytes: Uint8Array;
declare const input: ort.Tensor;

const adapter = await navigator.gpu.requestAdapter();
if (!adapter) throw new Error("WebGPU adapter unavailable");
ort.env.webgpu.adapter = adapter;
const session = await ort.InferenceSession.create(modelBytes, {
  executionProviders: ["webgpu"],
  preferredOutputLocation: "gpu-buffer",
});
const gpu = await initFromDevice(await ort.env.webgpu.device);
const output = (await session.run({ input })).output;
const destination = gpu.device.createBuffer({ size: output.gpuBuffer.size, usage: ["storage", "copy_dst"] });
try {
  const encoder = gpu.gpu.createCommandEncoder();
  encoder.copyBufferToBuffer(output.gpuBuffer, 0, destination.gpu, 0, output.gpuBuffer.size);
  gpu.gpu.queue.submit([encoder.finish()]);
  await gpu.device.queue.flush();
} finally {
  destination.dispose();
  output.dispose();
  gpu.dispose();
  await session.release();
}
```

## Browser reference

Wrap the model output directly — zero copies, strict lifetime:

```ts
import * as ort from "onnxruntime-web/webgpu";
import { initFromDevice, type Buffer, type Compute } from "vgpu";

declare const modelBytes: Uint8Array;
declare const input: ort.Tensor;
declare const compute: Compute;
declare const destination: Buffer;
declare const workgroups: number;

const session = await ort.InferenceSession.create(modelBytes, {
  executionProviders: ["webgpu"],
  preferredOutputLocation: "gpu-buffer",
});
const gpu = await initFromDevice(await ort.env.webgpu.device);
const output = (await session.run({ input })).output;
const source = gpu.device.wrapBuffer(output.gpuBuffer);
try {
  compute.set({ source, destination }).dispatch(workgroups);
  await gpu.device.queue.flush();
} finally {
  source.dispose();
  output.dispose();
  gpu.dispose();
  await session.release();
}
```


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Buffers & ownership
description: The integration is deliberately narrow: vgpu adopts a device and wraps buffers — everything else stays in your hands.
---

# Buffers & ownership



## SDK signatures

```ts
export interface InitOptions {
  readonly adapter?: VGPUAdapter;
  /** Never set: adoption lives in `initFromDevice(device)`. */
  readonly device?: never;
  readonly powerPreference?: GPUPowerPreference;
  readonly requiredFeatures?: readonly GPUFeatureName[];
  readonly requiredLimits?: RequiredDeviceLimits;
  readonly label?: string;
}

/** vgpu creates the device and destroys it on dispose. */
export declare function init(options?: InitOptions): Promise<Gpu>;

/** vgpu adopts a device it did not create and never destroys it. */
export declare function initFromDevice(device: GPUDevice): Promise<Gpu>;
```

```ts
declare class Device {
  /** Wraps a caller-owned GPUBuffer without taking ownership of its native lifetime. */
  wrapBuffer(buffer: GPUBuffer): Buffer;
}
```

| Error code                     | Condition                                                          |
| ------------------------------ | ------------------------------------------------------------------ |
| `VGPU-INIT-DEVICE-INVALID`     | The device passed to `initFromDevice` fails structural validation. |
| `VGPU-EXTERNAL-BUFFER-INVALID` | `wrapBuffer` receives a value without finite `size` and `usage`.   |

To adopt a device owned by another library, call `initFromDevice(device)` instead of `init()`. The two entry points are separate on purpose: `init()` stays byte-minimal for apps that let vgpu create its own device, and bundlers drop `initFromDevice` entirely when you do not import it.

```ts
import * as ort from "onnxruntime-web/webgpu";
import { init, initFromDevice } from "vgpu";

// Requested device — vgpu creates it and destroys it on dispose.
const owned = await init({ powerPreference: "high-performance" });

// Adopted device — vgpu borrows it and never destroys it.
const gpu = await initFromDevice(await ort.env.webgpu.device);

// A device is not an init() option.
// @ts-expect-error adoption is initFromDevice(device)
await init({ device: await ort.env.webgpu.device });
```

`Device.wrapBuffer` wraps a caller-owned `GPUBuffer` in a vgpu `Buffer` without taking ownership. `wrapper.gpu` is the exact object you passed in. Disposing the wrapper detaches it from vgpu but never destroys the underlying buffer, and dispose is idempotent — a double dispose is a no-op.

```ts
import type { Gpu } from "vgpu";

declare const gpu: Gpu;
declare const raw: GPUBuffer;

const wrapper = gpu.device.wrapBuffer(raw); // raw: a GPUBuffer you own

wrapper.gpu === raw; // true — same object, no copy
wrapper.dispose();   // detaches from vgpu; raw is NOT destroyed
wrapper.dispose();   // no-op — dispose is idempotent
raw.size;            // still valid — its lifetime never left your hands
```

## Platform and ownership matrix

| Platform | Mode      | Public route                                                                 | Required lifetime                                                 |
| -------- | --------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| Browser  | Snapshot  | `initFromDevice(device)`; one raw encoder copy into a vgpu-owned destination | retain Tensor through submit and `await gpu.device.queue.flush()` |
| Browser  | Reference | `gpu.device.wrapBuffer(tensor.gpuBuffer)`                                    | retain → wrap → submit → flush → wrapper dispose → Tensor dispose |
| Node     | Snapshot  | same route after user-side pinned Dawn and ORT initialization                | retain Tensor through submit and `await gpu.device.queue.flush()` |
| Node     | Reference | same route after user-side pinned Dawn and ORT initialization                | retain → wrap → submit → flush → wrapper dispose → Tensor dispose |

Choose one of two consumption modes. Snapshot copies the model output once, GPU-to-GPU, into a buffer vgpu owns; after the copy you are decoupled from the runtime and may free its tensor at any time. Reference wraps the runtime's buffer directly with zero copies; the runtime keeps ownership and you must respect its lifetime.

### Reference mode

In reference mode, always `await gpu.device.queue.flush()` before disposing the source tensor. Do not dispose the tensor while vgpu work that reads it is still in flight — skipping the flush is an experimental fast path, not a supported contract.

```ts
import * as ort from "onnxruntime-web/webgpu";
import type { Buffer, Compute, Gpu } from "vgpu";

declare const session: ort.InferenceSession;
declare const input: ort.Tensor;
declare const gpu: Gpu;
declare const compute: Compute;
declare const destination: Buffer;
declare const workgroups: number;

const output = (await session.run({ input })).output;       // 1. retain the tensor
const source = gpu.device.wrapBuffer(output.gpuBuffer);     // 2. wrap — zero copies
compute.set({ source, destination }).dispatch(workgroups);  // 3. submit vgpu work
await gpu.device.queue.flush();                             // 4. flush — required
source.dispose();                                           // 5. drop the wrapper
output.dispose();                                           // 6. runtime may free its buffer now
```

### Snapshot mode

Snapshot needs no new API: copy once with the raw escape hatch (`gpu.gpu` is the shared `GPUDevice`, `buffer.gpu` the raw `GPUBuffer`), then treat the destination as any other vgpu buffer.

```ts
import * as ort from "onnxruntime-web/webgpu";
import type { Gpu } from "vgpu";

declare const session: ort.InferenceSession;
declare const input: ort.Tensor;
declare const gpu: Gpu;

const output = (await session.run({ input })).output;
const destination = gpu.device.createBuffer({
  size: output.gpuBuffer.size,
  usage: ["storage", "copy_dst"],
});

const encoder = gpu.gpu.createCommandEncoder();
encoder.copyBufferToBuffer(output.gpuBuffer, 0, destination.gpu, 0, output.gpuBuffer.size);
gpu.gpu.queue.submit([encoder.finish()]);
await gpu.device.queue.flush();

output.dispose(); // decoupled — destination is yours, independent of the runtime
```

## Scope

The integration is deliberately narrow: vgpu adopts a device and wraps buffers — everything else stays in your hands.

vgpu does not import ORT, resolve ORT WASM assets, mutate Node globals, validate GPUBuffer provenance, interpret Tensor dtype/shape/layout, recover a lost device, or transfer ownership of the borrowed device or buffer.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Overview
description: Share one GPUDevice between vgpu and a machine learning runtime so model outputs stay on the GPU.
---

# Overview



Share one `GPUDevice` between vgpu and a machine learning runtime so model outputs stay on the GPU.

The `initFromDevice(device)` entry point adopts a `GPUDevice` that another library created. Use it when an ML runtime such as ONNX Runtime Web already owns a WebGPU device and you want vgpu shaders to consume the model's output buffers without a CPU roundtrip. The API is model-agnostic: vision, diffusion, embedding, or LLM outputs are all just `GPUBuffer`s to vgpu.

vgpu never takes ownership of an adopted device. `gpu.dispose()` releases the resources vgpu created, but it never calls `device.destroy()` on a device it did not request.

```ts
import * as ort from "onnxruntime-web/webgpu";
import { initFromDevice } from "vgpu";

declare const session: ort.InferenceSession;
declare const input: ort.Tensor;

const gpu = await initFromDevice(await ort.env.webgpu.device); // one shared GPUDevice
const output = (await session.run({ input })).output;      // model output stays on the GPU
const source = gpu.device.wrapBuffer(output.gpuBuffer);    // consume it with zero copies
```

There are two ways to consume a model output: snapshot copies it once, GPU-to-GPU, into a buffer vgpu owns; reference wraps the runtime's buffer directly with zero copies. [Buffers & ownership](/docs/ml/buffers) explains when to use each and the lifetime contract that comes with them.

Start with the quickstart for your environment:

* [Quickstart: Browser](/docs/ml/browser) — share ONNX Runtime Web's device in a page and consume a model output.
* [Quickstart: Node](/docs/ml/node) — the pinned Dawn and ORT recipe, plus the portable fallback for hosts the stock binaries reject.
* [Buffers & ownership](/docs/ml/buffers) — snapshot vs reference, `wrapBuffer` semantics, errors, and lifetime.

For the full API surface, see the [reference](/docs/reference) for `init`, `initFromDevice`, `Device`, and `Buffer`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Quickstart: Node
description: Same route after the pinned Dawn and ORT setup.
---

# Quickstart: Node



In this quickstart you run the same integration in Node, with Dawn providing WebGPU. Node has no global WebGPU, so the recipe wires one up explicitly before ORT initializes — pin the versions below exactly; the combination is what vgpu validates.

The primary Node matrix is Node 22, `webgpu@0.4.0`, `onnxruntime-web@1.27.0`, and vgpu/software-renderer 0.1.6. The `webgpu@0.4.0` Linux ARM64 prebuilt requires glibc 2.38; run the primary recipe and generic-WASM negative proof on x64 CI or ARM64 with glibc 2.38 or newer. The explicitly labeled host fallback uses the supported `@vgpu/adapter-node` portable Dawn and software renderer. Executable recipes are under `experiments/ort-init-device/`.

If `require("webgpu")` fails with a `GLIBC_2.38` error, run `npx vgpu doctor` and follow its prescription: `npx vgpu install-dawn` installs vgpu's portable Dawn build (glibc 2.31 floor), and `npx vgpu install-software-renderer` adds a portable software renderer for hosts without a GPU. The recipes below run unchanged on that fallback.

## Node snapshot

Same route after the pinned Dawn and ORT setup:

```ts
import * as ort from "onnxruntime-web/webgpu";
import { create, globals } from "webgpu";
import { initFromDevice } from "vgpu/node";

declare const modelBytes: Uint8Array;
declare const input: ort.Tensor;
declare function createOrtSession(dawn: GPU, modelBytes: Uint8Array): Promise<ort.InferenceSession>;

Object.assign(globalThis, globals);
const dawn = create([]);
Object.defineProperty(globalThis, "navigator", { configurable: true, value: { gpu: dawn } });
const session = await createOrtSession(dawn, modelBytes);
const rawDevice = await ort.env.webgpu.device;
const gpu = await initFromDevice(rawDevice);
const output = (await session.run({ input })).output;
const destination = gpu.device.createBuffer({ size: output.gpuBuffer.size, usage: ["storage", "copy_dst"] });
try {
  const encoder = gpu.gpu.createCommandEncoder();
  encoder.copyBufferToBuffer(output.gpuBuffer, 0, destination.gpu, 0, output.gpuBuffer.size);
  gpu.gpu.queue.submit([encoder.finish()]);
  await gpu.device.queue.flush();
} finally {
  destination.dispose();
  output.dispose();
  gpu.dispose();
  await session.release();
}
```

## Node reference

Same zero-copy route on Node:

```ts
import * as ort from "onnxruntime-web/webgpu";
import { initFromDevice, type Buffer, type Compute } from "vgpu/node";

declare const session: ort.InferenceSession;
declare const input: ort.Tensor;
declare const compute: Compute;
declare const destination: Buffer;
declare const workgroups: number;

const rawDevice = await ort.env.webgpu.device;
const gpu = await initFromDevice(rawDevice);
const output = (await session.run({ input })).output;
const source = gpu.device.wrapBuffer(output.gpuBuffer);
try {
  compute.set({ source, destination }).dispatch(workgroups);
  await gpu.device.queue.flush();
} finally {
  source.dispose();
  output.dispose();
  gpu.dispose();
  await session.release();
}
```


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: createMockAdapter
description: `createMockAdapter(options?)` returns a pure-JavaScript `VGPUAdapter`. Its devices allocate in-memory buffers backed by `Uint8Array`, making core testable without Dawn or native GPU libraries.
---

# createMockAdapter



`options.features` declares the optional features the mock adapter supports (its
equivalent of `GPUAdapter.features`); it defaults to none. `requestDevice` rejects a
`requiredFeatures` entry outside that set with `VGPU-FEATURE-UNSUPPORTED`, and —
faithful to WebGPU — the created device's `features` holds exactly the requested
features, not the adapter's full set. This lets tests exercise feature-gated code
paths (e.g. `"depth-clip-control"`) both with and without the feature granted.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Camera state
description: Compose orbit, pan, dolly, zoom, smoothing, and projection with application-owned camera state.
---

# Camera state



# orbitRig

Creates the mutable state of an orbit camera: a followed point, a world-space pan offset, yaw, pitch and distance. Use it for the goal and current rigs of a smoothed orbit camera; you own the state, the input handling and the update order.

## Import

```ts
import { orbitRig } from "vgpu/scene";
```

## Signature

```ts
declare function orbitRig(initial?: import("vgpu/scene").OrbitRigOptions): import("vgpu/scene").OrbitRig;
```

## Parameters

| Param            | Type                | Required | Default     | Notes                                                                                                                          |
| ---------------- | ------------------- | -------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------ |
| initial          | `OrbitRigOptions`   | ✖        | `{}`        | Every omitted field takes its default.                                                                                         |
| initial.target   | `ArrayLike<number>` | ✖        | `[0, 0, 0]` | World-space point the camera looks at. Exactly 3 finite float32-representable numbers. Copied into a new `Float32Array`.       |
| initial.pan      | `ArrayLike<number>` | ✖        | `[0, 0, 0]` | World-space offset added to `target`. Same rules as `target`; copied into its own `Float32Array`.                              |
| initial.yaw      | `number`            | ✖        | `0`         | Radians around world +Y. Any finite value; never wrapped.                                                                      |
| initial.pitch    | `number`            | ✖        | `0`         | Radians of elevation. Strictly between `-π/2` and `π/2`. Not clamped to the default `RigLimits`; the next `orbit()` clamps it. |
| initial.distance | `number`            | ✖        | `1`         | Camera distance from the pivot in world units. Finite and positive.                                                            |

**Returns:** `OrbitRig` — a new object whose `target` and `pan` are new `Float32Array(3)`s. Two rigs from `orbitRig()` never share vectors, and later changes to your input arrays do not affect the rig.

**Throws:**

* `VGPU-CAMERA-SIZE` when `target` or `pan` does not have exactly 3 values — pass 3 components.
* `VGPU-CAMERA-VALUE` when a `target` or `pan` component is `NaN`, `Infinity` or outside finite float32 range (about ±3.4e38), `yaw` is not finite, `pitch` is not strictly between `-π/2` and `π/2`, or `distance` is not finite and positive — the message names the field; pass values in those ranges.

## Examples

```ts
import { degToRad, orbitRig } from "vgpu/scene";

const goal = orbitRig({ target: [0, 1, 0], yaw: degToRad(30), pitch: degToRad(20), distance: 6 });
const current = orbitRig({ target: [0, 1, 0], yaw: degToRad(30), pitch: degToRad(20), distance: 6 }); // separate vectors
```

A complete smoothed orbit camera following a moving object. Input changes the goal, `smoothRig` eases an independent current rig toward it, and the matrices are packed into the draw on every update:

```wgsl
// scene.wgsl
struct ModelData { world: mat4x4f }
struct CameraData { viewProjection: mat4x4f }
@group(0) @binding(0) var<uniform> model: ModelData;
@group(1) @binding(0) var<uniform> camera: CameraData;

struct VertexOut { @builtin(position) position: vec4f, @location(0) normal: vec3f }

@vertex fn vs_main(@location(0) position: vec3f, @location(1) normal: vec3f) -> VertexOut {
  var out: VertexOut;
  out.position = camera.viewProjection * model.world * vec4f(position, 1.0);
  out.normal = (model.world * vec4f(normal, 0.0)).xyz;
  return out;
}

@fragment fn fs_main(@location(0) normal: vec3f) -> @location(0) vec4f {
  let shade = max(dot(normalize(normal), normalize(vec3f(0.4, 1.0, 0.6))), 0.15);
  return vec4f(vec3f(0.9, 0.5, 0.2) * shade, 1.0);
}
```

```ts
import { clock, draw, frameLoop, geometry, init, surface } from "vgpu";
import {
  box, composeMatrix, dolly, orbit, orbitRig, pan, perspective, rigPose, smoothRig, viewMatrices, worldPerPixel,
  type CameraMatrices, type Lens, type Pose, type RigLimits,
} from "vgpu/scene";
import sceneShader from "./scene.wgsl";

const gpu = await init();
const canvas = document.querySelector("canvas")!;
const canvasSurface = surface(gpu, canvas);

// ---cut---
const cube = draw(gpu, { shader: sceneShader, geometry: geometry(gpu, box({ size: 1 })), cull: "back" });

const limits: RigLimits = { minPitch: -0.2, maxPitch: 1.2, minDistance: 2, maxDistance: 30 };
const goal = orbitRig({ yaw: 0.6, pitch: 0.4, distance: 6 }); // input writes here
const current = orbitRig({ yaw: 0.6, pitch: 0.4, distance: 6 }); // smoothRig writes here
const lens: Lens = { fov: 50, near: 0.1, far: 100 };
const pose: Pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const projection = new Float32Array(16);
const matrices: CameraMatrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
const cubeWorld = new Float32Array(16);

// input is yours: pick the listeners, buttons and sensitivity
canvas.addEventListener("pointermove", (event) => {
  if (event.buttons !== 1) return;
  if (event.shiftKey) {
    const unitsPerPixel = worldPerPixel(current.distance, lens, Math.max(1, canvas.clientHeight)); // CSS pixels
    pan(goal, -event.movementX * unitsPerPixel, event.movementY * unitsPerPixel); // along goal's right/up axes
  } else {
    orbit(goal, -event.movementX * 0.005, event.movementY * 0.005, limits); // 0.005 radians per CSS pixel
  }
});
canvas.addEventListener("wheel", (event) => {
  event.preventDefault();
  dolly(goal, Math.exp(event.deltaY * 0.001), limits); // factor > 1 moves away
}, { passive: false });

frameLoop(gpu, (currentFrame) => {
  const { time, deltaTime } = clock(gpu);

  // 1. move the followed object, then point the goal at it; goal.pan keeps the user's offset
  const angle = time * 0.5;
  composeMatrix({ position: [Math.cos(angle) * 3, 0.5, Math.sin(angle) * 3], rotation: [0, angle, 0] }, cubeWorld);
  goal.target.set(cubeWorld.subarray(12, 15)); // world translation

  // 2. the input handlers above already changed the goal with orbit/pan/dolly

  // 3. ease the independent current rig toward the goal
  smoothRig(current, goal, deltaTime, { timeConstant: 0.12 });

  // 4. matrices from the smoothed state
  rigPose(current, pose);
  perspective(lens, canvasSurface.size[0] / canvasSurface.size[1], projection);
  viewMatrices(pose, projection, matrices);

  // 5. set() packs the values now, so repeat it on every update
  cube.set({ model: { world: cubeWorld }, camera: { viewProjection: matrices.viewProjection } });
  currentFrame.pass({ target: canvasSurface, clear: [0.05, 0.05, 0.08, 1] }, (pass) => pass.draw(cube));
});
```

The shader author chooses `@group(1) @binding(0)` for the camera; reflection maps the binding name `camera`, so the TypeScript side names no group index. `smoothRig` runs before `rigPose`, so the pose always comes from the current rig, never the goal.

## Notes

* Keep two rigs: a goal that input and following write, and a current that only `smoothRig` writes. Create both with `orbitRig()`; `smoothRig` throws `VGPU-CAMERA-ALIAS` when they share an object or any vector storage.
* To follow an object, write its world position into `goal.target` every update and leave `goal.pan` alone: the pan is a separate world-space offset, so the user's pan survives while the target moves. To follow without lag, also write `current.target`, or pass `timeConstant: 0`.
* The rig is plain data. You may write any field directly; every function validates the rig it reads (finite float32 3-vectors, finite `yaw`, `pitch` strictly inside `(-π/2, π/2)`, finite positive `distance`) and throws before changing anything when it is invalid. Direct writes are not clamped to your `RigLimits`.
* No input listeners, pointer sensitivity, scheduler, camera node or automatic uniform upload exist: you call each function in the order you want, and you pack the result into your draws.
* **See also:** `OrbitRig`, `orbit`, `pan`, `dolly`, `smoothRig`, `rigPose`, `viewMatrices`, `worldPerPixel`. See [Scene composition](/docs/guides/scene-composition) for the complete update loop and [Scene migration](/docs/guides/scene-migration) for removed API replacements.

## Migrate from camera nodes and orbitControls

`perspectiveCamera`, `orthographicCamera`, the camera node classes and `orbitControls` are removed. Their state now lives in your `OrbitRig`, `Lens`, `Pose` and matrix arrays. The scene composition guide and the release migration notes carry the full removed-export table.

Before (removed API):

```ts illustrative
import { clock, frameLoop } from "vgpu";
import { orbitControls, perspectiveCamera } from "vgpu/scene";

const camera = perspectiveCamera({ fov: 45, aspect: 16 / 9, near: 0.1, far: 100, position: [2, 2, 3], target: [0, 0, 0] });
const controls = orbitControls(camera, { element: canvas, damping: 0.1 });
cube.set({ camera: { viewProjection: camera.viewProjection } }); // bound once, updated in place

frameLoop(gpu, () => {
  controls.update(clock(gpu).deltaTime);
});
```

After — convert the old `position`/`target` pair into a rig once:

```ts
import { orbitRig, perspective, rigPose, viewMatrices, type CameraMatrices, type Lens, type Pose } from "vgpu/scene";

const eye = { x: 2, y: 2, z: 3 }; // old options.position
const lookAt = { x: 0, y: 0, z: 0 }; // old options.target
const offsetX = eye.x - lookAt.x, offsetY = eye.y - lookAt.y, offsetZ = eye.z - lookAt.z;
const rig = orbitRig({
  target: [lookAt.x, lookAt.y, lookAt.z],
  yaw: Math.atan2(offsetX, offsetZ),
  pitch: Math.atan2(offsetY, Math.hypot(offsetX, offsetZ)),
  distance: Math.hypot(offsetX, offsetY, offsetZ),
});

const lens: Lens = { fov: 45, near: 0.1, far: 100 }; // old fov/near/far; aspect moves to perspective()
const pose: Pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const projection = new Float32Array(16);
const matrices: CameraMatrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };

rigPose(rig, pose);
perspective(lens, 16 / 9, projection);
viewMatrices(pose, projection, matrices); // then draw.set({ camera: { viewProjection: matrices.viewProjection } })
```

| Removed                                                                    | Replacement                                                                                                                                                                                                                       |
| -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `perspectiveCamera({ fov, aspect, near, far })`                            | A `Lens` plus `perspective(lens, aspect, out)`.                                                                                                                                                                                   |
| `orthographicCamera({ left, right, bottom, top, near, far })`              | `orthographic(bounds, out)`.                                                                                                                                                                                                      |
| camera `position` / `target` / `up` / `lookAt()` / parenting under a group | A world-space `Pose` from `rigPose(rig, pose)`, or one you compute yourself.                                                                                                                                                      |
| `camera.view`, `camera.viewProjection`                                     | `viewMatrices(pose, projection, matrices)`.                                                                                                                                                                                       |
| `camera.set({ fov, aspect, near, far })`                                   | Change the `Lens` (or call `zoom`) and call `perspective` again.                                                                                                                                                                  |
| `orbitControls(node, { element, rotateSpeed, zoomSpeed })`                 | Your own listeners calling `orbit`, `pan` and `dolly` on the goal rig; multiply pointer deltas by your sensitivity (the old default was `0.005` radians per pixel). The old wheel zoom changed distance: use `dolly`, not `zoom`. |
| `orbitControls` `damping`, `distance`, `pitch` options                     | `smoothRig(current, goal, dt, { timeConstant })` (the old `damping` was already a time constant in seconds) and `RigLimits`.                                                                                                      |
| `controls.update(deltaTime?)`                                              | `smoothRig` with an explicit `dt`.                                                                                                                                                                                                |
| binding `camera.viewProjection` once                                       | `draw.set({ camera: { viewProjection: matrices.viewProjection } })` after every change.                                                                                                                                           |
| `VGPU-SCENE-VALUE-INVALID` from cameras                                    | `VGPU-CAMERA-VALUE`, `VGPU-CAMERA-SIZE`, `VGPU-CAMERA-ALIAS`.                                                                                                                                                                     |

Behavior changes to check when you migrate:

* `dt` is explicit. `smoothRig` has no fallback frame time; pass `clock(gpu).deltaTime` or your own finite, nonnegative seconds.
* Distance smooths in log space, so zooming from 1 to 100 passes 10 halfway instead of 50.5. The old controls interpolated distance linearly.
* The default pitch limits are `±(π/2 − 1e-4)` radians instead of the old `±(π/2 − 0.01)`, so the camera can get closer to the poles. Pass `{ minPitch: -(Math.PI / 2 - 0.01), maxPitch: Math.PI / 2 - 0.01 }` to keep the old range.
* The old orthographic camera rejected equal bounds but accepted flipped (mirrored) horizontal or vertical ranges. `orthographic` now requires `left < right` and `bottom < top` and throws `VGPU-CAMERA-VALUE` for flipped bounds. To mirror an image, build your own projection and pass it to `viewMatrices`. `near` may now be `0` (the old camera required a positive `near` and defaulted it to `0.1`).
* `Lens.far` must be finite. For an infinite far plane, build your own projection and pass it to `viewMatrices`.
* Matrices no longer update in place behind a stable binding. Each `set()` copies values when you call it.

***

# OrbitRig

The mutable orbit-camera state created by `orbitRig()` and changed by `orbit`, `pan`, `dolly` and `smoothRig`.

## Import

```ts
import type { OrbitRig } from "vgpu/scene";
```

## Signature

```ts
interface OrbitRig {
  target: Float32Array;
  pan: Float32Array;
  yaw: number;
  pitch: number;
  distance: number;
}
```

## Parameters

| Field    | Type           | Required | Default | Notes                                                                                                                                                              |
| -------- | -------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| target   | `Float32Array` | ✔        | —       | Exactly 3 finite values: the world-space point to follow. `orbitRig()` starts it at `[0, 0, 0]`. Write it (`goal.target.set(...)`) to follow an object.            |
| pan      | `Float32Array` | ✔        | —       | Exactly 3 finite values: a world-space offset added to `target`. `orbitRig()` starts it at `[0, 0, 0]`. `pan()` accumulates into it.                               |
| yaw      | `number`       | ✔        | —       | Radians around world +Y, finite, never wrapped. `0` places the camera on the +Z side of the pivot; positive yaw moves it toward +X. `orbitRig()` starts it at `0`. |
| pitch    | `number`       | ✔        | —       | Radians, strictly between `-π/2` and `π/2`. Positive pitch raises the camera above the pivot so it looks down. `orbitRig()` starts it at `0`.                      |
| distance | `number`       | ✔        | —       | Finite, positive world-space distance from the pivot to the camera. `orbitRig()` starts it at `1`.                                                                 |

## Examples

```ts
import { orbitRig, type OrbitRig } from "vgpu/scene";

const rig: OrbitRig = orbitRig({ distance: 8 });
rig.target.set([0, 2, -1]); // direct writes are allowed; the next rig function validates them
rig.yaw += Math.PI / 8;
```

## Notes

* The pivot is `target + pan`. The camera sits at `pivot + distance × [cos(pitch)·sin(yaw), sin(pitch), cos(pitch)·cos(yaw)]` and looks at the pivot along its local -Z axis, with +Y up (right-handed).
* Keep `target` and `pan` in separate storage. Build rigs with `orbitRig()` instead of object literals that share or overlap arrays: `smoothRig` rejects overlapping vectors with `VGPU-CAMERA-ALIAS`.
* `yaw` is unwrapped on purpose, so continuous spins keep accumulating. If you assign an absolute heading to `goal.yaw`, unwrap it relative to the current yaw yourself, or `smoothRig` takes the long way around.
* **See also:** `orbitRig`, `OrbitRigOptions`, `RigLimits`, `rigPose`.

***

# OrbitRigOptions

Initial values for `orbitRig()`. Every field is optional and copied.

## Import

```ts
import type { OrbitRigOptions } from "vgpu/scene";
```

## Signature

```ts
interface OrbitRigOptions {
  target?: ArrayLike<number>;
  pan?: ArrayLike<number>;
  yaw?: number;
  pitch?: number;
  distance?: number;
}
```

## Parameters

| Field    | Type                | Required | Default     | Notes                                                   |
| -------- | ------------------- | -------- | ----------- | ------------------------------------------------------- |
| target   | `ArrayLike<number>` | ✖        | `[0, 0, 0]` | Exactly 3 finite float32-representable numbers. Copied. |
| pan      | `ArrayLike<number>` | ✖        | `[0, 0, 0]` | Exactly 3 finite float32-representable numbers. Copied. |
| yaw      | `number`            | ✖        | `0`         | Finite radians.                                         |
| pitch    | `number`            | ✖        | `0`         | Radians strictly between `-π/2` and `π/2`.              |
| distance | `number`            | ✖        | `1`         | Finite and positive.                                    |

## Examples

```ts
import { orbitRig, type OrbitRigOptions } from "vgpu/scene";

const start: OrbitRigOptions = { target: new Float32Array([0, 1, 0]), pitch: 0.3, distance: 5 };
const goal = orbitRig(start);
const current = orbitRig(start); // same values, independent vectors
```

## Notes

* One options object can seed several rigs: each `orbitRig()` call copies `target` and `pan` into new arrays.
* **See also:** `orbitRig`, `OrbitRig`.

***

# RigLimits

Pitch and distance bounds applied by `orbit()` and `dolly()`. Limits are not stored in the rig: pass the same object on every call that should respect them.

## Import

```ts
import type { RigLimits } from "vgpu/scene";
```

## Signature

```ts
interface RigLimits {
  minPitch?: number;
  maxPitch?: number;
  minDistance?: number;
  maxDistance?: number;
}
```

## Parameters

| Field       | Type     | Required | Default                          | Notes                                                          |
| ----------- | -------- | -------- | -------------------------------- | -------------------------------------------------------------- |
| minPitch    | `number` | ✖        | `-(π/2 − 1e-4)` (≈ `-1.5706963`) | Radians, strictly between `-π/2` and `π/2`, and `<= maxPitch`. |
| maxPitch    | `number` | ✖        | `π/2 − 1e-4` (≈ `1.5706963`)     | Radians, strictly between `-π/2` and `π/2`, and `>= minPitch`. |
| minDistance | `number` | ✖        | `1e-4`                           | Finite, positive, and `<= maxDistance`.                        |
| maxDistance | `number` | ✖        | `Infinity`                       | Positive and finite, or `Infinity`.                            |

Equal minimum and maximum values are valid and pin the value.

## Examples

```ts
import { dolly, orbit, orbitRig, type RigLimits } from "vgpu/scene";

const limits: RigLimits = { minPitch: 0.05, maxPitch: 1.4, minDistance: 2, maxDistance: 40 };
const goal = orbitRig({ pitch: 0.3, distance: 10 });
orbit(goal, 0, 5, limits); // pitch clamps to 1.4
dolly(goal, 100, limits); // distance clamps to 40
```

## Notes

* `orbit()` and `dolly()` validate all four fields on every call, even the ones they do not apply: an invalid distance limit also fails `orbit()`. One shared limits object for both calls is the intended use.
* Limits bound only the results of `orbit()` (pitch) and `dolly()` (distance). `orbitRig()`, `pan()`, `smoothRig()` and direct field writes ignore them. `smoothRig` stays between the current and goal values, so it stays inside your limits when both rigs are.
* Invalid or reversed limits throw `VGPU-CAMERA-VALUE` before the rig changes.
* **See also:** `orbit`, `dolly`, `OrbitRig`.

***

# orbit

Rotates an orbit rig around its pivot by adding yaw and pitch deltas, clamping pitch to limits. Use it from your pointer or keyboard handlers on the goal rig. This `orbit` changes camera state; it replaces the removed object-animation helper `orbit(time, options)`.

## Import

```ts
import { orbit } from "vgpu/scene";
```

## Signature

```ts
declare function orbit(
  rig: import("vgpu/scene").OrbitRig,
  deltaYaw: number,
  deltaPitch: number,
  limits?: import("vgpu/scene").RigLimits,
): import("vgpu/scene").OrbitRig;
```

## Parameters

| Param      | Type        | Required | Default                                                                  | Notes                                                                                                                                      |
| ---------- | ----------- | -------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| rig        | `OrbitRig`  | ✔        | —                                                                        | Mutated: `yaw` and `pitch` only. Validated in full first.                                                                                  |
| deltaYaw   | `number`    | ✔        | —                                                                        | Finite radians added to `rig.yaw`. Not wrapped or clamped.                                                                                 |
| deltaPitch | `number`    | ✔        | —                                                                        | Finite radians added to `rig.pitch`; the sum is clamped to `[minPitch, maxPitch]`. `0` still clamps an out-of-range pitch into the limits. |
| limits     | `RigLimits` | ✖        | `{}` (every default: pitch `±(π/2 − 1e-4)`, distance `[1e-4, Infinity]`) | See `RigLimits`. All four fields are validated.                                                                                            |

**Returns:** `OrbitRig` — the same `rig`, for chaining.

**Throws:** every check runs before `rig` changes.

* `VGPU-CAMERA-SIZE` when `rig.target` or `rig.pan` does not have exactly 3 values — allocate 3-element vectors, for example with `orbitRig()`.
* `VGPU-CAMERA-VALUE` when `limits` are invalid or reversed, the rig state is invalid (non-finite vector component or `yaw`, `pitch` outside `(-π/2, π/2)`, non-positive `distance`), a delta is not finite, or `yaw + deltaYaw` or `pitch + deltaPitch` overflows to a non-finite value — the message names the field; pass finite deltas, ordered limits inside the stated ranges and a valid rig.

## Examples

```ts
import { degToRad, orbit, orbitRig } from "vgpu/scene";

const goal = orbitRig({ distance: 5 });
orbit(goal, degToRad(90), degToRad(30)); // camera moves from +Z to +X and rises 30°
orbit(goal, 4 * Math.PI, 0); // yaw keeps accumulating: no wrap
```

Order matters with `pan`, because `pan` moves along the rig's current axes:

```ts
import { orbit, orbitRig, pan } from "vgpu/scene";

const panThenOrbit = orbitRig();
pan(panThenOrbit, 1, 0); // offset along the yaw-0 right axis, world +X
orbit(panThenOrbit, Math.PI / 2, 0); // the camera swings around the panned pivot; the offset stays +X

const orbitThenPan = orbitRig();
orbit(orbitThenPan, Math.PI / 2, 0);
pan(orbitThenPan, 1, 0); // offset along the yaw-90° right axis, world -Z
```

## Notes

* `orbit` only changes angles. It never moves `target`, `pan` or `distance`, and never touches a `Lens`.
* There is no built-in sensitivity or sign convention. `orbit(goal, -movementX * k, movementY * k, limits)` gives the common drag-to-rotate feel; choose `k` in radians per pixel yourself.
* **See also:** `pan`, `dolly`, `RigLimits`, `smoothRig`.

## Migrate from orbit(time, options)

The removed `orbit(time, { radius, height, speed }): Mat4` animated an object; the new `orbit(rig, deltaYaw, deltaPitch, limits?): OrbitRig` changes camera state. TypeScript rejects the old call because the first parameter is now an `OrbitRig`.

Before (removed API):

```ts illustrative
import { orbit } from "vgpu/scene";

const model = orbit(time, { radius: 2, height: 0.5, speed: 0.4 }); // new matrix every call
```

After — build the same matrix with `composeMatrix`, using explicit sine/cosine translation and a Y rotation:

```ts
import { composeMatrix } from "vgpu/scene";

const time = 1.5; // your explicit clock value
const modelMatrix = new Float32Array(16); // allocate once, reuse every frame

const angle = time * 0.4; // old speed
composeMatrix({
  position: [Math.cos(angle) * 2, 0.5, Math.sin(angle) * 2], // old radius and height
  rotation: [0, angle, 0], // Y rotation, same as the old matrix
}, modelMatrix);
```

The result matches the old matrix up to float rounding. `composeMatrix` writes into your array instead of allocating, and rejects non-finite values with `VGPU-SCENE-VALUE`.

***

# pan

Moves an orbit rig's pivot sideways and vertically in the rig's own screen axes, accumulating into its world-space `pan` offset. Use it on the goal rig for drag-to-pan.

## Import

```ts
import { pan } from "vgpu/scene";
```

## Signature

```ts
declare function pan(rig: import("vgpu/scene").OrbitRig, right: number, up: number): import("vgpu/scene").OrbitRig;
```

## Parameters

| Param | Type       | Required | Default | Notes                                                                                                                                       |
| ----- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| rig   | `OrbitRig` | ✔        | —       | Mutated: `pan` only. Its `yaw` and `pitch` define the axes. Validated in full first.                                                        |
| right | `number`   | ✔        | —       | Finite world units along the rig's right axis `[cos(yaw), 0, -sin(yaw)]`. Positive moves the pivot, and so the view, to the camera's right. |
| up    | `number`   | ✔        | —       | Finite world units along the rig's up axis `[-sin(yaw)·sin(pitch), cos(pitch), -cos(yaw)·sin(pitch)]`. Positive moves the view up.          |

**Returns:** `OrbitRig` — the same `rig`, for chaining.

**Throws:** every check runs before `rig` changes.

* `VGPU-CAMERA-SIZE` when `rig.target` or `rig.pan` does not have exactly 3 values — allocate 3-element vectors.
* `VGPU-CAMERA-VALUE` when the rig state is invalid, `right` or `up` is not finite, or a new `pan` component is outside finite float32 range — pass finite offsets and a valid rig.

## Examples

Grab-and-drag panning, converting CSS-pixel pointer deltas into world units at the orbit distance:

```ts
import { orbitRig, pan, worldPerPixel, type Lens } from "vgpu/scene";

const canvas = document.querySelector("canvas")!;
const lens: Lens = { fov: 50, near: 0.1, far: 100 };
const goal = orbitRig({ distance: 8 });
const current = orbitRig({ distance: 8 });

canvas.addEventListener("pointermove", (event) => {
  if (event.buttons !== 1) return;
  const unitsPerPixel = worldPerPixel(current.distance, lens, Math.max(1, canvas.clientHeight));
  pan(goal, -event.movementX * unitsPerPixel, event.movementY * unitsPerPixel); // content follows the pointer
});
```

## Notes

* Pan the goal, and the axes come from the goal's `yaw`/`pitch` — the direction the camera is heading — not from a lagging current rig. `pan()` uses exactly the rig you pass.
* The offset is stored in world space. Later `orbit` calls rotate the camera around the panned pivot without rotating the offset, and writing `target` to follow an object keeps the offset.
* Reset panning with `goal.pan.fill(0)`.
* **See also:** `worldPerPixel`, `orbit`, `OrbitRig`.

***

# dolly

Scales an orbit rig's distance by a factor, clamped to distance limits. Use it for wheel or pinch "zoom" that physically moves the camera; use `zoom` to change the lens instead.

## Import

```ts
import { dolly } from "vgpu/scene";
```

## Signature

```ts
declare function dolly(
  rig: import("vgpu/scene").OrbitRig,
  factor: number,
  limits?: import("vgpu/scene").RigLimits,
): import("vgpu/scene").OrbitRig;
```

## Parameters

| Param  | Type        | Required | Default                                                                  | Notes                                                                                                                                                       |
| ------ | ----------- | -------- | ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| rig    | `OrbitRig`  | ✔        | —                                                                        | Mutated: `distance` only. Validated in full first.                                                                                                          |
| factor | `number`    | ✔        | —                                                                        | Finite and positive. `distance × factor` is clamped to `[minDistance, maxDistance]`. `> 1` moves away, `< 1` moves closer, `1` only clamps. `0` is invalid. |
| limits | `RigLimits` | ✖        | `{}` (every default: pitch `±(π/2 − 1e-4)`, distance `[1e-4, Infinity]`) | See `RigLimits`. All four fields are validated.                                                                                                             |

**Returns:** `OrbitRig` — the same `rig`, for chaining.

**Throws:** every check runs before `rig` changes.

* `VGPU-CAMERA-SIZE` when `rig.target` or `rig.pan` does not have exactly 3 values — allocate 3-element vectors.
* `VGPU-CAMERA-VALUE` when `limits` are invalid or reversed, the rig state is invalid, `factor` is not finite and positive, or `distance × factor` overflows to a non-finite value — pass a finite positive factor, ordered limits and a valid rig.

## Examples

```ts
import { dolly, orbitRig } from "vgpu/scene";

const canvas = document.querySelector("canvas")!;
const goal = orbitRig({ distance: 10 });

canvas.addEventListener("wheel", (event) => {
  event.preventDefault();
  dolly(goal, Math.exp(event.deltaY * 0.001), { minDistance: 1, maxDistance: 50 }); // exp keeps factors positive
}, { passive: false });
```

## Notes

* `dolly` never changes a `Lens`, and `zoom` never changes a rig: pick the one you want. Dollying changes perspective (near objects grow faster than far ones); zooming only narrows the field of view.
* `dolly` does not change an orthographic image's size, because orthographic bounds do not depend on distance. Scale the bounds instead.
* **See also:** `zoom`, `orbit`, `RigLimits`.

***

# smoothRig

Eases a current orbit rig toward a goal rig by an exponential step of `dt` seconds. Use it once per update, after input and following have changed the goal and before `rigPose`.

## Import

```ts
import { smoothRig } from "vgpu/scene";
```

## Signature

```ts
declare function smoothRig(
  current: import("vgpu/scene").OrbitRig,
  goal: import("vgpu/scene").OrbitRig,
  dt: number,
  options: { timeConstant: number },
): import("vgpu/scene").OrbitRig;
```

## Parameters

| Param                | Type       | Required | Default | Notes                                                                                                   |
| -------------------- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- |
| current              | `OrbitRig` | ✔        | —       | Mutated: every field moves toward `goal`. Must not be `goal` and must not share vector storage with it. |
| goal                 | `OrbitRig` | ✔        | —       | Read-only; never modified. Its `target` and `pan` may overlap each other.                               |
| dt                   | `number`   | ✔        | —       | Seconds since the last step. Finite and `>= 0`. There is no fallback frame time.                        |
| options.timeConstant | `number`   | ✔        | —       | Seconds, finite and `>= 0`: the time to cover about 63% of the remaining gap. `0` snaps to the goal.    |

**Returns:** `OrbitRig` — the same `current`, for chaining.

**Throws:** every check runs before `current` changes.

* `VGPU-CAMERA-ALIAS` when `current` and `goal` are the same object, `current.target` overlaps `current.pan`, or either `current` vector overlaps either `goal` vector — including different views of one buffer whose byte ranges overlap — create each rig with `orbitRig()` so every vector has its own storage.
* `VGPU-CAMERA-SIZE` when a `target` or `pan` of either rig does not have exactly 3 values — allocate 3-element vectors.
* `VGPU-CAMERA-VALUE` when either rig's state is invalid, `dt` or `timeConstant` is negative, `NaN` or `Infinity`, or a result is non-finite or leaves the valid pitch or distance range — pass valid rigs and finite nonnegative `dt` and `timeConstant`.

## Examples

```ts
import { clock, frameLoop, init } from "vgpu";
import { orbitRig, smoothRig } from "vgpu/scene";

const gpu = await init();
const goal = orbitRig({ distance: 5 });
const current = orbitRig({ distance: 5 });

frameLoop(gpu, () => {
  smoothRig(current, goal, clock(gpu).deltaTime, { timeConstant: 0.15 });
});
```

Distance moves in log space, so the halfway point between 1 and 100 is 10:

```ts
import { orbitRig, smoothRig } from "vgpu/scene";

const current = orbitRig({ distance: 1 });
const goal = orbitRig({ distance: 100 });
smoothRig(current, goal, Math.LN2, { timeConstant: 1 }); // k = 0.5
console.log(current.distance); // ≈ 10

smoothRig(current, goal, 0, { timeConstant: 0 }); // timeConstant 0 snaps, even with dt 0
console.log(current.distance); // 100
```

## Notes

* Each call computes `k = 1 − exp(−dt / timeConstant)` (as `-Math.expm1(-dt / timeConstant)`), then moves `target`, `pan`, `yaw` and `pitch` linearly by `k` and `distance` geometrically: `exp(lerp(log current, log goal, k))`. `timeConstant: 0` gives `k = 1`; `dt: 0` with a positive `timeConstant` gives `k = 0` and leaves `current` unchanged.
* Yaw is interpolated unwrapped. A goal at `yaw + 4π` spins the camera twice; this is intentional for continuous spins. Keep the goal's yaw continuous — change it with `orbit()` deltas — rather than assigning wrapped absolute angles.
* For a fixed goal, one step of `dt₁ + dt₂` lands where two steps of `dt₁` and `dt₂` land, up to float rounding. When the goal moves between calls (following, dragging), the path depends on how often you call `smoothRig`; there is no frame-rate independence guarantee for moving goals.
* Results stay between the current and goal values, so a current rig inside your `RigLimits` stays inside them while it converges to a goal that is also inside them.
* **See also:** `orbitRig`, `rigPose`, `OrbitRig`.

***

# rigPose

Converts an orbit rig into a world-space camera `Pose`: the camera position and its orientation quaternion. Use it on the current (smoothed) rig before `viewMatrices`.

## Import

```ts
import { rigPose } from "vgpu/scene";
```

## Signature

```ts
declare function rigPose(rig: import("vgpu/scene").OrbitRig, out: import("vgpu/scene").Pose): import("vgpu/scene").Pose;
```

## Parameters

| Param | Type       | Required | Default | Notes                                                                                                                                                         |
| ----- | ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| rig   | `OrbitRig` | ✔        | —       | Read-only. Validated in full.                                                                                                                                 |
| out   | `Pose`     | ✔        | —       | `out.position` needs exactly 3 elements and `out.quaternion` exactly 4. The two must not overlap. Both are overwritten on success and untouched on any error. |

**Returns:** `Pose` — the same `out`. `out.position = target + pan + distance × [cos(pitch)·sin(yaw), sin(pitch), cos(pitch)·cos(yaw)]`; `out.quaternion` is the unit XYZW quaternion `Ry(yaw) × Rx(−pitch)`, which points the camera's -Z axis at `target + pan` with +Y up.

**Throws:** every check runs before `out` changes.

* `VGPU-CAMERA-SIZE` when `rig.target` or `rig.pan` does not have exactly 3 values, `out.position` does not have exactly 3, or `out.quaternion` does not have exactly 4 — allocate `{ position: new Float32Array(3), quaternion: new Float32Array(4) }`.
* `VGPU-CAMERA-ALIAS` when `out.position` and `out.quaternion` overlap — allocate disjoint arrays.
* `VGPU-CAMERA-VALUE` when the rig state is invalid, or a position component is outside finite float32 range — keep the rig finite and in range.

## Examples

```ts
import { orbitRig, rigPose, type Pose } from "vgpu/scene";

const rig = orbitRig({ target: [0, 1, 0], distance: 4 });
const pose: Pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };

rigPose(rig, pose); // position [0, 1, 4], identity rotation: on +Z of the target, looking down -Z
rig.yaw = Math.PI / 2;
rigPose(rig, pose); // position ≈ [4, 1, 0], looking down world -X at the target
```

## Notes

* Everything is read before anything is written, so `out` may share storage with the rig's `target` or `pan`. That overwrites your rig; normally keep one separate `Pose` and reuse it.
* The pose is world-space. There is no parent node: to mount the camera on a moving object, follow it through `target` or compute your own `Pose`.
* **See also:** `Pose`, `viewMatrices`, `OrbitRig`.

***

# Pose

A world-space camera position and orientation. Produced by `rigPose` or built by you (first-person, flight or tracked cameras) and consumed by `viewMatrices`.

## Import

```ts
import type { Pose } from "vgpu/scene";
```

## Signature

```ts
interface Pose {
  position: Float32Array;
  quaternion: Float32Array;
}
```

## Parameters

| Field      | Type           | Required | Default | Notes                                                                                                                                                                      |
| ---------- | -------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| position   | `Float32Array` | ✔        | —       | Exactly 3 finite values: the camera's world-space position.                                                                                                                |
| quaternion | `Float32Array` | ✔        | —       | Exactly 4 finite values in XYZW order, nonzero length. `[0, 0, 0, 1]` looks down world -Z with +Y up. `viewMatrices` normalizes a copy; `rigPose` writes unit quaternions. |

## Examples

A first-person pose you compute yourself — yaw only, eye height 1.7:

```ts
import { degToRad, type Pose } from "vgpu/scene";

const heading = degToRad(30); // turn left 30° from -Z
const pose: Pose = {
  position: new Float32Array([0, 1.7, 5]),
  quaternion: new Float32Array([0, Math.sin(heading / 2), 0, Math.cos(heading / 2)]),
};
```

## Notes

* The camera looks along its local -Z axis with local +Y up, in a right-handed world with +Y up. A pose has no scale.
* Keep `position` and `quaternion` in separate storage: `rigPose` rejects overlapping output fields with `VGPU-CAMERA-ALIAS`.
* **See also:** `rigPose`, `viewMatrices`.

***

# Lens

The perspective lens: vertical field of view in degrees and the near and far clip distances. Read by `perspective`, `zoom` and `worldPerPixel`.

## Import

```ts
import type { Lens } from "vgpu/scene";
```

## Signature

```ts
interface Lens {
  fov: number;
  near: number;
  far: number;
}
```

## Parameters

| Field | Type     | Required | Default | Notes                                                                         |
| ----- | -------- | -------- | ------- | ----------------------------------------------------------------------------- |
| fov   | `number` | ✔        | —       | Vertical field of view in degrees, finite and strictly between `0` and `180`. |
| near  | `number` | ✔        | —       | Near clip distance, finite and positive.                                      |
| far   | `number` | ✔        | —       | Far clip distance, finite and greater than `near`. `Infinity` is rejected.    |

## Examples

```ts
import { perspective, type Lens } from "vgpu/scene";

const lens: Lens = { fov: 45, near: 0.1, far: 200 };
const projection = perspective(lens, 16 / 9, new Float32Array(16));
lens.fov = 30; // plain data: change it, then rebuild the projection
perspective(lens, 16 / 9, projection);
```

## Notes

* A lens is independent of the rig. Changing the lens never moves the camera, and `orbit`/`pan`/`dolly` never change the lens. Nothing re-runs `perspective` for you after a lens change.
* `fov` is degrees while rig angles are radians. Convert rig angles with `degToRad`; pass `fov` in degrees.
* There is no `lens()` factory; write the object literal.
* **See also:** `perspective`, `zoom`, `worldPerPixel`.

***

# zoom

Narrows or widens a lens by a factor applied to `tan(fov / 2)`, clamped to field-of-view limits. Use it for optical zoom that does not move the camera.

## Import

```ts
import { zoom } from "vgpu/scene";
```

## Signature

```ts
declare function zoom(
  lens: import("vgpu/scene").Lens,
  factor: number,
  limits?: { minFov?: number; maxFov?: number },
): import("vgpu/scene").Lens;
```

## Parameters

| Param         | Type     | Required | Default                   | Notes                                                                                                                                                                                                                                                                        |
| ------------- | -------- | -------- | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| lens          | `Lens`   | ✔        | —                         | Mutated: `fov` only. Validated in full first.                                                                                                                                                                                                                                |
| factor        | `number` | ✔        | —                         | Any finite positive number, including extremes such as `Number.MIN_VALUE` and `Number.MAX_VALUE`. The new FOV is `2 × atan(tan(fov / 2) / factor)`, clamped to `[minFov, maxFov]`. `> 1` narrows (magnifies), `< 1` widens, `2` shows half the height at the focus distance. |
| limits.minFov | `number` | ✖        | `1e-4`                    | Degrees, strictly between `0` and `180`, `<= maxFov`.                                                                                                                                                                                                                        |
| limits.maxFov | `number` | ✖        | `180 − 1e-4` (`179.9999`) | Degrees, strictly between `0` and `180`, `>= minFov`.                                                                                                                                                                                                                        |

**Returns:** `Lens` — the same `lens`, for chaining.

**Throws:** checks run in this order — limits, lens, factor, computed FOV — and all of them run before `lens` changes.

* `VGPU-CAMERA-VALUE` when `limits.minFov` or `limits.maxFov` is not strictly between `0` and `180` or `minFov > maxFov`, the lens is invalid (see `Lens`), `factor` is `0`, negative, `NaN` or `Infinity`, or the computed FOV arithmetic is non-finite — pass ordered limits inside `(0, 180)`, a valid lens and a finite positive factor. The last check is a guard: for inputs that pass the earlier checks, `tan` and `atan` keep the result finite.

## Examples

```ts
import { perspective, zoom, type Lens } from "vgpu/scene";

const lens: Lens = { fov: 60, near: 0.1, far: 100 };
const projection = new Float32Array(16);

zoom(lens, 2, { minFov: 10, maxFov: 90 }); // fov ≈ 32.2°: tan(fov/2) halves
perspective(lens, 16 / 9, projection); // zoom changes the lens; rebuild the projection yourself
```

Extreme factors clamp instead of throwing:

```ts
import { zoom, type Lens } from "vgpu/scene";

const wide: Lens = { fov: 60, near: 0.1, far: 100 };
zoom(wide, Number.MIN_VALUE); // raw FOV rounds to 180°; clamps to maxFov: 179.9999

const narrow: Lens = { fov: 60, near: 0.1, far: 100 };
zoom(narrow, Number.MAX_VALUE, { minFov: 10, maxFov: 90 }); // raw FOV ≈ 0°; clamps to minFov: 10
```

## Notes

* Every finite positive factor is valid. When the raw FOV is a finite value outside your limits — including one that rounds to exactly `0` or `180` degrees — `zoom` clamps it into `[minFov, maxFov]`. The limits are validated to lie strictly inside `(0, 180)`, so the result is always a valid `Lens.fov`. Clamp the factor yourself if you want to reject extreme input instead.
* `zoom` never changes a rig, and `dolly` never changes the lens. Use `dolly` to move the camera, `zoom` to change magnification.
* After `zoom`, `worldPerPixel` returns smaller values at the same distance, so drag panning stays matched to the screen if you recompute it.
* **See also:** `Lens`, `dolly`, `perspective`, `worldPerPixel`.

***

# perspective

Writes a right-handed perspective projection with WebGPU depth (`0` at near, `1` at far) into `out`. Use it with a `Lens` and your render target's aspect ratio.

## Import

```ts
import { perspective } from "vgpu/scene";
```

## Signature

```ts
declare function perspective(
  lens: import("vgpu/scene").Lens,
  aspect: number,
  out: import("vgpu/scene").Mat4,
): import("vgpu/scene").Mat4;
```

## Parameters

| Param  | Type     | Required | Default | Notes                                                                                                                    |
| ------ | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------ |
| lens   | `Lens`   | ✔        | —       | Vertical FOV in degrees and finite near/far. Read-only.                                                                  |
| aspect | `number` | ✔        | —       | Width / height, finite and positive. Use the target's size, for example `canvasSurface.size[0] / canvasSurface.size[1]`. |
| out    | `Mat4`   | ✔        | —       | `Float32Array` with exactly 16 elements. Overwritten on success, untouched on any error.                                 |

**Returns:** `Mat4` — the same `out`, column-major: with `f = 1 / tan(fov / 2)`, it is `[f/aspect, 0, 0, 0,  0, f, 0, 0,  0, 0, far/(near−far), −1,  0, 0, far·near/(near−far), 0]`. View-space points at `z = −near` map to depth `0` and at `z = −far` to depth `1`.

**Throws:**

* `VGPU-CAMERA-VALUE` when the lens is invalid, `aspect` is not finite and positive, or an element is outside finite float32 range (for example an extremely small `fov`) — pass a valid lens and a positive aspect.
* `VGPU-CAMERA-SIZE` when `out` does not have exactly 16 elements — allocate `new Float32Array(16)`.

## Examples

```ts
import { perspective, type Lens } from "vgpu/scene";

const lens: Lens = { fov: 60, near: 0.1, far: 100 };
const projection = new Float32Array(16);
perspective(lens, 1920 / 1080, projection);
```

## Notes

* The depth range matches the default draw depth state (`compare: "less-equal"`) and pass `clearDepth: 1`. For reversed-Z or an infinite far plane, write your own 16-value projection and pass it to `viewMatrices`.
* Call `perspective` again after changing the lens or when the target resizes; nothing tracks those for you.
* **See also:** `Lens`, `orthographic`, `viewMatrices`.

***

# orthographic

Writes a right-handed orthographic projection with WebGPU depth into `out` from a view-space box. Use it for CAD, 2D-in-3D, isometric or shadow-map views without perspective foreshortening.

## Import

```ts
import { orthographic } from "vgpu/scene";
```

## Signature

```ts
declare function orthographic(
  bounds: { left: number; right: number; bottom: number; top: number; near: number; far: number },
  out: import("vgpu/scene").Mat4,
): import("vgpu/scene").Mat4;
```

## Parameters

| Param         | Type     | Required | Default | Notes                                                                                                               |
| ------------- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------- |
| bounds.left   | `number` | ✔        | —       | Finite, `< right`. View-space x mapped to clip x `−1`.                                                              |
| bounds.right  | `number` | ✔        | —       | Finite, `> left`. Mapped to clip x `+1`.                                                                            |
| bounds.bottom | `number` | ✔        | —       | Finite, `< top`. Mapped to clip y `−1`.                                                                             |
| bounds.top    | `number` | ✔        | —       | Finite, `> bottom`. Mapped to clip y `+1`.                                                                          |
| bounds.near   | `number` | ✔        | —       | Finite, `>= 0` and `< far`. Distance in front of the camera (view `z = −near`) mapped to depth `0`. `0` is allowed. |
| bounds.far    | `number` | ✔        | —       | Finite, `> near`. View `z = −far` mapped to depth `1`.                                                              |
| out           | `Mat4`   | ✔        | —       | `Float32Array` with exactly 16 elements. Overwritten on success, untouched on any error.                            |

**Returns:** `Mat4` — the same `out`, column-major: `[2/(r−l), 0, 0, 0,  0, 2/(t−b), 0, 0,  0, 0, 1/(n−f), 0,  (r+l)/(l−r), (t+b)/(b−t), n/(n−f), 1]`.

**Throws:** bounds are checked first, then `out`.

* `VGPU-CAMERA-VALUE` when a bound is not finite, `left >= right`, `bottom >= top`, `near < 0`, `near >= far`, or an element is outside finite float32 range (bounds extremely close together) — pass ordered finite bounds with `0 <= near < far`.
* `VGPU-CAMERA-SIZE` when `out` does not have exactly 16 elements — allocate `new Float32Array(16)`.

## Examples

An orthographic view of an orbit rig, sized by a half-height in world units:

```ts
import { orbitRig, orthographic, rigPose, viewMatrices, type CameraMatrices, type Pose } from "vgpu/scene";

const aspect = 16 / 9;
const halfHeight = 5; // world units visible above the pivot; scale it to zoom
const rig = orbitRig({ pitch: 0.6, distance: 20 });
const projection = orthographic({
  left: -halfHeight * aspect, right: halfHeight * aspect,
  bottom: -halfHeight, top: halfHeight,
  near: 0, far: 40, // bracket rig.distance so the pivot is inside the depth range
}, new Float32Array(16));

const pose: Pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const matrices: CameraMatrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
viewMatrices(rigPose(rig, pose), projection, matrices);

const unitsPerPixel = (halfHeight * 2) / 1080; // orthographic world units per pixel: (top − bottom) / height
```

## Notes

* Bounds are in view space, relative to the camera, not world space. Move the camera with a `Pose`.
* Mirrored bounds (`left > right`) throw. To mirror, write your own projection and pass it to `viewMatrices`.
* `zoom`, `dolly` and `worldPerPixel` are perspective tools: an orthographic image changes size only when you change the bounds.
* **See also:** `perspective`, `viewMatrices`, `Pose`.

***

# viewMatrices

Writes a camera's view matrix and the combined view-projection matrix into `out`. Use it after `rigPose` (or your own `Pose`) and `perspective`/`orthographic`, then pack `viewProjection` into your draws.

## Import

```ts
import { viewMatrices } from "vgpu/scene";
```

## Signature

```ts
declare function viewMatrices(
  pose: import("vgpu/scene").Pose,
  projection: ArrayLike<number>,
  out: import("vgpu/scene").CameraMatrices,
): void;
```

## Parameters

| Param              | Type                | Required | Default | Notes                                                                                                                                                                               |
| ------------------ | ------------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| pose               | `Pose`              | ✔        | —       | Read-only. `position`: exactly 3 finite float32-representable values. `quaternion`: exactly 4 finite values with nonzero length; a normalized copy is used, `pose` is not modified. |
| projection         | `ArrayLike<number>` | ✔        | —       | Exactly 16 finite column-major values. Any projection works: from `perspective`, `orthographic`, or your own (reversed-Z, infinite far, jittered, off-axis).                        |
| out.view           | `Mat4`              | ✔        | —       | Exactly 16 elements. Receives the inverse of the pose's rigid transform.                                                                                                            |
| out.viewProjection | `Mat4`              | ✔        | —       | Exactly 16 elements, not overlapping `out.view`. Receives `projection × view`.                                                                                                      |

**Returns:** `void` — the results are in `out.view` and `out.viewProjection`. Both are written on success; neither changes on any error.

**Throws:** every check runs before `out` changes.

* `VGPU-CAMERA-SIZE` when `pose.position` does not have exactly 3 values, `pose.quaternion` exactly 4, or `projection`, `out.view` or `out.viewProjection` exactly 16 — allocate the stated lengths.
* `VGPU-CAMERA-VALUE` when a pose or projection component is `NaN` or `Infinity`, a position component is outside finite float32 range, the quaternion has zero length, or a result element is outside finite float32 range — pass a finite pose with a nonzero quaternion and a finite projection.
* `VGPU-CAMERA-ALIAS` when `out.view` and `out.viewProjection` overlap — allocate two disjoint 16-element arrays.

## Examples

```ts
import { degToRad, perspective, viewMatrices, type CameraMatrices, type Pose } from "vgpu/scene";

const heading = degToRad(30);
const pose: Pose = {
  position: new Float32Array([0, 1.7, 5]),
  quaternion: new Float32Array([0, 2 * Math.sin(heading / 2), 0, 2 * Math.cos(heading / 2)]), // not unit: normalized for the calculation
};
const projection = perspective({ fov: 70, near: 0.05, far: 500 }, 16 / 9, new Float32Array(16));
const matrices: CameraMatrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
viewMatrices(pose, projection, matrices); // pose.quaternion keeps its length-2 values
```

Pass your own projection — here reversed-Z with an infinite far plane:

```ts
import { viewMatrices, type CameraMatrices, type Pose } from "vgpu/scene";

const near = 0.1;
const aspect = 16 / 9;
const focal = 1 / Math.tan((60 * Math.PI) / 360); // 60° vertical FOV
const reversedInfinite = new Float32Array([
  focal / aspect, 0, 0, 0,
  0, focal, 0, 0,
  0, 0, 0, -1,
  0, 0, near, 0, // depth 1 at near, approaching 0 at infinity
]);
const pose: Pose = { position: new Float32Array([0, 2, 10]), quaternion: new Float32Array([0, 0, 0, 1]) };
const matrices: CameraMatrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
viewMatrices(pose, reversedInfinite, matrices); // draw with depth: { compare: "greater" } and clearDepth: 0
```

## Notes

* `viewMatrices` fills your arrays, but draws do not watch them. `draw.set({ camera: { viewProjection: matrices.viewProjection } })` copies the values when you call it; call `set()` again after every `viewMatrices` you want rendered. Binding the array once does not keep it fresh.
* Inputs are read before anything is written, so `out.view` or `out.viewProjection` may share storage with `pose` or `projection` — for example, you may reuse one scratch buffer as both a projection input and an output. Only the two output fields must be disjoint, since they hold different results.
* Conventions: right-handed, +Y up, camera looks down -Z, column-major, clip depth `0..1` as produced by `perspective` and `orthographic`.
* **See also:** `CameraMatrices`, `rigPose`, `perspective`, `orthographic`.

***

# CameraMatrices

Output storage for `viewMatrices`: the view matrix and the combined view-projection matrix.

## Import

```ts
import type { CameraMatrices } from "vgpu/scene";
```

## Signature

```ts
interface CameraMatrices {
  view: import("vgpu/scene").Mat4;
  viewProjection: import("vgpu/scene").Mat4;
}
```

## Parameters

| Field          | Type   | Required | Default | Notes                                                                                                                      |
| -------------- | ------ | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------- |
| view           | `Mat4` | ✔        | —       | `Float32Array` of exactly 16 elements: world → view space. Use it for view-space effects such as matcaps or fog.           |
| viewProjection | `Mat4` | ✔        | —       | `Float32Array` of exactly 16 elements, disjoint from `view`: world → clip space. Pack it into the shader's camera uniform. |

## Examples

```ts
import type { CameraMatrices } from "vgpu/scene";

const matrices: CameraMatrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };

const shared = new Float32Array(32); // one allocation, two disjoint views
const packed: CameraMatrices = { view: shared.subarray(0, 16), viewProjection: shared.subarray(16, 32) };
```

## Notes

* Allocate once and reuse every update. Overlapping `view` and `viewProjection` throw `VGPU-CAMERA-ALIAS`.
* **See also:** `viewMatrices`.

***

# worldPerPixel

Returns how many world units one pixel of screen height spans at a given distance through a perspective lens. Use it to turn pointer deltas into `pan` offsets so dragged content stays under the pointer.

## Import

```ts
import { worldPerPixel } from "vgpu/scene";
```

## Signature

```ts
declare function worldPerPixel(distance: number, lens: import("vgpu/scene").Lens, heightPixels: number): number;
```

## Parameters

| Param        | Type     | Required | Default | Notes                                                                                                                                        |
| ------------ | -------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| distance     | `number` | ✔        | —       | World-space distance from the camera to the plane you are dragging, finite and positive. For an orbit camera, the rendered rig's `distance`. |
| lens         | `Lens`   | ✔        | —       | Validated in full; only `fov` affects the result.                                                                                            |
| heightPixels | `number` | ✔        | —       | Viewport height, finite and positive, in the same units as your pointer deltas: `canvas.clientHeight` for CSS-pixel `movementX`/`movementY`. |

**Returns:** `number` — `2 × distance × tan(fov / 2) / heightPixels`, finite and positive.

**Throws:**

* `VGPU-CAMERA-VALUE` when `distance` or `heightPixels` is not finite and positive, the lens is invalid, or the result is not finite and positive — pass positive finite values; guard a hidden canvas with `Math.max(1, canvas.clientHeight)`.

## Examples

```ts
import { worldPerPixel } from "vgpu/scene";

const unitsPerPixel = worldPerPixel(10, { fov: 60, near: 0.1, far: 100 }, 1000);
console.log(unitsPerPixel); // ≈ 0.01155: 2 × 10 × tan(30°) / 1000
```

## Notes

* Mixing units breaks the 1:1 drag: device-pixel deltas need a device-pixel height, CSS-pixel deltas a CSS-pixel height. The canvas's backing size (`canvasSurface.size`) is in device pixels.
* Recompute it whenever the distance, the lens (`zoom`) or the canvas height changes; it is cheap and pure.
* For an orthographic camera use `(top − bottom) / heightPixels` instead.
* **See also:** `pan`, `Lens`, `zoom`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: degToRad
description: Converts degrees to radians for custom scene math. Use it when a shader uniform, animation helper, or math API expects radians while your input is in degrees.
---

# degToRad



## Import

```ts
import { degToRad } from "vgpu/scene";
```

## Signature

```ts
declare function degToRad(deg: number): number;
```

## Parameters

| Param | Type     | Required | Default | Notes                                                                                                                    |
| ----- | -------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------ |
| deg   | `number` | ✔        | —       | Angle in degrees. Positive, negative, fractional, `Infinity`, and `NaN` are passed through JavaScript number arithmetic. |

**Returns:** `number` — `deg * Math.PI / 180`, suitable for `Math.sin`, `Math.cos`, matrix helpers, or shader uniforms that expect radians.
**Throws:** None.

## Examples

```ts
import { degToRad } from "vgpu/scene";

const quarterTurn = degToRad(90);
const rotation = { sinAngle: Math.sin(quarterTurn), cosAngle: Math.cos(quarterTurn) };
void rotation;
```

```ts
import { degToRad } from "vgpu/scene";

const clockwise = degToRad(-45);
console.log(clockwise < 0);
```

## Notes

* Public camera helpers in `vgpu/scene` accept degrees for field-of-view values; do not convert `Lens.fov` yourself.
* Use `degToRad` for custom transforms and CPU-side uniform values that explicitly need radians.
* **See also:** `perspective`, `composeMatrix`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: box
description: Creates a pure cube descriptor for `geometry(gpu)`. Descriptors are device-agnostic, so you can serialize or clone them freely and upload later.
---

# box



## Import

```ts
import { box } from "vgpu/scene";
```

## Signature

```ts
declare function box(options?: import("vgpu/scene").BoxOptions): import("vgpu/scene").SceneGeometryOfKind<"box">;
```

## Parameters

| Param        | Type         | Required | Default | Notes                                                               |
| ------------ | ------------ | -------- | ------- | ------------------------------------------------------------------- |
| options      | `BoxOptions` | ✖        | `{}`    | Configuration bag for the cube descriptor.                          |
| options.size | `number`     | ✖        | `1`     | Edge length used by the geometry factory. Any positive value works. |

**Returns:** `SceneGeometryOfKind<"box">` — frozen descriptor with `kind: "box"` and the props you provided; omitted fields stay omitted until upload-time defaults are applied.

**Throws:** None. Negative sizes do not throw but invert normals when uploaded.

## Examples

```ts
import { box } from "vgpu/scene";

const tallCube = box({ size: 3 });
console.log(tallCube.kind); // "box"
```

## Notes

* Descriptors contain zero GPU state; call `geometry(gpu, descriptor)` per device.
* **See also:** `BoxOptions`, `SceneGeometryOfKind`.

***

# BoxOptions

Shape configuration shared by `box()` descriptors.

## Import

```ts
import type { BoxOptions } from "vgpu/scene";
```

## Signature

```ts
interface BoxOptions {
  readonly size?: number;
}
```

## Parameters

| Field | Type     | Required | Default | Notes                                |
| ----- | -------- | -------- | ------- | ------------------------------------ |
| size  | `number` | ✖        | `1`     | Edge length measured in scene units. |

**Returns:** Not applicable (type definition).

**Throws:** None.

## Examples

```ts
import type { BoxOptions } from "vgpu/scene";

const solid: BoxOptions = { size: 2 };
```

## Notes

* Undefined fields are filled by the geometry factory when the descriptor is uploaded.
* **See also:** `box`, `SceneGeometry`.

***

# sphere

Generates a UV sphere descriptor with configurable radius and tessellation.

## Import

```ts
import { sphere } from "vgpu/scene";
```

## Signature

```ts
declare function sphere(options?: import("vgpu/scene").SphereOptions): import("vgpu/scene").SceneGeometryOfKind<"sphere">;
```

## Parameters

| Param                  | Type            | Required | Default | Notes                                         |
| ---------------------- | --------------- | -------- | ------- | --------------------------------------------- |
| options                | `SphereOptions` | ✖        | `{}`    | Configure radius or segments before upload.   |
| options.radius         | `number`        | ✖        | `0.5`   | Physical radius. Must be `> 0` once uploaded. |
| options.widthSegments  | `number`        | ✖        | `32`    | Meridians. Integer `>= 3`.                    |
| options.heightSegments | `number`        | ✖        | `16`    | Latitudes. Integer `>= 2`.                    |

**Returns:** `SceneGeometryOfKind<"sphere">`.

**Throws:** None while creating the descriptor. `geometry(gpu, sphere(...))` throws `VGPU-CORE-INVALID-USAGE` if radius `<= 0`, segment counts drop below limits, or `(widthSegments + 1) * (heightSegments + 1)` exceeds the uint16 vertex cap (65 535).

## Examples

```ts
import { sphere } from "vgpu/scene";

const globe = sphere({ radius: 1.2, widthSegments: 48, heightSegments: 32 });
```

## Notes

* Higher segment counts increase vertex memory exponentially; use `icosphere()` for evenly distributed triangles.
* **See also:** `SphereOptions`, `Geometry`.

***

# SphereOptions

Configuration interface for `sphere()`.

## Import

```ts
import type { SphereOptions } from "vgpu/scene";
```

## Signature

```ts
interface SphereOptions {
  readonly radius?: number;
  readonly widthSegments?: number;
  readonly heightSegments?: number;
}
```

## Parameters

| Field          | Type     | Required | Default | Notes           |
| -------------- | -------- | -------- | ------- | --------------- |
| radius         | `number` | ✖        | `0.5`   | Must be `> 0`.  |
| widthSegments  | `number` | ✖        | `32`    | Integer `>= 3`. |
| heightSegments | `number` | ✖        | `16`    | Integer `>= 2`. |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { SphereOptions } from "vgpu/scene";

const detail: SphereOptions = { widthSegments: 96, heightSegments: 64 };
```

## Notes

* Leave properties undefined to rely on the geometry factory defaults shown above.
* **See also:** `sphere`, `IcosphereOptions`.

***

# plane

XZ-aligned quad descriptor centered at the origin with +Y normals. Use it for ground planes, decals, or full-quad geometry.

## Import

```ts
import { plane } from "vgpu/scene";
```

## Signature

```ts
declare function plane(options?: import("vgpu/scene").PlaneOptions): import("vgpu/scene").SceneGeometryOfKind<"plane">;
```

## Parameters

| Param                  | Type                 | Required | Default  | Notes                                        |
| ---------------------- | -------------------- | -------- | -------- | -------------------------------------------- |
| options                | `PlaneOptions`       | ✖        | `{}`     | Width/height and tessellation controls.      |
| options.width          | `number`             | ✖        | `1`      | Total X extent; must be `> 0`.               |
| options.height         | `number`             | ✖        | `1`      | Total Z extent; must be `> 0`.               |
| options.widthSegments  | `number`             | ✖        | `1`      | Integer `>= 1`.                              |
| options.heightSegments | `number`             | ✖        | `1`      | Integer `>= 1`.                              |
| options.shading        | `"flat" \| "smooth"` | ✖        | `"flat"` | Present for parity; normals remain +Y today. |

**Returns:** `SceneGeometryOfKind<"plane">`.

**Throws:** None while creating the descriptor. `geometry(gpu, plane(...))` throws `VGPU-CORE-INVALID-USAGE` if width/height `<= 0`, segment counts `< 1`, or tessellation exceeds 65 535 vertices.

## Examples

```ts
import { plane } from "vgpu/scene";

const tiled = plane({ width: 10, height: 10, widthSegments: 4, heightSegments: 4 });
```

## Notes

* Use `plane()` when you need explicit vertex data instead of the implicit full-screen quad helper.
* **See also:** `PlaneOptions`, `fullscreenQuad`.

***

# PlaneOptions

Options bag used by `plane()`.

## Import

```ts
import type { PlaneOptions } from "vgpu/scene";
```

## Signature

```ts
interface PlaneOptions {
  readonly width?: number;
  readonly height?: number;
  readonly widthSegments?: number;
  readonly heightSegments?: number;
  readonly shading?: "flat" | "smooth";
}
```

## Parameters

| Field          | Type                 | Required | Default  | Notes                                   |
| -------------- | -------------------- | -------- | -------- | --------------------------------------- |
| width          | `number`             | ✖        | `1`      | Must be `> 0`.                          |
| height         | `number`             | ✖        | `1`      | Must be `> 0`.                          |
| widthSegments  | `number`             | ✖        | `1`      | Integer `>= 1`.                         |
| heightSegments | `number`             | ✖        | `1`      | Integer `>= 1`.                         |
| shading        | `"flat" \| "smooth"` | ✖        | `"flat"` | Smooth is reserved for future upgrades. |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { PlaneOptions } from "vgpu/scene";

const quad: PlaneOptions = { width: 4, height: 2 };
```

## Notes

* Leave fields undefined to inherit the defaults enforced at upload time.
* **See also:** `plane`, `SceneGeometry`.

***

# torus

Donut descriptor with independent major/minor radii and optional arc slices.

## Import

```ts
import { torus } from "vgpu/scene";
```

## Signature

```ts
declare function torus(options?: import("vgpu/scene").TorusOptions): import("vgpu/scene").SceneGeometryOfKind<"torus">;
```

## Parameters

| Param                   | Type                 | Required | Default       | Notes                                                          |
| ----------------------- | -------------------- | -------- | ------------- | -------------------------------------------------------------- |
| options                 | `TorusOptions`       | ✖        | `{}`          | Controls radii, arc, and tessellation.                         |
| options.radius          | `number`             | ✖        | `0.5`         | Distance from origin to tube center; must be `> options.tube`. |
| options.tube            | `number`             | ✖        | `0.2`         | Minor radius; must be `> 0`.                                   |
| options.radialSegments  | `number`             | ✖        | `16`          | Around the tube. Integer `>= 3`.                               |
| options.tubularSegments | `number`             | ✖        | `32`          | Around the ring. Integer `>= 3`.                               |
| options.arc             | `number`             | ✖        | `Math.PI * 2` | Radians to sweep; must be `> 0`.                               |
| options.shading         | `"flat" \| "smooth"` | ✖        | `"smooth"`    | Flat duplicates vertices for per-triangle normals.             |

**Returns:** `SceneGeometryOfKind<"torus">`.

**Throws:** None while creating the descriptor. `geometry(gpu, torus(...))` throws `VGPU-CORE-INVALID-USAGE` if radii are invalid, segment counts fall below limits, `arc <= 0`, or vertex counts exceed 65 535.

## Examples

```ts
import { torus } from "vgpu/scene";

const gauge = torus({ radius: 1, tube: 0.15, arc: Math.PI * 1.25 });
```

## Notes

* Use partial arcs to build gauges or highlights without extra geometry.
* **See also:** `RingOptions`, `TorusOptions`.

***

# TorusOptions

Configuration interface for `torus()`.

## Import

```ts
import type { TorusOptions } from "vgpu/scene";
```

## Signature

```ts
interface TorusOptions {
  readonly radius?: number;
  readonly tube?: number;
  readonly radialSegments?: number;
  readonly tubularSegments?: number;
  readonly arc?: number;
  readonly shading?: "flat" | "smooth";
}
```

## Parameters

| Field           | Type                 | Required | Default       | Notes                     |
| --------------- | -------------------- | -------- | ------------- | ------------------------- |
| radius          | `number`             | ✖        | `0.5`         | Must be `> tube`.         |
| tube            | `number`             | ✖        | `0.2`         | Minor radius `> 0`.       |
| radialSegments  | `number`             | ✖        | `16`          | Integer `>= 3`.           |
| tubularSegments | `number`             | ✖        | `32`          | Integer `>= 3`.           |
| arc             | `number`             | ✖        | `Math.PI * 2` | Radians `> 0`.            |
| shading         | `"flat" \| "smooth"` | ✖        | `"smooth"`    | Flat duplicates vertices. |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { TorusOptions } from "vgpu/scene";

const tight: TorusOptions = { radius: 0.75, tube: 0.3 };
```

## Notes

* Keep `tube` significantly smaller than `radius` to avoid self-intersection.
* **See also:** `torus`, `ring`.

***

# fullscreenQuad

Descriptor for a clip-space fullscreen quad (two triangles, six vertices). Use it for fragment-only passes recorded via `draw(gpu)`.

## Import

```ts
import { fullscreenQuad } from "vgpu/scene";
```

## Signature

```ts
declare function fullscreenQuad(options?: import("vgpu/scene").FullscreenQuadOptions): import("vgpu/scene").SceneGeometryOfKind<"fullscreenQuad">;
```

## Parameters

| Param   | Type                    | Required | Default | Notes                                                   |
| ------- | ----------------------- | -------- | ------- | ------------------------------------------------------- |
| options | `FullscreenQuadOptions` | ✖        | `{}`    | Reserved for future overrides; currently has no fields. |

**Returns:** `SceneGeometryOfKind<"fullscreenQuad">`.

**Throws:** None.

## Examples

```ts
import { fullscreenQuad } from "vgpu/scene";

const descriptor = fullscreenQuad();
```

## Notes

* Generated geometry exposes only position attributes (xy4). Add UVs in WGSL using built-in coordinates.
* **See also:** `plane`, `Geometry`.

***

# FullscreenQuadOptions

Placeholder interface to keep API surface future-proof.

## Import

```ts
import type { FullscreenQuadOptions } from "vgpu/scene";
```

## Signature

```ts
interface FullscreenQuadOptions {}
```

## Parameters

No fields yet.

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { FullscreenQuadOptions } from "vgpu/scene";

const passthrough: FullscreenQuadOptions = {};
```

## Notes

* Leave the argument undefined; future versions may add configurable fields.
* **See also:** `fullscreenQuad`.

***

# capsule

Rounded capsule descriptor made of a cylinder body and two hemispherical caps.

## Import

```ts
import { capsule } from "vgpu/scene";
```

## Signature

```ts
declare function capsule(options?: import("vgpu/scene").CapsuleOptions): import("vgpu/scene").SceneGeometryOfKind<"capsule">;
```

## Parameters

| Param                  | Type                 | Required | Default    | Notes                                                                |
| ---------------------- | -------------------- | -------- | ---------- | -------------------------------------------------------------------- |
| options                | `CapsuleOptions`     | ✖        | `{}`       | Radius/height/tessellation overrides.                                |
| options.radius         | `number`             | ✖        | `0.5`      | Cap radius; must be `> 0`.                                           |
| options.height         | `number`             | ✖        | `1`        | Cylinder length between caps; total height is `height + 2 * radius`. |
| options.radialSegments | `number`             | ✖        | `32`       | Integer `>= 3`.                                                      |
| options.heightSegments | `number`             | ✖        | `8`        | Integer `>= 2`.                                                      |
| options.shading        | `"flat" \| "smooth"` | ✖        | `"smooth"` | Flat duplicates vertices per triangle.                               |

**Returns:** `SceneGeometryOfKind<"capsule">`.

**Throws:** None while creating the descriptor. `geometry(gpu, capsule(...))` throws `VGPU-CORE-INVALID-USAGE` if radius `<= 0`, height `< 0`, segment counts fall below limits, or vertex counts exceed 65 535.

## Examples

```ts
import { capsule } from "vgpu/scene";

const pillar = capsule({ radius: 0.3, height: 2, shading: "flat" });
```

## Notes

* Increase `heightSegments` to reduce stretching along the cylinder body.
* **See also:** `CapsuleOptions`, `cylinder`.

***

# CapsuleOptions

Configuration interface for `capsule()`.

## Import

```ts
import type { CapsuleOptions } from "vgpu/scene";
```

## Signature

```ts
interface CapsuleOptions {
  readonly radius?: number;
  readonly height?: number;
  readonly radialSegments?: number;
  readonly heightSegments?: number;
  readonly shading?: "flat" | "smooth";
}
```

## Parameters

| Field          | Type                 | Required | Default    | Notes                            |
| -------------- | -------------------- | -------- | ---------- | -------------------------------- |
| radius         | `number`             | ✖        | `0.5`      | Must be `> 0`.                   |
| height         | `number`             | ✖        | `1`        | Can be zero for perfect spheres. |
| radialSegments | `number`             | ✖        | `32`       | Integer `>= 3`.                  |
| heightSegments | `number`             | ✖        | `8`        | Integer `>= 2`.                  |
| shading        | `"flat" \| "smooth"` | ✖        | `"smooth"` | Flat duplicates vertices.        |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { CapsuleOptions } from "vgpu/scene";

const short: CapsuleOptions = { height: 0.5 };
```

## Notes

* Negative heights are rejected when uploading through `geometry(gpu)`.
* **See also:** `capsule`, `SceneGeometry`.

***

# cone

Circular cone descriptor with optional base cap and angular slice control.

## Import

```ts
import { cone } from "vgpu/scene";
```

## Signature

```ts
declare function cone(options?: import("vgpu/scene").ConeOptions): import("vgpu/scene").SceneGeometryOfKind<"cone">;
```

## Parameters

| Param                  | Type                 | Required | Default       | Notes                                  |
| ---------------------- | -------------------- | -------- | ------------- | -------------------------------------- |
| options                | `ConeOptions`        | ✖        | `{}`          | Controls size, caps, and tessellation. |
| options.radius         | `number`             | ✖        | `0.5`         | Base radius; must be `> 0`.            |
| options.height         | `number`             | ✖        | `1`           | Must be `> 0`.                         |
| options.radialSegments | `number`             | ✖        | `32`          | Integer `>= 3`.                        |
| options.heightSegments | `number`             | ✖        | `1`           | Integer `>= 1`.                        |
| options.openEnded      | `boolean`            | ✖        | `false`       | Omits the base cap.                    |
| options.thetaStart     | `number`             | ✖        | `0`           | Start angle in radians.                |
| options.thetaLength    | `number`             | ✖        | `Math.PI * 2` | Sweep `> 0`.                           |
| options.shading        | `"flat" \| "smooth"` | ✖        | `"smooth"`    | Flat duplicates vertices per face.     |

**Returns:** `SceneGeometryOfKind<"cone">`.

**Throws:** None while creating the descriptor. `geometry(gpu, cone(...))` throws `VGPU-CORE-INVALID-USAGE` for invalid radius/height, low segment counts, zero sweep, or vertex counts above 65 535.

## Examples

```ts
import { cone } from "vgpu/scene";

const spotlight = cone({ radius: 0.4, height: 1.2, openEnded: true, thetaLength: Math.PI });
```

## Notes

* Use `openEnded: true` for beams or funnels where the cap would never be visible.
* **See also:** `ConeOptions`, `cylinder`.

***

# ConeOptions

Configuration interface for `cone()`.

## Import

```ts
import type { ConeOptions } from "vgpu/scene";
```

## Signature

```ts
interface ConeOptions {
  readonly radius?: number;
  readonly height?: number;
  readonly radialSegments?: number;
  readonly heightSegments?: number;
  readonly openEnded?: boolean;
  readonly thetaStart?: number;
  readonly thetaLength?: number;
  readonly shading?: "flat" | "smooth";
}
```

## Parameters

| Field          | Type                 | Required | Default       | Notes                     |
| -------------- | -------------------- | -------- | ------------- | ------------------------- |
| radius         | `number`             | ✖        | `0.5`         | Must be `> 0`.            |
| height         | `number`             | ✖        | `1`           | Must be `> 0`.            |
| radialSegments | `number`             | ✖        | `32`          | Integer `>= 3`.           |
| heightSegments | `number`             | ✖        | `1`           | Integer `>= 1`.           |
| openEnded      | `boolean`            | ✖        | `false`       | Omits the base cap.       |
| thetaStart     | `number`             | ✖        | `0`           | Start angle in radians.   |
| thetaLength    | `number`             | ✖        | `Math.PI * 2` | Sweep `> 0`.              |
| shading        | `"flat" \| "smooth"` | ✖        | `"smooth"`    | Flat duplicates vertices. |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { ConeOptions } from "vgpu/scene";

const halfCone: ConeOptions = { thetaLength: Math.PI };
```

## Notes

* Upload-time validation enforces every invariant listed above.
* **See also:** `cone`, `SceneGeometry`.

***

# cylinder

Pure descriptor for cylinders or frustums with independent top/bottom radii and optional caps.

## Import

```ts
import { cylinder } from "vgpu/scene";
```

## Signature

```ts
declare function cylinder(options?: import("vgpu/scene").CylinderOptions): import("vgpu/scene").SceneGeometryOfKind<"cylinder">;
```

## Parameters

| Param                  | Type                 | Required | Default          | Notes                                                           |
| ---------------------- | -------------------- | -------- | ---------------- | --------------------------------------------------------------- |
| options                | `CylinderOptions`    | ✖        | `{}`             | Provide either `radius` or both `radiusTop` and `radiusBottom`. |
| options.radius         | `number`             | ✖        | `0.5`            | Uniform radius fallback when per-end radii are omitted.         |
| options.radiusTop      | `number`             | ✖        | `options.radius` | Provide with `radiusBottom` for frustums. Must be `>= 0`.       |
| options.radiusBottom   | `number`             | ✖        | `options.radius` | Same as `radiusTop`.                                            |
| options.height         | `number`             | ✖        | `1`              | Must be `> 0`.                                                  |
| options.radialSegments | `number`             | ✖        | `32`             | Integer `>= 3`.                                                 |
| options.heightSegments | `number`             | ✖        | `1`              | Integer `>= 1`.                                                 |
| options.openEnded      | `boolean`            | ✖        | `false`          | Omits caps (zero-radius caps are always skipped).               |
| options.thetaStart     | `number`             | ✖        | `0`              | Start angle.                                                    |
| options.thetaLength    | `number`             | ✖        | `Math.PI * 2`    | Sweep `> 0`.                                                    |
| options.shading        | `"flat" \| "smooth"` | ✖        | `"smooth"`       | Flat duplicates vertices.                                       |

**Returns:** `SceneGeometryOfKind<"cylinder">`.

**Throws:** None while creating the descriptor. `geometry(gpu, cylinder(...))` throws `VGPU-CORE-INVALID-USAGE` if you provide both uniform and explicit radii, resolve radii below zero, keep both radii at zero, use low segment counts, or exceed the vertex limit.

## Examples

```ts
import { cylinder } from "vgpu/scene";

const tapered = cylinder({ radiusTop: 0.2, radiusBottom: 0.4, height: 1.5, radialSegments: 48 });
```

## Notes

* Zero-radius ends are automatically omitted to avoid degenerate caps.
* **See also:** `CylinderOptions`, `capsule`.

***

# CylinderOptions

Configuration interface for `cylinder()`.

## Import

```ts
import type { CylinderOptions } from "vgpu/scene";
```

## Signature

```ts
interface CylinderOptions {
  readonly radius?: number;
  readonly radiusTop?: number;
  readonly radiusBottom?: number;
  readonly height?: number;
  readonly radialSegments?: number;
  readonly heightSegments?: number;
  readonly openEnded?: boolean;
  readonly thetaStart?: number;
  readonly thetaLength?: number;
  readonly shading?: "flat" | "smooth";
}
```

## Parameters

| Field          | Type                 | Required | Default                         | Notes                                                                                      |
| -------------- | -------------------- | -------- | ------------------------------- | ------------------------------------------------------------------------------------------ |
| radius         | `number`             | ✖        | `0.5`                           | Uniform fallback radius.                                                                   |
| radiusTop      | `number`             | ✖        | omitted; resolved from `radius` | Provide with `radiusBottom` for frustums. If `radius` is set, omitting this uses `radius`. |
| radiusBottom   | `number`             | ✖        | omitted; resolved from `radius` | Provide with `radiusTop`. If `radius` is set, omitting this uses `radius`.                 |
| height         | `number`             | ✖        | `1`                             | Must be `> 0`.                                                                             |
| radialSegments | `number`             | ✖        | `32`                            | Integer `>= 3`.                                                                            |
| heightSegments | `number`             | ✖        | `1`                             | Integer `>= 1`.                                                                            |
| openEnded      | `boolean`            | ✖        | `false`                         | Skip caps when `true`.                                                                     |
| thetaStart     | `number`             | ✖        | `0`                             | Start angle.                                                                               |
| thetaLength    | `number`             | ✖        | `Math.PI * 2`                   | Sweep `> 0`.                                                                               |
| shading        | `"flat" \| "smooth"` | ✖        | `"smooth"`                      | Flat duplicates vertices.                                                                  |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { CylinderOptions } from "vgpu/scene";

const frustum: CylinderOptions = { radiusTop: 0.25, radiusBottom: 0.6 };
```

## Notes

* Validation occurs when `geometry(gpu)` uploads the descriptor.
* **See also:** `cylinder`, `SceneGeometry`.

***

# disk

Flat disk descriptor oriented on the XZ plane with upward normals.

## Import

```ts
import { disk } from "vgpu/scene";
```

## Signature

```ts
declare function disk(options?: import("vgpu/scene").DiskOptions): import("vgpu/scene").SceneGeometryOfKind<"disk">;
```

## Parameters

| Param               | Type          | Required | Default       | Notes                             |
| ------------------- | ------------- | -------- | ------------- | --------------------------------- |
| options             | `DiskOptions` | ✖        | `{}`          | Radius and polar slice overrides. |
| options.radius      | `number`      | ✖        | `0.5`         | Must be `> 0`.                    |
| options.segments    | `number`      | ✖        | `32`          | Integer `>= 3`.                   |
| options.thetaStart  | `number`      | ✖        | `0`           | Slice start angle.                |
| options.thetaLength | `number`      | ✖        | `Math.PI * 2` | Sweep `> 0`.                      |

**Returns:** `SceneGeometryOfKind<"disk">`.

**Throws:** None while creating the descriptor. `geometry(gpu, disk(...))` throws `VGPU-CORE-INVALID-USAGE` if radius `<= 0`, segment counts `< 3`, sweep `<= 0`, or vertex counts exceed the uint16 limit.

## Examples

```ts
import { disk } from "vgpu/scene";

const portal = disk({ radius: 1, segments: 64, thetaLength: Math.PI * 1.5 });
```

## Notes

* Disk UVs map linearly from the center; combine with `ring()` for hollow shapes.
* **See also:** `DiskOptions`, `ring`.

***

# DiskOptions

Configuration interface for `disk()`.

## Import

```ts
import type { DiskOptions } from "vgpu/scene";
```

## Signature

```ts
interface DiskOptions {
  readonly radius?: number;
  readonly segments?: number;
  readonly thetaStart?: number;
  readonly thetaLength?: number;
}
```

## Parameters

| Field       | Type     | Required | Default       | Notes              |
| ----------- | -------- | -------- | ------------- | ------------------ |
| radius      | `number` | ✖        | `0.5`         | Must be `> 0`.     |
| segments    | `number` | ✖        | `32`          | Integer `>= 3`.    |
| thetaStart  | `number` | ✖        | `0`           | Slice start angle. |
| thetaLength | `number` | ✖        | `Math.PI * 2` | Sweep `> 0`.       |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { DiskOptions } from "vgpu/scene";

const slice: DiskOptions = { thetaLength: Math.PI };
```

## Notes

* Validation occurs when uploading through `geometry(gpu)`.
* **See also:** `disk`, `ring`.

***

# dodecahedron

Regular dodecahedron descriptor backed by the polyhedron geometry builder.

## Import

```ts
import { dodecahedron } from "vgpu/scene";
```

## Signature

```ts
declare function dodecahedron(options?: import("vgpu/scene").PolyhedronOptions): import("vgpu/scene").SceneGeometryOfKind<"dodecahedron">;
```

## Parameters

| Param          | Type                | Required | Default | Notes                                |
| -------------- | ------------------- | -------- | ------- | ------------------------------------ |
| options        | `PolyhedronOptions` | ✖        | `{}`    | Provide a radius override.           |
| options.radius | `number`            | ✖        | `0.5`   | Circumscribed radius; must be `> 0`. |

**Returns:** `SceneGeometryOfKind<"dodecahedron">`.

**Throws:** None while creating the descriptor. Uploading this descriptor with `geometry(gpu, ...)` throws `VGPU-CORE-INVALID-USAGE` if radius `<= 0`.

## Examples

```ts
import { dodecahedron } from "vgpu/scene";

const rock = dodecahedron({ radius: 0.8 });
```

## Notes

* Polyhedra stay well under the uint16 vertex cap, making them ideal for stylized rocks.
* **See also:** `PolyhedronOptions`, `icosahedron`.

***

# PolyhedronOptions

Shared options for `dodecahedron`, `icosahedron`, `octahedron`, and `tetrahedron`.

## Import

```ts
import type { PolyhedronOptions } from "vgpu/scene";
```

## Signature

```ts
interface PolyhedronOptions {
  readonly radius?: number;
}
```

## Parameters

| Field  | Type     | Required | Default | Notes                                |
| ------ | -------- | -------- | ------- | ------------------------------------ |
| radius | `number` | ✖        | `0.5`   | Circumscribed radius; must be `> 0`. |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { PolyhedronOptions } from "vgpu/scene";

const hudIcon: PolyhedronOptions = { radius: 0.25 };
```

## Notes

* All polyhedron helpers freeze the provided options before returning descriptors.
* **See also:** `dodecahedron`, `tetrahedron`.

***

# icosahedron

Regular 20-faced polyhedron descriptor.

## Import

```ts
import { icosahedron } from "vgpu/scene";
```

## Signature

```ts
declare function icosahedron(options?: import("vgpu/scene").PolyhedronOptions): import("vgpu/scene").SceneGeometryOfKind<"icosahedron">;
```

## Parameters

Same as `dodecahedron`; omit or override `radius`.

**Returns:** `SceneGeometryOfKind<"icosahedron">`.

**Throws:** None while creating the descriptor. Uploading this descriptor with `geometry(gpu, ...)` throws `VGPU-CORE-INVALID-USAGE` if radius `<= 0`.

## Examples

```ts
import { icosahedron } from "vgpu/scene";

const crystal = icosahedron({ radius: 0.6 });
```

## Notes

* Acts as the seed geometry for `icosphere()` subdivisions.
* **See also:** `PolyhedronOptions`, `icosphere`.

***

# icosphere

Geodesic sphere descriptor obtained by subdividing an icosahedron.

## Import

```ts
import { icosphere } from "vgpu/scene";
```

## Signature

```ts
declare function icosphere(options?: import("vgpu/scene").IcosphereOptions): import("vgpu/scene").SceneGeometryOfKind<"icosphere">;
```

## Parameters

| Param                | Type                 | Required | Default    | Notes                                                     |
| -------------------- | -------------------- | -------- | ---------- | --------------------------------------------------------- |
| options              | `IcosphereOptions`   | ✖        | `{}`       | Radius and subdivision overrides.                         |
| options.radius       | `number`             | ✖        | `0.5`      | Must be `> 0`.                                            |
| options.subdivisions | `number`             | ✖        | `2`        | Integer in `[0, 6]`; each step quadruples triangle count. |
| options.shading      | `"flat" \| "smooth"` | ✖        | `"smooth"` | Flat duplicates vertices for per-face normals.            |

**Returns:** `SceneGeometryOfKind<"icosphere">`.

**Throws:** None while creating the descriptor. `geometry(gpu, icosphere(...))` throws `VGPU-CORE-INVALID-USAGE` if radius/subdivision constraints are violated or vertex counts exceed 65 535.

## Examples

```ts
import { icosphere } from "vgpu/scene";

const moon = icosphere({ radius: 1, subdivisions: 4, shading: "flat" });
```

## Notes

* Prefer `icosphere()` over `sphere()` when you need evenly distributed triangles.
* **See also:** `IcosphereOptions`, `sphere`.

***

# IcosphereOptions

Configuration interface for `icosphere()`.

## Import

```ts
import type { IcosphereOptions } from "vgpu/scene";
```

## Signature

```ts
interface IcosphereOptions {
  readonly radius?: number;
  readonly subdivisions?: number;
  readonly shading?: "flat" | "smooth";
}
```

## Parameters

| Field        | Type                 | Required | Default    | Notes                     |
| ------------ | -------------------- | -------- | ---------- | ------------------------- |
| radius       | `number`             | ✖        | `0.5`      | Must be `> 0`.            |
| subdivisions | `number`             | ✖        | `2`        | Integer in `[0, 6]`.      |
| shading      | `"flat" \| "smooth"` | ✖        | `"smooth"` | Flat duplicates vertices. |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { IcosphereOptions } from "vgpu/scene";

const lowPoly: IcosphereOptions = { subdivisions: 1 };
```

## Notes

* Higher subdivision counts grow vertex counts exponentially; stay at `<= 4` for most hardware.
* **See also:** `icosphere`, `SphereOptions`.

***

# octahedron

Regular octahedron descriptor.

## Import

```ts
import { octahedron } from "vgpu/scene";
```

## Signature

```ts
declare function octahedron(options?: import("vgpu/scene").PolyhedronOptions): import("vgpu/scene").SceneGeometryOfKind<"octahedron">;
```

## Parameters

Same as `dodecahedron`.

**Returns:** `SceneGeometryOfKind<"octahedron">`.

**Throws:** None while creating the descriptor. Uploading this descriptor with `geometry(gpu, ...)` throws `VGPU-CORE-INVALID-USAGE` if radius `<= 0`.

## Examples

```ts
import { octahedron } from "vgpu/scene";

const diamond = octahedron({ radius: 0.7 });
```

## Notes

* Octahedra are useful for axis gizmos or debug visuals.
* **See also:** `PolyhedronOptions`, `tetrahedron`.

***

# ring

Annulus descriptor with independent inner/outer radii and optional polar slices.

## Import

```ts
import { ring } from "vgpu/scene";
```

## Signature

```ts
declare function ring(options?: import("vgpu/scene").RingOptions): import("vgpu/scene").SceneGeometryOfKind<"ring">;
```

## Parameters

| Param               | Type          | Required | Default       | Notes                      |
| ------------------- | ------------- | -------- | ------------- | -------------------------- |
| options             | `RingOptions` | ✖        | `{}`          | Controls radii and slices. |
| options.innerRadius | `number`      | ✖        | `0.25`        | Must be `> 0`.             |
| options.outerRadius | `number`      | ✖        | `0.5`         | Must be `> innerRadius`.   |
| options.segments    | `number`      | ✖        | `32`          | Integer `>= 3`.            |
| options.thetaStart  | `number`      | ✖        | `0`           | Slice start.               |
| options.thetaLength | `number`      | ✖        | `Math.PI * 2` | Sweep `> 0`.               |

**Returns:** `SceneGeometryOfKind<"ring">`.

**Throws:** None while creating the descriptor. `geometry(gpu, ring(...))` throws `VGPU-CORE-INVALID-USAGE` if the radii relationship is invalid, segment counts `< 3`, or vertex counts exceed 65 535.

## Examples

```ts
import { ring } from "vgpu/scene";

const halo = ring({ innerRadius: 0.9, outerRadius: 1, segments: 48 });
```

## Notes

* Combine `ring()` with emissive materials for portals or HUD highlights.
* **See also:** `RingOptions`, `disk`.

***

# RingOptions

Configuration interface for `ring()`.

## Import

```ts
import type { RingOptions } from "vgpu/scene";
```

## Signature

```ts
interface RingOptions {
  readonly innerRadius?: number;
  readonly outerRadius?: number;
  readonly segments?: number;
  readonly thetaStart?: number;
  readonly thetaLength?: number;
}
```

## Parameters

| Field       | Type     | Required | Default       | Notes                    |
| ----------- | -------- | -------- | ------------- | ------------------------ |
| innerRadius | `number` | ✖        | `0.25`        | Must be `> 0`.           |
| outerRadius | `number` | ✖        | `0.5`         | Must be `> innerRadius`. |
| segments    | `number` | ✖        | `32`          | Integer `>= 3`.          |
| thetaStart  | `number` | ✖        | `0`           | Slice start.             |
| thetaLength | `number` | ✖        | `Math.PI * 2` | Sweep `> 0`.             |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { RingOptions } from "vgpu/scene";

const arc: RingOptions = { thetaLength: Math.PI * 0.75 };
```

## Notes

* Upload-time validation enforces every constraint listed above.
* **See also:** `ring`, `SceneGeometry`.

***

# tetrahedron

Regular tetrahedron descriptor.

## Import

```ts
import { tetrahedron } from "vgpu/scene";
```

## Signature

```ts
declare function tetrahedron(options?: import("vgpu/scene").PolyhedronOptions): import("vgpu/scene").SceneGeometryOfKind<"tetrahedron">;
```

## Parameters

Same as `dodecahedron`.

**Returns:** `SceneGeometryOfKind<"tetrahedron">`.

**Throws:** None while creating the descriptor. Uploading this descriptor with `geometry(gpu, ...)` throws `VGPU-CORE-INVALID-USAGE` if radius `<= 0`.

## Examples

```ts
import { tetrahedron } from "vgpu/scene";

const marker = tetrahedron({ radius: 0.3 });
```

## Notes

* Tetrahedra are handy for directional HUD markers or gizmos.
* **See also:** `PolyhedronOptions`, `GeometryKind`.

***

# geometries

Frozen namespace exposing every primitive helper through properties, useful for UI pickers or serialization.

## Import

```ts
import { geometries } from "vgpu/scene";
```

## Signature

```ts
declare const geometries: {
  readonly box: typeof import("vgpu/scene")["box"];
  readonly capsule: typeof import("vgpu/scene")["capsule"];
  readonly cone: typeof import("vgpu/scene")["cone"];
  readonly cylinder: typeof import("vgpu/scene")["cylinder"];
  readonly disk: typeof import("vgpu/scene")["disk"];
  readonly dodecahedron: typeof import("vgpu/scene")["dodecahedron"];
  readonly fullscreenQuad: typeof import("vgpu/scene")["fullscreenQuad"];
  readonly icosahedron: typeof import("vgpu/scene")["icosahedron"];
  readonly icosphere: typeof import("vgpu/scene")["icosphere"];
  readonly octahedron: typeof import("vgpu/scene")["octahedron"];
  readonly plane: typeof import("vgpu/scene")["plane"];
  readonly ring: typeof import("vgpu/scene")["ring"];
  readonly sphere: typeof import("vgpu/scene")["sphere"];
  readonly tetrahedron: typeof import("vgpu/scene")["tetrahedron"];
  readonly torus: typeof import("vgpu/scene")["torus"];
};
```

## Parameters

| Property            | Type       | Required | Default | Notes                                        |
| ------------------- | ---------- | -------- | ------- | -------------------------------------------- |
| `geometries.<name>` | `Function` | ✔        | —       | Each property mirrors the standalone export. |

**Returns:** Frozen object with the same helpers you can import individually.

**Throws:** None.

## Examples

```ts
import { geometries } from "vgpu/scene";

const primitiveNames = Object.keys(geometries);
```

## Notes

* Great for inspector tooling that needs to enumerate available primitives without hard-coding imports.
* **See also:** `GeometryKind`, `SceneGeometry`.

***

# GeometryKind

String-literal union covering every built-in geometry kind.

## Import

```ts
import type { GeometryKind } from "vgpu/scene";
```

## Signature

```ts
type GeometryKind =
  | "box"
  | "capsule"
  | "cone"
  | "cylinder"
  | "disk"
  | "dodecahedron"
  | "fullscreenQuad"
  | "icosahedron"
  | "icosphere"
  | "octahedron"
  | "plane"
  | "ring"
  | "sphere"
  | "tetrahedron"
  | "torus";
```

## Parameters

| Value           | Type           | Required | Default | Notes                                     |
| --------------- | -------------- | -------- | ------- | ----------------------------------------- |
| listed literals | `GeometryKind` | ✔        | —       | Each literal matches a descriptor `kind`. |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import type { GeometryKind } from "vgpu/scene";

function isPolyhedron(kind: GeometryKind): boolean {
  return ["dodecahedron", "icosahedron", "octahedron", "tetrahedron"].includes(kind);
}
```

## Notes

* Use `GeometryKind` when switching on `geometry.kind` to retain exhaustiveness checking.
* **See also:** `SceneGeometry`, `SceneGeometryOfKind`.

***

# SceneGeometry

Union of every primitive descriptor returned by the geometry helpers.

## Import

```ts
import type { SceneGeometry } from "vgpu/scene";
```

## Signature

```ts
type SceneGeometry = import("vgpu/scene").SceneGeometry;
```

## Parameters

| Field | Type            | Required | Default | Notes                                                                                                                           |
| ----- | --------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------- |
| kind  | `GeometryKind`  | ✔        | —       | Identifies the primitive helper that produced the descriptor.                                                                   |
| props | `Readonly<...>` | ✔        | —       | Captured options exactly as provided and frozen; upload-time geometry factories apply the defaults listed on each option table. |

**Returns:** Not applicable (type definition).

**Throws:** None.

## Examples

```ts
import { box } from "vgpu/scene";
import type { SceneGeometry } from "vgpu/scene";

const primitives: SceneGeometry[] = [box({ size: 2 })];
```

## Notes

* `SceneGeometry` objects are fully serializable, making them ideal for editor save files.
* **See also:** `SceneGeometryOfKind`, `Geometry`.

***

# SceneGeometryOfKind

Conditional helper that narrows a `SceneGeometry` union to a specific primitive.

## Import

```ts
import type { SceneGeometryOfKind } from "vgpu/scene";
```

## Signature

```ts
type SceneGeometryOfKind<K extends import("vgpu/scene").GeometryKind> = Extract<import("vgpu/scene").SceneGeometry, { readonly kind: K }>;
```

## Parameters

| Param | Type           | Required | Default | Notes                                |
| ----- | -------------- | -------- | ------- | ------------------------------------ |
| K     | `GeometryKind` | ✔        | —       | Primitive to extract from the union. |

**Returns:** Not applicable.

**Throws:** None.

## Examples

```ts
import { sphere } from "vgpu/scene";
import type { SceneGeometryOfKind } from "vgpu/scene";

const glossy: SceneGeometryOfKind<"sphere"> = sphere({ radius: 1 });
```

## Notes

* Use this helper when writing utilities that only accept a single primitive while keeping props strongly typed.
* **See also:** `SceneGeometry`, `GeometryKind`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: External hierarchy
description: Evaluate parent-child transforms stored in application-owned arrays.
---

# External hierarchy



# hierarchyOrder

Validates a dense parent-index array and compiles it into an opaque `HierarchyOrder` token for `evaluateHierarchy`. Build it once per topology — at load time and again whenever any parent link changes.

## Import

```ts
import { hierarchyOrder } from "vgpu/scene";
```

## Signature

```ts
declare function hierarchyOrder(parents: Int32Array): import("vgpu/scene").HierarchyOrder;
```

## Parameters

| Param   | Type         | Required | Default | Notes                                                                                                                                                                                                                                                                            |
| ------- | ------------ | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| parents | `Int32Array` | ✔        | —       | One entry per row: `-1` for a root, otherwise the index of the parent row in `0..n-1`. Rows may appear in any order (a child may precede its parent) and there may be any number of roots. An empty array is valid. Copied: later changes to your array do not affect the token. |

**Returns:** `HierarchyOrder` — an opaque, frozen token whose only public field is `size` (the row count). It privately holds a copy of `parents`, a parent-before-child traversal order, and reusable scratch memory.

**Throws:**

* `VGPU-SPATIAL-PARENT` when `parents[row]` is below `-1` or at least `parents.length` — the message names the row and value; use `-1` for a root or a valid row index.
* `VGPU-SPATIAL-CYCLE` when a row is its own parent or several rows form a cycle — the message lists the implicated rows; remove the cyclic parent links before compiling.

## Examples

```ts
import { hierarchyOrder } from "vgpu/scene";

// row 0: base (root), row 1: upper arm, row 2: forearm, row 3: a second, unrelated root
const parents = new Int32Array([-1, 0, 1, -1]);
const order = hierarchyOrder(parents);
console.log(order.size); // 4
```

## Notes

* Cost: O(n) time plus a few `Int32Array`/`Uint8Array` allocations of size n. Keep the token and reuse it every frame; do not rebuild it per frame unless the topology actually changes.
* After any change to `parents`, build a new token and run a full evaluation (omit `changed`). Evaluating with the old token throws `VGPU-SPATIAL-ORDER`.
* The token has no mutable rows or traversal data; you cannot inspect or edit the compiled order.
* **See also:** `evaluateHierarchy`, `HierarchyOrder`, `HierarchyEvaluation`.

***

# evaluateHierarchy

Computes world matrices for a flat hierarchy stored in packed arrays: `worlds[row] = worlds[parent] × locals[row]`, or `locals[row]` for roots. Use it for large or externally owned hierarchies (imported skeletons, ECS data, physics-driven rigs) where one `SceneNode` object per row is unnecessary.

## Import

```ts
import { evaluateHierarchy } from "vgpu/scene";
```

## Signature

```ts
declare function evaluateHierarchy(input: import("vgpu/scene").HierarchyEvaluation): number;
```

## Parameters

| Param         | Type             | Required | Default                      | Notes                                                                                                                                                            |
| ------------- | ---------------- | -------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| input.order   | `HierarchyOrder` | ✔        | —                            | Token from `hierarchyOrder(parents)`. Hand-made objects are rejected.                                                                                            |
| input.parents | `Int32Array`     | ✔        | —                            | Exactly `order.size` entries, identical to the array the token was compiled from. Read-only.                                                                     |
| input.locals  | `Float32Array`   | ✔        | —                            | Exactly `16 * order.size` values: one column-major local matrix per row. Read-only. Assumed finite and affine; not validated per call.                           |
| input.worlds  | `Float32Array`   | ✔        | —                            | Exactly `16 * order.size` values. Written for every recomputed row; rows that are not recomputed are read (as parent worlds) and left as they are.               |
| input.changed | `Uint8Array`     | ✖        | omitted: recompute every row | Exactly `order.size` flags; nonzero marks a row whose local matrix changed. Marked rows and every descendant of a recomputed row are recomputed. Never modified. |
| input.updated | `Uint8Array`     | ✖        | omitted: no report           | Exactly `order.size` flags. Every entry is overwritten: `1` for rows recomputed by this call, `0` for all others.                                                |

**Returns:** `number` — how many world rows this call recomputed, including descendants reached through propagation. `0` for an empty hierarchy or when no flag is set.

**Throws:** all checks run before any write, so `worlds` and `updated` are untouched when the call throws.

* `VGPU-SPATIAL-ORDER` when `order` was not created by `hierarchyOrder`, or `parents` differs from the compiled copy — the message names the first differing row; rebuild with `hierarchyOrder(parents)`, then run a full evaluation without `changed`.
* `VGPU-SPATIAL-SIZE` when `parents`, `changed` or `updated` does not have exactly `order.size` entries, or `locals` or `worlds` does not have exactly `16 * order.size` — the message states the actual and required length; allocate exact lengths (use `subarray` to trim a larger buffer).
* `VGPU-SPATIAL-ALIAS` when `worlds` or `updated` overlaps the other output or any input array in memory — use non-overlapping byte ranges for the writable outputs.

## Examples

Initialize with a full evaluation, then recompute only what changed:

```ts
import { composeMatrix, evaluateHierarchy, hierarchyOrder } from "vgpu/scene";

const parents = new Int32Array([-1, 0, 1]); // base → upper arm → forearm
const rowCount = parents.length;
const locals = new Float32Array(rowCount * 16);
const worlds = new Float32Array(rowCount * 16);
const localRow = (row: number) => locals.subarray(row * 16, row * 16 + 16);

composeMatrix({ position: [0, 0.5, 0] }, localRow(0));
composeMatrix({ position: [0, 1, 0] }, localRow(1));
composeMatrix({ position: [0, 1, 0] }, localRow(2));

const order = hierarchyOrder(parents);
evaluateHierarchy({ order, parents, locals, worlds }); // full evaluation: returns 3

const changed = new Uint8Array(rowCount);
composeMatrix({ position: [0, 1, 0], rotation: [0, 0, 0.4] }, localRow(1));
changed[1] = 1; // you must mark every row whose local you wrote
const recomputed = evaluateHierarchy({ order, parents, locals, worlds, changed }); // 2: upper arm + forearm
changed.fill(0); // evaluateHierarchy never clears your flags
void recomputed;
```

Change the topology — rebuild the token and evaluate everything:

```ts
import { composeMatrix, evaluateHierarchy, hierarchyOrder } from "vgpu/scene";

const parents = new Int32Array([-1, 0, 1]);
const locals = new Float32Array(3 * 16);
const worlds = new Float32Array(3 * 16);
for (let row = 0; row < parents.length; row++) {
  composeMatrix({}, locals.subarray(row * 16, row * 16 + 16));
}
let order = hierarchyOrder(parents);
evaluateHierarchy({ order, parents, locals, worlds });

parents[2] = 0; // reparent the forearm onto the base
order = hierarchyOrder(parents); // the old token now throws VGPU-SPATIAL-ORDER
evaluateHierarchy({ order, parents, locals, worlds }); // full evaluation after a topology change
```

Report which rows need re-upload, using disjoint views of one buffer:

```ts
import { composeMatrix, evaluateHierarchy, hierarchyOrder } from "vgpu/scene";

const rowCount = 2;
const parents = new Int32Array([-1, 0]);
const matrices = new Float32Array(rowCount * 32); // locals then worlds in one allocation
const locals = matrices.subarray(0, rowCount * 16);
const worlds = matrices.subarray(rowCount * 16); // disjoint from locals: allowed
const changed = new Uint8Array(rowCount);
const updated = new Uint8Array(rowCount);
const order = hierarchyOrder(parents);
for (let row = 0; row < rowCount; row++) {
  composeMatrix({}, locals.subarray(row * 16, row * 16 + 16));
}

evaluateHierarchy({ order, parents, locals, worlds, updated }); // updated = [1, 1]
changed[1] = 1;
evaluateHierarchy({ order, parents, locals, worlds, changed, updated }); // updated = [0, 1]
```

## Notes

* Full evaluation first: omit `changed` after creating a token, after a topology change, and whenever `worlds` is a new, reset, or externally overwritten buffer. With `changed`, clean rows keep whatever `worlds` already holds and children of clean rows read that stored parent world, so stale or zeroed rows stay stale.
* Dirty marking is your responsibility: vgpu cannot detect a local row you wrote without setting its flag. `evaluateHierarchy` does not clear `changed`; reset it yourself after the call.
* Cost: every call compares `parents` with the compiled copy and scans all n rows in parent-before-child order (O(n)), then performs one 4×4 multiply (or a 16-value copy for roots) per recomputed row. There is no partial traversal and no sparse-only path; a single changed root recomputes its whole subtree.
* Aliasing: the writable outputs `worlds` and `updated` must not share any byte with each other or with `parents`, `locals` or `changed` — checked by byte range, so overlapping `subarray` views of one buffer are rejected while disjoint views are allowed. Read-only inputs may overlap each other.
* No output state is retained: the token does not remember `worlds` or whether a buffer was initialized, so the same token can drive several output buffers as long as each gets its own full evaluation first.
* `locals` are trusted for speed: non-finite or non-affine rows are not detected and propagate into `worlds`. Validate data from untrusted sources before writing it, or write rows with `composeMatrix`/`localFromWorld`, which validate.
* Calls are synchronous; mutating the arrays concurrently (for example from a worker through a `SharedArrayBuffer`) is not supported.
* **See also:** `hierarchyOrder`, `HierarchyEvaluation`, `composeMatrix`, `localFromWorld`, `SceneNode`.

***

# HierarchyOrder

The opaque compiled-topology token returned by `hierarchyOrder`. Pass it back to `evaluateHierarchy` unchanged; its only public field is the row count.

## Import

```ts
import type { HierarchyOrder } from "vgpu/scene";
```

## Signature

```ts
interface HierarchyOrder {
  readonly size: number;
}
```

## Parameters

| Field | Type     | Required | Default | Notes                                                                      |
| ----- | -------- | -------- | ------- | -------------------------------------------------------------------------- |
| size  | `number` | ✔        | —       | Number of rows compiled into the token (`parents.length` at compile time). |

**Returns:** Not a callable.

**Throws:** None by itself; `evaluateHierarchy` throws `VGPU-SPATIAL-ORDER` for any object not produced by `hierarchyOrder`, even one with a matching `size`.

## Examples

```ts
import { hierarchyOrder, type HierarchyOrder } from "vgpu/scene";

const order: HierarchyOrder = hierarchyOrder(new Int32Array([-1, 0, 0]));
const rowCount = order.size; // 3
const worlds = new Float32Array(rowCount * 16);
void worlds;
```

## Notes

* Do not construct `{ size }` objects yourself; they cannot carry the compiled topology.
* The token is frozen and holds private copies, so it stays valid until you stop referencing it. Memory is released when the token is garbage-collected.
* **See also:** `hierarchyOrder`, `evaluateHierarchy`.

***

# HierarchyEvaluation

The input object for `evaluateHierarchy`: a compiled order, its parents, packed local and world matrices, and optional dirty flags in and out.

## Import

```ts
import type { HierarchyEvaluation } from "vgpu/scene";
```

## Signature

```ts
interface HierarchyEvaluation {
  order: import("vgpu/scene").HierarchyOrder;
  parents: Int32Array;
  locals: Float32Array;
  worlds: Float32Array;
  changed?: Uint8Array;
  updated?: Uint8Array;
}
```

## Parameters

| Field   | Type             | Required | Default                     | Notes                                                                               |
| ------- | ---------------- | -------- | --------------------------- | ----------------------------------------------------------------------------------- |
| order   | `HierarchyOrder` | ✔        | —                           | From `hierarchyOrder(parents)`.                                                     |
| parents | `Int32Array`     | ✔        | —                           | Length n; must equal the compiled parents exactly. Read-only.                       |
| locals  | `Float32Array`   | ✔        | —                           | Length 16n; finite affine column-major matrices. Read-only.                         |
| worlds  | `Float32Array`   | ✔        | —                           | Length 16n; output. Must not overlap any other field.                               |
| changed | `Uint8Array`     | ✖        | omitted: recompute all rows | Length n; nonzero = local changed. Read-only; never cleared by vgpu.                |
| updated | `Uint8Array`     | ✖        | omitted: no report          | Length n; output, fully overwritten with `1`/`0`. Must not overlap any other field. |

**Returns:** Not a callable.

**Throws:** None by itself; see `evaluateHierarchy` for `VGPU-SPATIAL-ORDER`, `VGPU-SPATIAL-SIZE` and `VGPU-SPATIAL-ALIAS`.

## Examples

```ts
import { composeMatrix, evaluateHierarchy, hierarchyOrder, type HierarchyEvaluation } from "vgpu/scene";

const parents = new Int32Array([-1, 0]);
const locals = new Float32Array(2 * 16);
for (let row = 0; row < parents.length; row++) {
  composeMatrix({}, locals.subarray(row * 16, row * 16 + 16));
}
const skeleton: HierarchyEvaluation = {
  order: hierarchyOrder(parents),
  parents,
  locals,
  worlds: new Float32Array(2 * 16),
};
evaluateHierarchy(skeleton); // full evaluation
skeleton.changed = new Uint8Array(2);
evaluateHierarchy(skeleton); // later frames: set flags, evaluate, clear flags
```

## Notes

* The object fields are mutable so an app may attach or replace `changed`; the typed arrays remain app-owned. Omit `changed` whenever a full evaluation is required.
* **See also:** `evaluateHierarchy`, `hierarchyOrder`, `HierarchyOrder`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: instances
description: Creates a fixed-capacity collection of instance records: one world matrix plus your typed per-instance attributes, packed for upload. Use it for large populations of the same mesh (trees, particles, crowd agents, debris) where one `SceneNode` per object is unnecessary.
---

# instances



## Import

```ts
import { instances } from "vgpu/scene";
```

## Signature

```ts
declare function instances<const A extends import("vgpu/scene").InstanceAttributes = {}>(options: {
  capacity: number;
  attributes?: A;
}): import("vgpu/scene").InstanceCollection<A>;
```

## Parameters

| Param              | Type                 | Required | Default | Notes                                                                                                                                                                                                                                                                                                                                                                         |
| ------------------ | -------------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| options.capacity   | `number`             | ✔        | —       | Maximum number of live instances. A nonnegative integer; `0` is valid (every `add()` then throws `VGPU-INSTANCE-CAPACITY`). Fixed for the life of the collection: there is no growth.                                                                                                                                                                                         |
| options.attributes | `InstanceAttributes` | ✖        | `{}`    | Per-instance attributes in declaration order. Each value is an `InstanceFormat` string (required on `add`) or `{ format, default }` (optional on `add`). Names must not be numeric and must not be `world0`, `world1`, `world2` or `world3`, which are reserved for the world matrix columns. Snapshotted: later changes to this object or its default arrays have no effect. |

**Returns:** `InstanceCollection<A>` — an empty collection (`count` is `0`) whose `add`, `set` and value types are inferred from `attributes`. You do not need `as const`.

**Throws:**

* `VGPU-INSTANCE-CAPACITY` when `capacity` is negative, fractional, `NaN`, `Infinity`, or so large that `capacity × stride` bytes cannot be represented — pass a nonnegative integer sized for your peak population.
* `VGPU-INSTANCE-ATTRIBUTE` when an attribute has an unknown format, a numeric name, or a reserved `world0`–`world3` name — use one of the 12 `InstanceFormat` values and rename the key.
* `VGPU-INSTANCE-VALUE` when a `default` does not match its format: wrong arity (a number for a vector format, an array for a scalar, or the wrong length), a non-finite or float32-overflowing float, or a non-integer or out-of-range integer — the message names the attribute path; supply a default of the exact format.

## Examples

One required attribute and one defaulted attribute:

```ts
import { instances } from "vgpu/scene";

const trees = instances({
  capacity: 1024,
  attributes: {
    windPhase: "float32", // required on add()
    tint: { format: "float32x3", default: [0.3, 0.6, 0.2] }, // optional on add()
  },
});

const oak = trees.add({ windPhase: 0.4 }); // tint uses the default, world is identity
const birch = trees.add({ windPhase: 1.7, tint: [0.8, 0.8, 0.7] });
trees.setWorld(oak, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 4, 0, -2, 1]); // translate to (4, 0, -2)
console.log(trees.count, trees.slotOf(birch)); // 2, 1
```

A collection without attributes stores only world matrices, and `add()` takes no argument:

```ts
import { instances } from "vgpu/scene";

const rocks = instances({ capacity: 64 });
const boulder = rocks.add(); // identity world
rocks.setWorld(boulder, [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1]); // uniform scale 2
```

## Notes

* Record layout: each record starts with the 64-byte column-major world matrix, followed by your attributes in declaration order, tightly packed at 4-byte alignment (4 bytes per component, no padding to 16). The stride is `64 + 4 × (total attribute components)`: `windPhase: "float32"` plus `tint: "float32x3"` gives an 80-byte record, with `windPhase` at byte 64 and `tint` at byte 68.
* Fixed capacity: memory for `capacity` records is allocated once. When you outgrow it, create a larger collection, re-add your instances (which issues new `InstanceId`s), re-create any `bindWorld` sources and GPU bridges, and switch your draws to the new ones.
* Types check scalar versus vector and the attribute names; they cannot check vector length, because vector values are `ArrayLike<number>`. The runtime checks exact arity on every write. A `default`'s shape is not checked against its `format` by the types either.
* The collection is CPU-only. It never uploads: nothing reaches the GPU until a GPU bridge publishes it (`instanceGeometry(gpu, collection, { mesh })` from `vgpu/scene/gpu`, whose reference documents publication ordering).
* **See also:** `InstanceCollection`, `InstanceAttributes`, `InstanceFormat`, `InstanceId`, `evaluateHierarchy`, `group`.

***

# InstanceCollection

A dense, fixed-capacity store of instance records created by `instances()`. Each live instance has an opaque `InstanceId` handle and a current slot in `0..count-1`; the handle is stable while the instance lives, the slot is not.

## Import

```ts
import type { InstanceCollection } from "vgpu/scene";
```

## Signature

```ts
interface InstanceCollection<A extends import("vgpu/scene").InstanceAttributes = {}> {
  readonly capacity: number;
  readonly count: number;
  add(...args: import("vgpu/scene").InstanceAddArgs<A>): import("vgpu/scene").InstanceId;
  remove(id: import("vgpu/scene").InstanceId): void;
  set(id: import("vgpu/scene").InstanceId, values: Partial<import("vgpu/scene").InstanceValues<A>>): void;
  setWorld(id: import("vgpu/scene").InstanceId, world: ArrayLike<number>): void;
  setWorlds(ids: ArrayLike<import("vgpu/scene").InstanceId>, worlds: Float32Array, firstRow?: number): void;
  bindWorld(id: import("vgpu/scene").InstanceId, source: () => ArrayLike<number>): void;
  unbindWorld(id: import("vgpu/scene").InstanceId): void;
  syncWorlds(): number;
  slotOf(id: import("vgpu/scene").InstanceId): number;
  idAt(slot: number): import("vgpu/scene").InstanceId;
}
```

## Parameters

| Member                           | Type                                          | Required                                           | Default                                               | Notes                                                                                                                                                                                                                                                                     |
| -------------------------------- | --------------------------------------------- | -------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| capacity                         | `number`                                      | —                                                  | from `instances()`                                    | Read-only. Maximum live instances; never changes.                                                                                                                                                                                                                         |
| count                            | `number`                                      | —                                                  | `0`                                                   | Read-only. Live instances, stored densely in slots `0..count-1`.                                                                                                                                                                                                          |
| add(values)                      | `InstanceInitialValues<A>`                    | ✔ when any attribute has no `default`, otherwise ✖ | omitted fields use their `default`; world is identity | Appends a record and returns its new `InstanceId`. Unknown and missing required fields are rejected. Validates every field before writing, so a failed `add` leaves `count` unchanged.                                                                                    |
| remove(id)                       | `InstanceId`                                  | ✔                                                  | —                                                     | Swap-remove: the record in the last slot is copied into the removed slot and `count` drops by 1. The moved instance keeps its `InstanceId` but its slot changes. Drops the removed instance's `bindWorld` source. The removed `id` is never valid again and never reused. |
| set(id, values)                  | `InstanceId, Partial<InstanceValues<A>>`      | ✔                                                  | —                                                     | Patches attributes: omitted fields keep their values. All fields are validated before any is written. Allowed on world-bound instances. Cannot write the world; use `setWorld`, `setWorlds` or `bindWorld`.                                                               |
| setWorld(id, world)              | `InstanceId, ArrayLike<number>`               | ✔                                                  | —                                                     | Copies one world matrix: exactly 16 column-major values, finite and float32-representable, with bottom row (indices 3, 7, 11, 15) exactly `0, 0, 0, 1`. Shear and reflection are allowed. Rejected on a world-bound instance.                                             |
| setWorlds(ids, worlds, firstRow) | `ArrayLike<InstanceId>, Float32Array, number` | ids ✔, worlds ✔, firstRow ✖                        | firstRow `0`                                          | Copies `ids[i]`'s world from `worlds` row `firstRow + i` (elements `(firstRow + i) × 16` to `+16`). Validates the whole batch — every handle, duplicates, bound state, the range and every matrix — before copying any row. An empty `ids` is valid and changes nothing.  |
| bindWorld(id, source)            | `InstanceId, () => ArrayLike<number>`         | ✔                                                  | —                                                     | Registers a synchronous accessor that `syncWorlds()` reads. Does not call `source`; the world keeps its current value until the next `syncWorlds()`.                                                                                                                      |
| unbindWorld(id)                  | `InstanceId`                                  | ✔                                                  | —                                                     | Removes the source. The world keeps the last copied value. A no-op for a live, unbound instance.                                                                                                                                                                          |
| syncWorlds()                     | —                                             | —                                                  | —                                                     | Calls every bound source once and copies its result into that instance's world. Never uploads.                                                                                                                                                                            |
| slotOf(id)                       | `InstanceId`                                  | ✔                                                  | —                                                     | Current slot of a live instance. Changes when another instance is removed.                                                                                                                                                                                                |
| idAt(slot)                       | `number`                                      | ✔                                                  | —                                                     | The `InstanceId` currently in `slot`; `slot` must be an integer in `0..count-1`.                                                                                                                                                                                          |

**Returns:** `add` returns the new `InstanceId`. `syncWorlds` returns the number of sources it copied. `slotOf` returns a slot number and `idAt` an `InstanceId`. `remove`, `set`, `setWorld`, `setWorlds`, `bindWorld` and `unbindWorld` return `undefined`.

**Throws:** every method validates its complete input before changing anything, except `syncWorlds` (see the source bullet).

* `VGPU-INSTANCE-HANDLE` from any method taking an `InstanceId` when the handle was removed, belongs to another collection, or is a number that was not returned by this collection's `add` — use a live `InstanceId` from this collection; never pass a slot as a handle.
* `VGPU-INSTANCE-CAPACITY` from `add` when `count` equals `capacity` — remove instances, or create a larger collection and rebuild its bindings and GPU bridges.
* `VGPU-INSTANCE-ATTRIBUTE` from `add` when a required attribute is missing, or from `add`/`set` when a key is not a declared attribute — pass every attribute without a `default` and only declared names.
* `VGPU-INSTANCE-VALUE` from `add`/`set` when a value has the wrong arity, is `NaN`/`Infinity` or overflows float32 for a float format, or is fractional or outside the 32-bit range for `sint32` (`-2147483648..2147483647`) or `uint32` (`0..4294967295`); from `setWorld`/`setWorlds` when a matrix is not 16 finite float32-representable values or its bottom row is not exactly `0, 0, 0, 1`; or from `setWorlds` when `worlds` is not a `Float32Array` — the message names the attribute or matrix element; pass a value of the exact format, or an affine `Float32Array` of 16-value rows.
* `VGPU-INSTANCE-RANGE` from `setWorlds` when `ids` is not array-like, `firstRow` is not a nonnegative integer, `worlds` has fewer than `(firstRow + ids.length) × 16` elements, or an `InstanceId` appears twice in `ids`; from `idAt` when `slot` is not an integer in `0..count-1` — pass in-range contiguous rows, each handle at most once, and a live slot.
* `VGPU-INSTANCE-BOUND` from `bindWorld` when the instance already has a source, or from `setWorld`/`setWorlds` when it has one — call `unbindWorld(id)` first.
* `VGPU-INSTANCE-SOURCE` from `bindWorld` when `source` is not a function, or from `syncWorlds` when a source throws (the original error is the `cause`) or returns an invalid matrix (the `VGPU-INSTANCE-VALUE` error is the `cause`) — the message names the instance; make the source return a finite affine 16-value matrix synchronously. Sources called before the failing one have already been copied: there is no rollback or retry.
* `VGPU-INSTANCE-REENTRANT` when any mutation (`add`, `remove`, `set`, `setWorld`, `setWorlds`, `bindWorld`, `unbindWorld`), a nested `syncWorlds`, or a GPU bridge publication runs while `syncWorlds` is calling sources — keep sources read-only and mutate or publish after `syncWorlds` returns.
* `VGPU-INSTANCE-EXHAUSTED` when an internal identity or change counter would pass the largest safe integer — the message names the counter. Counters never wrap into stale values; stop using the exhausted collection and rebuild your instance state as the message directs.

## Examples

Drive instance worlds from articulated nodes with `bindWorld`:

```ts
import { group, instances } from "vgpu/scene";

const turret = group({ position: [0, 1, 0] });
const barrelLeft = group({ position: [-0.3, 0.2, -1] });
const barrelRight = group({ position: [0.3, 0.2, -1] });
turret.add(barrelLeft, barrelRight);

const barrels = instances({ capacity: 2, attributes: { heat: { format: "float32", default: 0 } } });
const left = barrels.add();
const right = barrels.add();
barrels.bindWorld(left, () => barrelLeft.worldMatrix); // read-only accessor; the result is copied
barrels.bindWorld(right, () => barrelRight.worldMatrix);

// every frame: update nodes, copy their worlds, then publish through your GPU bridge
turret.set({ rotation: [0, 0.3, 0] });
const copied = barrels.syncWorlds(); // 2
barrels.set(left, { heat: 0.8 }); // attributes stay writable while the world is bound
```

Copy final worlds from an external array in one validated batch:

```ts
import { composeMatrix, instances } from "vgpu/scene";

const agentCount = 3;
const crowd = instances({ capacity: 256, attributes: { team: "uint32" } });
const agentIds = Array.from({ length: agentCount }, (_, index) => crowd.add({ team: index % 2 }));

const simulationWorlds = new Float32Array(agentCount * 16); // owned by your simulation
for (let row = 0; row < agentCount; row++) {
  composeMatrix({ position: [row * 2, 0, 0] }, simulationWorlds.subarray(row * 16, row * 16 + 16));
}

crowd.setWorlds(agentIds, simulationWorlds); // row i → agentIds[i]; all-or-nothing
crowd.setWorlds(agentIds.slice(1), simulationWorlds, 1); // rows 1 and 2 only
```

Hand an instance from a node to a physics engine that writes final worlds:

```ts
import { group, instances } from "vgpu/scene";

const hand = group({ position: [0, 1.2, 0] });
const crates = instances({ capacity: 32 });
const crate = crates.add();
crates.bindWorld(crate, () => hand.worldMatrix); // carried by the hand
crates.syncWorlds();

crates.unbindWorld(crate); // released: the last copied world stays in place
const physicsWorld = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0.9, 0, 1]);
crates.setWorld(crate, physicsWorld); // direct writes are allowed again
```

Map a picked `instance_index` back to your data and remove it:

```ts
import { instances, type InstanceId } from "vgpu/scene";

const stars = instances({ capacity: 3, attributes: { brightness: "float32" } });
const names = new Map<InstanceId, string>();
names.set(stars.add({ brightness: 1 }), "Vega");
names.set(stars.add({ brightness: 0.4 }), "Deneb");
const altair = stars.add({ brightness: 0.8 });
names.set(altair, "Altair");

const pickedSlot = 0; // e.g. instance_index read back from a picking pass drawn from instance 0
const pickedId = stars.idAt(pickedSlot); // resolve before the next add/remove moves slots
stars.remove(pickedId); // swap-remove: Altair moves from slot 2 to slot 0
names.delete(pickedId);
console.log(stars.count, stars.slotOf(altair)); // 2, 0
```

## Notes

* Handles vs slots: an `InstanceId` identifies one live instance of one collection and is never reused. A slot is its current position in the packed records and equals WGSL `instance_index` when the draw starts at instance 0. Slots move on every `remove` that is not the last slot. Keep your own data keyed by `InstanceId`, never by slot. Picking maps and per-frame slot snapshots for results read back later are yours to keep; `idAt` answers only for the current state.
* Handles are opaque numbers with no serialization or cross-process meaning. Do not store them in files or send them across workers.
* Sources: a source runs synchronously inside `syncWorlds()` and its result is copied, so returning a borrowed array such as `node.worldMatrix` is safe. `syncWorlds()` does not evaluate hierarchies or cameras for you — sources read whatever state they close over.
* When `syncWorlds()` throws `VGPU-INSTANCE-SOURCE`, some worlds may already hold this frame's values and others last frame's. Let the error end the frame (an uncaught error stops `frameLoop(gpu)`), fix or `unbindWorld` the failing source, then call `syncWorlds()` again before the next publication. The reentrancy guard is always released, even after a throw.
* Costs: `setWorld` and each `setWorlds` row cost validation plus a 64-byte copy; `setWorlds` validates the entire batch before copying. `syncWorlds` calls each source once and pays the same validation and copy per source. `add` writes one full record, and `set` stages and copies one full record after validating the supplied fields. A `remove` that is not the last slot copies one full record. No method promises to be allocation-free.
* Change tracking: every successful `add`, `set`, world write, swap-remove move and `syncWorlds` copy marks the affected slot as changed; a `remove` of the last slot shrinks `count` and that change is visible too. Each GPU bridge keeps its own cursor, so two bridges over the same collection each see every change — publishing one does not consume another's pending updates. Do not assume publication cost is proportional to the number of changes; a bridge may scan every record.
* The world is written only by `setWorld`, `setWorlds` and `syncWorlds`. There is no implicit parent/child relationship between instances; combine matrices yourself, or use nodes or `evaluateHierarchy` and copy the results.
* Do not read or write the packed records directly; the collection exposes no mutable arrays. Write through the methods so change tracking stays correct.
* **See also:** `instances`, `InstanceId`, `InstanceValues`, `group`, `evaluateHierarchy`, `composeMatrix`.

***

# InstanceId

An opaque, branded handle for one live instance in one `InstanceCollection`. Returned by `add()` and accepted by every per-instance method.

## Import

```ts
import type { InstanceId } from "vgpu/scene";
```

## Signature

```ts
type InstanceId = number & { readonly __instanceId: unique symbol };
```

## Parameters

| Field   | Type     | Required | Default | Notes                                                                                                                                                      |
| ------- | -------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| (value) | `number` | —        | —       | Issued by `add()`. Stable while the instance lives, invalid after `remove()`, never reused, and rejected by other collections with `VGPU-INSTANCE-HANDLE`. |

## Examples

```ts
import { instances, type InstanceId } from "vgpu/scene";

const lamps = instances({ capacity: 8 });
const lampIds: InstanceId[] = [lamps.add(), lamps.add()];
lamps.remove(lampIds[0]!);
console.log(lamps.slotOf(lampIds[1]!)); // 0: the handle stayed valid, the slot moved
```

## Notes

* The brand stops plain numbers and slots from type-checking as handles. Do not cast a slot or a stored number to `InstanceId`; `VGPU-INSTANCE-HANDLE` rejects handles this collection did not issue.
* The numeric value carries no slot, generation or ordering information you can rely on.
* **See also:** `InstanceCollection`, `instances`.

***

# InstanceFormat

The 12 formats an instance attribute can use: 32-bit float, signed integer and unsigned integer scalars and 2-, 3- and 4-component vectors.

## Import

```ts
import type { InstanceFormat } from "vgpu/scene";
```

## Signature

```ts
type InstanceFormat =
  | "float32" | "float32x2" | "float32x3" | "float32x4"
  | "sint32" | "sint32x2" | "sint32x3" | "sint32x4"
  | "uint32" | "uint32x2" | "uint32x3" | "uint32x4";
```

## Parameters

| Value                     | Type                           | Required | Default | Notes                                                                                 |
| ------------------------- | ------------------------------ | -------- | ------- | ------------------------------------------------------------------------------------- |
| `float32`, `float32x2..4` | `number` / `ArrayLike<number>` | —        | —       | 4 bytes per component. Values must be finite and stay finite when rounded to float32. |
| `sint32`, `sint32x2..4`   | `number` / `ArrayLike<number>` | —        | —       | 4 bytes per component. Integers in `-2147483648..2147483647`.                         |
| `uint32`, `uint32x2..4`   | `number` / `ArrayLike<number>` | —        | —       | 4 bytes per component. Integers in `0..4294967295`.                                   |

## Examples

```ts
import { instances, type InstanceFormat } from "vgpu/scene";

const cellFormat: InstanceFormat = "sint32x2";
const tiles = instances({ capacity: 16, attributes: { cell: cellFormat } });
tiles.add({ cell: new Int32Array([3, -1]) });
```

## Notes

* Scalar formats take a `number`; vector formats take an `ArrayLike<number>` of exactly 2, 3 or 4 values — arrays and typed arrays both work.
* No 8- or 16-bit or normalized formats exist; widen small values to 32 bits.
* **See also:** `InstanceAttribute`, `InstanceValue`.

***

# InstanceAttribute

One attribute declaration: a bare `InstanceFormat` (required on `add`) or `{ format, default }` (optional on `add`, filled from `default`).

## Import

```ts
import type { InstanceAttribute } from "vgpu/scene";
```

## Signature

```ts
type InstanceAttribute = import("vgpu/scene").InstanceFormat | {
  format: import("vgpu/scene").InstanceFormat;
  default: number | ArrayLike<number>;
};
```

## Parameters

| Field         | Type                          | Required | Default | Notes                                                                                                                                                        |
| ------------- | ----------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| (string form) | `InstanceFormat`              | —        | —       | No default: `add()` must supply the value.                                                                                                                   |
| format        | `InstanceFormat`              | ✔        | —       | Format of the attribute.                                                                                                                                     |
| default       | `number \| ArrayLike<number>` | ✔        | —       | Value used when `add()` omits the field. A `number` for scalar formats, exactly 2–4 values for vectors. Validated and copied when the collection is created. |

## Examples

```ts
import { instances, type InstanceAttribute } from "vgpu/scene";

const tint: InstanceAttribute = { format: "float32x4", default: [1, 1, 1, 1] };
const sprites = instances({ capacity: 100, attributes: { tint, frame: "uint32" } });
sprites.add({ frame: 0 }); // tint defaults to opaque white
```

## Notes

* The types do not tie `default`'s shape to `format`; `instances()` throws `VGPU-INSTANCE-VALUE` for a mismatched default.
* **See also:** `InstanceAttributes`, `InstanceFormat`, `instances`.

***

# InstanceAttributes

The schema object passed as `instances({ attributes })`: attribute names mapped to `InstanceAttribute` declarations, in declaration order.

## Import

```ts
import type { InstanceAttributes } from "vgpu/scene";
```

## Signature

```ts
type InstanceAttributes = Record<string, import("vgpu/scene").InstanceAttribute>;
```

## Parameters

| Field   | Type                | Required | Default       | Notes                                                                                          |
| ------- | ------------------- | -------- | ------------- | ---------------------------------------------------------------------------------------------- |
| \[name] | `InstanceAttribute` | ✖        | no attributes | Key order is record layout order. Names must not be numeric and must not be `world0`–`world3`. |

## Examples

```ts
import { instances } from "vgpu/scene";

const particles = instances({
  capacity: 4096,
  attributes: {
    velocity: "float32x3",
    age: { format: "float32", default: 0 },
    seed: "uint32",
  },
});
particles.add({ velocity: [0, 2, 0], seed: 7 }); // record: world, velocity, age, seed (84 bytes)
```

## Notes

* Pass the object literal directly to `instances()` so required and defaulted keys are inferred. A value annotated as `InstanceAttributes` loses its literal keys, and `add`/`set` then accept any string key at compile time.
* **See also:** `instances`, `InstanceAttribute`, `InstanceInitialValues`.

***

# InstanceAttributeFormat

Type helper that extracts the `InstanceFormat` of one attribute declaration, whether it is a bare format or `{ format, default }`.

## Import

```ts
import type { InstanceAttributeFormat } from "vgpu/scene";
```

## Signature

```ts
type InstanceAttributeFormat<T extends import("vgpu/scene").InstanceAttribute> =
  T extends { format: infer F extends import("vgpu/scene").InstanceFormat }
    ? F
    : Extract<T, import("vgpu/scene").InstanceFormat>;
```

## Parameters

| Param | Type                | Required | Default | Notes                                                                                  |
| ----- | ------------------- | -------- | ------- | -------------------------------------------------------------------------------------- |
| T     | `InstanceAttribute` | ✔        | —       | `"float32x3"` and `{ format: "float32x3"; default: … }` both resolve to `"float32x3"`. |

## Examples

```ts
import type { InstanceAttributeFormat } from "vgpu/scene";

type TintFormat = InstanceAttributeFormat<{ format: "float32x4"; default: [1, 1, 1, 1] }>; // "float32x4"
const tintFormat: TintFormat = "float32x4";
```

## Notes

* **See also:** `InstanceValue`, `InstanceValues`.

***

# InstanceValue

Type helper that maps an `InstanceFormat` to the value you pass: `number` for scalar formats, `ArrayLike<number>` for vector formats.

## Import

```ts
import type { InstanceValue } from "vgpu/scene";
```

## Signature

```ts
type InstanceValue<F extends import("vgpu/scene").InstanceFormat> =
  F extends "float32" | "sint32" | "uint32" ? number : ArrayLike<number>;
```

## Parameters

| Param | Type             | Required | Default | Notes                                                                                      |
| ----- | ---------------- | -------- | ------- | ------------------------------------------------------------------------------------------ |
| F     | `InstanceFormat` | ✔        | —       | Scalar formats resolve to `number`; `x2`/`x3`/`x4` formats resolve to `ArrayLike<number>`. |

## Examples

```ts
import type { InstanceValue } from "vgpu/scene";

const layer: InstanceValue<"uint32"> = 3;
const offset: InstanceValue<"float32x2"> = new Float32Array([0.5, -0.5]);
```

## Notes

* Vector length is checked at runtime, not by this type.
* **See also:** `InstanceFormat`, `InstanceValues`.

***

# InstanceValues

Type helper for a complete set of attribute values of a schema: every attribute key, each typed by `InstanceValue` of its format. `set()` takes `Partial<InstanceValues<A>>`.

## Import

```ts
import type { InstanceValues } from "vgpu/scene";
```

## Signature

```ts
type InstanceValues<A extends import("vgpu/scene").InstanceAttributes> = {
  [K in keyof A]: import("vgpu/scene").InstanceValue<import("vgpu/scene").InstanceAttributeFormat<A[K]>>;
};
```

## Parameters

| Param | Type                 | Required | Default | Notes                                                                                                               |
| ----- | -------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------- |
| A     | `InstanceAttributes` | ✔        | —       | The collection's schema. Defaulted attributes are required here too; use `InstanceInitialValues` for `add()` input. |

## Examples

```ts
import { instances, type InstanceValues } from "vgpu/scene";

const schema = { heading: "float32", color: { format: "float32x3", default: [1, 1, 1] } } as const;
const boids = instances({ capacity: 500, attributes: schema });
const boid = boids.add({ heading: 0 });

const update: Partial<InstanceValues<typeof schema>> = { color: [1, 0.2, 0.2] };
boids.set(boid, update);
```

## Notes

* When you hoist a schema into a variable to reuse its type, keep its literal types with `as const`; inline object literals passed to `instances()` need no annotation.
* **See also:** `InstanceInitialValues`, `InstanceCollection`.

***

# InstanceInitialValues

Type helper for `add()` input: attributes without a `default` are required keys, attributes with a `default` are optional keys.

## Import

```ts
import type { InstanceInitialValues } from "vgpu/scene";
```

## Signature

```ts
type InstanceInitialValues<A extends import("vgpu/scene").InstanceAttributes> =
  { [K in keyof A as A[K] extends { default: unknown } ? never : K]: import("vgpu/scene").InstanceValues<A>[K] } &
  { [K in keyof A as A[K] extends { default: unknown } ? K : never]?: import("vgpu/scene").InstanceValues<A>[K] };
```

## Parameters

| Param | Type                 | Required | Default | Notes                                                                       |
| ----- | -------------------- | -------- | ------- | --------------------------------------------------------------------------- |
| A     | `InstanceAttributes` | ✔        | —       | The collection's schema. Omitted optional keys take the declared `default`. |

## Examples

```ts
import type { InstanceInitialValues } from "vgpu/scene";

type Schema = { mass: "float32"; tint: { format: "float32x3"; default: [1, 1, 1] } };
const heavy: InstanceInitialValues<Schema> = { mass: 40 }; // tint may be omitted
const painted: InstanceInitialValues<Schema> = { mass: 2, tint: [0.9, 0.1, 0.1] };
```

## Notes

* Unknown keys are rejected at compile time for object literals and at runtime with `VGPU-INSTANCE-ATTRIBUTE`.
* **See also:** `InstanceAddArgs`, `InstanceValues`.

***

# InstanceAddArgs

Type helper for the argument tuple of `add()`: the values argument is optional when every attribute has a `default` (or there are none) and required otherwise.

## Import

```ts
import type { InstanceAddArgs } from "vgpu/scene";
```

## Signature

```ts
type InstanceAddArgs<A extends import("vgpu/scene").InstanceAttributes> = {} extends import("vgpu/scene").InstanceInitialValues<A>
  ? [values?: import("vgpu/scene").InstanceInitialValues<A>]
  : [values: import("vgpu/scene").InstanceInitialValues<A>];
```

## Parameters

| Param | Type                 | Required | Default | Notes                                                                       |
| ----- | -------------------- | -------- | ------- | --------------------------------------------------------------------------- |
| A     | `InstanceAttributes` | ✔        | —       | `[values?]` when no attribute is required, `[values]` when at least one is. |

## Examples

```ts
import { instances } from "vgpu/scene";

const markers = instances({ capacity: 4, attributes: { size: { format: "float32", default: 1 } } });
markers.add(); // every attribute has a default
const labelled = instances({ capacity: 4, attributes: { labelIndex: "uint32" } });
labelled.add({ labelIndex: 0 }); // required: labelled.add() does not compile
```

## Notes

* **See also:** `InstanceInitialValues`, `InstanceCollection`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: group
description: Creates a spatial `SceneNode`: a local position/rotation/scale with parent and children links. Use nodes for a modest number of articulated objects (a robot arm, a camera rig, a vehicle and its wheels); use `evaluateHierarchy` for large or externally owned hierarchies and instance collections for large populations.
---

# group



## Import

```ts
import { group } from "vgpu/scene";
```

## Signature

```ts
declare function group(options?: import("vgpu/scene").NodeOptions): import("vgpu/scene").SceneNode;
```

## Parameters

| Param              | Type                          | Required | Default        | Notes                                                                                                                                   |
| ------------------ | ----------------------------- | -------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| options            | `NodeOptions`                 | ✖        | `{}`           | Initial transform, flags and children. Omit it for an unlabeled, visible node at the origin with identity rotation and scale 1.         |
| options.position   | `ArrayLike<number>`           | ✖        | `[0, 0, 0]`    | Exactly 3 finite, float32-representable numbers. Copied.                                                                                |
| options.rotation   | `ArrayLike<number>`           | ✖        | no rotation    | Exactly 3 finite numbers, intrinsic XYZ Euler radians. Stored as a quaternion. Ignored when `quaternion` is present.                    |
| options.quaternion | `ArrayLike<number>`           | ✖        | `[0, 0, 0, 1]` | Exactly 4 finite numbers, XYZW, nonzero length. A normalized copy is stored; your array is not modified.                                |
| options.scale      | `number \| ArrayLike<number>` | ✖        | `1`            | One number or exactly 3 numbers, each finite and float32-representable.                                                                 |
| options.visible    | `boolean`                     | ✖        | `true`         | App metadata only; see `SceneNode`.                                                                                                     |
| options.label      | `string`                      | ✖        | `undefined`    | App metadata; also used in error `where` strings.                                                                                       |
| options.children   | `readonly SceneNode[]`        | ✖        | `[]`           | Attached in order after the transform is validated. A child that already has a parent is moved here with its local transform unchanged. |

**Returns:** `SceneNode` with `kind: "group"`.

**Throws:**

* `VGPU-SCENE-VALUE` when a transform field has the wrong length, a non-finite or non-float32 component, a zero-length quaternion, a composed matrix outside float32 range, `visible` is not a boolean, `label` is not a string, or a `children` entry is not a `SceneNode` — the message names the field (for example `group.set.position[1]`); fix the value. Nothing is attached when this throws.

## Examples

```ts
import { group } from "vgpu/scene";

const wheelFront = group({ label: "wheel-front", position: [0, -0.3, 1.2] });
const wheelBack = group({ label: "wheel-back", position: [0, -0.3, -1.2] });
const car = group({ label: "car", position: [0, 0.5, 0], children: [wheelFront, wheelBack] });

console.log(wheelFront.worldPosition); // ≈ [0, 0.2, 1.2], rounded to float32
void car;
```

## Notes

* `group()` is the only node factory; it is equivalent to `new SceneNode("group", options)`.
* Nodes are plain CPU state: no geometry, material, or GPU resources. Upload `worldMatrix` to your own uniforms or instance worlds.
* **See also:** `SceneNode`, `NodeOptions`, `composeMatrix`, `evaluateHierarchy`.

***

# SceneNode

A spatial node with a local transform, lazily computed local and world matrices, and parent/children links. Write the transform through `set()` or `lookAt()`; read matrices from the getters, which return stable arrays refreshed on read.

## Import

```ts
import { SceneNode } from "vgpu/scene";
```

## Signature

```ts
declare class SceneNode {
  constructor(kind: import("vgpu/scene").SceneNodeKind, options?: import("vgpu/scene").NodeOptions);
  readonly kind: import("vgpu/scene").SceneNodeKind;
  label: string | undefined;
  visible: boolean;
  set(values: import("vgpu/scene").NodeTransformValues): this;
  lookAt(target: import("vgpu/scene").Vec3Like, up?: import("vgpu/scene").Vec3Like): this;
  add(...nodes: SceneNode[]): this;
  remove(...nodes: SceneNode[]): this;
  removeFromParent(): this;
  traverse(visit: (node: SceneNode) => void): void;
  get parent(): SceneNode | null;
  get children(): readonly SceneNode[];
  get position(): Float32Array;
  get quaternion(): Float32Array;
  get scale(): Float32Array;
  get localMatrix(): import("vgpu/scene").Mat4;
  get worldMatrix(): import("vgpu/scene").Mat4;
  get worldPosition(): Float32Array;
}
```

## Parameters

| Member                        | Type                                         | Required       | Default                                    | Notes                                                                                                                                                                                          |
| ----------------------------- | -------------------------------------------- | -------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| constructor kind              | `SceneNodeKind`                              | ✔              | —                                          | Only `"group"`. Prefer `group(options)`.                                                                                                                                                       |
| constructor options           | `NodeOptions`                                | ✖              | `{}`                                       | Same as `group(options)`.                                                                                                                                                                      |
| label                         | `string \| undefined`                        | ✖              | `undefined`                                | Writable app metadata. Used in error `where` strings.                                                                                                                                          |
| visible                       | `boolean`                                    | ✖              | `true`                                     | Writable app metadata. Nothing in vgpu reads it: it does not hide the node, skip its matrices, or propagate to children or instances.                                                          |
| set(values)                   | `NodeTransformValues`                        | ✔              | —                                          | Patches the local state: omitted fields keep their current values. Validates the complete candidate state before writing anything.                                                             |
| lookAt(target, up)            | `Vec3Like, Vec3Like`                         | target ✔, up ✖ | up `[0, 1, 0]`                             | Rotates the node so its local -Z axis points at the world-space `target`, with +Y as close to the world-space `up` as possible. Position and scale are unchanged.                              |
| add(...nodes)                 | `SceneNode[]`                                | ✖              | no nodes                                   | Appends children in order. Nodes with another parent are moved; re-adding an existing child moves it to the end. Local transforms are preserved, so world matrices change with the new parent. |
| remove(...nodes)              | `SceneNode[]`                                | ✖              | no nodes                                   | Detaches direct children. Nodes that are not children of this node are ignored. The removed node keeps its local transform and becomes a root.                                                 |
| removeFromParent()            | —                                            | —              | —                                          | Detaches this node from its parent; no-op on a root.                                                                                                                                           |
| traverse(visit)               | `(node: SceneNode) => void`                  | ✔              | —                                          | Depth-first pre-order walk of this node and its descendants, children in insertion order. Iterative, so deep chains do not overflow the stack.                                                 |
| parent / children             | `SceneNode \| null` / `readonly SceneNode[]` | —              | `null` / `[]`                              | Read-only links. Change them only through `add`, `remove` and `removeFromParent`.                                                                                                              |
| position / quaternion / scale | `Float32Array`                               | —              | `[0, 0, 0]` / `[0, 0, 0, 1]` / `[1, 1, 1]` | Local state, stored as float32. The quaternion is always normalized. There is no Euler getter.                                                                                                 |
| localMatrix                   | `Mat4`                                       | —              | identity                                   | `composeMatrix` of the local state, recomputed on read after a change.                                                                                                                         |
| worldMatrix                   | `Mat4`                                       | —              | identity                                   | `parent.worldMatrix × localMatrix`, recomputed on read for this node and any changed ancestors.                                                                                                |
| worldPosition                 | `Float32Array`                               | —              | `[0, 0, 0]`                                | Elements 12, 13, 14 of `worldMatrix`, refreshed on each read.                                                                                                                                  |

**Returns:** `set`, `lookAt`, `add`, `remove` and `removeFromParent` return the same node for chaining; `traverse` returns `undefined`.

**Throws:**

* `VGPU-SCENE-VALUE` from `set()` or the constructor for an invalid field (see `group`), from `lookAt()` when `target` or `up` does not have exactly 3 finite, float32-representable numbers, and from `add()` when an argument is not a `SceneNode` — fix the named field; the node is unchanged.
* `VGPU-SCENE-CYCLE` from `add()` when a node is this node or one of its ancestors — remove the ancestor link or attach a different node. `add()` checks every argument first, so nothing is attached when it throws.
* `VGPU-SPATIAL-SINGULAR` from `lookAt()` when the parent's world matrix cannot be inverted (for example a zero scale on an ancestor) — restore an invertible ancestor transform; the quaternion is unchanged.
* `VGPU-SCENE-VALUE` from reading `worldMatrix` or `worldPosition` when a parent × local product leaves float32 range (for example nested scales of `1e20`) — keep accumulated transforms within float32 range.

## Examples

```ts
import { group } from "vgpu/scene";

const shoulder = group({ label: "shoulder", position: [0, 1.5, 0] });
const elbow = group({ label: "elbow", position: [0, 0, -1] });
shoulder.add(elbow);

const elbowWorld = elbow.worldMatrix; // stable identity
shoulder.set({ rotation: [0, Math.PI / 2, 0] }); // patch: position stays [0, 1.5, 0]
console.log(elbowWorld === elbow.worldMatrix, elbow.worldPosition); // true, ≈ [-1, 1.5, 0]
```

Aim a node at a world-space point, even under a rotated, non-uniformly scaled parent:

```ts
import { group } from "vgpu/scene";

const turret = group({ rotation: [0, 0.6, 0], scale: [2, 1, 0.5] });
const barrel = group({ position: [0, 0.4, 0] });
turret.add(barrel);

barrel.lookAt([5, 0, -3]); // world-space target; the parent transform is compensated
```

Reparent while keeping the local transform:

```ts
import { group } from "vgpu/scene";

const table = group({ position: [4, 0, 0] });
const hand = group({ position: [0, 1, 0] });
const cup = group({ position: [0, 0.8, 0] });
table.add(cup);

hand.add(cup); // cup.position is still [0, 0.8, 0]; its world position now follows hand
console.log(cup.worldPosition); // ≈ [0, 1.8, 0]
```

## Notes

* Borrowed arrays: `position`, `quaternion`, `scale`, `localMatrix`, `worldMatrix` and `worldPosition` return the node's own arrays with a stable identity. They are safe to read or upload, but treat them as read-only — writing to them skips dirty tracking and leaves matrices stale. Change state through `set()` or `lookAt()`.
* Patch vs compose: `node.set({ scale: 2 })` changes only the scale. `composeMatrix({ scale: 2 }, out)` resets position and rotation to defaults.
* `set()` stores `rotation` as a quaternion and normalizes a supplied `quaternion`, so `node.quaternion` can differ from the array you passed. Inputs are stored as float32; `localMatrix` matches `composeMatrix` of the stored `position`, `quaternion` and `scale`.
* `set({ label: undefined })` and `set({ visible: undefined })` keep the current values; assign `node.label = undefined` to clear a label.
* Lazy reads: `set`, `lookAt` and reparenting only mark the node and its descendants dirty. Each `worldMatrix` read walks up to the root and recomputes dirty ancestors, so read it once per frame per node rather than in inner loops.
* `lookAt` aims from the node's own world position. If `target`, rounded to float32, equals `worldPosition`, the quaternion becomes identity after any parent inverse is validated; a singular parent therefore still throws without changing the quaternion. If `up` is parallel to the view direction, a fixed fallback axis keeps the result deterministic.
* Keep-world reparenting is not supported: there is no matrix decomposition and no matrix input on nodes. Recompute the local transform yourself before `add()` if the node must stay in place.
* Mutating the tree from inside a `traverse` callback changes which nodes are visited; collect the nodes first, then mutate.
* **See also:** `group`, `NodeTransformValues`, `composeMatrix`, `localFromWorld`, `evaluateHierarchy`.

***

# NodeOptions

Options for `group()` and the `SceneNode` constructor: every `NodeTransformValues` field plus initial `children`.

## Import

```ts
import type { NodeOptions } from "vgpu/scene";
```

## Signature

```ts
interface NodeOptions {
  position?: ArrayLike<number>;
  rotation?: ArrayLike<number>;
  quaternion?: ArrayLike<number>;
  scale?: number | ArrayLike<number>;
  readonly visible?: boolean;
  readonly label?: string;
  readonly children?: readonly import("vgpu/scene").SceneNode[];
}
```

## Parameters

| Field      | Type                          | Required | Default        | Notes                                                                                     |
| ---------- | ----------------------------- | -------- | -------------- | ----------------------------------------------------------------------------------------- |
| position   | `ArrayLike<number>`           | ✖        | `[0, 0, 0]`    | Exactly 3 finite, float32-representable numbers.                                          |
| rotation   | `ArrayLike<number>`           | ✖        | no rotation    | Intrinsic XYZ Euler radians. Ignored when `quaternion` is present.                        |
| quaternion | `ArrayLike<number>`           | ✖        | `[0, 0, 0, 1]` | XYZW, nonzero length, normalized copy stored.                                             |
| scale      | `number \| ArrayLike<number>` | ✖        | `1`            | Uniform number or 3 per-axis numbers.                                                     |
| visible    | `boolean`                     | ✖        | `true`         | App metadata; not consumed by vgpu.                                                       |
| label      | `string`                      | ✖        | `undefined`    | App metadata and error context.                                                           |
| children   | `readonly SceneNode[]`        | ✖        | `[]`           | Attached in order after validation; existing parents are replaced, local transforms kept. |

**Returns:** Not a callable.

**Throws:** None by itself; `group()` throws `VGPU-SCENE-VALUE` for invalid fields.

## Examples

```ts
import { group, type NodeOptions } from "vgpu/scene";

const rigOptions: NodeOptions = { label: "rig", position: [0, 2, 0], children: [group({ label: "pivot" })] };
const rig = group(rigOptions);
console.log(rig.children.length); // 1
```

## Notes

* The options object and its arrays are copied; mutating them after `group()` has no effect on the node.
* **See also:** `group`, `NodeTransformValues`, `TransformValues`.

***

# NodeTransformValues

Transform and flag values accepted by `SceneNode.set()`. Every field is optional and omitted fields keep the node's current value.

## Import

```ts
import type { NodeTransformValues } from "vgpu/scene";
```

## Signature

```ts
interface NodeTransformValues {
  position?: ArrayLike<number>;
  rotation?: ArrayLike<number>;
  quaternion?: ArrayLike<number>;
  scale?: number | ArrayLike<number>;
  readonly visible?: boolean;
  readonly label?: string;
}
```

## Parameters

| Field      | Type                          | Required | Default          | Notes                                                                                                                     |
| ---------- | ----------------------------- | -------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------- |
| position   | `ArrayLike<number>`           | ✖        | current position | Exactly 3 finite, float32-representable numbers.                                                                          |
| rotation   | `ArrayLike<number>`           | ✖        | current rotation | Exactly 3 finite numbers, intrinsic XYZ Euler radians; replaces the whole rotation. Ignored when `quaternion` is present. |
| quaternion | `ArrayLike<number>`           | ✖        | current rotation | Exactly 4 finite numbers, XYZW, nonzero length; normalized copy stored.                                                   |
| scale      | `number \| ArrayLike<number>` | ✖        | current scale    | Uniform number or 3 per-axis numbers, each finite and float32-representable.                                              |
| visible    | `boolean`                     | ✖        | current value    | App metadata; `undefined` keeps the current value.                                                                        |
| label      | `string`                      | ✖        | current value    | App metadata; `undefined` keeps the current value.                                                                        |

**Returns:** Not a callable.

**Throws:** None by itself; `set()` throws `VGPU-SCENE-VALUE` for invalid fields and then leaves the node unchanged.

## Examples

```ts
import { group } from "vgpu/scene";

const lamp = group({ position: [0, 3, 0], scale: 0.5 });
lamp.set({ rotation: [-Math.PI / 4, 0, 0] }); // position and scale unchanged
lamp.set({ visible: false, label: "lamp" }); // flags only: matrices stay clean
```

## Notes

* A `set()` call that touches only `visible` or `label` does not invalidate any matrix.
* **See also:** `SceneNode`, `TransformValues`, `NodeOptions`.

***

# SceneNodeKind

The kind tag of a `SceneNode`. The only supported kind is `"group"`.

## Import

```ts
import type { SceneNodeKind } from "vgpu/scene";
```

## Signature

```ts
type SceneNodeKind = "group";
```

## Parameters

| Param         | Type      | Required | Default | Notes                                                                         |
| ------------- | --------- | -------- | ------- | ----------------------------------------------------------------------------- |
| SceneNodeKind | `"group"` | ✔        | —       | Nodes are spatial only; there are no mesh, camera, light or scene node kinds. |

**Returns:** Not a callable.

**Throws:** None.

## Examples

```ts
import { group, type SceneNodeKind } from "vgpu/scene";

const kind: SceneNodeKind = group().kind;
console.log(kind); // "group"
```

## Notes

* Use `label` for your own categories; `kind` does not describe what you draw.
* **See also:** `SceneNode`, `group`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: srgb
description: Converts sRGB color literals into linear RGB floats for CPU-side scene constants. Use it when your source color is a web-style hex value or normalized sRGB tuple but your shader math expects linear color.
---

# srgb



## Import

```ts
import { srgb } from "vgpu/scene";
```

## Signature

```ts
type SrgbInput = number | string | [number, number, number];
type LinearRgb = [number, number, number];

declare function srgb(input: SrgbInput): LinearRgb;
```

## Parameters

| Param | Type                                           | Required | Default | Notes                                                                                                                                                                 |
| ----- | ---------------------------------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| input | `number \| string \| [number, number, number]` | ✔        | —       | A packed `0xRRGGBB` number, a `"#rrggbb"` hex string, or a three-channel sRGB tuple. Tuple channels are expected in normalized `0..1` units, not byte `0..255` units. |

**Returns:** `LinearRgb` (`[number, number, number]`) — normalized linear RGB channels. Each channel uses the standard sRGB transfer curve: `channel / 12.92` for `channel <= 0.04045`, otherwise `((channel + 0.055) / 1.055) ** 2.4`.
**Throws:** `VGPU-CORE-INVALID-USAGE` for malformed hex strings; numeric and tuple inputs are not validated.

## Examples

```ts
import { srgb } from "vgpu/scene";

const albedo = srgb(0xff8040);
const sky = srgb("#3b82f6");
console.log(albedo.length, sky.length); // 3 3
```

```ts
import { srgb } from "vgpu/scene";

const normalizedWhite = srgb([1, 1, 1]);
const normalizedGray = srgb([0.5, 0.5, 0.5]);
void normalizedWhite;
void normalizedGray;
```

## Notes

* The numeric form is a packed hexadecimal color (`0xff8040`); the string form accepts `"#rrggbb"` or `"rrggbb"`. Do not call `srgb(255, 128, 64)`; that is not the function signature.
* Tuple input is not clamped. Values outside `0..1`, `NaN`, and `Infinity` flow through JavaScript arithmetic and can produce non-display color values.
* `srgb` is CPU-side only. For texture sampling and post-processing, keep color-management decisions explicit in WGSL.
* **See also:** `degToRad`, `SceneGeometry`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: composeMatrix
description: Writes a complete local transform matrix from position, rotation (Euler or quaternion) and scale into `out`. Use it to fill matrices for flat hierarchy rows, instance worlds, or any shader uniform that needs an object transform without a `SceneNode`.
---

# composeMatrix



## Import

```ts
import { composeMatrix } from "vgpu/scene";
```

## Signature

```ts
declare function composeMatrix(
  values: import("vgpu/scene").TransformValues,
  out: import("vgpu/scene").Mat4,
): import("vgpu/scene").Mat4;
```

## Parameters

| Param             | Type                          | Required | Default        | Notes                                                                                                                                                        |
| ----------------- | ----------------------------- | -------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| values            | `TransformValues`             | ✔        | —              | Complete transform description. Every omitted field resets to its default; `composeMatrix` never reads the previous contents of `out`.                       |
| values.position   | `ArrayLike<number>`           | ✖        | `[0, 0, 0]`    | Exactly 3 finite numbers; written to translation indices 12, 13, 14.                                                                                         |
| values.rotation   | `ArrayLike<number>`           | ✖        | no rotation    | Exactly 3 finite numbers: intrinsic XYZ Euler angles in radians. Ignored — and not validated — when `quaternion` is present.                                 |
| values.quaternion | `ArrayLike<number>`           | ✖        | `[0, 0, 0, 1]` | Exactly 4 finite numbers in XYZW order, nonzero length. Normalized for the calculation; the caller's array is not modified. Wins over `rotation`.            |
| values.scale      | `number \| ArrayLike<number>` | ✖        | `1`            | One finite number for uniform scale, or exactly 3 finite per-axis factors. Zero and negative factors are allowed (the matrix is then singular or reflected). |
| out               | `Mat4`                        | ✔        | —              | `Float32Array` with exactly 16 elements. Fully overwritten on success, untouched on any error.                                                               |

**Returns:** `Mat4` — the same `out` array, so calls can be chained into other matrix functions.

**Throws:**

* `VGPU-SPATIAL-SIZE` when `out` does not have exactly 16 elements — allocate `new Float32Array(16)` or pass an exact 16-element `subarray`.
* `VGPU-SCENE-VALUE` when `position`, `rotation` or vector `scale` does not have exactly 3 elements, `quaternion` does not have exactly 4, any component or scalar `scale` is `NaN`/`Infinity`, the quaternion has zero length, or a result element is outside finite float32 range (about ±3.4e38) — the message names the field and index; pass finite, correctly sized values and a nonzero quaternion.

## Examples

```ts
import { composeMatrix } from "vgpu/scene";

const modelMatrix = new Float32Array(16);
composeMatrix({ position: [0, 1, -4], rotation: [0, Math.PI / 4, 0], scale: 2 }, modelMatrix);

composeMatrix({ position: [0, 1, -4] }, modelMatrix); // complete replacement: rotation and scale reset to identity
```

Write one row of a packed matrix array by passing an exact 16-element view:

```ts
import { composeMatrix } from "vgpu/scene";

const rowCount = 3;
const locals = new Float32Array(rowCount * 16);
for (let row = 0; row < rowCount; row++) {
  composeMatrix({ position: [row * 2, 0, 0] }, locals.subarray(row * 16, row * 16 + 16));
}
```

## Notes

* Conventions: right-handed, +Y up, column-major storage, translation at indices 12, 13, 14, affine bottom row at indices 3, 7, 11, 15 = `0, 0, 0, 1`. The matrix applies scale, then rotation, then translation.
* Complete composition, not a patch: omitted fields take their defaults. To change one component of existing state, keep the other values yourself or use a node's `set()`, which patches.
* Math runs in JavaScript doubles and is rounded to float32 when written. Float32 carries about 7 significant digits: at a distance of `1e7` units, adjacent representable translations are 1 unit apart. There is no large-coordinate precision handling; keep coordinates near the origin.
* Validation and computation finish before the first write, so `out` may share memory with the input arrays.
* **See also:** `TransformValues`, `multiplyMatrices`, `invertAffine`, `SceneNode`, `evaluateHierarchy`.

***

# multiplyMatrices

Writes the column-major product `a × b` into `out`. Use it to combine a parent world with a child local (`world = parentWorld × local`) or a projection with a view; neither argument has to be affine.

## Import

```ts
import { multiplyMatrices } from "vgpu/scene";
```

## Signature

```ts
declare function multiplyMatrices(
  a: ArrayLike<number>,
  b: ArrayLike<number>,
  out: import("vgpu/scene").Mat4,
): import("vgpu/scene").Mat4;
```

## Parameters

| Param | Type                | Required | Default | Notes                                                                                                                 |
| ----- | ------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------- |
| a     | `ArrayLike<number>` | ✔        | —       | Left matrix, exactly 16 finite numbers, column-major.                                                                 |
| b     | `ArrayLike<number>` | ✔        | —       | Right matrix, exactly 16 finite numbers, column-major. Applied to a vector first.                                     |
| out   | `Mat4`              | ✔        | —       | `Float32Array` with exactly 16 elements. May be the same array as `a` or `b`, or a view that partially overlaps them. |

**Returns:** `Mat4` — the same `out` array.

**Throws:**

* `VGPU-SPATIAL-SIZE` when `a`, `b` or `out` does not have exactly 16 elements — the message states the actual length; pass exact 16-element matrices.
* `VGPU-SCENE-VALUE` when an element of `a` or `b` is `NaN`/`Infinity`, or a product element is outside finite float32 range — pass finite matrices whose product fits in float32.

## Examples

```ts
import { composeMatrix, multiplyMatrices } from "vgpu/scene";

const parentWorld = composeMatrix({ position: [0, 2, 0], rotation: [0, Math.PI / 2, 0] }, new Float32Array(16));
const childLocal = composeMatrix({ position: [1, 0, 0] }, new Float32Array(16));

const childWorld = multiplyMatrices(parentWorld, childLocal, new Float32Array(16));
multiplyMatrices(parentWorld, childLocal, childLocal); // in place: childLocal now holds the world matrix
void childWorld;
```

The product is staged before any write, so `out` can alias either input without corrupting the result.

## Notes

* Order matters: `multiplyMatrices(a, b, out)` transforms by `b` first, then `a`. For hierarchies, pass the parent world as `a` and the child local as `b`.
* You do not need a temporary matrix to avoid aliasing; in-place output is supported.
* **See also:** `composeMatrix`, `invertAffine`, `localFromWorld`, `evaluateHierarchy`.

***

# invertAffine

Writes the inverse of an affine matrix into `out`, or throws without touching `out` when no finite float32 inverse exists. Use it to move points from world space into an object's local space.

## Import

```ts
import { invertAffine } from "vgpu/scene";
```

## Signature

```ts
declare function invertAffine(
  matrix: ArrayLike<number>,
  out: import("vgpu/scene").Mat4,
): import("vgpu/scene").Mat4;
```

## Parameters

| Param  | Type                | Required | Default | Notes                                                                                                                                   |
| ------ | ------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| matrix | `ArrayLike<number>` | ✔        | —       | Exactly 16 finite numbers, column-major, affine: indices 3, 7, 11, 15 must be exactly `0, 0, 0, 1`. Shear and reflection are supported. |
| out    | `Mat4`              | ✔        | —       | `Float32Array` with exactly 16 elements. May alias `matrix`. Untouched on any error.                                                    |

**Returns:** `Mat4` — the same `out` array.

**Throws:**

* `VGPU-SPATIAL-SIZE` when `matrix` or `out` does not have exactly 16 elements — pass exact 16-element matrices.
* `VGPU-SCENE-VALUE` when an element of `matrix` is `NaN`/`Infinity`, or the bottom row is not exactly `0, 0, 0, 1` — pass a finite affine matrix; use a general inverse for projections.
* `VGPU-SPATIAL-SINGULAR` when the determinant of the 3×3 linear part is zero or non-finite, or an inverse element is outside finite float32 range — restore an invertible finite affine matrix and use scales whose inverse fits in float32; `out` is left unchanged.

## Examples

```ts
import { composeMatrix, invertAffine } from "vgpu/scene";

const objectWorld = composeMatrix({ position: [3, 0, 0], scale: [2, 1, 1] }, new Float32Array(16));
const worldToObject = invertAffine(objectWorld, new Float32Array(16));
void worldToObject;
```

Recover from a singular matrix instead of rendering with zeros or `NaN`:

```ts
import { composeMatrix, invertAffine } from "vgpu/scene";
import { VGPUError } from "vgpu";

const collapsed = composeMatrix({ scale: [1, 0, 1] }, new Float32Array(16));
const inverse = new Float32Array(16);
try {
  invertAffine(collapsed, inverse);
} catch (error) {
  if (!(error instanceof VGPUError) || error.code !== "VGPU-SPATIAL-SINGULAR") throw error;
  // inverse still holds its previous contents (all zeros here)
}
```

## Notes

* There is no absolute epsilon: any nonzero finite determinant is accepted as long as every inverse element fits in float32. A uniform scale of `1e-20` inverts to about `1e20`; a scale of `1e-39` throws `VGPU-SPATIAL-SINGULAR` because its inverse, `1e39`, exceeds float32 range.
* Near-singular matrices invert with large elements and reduced precision; the function does not warn about conditioning.
* Do not invert a perspective or orthographic projection with `invertAffine`; its bottom row is not `0, 0, 0, 1` and the call throws `VGPU-SCENE-VALUE`.
* **See also:** `localFromWorld`, `multiplyMatrices`, `composeMatrix`.

***

# localFromWorld

Writes the local matrix that reproduces `world` under `parentWorld` — `inverse(parentWorld) × world` — into `out`. Use it when an external system (physics, animation import) supplies final world matrices and you need local rows for a flat hierarchy.

## Import

```ts
import { localFromWorld } from "vgpu/scene";
```

## Signature

```ts
declare function localFromWorld(
  parentWorld: ArrayLike<number>,
  world: ArrayLike<number>,
  out: import("vgpu/scene").Mat4,
): import("vgpu/scene").Mat4;
```

## Parameters

| Param       | Type                | Required | Default | Notes                                                                                                     |
| ----------- | ------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------- |
| parentWorld | `ArrayLike<number>` | ✔        | —       | Parent world matrix: exactly 16 finite numbers, affine (indices 3, 7, 11, 15 = `0, 0, 0, 1`), invertible. |
| world       | `ArrayLike<number>` | ✔        | —       | Desired child world matrix: exactly 16 finite numbers, affine. May contain shear.                         |
| out         | `Mat4`              | ✔        | —       | `Float32Array` with exactly 16 elements. May alias either input. Untouched on any error.                  |

**Returns:** `Mat4` — the same `out` array; `multiplyMatrices(parentWorld, out, result)` reproduces `world` up to float32 rounding.

**Throws:**

* `VGPU-SPATIAL-SIZE` when any argument does not have exactly 16 elements — pass exact 16-element matrices.
* `VGPU-SCENE-VALUE` when an element of `parentWorld` or `world` is `NaN`/`Infinity`, or either bottom row is not exactly `0, 0, 0, 1` — pass finite affine matrices.
* `VGPU-SPATIAL-SINGULAR` when `parentWorld` has a zero or non-finite linear determinant or its inverse is outside finite float32 range — restore an invertible finite affine parent with representable scales; `out` is left unchanged.
* `VGPU-SCENE-VALUE` when an element of the resulting local matrix is outside finite float32 range — use parent/world values whose local product fits in float32; `out` is left unchanged.

## Examples

```ts
import { composeMatrix, localFromWorld, multiplyMatrices } from "vgpu/scene";

const parentWorld = composeMatrix({ position: [0, 1, 0], scale: 2 }, new Float32Array(16));
const physicsWorld = composeMatrix({ position: [4, 1, 0] }, new Float32Array(16)); // from your physics step

const childLocal = localFromWorld(parentWorld, physicsWorld, new Float32Array(16));
const check = multiplyMatrices(parentWorld, childLocal, new Float32Array(16)); // equals physicsWorld
void check;
```

## Notes

* The result is a matrix, not position/rotation/scale: vgpu has no matrix decomposition and nodes cannot take a matrix. Feed the result to matrix consumers such as `evaluateHierarchy` locals rows or instance worlds.
* If the world matrix is already final and nothing inherits from it, skip the hierarchy and use the world matrix directly.
* The inverse and final local matrix are computed in doubles and each is checked against finite float32 range before `out` is written. Cancellation with `world` does not make an unrepresentable parent inverse valid.
* **See also:** `invertAffine`, `multiplyMatrices`, `evaluateHierarchy`.

***

# TransformValues

Position, rotation and scale input shared by `composeMatrix` and node options. Every field is optional; what an omitted field means depends on the consumer.

## Import

```ts
import type { TransformValues } from "vgpu/scene";
```

## Signature

```ts
interface TransformValues {
  position?: ArrayLike<number>;
  rotation?: ArrayLike<number>;
  quaternion?: ArrayLike<number>;
  scale?: number | ArrayLike<number>;
}
```

## Parameters

| Field      | Type                          | Required | Default                                                     | Notes                                                                                                                                               |
| ---------- | ----------------------------- | -------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| position   | `ArrayLike<number>`           | ✖        | `[0, 0, 0]` in `composeMatrix`; current value in `set()`    | Exactly 3 finite numbers.                                                                                                                           |
| rotation   | `ArrayLike<number>`           | ✖        | no rotation in `composeMatrix`; current value in `set()`    | Exactly 3 finite numbers, intrinsic XYZ Euler angles in radians. Converted to a quaternion; ignored and not validated when `quaternion` is present. |
| quaternion | `ArrayLike<number>`           | ✖        | `[0, 0, 0, 1]` in `composeMatrix`; current value in `set()` | Exactly 4 finite numbers, XYZW, nonzero length. Normalized without modifying the input.                                                             |
| scale      | `number \| ArrayLike<number>` | ✖        | `1` in `composeMatrix`; current value in `set()`            | One number for uniform scale or exactly 3 per-axis numbers.                                                                                         |

**Returns:** Not a callable.

**Throws:** None by itself; consumers throw `VGPU-SCENE-VALUE` for invalid fields.

## Examples

```ts
import { composeMatrix, group, type TransformValues } from "vgpu/scene";

const pose: TransformValues = { position: [0, 1, 0], quaternion: [0, 0.7071, 0, 0.7071] };
composeMatrix(pose, new Float32Array(16)); // complete: scale defaults to 1
group().set(pose); // patch: fields you omit keep their current values
```

## Notes

* Tuples, plain arrays and typed arrays all work; values are read once and copied.
* Do not pass both `rotation` and `quaternion` expecting them to combine — `quaternion` wins and `rotation` is ignored.
* **See also:** `composeMatrix`, `NodeTransformValues`, `Vec3Like`, `QuatLike`.

***

# Mat4

A 4×4 matrix stored as a `Float32Array` of exactly 16 elements in column-major order. Every scene matrix output and every node matrix getter uses this type.

## Import

```ts
import type { Mat4 } from "vgpu/scene";
```

## Signature

```ts
type Mat4 = Float32Array;
```

## Parameters

| Param | Type           | Required | Default | Notes                                                                                                                                                 |
| ----- | -------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| Mat4  | `Float32Array` | ✔        | —       | Exactly 16 elements. Column `c`, row `r` lives at index `c * 4 + r`; translation is at 12, 13, 14; an affine matrix has `0, 0, 0, 1` at 3, 7, 11, 15. |

**Returns:** Not a callable.

**Throws:** None by itself; matrix functions throw `VGPU-SPATIAL-SIZE` when a `Mat4` does not have exactly 16 elements.

## Examples

```ts
import { composeMatrix, type Mat4 } from "vgpu/scene";

const identity: Mat4 = new Float32Array([
  1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 1,
]);
composeMatrix({ position: [1, 2, 3] }, identity);
console.log(identity[12], identity[13], identity[14]); // 1 2 3
```

## Notes

* The type alias cannot enforce the length; functions check it at runtime.
* A 16-element `subarray` of a larger `Float32Array` is a valid `Mat4`, which lets you write rows of packed matrix arrays in place.
* **See also:** `composeMatrix`, `multiplyMatrices`, `Vec3Like`.

***

# Vec3Like

Three-component vector input: a tuple, plain array, or typed array with exactly 3 numbers.

## Import

```ts
import type { Vec3Like } from "vgpu/scene";
```

## Signature

```ts
type Vec3Like = ArrayLike<number>;
```

## Parameters

| Param    | Type                | Required | Default | Notes                                                                        |
| -------- | ------------------- | -------- | ------- | ---------------------------------------------------------------------------- |
| Vec3Like | `ArrayLike<number>` | ✔        | —       | Exactly 3 finite numbers at runtime; other lengths throw `VGPU-SCENE-VALUE`. |

**Returns:** Not a callable.

**Throws:** None by itself.

## Examples

```ts
import { group, type Vec3Like } from "vgpu/scene";

const target: Vec3Like = new Float32Array([0, 0, -5]);
group({ position: [0, 2, 0] }).lookAt(target);
```

## Notes

* The type alias cannot enforce the length; consumers check it at runtime and copy the values.
* **See also:** `QuatLike`, `TransformValues`, `Mat4`.

***

# QuatLike

Quaternion input in XYZW order: a tuple, plain array, or typed array with exactly 4 numbers.

## Import

```ts
import type { QuatLike } from "vgpu/scene";
```

## Signature

```ts
type QuatLike = ArrayLike<number>;
```

## Parameters

| Param    | Type                | Required | Default | Notes                                                                                                          |
| -------- | ------------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------- |
| QuatLike | `ArrayLike<number>` | ✔        | —       | Exactly 4 finite numbers, `[x, y, z, w]`, nonzero length. Need not be unit length: consumers normalize a copy. |

**Returns:** Not a callable.

**Throws:** None by itself; consumers throw `VGPU-SCENE-VALUE` for a wrong length, non-finite component, or zero-length quaternion.

## Examples

```ts
import { group, type QuatLike } from "vgpu/scene";

const halfTurnY: QuatLike = [0, 1, 0, 0];
const node = group({ quaternion: halfTurnY });
console.log(node.quaternion); // Float32Array [0, 1, 0, 0]
```

## Notes

* The identity rotation is `[0, 0, 0, 1]`, not `[1, 0, 0, 0]`.
* **See also:** `Vec3Like`, `TransformValues`, `SceneNode`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Vec3
description: A three-component float32 vector. Use this retained type for owned vector storage; functions accepting read-only input usually take the broader `Vec3Like` type.
---

# Vec3



## Import

```ts
import type { Vec3 } from "vgpu/scene";
```

## Signature

```ts illustrative
type Vec3 = Float32Array;
```

## Parameters

| Field    | Type     | Required | Default | Notes                                                                                                           |
| -------- | -------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| elements | `number` | ✔        | —       | Three components in X, Y, Z order. The type alone cannot enforce length; scene functions validate their inputs. |

**Returns:** Not callable; a type alias for vector storage.
**Throws:** None; consuming functions perform validation.

## Examples

```ts
import type { Vec3 } from "vgpu/scene";

const position: Vec3 = new Float32Array([1, 2, 3]);
console.log(position[0]);
```

## Notes

* Float32 storage loses precision at large coordinates. Keep application coordinates near the origin or rebase them explicitly.
* A node's borrowed vector getters remain read-only by contract even though `Float32Array` is mutable. Use node `.set()` for local changes.
* **See also:** `Vec3Like`, `Pose`, `SceneNode`, `Mat4`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: tslExports
description: Creates callable three.js TSL functions from selected direct exports of a resolved WGSL module. Use it to reuse pure WGSL libraries in Three node materials while Three retains ownership of shader stages and bindings.
---

# tslExports



## Import

```ts
import { tslExports } from "vgpu/three";
```

`three` is an optional peer of `vgpu`. Importing other `vgpu` entry points does not load Three.

## Signature

```ts
import type { ShaderFunctionExport } from "vgpu";
import type { Node } from "three/webgpu";
import type { ShaderNodeObject } from "three/tsl";

type TslExportsSource = string | {
  readonly wgsl: string;
  readonly functionExports?: readonly ShaderFunctionExport[];
};

type TslInputs = Readonly<Record<string, Node | number>>;
type DefaultTslContract = Readonly<Record<string, TslInputs>>;
type TslContractShape<Contract> = Readonly<{
  [Name in keyof Contract]: TslInputs;
}>;
type TslFunctions<Contract extends TslContractShape<Contract>> = {
  readonly [Name in keyof Contract]: (
    inputs: Contract[Name],
  ) => ShaderNodeObject<Node>;
};
type SelectedTslFunctions<
  Contract extends TslContractShape<Contract>,
  Names extends readonly (keyof Contract & string)[],
> = number extends Names["length"]
  ? Partial<Pick<TslFunctions<Contract>, Names[number]>>
  : Names extends readonly []
    ? Pick<TslFunctions<Contract>, never>
    : Names extends readonly [
        infer Name extends keyof Contract & string,
        ...infer Rest extends readonly (keyof Contract & string)[],
      ]
      ? Name extends keyof Contract
        ? Pick<TslFunctions<Contract>, Name>
          & SelectedTslFunctions<Contract, Rest>
        : never
      : never;

declare function tslExports<
  Contract extends TslContractShape<Contract> = DefaultTslContract,
>(
  source: TslExportsSource,
): <const Names extends readonly (keyof Contract & string)[]>(
  ...names: Names
) => SelectedTslFunctions<Contract, Names>;
```

`TslExportsSource` describes the accepted shape; it is not a separately exported adapter type. Both a loader-emitted `ShaderSource` and the complete result of `resolveShader()` satisfy the object form.

## Parameters

| Param                    | Type                                                |             Required | Default            | Notes                                                                                                                                                                                                                                                                                           |
| ------------------------ | --------------------------------------------------- | -------------------: | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source`                 | `{ wgsl, functionExports? } \| string`              |                    ✔ | —                  | Prefer the complete loader or resolver artifact. A raw string is a compatibility path for non-minified hand-written or legacy WGSL.                                                                                                                                                             |
| `source.wgsl`            | `string`                                            |    ✔ for object form | —                  | Final ordinary WGSL passed to one shared Three `wgsl()` include.                                                                                                                                                                                                                                |
| `source.functionExports` | `readonly ShaderFunctionExport[]`                   | ✖ for legacy objects | absent             | Authoritative direct-export identity. New vgpu artifacts always emit this property, including `[]`.                                                                                                                                                                                             |
| `...names`               | positional `string` arguments                       |                    ✔ | —                  | Authored names of direct, surviving `export fn` declarations. Each literal argument becomes a key of the returned object. Spread an `as const` tuple when names are already grouped. A union-valued name returns a union of its possible result objects; a widened array returns optional keys. |
| `Contract`               | `{ exportName: { parameterName: Node \| number } }` |                    ✖ | broad named inputs | Optional manual TypeScript contract. Its keys restrict the selector; each value types that export's input object. A reusable contract may contain exports not selected by a particular call.                                                                                                    |

**Returns:** A selector function that accepts authored export names as positional strings. Calling the selector returns a readonly object with one callable Three TSL node for each requested name. Every callable takes one named-input object whose keys match the authored WGSL parameter names and whose values are Three nodes or numbers.

**Throws:** `VGPU-THREE-TSL-EXPORT-NOT-FOUND` when no authoritative direct export matches; `VGPU-THREE-TSL-EXPORT-AMBIGUOUS` when multiple exports match; `VGPU-THREE-TSL-SIGNATURE-UNSUPPORTED` for a void or non-forwardable function, or when the module contains a global `enable`, `requires`, or `diagnostic` directive; `VGPU-THREE-TSL-SOURCE-INVALID` when metadata and emitted WGSL disagree, the final declaration is malformed, or source uses the private adapter namespace. Errors thrown by Three are not wrapped.

## TslExportsErrorCode

Type-only union of the stable codes thrown by `tslExports()`:

```ts
import type { TslExportsErrorCode } from "vgpu/three";

declare const code: TslExportsErrorCode;
void code;
```

Use this type when a helper accepts or exhaustively handles adapter error codes. It does not export an adapter-specific error class; catch values still begin as `unknown` and should be narrowed before reading `.code`.

## Example

```ts
import type { Node } from "three/webgpu";
import { float, positionLocal } from "three/tsl";
import { tslExports } from "vgpu/three";
import surfaceModule from "./surface.wgsl";

type SurfaceExports = {
  surfaceColor: {
    position: Node;
    timeSeconds: Node | number;
  };
};

const { surfaceColor } = tslExports<SurfaceExports>(surfaceModule)(
  "surfaceColor",
);

const colorNode = surfaceColor({
  position: positionLocal,
  timeSeconds: float(2),
});
```

Identifier minification is fully supported when you pass the complete imported object. The resolver records each authored export name, its authored parameter names, and the corresponding declaration name in the minified WGSL; `tslExports()` uses those references to build the callable.

## Manual TypeScript contract

The default contract infers the returned property names but accepts any named `Node | number` inputs. For application code, prefer the manual contract shown above. An explicit contract constrains each positional name to a contract key, returns only the selected keys, and types each callable's input object from the corresponding contract value. Omitting `timeSeconds` from the example's `surfaceColor()` call, for instance, becomes a type error.

The contract is a compile-time assertion maintained by the application; it is not generated from or compared with the WGSL. It may describe a complete module while each selector call requests only the exports it needs. TypeScript rejects a selected name outside the contract and does not expose unselected contract keys, but cannot prove that a contract name exists in the shader. At runtime, the shader artifact remains authoritative for export identity and authored parameter names. Three's `Node` type is not branded by WGSL value type, so the manually chosen value types do not prove `f32` versus `vec3f` compatibility.

Literal positional names and spread `as const` tuples produce exact required properties. A name typed as `"surfaceColor" | "surfaceRoughness"` produces a union of the two possible result objects, which you can narrow with `"surfaceColor" in selected`. If you spread a widened `(keyof Contract)[]`, the selected names are not knowable at compile time, so the corresponding result properties are optional.

## Notes

* One `tslExports(source)` call creates one shared `wgsl()` include. Each selector invocation creates one `wgslFn()` forwarding wrapper for every requested export.
* The presence of `functionExports` is authoritative. An empty array exposes nothing, even if the WGSL contains private functions whose names happen to match.
* New loader and resolver artifacts always carry `functionExports`, even when it is empty. Only raw strings and legacy artifacts without that property use the text-scanning fallback; those inputs must retain their original identifiers and do not provide a reliable export boundary.
* Only direct function declarations are exports. Import aliases and private helpers do not become callable adapter exports.
* Duplicate authored names are retained in generic WGSL metadata so the adapter can report ambiguity instead of silently choosing one.
* Export metadata keeps authored `parameterNames` in declaration order and uses `resolvedName` for the exact declaration identifier in the final WGSL.
* The `_vgpu_three_` top-level declaration namespace is reserved for private forwarding functions. Source that declares a name in that namespace fails with `VGPU-THREE-TSL-SOURCE-INVALID`.
* Functions must be pure, have no shader-stage attribute, receive values through parameters, and return a value.
* Global `enable`, `requires`, and `diagnostic` directives are unsupported because Three emits `wgsl()` includes after its own global declarations. An `@diagnostic(...)` attribute is not a module directive and is not rejected by this check; the adapter's other signature constraints still apply.
* Without a manual `Contract`, TypeScript infers requested export keys but not WGSL parameter names or WGSL value and return types.
* Match thrown values by `.code`; import `TslExportsErrorCode` when you need the stable code union. The adapter does not export an error class.
* **See also:** [Use WGSL modules in three.js TSL](/docs/guides/threejs), [Three.js WGSL modules](/examples/tsl-exports), `ShaderSource`, and `resolveShader`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Instance geometry
description: Publish fixed-capacity instance collections as vertex streams for application-owned geometry and shaders.
---

# Instance geometry



# instanceGeometry

Publishes an instance collection from `instances()` as an instanced vertex stream on top of a base mesh, and returns a composed `Geometry` for `draw(gpu, { geometry })`. Use it to draw a whole collection — crates, trees, particles — with one instanced draw call and your own WGSL.

## Import

```ts
import { instanceGeometry } from "vgpu/scene/gpu";
```

## Signature

```ts
declare function instanceGeometry<A extends import("vgpu/scene").InstanceAttributes>(
  gpu: import("vgpu").Gpu,
  collection: import("vgpu/scene").InstanceCollection<A>,
  options: { mesh: import("vgpu").Geometry },
): import("vgpu/scene/gpu").InstanceGeometry;
```

## Parameters

| Param        | Type                    | Required | Default | Notes                                                                                                                                                                                      |
| ------------ | ----------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| gpu          | `Gpu`                   | ✔        | —       | The live `gpu` from `init()`. The bridge's buffer and composed geometry belong to it.                                                                                                      |
| collection   | `InstanceCollection<A>` | ✔        | —       | A collection created by `instances()`. Its `capacity` and attribute schema fix the size and layout of the instance buffer for the bridge's lifetime.                                       |
| options.mesh | `Geometry`              | ✔        | —       | The base mesh, for example `geometry(gpu, box())`. Must be live, created from the same `gpu`, and have no instance-step vertex buffer of its own. Borrowed, never destroyed by the bridge. |

**Returns:** `InstanceGeometry` — a bridge whose `geometry` holds the base mesh's vertex streams and index buffer plus one instance stream sized for the full `capacity`. Nothing is uploaded from the collection until the first `publish()`.

**Throws:** every check below runs before the bridge allocates any GPU resource.

* `VGPU-GPU-DISPOSED` / `VGPU-GPU-FOREIGN` when `gpu` is disposed or is not a `gpu` from `init()` — pass the live `gpu`.
* `TypeError` ("Expected an instance collection created by instances().") when `collection` was not created by `instances()` — pass the collection itself, not a copy or a plain object.
* `VGPU-INSTANCE-LAYOUT` when `options.mesh` is missing, is not a `Geometry` (for a `GeometrySlice`, pass `slice.geometry`), belongs to a different `gpu`, or is already destroyed — create a live base mesh with the same `gpu`.
* `VGPU-INSTANCE-LAYOUT` when `options.mesh` already has an instance-step vertex buffer — use a vertex-only base mesh; the bridge appends the single instance stream.
* `VGPU-INSTANCE-LAYOUT` when a base attribute name equals `world0`–`world3` or one of your attribute names; the message names the attribute — rename it on the base mesh or in the collection schema so every shader input has one source.
* `VGPU-INSTANCE-LAYOUT` when the composed geometry needs more vertex buffers than `min(8, maxVertexBuffers)`, more vertex attributes than `maxVertexAttributes`, an instance stride above `min(2048, maxVertexBufferArrayStride)` bytes, or a buffer (`capacity × stride`, at least 4 bytes) above `maxBufferSize`; the message prints the actual and permitted numbers — drop base or custom attributes, narrow attribute formats, lower `capacity`, or split the population across several collections and bridges.
* `VGPU-INSTANCE-LAYOUT` when the CPU copy of the initial zero-filled buffer contents cannot be allocated; the message prints the byte count — lower `capacity` or the attribute width.
* A failure while creating the instance buffer or composing the geometry propagates unchanged. The bridge destroys only the buffer it just created; the base mesh stays usable.

## Examples

Publish once and draw once. The shader declares every vertex input the composed geometry provides, including `kind`, which it does not use, and the draw passes the count from `publish()`:

```wgsl
// crates.wgsl
struct CameraData { viewProjection: mat4x4f }
@group(0) @binding(0) var<uniform> camera: CameraData; // group and binding are your choice

struct VertexIn {
  @location(0) position: vec3f, // box() mesh
  @location(1) normal: vec3f,   // box() mesh
  @location(3) world0: vec4f,   // instance stream: world matrix columns
  @location(4) world1: vec4f,
  @location(5) world2: vec4f,
  @location(6) world3: vec4f,
  @location(7) tint: vec3f,     // "tint": "float32x3"
  @location(8) kind: u32,       // "kind": "uint32" — unused, but must be declared
}

struct VertexOut {
  @builtin(position) clip: vec4f,
  @location(0) normal: vec3f,
  @location(1) tint: vec3f,
}

@vertex fn vs_main(input: VertexIn) -> VertexOut {
  let world = mat4x4f(input.world0, input.world1, input.world2, input.world3);
  var out: VertexOut;
  out.clip = camera.viewProjection * world * vec4f(input.position, 1.0);
  out.normal = (world * vec4f(input.normal, 0.0)).xyz;
  out.tint = input.tint;
  return out;
}

@fragment fn fs_main(input: VertexOut) -> @location(0) vec4f {
  let light = max(dot(normalize(input.normal), normalize(vec3f(0.4, 1.0, 0.3))), 0.0);
  return vec4f(input.tint * (0.2 + 0.8 * light), 1.0);
}
```

```ts
import { draw, frame, geometry, init, surface } from "vgpu";
import { box, instances } from "vgpu/scene";
import { instanceGeometry } from "vgpu/scene/gpu";
import crateShader from "./crates.wgsl";

const gpu = await init();
const canvasSurface = surface(gpu, document.querySelector("canvas")!);
const viewProjection = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); // from your camera

// ---cut---
const crates = instances({ capacity: 256, attributes: { tint: "float32x3", kind: "uint32" } });
const firstCrate = crates.add({ tint: [0.9, 0.5, 0.1], kind: 0 });
const secondCrate = crates.add({ tint: [0.2, 0.6, 0.9], kind: 1 });
crates.setWorld(firstCrate, [0.4, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0.4, 0, -0.5, 0, 0, 1]);
crates.setWorld(secondCrate, [0.4, 0, 0, 0, 0, 0.4, 0, 0, 0, 0, 0.4, 0, 0.5, 0, 0, 1]);

const crateMesh = geometry(gpu, box()); // yours: the bridge borrows it
const crateBridge = instanceGeometry(gpu, crates, { mesh: crateMesh });
const crateDraw = draw(gpu, { shader: crateShader, geometry: crateBridge.geometry });

const crateCount = crateBridge.publish(); // uploads both records, returns 2
crateDraw.set({ camera: { viewProjection } });

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: canvasSurface, clear: [0.05, 0.05, 0.08, 1] }, (pass) => {
    pass.draw(crateDraw, { instances: crateCount }); // the count reaches the GPU only here
  });
});
```

`box()` pins `position` to `@location(0)` and `normal` to `@location(1)`; the instance inputs start at `@location(3)` so they also stay clear of `uv` at `@location(2)` on recipes that have one. The world columns and custom attributes match by name, so their locations are free as long as they do not collide.

Every frame follows the same order: update your state, write the worlds, compute the camera, publish, set uniforms, then encode every pass. `frameLoop(gpu)` submits when the callback returns:

```ts
import { clock, draw, frameLoop, geometry, init, surface, target } from "vgpu";
import { box, instances, type InstanceId } from "vgpu/scene";
import { instanceGeometry } from "vgpu/scene/gpu";
import crateShader from "./crates.wgsl";

declare function stepSimulation(deltaTime: number, worldRows: Float32Array): void; // your physics or ECS
declare function writeViewProjection(out: Float32Array): void; // your camera

const gpu = await init();
const canvasSurface = surface(gpu, document.querySelector("canvas")!);
const minimapTarget = target(gpu, { size: [256, 256] });
const crates = instances({ capacity: 1024, attributes: { tint: "float32x3", kind: "uint32" } });
const crateIds: InstanceId[] = [];
for (let index = 0; index < 64; index++) crateIds.push(crates.add({ tint: [0.8, 0.6, 0.3], kind: index % 3 }));
const worldRows = new Float32Array(crateIds.length * 16); // one 16-float world row per crate
const crateBridge = instanceGeometry(gpu, crates, { mesh: geometry(gpu, box()) });
const crateDraw = draw(gpu, { shader: crateShader, geometry: crateBridge.geometry });
const viewProjection = new Float32Array(16);
const frameClock = clock(gpu);

// ---cut---
const loop = frameLoop(gpu, (currentFrame) => {
  stepSimulation(frameClock.deltaTime, worldRows); // 1–2. app update, evaluate worlds
  crates.setWorlds(crateIds, worldRows);           // 3. copy worlds (or syncWorlds() for bindWorld sources)
  writeViewProjection(viewProjection);             // 4. camera matrices
  const crateCount = crateBridge.publish();        // 5. publish once per frame
  crateDraw.set({ camera: { viewProjection } });   // 6. named uniforms

  // 7. every pass that reads this bridge sees the same publication
  currentFrame.pass({ target: canvasSurface, clear: [0.05, 0.05, 0.08, 1] }, (pass) => {
    pass.draw(crateDraw, { instances: crateCount });
  });
  currentFrame.pass({ target: minimapTarget, clear: [0, 0, 0, 1] }, (pass) => {
    pass.draw(crateDraw, { instances: crateCount });
  });
}); // 8. submit when the callback returns

// call loop.stop() when your component unmounts
```

A render bundle records the count it was given. Record a new bundle when `publish()` returns a different count; changed row contents need no new bundle, because replay reads the same instance buffer. Record the next bundle first, swap it in, then dispose the old one, so a recording that throws leaves the previous bundle in place:

```ts
import { bundle, draw, frameLoop, geometry, init, surface, type Bundle } from "vgpu";
import { box, instances } from "vgpu/scene";
import { instanceGeometry } from "vgpu/scene/gpu";
import crateShader from "./crates.wgsl";

declare function moveCrates(collection: typeof crates): void; // your per-frame world updates

const gpu = await init();
const canvasSurface = surface(gpu, document.querySelector("canvas")!);
const crates = instances({ capacity: 1024, attributes: { tint: "float32x3", kind: "uint32" } });
const crateBridge = instanceGeometry(gpu, crates, { mesh: geometry(gpu, box()) });
const crateDraw = draw(gpu, { shader: crateShader, geometry: crateBridge.geometry });
crateDraw.set({ camera: { viewProjection: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]) } });

// ---cut---
let crateBundle: Bundle | undefined;
let recordedCount = -1;

function recordCrates(count: number): Bundle {
  return bundle(gpu, { target: canvasSurface, label: "crates" }, (recorder) => { // reads the surface's configuration, no canvas texture
    recorder.draw(crateDraw, { instances: count }); // the count is frozen into the bundle
  });
}

const loop = frameLoop(gpu, (currentFrame) => {
  moveCrates(crates); // adds, removes and moves change rows; adds and removes change the count
  const crateCount = crateBridge.publish();
  if (crateCount !== recordedCount) {
    const nextBundle = recordCrates(crateCount); // if this throws, crateBundle is untouched
    const previousBundle = crateBundle;
    crateBundle = nextBundle;
    recordedCount = crateCount;
    previousBundle?.dispose(); // release the old count's bundle now
  }
  currentFrame.pass({ target: canvasSurface, clear: [0.05, 0.05, 0.08, 1] }, (pass) => {
    pass.bundles(crateBundle!);
  });
});

function teardown(): void { // call it when your component unmounts
  loop.stop();
  crateBundle?.dispose(); // the draw, bridge and base mesh stay usable
  crateBridge.destroy();
}
```

Recording against `canvasSurface` reads only its configured render signature, so it does not depend on the frame's canvas texture, works inside or outside a frame, and keeps replaying when the canvas resizes. Dropping a replaced bundle also lets it be collected eventually; `dispose()` releases it at that point instead. Disposing a bundle never destroys `crateDraw`, the bridge or the base mesh.

## Notes

* **Instance layout.** One vertex buffer with `stepMode: "instance"`, `capacity × stride` bytes, allocated once and zero-filled. Each record is the collection's record: `world0`, `world1`, `world2`, `world3` as `float32x4` at byte offsets 0, 16, 32 and 48 (the column-major world matrix), then your attributes in declaration order at 4-byte alignment. The stride is `64 + 4 × (total custom components)`: `tint: "float32x3"` plus `kind: "uint32"` gives 80 bytes. There is no growth: to raise `capacity`, create a new collection and a new bridge.
* **Formats.** Custom attributes use the 12 `InstanceFormat` values: `float32`, `sint32` and `uint32` scalars and `x2`/`x3`/`x4` vectors, read in WGSL as `f32`/`vecNf`, `i32`/`vecNi` and `u32`/`vecNu`. There are no 8- or 16-bit or normalized formats.
* **The world matrix costs four attributes.** Each world column is its own vertex attribute, so the bridge adds `4 + (number of custom attributes)` to the base mesh's attribute count, and 64 bytes to every record. At the WebGPU default of 16 `maxVertexAttributes`, a `box()` base (2 attributes) leaves room for 10 custom attributes and a `sphere()` base (3 attributes) for 9. A custom attribute costs one vertex attribute whatever its width, so a `float32x4` is cheaper in attributes than four `float32`s.
* **Composed geometry.** `bridge.geometry` keeps every base attribute's name, format, offset and explicit location, and the base topology, index buffer, index format, index count and vertex count. Its `instanceCount` is `0`, and it adds no bindings: the instance data reaches your shader only as the vertex inputs you declare. There is no shader injection, no storage-buffer variant and no reserved bind group — `@group(0) @binding(0)` in the examples is the shader author's choice.
* **Declare every name-matched input.** Instance attributes carry no explicit location, so all of them — `world0..world3` and each custom attribute — are matched by name and must be declared in every shader drawn with `bridge.geometry`, including depth-only or picking shaders that ignore them; a missing one throws `VGPU-MESH-ATTRIBUTE-UNMATCHED` when the draw is created. The same applies to named base attributes without a location. Recipe attributes (`position` at 0, `normal` at 1, `uv` at 2) have explicit locations and may still be omitted, as with any geometry, but their locations stay taken: two inputs on one location throw `VGPU-MESH-LOCATION-CONFLICT`, an input the geometry does not provide throws `VGPU-MESH-INPUT-MISSING`, and a type that does not match the format throws `VGPU-MESH-FORMAT-MISMATCH`.
* **The shared shader input layout** for a `box()` bridge over `{ tint: "float32x3", kind: "uint32" }` is: `position: vec3f` and `normal: vec3f` from the base, then `world0: vec4f`, `world1: vec4f`, `world2: vec4f`, `world3: vec4f`, `tint: vec3f`, `kind: u32` from the instance stream. Declare the complete list in every shader that shares the bridge so all consumers read the same stream layout.
* **The draw count is explicit.** Pass the value from `publish()` as `instances` on every `pass.draw()`, `drawable.draw()` or `recorder.draw()`. `0` is valid and draws nothing. Omitting `instances` falls back to the composed geometry's `instanceCount` of `0`, so the draw silently renders nothing. vgpu does not compare a caller-supplied `instances` count with the collection's `count` or `capacity`. Pass exactly the value `publish()` returned: any other count can address inactive or out-of-capacity instance indices, and the result is not defined by vgpu.
* **Bundles capture the count.** A bundle freezes the `instances` value it was recorded with and the buffer it reads, not the row contents. Record a new one whenever the count from `publish()` changes — record next, swap, then `dispose()` the old bundle — and dispose the current one on teardown; rows published later are what replay reads.
* **Frame order.** `app update → evaluate/read worlds → syncWorlds or setWorlds → camera matrices → publish → named uniform set → encode all passes → submit`. `publish()` never calls bound sources, evaluates nodes or hierarchies, or touches the camera, so everything before it must already be in the collection.
* **One publication per frame per bridge.** `publish()` writes through the device queue, and a queue write lands before the next submit — before every pass of the frame being encoded, including passes encoded before the call. Do not publish a bridge again while passes that read it are still unsubmitted: the second write replaces what those passes read. Later frames are ordered by the queue, so publishing at the start of the next frame needs no wait for the GPU to go idle. If two passes in one frame need different instance contents, use separate bridges or separate collections — a second bridge mirrors the collection as of its own last `publish()`.
* **What `publish()` costs.** Each call scans slots `0..count-1` for changes since this bridge's last successful publication — O(`count`) even when nothing changed — then copies each contiguous run of changed records out of the collection and writes it to the buffer. The first `publish()` writes every active record; a `publish()` with no changes in between writes 0 bytes; a swap-remove writes the moved record; removing the last slot writes nothing and only lowers the returned count. A collection with `capacity: 0` still gets a minimal 4-byte buffer; its `publish()` returns `0` and writes nothing.
* **Independent mirrors.** Each bridge has its own buffer and its own change cursor. Two bridges over one collection — a detailed mesh and a low-poly proxy — each see every change, and publishing one never consumes the other's pending changes.
* **When `publish()` throws.** The bridge's cursor and returned count stay where they were, so nothing is lost: fix the cause and the next `publish()` writes every change still pending. Records written before the failure stay written and are written again. The write is not part of the frame's command buffer, so a frame that throws after `publish()` does not undo it; the uncaught error ends a `frameLoop(gpu)`.
* **When a world source throws.** `syncWorlds()` throwing `VGPU-INSTANCE-SOURCE` leaves some worlds at this frame's values and others at the previous frame's, and there is no rollback. `publish()` uploads whatever the records hold, so recover before you publish: let the error end the frame, fix or `unbindWorld` the failing source, call `syncWorlds()` again, then `publish()`. The same applies to any synchronous failure in your own update or world-writing code.
* **Ownership.** The bridge owns its instance buffer and the composed `bridge.geometry` wrapper; the base mesh stays yours. The bridge borrows the base's vertex buffers and index buffer, never destroys them, and sees later writes to them. Destroying the bridge leaves the base mesh usable.
* **Lifetimes.** `bridge.destroy()` and `bridge.geometry.destroy()` share one destroyed state, and both are idempotent. `gpu.dispose()` destroys the bridge too. Once the bridge, its geometry or the base mesh is destroyed, `publish()`, creating or encoding a draw with `bridge.geometry` (direct, indexed, indirect or zero-instance), recording it into a bundle, and replaying a bundle that contains it all throw `VGPU-INSTANCE-DESTROYED` — also for draws compiled before the destruction. Replaying a bundle you already disposed throws `VGPU-BUNDLE-DISPOSED` instead. Destroying the base mesh does not free the bridge's instance buffer; call `bridge.destroy()` to release it. vgpu detects destruction through `Geometry.destroy()` only; destroying a raw `GPUBuffer` behind vgpu's back is not detected.
* **Anti-pattern:** `pass.draw(crateDraw)` without `instances` renders nothing. Always pass `{ instances: crateCount }`, where `crateCount` is the value this frame's `publish()` returned.
* **Anti-pattern:** calling `publish()` between two passes of one frame to show each pass different rows. Both passes see the second publication; use two bridges.
* **See also:** `InstanceGeometry`, `instances`, `InstanceCollection`, `geometry`, `draw`, `bundle`, `frame`, `frameLoop`, `instanceWorldMatrix` and `transformNormal` from `@vgpu/wgsl-std/scene`, [Scene composition](/docs/guides/scene-composition).

***

# InstanceGeometry

The bridge returned by `instanceGeometry()`: a composed `Geometry` to draw with, a `publish()` that uploads pending collection changes and returns the count to draw, and a `destroy()` that releases the instance buffer.

## Import

```ts
import type { InstanceGeometry } from "vgpu/scene/gpu";
```

## Signature

```ts
interface InstanceGeometry {
  readonly geometry: import("vgpu").Geometry;
  publish(): number;
  destroy(): void;
}
```

## Parameters

| Member    | Type       | Required | Default              | Notes                                                                                                                                                                                                                                                                      |
| --------- | ---------- | -------- | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| geometry  | `Geometry` | —        | composed at creation | Read-only. The base mesh's streams and index buffer plus the instance stream; `instanceCount` is `0`. Pass it as `draw(gpu, { geometry })` and always draw with an explicit `instances`. Destroying it destroys the bridge.                                                |
| publish() | —          | —        | —                    | Writes the collection's records changed since this bridge's last successful publication to the instance buffer, then returns the collection's current `count`. Never calls bound sources. Call it once per frame, after the worlds are written and before encoding passes. |
| destroy() | —          | —        | —                    | Destroys the instance buffer and the composed geometry. Idempotent. Does not destroy the base mesh.                                                                                                                                                                        |

**Returns:** `publish()` returns the number of live instances to pass as `instances` — `0` when the collection is empty. `destroy()` returns `undefined`.

**Throws:**

* `VGPU-INSTANCE-DESTROYED` from `publish()` after `destroy()`, `geometry.destroy()`, `gpu.dispose()` or destruction of the base mesh; also from creating, encoding, recording or replaying a draw that uses `geometry` after any of those — create a new bridge from a live base mesh, then recreate the affected draws and re-record the affected bundles. Disposing an affected bundle does not throw; it only releases the bundle.
* `VGPU-INSTANCE-REENTRANT` from `publish()` when a bound world source calls it during `syncWorlds()` — keep sources read-only and publish after `syncWorlds()` returns. `syncWorlds()` rethrows this error unwrapped.
* Errors from writing the instance buffer propagate unchanged; the bridge's cursor does not advance, so the next `publish()` retries every pending change.
* Collection errors (`VGPU-INSTANCE-SOURCE`, `VGPU-INSTANCE-VALUE`, `VGPU-INSTANCE-CAPACITY` and the rest) come from the collection methods that caused them, never from `publish()`, and keep their original code, path and fix — see `InstanceCollection`.

## Examples

Tear down in any order; the base mesh outlives the bridge:

```ts
import { geometry, init } from "vgpu";
import { box, instances } from "vgpu/scene";
import { instanceGeometry } from "vgpu/scene/gpu";

const gpu = await init();

// ---cut---
const crateMesh = geometry(gpu, box());
const crates = instances({ capacity: 64 });
const crateBridge = instanceGeometry(gpu, crates, { mesh: crateMesh });

crates.add();
console.log(crateBridge.publish()); // 1

crateBridge.destroy(); // frees the instance buffer; crateMesh is still usable
crateBridge.destroy(); // no-op
// crateBridge.publish() would now throw VGPU-INSTANCE-DESTROYED

const proxyBridge = instanceGeometry(gpu, crates, { mesh: crateMesh }); // a fresh bridge on the same mesh
console.log(proxyBridge.publish()); // 1 — a new bridge uploads every active record
```

A collection without custom attributes still needs `world0..world3` declared in the shader.

## Notes

* `publish()` is the only way data moves from the collection to the GPU. Mutating the collection after `publish()` changes nothing on the GPU until the next `publish()`.
* Keep the base mesh alive while the bridge is in use; destroying it invalidates the bridge without freeing the bridge's buffer.
* **See also:** `instanceGeometry`, `instances`, `InstanceCollection`, `Geometry`, `bundle`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: @vgpu/wgsl-std/color
description: Pure WGSL color utilities for shaders resolved by `@vgpu/wgsl`. Import these functions from WGSL modules when you need sRGB transfer, luminance, exposure, tone mapping, or bloom threshold helpers without declaring any resources.
---

# @vgpu/wgsl-std/color



## Import

```wgsl
import { applyExposure, luminance, luminanceThreshold, tonemapAces, tonemapReinhard } from "@vgpu/wgsl-std/color";
```

## Signature

```wgsl
export fn luminance(value: vec3f) -> f32;
export fn applyExposure(value: vec3f, exposure: f32) -> vec3f;
export fn srgbToLinear(value: f32) -> f32;
export fn srgbToLinear3(value: vec3f) -> vec3f;
export fn srgbToLinear4(value: vec4f) -> vec4f;
export fn linearToSrgb(value: f32) -> f32;
export fn linearToSrgb3(value: vec3f) -> vec3f;
export fn linearToSrgb4(value: vec4f) -> vec4f;
export fn tonemapAces(value: vec3f) -> vec3f;
export fn tonemapReinhard(value: vec3f) -> vec3f;
export fn luminanceThreshold(value: vec3f, threshold: f32, softKnee: f32) -> vec3f;
```

## Parameters

| Param     | Type    | Required | Default | Notes                                                                                                                                                              |
| --------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| value     | `f32`   | ✔        | —       | Scalar color channel for `srgbToLinear` or `linearToSrgb`. Expected range is usually `[0.0, 1.0]`; helpers do not clamp scalar transfer inputs.                    |
| value     | `vec3f` | ✔        | —       | RGB/linear-HDR color for `luminance`, `applyExposure`, `tonemap*`, `luminanceThreshold`, `srgbToLinear3`, and `linearToSrgb3`.                                     |
| value     | `vec4f` | ✔        | —       | RGBA color for `srgbToLinear4` and `linearToSrgb4`; RGB is converted and alpha is preserved unchanged.                                                             |
| exposure  | `f32`   | ✔        | —       | Exposure in stops/EV for `applyExposure`; `1.0` doubles, `0.0` leaves unchanged, `-2.0` multiplies by `0.25`.                                                      |
| threshold | `f32`   | ✔        | —       | Linear luminance threshold for `luminanceThreshold`.                                                                                                               |
| softKnee  | `f32`   | ✔        | —       | Width of bright-pass transition. Internally clamped with `max(softKnee, 0.000001)`, so `0.0` behaves as an extremely hard edge without invalid `smoothstep` edges. |

**Returns:** WGSL functions return `f32`, `vec3f`, or `vec4f` as declared. Transfer helpers return converted color, `luminance` returns Rec.709/sRGB relative luminance, exposure/tonemap/threshold helpers return linear color values.

**Throws:** These WGSL declarations do not throw. `resolveShader()` can still throw `VGPU-WGSL-SYM-NOEXPORT` for misspelled imports, `VGPU-WGSL-PKG-NOTFOUND` if the package import cannot be resolved, or validation errors such as `VGPU-WGSL-NAGA-UNKNOWN` if caller WGSL is invalid.

## Examples

```ts
const shaderWgsl = `
import { applyExposure, linearToSrgb3, srgbToLinear3, tonemapAces } from "@vgpu/wgsl-std/color";

fn grade(baseColorSrgb: vec3f, exposureStops: f32) -> vec3f {
  let linear = srgbToLinear3(baseColorSrgb);
  let exposed = applyExposure(linear, exposureStops);
  return linearToSrgb3(tonemapAces(exposed));
}
`;

console.log(shaderWgsl.includes("tonemapAces"));
```

```ts
const bloomWgsl = `
import { luminanceThreshold } from "@vgpu/wgsl-std/color";

fn bloomExtract(hdrColor: vec3f) -> vec3f {
  return luminanceThreshold(hdrColor, 1.0, 0.25);
}
`;

console.log(bloomWgsl.length > 0);
```

## Notes

* This module is pure WGSL: it declares no `@group`, no `@binding`, no overrides, no hidden state, and no entry points. It is safe to import into resolver graphs.
* `luminance` uses `dot(value, vec3f(0.2126, 0.7152, 0.0722))`; pass linear-light colors, not encoded sRGB.
* `tonemapAces` implements the Narkowicz ACES fit and clamps to `[0.0, 1.0]`; `tonemapReinhard` uses `value / (1.0 + luminance(value))` and does not explicitly clamp.
* sRGB transfer helpers implement the standard piecewise formulas and do not clamp. Clamp explicitly if your target requires saturated display-range values.
* This module intentionally does not include PBR, BRDF, Fresnel, IBL, Hable/Filament tone mappers, or a default display pipeline.
* **See also:** `@vgpu/wgsl-std/hash`, `@vgpu/wgsl-std/noise`, `resolveShader`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: @vgpu/wgsl-std/fullscreen
description: Pure WGSL fullscreen-triangle helpers for resolver-managed shaders. Import them when a vertex shader should draw a full-screen pass with three vertices and no vertex buffer.
---

# @vgpu/wgsl-std/fullscreen



## Import

```wgsl
import { fullscreenTriangleClip, fullscreenTriangleUv } from "@vgpu/wgsl-std/fullscreen";
```

## Signature

```wgsl
export fn fullscreenTriangleClip(index: u32) -> vec4f;
export fn fullscreenTriangleUv(clipXy: vec2f) -> vec2f;
```

## Parameters

| Param  | Type    | Required | Default | Notes                                                                                                                                                                   |
| ------ | ------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| index  | `u32`   | ✔        | —       | Vertex index for `fullscreenTriangleClip`. Use `@builtin(vertex_index)` and draw exactly 3 vertices. Values `0`, `1`, and `2` map to the oversized fullscreen triangle. |
| clipXy | `vec2f` | ✔        | —       | Clip-space XY position, normally `fullscreenTriangleClip(index).xy`, for UV conversion with a render-target-friendly Y flip.                                            |

**Returns:** `fullscreenTriangleClip` returns clip-space `vec4f`; `fullscreenTriangleUv` returns `vec2f` UVs where clip-space top-left `(-1.0, 1.0)` maps to `(0.0, 0.0)`.

**Throws:** These WGSL declarations do not throw. `resolveShader()` can still throw `VGPU-WGSL-SYM-NOEXPORT` for misspelled imports, `VGPU-WGSL-PKG-NOTFOUND` if the package import cannot be resolved, or validation errors such as `VGPU-WGSL-NAGA-UNKNOWN` if caller WGSL is invalid.

## Examples

```ts
const fullscreenVertexWgsl = `
import { fullscreenTriangleClip, fullscreenTriangleUv } from "@vgpu/wgsl-std/fullscreen";

struct VertexOutput {
  @builtin(position) position: vec4f,
  @location(0) uv: vec2f,
}

@vertex
fn vs_main(@builtin(vertex_index) index: u32) -> VertexOutput {
  var out: VertexOutput;
  out.position = fullscreenTriangleClip(index);
  out.uv = fullscreenTriangleUv(out.position.xy);
  return out;
}
`;

console.log(fullscreenVertexWgsl.includes("vs_main"));
```

```ts
const postProcessWgsl = `
import { fullscreenTriangleClip } from "@vgpu/wgsl-std/fullscreen";

@vertex
fn vs_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4f {
  return fullscreenTriangleClip(index);
}
`;

console.log(postProcessWgsl.length > 0);
```

## Notes

* This module is pure WGSL: it declares no `@group`, no `@binding`, no overrides, no hidden state, and no entry points.
* Clip outputs are `0 -> (-1, -3)`, `1 -> (-1, 1)`, `2 -> (3, 1)`, covering the viewport as one oversized triangle.
* `fullscreenTriangleUv` applies `clipXy * vec2f(0.5, -0.5) + vec2f(0.5)`, matching top-left texture coordinate convention for fullscreen passes.
* The helpers do not choose varying locations, fragment outputs, bind groups, or samplers; those remain in your entry shader.
* **See also:** `@vgpu/wgsl-std/color`, `resolveShader`, `wgslVitePlugin`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: @vgpu/wgsl-std/hash
description: Pure WGSL hash utilities for deterministic shader randomness. Import them for integer hashing, multi-output PCG-style lattice hashes, and stable conversion from `u32` hashes to unit floats.
---

# @vgpu/wgsl-std/hash



## Import

```wgsl
import { hash1, hash2, hash3, hashU32, pcg2d, pcg3d, unitFloat } from "@vgpu/wgsl-std/hash";
```

## Signature

```wgsl
export fn hashU32(value: u32) -> u32;
export fn pcg2d(value: vec2u) -> vec2u;
export fn pcg3d(value: vec3u) -> vec3u;
export fn unitFloat(hash: u32) -> f32;
export fn hash1(seed: f32) -> f32;
export fn hash2(seed: vec2f) -> vec2f;
export fn hash3(seed: vec3f) -> vec3f;
```

## Parameters

| Param | Type    | Required | Default | Notes                                                                                                    |
| ----- | ------- | -------- | ------- | -------------------------------------------------------------------------------------------------------- |
| value | `u32`   | ✔        | —       | Input integer for `hashU32`, implemented with Wellons lowbias32 constants.                               |
| value | `vec2u` | ✔        | —       | Two-dimensional unsigned seed for `pcg2d`; returns two decorrelated unsigned outputs.                    |
| value | `vec3u` | ✔        | —       | Three-dimensional unsigned seed for `pcg3d`; returns three decorrelated unsigned outputs.                |
| hash  | `u32`   | ✔        | —       | Hash bits passed to `unitFloat`. The low 8 bits are discarded, then the top 24 bits map to `[0.0, 1.0)`. |
| seed  | `f32`   | ✔        | —       | Float seed for `hash1`; bitcast to `u32` before hashing. `-0.0` and `0.0` hash differently.              |
| seed  | `vec2f` | ✔        | —       | Float vector seed for `hash2`; bitcast to `vec2u`, hashed with `pcg2d`, converted with `unitFloat`.      |
| seed  | `vec3f` | ✔        | —       | Float vector seed for `hash3`; bitcast to `vec3u`, hashed with `pcg3d`, converted with `unitFloat`.      |

**Returns:** `hashU32` returns `u32`; `pcg2d`/`pcg3d` return unsigned vectors; `unitFloat` and `hash1` return `f32` in `[0.0, 1.0)`; `hash2`/`hash3` return float vectors with each component in `[0.0, 1.0)`.

**Throws:** These WGSL declarations do not throw. `resolveShader()` can still throw `VGPU-WGSL-SYM-NOEXPORT` for misspelled imports, `VGPU-WGSL-PKG-NOTFOUND` if the package import cannot be resolved, or validation errors such as `VGPU-WGSL-NAGA-UNKNOWN` if caller WGSL is invalid.

## Examples

```ts
const hashWgsl = `
import { pcg3d, unitFloat } from "@vgpu/wgsl-std/hash";

fn cellRandom(cell: vec3i) -> f32 {
  return unitFloat(pcg3d(bitcast<vec3u>(cell)).x);
}
`;

console.log(hashWgsl.includes("cellRandom"));
```

```ts
const jitterWgsl = `
import { hash2 } from "@vgpu/wgsl-std/hash";

fn jitter(pixel: vec2f) -> vec2f {
  return hash2(pixel) - vec2f(0.5);
}
`;

console.log(jitterWgsl.length > 0);
```

## Notes

* This module is pure WGSL: it declares no `@group`, no `@binding`, no overrides, no hidden state, and no entry points.
* `hashU32` is Wellons lowbias32, not PCG. `pcg2d` and `pcg3d` are multi-output PCG-style vector hashes for lattice coordinates.
* `unitFloat(hash)` computes `f32(hash >> 8u) * (1.0 / 16777216.0)`, so it never returns `1.0`.
* Float wrappers hash raw IEEE bit patterns. Normalize NaNs and signed zero yourself if those values should collide.
* For lattice noise, prefer integer cell coordinates (`vec*i` bitcast to `vec*u`) over sine/fract-style float hashes.
* **See also:** `@vgpu/wgsl-std/noise`, `@vgpu/wgsl-std/color`, `resolveShader`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: @vgpu/wgsl-std/noise
description: Pure WGSL Voronoi noise primitives for resolver-managed shaders. Import these when you need nearest and second-nearest jittered feature-cell distances without adding bindings or policy-specific styling. For smooth, non-cellular fields and fBM, use @vgpu/wgsl-std/noise/perlin or @vgpu/wgsl-std/noise/simplex instead.
---

# @vgpu/wgsl-std/noise



> **Want fBM, clouds, terrain, fog or plasma? You are on the wrong page.** This module is Voronoi
> (cellular) noise and ships **no fBM helper** — do not hand-roll octaves on top of it. Use
> `@vgpu/wgsl-std/noise/perlin` (`fbmPerlin2d`/`fbmPerlin3d`) or `@vgpu/wgsl-std/noise/simplex`
> (`fbmSimplex2d`/`fbmSimplex3d`): separate subpaths, amplitude-normalized, guaranteed `(-1, 1)`.
> `npx vgpu docs cat /@vgpu/wgsl-std/noise/perlin/index.docs.md`. Stay here only for cells, edges
> (`f2 - f1`) and per-cell IDs (`cell`).

## Import

```wgsl
import { VoronoiSample2, VoronoiSample3, voronoi2d, voronoi3d } from "@vgpu/wgsl-std/noise";
```

## Signature

```wgsl
export struct VoronoiSample2 {
  f1: f32,
  f2: f32,
  cell: vec2i,
}

export struct VoronoiSample3 {
  f1: f32,
  f2: f32,
  cell: vec3i,
}

export fn voronoi2d(position: vec2f) -> VoronoiSample2;
export fn voronoi3d(position: vec3f) -> VoronoiSample3;
```

## Parameters

| Param    | Type    | Required | Default | Notes                                                                                                     |
| -------- | ------- | -------- | ------- | --------------------------------------------------------------------------------------------------------- |
| position | `vec2f` | ✔        | —       | 2D sample position for `voronoi2d`. The function searches the `3 x 3` cells around `floor(position)`.     |
| position | `vec3f` | ✔        | —       | 3D sample position for `voronoi3d`. The function searches the `3 x 3 x 3` cells around `floor(position)`. |

`VoronoiSample2` fields:

| Param | Type    | Required | Default | Notes                                                                                                       |
| ----- | ------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------- |
| f1    | `f32`   | ✔        | —       | Euclidean distance to the nearest jittered feature point.                                                   |
| f2    | `f32`   | ✔        | —       | Euclidean distance to the second-nearest jittered feature point. `f1 <= f2`.                                |
| cell  | `vec2i` | ✔        | —       | Integer lattice cell containing the nearest feature point. Use it for stable per-cell randomization or IDs. |

`VoronoiSample3` fields:

| Param | Type    | Required | Default | Notes                                                                                                       |
| ----- | ------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------- |
| f1    | `f32`   | ✔        | —       | Euclidean distance to the nearest jittered feature point.                                                   |
| f2    | `f32`   | ✔        | —       | Euclidean distance to the second-nearest jittered feature point. `f1 <= f2`.                                |
| cell  | `vec3i` | ✔        | —       | Integer lattice cell containing the nearest feature point. Use it for stable per-cell randomization or IDs. |

**Returns:** `voronoi2d` returns `VoronoiSample2`; `voronoi3d` returns `VoronoiSample3`. The returned sample contains nearest distance `f1`, second-nearest distance `f2`, and the winning feature cell.

**Throws:** These WGSL declarations do not throw. `resolveShader()` can still throw `VGPU-WGSL-SYM-NOEXPORT` for misspelled imports, `VGPU-WGSL-PKG-NOTFOUND` if the package import cannot be resolved, or validation errors such as `VGPU-WGSL-NAGA-UNKNOWN` if caller WGSL is invalid. Because this module imports `@vgpu/wgsl-std/hash`, package resolution must also be able to resolve that package export.

## Examples

```ts
const voronoiWgsl = `
import { voronoi2d } from "@vgpu/wgsl-std/noise";

fn edgeMask(position: vec2f) -> f32 {
  let sample = voronoi2d(position);
  return sample.f2 - sample.f1;
}
`;

console.log(voronoiWgsl.includes("edgeMask"));
```

```ts
const styledVoronoiWgsl = `
import { pcg3d, unitFloat } from "@vgpu/wgsl-std/hash";
import { voronoi3d } from "@vgpu/wgsl-std/noise";

fn animatedCell(position: vec2f, time: f32) -> f32 {
  let sample = voronoi3d(vec3f(position, time));
  return unitFloat(pcg3d(bitcast<vec3u>(sample.cell)).x);
}
`;

console.log(styledVoronoiWgsl.length > 0);
```

```ts
const cloudWgsl = `
import { voronoi3d } from "@vgpu/wgsl-std/noise";

// Prefer fbmPerlin3d/fbmSimplex3d for this look; only stack Voronoi octaves when
// you want the cellular structure to survive. Voronoi has no built-in fBM helper,
// so build the octaves yourself ("@vgpu/wgsl-std/noise/perlin" and
// "@vgpu/wgsl-std/noise/simplex" ship their own amplitude-normalized
// fbmPerlin*/fbmSimplex* instead).
fn cloudFbm(position: vec3f) -> f32 {
  var value = 0.0;
  var amplitude = 0.5;
  var frequency = 1.0;
  for (var octave = 0u; octave < 4u; octave = octave + 1u) {
    let sample = voronoi3d(position * frequency);
    value = value + amplitude * (1.0 - sample.f1);
    frequency = frequency * 2.03;
    amplitude = amplitude * 0.5;
  }
  return value;
}

// Animate by feeding time as the third dimension, and soften the cell edges by
// warping the domain with a lower-frequency sample before the octave loop.
fn clouds(uv: vec2f, time: f32) -> f32 {
  let warp = voronoi3d(vec3f(uv * 0.5, time * 0.1)).f1;
  return cloudFbm(vec3f(uv + vec2f(warp), time * 0.2));
}
`;

console.log(cloudWgsl.includes("cloudFbm"));
```

## Notes

* This module is pure WGSL: it declares no `@group`, no `@binding`, no overrides, no hidden state, and no entry points. It imports only pure hash helpers.
* `@vgpu/wgsl-std` is a dependency of the `vgpu` package, so `import ... from "@vgpu/wgsl-std/noise";` resolves in any project that installed `vgpu` — no separate install. A `VGPU-WGSL-PKG-NOTFOUND` for this package means it is genuinely absent from `node_modules`.
* **This module is Voronoi (cellular) noise only** — it looks like cells, not smooth clouds. For a cloud/plasma/fog look built purely from Voronoi, sum octaves of `1.0 - sample.f1` and warp the domain, as the third example above shows; for an animated version pass time as the `vec3f` Z coordinate. For a smooth, non-cellular gradient noise, use `@vgpu/wgsl-std/noise/perlin` (`perlin2d`/`perlin3d`) or `@vgpu/wgsl-std/noise/simplex` (`simplex2d`/`simplex3d`) instead — both ship their own amplitude-normalized `fbmPerlin*`/`fbmSimplex*` and are separate subpaths so importing this module never pulls them in. Validate the result with pixels (`npx vgpu check`, then a headless render), not by eye.
* Each lattice cell owns one fully jittered feature point in `[0.0, 1.0)^n`, generated by `pcg2d` or `pcg3d` and converted with `unitFloat`.
* The module returns geometric data only. It does not choose colors, edge widths, jitter strength, smoothing curves, animation, or material policy.
* Use `sample.cell` for stable per-cell styling; use `sample.f2 - sample.f1` for Voronoi edge distance patterns.
* **See also:** `@vgpu/wgsl-std/hash`, `@vgpu/wgsl-std/color`, `resolveShader`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: @vgpu/wgsl-std/noise/perlin
description: Improved Perlin gradient noise (2D/3D) plus amplitude-normalized fBM, for clouds, terrain, water and plasma. Smooth, band-limited, and **guaranteed to stay inside `(-1, 1)`** — unlike the widespread `2.2 *` normalization, nothing here ever needs clamping. Import this when you want a smooth field; import `@vgpu/wgsl-std/noise` (Voronoi) when you want cells.
---

# @vgpu/wgsl-std/noise/perlin



## Import

```wgsl
import { fbmPerlin2d, fbmPerlin3d, perlin2d, perlin3d } from "@vgpu/wgsl-std/noise/perlin";
```

## Signature

```wgsl
export fn perlin2d(position: vec2f) -> f32;
export fn perlin3d(position: vec3f) -> f32;
export fn fbmPerlin2d(position: vec2f, octaves: i32, lacunarity: f32, gain: f32) -> f32;
export fn fbmPerlin3d(position: vec3f, octaves: i32, lacunarity: f32, gain: f32) -> f32;
```

## Parameters

| Param      | Type              | Required | Default | Notes                                                                                                                                                                                                                                       |
| ---------- | ----------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| position   | `vec2f` / `vec3f` | ✔        | —       | Sample position in noise space. One unit is one lattice cell, so scale the input to choose the feature size (`perlin3d(worldPosition * 0.35)`). There is no seed parameter — offset `position` instead (see Notes).                         |
| octaves    | `i32`             | ✔        | —       | Number of fBM octaves. **Silently clamped to `[1, 16]`**: `0` and negatives behave as `1`, values above `16` as `16`. The clamp bounds shader cost and keeps a garbage value (from a uniform, say) from hanging the GPU.                    |
| lacunarity | `f32`             | ✔        | —       | Frequency multiplier per octave; `2.0` is the usual choice. Not clamped. Irrational-ish values (`2.17`) hide the lattice better than exact powers of two. Effective coordinate of the last octave is `position * lacunarity^(octaves - 1)`. |
| gain       | `f32`             | ✔        | —       | Amplitude multiplier per octave; `0.5` is the usual choice. **Silently clamped to `[0, 1]`**, because a negative gain would break the range proof. `gain = 0` reduces fBM to a single octave.                                               |

**Returns:** `f32` in the open interval `(-1, 1)` for every finite input, for all four functions. This is a proof, not an observation: the quintic blend is a convex combination of the corner gradient dot products, and each normalizer is strictly below `1 / sup`. fBM divides by the sum of its amplitudes, so `|sum| <= weight` keeps the same bound across octaves.

Measured over 1e6 random samples (`packages/wgsl-std/tests/perlin.test.ts` pins these):

| fn         | max \|value\|          | typical σ | max slope | corners hashed |
| ---------- | ---------------------- | --------- | --------- | -------------- |
| `perlin2d` | 0.9937 (bound 0.99996) | 0.305     | ≈2.74     | 4 × `pcg2d`    |
| `perlin3d` | 0.9560 (bound 0.99956) | 0.260     | ≈2.45     | 8 × `pcg3d`    |

`perlin2d` and `perlin3d` are **exactly `0.0` at every integer lattice point** (`perlin3d(vec3f(3.0, -1.0, 8.0)) == 0.0`). That is inherent to gradient noise, not a bug: if your field looks like a zero grid, you are sampling integers — offset by a fraction of a cell.

**Throws:** These WGSL declarations do not throw. `resolveShader()` can still throw `VGPU-WGSL-SYM-NOEXPORT` for a misspelled import (note this module is `@vgpu/wgsl-std/noise/perlin`, *not* `@vgpu/wgsl-std/noise`), `VGPU-WGSL-PKG-NOTFOUND` if the package cannot be resolved, or validation errors such as `VGPU-WGSL-NAGA-UNKNOWN` if caller WGSL is invalid. This module also reaches `@vgpu/wgsl-std/hash`, so that package export must resolve too.

## Examples

```ts
const remapWgsl = `
import { perlin3d } from "@vgpu/wgsl-std/noise/perlin";
import { remap, saturate } from "@vgpu/wgsl-std/math";

// The field is (-1, 1) with sigma ~= 0.26, so remap the band you actually care
// about instead of saturating: saturate() would throw away half the signal and
// flatten everything above 1.0 that the field never reaches anyway.
fn fogDensity(worldPosition: vec3f, time: f32) -> f32 {
  let field = perlin3d(worldPosition * 0.35 + vec3f(0.0, 0.0, time * 0.15));
  return saturate(remap(-0.4, 0.6, 0.0, 1.0, field));
}
`;

console.log(remapWgsl.includes("fogDensity"));
```

```ts
const cloudsWgsl = `
import { fbmPerlin3d } from "@vgpu/wgsl-std/noise/perlin";
import { remap, saturate } from "@vgpu/wgsl-std/math";

// Animated clouds: FBM over a domain-warped field.
// Offsets are >= 2 units apart so the three warp components are decorrelated.
fn cloudCoverage(position: vec3f, time: f32) -> f32 {
  let drift = vec3f(position.xy + vec2f(time * 0.02, 0.0), position.z + time * 0.05);

  // Domain warp: displace the sample point with a low-frequency field.
  let warp = vec3f(
    fbmPerlin3d(drift, 3, 2.0, 0.5),
    fbmPerlin3d(drift + vec3f(37.2, 11.7, 5.3), 3, 2.0, 0.5),
    fbmPerlin3d(drift + vec3f(-19.4, 42.1, 23.8), 3, 2.0, 0.5),
  );

  // Detail octaves on the warped domain, then shape coverage.
  let field = fbmPerlin3d(drift + warp * 0.45, 5, 2.0, 0.5);
  let coverage = saturate(remap(-0.15, 0.65, 0.0, 1.0, field));
  return coverage * coverage * (3.0 - 2.0 * coverage);
}
`;

console.log(cloudsWgsl.includes("cloudCoverage"));
```

```ts
const shapingWgsl = `
import { perlin3d } from "@vgpu/wgsl-std/noise/perlin";

// Turbulence (billowy): sum |noise| per octave -> [0, 1).
// Must be per-octave; abs(fbmPerlin3d(...)) is NOT the same thing.
fn turbulence3d(position: vec3f, octaves: i32) -> f32 {
  var sum = 0.0; var amplitude = 1.0; var weight = 0.0; var sample = position;
  for (var i = 0; i < octaves; i = i + 1) {
    sum = sum + amplitude * abs(perlin3d(sample));
    weight = weight + amplitude;
    sample = sample * 2.0;
    amplitude = amplitude * 0.5;
  }
  return sum / weight;
}

// Ridged (terrain): replace abs(n) with (1.0 - abs(n)) squared, per octave.
fn ridged3d(position: vec3f, octaves: i32) -> f32 {
  var sum = 0.0; var amplitude = 1.0; var weight = 0.0; var sample = position;
  for (var i = 0; i < octaves; i = i + 1) {
    let ridge = 1.0 - abs(perlin3d(sample));
    sum = sum + amplitude * ridge * ridge;
    weight = weight + amplitude;
    sample = sample * 2.0;
    amplitude = amplitude * 0.5;
  }
  return sum / weight;
}

// Normals: finite differences on the final field are adequate; analytic
// derivatives are not part of this release.
`;

console.log(shapingWgsl.includes("turbulence3d"));
```

## Notes

* **Range and shaping.** Output is `(-1, 1)`, never clipped, but `σ ≈ 0.305` (2D) / `0.260` (3D) means extremes are rare: over 1e6 samples the largest magnitudes seen were 0.9937 and 0.9560. Use `remap` from `@vgpu/wgsl-std/math` to stretch the band you care about; reaching for `saturate` alone discards the entire negative half of the field.
* **Zero on the lattice.** `perlin2d`/`perlin3d` return exactly `0.0` at integer coordinates. Sample at cell fractions, and remember that `fbmPerlin*` inherits this at octave 1 only (later octaves land off-lattice).
* **Seeding is an input offset — there is no `seed` argument.** Measured Pearson correlation of `perlin3d(p)` against `perlin3d(p + offset)` over 2e5 samples:

  | offset         | correlation |
  | -------------- | ----------- |
  | `(0.5, 0, 0)`  | 0.400       |
  | `(1, 0, 0)`    | −0.043      |
  | `(2, 0, 0)`    | 0.0017      |
  | `(17, 0, 0)`   | −0.0004     |
  | `(101, 53, 7)` | 0.0035      |

  So **any offset of ≥ 2.0 units on some axis decorrelates**; sub-cell offsets do not (`+0.5` still correlates at 0.40). Keep offsets in the tens–thousands, not 1e6, because of the f32 mantissa.
* **Period and f32 domain.** The gradient hash covers 2³² cells, so there is no visible tiling (compare the period-289 float `permute` hashes found in GLSL ports). The practical limit is f32 precision, not the period: `position - floor(position)` is quantized to \~2⁻²⁴·|p|, so detail bands visibly past `|p| ≈ 1e4` and vanishes entirely at `|p| ≥ 2²³` (the field is then exactly 0, because every sample lands on a lattice point). fBM multiplies the effective coordinate by `lacunarity^(octaves - 1)` — 6 octaves at `lacunarity = 2.0` reaches 32× your input.
* **Animating with time.** Feeding an unbounded `time` into the third axis works, but it walks the coordinate toward the f32 limit above, so a long-running session eventually looks blocky. Wrap or scale time (`time * 0.05`, reset periodically), or animate a 2D field's offset instead.
* **Cost model.** `perlin2d` = 4 `pcg2d` hashes, `perlin3d` = 8 `pcg3d` hashes. A 6-octave `fbmPerlin3d` is 48 hashes per sample, and the domain-warped clouds recipe above is ≈4× that (three warp calls plus the detail call). Prefer `fbmPerlin2d` when the third axis only carries animation, and measure before shipping a fullscreen 6-octave 3D field.
* **Determinism.** Gradient selection goes through the integer `pcg2d`/`pcg3d` hashes and the arithmetic uses no `sin`/`cos`/`sqrt`/`inverseSqrt`/`pow`, whose accuracy is implementation-defined. Which gradient a cell gets is therefore bit-identical on every backend; only the final interpolation may differ by a few ulp. The test suite compares real GPU output against an f32-exact CPU reference at 1e-5.
* **Purity.** This module declares no `@group`, no `@binding`, no overrides, no entry points and no hidden state. It imports pure hash helpers plus a private gradient core shared with the simplex module.
* **Credit.** Algorithmic reference: Ken Perlin, *Improving Noise* (SIGGRAPH 2002) — quintic fade and the 12 cube-edge gradient set. No code was copied from any implementation; the gradients are re-derived on this package's own `pcg2d`/`pcg3d` hashes.
* **See also:** `@vgpu/wgsl-std/noise/simplex` (same shape, \~2.5× the slope and \~1.7× the σ at the same input scale — scale `position` by \~0.4–0.5 when migrating, and it hashes 4 corners instead of 8 in 3D), `@vgpu/wgsl-std/noise` (Voronoi/cellular, for cells rather than smooth fields), `@vgpu/wgsl-std/math` (`remap`, `saturate`), `@vgpu/wgsl-std/hash`, `resolveShader`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: @vgpu/wgsl-std/scene
description: Pure WGSL transform helpers for instanced and scene-composed vertex shaders. Import them when a vertex shader receives a world matrix — as four per-instance columns from [`instanceGeometry()`](/reference/vgpu-scene-gpu/instance-geometry) or from your own data — and needs world-space positions, directions, and normals without declaring any resources.
---

# @vgpu/wgsl-std/scene



## Import

```wgsl
import { instanceWorldMatrix, transformDirection, transformNormal, transformPosition } from "@vgpu/wgsl-std/scene";
```

## Signature

```wgsl
export fn instanceWorldMatrix(world0: vec4f, world1: vec4f, world2: vec4f, world3: vec4f) -> mat4x4f;
export fn transformPosition(world: mat4x4f, position: vec3f) -> vec3f;
export fn transformDirection(world: mat4x4f, direction: vec3f) -> vec3f;
export fn transformNormal(world: mat4x4f, normal: vec3f) -> vec3f;
```

## Parameters

| Param     | Type      | Required | Default | Notes                                                                                                                                                                       |
| --------- | --------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| world0    | `vec4f`   | ✔        | —       | Column 0 of the world matrix for `instanceWorldMatrix` (matrix elements 0–3, the transformed X axis). `instanceGeometry()` supplies it as the `world0` instance attribute.  |
| world1    | `vec4f`   | ✔        | —       | Column 1 (elements 4–7, the transformed Y axis). Supplied as the `world1` instance attribute.                                                                               |
| world2    | `vec4f`   | ✔        | —       | Column 2 (elements 8–11, the transformed Z axis). Supplied as the `world2` instance attribute.                                                                              |
| world3    | `vec4f`   | ✔        | —       | Column 3 (elements 12–15): translation in `xyz`, `1.0` in `w` for an affine matrix. Supplied as the `world3` instance attribute.                                            |
| world     | `mat4x4f` | ✔        | —       | Column-major world matrix for `transformPosition`, `transformDirection`, and `transformNormal`. Only finite affine matrices (bottom row `0, 0, 0, 1`) have defined results. |
| position  | `vec3f`   | ✔        | —       | Local-space point for `transformPosition`. Transformed with `w = 1.0`, so translation applies.                                                                              |
| direction | `vec3f`   | ✔        | —       | Local-space direction for `transformDirection`, for example a tangent. Transformed with `w = 0.0`, so translation is ignored. Any length, including zero.                   |
| normal    | `vec3f`   | ✔        | —       | Local-space surface normal for `transformNormal`. Any nonzero length; the result is normalized. A zero vector returns `vec3f(0.0)`.                                         |

**Returns:**

### instanceWorldMatrix

Returns `mat4x4f(world0, world1, world2, world3)` — the four arguments become the matrix columns, in order.

### transformPosition

Returns `(world * vec4f(position, 1.0)).xyz`, the world-space point.

### transformDirection

Returns `(world * vec4f(direction, 0.0)).xyz`, the world-space direction. It is **not** normalized: scale and shear in `world` change its length.

### transformNormal

Returns the normalized inverse-transpose of the upper-left 3×3 linear part of `world` applied to `normal`, with the determinant sign preserved. For well-conditioned finite inputs, a nonzero `normal` and a nonsingular linear part produce a unit-length `vec3f`. An exact-zero guard returns `vec3f(0.0)` when the supplied `f32` arithmetic detects a zero normal, zero linear magnitude, zero computed determinant, or zero cofactor result.

**Throws:** These WGSL declarations do not throw and raise no `VGPU-*` errors at runtime. `resolveShader()` or the WGSL loader can still throw `VGPU-WGSL-SYM-NOEXPORT` for misspelled imports, `VGPU-WGSL-PKG-NOTFOUND` if the package import cannot be resolved, or validation errors such as `VGPU-WGSL-NAGA-UNKNOWN` if caller WGSL is invalid.

## Examples

Transform a point, a tangent, and a normal by a world matrix you already have:

```ts
const transformWgsl = `
import { transformDirection, transformNormal, transformPosition } from "@vgpu/wgsl-std/scene";

struct WorldVertex {
  position: vec3f,
  tangent: vec3f,
  normal: vec3f,
}

fn toWorld(world: mat4x4f, position: vec3f, tangent: vec3f, normal: vec3f) -> WorldVertex {
  return WorldVertex(
    transformPosition(world, position),
    normalize(transformDirection(world, tangent)), // normalize yourself when you need unit length
    transformNormal(world, normal), // already unit length, or vec3f(0.0)
  );
}
`;

console.log(transformWgsl.includes("toWorld"));
```

### Instanced vertex shader with an explicit camera uniform

A complete vertex input for a mesh drawn through `instanceGeometry()`. The base mesh contributes `position`, `normal`, and `uv`; the bridge contributes the four world columns `world0`–`world3` plus each custom attribute declared on the collection — here a `tint` attribute declared as `"float32x4"`. Declare every attribute the geometry provides, even ones the shader does not use. vgpu matches named attributes to vertex inputs by name; attributes that carry an explicit location — the primitive recipes such as `sphere()` pin `position`, `normal`, and `uv` to `@location(0)`, `@location(1)`, and `@location(2)` — must keep that location. The world columns and custom attributes can use any other unique locations.

```wgsl
// instanced-scene.wgsl
import { instanceWorldMatrix, transformNormal, transformPosition } from "@vgpu/wgsl-std/scene";

struct CameraData {
  viewProjection: mat4x4f,
}

// Owned by this entry shader: you choose the group and binding, vgpu reflects the name `camera`.
@group(1) @binding(0) var<uniform> camera: CameraData;

struct VertexInput {
  @location(0) position: vec3f, // base mesh
  @location(1) normal: vec3f, // base mesh
  @location(2) uv: vec2f, // base mesh, declared even though only passed through
  @location(3) world0: vec4f, // instance world column 0
  @location(4) world1: vec4f, // instance world column 1
  @location(5) world2: vec4f, // instance world column 2
  @location(6) world3: vec4f, // instance world column 3 (translation)
  @location(7) tint: vec4f, // custom instance attribute
}

struct VertexOutput {
  @builtin(position) clip: vec4f,
  @location(0) worldNormal: vec3f,
  @location(1) uv: vec2f,
  @location(2) tint: vec4f,
}

@vertex
fn vs_main(input: VertexInput) -> VertexOutput {
  let world = instanceWorldMatrix(input.world0, input.world1, input.world2, input.world3);
  var out: VertexOutput;
  out.clip = camera.viewProjection * vec4f(transformPosition(world, input.position), 1.0);
  out.worldNormal = transformNormal(world, input.normal);
  out.uv = input.uv;
  out.tint = input.tint;
  return out;
}

@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4f {
  return input.tint; // shading is yours: re-normalize input.worldNormal and light it as you like
}
```

Connect the camera by binding name from TypeScript. Pass the full binding object — `{ camera: { viewProjection } }` — so the value maps to the `camera` binding and its `viewProjection` member without a group or binding index in TypeScript:

```ts
import { draw, frame, geometry, init, target } from "vgpu";
import { instances, orbitRig, perspective, rigPose, sphere, viewMatrices } from "vgpu/scene";
import { instanceGeometry } from "vgpu/scene/gpu";
import sceneShader from "./instanced-scene.wgsl";

const gpu = await init();
const sceneTarget = target(gpu, { size: [640, 360], depth: true });
const objects = instances({ capacity: 1, attributes: { tint: "float32x4" } });
objects.add({ tint: [0.8, 0.4, 0.2, 1] });
const bridge = instanceGeometry(gpu, objects, { mesh: geometry(gpu, sphere()) });
const projection = perspective({ fov: 45, near: 0.1, far: 100 }, 640 / 360, new Float32Array(16));
const pose = rigPose(orbitRig({ distance: 4 }), { position: new Float32Array(3), quaternion: new Float32Array(4) });
const matrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };
viewMatrices(pose, projection, matrices);

// ---cut---
const instancedScene = draw(gpu, { shader: sceneShader, geometry: bridge.geometry });

frame(gpu, (currentFrame) => {
  const count = bridge.publish(); // upload changed instance rows before encoding any pass
  instancedScene.set({ camera: { viewProjection: matrices.viewProjection } });
  currentFrame.pass({ target: sceneTarget, clear: [0, 0, 0, 1] }, (pass) => {
    pass.draw(instancedScene, { instances: count });
  });
});
```

`set()` validates and packs `matrices.viewProjection` when you call it — it keeps no reference to your `Float32Array`. After you mutate the matrix (for example by calling `viewMatrices()` again), call `set()` again; the draw keeps using the values from the last `set()` call. The instance world matrix needs no bind group at all: it arrives through vertex locations.

## Notes

* This module is pure WGSL: it declares no `@group`, no `@binding`, no overrides, no hidden state, no resources, and no entry points. Camera data, textures, and every other resource stay in your entry shader; the resolver rejects bindings in imported modules anyway.
* **Column-major.** The world matrix uses vgpu's column-major convention: CPU `Mat4` index `4 * column + row`, translation at indices 12, 13, 14. `instanceWorldMatrix` takes columns, not rows — passing rows produces the transposed matrix.
* **Normals.** `transformNormal` returns the normalized inverse-transpose of the 3×3 linear part applied to `normal`, so normals stay perpendicular to transformed surfaces under rotation, nonuniform scale, shear, and reflections. The result depends only on the direction of `normal`, not its length. Translation never affects it.
* **Reflected (negative-determinant) transforms** keep normal orientation: the determinant sign is preserved, so an outward normal stays outward on the mirrored surface. The helper only transforms normals; triangle winding and face culling are not affected by it.
* **Exact-zero fallback.** `transformNormal` returns exactly `vec3f(0.0)` when `normal` is the zero vector or when its guarded `f32` calculations produce a zero linear magnitude, determinant, or cofactor result. There is no epsilon or rank tolerance. A matrix intended to be singular before conversion to `f32` can become full-rank after rounding, so the helper cannot recover that pre-rounded intent and can return a direction instead of the fallback. Use a stable exact singular representation, such as a zero column, when the fallback is required; test for zero length if your shading needs a fallback direction.
* **Finite-precision limits.** Scaling the inputs before determinant and normalization calculations reduces avoidable overflow and underflow, but it does not make ill-conditioned normal transforms exact. Near-singular matrices and extreme axis ratios can amplify `f32` rounding, change the computed determinant sign or direction, or encounter backend-dependent subnormal flushing. Do not rely on exact symbolic rank detection or a unit result for those extreme cases. Well-conditioned finite affine transforms, including shear, reflection, nonuniform scale, and small uniform scale, preserve the behavior described above.
* **Finite affine input only.** Results are defined for finite matrices with bottom row `0, 0, 0, 1`. `NaN`, infinities, and projective matrices have no promised behavior. `transformPosition` drops `w` without a perspective divide — do not pass a view-projection matrix to it; multiply `camera.viewProjection * vec4f(worldPosition, 1.0)` for clip space as the example does.
* **Extra deformation needs the complete transform.** The helpers only see the matrix you pass. If your shader also scales, stretches, or displaces vertices — a per-instance stretch attribute, wind sway, a morph target — build the complete matrix (for example `world * shape`) and pass it to both `transformPosition` and `transformNormal`, or compute an adjusted normal yourself. The helpers cannot infer displacement applied elsewhere in the shader, and a normal transformed by `world` alone is wrong for the deformed surface.
* **No material, lighting, or color behavior.** The helpers return geometry only. There is no PBR model, light model, default material, or color-space assumption; shade `worldNormal` with your own fragment code, for example `lambert` from `@vgpu/wgsl-std/light`.
* **See also:** [`instanceGeometry()`](/docs/reference/vgpu-scene-gpu/instance-geometry), the [Scene composition guide](/docs/guides/scene-composition), [`Draw.set()`](/docs/reference/vgpu/draw#draw), [WGSL modules](/docs/concepts/wgsl-modules), `resolveShader`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: @vgpu/wgsl-std/noise/simplex
description: Pure WGSL simplex noise (`simplex2d`, `simplex3d`) and amplitude-normalized fBM (`fbmSimplex2d`, `fbmSimplex3d`) for resolver-managed shaders. Import these for smooth gradient noise — clouds, terrain, water, plasma — when you want the cheaper, higher-frequency sibling of `@vgpu/wgsl-std/noise/perlin`. For cell/edge patterns use `@vgpu/wgsl-std/noise` (Voronoi) instead.
---

# @vgpu/wgsl-std/noise/simplex



## Import

```wgsl
import { simplex2d, simplex3d, fbmSimplex2d, fbmSimplex3d } from "@vgpu/wgsl-std/noise/simplex";
```

## Signature

```wgsl
export fn simplex2d(position: vec2f) -> f32;
export fn simplex3d(position: vec3f) -> f32;
export fn fbmSimplex2d(position: vec2f, octaves: i32, lacunarity: f32, gain: f32) -> f32;
export fn fbmSimplex3d(position: vec3f, octaves: i32, lacunarity: f32, gain: f32) -> f32;
```

## Parameters

| Param      | Type    | Required | Default | Notes                                                                                                                                                                                                       |
| ---------- | ------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| position   | `vec2f` | ✔        | —       | 2D sample position for `simplex2d` / `fbmSimplex2d`. One unit is one lattice cell; scale the input to set the feature size.                                                                                 |
| position   | `vec3f` | ✔        | —       | 3D sample position for `simplex3d` / `fbmSimplex3d`. Passing time as Z animates a 2D field, but see the note on unbounded time below.                                                                       |
| octaves    | `i32`   | ✔        | —       | Number of fBM octaves. **Silently clamped to `[1, 16]`**: an unbounded dynamic loop count is a GPU-hang risk. `1` returns exactly the base noise.                                                           |
| lacunarity | `f32`   | ✔        | —       | Per-octave frequency multiplier. Not clamped. `2.0` is the usual choice; a slightly irrational value such as `2.17` avoids octaves lining up on the lattice.                                                |
| gain       | `f32`   | ✔        | —       | Per-octave amplitude multiplier. **Silently clamped to `[0, 1]`**: a negative gain would break the amplitude sum the range guarantee rests on. `0.5` is the usual choice; `0` collapses to a single octave. |

**Returns:** `f32` in the open interval `(-1, 1)` — never clipped, for every finite input, including all fBM parameter combinations. The bound is a proof, not an observation: the normalizers (`98.0` for 2D, `76.0` for 3D) sit just below `1 / sup` of the raw kernel sum (`0.0100802047` and `0.0130071572`), so `abs(simplex2d) <= 0.98786` and `abs(simplex3d) <= 0.98854`; fBM divides by the sum of the amplitudes, so the bound survives octaves.

**Throws:** These WGSL declarations do not throw. `resolveShader()` can still throw `VGPU-WGSL-SYM-NOEXPORT` for a misspelled import (note the module is `@vgpu/wgsl-std/noise/simplex`, not `@vgpu/wgsl-std/noise`), `VGPU-WGSL-PKG-NOTFOUND` if the package import cannot be resolved, or validation errors such as `VGPU-WGSL-NAGA-UNKNOWN` if the calling WGSL is invalid. This module reaches `@vgpu/wgsl-std/hash` through a private gradient core, so package resolution must be able to resolve that package export too.

## Measured field properties

| fn          | guaranteed range | max after normalization | observed max | sigma     | max slope | hashes per call |
| ----------- | ---------------- | ----------------------- | ------------ | --------- | --------- | --------------- |
| `simplex2d` | `(-1, 1)`        | 0.98786                 | 0.9878       | **0.533** | ≈6.95     | 3 × `pcg2d`     |
| `simplex3d` | `(-1, 1)`        | 0.98854                 | 0.9884       | **0.388** | ≈6.53     | 4 × `pcg3d`     |

Extremes are rare: with sigma ≈ 0.39–0.53 most samples sit well inside the range. **Remap, do not saturate** — `saturate(simplex3d(p))` throws away the whole negative half of the field. Use `remap(-0.6, 0.6, 0.0, 1.0, value)` from `@vgpu/wgsl-std/math` and clamp afterwards if you need `[0, 1]`.

## Examples

```ts
const simplexWgsl = `
import { simplex3d } from "@vgpu/wgsl-std/noise/simplex";
import { remap, saturate } from "@vgpu/wgsl-std/math";

// A single octave, remapped into [0, 1] for use as a mask.
fn smoke(position: vec2f, time: f32) -> f32 {
  let value = simplex3d(vec3f(position * 3.0, time * 0.2));
  return saturate(remap(-0.6, 0.6, 0.0, 1.0, value));
}
`;

console.log(simplexWgsl.includes("smoke"));
```

```ts
const cloudWgsl = `
import { fbmSimplex3d } from "@vgpu/wgsl-std/noise/simplex";
import { remap, saturate } from "@vgpu/wgsl-std/math";

// Animated clouds: fBM over a domain-warped field.
// Offsets are >= 2 units apart so the three warp components are decorrelated.
fn cloudCoverage(position: vec3f, time: f32) -> f32 {
  let drift = vec3f(position.xy + vec2f(time * 0.02, 0.0), position.z + time * 0.05);

  // Domain warp: displace the sample point with a low-frequency field.
  let warp = vec3f(
    fbmSimplex3d(drift, 3, 2.0, 0.5),
    fbmSimplex3d(drift + vec3f(37.2, 11.7, 5.3), 3, 2.0, 0.5),
    fbmSimplex3d(drift + vec3f(-19.4, 42.1, 23.8), 3, 2.0, 0.5),
  );

  // Detail octaves on the warped domain, then shape coverage.
  let field = fbmSimplex3d(drift + warp * 0.45, 5, 2.0, 0.5);
  let coverage = saturate(remap(-0.15, 0.65, 0.0, 1.0, field));
  return coverage * coverage * (3.0 - 2.0 * coverage);
}
`;

console.log(cloudWgsl.includes("cloudCoverage"));
```

```ts
const shapedWgsl = `
import { simplex3d } from "@vgpu/wgsl-std/noise/simplex";

// Turbulence (billowy): sum abs(noise) per octave -> [0, 1).
// Must be per-octave; abs(fbmSimplex3d(...)) is NOT the same thing.
fn turbulenceSimplex3d(position: vec3f, octaves: i32) -> f32 {
  var sum = 0.0;
  var amplitude = 1.0;
  var weight = 0.0;
  var sample = position;
  for (var i = 0; i < octaves; i = i + 1) {
    sum = sum + amplitude * abs(simplex3d(sample));
    weight = weight + amplitude;
    sample = sample * 2.0;
    amplitude = amplitude * 0.5;
  }
  return sum / weight;
}

// Ridged (terrain): replace abs(n) with a squared (1.0 - abs(n)), per octave.
fn ridgedSimplex3d(position: vec3f, octaves: i32) -> f32 {
  var sum = 0.0;
  var amplitude = 1.0;
  var weight = 0.0;
  var sample = position;
  for (var i = 0; i < octaves; i = i + 1) {
    let ridge = 1.0 - abs(simplex3d(sample));
    sum = sum + amplitude * ridge * ridge;
    weight = weight + amplitude;
    sample = sample * 2.0;
    amplitude = amplitude * 0.5;
  }
  return sum / weight;
}
`;

console.log(shapedWgsl.includes("ridgedSimplex3d"));
```

```ts
const seededWgsl = `
import { simplex2d } from "@vgpu/wgsl-std/noise/simplex";

// There is no seed parameter: offset the input instead, by >= 2.0 units.
fn twoIndependentFields(position: vec2f) -> vec2f {
  return vec2f(simplex2d(position), simplex2d(position + vec2f(37.0, -19.0)));
}
`;

console.log(seededWgsl.includes("twoIndependentFields"));
```

## Notes

* **Kernel radius² is `0.5`, not the widespread `0.6`.** The canonical Gustavson/webgl-noise value has a support radius of 0.775, which exceeds the reach of the 3-corner (2D) / 4-corner (3D) traversal, so corners that still carry a non-zero contribution get dropped at a simplex face: a genuine C0 crack. Measured with a dense line scan (step `1e-6`): max `|Δv|` is `9.5e-5` / `4.6e-5` (raw field) at `0.6` versus `4.8e-8` / `2.9e-8` at `0.5`, i.e. \~1000× worse, \~0.8% of the normalized range. It is invisible in a flat colour ramp and obvious as a seam in normals or high-contrast ramps. `0.5` is not merely "smaller and safer": it is exactly the largest radius² for which every dropped corner is already outside the kernel (equality is attained, in 2D, at `d = (G2 - 0.5, 0.5)`). **Do not "fix" this back to `0.6`** — `tests/simplex.test.ts` fails loudly, by design, if you do.
* **Simplex vs Perlin at the same input scale:** \~2.5× the slope and \~1.7× the sigma. `simplex3d(p)` is *not* "`perlin3d(p)` but faster" — it is a higher-frequency, higher-contrast field. When migrating, **scale `p` by \~0.4–0.5** (`simplex3d(p * 0.45)`) to get a comparable look.
* **Cost:** `simplex3d` costs 4 `pcg3d` hashes against `perlin3d`'s 8, so it is roughly half the price per call — but a fair comparison has to account for the frequency difference above: matching Perlin's look means sampling a scaled-down domain, not a cheaper field. A 6-octave `fbmSimplex3d` is 24 `pcg3d` hashes; the cloud recipe above (3 warp fields at 3 octaves plus 5 detail octaves) is \~14 `simplex3d` calls, i.e. \~56 hashes per pixel. Prefer `simplex2d` where the third axis is only animation.
* **Seeding is by input offset; there is no `seed` parameter** (same convention as `voronoi2d`/`voronoi3d`). Measured Pearson correlation between `p` and `p + offset`: `(0.5,0,0)` → 0.400, `(1,0,0)` → −0.043, `(2,0,0)` → 0.0017, `(17,0,0)` → −0.0004, `(101,53,7)` → 0.0035. **Any offset of ≥ 2.0 units on some axis decorrelates; sub-cell offsets do not.** Keep offsets in the tens–thousands, not `1e6`, because of the f32 mantissa.
* **Period is 2³² cells** — the gradient index comes from `pcg2d`/`pcg3d` over the integer cell, not from a float `mod 289` permutation, so there is no visible tiling.
* **f32 domain:** the fractional part `p - floor(p)` is quantized to \~2⁻²⁴·|p|, so detail visibly bands beyond `|p| ≈ 1e4` and vanishes entirely at `|p| >= 2²³`. fBM multiplies the effective coordinate by `lacunarity^(octaves - 1)` (6 octaves at λ=2 → 32×), so it reaches that limit 32× sooner. **An animation that feeds unbounded `time` into the third axis degrades after long sessions** — wrap or scale time (`fract(time * 0.05) * 20.0`, or reset a session clock), do not let it grow without bound.
* Unlike Perlin, simplex has **no zero on the integer grid**: the simplex lattice is sheared, so integer coordinates are generically interior points. The field *is* exactly 0 at each lattice vertex of the sheared grid (e.g. `simplex3d(vec3f(0.5))` is `0.0`), because there the gradient offset is the zero vector and every other corner lies outside the kernel. Do not build a lattice-zero assumption on top of `simplex2d`/`simplex3d`.
* This module is pure WGSL: no `@group`, no `@binding`, no overrides, no entry points, no hidden state. It contains no lookup table (no `array<...>`) and no `sin`/`cos`/`sqrt`/`inverseSqrt`/`pow`: those have implementation-defined accuracy, so an angle-based gradient would drift per driver. Gradient *selection* is therefore bit-identical on every backend; only the final interpolation may differ by a few ulp.
* The module returns a scalar field only. It does not choose colours, coverage curves, warp strength, animation speed, or material policy — the recipes above are examples to copy and tune, not policy the module enforces.
* Algorithmic references (no code copied, no third-party licence obligation incurred): Perlin 2001, *Hardware-accelerated procedural texturing* / simplex construction; Stefan Gustavson, *Simplex noise demystified*. The US patent on simplex noise (US 6,867,776 B2) expired in 2022.
* **See also:** `@vgpu/wgsl-std/noise/perlin` (`perlin2d`/`perlin3d`/`fbmPerlin2d`/`fbmPerlin3d` — smoother, exactly 0 on the integer lattice, \~2.5× less slope), `@vgpu/wgsl-std/noise` (Voronoi cells), `@vgpu/wgsl-std/math` (`remap`, `saturate`), `@vgpu/wgsl-std/hash` (`pcg2d`, `pcg3d`).


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: compile
description: Converts one raw runtime WGSL string into the data-only `ResolvedShader` shape used by `@vgpu/wgsl`. Use it when the shader source is already a complete WGSL entry module and does not need import resolution.
---

# compile



## Import

```ts
import { compile } from "@vgpu/wgsl";
```

## Signature

```ts
import type { ResolvedShader } from "@vgpu/wgsl";

declare function compile(wgsl: string): ResolvedShader;
```

## Parameters

| Param | Type   | Required | Default | Notes                                                                                                                                                                                                 |
| ----- | ------ | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| wgsl  | string | ✔        | —       | Complete WGSL source for one runtime shader. It is copied byte-for-byte to `resolved.wgsl`. Top-level `import` syntax is rejected; use `resolveShader` or a build-time loader for WGSL import graphs. |

**Returns:** `ResolvedShader` — a data object with `kind: "wgsl"`, the original `wgsl`, passthrough source/AST/source-map metadata, deterministic `cacheKey`, lexically detected `entryPoints`, and source `stats`.

**Throws:** `VGPU-WGSL-RUNTIME-IMPORT` when the trimmed source starts with a top-level `import` statement after comments are stripped — remove the import, pre-resolve with `resolveShader`, or use the Vite/webpack loader.

## Examples

```ts
import { compile } from "@vgpu/wgsl";

const shader = compile(`
@compute @workgroup_size(1)
fn main() {
}
`);

shader.kind satisfies "wgsl";
shader.entryPoints satisfies readonly string[];
console.log(shader.entryPoints.includes("main"));
```

```ts
import { compile } from "@vgpu/wgsl";

try {
  compile(`import { helper } from "./helper.wgsl";`);
} catch (error) {
  if (error instanceof Error && "code" in error) {
    console.log(error.code === "VGPU-WGSL-RUNTIME-IMPORT");
  }
}
```

## Notes

* `compile()` does not read files, resolve packages, mangle imported symbols, reflect binding layouts, or validate WGSL semantics.
* The only syntax check is import rejection. Invalid WGSL without `import` still returns a `ResolvedShader`; WebGPU validation happens later when a shader module is created.
* `entryPoints` contains the names of top-level `fn` declarations carrying an exact `@vertex`, `@fragment`, or `@compute` attribute, in source order. Other declaration attributes may appear before or after the stage attribute. Comments and function bodies are ignored, and Unicode XID names are preserved without normalization.
* Entry-point detection is intentionally lexical rather than semantic. It does not validate stage signatures, workgroup sizes, duplicate attributes, or any other WGSL rule. In incomplete source, an unterminated block comment or attribute argument ends extraction without throwing; names confirmed earlier are retained.
* `stats.bindGroups` is `0` in this runtime passthrough shape. Do not use it as reflection for resource bindings.
* Runtime WGSL modules with resources are allowed because there is no import graph. For imported WGSL modules, keep modules pure and declare every `@group/@binding` resource in the entry module.
* `compile()` output is not a renderer input: a `ResolvedShader` has no artifact `version`, so `draw`, `effect`, and `compute` reject it with `VGPU-SHADER-SOURCE-INVALID`. Pass `prepareShader(resolved.wgsl)` from `@vgpu/wgsl/prepare` instead, or import the file through a loader.
* **See also:** `ResolvedShader`, `ShaderSource`, `prepareShader` (`@vgpu/wgsl/prepare`), `resolveShader`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: wgslVitePlugin and transformWgsl
description: Vite/Rollup transform that turns `.wgsl` files into JavaScript modules whose default export is a prepared `ShaderSource` v2 artifact. Use the plugin in Vite apps and `transformWgsl()` in tests or custom tooling; both reflect the final shader at build time so the browser never loads the WGSL parser.
---

# wgslVitePlugin and transformWgsl



## Import

```ts
import wgslVitePlugin, { transformWgsl } from "@vgpu/wgsl/loader-vite";
import type { ViteLoadResult } from "@vgpu/wgsl/loader-vite";
```

## Signature

```ts
interface ViteLoadResult { readonly code: string; readonly map: null }

interface WgslVitePluginOptions {
  readonly minify?: boolean | { readonly whitespace?: boolean; readonly identifiers?: "none" | "safe" };
}

interface TransformWgslOptions extends WgslVitePluginOptions {
  readonly source: string;
  readonly id: string;
  readonly onDependency?: (absPath: string) => void;
}

declare function transformWgsl(source: string, id: string, options?: WgslVitePluginOptions): Promise<ViteLoadResult>;
declare function transformWgsl(opts: TransformWgslOptions): Promise<ViteLoadResult>;
declare function wgslVitePlugin(options?: WgslVitePluginOptions): {
  readonly name: string;
  readonly transform: (this: { addWatchFile(fileName: string): void }, source: string, id: string) => Promise<ViteLoadResult | null>;
};
```

## Parameters

| Param             | Type                        | Required        | Default     | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |                                                                                                                                                                                                                                        |
| ----------------- | --------------------------- | --------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| options.minify    | \`boolean                   | MinifyOptions\` | ✖           | `false`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          | Shared plugin/transform minify option. `true` means `{ whitespace: true, identifiers: "safe" }`; object form defaults to `{ whitespace: true, identifiers: "none" }`. Reflection and the checksum always describe the minified output. |
| source            | string                      | ✔               | —           | WGSL contents supplied to the transform. This value is authoritative for the entry module in every branch — ordinary leaves, direct-export leaves, and import graphs; the entry is never reread from `id`. Imported modules still use normal file/package resolution.                                                                                                                                                                                                                                                                                                                                                                                                            |                                                                                                                                                                                                                                        |
| id                | string                      | ✔               | —           | WGSL file id/path. Anchors relative import resolution, dependency reporting, and the path named in reflection diagnostics; direct `transformWgsl()` calls may use an entry path that does not exist on disk. The plugin transforms ids ending with `.wgsl` plus the private metadata requests that its own generated modules make; it returns `null` for every other id, including a `.wgsl` import with an unrelated query such as `?raw`.                                                                                                                                                                                                                                      |                                                                                                                                                                                                                                        |
| opts.source       | string                      | ✔               | —           | Object-overload source field.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |                                                                                                                                                                                                                                        |
| opts.id           | string                      | ✔               | —           | Object-overload id field.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |                                                                                                                                                                                                                                        |
| opts.onDependency | `(absPath: string) => void` | ✖               | no callback | Called for each transitive dependency as soon as its path resolves, before it is loaded. Discovered dependencies are still reported when a later resolution step throws. When a relative, `@/`, or mapped import — or the target of an installed package's `exports` entry — names a file that does not exist, it also receives the missing candidate paths (the path itself when it has an extension, otherwise `<path>.wgsl` then `<path>/index.wgsl`) before `VGPU-WGSL-RES-NOTFOUND` is thrown. Successful resolution reports only the selected file, in the same order as before. Leaf files intentionally do not call it. The plugin forwards it to Vite's `addWatchFile`. |                                                                                                                                                                                                                                        |

**Returns:** `Promise<ViteLoadResult>` from `transformWgsl()` with JavaScript module `code` and `map: null`; plugin `transform` returns that result for `.wgsl` ids and its own private metadata requests, or `null` for other ids. The `code` is ESM source whose default export evaluates to the plain object `{ version: 2, wgsl, reflection, sourceChecksum, producer: "@vgpu/wgsl/prepare-v2", functionExports }`. It can contain `import` statements (see Notes), so evaluate it as a module; do not parse it as a lone JSON literal.

**Throws:**

* Any `resolveShader()` `VGPU-WGSL-*` or `VGPU-RESOLVE-MODULE-BINDING` error when import graph resolution fails — fix imports, module purity, package resolution, duplicates, or minification.
* `VGPU-WGSL-MINIFY-IDENTIFIERS` or `VGPU-WGSL-MINIFY-BLOCK` when minification options/source are invalid for a leaf file — pass a valid minify mode or fix unterminated comments.
* The `prepareShader()` lexer, parser, and reflection diagnostics (`VGPU-WGSL-LEX-*`, `VGPU-WGSL-REFLECT-*`) when the final WGSL cannot be reflected — fix the WGSL the diagnostic reports. The transform supplies `id` as diagnostic context, although individual layout errors may omit it from their message. For ordinary leaves these now fail the build; see Notes.
* `VGPU-WGSL-PACKED-METADATA-INVALID` when loader-generated shader metadata is malformed or was produced by incompatible `@vgpu/wgsl` loader assets — during the build, for a generated metadata request, or when a generated shader module is evaluated. It is an ordinary `Error` with `code` and `fix` (`"Rebuild with compatible @vgpu/wgsl loader assets."`), not a `ShaderSource` error — rebuild the affected bundle with compatible loader assets, and never import or edit generated metadata requests by hand.

## Examples

```ts
import wgslVitePlugin from "@vgpu/wgsl/loader-vite";

const viteConfig = {
  plugins: [wgslVitePlugin({ minify: true })],
};

export default viteConfig;
```

Call `transformWgsl()` directly to inspect the emitted artifact. The entry path does not need to exist on disk:

```ts
import { transformWgsl } from "@vgpu/wgsl/loader-vite";

const result = await transformWgsl(
  "@compute @workgroup_size(64) fn main() {}",
  "/src/shaders/particles.wgsl",
  { minify: { whitespace: true } },
);

console.log(typeof result.code); // "string" — ESM module source
console.log(result.map); // null
console.log(result.code.includes('"producer":"@vgpu/wgsl/prepare-v2"')); // true
```

The module's default export carries the minified `wgsl`, a `reflection` of that exact text (here one compute entry with workgroup size `[64, 1, 1]`), its `sourceChecksum`, and `functionExports: []`. Nothing in it imports or calls the WGSL parser, resolver, reflection, or `prepareShader()`.

## Notes

* **Output is a prepared `ShaderSource` v2 artifact.** The default export is `{ version: 2, wgsl, reflection, sourceChecksum, producer, functionExports }` — the same shape `prepareShader()` returns, with `producer: "@vgpu/wgsl/prepare-v2"`. The evaluated default export is always that full plain object with own data properties. The exported object is deeply frozen in every form (literal and compact), so the renderer validates it once and reuses the result; no new imports, options, or syntax are involved. The module contains no `prepareShader()` call and no parser, resolver, or reflection import, so `draw`, `effect`, and `compute` consume it without bundling the WGSL parser. Rebuild with matching `@vgpu/wgsl` and `vgpu` versions; the renderer rejects older v1 artifacts.
* **Eligible reflection metadata may be emitted compactly.** When bounded packing and module-extraction estimates predict a smaller representation, the generated module imports a small parser-free decoder and independently reachable metadata modules that the plugin itself generates, and rebuilds the full `reflection` when the module is evaluated. Rollup's normal graph decides which chunks include them, so final chunking and compression can change the result; compact selection estimates savings rather than guaranteeing a smaller compressed bundle. Both compact and literal forms export identical prepared data, and each artifact gets its own freshly built, frozen objects, so one artifact never shares mutable state with another even when encoded metadata is shared. Inputs that are small, exceed a bound, or do not beat the estimate stay in a plain object literal. None of this needs configuration or an extra dependency — the generated imports point at the `@vgpu/wgsl` installation that ran the transform — and the decoder, encoded format, and generated requests are private implementation details, not author APIs.
* **Reflection describes the final WGSL.** The transform prepares the text it actually emits — after identifier and whitespace minification, import resolution, and dead-code elimination. For import graphs and direct-export leaves it reflects `resolved.wgsl` again instead of reusing `resolved.reflection`, which can describe the source before identifier minification. `sourceChecksum` is computed over that same final string.
* **`functionExports` is authoritative.** Every artifact includes the property. Ordinary leaves emit `functionExports: []`. Direct-export leaves and import graphs emit one record per surviving `export fn`: `name` is the authored export name, `resolvedName` is the declaration's final name in the emitted WGSL (after minification), and `parameterNames` keeps the authored parameter names.
* Author imports stay ordinary `.wgsl` files. Besides those, `wgslVitePlugin()` handles only the private metadata requests its own generated modules make; ids with other queries or extensions keep their previous behavior. Use `transformWgsl()` directly for tests and non-Vite tooling.
* For resolver-backed transforms, `source` remains the entry module instead of being reread from `id`. This preserves changes made by earlier Vite plugins and supports virtual entry modules while imports continue to resolve relative to `id`.
* Leaf shader transforms do not call `onDependency` because Vite already tracks the entry file. Imported graph transforms call it for transitive dependencies before loading them, including on resolution paths that later fail, so a later valid save of the broken import triggers a rebuild. A deleted import works the same way: its missing candidate paths are reported before `VGPU-WGSL-RES-NOTFOUND` fails the transform, so restoring the file triggers a rebuild.
* A leaf with a direct `export fn` goes through resolution even without imports: the author-only `export` marker is removed and the surviving function receives authored-to-final identity metadata. Ordinary leaves skip resolution — reserved-identifier diagnostics, optional minification, then preparation — and emit `functionExports: []`.
* **Reflection-detectable parse and layout errors in ordinary leaves now fail the build.** Ordinary leaves used to be emitted with no parsing beyond optional minification. They are now reflected at build time, so malformed reflected declarations and invalid host-shareable layouts (for example a `bool` in a uniform struct) may throw `VGPU-WGSL-LEX-*` or `VGPU-WGSL-REFLECT-*` during `vite build`/`vite dev` instead of surfacing at runtime. Reflection is not device validation: type errors, undefined identifiers inside function bodies, and other errors only the native WGSL compiler detects still ship.
* **The plugin never validates WGSL on a device, in any mode.** It calls `resolveShader({ validate: false })` for import graphs and direct-export leaves; that explicit value wins over `VGPU_VALIDATE`, so setting that environment variable never makes the plugin acquire a device. Preparation itself is GPU-free. There is no plugin option to opt into validation. The validation gate is `npx vgpu check --require-validation <file>` — run it in CI or as a pre-commit hook; see `npx vgpu docs cat cli.docs.md`.
* A leaf WGSL file may declare entry resources. Shared/imported modules must be pure: no `@group/@binding` outside the entry.
* **See also:** `ShaderSource`, `prepareShader` (`@vgpu/wgsl/prepare`), `resolveShader`, `wgslWebpackLoader`, and the `nextjs` guide (`npx vgpu docs cat nextjs.md`) for the ambient `.d.ts` that types `.wgsl` imports.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: wgslWebpackLoader
description: Webpack loader that turns `.wgsl` files into JavaScript modules whose default export is a prepared `ShaderSource` v2 artifact. Use it when webpack should inline WGSL, resolve vgpu WGSL imports, and reflect the final shader at build time so the browser never loads the WGSL parser.
---

# wgslWebpackLoader



## Import

```ts
import wgslWebpackLoader from "@vgpu/wgsl/loader-webpack";
```

## Signature

```ts
interface WgslWebpackLoaderOptions {
  readonly minify?: boolean | { readonly whitespace?: boolean; readonly identifiers?: "none" | "safe" };
}

type LoaderContext = {
  resourcePath?: string;
  resourceQuery?: string;
  async?: () => (error: Error | null, result?: string) => void;
  addBuildDependency?: (file: string) => void;
  addDependency?: (file: string) => void;
  getOptions?: () => unknown;
};

type WgslWebpackLoader = (this: LoaderContext, source: string) => string | void;
```

## Parameters

| Param                   | Type                     | Required        | Default                                   | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |                                                                                                                                                                                                 |
| ----------------------- | ------------------------ | --------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| source                  | string                   | ✔               | —                                         | WGSL contents supplied by webpack. This value is authoritative for the entry module in every branch — ordinary leaves, direct-export leaves, and import graphs; the loader never rereads the entry from disk. Imported modules still use normal file/package resolution.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |                                                                                                                                                                                                 |
| this.resourcePath       | string                   | ✖               | `"<webpack>"`                             | Absolute path to the `.wgsl` entry. Anchors relative import resolution, dependency reporting, and the path named in reflection diagnostics.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |                                                                                                                                                                                                 |
| this.resourceQuery      | string                   | ✖               | `""`                                      | Supplied by webpack or Turbopack for the current request — never an author option. The loader reads it only to recognize the private metadata requests that its own generated modules make; any other query, or none, takes the ordinary shader path unchanged.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |                                                                                                                                                                                                 |
| this.async              | `() => callback`         | ✖               | synchronous mode                          | Required when the WGSL source has top-level imports or a direct `export fn`. Without async mode, those resolver paths throw `VGPU-WGSL-RUNTIME-IMPORT`. Ordinary leaves never call it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |                                                                                                                                                                                                 |
| this.addBuildDependency | `(file: string) => void` | ✖               | compiler files go to `this.addDependency` | Receives the loader's own compiler files — the installed `@vgpu/wgsl` `package.json`, its shipped metadata anchor, and every published `dist` JavaScript file — first, on every call: before private metadata requests and ordinary leaves return, and before any shader error. Webpack records them as build dependencies of the module; its default managed-package snapshot still treats an installed package's unchanged `name@version` as immutable (see Notes). Turbopack contexts never use this hook, even when one is present.                                                                                                                                                                                                                                                                                                                                                             |                                                                                                                                                                                                 |
| this.addDependency      | `(file: string) => void` | ✖               | no explicit extra dependencies            | Receives the compiler files when the context is Turbopack's or has no `addBuildDependency`; a context with neither hook skips compiler registration and still transforms. Separately, it is called as each transitive shader dependency is discovered, before it is loaded, so the bundler invalidates on imported `.wgsl` changes even when the current resolution fails. When a relative, `@/`, or mapped import — or the target of an installed package's `exports` entry — names a file that does not exist, the loader also registers the missing candidate paths (the path itself when it has an extension, otherwise `<path>.wgsl` then `<path>/index.wgsl`) before throwing `VGPU-WGSL-RES-NOTFOUND`, so recreating the file invalidates the build. Successful resolution registers only the selected shader file; shader dependencies keep their previous order, after any compiler files. |                                                                                                                                                                                                 |
| this.getOptions         | `() => unknown`          | ✖               | `{}`                                      | Reads `options.minify` when present. Unknown options, including `validate` and the private compiler identity that `wgslTurbopackRule()` adds, are ignored.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |                                                                                                                                                                                                 |
| options.minify          | \`boolean                | MinifyOptions\` | ✖                                         | `false`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | `true` means `{ whitespace: true, identifiers: "safe" }`; object form defaults to `{ whitespace: true, identifiers: "none" }`. Reflection and the checksum always describe the minified output. |

**Returns:** `string | void` — for ordinary leaf shaders, returns the JavaScript module source synchronously. For direct-export leaves and import graphs, returns `void` and passes the JavaScript module source to webpack's async callback. Either way the module's default export evaluates to the plain object `{ version: 2, wgsl, reflection, sourceChecksum, producer: "@vgpu/wgsl/prepare-v2", functionExports }`; the module may also import a small parser-free decoder and loader-generated metadata modules (see Notes). The loader answers those private metadata requests synchronously.

**Throws:**

* `VGPU-WGSL-CACHE-IDENTITY` (`where: "wgslWebpackLoader"`) when the loader cannot list its compiler files — a missing, unreadable, or inconsistent `package.json`, `./loader-webpack` export, metadata anchor, or `dist` directory, a file resolving outside the package, or a symbolic directory inside `dist` — or when a dependency hook throws while registering one. `metadata.path` names the file — reinstall the matching `@vgpu/wgsl` release; for a workspace package, build `@vgpu/wgsl` first. Ordinary leaves and private metadata requests throw synchronously; import graphs and direct-export leaves report it through the async callback.
* `VGPU-WGSL-RUNTIME-IMPORT` when a WGSL file contains imports or direct exports but the loader context does not provide async mode — enable webpack asynchronous loader execution.
* Any `resolveShader()` `VGPU-WGSL-*` or `VGPU-RESOLVE-MODULE-BINDING` error when import graph resolution fails — fix the WGSL import graph, module purity, or minify options.
* `VGPU-WGSL-MINIFY-IDENTIFIERS` or `VGPU-WGSL-MINIFY-BLOCK` when minification options/source are invalid for a leaf file — pass a valid minify mode or fix unterminated comments.
* The `prepareShader()` lexer, parser, and reflection diagnostics (`VGPU-WGSL-LEX-*`, `VGPU-WGSL-REFLECT-*`) when the final WGSL cannot be reflected — fix the WGSL the diagnostic reports. The loader supplies `resourcePath` as diagnostic context, although individual layout errors may omit it from their message. For ordinary leaves these now fail the build; see Notes.
* `VGPU-WGSL-PACKED-METADATA-INVALID` when loader-generated shader metadata is malformed or was produced by incompatible `@vgpu/wgsl` loader assets — during the build, for a generated metadata request, or when a generated shader module is evaluated. It is an ordinary `Error` with `code` and `fix` (`"Rebuild with compatible @vgpu/wgsl loader assets."`), not a `ShaderSource` error — rebuild the affected bundle with compatible loader assets, and never import or edit generated metadata requests by hand.

## Examples

```ts
const config = {
  module: {
    rules: [
      {
        test: /\.wgsl$/,
        loader: "@vgpu/wgsl/loader-webpack",
        options: { minify: true },
      },
    ],
  },
};

export default config;
```

An ordinary leaf returns its module source synchronously, which makes the loader easy to exercise in a test:

```ts
import wgslWebpackLoader from "@vgpu/wgsl/loader-webpack";

const glowSource = `
@group(0) @binding(0) var<uniform> intensity: f32;

@fragment
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv * intensity, 0.0, 1.0);
}
`;

const moduleSource = wgslWebpackLoader.call({ resourcePath: "/src/shaders/glow.wgsl" }, glowSource);

console.log(typeof moduleSource); // "string" — no async callback for an ordinary leaf
console.log(moduleSource?.includes('"producer":"@vgpu/wgsl/prepare-v2"')); // true
console.log(moduleSource?.includes("prepareShader")); // false — the emitted module never calls it
```

The module's default export carries `version: 2`, the exact `wgsl`, its `reflection`, `sourceChecksum`, `producer`, and `functionExports: []`. Nothing in it imports or calls the WGSL parser, resolver, reflection, or `prepareShader()`.

## Notes

* **Framework setup lives in a guide, not here.** For `next.config.ts` (Turbopack rules or the `webpack()` hook), the ambient `.d.ts` that types `import shader from "./x.wgsl"`, and the client component that owns the canvas, read `npx vgpu docs cat nextjs.md`.
* **For Next.js Turbopack, use `wgslTurbopackRule()` from `@vgpu/wgsl/next` instead of this loader's specifier.** It returns a rule pointing at this loader, plus a compiler identity that changes Turbopack's cache key whenever the installed compiler changes. Use the raw loader directly for webpack — including Next's webpack mode — and custom bundlers.
* **Compiler files are registered on every call.** The installed `@vgpu/wgsl` `package.json`, metadata anchor, and published `dist` JavaScript go to `addBuildDependency` (webpack) or `addDependency` (Turbopack, or contexts without build dependencies). Registration takes effect only when the loader runs: a Turbopack cache hit can skip the loader, so a cache written by `@vgpu/wgsl` 0.5.0's bare-string rule needs the `wgslTurbopackRule()` migration or a one-time clear.
* **Webpack's default managed-package snapshot is version-based.** For packages installed under managed `node_modules`, webpack trusts an unchanged package `name@version` instead of hashing internal files; `addBuildDependency()` does not override that assumption. The retained-cache matrix rebuilt exact v2 for an authentic 0.5.0 `require.resolve()` upgrade whose public target changed, and in a separate disposable replay after the candidate manifest version changed. A bare same-version replacement stayed on v1. Workspace symlinks did observe same-version compiler edits and recovery. Clear webpack's cache only for a same-version in-place replacement or observed stale v1 output — not for every package upgrade.
* Do not add compiler files, a version string, or a cache key to the rule yourself, and do not disable caching to work around stale output. Use `wgslTurbopackRule()` for Turbopack; for webpack, preserve normal package versions and verify the rebuilt artifact is v2.
* TypeScript needs an ambient declaration before it accepts a `.wgsl` import. `@vgpu/wgsl` ships one: add `/// <reference types="@vgpu/wgsl/wgsl-types" />` to any `.d.ts` in your project.
* **Output is a prepared `ShaderSource` v2 artifact.** The default export is `{ version: 2, wgsl, reflection, sourceChecksum, producer, functionExports }` — the same shape `prepareShader()` returns, with `producer: "@vgpu/wgsl/prepare-v2"`. The evaluated default export is always that full plain object with own data properties. The exported object is deeply frozen in every form (literal and compact), so the renderer validates it once and reuses the result; no new imports, options, or syntax are involved. The module contains no `prepareShader()` call and no parser, resolver, or reflection import, so `draw`, `effect`, and `compute` consume it without bundling the WGSL parser. Rebuild with matching `@vgpu/wgsl` and `vgpu` versions; the renderer rejects older v1 artifacts.
* **Eligible reflection metadata may be emitted compactly.** When the bounded packing estimate predicts a smaller representation, the generated module imports a small parser-free decoder and rebuilds the full `reflection` when evaluated. Real webpack builds can additionally share independently reachable encoded metadata modules through the normal module graph. Turbopack and loader bridges that cannot guarantee a separate anchor rule keep the encoded table inline and resolve the decoder relative to the loader's own installed package. Final chunking and compression can change the result, so compact selection estimates savings rather than guaranteeing a smaller compressed bundle. Compact and literal forms export identical prepared data, and in either form each artifact gets its own freshly built, frozen objects, so one never shares mutable state with another. Inputs that are small, exceed a bound, or do not beat the estimate stay in a plain object literal. No author configuration or extra dependency is required, and the decoder, encoded format, generated anchor, and metadata requests are private implementation details, not author APIs.
* **Reflection describes the final WGSL.** The loader prepares the text it actually emits — after identifier and whitespace minification, import resolution, and dead-code elimination. For import graphs and direct-export leaves it reflects `resolved.wgsl` again instead of reusing `resolved.reflection`, which can describe the source before identifier minification. `sourceChecksum` is computed over that same final string.
* **`functionExports` is authoritative.** Every artifact includes the property. Ordinary leaves emit `functionExports: []`. Direct-export leaves and import graphs emit one record per surviving `export fn`: `name` is the authored export name, `resolvedName` is the declaration's final name in the emitted WGSL (after minification), and `parameterNames` keeps the authored parameter names.
* **Synchronous and asynchronous branches are unchanged.** An ordinary leaf — no top-level imports and no direct `export fn` — runs reserved-identifier diagnostics, optional minification, and preparation synchronously. A leaf with a direct `export fn` or any top-level import goes through `resolveShader()` asynchronously, which removes the author-only `export` marker and records authored-to-final identities.
* For resolver-backed transforms, webpack's `source` argument remains the entry module instead of being reread from `resourcePath`. This preserves changes made by earlier loaders while imports continue to resolve relative to `resourcePath`.
* Imported files are registered with webpack before they are loaded. If a transient edit causes resolution to fail, a later valid save can therefore invalidate and rebuild the failed importer without restarting the dev server. A deleted import works the same way: its missing candidate paths are registered before `VGPU-WGSL-RES-NOTFOUND` fails the build, so restoring the file lets webpack rebuild the importer.
* **Reflection-detectable parse and layout errors in ordinary leaves now fail the build.** Ordinary leaves used to be emitted with no parsing beyond optional minification. They are now reflected at build time, so malformed reflected declarations and invalid host-shareable layouts (for example a `bool` in a uniform struct) may throw `VGPU-WGSL-LEX-*` or `VGPU-WGSL-REFLECT-*` during `next build`/`next dev` instead of surfacing at runtime. Reflection is not device validation: type errors, undefined identifiers inside function bodies, and other errors only the native WGSL compiler detects still ship.
* **The loader never validates WGSL on a device, in any mode.** It calls `resolveShader({ validate: false })` for import graphs and direct-export leaves; that explicit value wins over `VGPU_VALIDATE`, so setting that environment variable never makes the loader acquire a device. Preparation itself is GPU-free. There is no loader option to opt into validation. The validation gate is `npx vgpu check --require-validation <file>` — run it in CI or as a pre-commit hook; see `npx vgpu docs cat cli.docs.md`.
* A leaf WGSL file may declare entry resources. The imported-module purity rule is enforced when `resolveShader()` sees an import graph. Do not put `@group/@binding` declarations in shared WGSL modules; put resources in the entry file and export shared structs/functions from modules.
* **See also:** `wgslTurbopackRule` (`@vgpu/wgsl/next`), `ShaderSource`, `prepareShader` (`@vgpu/wgsl/prepare`), `resolveShader`, `wgslVitePlugin`, and the `nextjs` guide (`npx vgpu docs cat nextjs.md`).


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: wgslTurbopackRule
description: Node configuration helper that returns a complete Next.js Turbopack rule for `.wgsl` files. Use it as the `"*.wgsl"` entry in `turbopack.rules` so restored Turbopack caches rebuild shader output when the installed `@vgpu/wgsl` compiler changes.
---

# wgslTurbopackRule



## Import

```ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";
import type { WgslTurbopackRule, WgslTurbopackRuleOptions } from "@vgpu/wgsl/next";
```

`@vgpu/wgsl/next` is Node tooling: import it from `next.config.ts` (or `.mjs`/`.js`), never from browser or React code. Declare `@vgpu/wgsl` directly in the `package.json` of the app that owns `next.config`, at the release your `vgpu` version depends on. A copy that only `vgpu` installs transitively is not importable under pnpm's isolated layout or Yarn PnP.

## Signature

```ts
import type { WgslWebpackLoaderOptions } from "@vgpu/wgsl/loader-webpack";

// { readonly minify?: boolean | { readonly whitespace?: boolean; readonly identifiers?: "none" | "safe" } }
type WgslTurbopackRuleOptions = WgslWebpackLoaderOptions;

type RuleValue = string | number | boolean | RuleValue[] | { [key: string]: RuleValue };

interface WgslTurbopackRule {
  loaders: [{ loader: string; options: Record<string, RuleValue> }];
  as: "*.js";
}

declare function wgslTurbopackRule(options?: WgslTurbopackRuleOptions): WgslTurbopackRule;
```

`RuleValue` is declaration support for serializable option values, not an export. The declarations import nothing from `next`; the returned rule is assignable to the `turbopack.rules` entry type of Next 15.5 and Next 16.

## Parameters

### WgslTurbopackRuleOptions

The helper accepts the raw loader’s `WgslWebpackLoaderOptions` type:

| Param                      | Type                       | Required | Default                 | Notes                                                                                                                                                                                |
| -------------------------- | -------------------------- | -------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| options                    | `WgslTurbopackRuleOptions` | ✖        | `{}`                    | Plain object. `undefined` means omitted. `minify` is the only accepted field — there is no loader, path, version, or cache-key override.                                             |
| options.minify             | `boolean \| MinifyOptions` | ✖        | `false`                 | Same vocabulary as the raw loader. `true` means `{ whitespace: true, identifiers: "safe" }`; `false` disables both. Reflection and the checksum always describe the minified output. |
| options.minify.whitespace  | `boolean`                  | ✖        | `true` in object form   | `{ minify: {} }` strips comments and whitespace.                                                                                                                                     |
| options.minify.identifiers | `"none" \| "safe"`         | ✖        | `"none"` in object form | `"safe"` shortens only function-local names, parameters, and safe resolver-generated helpers.                                                                                        |

Known optional fields set to `undefined` count as omitted. Unknown field names are errors, even when their value is `undefined`.

### WgslTurbopackRule

**Returns:** `WgslTurbopackRule` — a fresh plain object with exactly one loader entry and `as: "*.js"`. Put it under `"*.wgsl"` unchanged:

* `loaders[0].loader` is the absolute path of the public `@vgpu/wgsl/loader-webpack` target in the same `@vgpu/wgsl` installation as the helper you imported — not resolved from the app's working directory or a guessed hoisted copy.
* `loaders[0].options` holds the normalized minify settings and an opaque compiler identity. Omitted or `false` normalizes to `{ whitespace: false, identifiers: "none" }`; `true` to `{ whitespace: true, identifiers: "safe" }`; object form fills the defaults above. Both values are private: do not edit, persist, or copy them into another rule.

Every call returns new objects and copies your input, so mutating the result or reusing your options object never affects another rule.

**Throws:** synchronously, while Next evaluates your config. Errors are `VGPUError` values with `code`, `fix`, and `where: "wgslTurbopackRule"`; options are validated before any file is read.

* `VGPU-WGSL-NEXT-OPTIONS` when `options` is not omitted or a plain object (including `null`, arrays, and class instances), has an unknown field, `minify` is not omitted/a boolean/a plain object, `minify` has an unknown field, or `minify.whitespace` is defined and not a boolean. `metadata.field` names the invalid field (for example `"minify.level"`) — pass only `{ minify?: boolean | { whitespace?: boolean; identifiers?: "none" | "safe" } }`.
* `VGPU-WGSL-MINIFY-IDENTIFIERS` when `minify.identifiers` is defined and not `"none"` or `"safe"` — use `identifiers: "none"` or `"safe"`.
* `VGPU-WGSL-CACHE-IDENTITY` when the helper cannot resolve its own installation's public loader, the resolved loader does not match that installation's `package.json`, or a required compiler file (`package.json`, the shipped metadata anchor, or published `dist` JavaScript) is missing, unreadable, outside the package, or inconsistent. `cause` and `metadata.path` identify the file — reinstall the matching `@vgpu/wgsl` release; for a workspace package, build `@vgpu/wgsl` before running Next. The helper never falls back to an empty or version-only identity.

If `@vgpu/wgsl` is not a direct dependency, Node fails to resolve `@vgpu/wgsl/next` with its own module-not-found error before the helper runs — add `@vgpu/wgsl` to the app's `package.json`.

## Examples

```ts
// next.config.ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

const nextConfig = {
  turbopack: {
    rules: {
      "*.wgsl": wgslTurbopackRule(),
    },
  },
};

export default nextConfig;
```

Pass `minify` to the helper, never to the returned rule. `true` is the production preset; object form defaults to whitespace-only:

```ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

const productionRule = wgslTurbopackRule({ minify: true }); // whitespace + safe identifier shortening
const whitespaceRule = wgslTurbopackRule({ minify: { whitespace: true } }); // identifiers kept

console.log(productionRule.as); // "*.js"
console.log(productionRule.loaders[0].options.minify); // { whitespace: true, identifiers: "safe" }
console.log(whitespaceRule.loaders[0].options.minify); // { whitespace: true, identifiers: "none" }
```

Add the rule next to rules and settings your config already has. Spread each level you extend so nothing else is replaced:

```ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

const existingConfig = {
  reactStrictMode: true,
  turbopack: {
    rules: {
      "*.svg": {
        loaders: [{ loader: "@svgr/webpack", options: { icon: true } }],
        as: "*.js",
      },
    },
  },
};

const nextConfig = {
  ...existingConfig,
  turbopack: {
    ...existingConfig.turbopack,
    rules: {
      ...existingConfig.turbopack.rules,
      "*.wgsl": wgslTurbopackRule({ minify: { whitespace: true } }),
    },
  },
};

export default nextConfig;
```

For a phase-based or async config, call the helper inside the function and return the rule as part of the config:

```ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

export default async function nextConfig(phase: string) {
  const productionBuild = phase === "phase-production-build"; // PHASE_PRODUCTION_BUILD from "next/constants"
  return {
    turbopack: {
      rules: {
        "*.wgsl": wgslTurbopackRule({ minify: productionBuild }),
      },
    },
  };
}
```

Config plugins such as MDX receive the finished config, so build the rule first and wrap last:

```ts illustrative
// next.config.ts
import createMDX from "@next/mdx";
import type { NextConfig } from "next";
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

const withMDX = createMDX({});

const nextConfig: NextConfig = {
  pageExtensions: ["ts", "tsx", "md", "mdx"],
  turbopack: {
    rules: {
      "*.wgsl": wgslTurbopackRule({ minify: true }),
    },
  },
};

export default withMDX(nextConfig); // the wrapper sees the completed WGSL rule
```

Option mistakes fail while the config loads, not later during a shader build:

```ts
import { wgslTurbopackRule } from "@vgpu/wgsl/next";

const shaderOptions = JSON.parse('{"minify":{"identifiers":"aggressive"}}'); // untyped config data

try {
  wgslTurbopackRule(shaderOptions);
} catch (error) {
  console.log((error as { code?: string }).code); // "VGPU-WGSL-MINIFY-IDENTIFIERS"
}
```

## Notes

* **Identity is computed before Turbopack looks up its cache.** Each call reads the installed compiler — its `package.json`, the shipped metadata anchor, and every published `dist` JavaScript file, sorted by relative path — and hashes their contents into the loader options. Turbopack keys loader output on the rule's loader and options, so a changed or rebuilt compiler produces a new rule and misses old cache entries, while an unchanged installation produces the same rule and keeps its cache. The hash covers file contents, including the manifest, rather than relying only on timestamps, package versions, or installation paths, and nothing is memoized across calls.
* **The identity changes when Next evaluates the config.** After upgrading or rebuilding `@vgpu/wgsl`, restart `next dev` or start a new `next build`. A running dev server keeps the compiler it already loaded; ordinary `.wgsl` edits keep their normal watch and HMR behavior.
* **Insert the rule intact.** Keep its generated `loader` and `options` together. There is no public fingerprint function or cache-option name to assemble a rule yourself; replacing these fields can silently drop the protection.
* **Turbopack only.** Next's webpack mode (`next build --webpack` on Next 16, or Next 15 without `--turbopack`) ignores `turbopack.rules`. Keep a `webpack()` hook with the raw loader for that mode; see `wgslWebpackLoader`.
* **Stable Next 15.5 cannot enable Turbopack's persistent cache.** Next 15.5.25 rejects `experimental.turbopackPersistentCaching: true` with `CanaryOnlyError` when it loads the config, so the retained-cache matrix applies to Next 16.3.3. The helper still passes Next 15.5 production builds, TypeScript config checking, and dev edit/delete/recreate recovery.
* **Upgrading from `@vgpu/wgsl` 0.5.0.** On Next 16.3.3, an unchanged `require.resolve("@vgpu/wgsl/loader-webpack")` rule rebuilt authentic v1 output to exact v2 with its cache retained because the public resolved target changed. A cache written by the bare-string rule `loaders: ["@vgpu/wgsl/loader-webpack"]` stayed on v1 when that string did not change. Replacing the bare rule with `wgslTurbopackRule()` rebuilt exact v2 without deleting the cache. If you keep a hand-written bare rule instead, clear that app's `.next/cache` once after upgrading. The `nextjs` guide (`npx vgpu docs cat nextjs.md`) covers the full migration.
* **Prebuilt shader assets bypass the rule.** JavaScript or JSON shader artifacts that a package or build step already generated are imported as ordinary modules, not run through the loader. Regenerate them with matching tooling; this helper cannot upgrade them.
* **Rule output is a frozen artifact.** Each transformed `.wgsl` import exports a deeply frozen `ShaderSource`, so the renderer validates it once; import `.wgsl` files at module level. A JSON asset parsed at runtime is mutable and revalidated on every call.
* **No Next dependency.** `@vgpu/wgsl` neither depends on nor imports `next`. Use your app's own `NextConfig` type for annotations.
* **See also:** `wgslWebpackLoader` (`@vgpu/wgsl/loader-webpack`) for webpack mode and custom bundlers, `wgslVitePlugin` (`@vgpu/wgsl/loader-vite`), `ShaderSource`, and the `nextjs` guide (`npx vgpu docs cat nextjs.md`) for TypeScript `.wgsl` types and the client component.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: prepareShader
description: Turns one import-free WGSL string into the prepared `ShaderSource` artifact that `draw`, `effect`, and `compute` consume. Use it for WGSL you build or receive at runtime, for resolver output, and to upgrade legacy v1 assets; for static `.wgsl` files, the Vite/webpack loaders already call it at build time.
---

# prepareShader



## Import

```ts
import { prepareShader } from "@vgpu/wgsl/prepare";
```

`@vgpu/wgsl/prepare` is the only entrypoint that exports `prepareShader`. It is not re-exported from `vgpu`, `vgpu/node`, `vgpu/mock`, or the `@vgpu/wgsl` root. `@vgpu/wgsl` is a dependency of `vgpu`; when your package manager does not expose transitive dependencies to your code (pnpm's default isolated layout does not), add `@vgpu/wgsl` to your own `package.json` at the version your `vgpu` release depends on before importing it.

## Signature

```ts
import type { ShaderSource } from "@vgpu/wgsl";

declare function prepareShader(
  source: string | Pick<ShaderSource, "wgsl" | "functionExports">,
  path?: string,
): ShaderSource;
```

## Parameters

| Param                                                                     | Type                                                        | Required        | Default       | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ------------------------------------------------------------------------- | ----------------------------------------------------------- | --------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| source                                                                    | `string \| Pick<ShaderSource, "wgsl" \| "functionExports">` | ✔               | —             | The WGSL to prepare: either the string itself or an object carrying it. A `ResolvedShader` from `resolveShader()` and a legacy v1 `ShaderSource` both fit the object form.                                                                                                                                                                                                                                                                                   |
| source.wgsl                                                               | string                                                      | ✔ (object form) | —             | Complete WGSL for one module, reflected exactly as given. It must be an own data property; accessors are rejected without being called.                                                                                                                                                                                                                                                                                                                      |
| source.functionExports                                                    | `readonly ShaderFunctionExport[]`                           | ✖               | absent        | Authored `export fn` identities to carry into the artifact. When present it must be an array of `{ name, resolvedName, parameterNames }` records; each record and its `parameterNames` array is copied, so the arrays and objects you pass are never frozen or aliased. An explicit `[]` stays `[]`; an absent property stays absent. An own property set to `undefined` is present and invalid, so omit it instead. Duplicate authored `name`s are allowed. |
| source.version, source.reflection, source.sourceChecksum, source.producer | —                                                           | ✖               | ignored       | Never read. Reflection, checksum, and producer are always recomputed from `wgsl`, so stale metadata on an old artifact is never carried forward.                                                                                                                                                                                                                                                                                                             |
| path                                                                      | nonempty string                                             | ✖               | `"<runtime>"` | Diagnostic context passed to reflection. Pass the file path when you have one; most lexer and parser diagnostics name it, but some retained reflection and layout errors (for example `VGPU-WGSL-REFLECT-BOOL-HOST-SHAREABLE`) omit it from their message.                                                                                                                                                                                                   |

**Returns:** `ShaderSource` — a new, deeply frozen plain-data object that is JSON- and `structuredClone`-safe; optional properties are omitted rather than set to `undefined`. The root, `reflection`, every nested object and array, `functionExports`, and each `parameterNames` array are frozen, so assigning to any of them throws in strict mode. Its fields:

* `version: 2` — artifact format version, independent of package versions.
* `wgsl` — the exact input string, unmodified.
* `reflection` — `ShaderReflection` for that string: every binding, entry point, override, required feature, alias, struct, and host-shareable layout that `reflectSource()` reports. Every entry point has `bindings` and `samplingPairs` arrays, including unselected entries.
* `sourceChecksum` — `"fnv1a64-utf16le-v1:"` followed by 16 lowercase hex digits.
* `producer` — `"@vgpu/wgsl/prepare-v2"`.
* `functionExports` — copied from the object input when present; absent for string input and when the input omits it.

**Throws:**

* `VGPU-SHADER-SOURCE-INVALID` when `source` is neither a string nor an object with an own string `wgsl` data property, when `path` is not a nonempty string, or when a present `functionExports` is not an array of valid function-export records (including accessor-backed fields and explicit `undefined`) — pass plain data with the documented shape and omit `functionExports` when unavailable.
* `VGPU-WGSL-REFLECT-SOURCE-IMPORT` when the WGSL contains a top-level `import` — `prepareShader()` reflects one module, not an import graph. Import the file through the Vite/webpack loader, or call `resolveShader()` (`@vgpu/wgsl/runtime`) and prepare its result.
* The existing `VGPU-WGSL-*` lexer, parser, and reflection diagnostics for malformed WGSL or invalid host-shareable layouts, unchanged by preparation — fix the WGSL the diagnostic reports. `path` is supplied as diagnostic context, but individual reflection and layout errors may not include it.

## Examples

```ts
import { prepareShader } from "@vgpu/wgsl/prepare";

const particleShader = prepareShader(
  `
@group(0) @binding(0) var<storage, read_write> particles: array<vec4f>;

@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3u) {
  particles[id.x] += vec4f(0.0, -0.01, 0.0, 0.0);
}
`,
  "shaders/particles.wgsl", // diagnostics name this path instead of "<runtime>"
);

console.log(particleShader.version, particleShader.producer); // 2 "@vgpu/wgsl/prepare-v2"
console.log(particleShader.reflection.entryPoints[0]?.workgroupSize); // [64, 1, 1]
```

Prepare runtime WGSL once, then pass the artifact to the renderer. This is the migration for code that used to pass a raw string to `effect`, `draw`, or `compute`:

```ts
import { effect, init } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const pulseSource = `
@group(0) @binding(0) var<uniform> time: f32;

@fragment
fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, 0.5 + 0.5 * sin(time), 1.0);
}
`;

// Before: effect(gpu, pulseSource)
const pulseEffect = effect(gpu, prepareShader(pulseSource)); // prepare once, outside the frame loop
```

Prepare resolver output from its final `wgsl` and `functionExports`. `prepareShader()` reflects `resolved.wgsl` again and ignores `resolved.reflection`, which can describe the source before identifier minification:

```ts
import { resolveShader } from "@vgpu/wgsl/runtime";
import { prepareShader } from "@vgpu/wgsl/prepare";

const entry = "src/shaders/scene.wgsl";
const resolved = await resolveShader({ entry, validate: "off", minify: true });

const sceneShader = prepareShader(resolved, entry); // keeps resolved.functionExports
```

Upgrade a legacy v1 asset. The object form keeps its function-export metadata and discards the old version:

```ts
import type { ShaderFunctionExport, ShaderSource } from "@vgpu/wgsl";
import { prepareShader } from "@vgpu/wgsl/prepare";

interface LegacyShaderAsset {
  readonly version: 1;
  readonly wgsl: string;
  readonly functionExports?: readonly ShaderFunctionExport[];
}

function upgradeShaderAsset(asset: LegacyShaderAsset, assetPath: string): ShaderSource {
  return prepareShader(asset, assetPath); // version 1 is ignored; functionExports is copied
}
```

Prepare in a build script to keep the parser out of the browser. The output is ordinary JSON:

```ts
import { readFile, writeFile } from "node:fs/promises";
import { prepareShader } from "@vgpu/wgsl/prepare";

const shaderPath = "src/shaders/post.wgsl";
const postShader = prepareShader(await readFile(shaderPath, "utf8"), shaderPath);

await writeFile("src/shaders/post.shader.json", JSON.stringify(postShader));
```

## Notes

* **Parser cost.** `prepareShader()` runs the full WGSL scanner, parser, and reflection. Importing `@vgpu/wgsl/prepare` from browser code bundles all of it into that consumer. For static shaders, import `.wgsl` files through the Vite/webpack loader or ship prebuilt artifacts: the renderer then reads the prepared metadata and never loads the parser.
* **Placement.** `prepareShader()` keeps no cache — every call reparses and returns a new artifact. Prepare once per source revision, outside `frame(gpu)` and `frameLoop(gpu)` callbacks, and reuse that one artifact for every `draw`/`effect`/`compute` built from that source.
* **Frozen, so validated once.** Every `prepareShader()` result is deeply frozen, so the renderer validates it the first time it sees it and later `draw`/`effect`/`compute` calls with the same artifact reuse that snapshot. Copies such as `structuredClone`, a JSON round trip, or `{ ...shader }` are valid but mutable, and are revalidated on every call. The cache holds artifacts weakly and changes nothing about GPU resource disposal; the full rules are in `ShaderSource`.
* **Exact-source reflection only.** `prepareShader()` does not resolve imports, minify, compile a native shader module, or acquire a GPU device. It is synchronous and works without WebGPU. Errors that only the native WGSL compiler detects still surface when the renderer creates the shader module.
* **Workgroup sizes.** An axis the reflection reads as a plain numeric literal stays a number, even when the device will later reject it; device limits are not checked here. Any other axis — a named `const` or `override`, or a suffixed literal such as `64u` — is serialized as `"unresolved"` and left to native pipeline validation. Omitted axes are `1`.
* **Metadata trust limits.** `sourceChecksum` is FNV-1a 64 over the UTF-16 code units of `wgsl` with no normalization, so `\r\n` and `\n` sources differ. It detects accidental replacement of the `wgsl` text after preparation. It does not authenticate the artifact, prove that `reflection` matches the WGSL, or detect a stale artifact whose fields are internally consistent. Trust artifacts from supported producers — this helper and the vgpu Vite/webpack loaders — and regenerate them whenever the source or the tooling version changes. Do not hand-write or hand-edit `reflection`.
* **`producer` and `version`.** `producer` names the implementation and format (`"@vgpu/wgsl/prepare-v2"`), not a package release. The renderer checks compatibility by `version`; record package versions separately if you need provenance.
* **Renderer rejection.** `draw`, `effect`, and `compute` accept only prepared artifacts. They throw `VGPU-SHADER-SOURCE-UNPREPARED` for a raw string or a v1 artifact, `VGPU-SHADER-SOURCE-VERSION` for an unsupported `version`, and `VGPU-SHADER-SOURCE-INVALID` for missing or malformed fields or a checksum mismatch — rebuild with compatible tooling, or call `prepareShader()`.
* **Output stays unpacked.** `prepareShader()` always returns the full plain object described under Returns — no compact tables, shared records, or decoder imports — so `JSON.stringify` and `structuredClone` copy it completely. Only the Vite/webpack loaders may emit large metadata compactly, and their generated module's default export still evaluates to the same v2 value that `prepareShader({ wgsl, functionExports })` returns for the final WGSL.
* **Loader defaults and earlier diagnostics.** The Vite/webpack loaders prepare every `.wgsl` module — ordinary leaves with `functionExports: []`, import graphs and direct exports from the resolver's final WGSL — and emit a module with no parser import whose default export is that prepared artifact. Ordinary leaves used to ship without reflection, so reflection-detectable parse and layout errors in them (for example a `bool` in a uniform struct) that previously surfaced at runtime now fail the build. Reflection is not device validation: errors only the native WGSL compiler detects still ship; gate them with `npx vgpu check --require-validation`.
* **What does not migrate.** `reflectSource()` (`@vgpu/wgsl/reflect-source`) and `compile()` (`@vgpu/wgsl`) keep their existing string contracts — `compile()` still returns the same `ResolvedShader`, which is not a renderer input — and raw strings passed to a native `device.createShaderModule({ code })` are unaffected. `vgpu/three` keeps accepting raw strings, structural `{ wgsl, functionExports }` objects, and v1 artifacts.
* Do not call `prepareShader(source)` inside a frame callback. When the WGSL or its metadata changes, prepare a new artifact (call `prepareShader()` again, or rebuild through the loader) instead of editing an existing one; never edit `reflection` by hand. A new artifact is a new identity, so it is validated once on its own first use.
* **See also:** `ShaderSource`, `ShaderReflection`, `ShaderFunctionExport`, `reflectSource` (`@vgpu/wgsl/reflect-source`), `resolveShader` (`@vgpu/wgsl/runtime`), `wgslVitePlugin` (`@vgpu/wgsl/loader-vite`), `wgslWebpackLoader` (`@vgpu/wgsl/loader-webpack`).


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: reflectSource
description: Reflects one raw WGSL string — bindings, entry points, structs, aliases, overrides, and host-shareable layouts — through the same scanner/parser/reflection path `resolveShader()` uses internally. Use it when you already have a single, import-free WGSL string you built or loaded yourself and want reflection data without resolving an import graph. A loader-emitted `ShaderSource` already carries this reflection in its `reflection` field; to hand a string to `draw`, `effect`, or `compute`, call `prepareShader()` (`@vgpu/wgsl/prepare`), which stores the same reflection in a `ShaderSource`.
---

# reflectSource



## Import

```ts
import { reflectSource } from "@vgpu/wgsl/reflect-source";
import type { EntryPointInfo, Reflection } from "@vgpu/wgsl/reflect-source";
```

## Signature

```ts
declare function reflectSource(wgsl: string, path?: string): Reflection;

interface Reflection {
  readonly bindings: readonly BindingInfo[];
  readonly entryPoints: readonly EntryPointInfo[];
  readonly overrides: readonly OverrideInfo[];
  readonly featuresRequired: readonly string[];
  readonly aliases: readonly AliasInfo[];
  readonly structs: readonly StructInfo[];
  readonly hostShareableLayouts: readonly HostShareableLayout[];
}

interface EntryPointInfo {
  readonly name: string;
  readonly mangledName: string;
  readonly stage: "vertex" | "fragment" | "compute";
  readonly workgroupSize?: readonly [number, number, number];
  readonly inputs?: readonly EntryPointInputInfo[];
  readonly bindings?: readonly BindingRef[];
  readonly samplingPairs?: readonly SamplingPair[];
}

interface BindingRef {
  readonly group: number;
  readonly binding: number;
}
```

`Reflection` also re-exports the supporting types used by its fields: `BindingInfo`, `BindingKind`,
`AddressSpace`, `AccessMode`, `StructInfo`, `StructMemberInfo`, `AliasInfo`, `OverrideInfo`,
`EntryPointInputInfo`, `SamplingPair`, `HostShareableLayout`, `LayoutMember`, `LayoutMode`,
`ReflectedBindingLayout`, and `WGSLType` — all importable from `@vgpu/wgsl/reflect-source`.
`ReflectionFacade` is a deprecated alias kept for backwards compatibility with the pre-#252 name;
prefer `Reflection`.

## Parameters

| Param | Type   | Required | Default       | Notes                                                                                                                               |
| ----- | ------ | -------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| wgsl  | string | ✔        | —             | A single WGSL module as text. Must not contain top-level `import` — `reflectSource()` reflects one raw string, not an import graph. |
| path  | string | ✖        | `"<runtime>"` | Label attached to diagnostics/positions for this string. Purely cosmetic when you have no real file path.                           |

**Returns:** `Reflection` — the same plain-data shape `resolveShader()` exposes as `ResolvedShader.reflection`: `bindings` (every `@group/@binding` declaration), `entryPoints` (every `@vertex`/`@fragment`/`@compute` function), `overrides`, `featuresRequired`, `aliases`, `structs`, and `hostShareableLayouts` (CPU-memory layout for uniform/storage types).

**Throws:** `VGPU-WGSL-REFLECT-SOURCE-IMPORT` when `wgsl` contains a top-level `import` — `reflectSource()` intentionally rejects WGSL import graphs. Use `resolveShader()` (`@vgpu/wgsl/runtime`) instead, which resolves imports first and exposes the identical `Reflection` shape on `ResolvedShader.reflection`.
**Throws:** The same lexer/parser `VGPU-WGSL-LEX-*`/`VGPU-WGSL-*` diagnostics `resolveShader()` raises for malformed WGSL (unterminated comments/strings, non-ASCII identifiers, etc.) — fix the WGSL reported by the diagnostic.

## Examples

```ts
import { reflectSource } from "@vgpu/wgsl/reflect-source";

const reflection = reflectSource(`
@group(0) @binding(0) var<uniform> scale: f32;

@fragment
fn fs_main() -> @location(0) vec4f {
  return vec4f(scale);
}
`);

console.log(reflection.entryPoints[0]?.name); // "fs_main"
console.log(reflection.bindings[0]?.group, reflection.bindings[0]?.binding); // 0 0
```

```ts
import { reflectSource, type EntryPointInfo } from "@vgpu/wgsl/reflect-source";

const reflection = reflectSource(`
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) id: vec3u) {}
`);

const entry: EntryPointInfo = reflection.entryPoints[0]!;

// EntryPointInfo is plain data: JSON.stringify, spread, and Object.keys all see the
// complete shape — nothing is hidden behind a getter, a class instance, or a toJSON hook.
const json = JSON.stringify(entry);
const copy = { ...entry };
const keys = Object.keys(entry);

console.log(json.includes("\"stage\":\"compute\""), copy.stage, keys);
```

```ts
import { reflectSource } from "@vgpu/wgsl/reflect-source";

// Serialization survives a structured clone / worker postMessage boundary too — no `toJSON`
// hook runs, so the clone has exactly the same enumerable own keys as the original.
const reflection = reflectSource("@fragment\nfn fs_main() -> @location(0) vec4f { return vec4f(1.0); }");
const cloned = structuredClone(reflection.entryPoints[0]);
console.log(Object.keys(cloned!).length === Object.keys(reflection.entryPoints[0]!).length);
```

## Notes

* Every `HostShareableLayout` uses `layoutMode: "wgsl-host-shareable-v1"` and reports intrinsic WGSL alignment, size, member offsets, array stride, and matrix stride. A layout does not contain an address space: read `BindingInfo.addressSpace` for `uniform` versus `storage`. Address-space validation may reject a use, but never changes its reflected bytes.
* **Serialization contract (issue [#252](https://github.com/vercel-labs/vgpu/issues/252)):** every field of `EntryPointInfo` — and of `Reflection` as a whole — is an ordinary enumerable, own, writable property. `JSON.stringify`, `{ ...entry }`, `Object.keys`/`Object.entries`/`Object.assign`, `structuredClone`, and worker `postMessage` all see the complete shape. There is no `toJSON` hook and no hidden/non-enumerable metadata. `workgroupSize`, `inputs`, `bindings`, and `samplingPairs` are simply *absent* (not present as an `undefined`-valued key) when they do not apply, so the key set stays identical across a serialization boundary — an own key valued `undefined` would survive `structuredClone` but get dropped by `JSON.stringify`, which would otherwise make the two disagree.
* `Reflection` and `EntryPointInfo` are the **frozen/stable** reflection shapes: this is the same interface `ResolvedShader.reflection` exposes from `resolveShader()` (`@vgpu/wgsl/runtime`), not a different or looser one. Do not confuse this with `ResolvedShader.entryPoints` from the top-level `@vgpu/wgsl` `compile()` (`npx vgpu docs cat /@vgpu/wgsl/resolved-shader.docs.md`) — that is an unrelated, older, and much simpler `readonly string[]` of matched entry-point names with no bindings/stage/inputs. `reflectSource()`/`resolveShader()`'s `EntryPointInfo[]` is the one to reach for whenever you need stage, workgroup size, vertex inputs, or bound resources.
* `reflectSource()` only accepts a single raw WGSL string with no imports. If your WGSL imports other modules, call `resolveShader()` (`@vgpu/wgsl/runtime`) instead and read `.reflection` off the result — it walks the same scanner/parser/`ReflectionFacade` path and returns the identical `Reflection` shape.
* `bindings`/`samplingPairs` on an `EntryPointInfo` are scoped to that entry point and its transitive callees (a conservative "used by the whole module" fallback applies when static analysis cannot prove otherwise); `Reflection.bindings` at the top level lists every declared `@group/@binding` in the module regardless of which entry points use it.
* `ShaderReflection` (`ShaderSource.reflection`) is this `Reflection` with every entry point's `bindings` and `samplingPairs` always present and non-literal workgroup axes serialized as `"unresolved"`. `reflectSource()` itself is unchanged and keeps returning `Reflection`.
* **See also:** `prepareShader` (`@vgpu/wgsl/prepare`), `ShaderReflection`, `ResolvedShader` (`compile()`, `@vgpu/wgsl`), `resolveShader` (`@vgpu/wgsl/runtime`).


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: resolveShader
description: Loads a WGSL entry module, resolves vgpu WGSL imports, enforces pure imported modules, and emits one plain WGSL string. Use it in build/setup/tooling code when shader source is split across files or in-memory modules.
---

# resolveShader



## Import

```ts
import { resolveShader } from "@vgpu/wgsl/runtime";
import type { ResolveOptions, ResolvedShader } from "@vgpu/wgsl/runtime";
```

## Signature

```ts
import type { ResolvedShader } from "@vgpu/wgsl/runtime";

interface ResolveOptions {
  readonly entry: string;
  readonly rootDir?: string;
  readonly packageMap?: Record<string, string>;
  readonly modules?: Record<string, string>;
  readonly onDependency?: (path: string) => void;
  readonly validate?: "off" | "auto" | "require" | boolean;
  readonly minify?: boolean | { readonly whitespace?: boolean; readonly identifiers?: "none" | "safe" };
}

declare function resolveShader(opts: ResolveOptions): Promise<ResolvedShader>;
```

## Parameters

| Param             | Type                     | Required        | Default                                                                | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |                                                                                                                                                                                                                  |                                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |        |                                                                                                                                                                                                                                                           |
| ----------------- | ------------------------ | --------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| opts.entry        | string                   | ✔               | —                                                                      | Entry WGSL module path. With `modules`, it is canonicalized against the virtual module map; without `modules`, it is resolved on disk and may omit `.wgsl` when a matching file or `index.wgsl` exists. The entry may declare `@group/@binding` resources.                                                                                                                                                                                                                                                               |                                                                                                                                                                                                                  |                                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |        |                                                                                                                                                                                                                                                           |
| opts.rootDir      | string                   | ✖               | `dirname(entry)` for cache-key grouping; no `@/` alias unless provided | Base directory for `@/foo.wgsl` imports. Also used as the default root passed to cache key generation when present.                                                                                                                                                                                                                                                                                                                                                                                                      |                                                                                                                                                                                                                  |                                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |        |                                                                                                                                                                                                                                                           |
| opts.packageMap   | `Record<string, string>` | ✖               | `{}`                                                                   | Prefix map for package-style WGSL imports. If a specifier starts with a key, the target prefix is joined with the remainder.                                                                                                                                                                                                                                                                                                                                                                                             |                                                                                                                                                                                                                  |                                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |        |                                                                                                                                                                                                                                                           |
| opts.modules      | `Record<string, string>` | ✖               | filesystem reads                                                       | In-memory WGSL filesystem. Keys are normalized with `/`; relative imports use virtual paths and package imports require `packageMap`.                                                                                                                                                                                                                                                                                                                                                                                    |                                                                                                                                                                                                                  |                                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |        |                                                                                                                                                                                                                                                           |
| opts.onDependency | `(path: string) => void` | ✖               | no callback                                                            | Called once for each imported module as soon as its path resolves, before it is read or parsed; already-loaded modules and the entry are omitted. When filesystem import resolution fails, also reports the missing candidate paths (including `.wgsl` and `index.wgsl` alternatives for extensionless imports) before throwing, so build tools can watch for file creation. In-memory resolution does not report missing filesystem candidates. Previously discovered dependencies are retained if a later step throws. |                                                                                                                                                                                                                  |                                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |        |                                                                                                                                                                                                                                                           |
| opts.validate     | \`"off"                  | "auto"          | "require"                                                              | boolean\`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | ✖                                                                                                                                                                                                                | `"auto"`, or `VGPU_VALIDATE` when set | Device-backed validation of emitted WGSL (`createShaderModule` plus a compilation-info round trip) through a lazily imported `@vgpu/adapter-node`. `"auto"` attempts validation and throws `VGPU-WGSL-NAGA-UNKNOWN` for invalid WGSL, but when no device/adapter is available it warns once to stderr and continues, recording the skip on `ResolvedShader.validation`. `"require"` (or `true`) throws `VGPU-WGSL-VALIDATE-NO-DEVICE`/`VGPU-WGSL-VALIDATE-ADAPTER-MISSING` instead of skipping. `"off"` (or `false`) never attempts validation and never imports device code. An explicit value here always wins over `VGPU_VALIDATE` (\`"off" | "auto" | "require"`; anything else throws `VGPU-WGSL-VALIDATE-ENV-INVALID`). Independent of this option, `minify`with`identifiers: "safe"` always self-checks that renaming left no dangling reference (`VGPU-WGSL-MINIFY-DANGLING-IDENT\`), with no GPU involved. |
| opts.minify       | \`boolean                | MinifyOptions\` | ✖                                                                      | `false`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  | `true` means `{ whitespace: true, identifiers: "safe" }`; object form defaults to `{ whitespace: true, identifiers: "none" }`; `false` or omitted preserves whitespace/comments after resolver emission and DCE. |                                       |                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |        |                                                                                                                                                                                                                                                           |

Validation always covers the WGSL you get back. When `minify` rewrites the emitted text, validation runs twice: first on the unminified emission, because that text is what gives diagnostics accurate line/column mapping back to your modules, and then on the final minified string. So a successful resolve with `validation.ok === true` means the exact `wgsl` returned was accepted by the device — a minifier bug cannot slip corrupt output past a passing validation. Both passes share the same leased device, and the second one is skipped when minification changed nothing (the returned text was already validated).

Validation acquires one WebGPU device per process through `@vgpu/adapter-node` and reuses it across calls, then destroys it shortly after the last validation finishes — a live device holds handles on the Node event loop, so without that release a script that validated a shader would never exit on its own. A later `resolveShader` transparently acquires a new device; a *failed* acquisition is remembered and **not retried for the lifetime of the process**, so after installing a device (for example `npx vgpu install-software-renderer`) restart the process rather than expecting the next call to pick it up.

**Returns:** `Promise<ResolvedShader>` — resolved WGSL plus `functionExports`, dependency paths, cache keys, lightweight AST modules, source map, diagnostics, reflection for entry points/resources, and `validation: { mode, attempted, ok, skipped? }` reporting what the device-backed check actually did (`skipped` carries the `code`, `message`, and `fix` when `"auto"` could not get a device). `functionExports` is always present and records each surviving direct `export fn` as `{ name, resolvedName, parameterNames }`.

**Throws:** `VGPU-RESOLVE-MODULE-BINDING` when a non-entry imported module declares any `@group(...)` or `@binding(...)` resource — move the resource declaration into the entry module and export only structs/functions from the module. The error message is exactly:

```text
VGPU-RESOLVE-MODULE-BINDING: <module> declares '@group(<group>) @binding(<binding>) <name>'.
Modules cannot declare bindings — export the struct and declare it in your entry:
  export struct NoiseConfig { seed: u32 }
  // in your entry: @group(0) @binding(0) var<uniform> cfg: NoiseConfig;
```

**Throws:** `VGPU-WGSL-RES-ABS` when an import specifier starts with `/` — use a relative, `@/`, or package import.
**Throws:** `VGPU-WGSL-RES-NOTFOUND` when the entry/import path or virtual module cannot be found, or when an import path token is not a string — add the module, fix the spelling, or add `.wgsl`/`index.wgsl`.
**Throws:** `VGPU-WGSL-PKG-NOTFOUND` when a package or package export cannot be found. WGSL package imports resolve through `node_modules` exactly like JavaScript imports, so the message names the package and the fix:

```text
Package @vgpu/wgsl-std was not found. Install the package (npm install @vgpu/wgsl-std) or check the specifier
```

With `modules` (in-memory resolution) `node_modules` is never consulted, so the same code reports `Map it with packageMap or add the module to modules`. An unknown subpath reports `Package export ./missing was not found in <pkg>. Check the package's exports map or fix the import subpath`.

Package specifiers resolve in two steps: first by walking `node_modules` up from the importing file, so a copy in the project always wins; then, only if that fails, through Node's own resolver next to `@vgpu/wgsl`. The second step is what lets a package that reaches the project transitively — `@vgpu/wgsl-std` through `vgpu`, for example — resolve under pnpm's isolated `node_modules` and Yarn PnP, where it is installed but absent from the project's own tree.
**Throws:** `VGPU-WGSL-IMP-SELF` when the graph contains an import cycle — break the cycle.
**Throws:** `VGPU-WGSL-IMP-ORDER` when an `import` appears after declarations — move imports before declarations.
**Throws:** `VGPU-WGSL-IMP-SIDEEFFECT` for `import "x"` — import named symbols or a namespace.
**Throws:** `VGPU-WGSL-IMP-DEFAULT` for default import syntax or malformed import bindings — use `import { name } from "..."` or `import * as ns from "..."`.
**Throws:** `VGPU-WGSL-EXP-REEXPORT-CYCLE` for `export { ... }` re-export syntax — export declarations directly.
**Throws:** `VGPU-WGSL-EXP-NOTDECL` for invalid export attributes or exported declarations without a name — attach `export` to a declaration.
**Throws:** `VGPU-WGSL-SYM-NOEXPORT` when an imported binding is not exported by the target module — export it or fix the import name.
**Throws:** `VGPU-WGSL-SYM-IMPORT-SHADOW` when imports conflict with each other or shadow locals — rename with `as` or rename the local declaration.
**Throws:** `VGPU-WGSL-OVERRIDE-DUP` or `VGPU-WGSL-ENTRYPOINT-DUP` when JavaScript-visible override or entry-point names appear in multiple modules — rename one declaration.
**Throws:** `VGPU-WGSL-MANGLE-COLLISION` when canonical path hashes collide — rename one directory in either path.
**Throws:** `VGPU-WGSL-NS-NOTVALUE` or `VGPU-WGSL-NS-NOMEMBER` for invalid namespace use — access exported namespace members directly.
**Throws:** `VGPU-WGSL-MINIFY-IDENTIFIERS` when `minify.identifiers` is not `"none"` or `"safe"` — pass a valid mode.
**Throws:** `VGPU-WGSL-MINIFY-BLOCK`, `VGPU-WGSL-LEX-UNTERM-COMMENT`, or `VGPU-WGSL-LEX-UNTERM-STRING` for unterminated WGSL comments/strings during scanning/minification — close the token.
**Throws:** `VGPU-WGSL-IDENT-NONASCII` when an identifier in any resolved module contains a non-ASCII character (`let Ω = 1.0;`, `fn åhelper()`, `let café = 1.0;`) — rename it using ASCII letters, digits and `_`. WGSL itself allows Unicode (XID) identifiers; vgpu does not yet, and rejects them in the scanner so no path can half-support them (support is tracked in [issue #294](https://github.com/vercel-labs/vgpu/issues/294)). The diagnostic names the identifier and carries `line`/`column` plus `range.file` for the module that declared it. Non-ASCII text in **comments**, in string literals and in import paths stays legal, as does a leading byte-order mark; only code positions are rejected.
**Throws:** `VGPU-WGSL-NAGA-UNKNOWN` when validation is active (`"auto"` or `"require"`) and WebGPU/Naga rejects emitted WGSL — fix the WGSL reported by the diagnostic.
**Throws:** `VGPU-WGSL-VALIDATE-NO-DEVICE` in `"require"` mode when `@vgpu/adapter-node` cannot acquire a device — the error forwards adapter-node's own `fix` (and `metadata.causeCode`); run `npx vgpu doctor`, or use `"auto"`/`"off"` on machines without a GPU.
**Throws:** `VGPU-WGSL-VALIDATE-ADAPTER-MISSING` in `"require"` mode when `@vgpu/adapter-node` (an optional peer dependency) cannot be imported — install it (`pnpm add -D @vgpu/adapter-node`), or pass `validate: "off"`.
**Throws:** `VGPU-WGSL-VALIDATE-ENV-INVALID` when `VGPU_VALIDATE` is set to anything other than `off`, `auto`, or `require` — unset it or use one of those values.

**Diagnostic:** `VGPU-WGSL-RESERVED-IDENT` (severity `error`, never thrown) for every declared identifier that WGSL reserves — struct names, struct members, type aliases, module-scope variables, overrides, functions, parameters, and local variables. Each diagnostic carries the offending name, `line`/`column`, and a `range` pointing at the source module. Rename the declaration; Dawn/Tint would otherwise reject the shader only at pipeline creation.

## Examples

```ts
import { resolveShader } from "@vgpu/wgsl/runtime";

const resolved = await resolveShader({
  entry: "/entry.wgsl",
  validate: false,
  modules: {
    "/math.wgsl": `
export fn tint(value: vec3f) -> vec3f {
  return value * vec3f(1.0, 0.5, 0.25);
}
`,
    "/entry.wgsl": `
import { tint } from "./math.wgsl";

@fragment
fn fs_main() -> @location(0) vec4f {
  return vec4f(tint(vec3f(1.0)), 1.0);
}
`,
  },
});

console.log(resolved.wgsl.includes("fs_main"));
console.log(resolved.functionExports);
```

```ts
import { resolveShader } from "@vgpu/wgsl/runtime";

const resolved = await resolveShader({
  entry: "/entry.wgsl",
  validate: false,
  minify: { whitespace: true },
  modules: {
    "/types.wgsl": `
export struct NoiseConfig { seed: u32 }
export fn noise(cfg: NoiseConfig) -> f32 { return f32(cfg.seed); }
`,
    "/entry.wgsl": `
import { NoiseConfig, noise } from "./types.wgsl";

@group(0) @binding(0) var<uniform> cfg: NoiseConfig;

@fragment
fn fs_main() -> @location(0) vec4f {
  return vec4f(noise(cfg));
}
`,
  },
});

console.log(resolved.deps.length);
```

## Notes

* Imported modules are pure: no `@group`/`@binding` in any non-entry module. Export structs, aliases, constants, and functions from modules; declare uniforms/storage/textures/samplers only in the entry.
* `resolveShader()` is for setup, tests, loaders, and build tooling. Do not call it per frame; resolve and create pipelines off the render hot path.
* Declaration-level DCE always runs before validation/minification when entry points exist. There is no DCE opt-out in this release.
* `functionExports` is produced after DCE. It includes every surviving direct function export across the resolved graph, retains authored function and parameter names, and points `resolvedName` at the exact declaration in final WGSL after mangling and safe identifier minification. Import aliases are not exports, duplicate authored names remain separate entries, and the metadata never roots otherwise-dead declarations.
* Pass the complete `ResolvedShader` to consumers that need authored identity, such as `tslExports()` from `vgpu/three`. Passing only `.wgsl` discards the authored-to-minified mapping.
* `minify: true` is the production preset. Safe identifier minification is conservative and does not rename entry points, resources, overrides, structs, fields, import/export names, attributes, builtins, or predeclared WGSL names.
* Reserved-word diagnostics are collected per loaded module before emission, so imported modules report their own file/line. `import`/`export`/`from`/`as` module syntax is exempt; only declared identifiers are checked.
* Validation maps diagnostics back to generated module headers. Columns can be approximate when substituted identifiers appear; those diagnostics include `VGPU-WGSL-COL-APPROX` metadata.
* **`wgslWebpackLoader` and `wgslVitePlugin` always pass `validate: false` and expose no `validate` option** — the bundler build never runs this device-backed check, for leaf files or import graphs. They do parse and reflect every module to prepare it, so parse and reflection errors fail the build. `opts.validate` above only takes effect when you call `resolveShader()` yourself (setup scripts, tests, tooling) or through the CLI. The gate for a Next.js/Vite app is `npx vgpu check --require-validation <file>` run in CI or pre-commit, not the dev server or the production build. See `wgslWebpackLoader`, `wgslVitePlugin`, and `npx vgpu docs cat cli.docs.md`.
* **Works from ESM and CommonJS:** the `./runtime` subpath's `exports` map in `@vgpu/wgsl` declares both an `import` and a `require` condition, both pointing at the same ESM file. `import { resolveShader } from "@vgpu/wgsl/runtime"` works as expected, and so does `const { resolveShader } = require("@vgpu/wgsl/runtime")` from a plain CommonJS entry point (no `"type": "module"`, no `.mjs`/`.mts` rename needed) — Node resolves the `require` condition and loads the ESM file through its native `require(esm)` support. See the [no-bundler guide](/docs/guides/no-bundler) for the full script-from-disk workflow.
* To render the result, pass it to `prepareShader(resolved, entry)` from `@vgpu/wgsl/prepare`; `draw`, `effect`, and `compute` do not accept a `ResolvedShader` or its `.wgsl` string. `prepareShader()` reflects `resolved.wgsl` again and copies `functionExports`.
* **See also:** `compile`, `ShaderSource`, `prepareShader` (`@vgpu/wgsl/prepare`), `wgslVitePlugin`, `wgslWebpackLoader`, `@vgpu/wgsl-std/hash`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: ResolvedShader and ShaderSource
description: Data shapes returned or consumed by the WGSL helpers. Use `ShaderSource` for the prepared shader artifacts that `draw`, `effect`, and `compute` consume, `ShaderReflection` for the metadata inside them, `ResolvedShader` for `compile()` output, and `isShaderFunctionExport()` to check unknown function-export metadata at an integration boundary.
---

# ResolvedShader and ShaderSource



## Import

```ts
import { isShaderFunctionExport } from "@vgpu/wgsl";
import type {
  ResolvedShader,
  ShaderFunctionExport,
  ShaderReflection,
  ShaderSource,
  SourceMap,
  WGSLAst,
  WGSLSource,
} from "@vgpu/wgsl";
```

`vgpu`, `vgpu/node`, `vgpu/mock`, and `vgpu/client` re-export `ShaderSource`, `ShaderReflection`, and `ShaderFunctionExport` as the same types.

## Signature

```ts
import type { EntryPointInfo, Reflection } from "@vgpu/wgsl/reflect-source";

interface ShaderFunctionExport {
  readonly name: string;
  readonly resolvedName: string;
  readonly parameterNames: readonly string[];
}

declare function isShaderFunctionExport(
  value: unknown,
): value is ShaderFunctionExport;

type ShaderReflection = Omit<Reflection, "entryPoints"> & {
  readonly entryPoints: readonly (Omit<
    EntryPointInfo,
    "workgroupSize" | "bindings" | "samplingPairs"
  > & {
    readonly workgroupSize?: readonly [
      number | "unresolved",
      number | "unresolved",
      number | "unresolved",
    ];
    readonly bindings: NonNullable<EntryPointInfo["bindings"]>;
    readonly samplingPairs: NonNullable<EntryPointInfo["samplingPairs"]>;
  })[];
};

interface ShaderSource {
  readonly version: 2;
  readonly wgsl: string;
  readonly reflection: ShaderReflection;
  readonly sourceChecksum: string;
  readonly producer: string;
  readonly functionExports?: readonly ShaderFunctionExport[];
}

interface WGSLSource {
  readonly text: string;
  readonly path?: string;
  readonly imports?: readonly { readonly path: string; readonly from: string }[];
}

interface SourceMap {
  readonly version: 1;
  readonly mappings: readonly [];
}

interface WGSLAst {
  readonly version: 1;
  readonly modules: readonly [{ readonly path: string; readonly text: string }];
  readonly diagnostics: readonly [];
  readonly sourceMap: SourceMap;
  readonly cacheKey: Record<string, string>;
}

interface ResolvedShader {
  readonly kind: "wgsl";
  readonly wgsl: string;
  readonly source: WGSLSource;
  readonly ast: WGSLAst;
  readonly sourceMap: SourceMap;
  readonly diagnostics: readonly [];
  readonly cacheKey: Record<string, string>;
  readonly entryPoints: readonly string[];
  readonly stats: { readonly lines: number; readonly bytes: number; readonly bindGroups: number };
}
```

## Parameters

`ResolvedShader` fields:

| Param       | Type                                                   | Required | Default | Notes                                                                                                                                                                                                                                                                                                                              |
| ----------- | ------------------------------------------------------ | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| kind        | `"wgsl"`                                               | ✔        | —       | Discriminant for WGSL shader data returned by `compile()`.                                                                                                                                                                                                                                                                         |
| wgsl        | string                                                 | ✔        | —       | Original source string passed to `compile()`.                                                                                                                                                                                                                                                                                      |
| source      | `WGSLSource`                                           | ✔        | —       | Runtime source metadata. `compile()` sets `text` to the input, `path` to `"<runtime>"`, and `imports` to `[]`.                                                                                                                                                                                                                     |
| ast         | `WGSLAst`                                              | ✔        | —       | Lightweight passthrough AST metadata with one runtime module and no diagnostics.                                                                                                                                                                                                                                                   |
| sourceMap   | `SourceMap`                                            | ✔        | —       | Passthrough v1 source map with empty `mappings`.                                                                                                                                                                                                                                                                                   |
| diagnostics | `readonly []`                                          | ✔        | —       | Always empty for `compile()` output.                                                                                                                                                                                                                                                                                               |
| cacheKey    | `Record<string, string>`                               | ✔        | —       | Deterministic FNV-style key in the form `vgpu-wgsl-1:<hash>` under `default`.                                                                                                                                                                                                                                                      |
| entryPoints | `readonly string[]`                                    | ✔        | —       | Names of top-level functions carrying an exact `@vertex`, `@fragment`, or `@compute` attribute, in source order. Other attributes may surround the stage attribute; comments and function bodies are ignored, and Unicode XID names retain their original spelling. This is lexical metadata and does not validate WGSL semantics. |
| stats       | `{ lines: number; bytes: number; bindGroups: number }` | ✔        | —       | Line count, UTF-8 byte length, and `bindGroups: 0`.                                                                                                                                                                                                                                                                                |

### ShaderSource

A prepared shader artifact: one final WGSL module plus the reflection that `draw`, `effect`, and `compute` read bindings, entry points, and layouts from, so the renderer never parses WGSL. The `@vgpu/wgsl` Vite/webpack loaders emit one for every `.wgsl` import at build time; `prepareShader()` from `@vgpu/wgsl/prepare` builds one from a string, a `resolveShader()` result, or a legacy v1 asset. It is plain JSON-compatible data. Artifacts from the loaders and `prepareShader()` are deeply frozen, which lets the renderer validate them once and reuse the result.

```ts
import type { ShaderSource } from "@vgpu/wgsl";
import postShader from "./post.wgsl"; // the loader emits a ShaderSource

const artifact: ShaderSource = postShader;
console.log(artifact.version, artifact.producer); // 2 "@vgpu/wgsl/prepare-v2"
```

Fields:

| Param           | Type                              | Required | Default | Notes                                                                                                                                                                                                     |
| --------------- | --------------------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| version         | `2`                               | ✔        | —       | Artifact format version, independent of package versions. The renderer checks compatibility by this field alone.                                                                                          |
| wgsl            | string                            | ✔        | —       | The exact final WGSL — after import resolution, dead-code elimination, and minification when a loader produced it.                                                                                        |
| reflection      | `ShaderReflection`                | ✔        | —       | Reflection of exactly `wgsl`. Produce it with a supported producer; never hand-write or hand-edit it.                                                                                                     |
| sourceChecksum  | string                            | ✔        | —       | `"fnv1a64-utf16le-v1:"` plus 16 lowercase hex digits: FNV-1a 64 over the UTF-16 code units of `wgsl`, with no normalization.                                                                              |
| producer        | string                            | ✔        | —       | Nonempty name of the implementation and format that built the artifact. The built-in producer is `"@vgpu/wgsl/prepare-v2"`; other nonempty strings are accepted.                                          |
| functionExports | `readonly ShaderFunctionExport[]` | ✖        | absent  | Authoritative identity for surviving direct `export fn` declarations. vgpu loaders always emit the property, including `[]`; `prepareShader()` copies it from object input and omits it for string input. |

### ShaderReflection

The reflection stored in `ShaderSource.reflection`. It is `reflectSource()`'s `Reflection` (`@vgpu/wgsl/reflect-source`) with a serializable entry-point shape, so the artifact survives `JSON.stringify` and `structuredClone` unchanged.

```ts
import type { ShaderReflection } from "@vgpu/wgsl";
import { prepareShader } from "@vgpu/wgsl/prepare";

const reflection: ShaderReflection = prepareShader(`
@group(0) @binding(0) var<storage, read_write> cells: array<u32>;
@compute @workgroup_size(64) fn main() {}
`).reflection;

console.log(reflection.bindings[0]?.name); // "cells"
console.log(reflection.entryPoints[0]?.workgroupSize); // [64, 1, 1]
```

Fields:

| Param                                                                         | Type                                                                                | Required | Default | Notes                                                                                                                                                                                                                                |
| ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| bindings, overrides, featuresRequired, aliases, structs, hostShareableLayouts | as in `Reflection`                                                                  | ✔        | —       | Same shapes and meaning as `reflectSource()` output for the same WGSL.                                                                                                                                                               |
| entryPoints                                                                   | readonly entry-point records                                                        | ✔        | —       | Every `@vertex`, `@fragment`, and `@compute` entry, selected or not. Each keeps `name`, `mangledName`, `stage`, and optional `inputs` from `EntryPointInfo`.                                                                         |
| entryPoints\[].bindings                                                       | `readonly BindingRef[]` (`@vgpu/wgsl/reflect-source`)                               | ✔        | —       | Always present, `[]` when the entry uses no resources. Scoped to the entry and its transitive callees.                                                                                                                               |
| entryPoints\[].samplingPairs                                                  | `NonNullable<EntryPointInfo["samplingPairs"]>`                                      | ✔        | —       | Always present, `[]` when the entry samples nothing.                                                                                                                                                                                 |
| entryPoints\[].workgroupSize                                                  | `readonly [number \| "unresolved", number \| "unresolved", number \| "unresolved"]` | ✖        | absent  | Compute entries only. A plain numeric literal stays a number; an axis reflection cannot read as one — a named `const` or `override`, or a suffixed literal such as `64u` — is `"unresolved"` and left to native pipeline validation. |

### ShaderFunctionExport

Fields:

| Param          | Type                | Required | Default | Notes                                                                                                   |
| -------------- | ------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------- |
| name           | string              | ✔        | —       | Authored direct-export name. Import aliases do not create entries.                                      |
| resolvedName   | string              | ✔        | —       | Exact declaration identifier in final WGSL, after mangling and optional identifier minification.        |
| parameterNames | `readonly string[]` | ✔        | —       | Authored parameter names in declaration order. Types and return values remain in the final WGSL header. |

**Returns:** These are TypeScript interfaces, not callables. They return nothing.

**Throws:** These type declarations throw nothing. `compile()` throws before constructing `ResolvedShader` when runtime WGSL contains a top-level import.

## isShaderFunctionExport

Checks whether one unknown value has the public `ShaderFunctionExport` shape and uses valid WGSL declaration identifiers. Use it when accepting metadata from a third-party loader, serialized data, or another untyped integration. Artifacts produced and consumed entirely by matching vgpu packages normally do not need a separate manual check.

The canonical import belongs to `@vgpu/wgsl`:

```ts
import {
  isShaderFunctionExport,
  type ShaderFunctionExport,
} from "@vgpu/wgsl";

function readFunctionExport(
  value: unknown,
): ShaderFunctionExport | undefined {
  return isShaderFunctionExport(value) ? value : undefined;
}

const metadata = readFunctionExport({
  name: "surfaceColor",
  resolvedName: "a",
  parameterNames: ["position", "timeSeconds"],
});

console.log(metadata?.resolvedName);
```

Applications that already depend on the main package can use its convenience re-export without installing or importing a second package directly:

```ts
import { isShaderFunctionExport } from "vgpu";

const candidate: unknown = {
  name: "surfaceColor",
  resolvedName: "a",
  parameterNames: ["position", "timeSeconds"],
};

if (isShaderFunctionExport(candidate)) {
  console.log(candidate.parameterNames);
}
```

| Param | Type    | Required | Default | Notes                                                                          |
| ----- | ------- | -------- | ------- | ------------------------------------------------------------------------------ |
| value | unknown | ✔        | —       | One possible `ShaderFunctionExport` record. Additional properties are allowed. |

Valid identifiers use ASCII letters, digits, and underscores, cannot be `_` or start with `__`, and cannot be WGSL keywords or reserved words (including the legacy `binding_array` reservation).

**Returns:** `value is ShaderFunctionExport` — `true` only when `name`, `resolvedName`, and every member of `parameterNames` are valid declaration identifiers and parameter names are unique. The predicate narrows `value` for TypeScript.

**Throws:** Nothing. Malformed values, including values whose properties cannot be read, return `false`.

The check is structural and syntactic. It does not parse shader text, prove that `resolvedName` exists in final WGSL, compare parameter or return types, validate arity, validate a surrounding `ShaderSource`, or detect duplicate authored names across multiple export records. Consumer adapters such as `tslExports()` perform the source-specific checks they require after this predicate succeeds.

## Examples

A loader import is already a `ShaderSource`; pass it to the renderer unchanged:

```ts
import { init, effect } from "vgpu";
import vignetteShader from "./vignette.wgsl";

const gpu = await init();
const vignette = effect(gpu, vignetteShader); // no parser in the browser bundle
```

`compile()` returns a `ResolvedShader`, not a renderer input. Prepare its WGSL before passing it to a renderer:

```ts
import { compile, type ResolvedShader, type ShaderSource } from "@vgpu/wgsl";
import { prepareShader } from "@vgpu/wgsl/prepare";

const resolved: ResolvedShader = compile(`
@fragment
fn fs_main() -> @location(0) vec4f {
  return vec4f(1.0, 0.0, 0.0, 1.0);
}
`);

const source: ShaderSource = prepareShader(resolved.wgsl);
console.log(resolved.entryPoints[0], source.reflection.entryPoints[0]?.stage); // "fs_main" "fragment"
```

Accept artifacts at an integration boundary by type, and let the renderer validate them:

```ts
import type { ShaderSource } from "@vgpu/wgsl";

function describeShader(shader: ShaderSource): string {
  const stages = shader.reflection.entryPoints.map((entry) => `${entry.stage}:${entry.name}`);
  return `${shader.producer} v${shader.version} — ${stages.join(", ")}`;
}
```

## Notes

* `ShaderSource` is `version: 2`. Renderers throw `VGPU-SHADER-SOURCE-UNPREPARED` for raw strings and v1 artifacts, `VGPU-SHADER-SOURCE-VERSION` for other integer versions, and `VGPU-SHADER-SOURCE-INVALID` for malformed fields or checksum mismatches. Rebuild with matching tooling/runtime versions, regenerate prebuilt assets, or call `prepareShader()`; object input keeps `functionExports`.
* **Validation and reuse.** The renderer fully validates an artifact (WGSL checksum and reflection) the first time it sees it and keeps its own frozen, device-independent snapshot, never the object you passed. When all consumed data — the artifact object itself, `reflection`, `functionExports`, and every object and array inside them — was already frozen, which holds for loader imports and `prepareShader()` results, later `draw`/`effect`/`compute` calls with the same artifact on any `gpu` reuse that snapshot instead of validating again. Objects reachable only through extra, unconsumed properties need not be frozen. Per-instance labels, `set` values, and binding assignments stay independent; existing GPU caches (pipelines, shader modules, layouts), explicit resource sharing such as a `uniforms()` object bound twice, and GPU resource disposal are unchanged. Artifacts whose consumed data is not entirely frozen, such as a `structuredClone` or JSON copy, an object spread (mutable root), a root-only `Object.freeze`, or a typical hand-built object, are valid but are revalidated on every call and never frozen or retained by vgpu, so mutating them afterwards does not affect existing handles. For those, only the checksum of unchanged `wgsl` text is remembered; the supplied `sourceChecksum` is still compared every time and changed text is rehashed. An invalid artifact throws on every call. The cache keys are weak and do not keep an artifact alive, but a live `draw`/`effect`/`compute` keeps the reflection it uses until its `dispose()` and an imported module can keep its artifact for the session; collection timing is not guaranteed. Import `.wgsl` modules at module level or call `prepareShader()` once per source revision. To change the WGSL or its metadata, prepare or rebuild a new artifact — it is validated once on its first use — and never edit `reflection`. Prepared metadata is trusted, not verified: the checksum detects accidental replacement of `wgsl`, but it does not authenticate the artifact, prove that `reflection` matches `wgsl`, or detect a stale artifact whose fields agree with each other. Regenerate artifacts whenever the source or the tooling version changes.
* `functionExports` is optional in TypeScript so artifacts without direct-export metadata remain assignable, but every vgpu loader artifact emits it. Property presence is authoritative: `[]` exposes no callable direct exports, while absence denotes an artifact without that metadata.
* `functionExports` contains only direct `export fn` declarations that survive graph emission and DCE. It does not root otherwise-dead declarations, publish import aliases, or include source paths.
* `isShaderFunctionExport()` validates declaration identifiers, not the stricter set of names a code generator may choose for minification. Predeclared identifiers remain syntactically valid metadata names.
* `ShaderReflection` is not a different reflection model. Its only differences from `Reflection` are required per-entry `bindings`/`samplingPairs` arrays and the `"unresolved"` workgroup marker; `reflectSource()` and `resolveShader()` keep returning `Reflection`.
* Treat `ResolvedShader` fields as read-only data. Do not patch placeholder AST internals to represent imports; use `resolveShader()` for import graphs.
* `compile()` output does not prove WGSL validity. It only packages the string and rejects top-level `import`.
* Pure-module contract for resolver graphs: imported modules may export structs/functions/constants/aliases, but no imported module may declare `@group/@binding`; declare resources only in the entry module.
* **`entryPoints` here is not reflection.** `ResolvedShader.entryPoints` (this page, `compile()`'s output) is just a lexical `readonly string[]` of entry-point names. It does not validate stage signatures or expose stage, workgroup size, inputs, bindings, or sampling pairs. The reflection `EntryPointInfo[]` returned by `reflectSource()` and by `resolveShader()`'s `ResolvedShader.reflection.entryPoints` (`@vgpu/wgsl/runtime`) carries that semantic metadata. If you need it, reach for `reflectSource` (`npx vgpu docs cat /@vgpu/wgsl/reflect-source/reflect-source.docs.md`) or `resolveShader`, not `compile()`.
* **See also:** `prepareShader` (`@vgpu/wgsl/prepare`), `compile`, `resolveShader`, `reflectSource`, `wgslVitePlugin`, `wgslWebpackLoader`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: bind and explicit binding helpers
description: `bind`, `createBindGroupLayout`, `createPipelineLayout`, `createBindGroup`, and `createSampler` are thin core helpers for explicit WebGPU binding. Use them when you want raw WebGPU layouts, bind groups, and samplers without shader reflection or `layout: "auto"` inference.
---

# bind and explicit binding helpers



## Import

```ts
import { bind, createBindGroup, createBindGroupLayout, createPipelineLayout, createSampler } from "vgpu/core";
```

## Signature

```ts
import type { Buffer, Device, Texture } from "vgpu/core";

type BindVisibility = GPUShaderStageFlags | string | readonly ("vertex" | "fragment" | "compute")[];
type DeviceLike = GPUDevice | Device | { readonly gpu: GPUDevice };

interface CreateBindGroupLayoutOptions {
  readonly label?: string;
  readonly entries: readonly GPUBindGroupLayoutEntry[];
}

interface CreatePipelineLayoutOptions {
  readonly label?: string;
  readonly bindGroups: readonly GPUBindGroupLayout[];
}

interface CreateBindGroupOptions {
  readonly label?: string;
  readonly layout: GPUBindGroupLayout;
  readonly entries: readonly GPUBindGroupEntry[];
}

interface SamplerDescriptorWithSugar extends GPUSamplerDescriptor {
  readonly filter?: "linear" | "nearest";
  readonly wrap?: "clamp" | "repeat" | "mirror";
}

declare function createBindGroupLayout(device: DeviceLike, opts: CreateBindGroupLayoutOptions): GPUBindGroupLayout;
declare function createPipelineLayout(device: DeviceLike, opts: CreatePipelineLayoutOptions): GPUPipelineLayout;
declare function createBindGroup(device: DeviceLike, opts: CreateBindGroupOptions): GPUBindGroup;
declare function createSampler(device: DeviceLike, descriptor?: SamplerDescriptorWithSugar): GPUSampler;

declare const bind: {
  readonly uniform: (binding: number, visibility: BindVisibility, opts?: Omit<GPUBufferBindingLayout, "type">) => GPUBindGroupLayoutEntry;
  readonly storage: (binding: number, visibility: BindVisibility, opts?: Omit<GPUBufferBindingLayout, "type">) => GPUBindGroupLayoutEntry;
  readonly readonlyStorage: (binding: number, visibility: BindVisibility, opts?: Omit<GPUBufferBindingLayout, "type">) => GPUBindGroupLayoutEntry;
  readonly texture: (binding: number, visibility: BindVisibility, opts?: GPUTextureBindingLayout) => GPUBindGroupLayoutEntry;
  readonly storageTexture: (binding: number, visibility: BindVisibility, opts: GPUStorageTextureBindingLayout) => GPUBindGroupLayoutEntry;
  readonly sampler: (binding: number, visibility: BindVisibility, opts?: GPUSamplerBindingLayout) => GPUBindGroupLayoutEntry;
  readonly resource: (binding: number, value: Buffer | Texture | GPUBuffer | GPUBufferBinding | GPUBindingResource | unknown) => GPUBindGroupEntry;
};
```

## Parameters

### Shared parameters

| Param      | Type                                                                                | Required | Default | Notes                                                                                                             |                                                                                                                |
| ---------- | ----------------------------------------------------------------------------------- | -------: | ------- | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| device     | `DeviceLike`                                                                        |        ✔ | —       | A raw `GPUDevice`, a vgpu `Device`, or an object with `.gpu: GPUDevice`. Helpers unwrap it before calling WebGPU. |                                                                                                                |
| binding    | `number`                                                                            |        ✔ | —       | Explicit non-negative integer `@binding(n)`. Invalid values throw `VGPU-CORE-BINDING-INVALID`.                    |                                                                                                                |
| visibility | `GPUShaderStageFlags \| string \| readonly ("vertex" \| "fragment" \| "compute")[]` |        ✔ | —       | Numeric flags pass through. Strings split on \`                                                                   | `, comma, or whitespace. Arrays use stage names directly. Unknown names throw `VGPU-CORE-VISIBILITY-INVALID\`. |

### `createBindGroupLayout(device, opts)`

| Param        | Type                                 | Required | Default     | Notes                                                                                               |
| ------------ | ------------------------------------ | -------: | ----------- | --------------------------------------------------------------------------------------------------- |
| opts         | `CreateBindGroupLayoutOptions`       |        ✔ | —           | Layout descriptor wrapper.                                                                          |
| opts.label   | `string`                             |        ✖ | `undefined` | Forwarded to `GPUDevice.createBindGroupLayout`.                                                     |
| opts.entries | `readonly GPUBindGroupLayoutEntry[]` |        ✔ | —           | Copied with `[...opts.entries]` before calling WebGPU; metadata is attached to the returned layout. |

### `createPipelineLayout(device, opts)`

| Param           | Type                            | Required | Default     | Notes                                                         |
| --------------- | ------------------------------- | -------: | ----------- | ------------------------------------------------------------- |
| opts            | `CreatePipelineLayoutOptions`   |        ✔ | —           | Pipeline layout descriptor wrapper.                           |
| opts.label      | `string`                        |        ✖ | `undefined` | Forwarded to `GPUDevice.createPipelineLayout`.                |
| opts.bindGroups | `readonly GPUBindGroupLayout[]` |        ✔ | —           | Copied to WebGPU as `bindGroupLayouts: [...opts.bindGroups]`. |

### `createBindGroup(device, opts)`

| Param        | Type                           | Required | Default     | Notes                                                                                                                                      |
| ------------ | ------------------------------ | -------: | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| opts         | `CreateBindGroupOptions`       |        ✔ | —           | Bind group descriptor wrapper.                                                                                                             |
| opts.label   | `string`                       |        ✖ | `undefined` | Forwarded to `GPUDevice.createBindGroup`.                                                                                                  |
| opts.layout  | `GPUBindGroupLayout`           |        ✔ | —           | Required explicit layout. Missing/falsy layout throws `VGPU-CORE-BIND-GROUP-LAYOUT-REQUIRED`; vgpu never uses bind group `layout: "auto"`. |
| opts.entries | `readonly GPUBindGroupEntry[]` |        ✔ | —           | Copied with `[...opts.entries]` before calling WebGPU; metadata is attached to the returned bind group.                                    |

### `createSampler(device, descriptor?)`

| Param                    | Type                              | Required | Default        | Notes                                                                                                                                                             |
| ------------------------ | --------------------------------- | -------: | -------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| descriptor               | `SamplerDescriptorWithSugar`      |        ✖ | `{}`           | Raw `GPUSamplerDescriptor` plus vgpu sugar. Sugar is stripped before calling WebGPU.                                                                              |
| descriptor.filter        | `"linear" \| "nearest"`           |        ✖ | `undefined`    | Expands to `magFilter` and `minFilter` only. Raw `magFilter`/`minFilter` override this per key.                                                                   |
| descriptor.wrap          | `"clamp" \| "repeat" \| "mirror"` |        ✖ | `undefined`    | Expands to all three address modes: `"clamp"` → `"clamp-to-edge"`, `"repeat"` → `"repeat"`, `"mirror"` → `"mirror-repeat"`. Raw address fields override per axis. |
| descriptor.mipmapFilter  | `GPUMipmapFilterMode`             |        ✖ | WebGPU default | Not set by `filter`; pass `"linear"` explicitly for anisotropic sampling.                                                                                         |
| descriptor.maxAnisotropy | `number`                          |        ✖ | WebGPU default | If `filter` sugar is used and `maxAnisotropy > 1`, all three filters must resolve to `"linear"`.                                                                  |

### `bind.*` layout entry helpers

| Param                     | Type                                   | Required | Default | Notes                                                                                                                                                                                   |
| ------------------------- | -------------------------------------- | -------: | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| bind.uniform opts         | `Omit<GPUBufferBindingLayout, "type">` |        ✖ | `{}`    | Returns `{ binding, visibility, buffer: { ...opts, type: "uniform" } }`.                                                                                                                |
| bind.storage opts         | `Omit<GPUBufferBindingLayout, "type">` |        ✖ | `{}`    | Returns `{ binding, visibility, buffer: { ...opts, type: "storage" } }`.                                                                                                                |
| bind.readonlyStorage opts | `Omit<GPUBufferBindingLayout, "type">` |        ✖ | `{}`    | Returns `{ binding, visibility, buffer: { ...opts, type: "read-only-storage" } }`.                                                                                                      |
| bind.texture opts         | `GPUTextureBindingLayout`              |        ✖ | `{}`    | Returns `{ binding, visibility, texture: opts }`.                                                                                                                                       |
| bind.storageTexture opts  | `GPUStorageTextureBindingLayout`       |        ✔ | —       | Returns `{ binding, visibility, storageTexture: opts }`; storage texture layout fields are not inferred.                                                                                |
| bind.sampler opts         | `GPUSamplerBindingLayout`              |        ✖ | `{}`    | Returns `{ binding, visibility, sampler: opts }`.                                                                                                                                       |
| bind.resource value       | `unknown`                              |        ✔ | —       | Converts vgpu `Buffer` to `{ buffer: buffer.gpu }`, vgpu `Texture`/texture-like objects to `createView()`, raw `GPUBuffer` to `{ buffer }`, and passes through other binding resources. |

**Returns:**

* `createBindGroupLayout(...)` returns `GPUBindGroupLayout` with vgpu layout metadata attached.
* `createPipelineLayout(...)` returns raw `GPUPipelineLayout`.
* `createBindGroup(...)` returns `GPUBindGroup` with vgpu bind-group metadata attached.
* `createSampler(...)` returns raw `GPUSampler`.
* `bind.uniform(...)`, `bind.storage(...)`, `bind.readonlyStorage(...)`, `bind.texture(...)`, `bind.storageTexture(...)`, and `bind.sampler(...)` return `GPUBindGroupLayoutEntry`.
* `bind.resource(...)` returns `GPUBindGroupEntry`.

**Throws:**

* `VGPU-CORE-BIND-GROUP-LAYOUT-REQUIRED` when `createBindGroup(...)` receives a missing/falsy `opts.layout` — create and pass an explicit `GPUBindGroupLayout`.
* `VGPU-CORE-SAMPLER-ANISOTROPY-FILTERS` when `createSampler(...)` uses `filter` sugar with `maxAnisotropy > 1` but the resolved `magFilter`, `minFilter`, and `mipmapFilter` are not all `"linear"` — add `mipmapFilter: "linear"` and avoid raw non-linear overrides.
* `VGPU-CORE-BINDING-INVALID` when any `bind.*` helper receives a negative, non-integer, or otherwise invalid `binding` — pass an explicit non-negative integer.
* `VGPU-CORE-VISIBILITY-INVALID` when a string/array visibility contains an unknown shader stage name — use only `"vertex"`, `"fragment"`, and `"compute"`, or pass numeric `GPUShaderStageFlags`.
* Native WebGPU validation errors may occur for descriptor/layout/resource incompatibilities — fix the WebGPU descriptor or resource usage.

## Examples

```ts
import { bind, createBindGroup, createBindGroupLayout, createPipelineLayout, createSampler } from "vgpu/core";
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();
const uniformBuffer = device.createBuffer({ size: 64, usage: ["uniform", "copy_dst"] });
const texture = device.createTexture({
  kind: "2d",
  size: [1, 1],
  format: "rgba8unorm",
  usage: ["texture_binding", "copy_src"],
});
const sampler = createSampler(device, { filter: "linear", wrap: "clamp" });

const groupLayout = createBindGroupLayout(device, {
  label: "scene.group0",
  entries: [
    bind.uniform(0, "vertex|fragment"),
    bind.texture(1, "fragment", { sampleType: "float" }),
    bind.sampler(2, ["fragment"], { type: "filtering" }),
  ],
});

const pipelineLayout = createPipelineLayout(device, { bindGroups: [groupLayout] });
const group = createBindGroup(device, {
  layout: groupLayout,
  entries: [
    bind.resource(0, uniformBuffer),
    bind.resource(1, texture),
    bind.resource(2, sampler),
  ],
});

console.log(pipelineLayout, group);
device.destroy();
```

```ts
import { createSampler } from "vgpu/core";
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();

const mixedSampler = createSampler(device, {
  filter: "linear",
  wrap: "repeat",
  magFilter: "nearest", // raw field wins for this key only
});

const anisotropicSampler = createSampler(device, {
  filter: "linear",
  mipmapFilter: "linear",
  maxAnisotropy: 16,
});

console.log(mixedSampler, anisotropicSampler);
device.destroy();
```

```ts
import { bind, createBindGroupLayout } from "vgpu/core";
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();
const computeLayout = createBindGroupLayout(device, {
  entries: [
    bind.storage(0, "compute", { hasDynamicOffset: true }),
    bind.storageTexture(1, "compute", { access: "write-only", format: "rgba8unorm", viewDimension: "2d" }),
  ],
});

console.log(computeLayout);
device.destroy();
```

## Notes

* These helpers are explicit by design: no WGSL reflection, no named binding maps, no hidden resource creation, and no `layout: "auto"` bind groups.
* `filter` sugar does not set `mipmapFilter`. For anisotropic sampling, spell trilinear filtering explicitly.
* Raw WebGPU descriptor fields override sugar per key, not all-or-nothing.
* `bind.resource(...)` creates a default texture view for vgpu `Texture`; use a raw `GPUTextureView` when you need a non-default mip/array/format view.
* Keep shader `@group/@binding` numbers synchronized with helper `binding` numbers; vgpu does not reflect or renumber them here.
* **See also:** `Device`, `Buffer`, `Texture`, `Queue`, `VGPUError`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Buffer
description: `Buffer` is the core wrapper around a `GPUBuffer`. Use it for explicit GPU buffer allocation through `Device.createBuffer(...)`, CPU-to-GPU writes, deterministic readback, and wrapper-aware teardown.
---

# Buffer



## Import

```ts
import { Buffer } from "vgpu/core";
```

## Signature

```ts
import type { Device } from "vgpu/core";

type BufferUsageName =
  | "map_read"
  | "map_write"
  | "copy_src"
  | "copy_dst"
  | "index"
  | "vertex"
  | "uniform"
  | "storage"
  | "indirect"
  | "query_resolve";

interface BufferOptions {
  readonly size: number;
  readonly usage: readonly BufferUsageName[];
  readonly label?: string;
}

type BufferWriteData = ArrayBuffer | ArrayBufferView<ArrayBuffer>;

declare class Buffer {
  readonly gpu: GPUBuffer;
  readonly options: BufferOptions;
  constructor(device: Device, gpu: GPUBuffer, options: BufferOptions);
  write(data: BufferWriteData, offset?: number): void;
  read(byteLength: number, offset?: number): Promise<ArrayBuffer>;
  destroy(): void;
  dispose(): void;
}
```

## Parameters

### `Device.createBuffer(opts)` / `BufferOptions`

| Param      | Type                         | Required | Default     | Notes                                                                              |
| ---------- | ---------------------------- | -------: | ----------- | ---------------------------------------------------------------------------------- |
| opts.size  | `number`                     |        ✔ | —           | Buffer byte length. Must be finite and greater than `0`.                           |
| opts.usage | `readonly BufferUsageName[]` |        ✔ | —           | One or more vgpu usage names mapped to `GPUBufferUsage` flags. Empty arrays throw. |
| opts.label | `string`                     |        ✖ | `undefined` | Forwarded to `GPUBufferDescriptor.label`.                                          |

Valid `BufferUsageName` values: `"map_read"`, `"map_write"`, `"copy_src"`, `"copy_dst"`, `"index"`, `"vertex"`, `"uniform"`, `"storage"`, `"indirect"`, `"query_resolve"`.

### Constructor

| Param   | Type            | Required | Default | Notes                                                                                                      |
| ------- | --------------- | -------: | ------- | ---------------------------------------------------------------------------------------------------------- |
| device  | `Device`        |        ✔ | —       | Owning device wrapper used for queue writes and readback. Normally supplied by `Device.createBuffer(...)`. |
| gpu     | `GPUBuffer`     |        ✔ | —       | Raw WebGPU buffer.                                                                                         |
| options | `BufferOptions` |        ✔ | —       | Original vgpu descriptor exposed as `buffer.options`.                                                      |

### `write(data, offset?)`

| Param  | Type                                          | Required | Default | Notes                                                                 |
| ------ | --------------------------------------------- | -------: | ------- | --------------------------------------------------------------------- |
| data   | `ArrayBuffer \| ArrayBufferView<ArrayBuffer>` |        ✔ | —       | Bytes passed to `device.queue.writeBuffer(buffer.gpu, offset, data)`. |
| offset | `number`                                      |        ✖ | `0`     | Destination byte offset in the GPU buffer.                            |

### `read(byteLength, offset?)`

| Param      | Type     | Required | Default | Notes                                                        |
| ---------- | -------- | -------: | ------- | ------------------------------------------------------------ |
| byteLength | `number` |        ✔ | —       | Number of bytes to copy from the GPU buffer into CPU memory. |
| offset     | `number` |        ✖ | `0`     | Source byte offset in the GPU buffer.                        |

**Returns:**

* `Device.createBuffer(opts)` returns `Buffer`.
* `write(data, offset?)`, `destroy()`, and `dispose()` return `void`.
* `read(byteLength, offset?)` returns `Promise<ArrayBuffer>` containing exactly the requested byte range.

**Throws:**

* `VGPU-CORE-INVALID-USAGE` from `Device.createBuffer(...)` when `opts.size` is non-finite, `opts.size <= 0`, or `opts.usage.length === 0` — pass a positive byte length and at least one usage.
* `VGPU-BUFFER-DISPOSED` (`"Buffer is destroyed."`) when `write(...)` or `read(...)` is called after `destroy()`/`dispose()` — create a new buffer instead of reusing a destroyed wrapper. Reported for a wrapper you disposed and for one destroyed with its gpu, and in preference to the owning device's own disposal error.
* Native WebGPU validation errors may occur if usage flags do not allow the operation, for example reading a buffer without `"copy_src"` or writing without `"copy_dst"`.

## Examples

```ts
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();
const buffer = device.createBuffer({
  label: "cpu-visible-data",
  size: 16,
  usage: ["copy_dst", "copy_src"],
});

buffer.write(new Uint32Array([1, 2, 3, 4]));
const bytes = await buffer.read(16);
console.log(new Uint32Array(bytes)[2]); // 3

buffer.destroy();
device.destroy();
```

```ts
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();

device.pushErrorScope("validation");
const placeholder = device.createBuffer({ size: 0, usage: ["copy_dst"] });
const error = await device.popErrorScope();

console.log(placeholder.options.size); // 0: wrapper exists, backing GPU buffer is mock-sized
console.log(error?.code); // "VGPU-CORE-INVALID-USAGE"

device.destroy();
```

## Notes

* `Buffer` does not infer usages. Include `"copy_dst"` for `write(...)`, `"copy_src"` for `read(...)`, `"vertex"` for vertex input, `"index"` for index input, `"uniform"` for uniforms, and `"storage"` for storage bindings.
* Prefer `buffer.destroy()`/`buffer.dispose()` over `buffer.gpu.destroy()` so lifecycle callbacks, mocks, and wrapper state stay synchronized.
* `destroy()` is idempotent. After destroy, `write(...)` and `read(...)` intentionally fail.
* `read(...)` copies through the device readback path; avoid it in frame loops unless you intentionally need CPU synchronization.
* **See also:** `Device`, `Queue`, `Texture`, `bind.resource`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Device
description: `Device` is the core wrapper around a raw `GPUDevice`. Use it when you need explicit low-level resource creation (`Buffer`, `Texture`, `Shader`), queue access, readback, and structured WebGPU error scopes.
---

# Device



## Import

```ts
import { Device } from "vgpu/core";
```

## Signature

```ts
import type { Buffer, BufferOptions, Queue, Shader, ShaderInput, Texture, TextureOptions, VGPUError } from "vgpu/core";

interface DeviceOptions {
  readonly isCompatibilityMode?: boolean;
}

declare class Device {
  readonly gpu: GPUDevice;
  readonly adapterInfo: GPUAdapterInfo | null;
  readonly queue: Queue;
  readonly isCompatibilityMode: boolean;
  constructor(gpu: GPUDevice, adapterInfo?: GPUAdapterInfo | null, opts?: DeviceOptions);
  get limits(): GPUSupportedLimits;
  get features(): GPUSupportedFeatures;
  createShader(input: ShaderInput): Shader;
  createTexture(opts: TextureOptions): Texture;
  createBuffer(opts: BufferOptions): Buffer;
  pushErrorScope(filter: GPUErrorFilter): void;
  popErrorScope(): Promise<VGPUError | null>;
  destroy(): void;
  dispose(): void;
}
```

## Parameters

### Constructor

| Param                    | Type                     | Required | Default | Notes                                                                                                               |
| ------------------------ | ------------------------ | -------: | ------- | ------------------------------------------------------------------------------------------------------------------- |
| gpu                      | `GPUDevice`              |        ✔ | —       | Raw WebGPU device. `Device` does not request adapters itself.                                                       |
| adapterInfo              | `GPUAdapterInfo \| null` |        ✖ | `null`  | Stored as `device.adapterInfo`; pass adapter metadata when an adapter provides it.                                  |
| opts                     | `DeviceOptions`          |        ✖ | `{}`    | Core-only options for wrapper behavior.                                                                             |
| opts.isCompatibilityMode | `boolean`                |        ✖ | `false` | Stored as `device.isCompatibilityMode`; adapters set it when they requested WebGPU `featureLevel: "compatibility"`. |

### `createShader(input)`

| Param | Type          | Required | Default | Notes                                                                                                                                    |
| ----- | ------------- | -------: | ------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| input | `ShaderInput` |        ✔ | —       | A WGSL string or a resolved shader object with `.wgsl`. Strings are compiled with `@vgpu/wgsl` before creating the native shader module. |

### `createTexture(opts)`

| Param | Type             | Required | Default | Notes                                                                     |
| ----- | ---------------- | -------: | ------- | ------------------------------------------------------------------------- |
| opts  | `TextureOptions` |        ✔ | —       | Descriptor-first texture options; see `TextureOptions` rows in `Texture`. |

### `createBuffer(opts)`

| Param | Type            | Required | Default | Notes                                                                  |
| ----- | --------------- | -------: | ------- | ---------------------------------------------------------------------- |
| opts  | `BufferOptions` |        ✔ | —       | Descriptor-first buffer options; see `BufferOptions` rows in `Buffer`. |

### Error scopes and teardown

| Param  | Type             | Required | Default | Notes                                                                                 |
| ------ | ---------------- | -------: | ------- | ------------------------------------------------------------------------------------- |
| filter | `GPUErrorFilter` |        ✔ | —       | Passed to `gpu.pushErrorScope(filter)` and also starts a vgpu structured-error scope. |

**Returns:**

* `new Device(...)` returns a wrapper with `.gpu`, `.queue`, `.limits`, `.features`, and resource factory methods.
* `createShader(input)` returns `Shader`.
* `createTexture(opts)` returns `Texture`.
* `createBuffer(opts)` returns `Buffer`.
* `pushErrorScope(filter)`, `destroy()`, and `dispose()` return `void`.
* `popErrorScope()` returns `Promise<VGPUError | null>`; the first captured vgpu error wins, otherwise a native `GPUError` is converted to `VGPU-CORE-VALIDATION`, otherwise `null`.

**Throws:**

* `VGPU-CORE-INVALID-USAGE` when `createBuffer({ size })` receives a non-finite size, `size <= 0`, or an empty `usage` array — pass a positive byte size and at least one buffer usage.
* `VGPU-CORE-VALIDATION` can be returned from `popErrorScope()` when the native WebGPU scope reports a `GPUError` — inspect `.message` and fix the invalid WebGPU descriptor or command.
* `VGPU-DEVICE-LOST` when `limits`, `features`, a resource factory, an error-scope method, or queue work runs after the wrapper observed its native `GPUDevice.lost` promise resolve. The message includes the native reason and message, and `cause` is the native `GPUDeviceLostInfo`. A lost device cannot be reused — create a new Gpu with `init()`, then recreate its resources and restart the loop.
* Native WebGPU errors may be thrown by `gpu.createShaderModule`, `gpu.createTexture`, `gpu.pushErrorScope`, `gpu.popErrorScope`, or `gpu.destroy`; use error scopes around native validation-sensitive calls.

## Examples

```ts
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();

const buffer = device.createBuffer({
  label: "positions",
  size: 16,
  usage: ["vertex", "copy_dst", "copy_src"],
});

buffer.write(new Float32Array([0, 1, 2, 3]));
const bytes = await buffer.read(16);
console.log(bytes.byteLength);

device.destroy();
```

```ts
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();

device.pushErrorScope("validation");
const badBuffer = device.createBuffer({ size: 0, usage: ["copy_dst"] });
const error = await device.popErrorScope();

console.log(badBuffer.options.size, error?.code); // "VGPU-CORE-INVALID-USAGE"
device.dispose();
```

```ts
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();

if (device.features.has("timestamp-query")) {
  console.log("timestamp queries are available");
}

console.log(device.limits.maxTextureDimension2D);
console.log(device.isCompatibilityMode);

device.destroy();
```

## Notes

* `Device` is intentionally low-level: it does not infer buffer/texture usage from shaders or pipeline state. Provide explicit descriptors.
* Prefer `device.createBuffer(...)` and `device.createTexture(...)` over raw `.gpu` creation when you want vgpu wrappers, readback, lifecycle callbacks, or structured core errors.
* `destroy()` is idempotent and `dispose()` is an alias. Do not call `device.gpu.destroy()` directly unless you intentionally bypass vgpu lifecycle.
* `createBuffer` throws immediately without an error scope, but captures into the current vgpu error scope when one is active.
* `Device` has no loss promise or loss event of its own. In the main API (`vgpu`), subscribe to `gpu.lost` to learn about loss; vgpu stops the gpu's frame loops before its handlers run. Calling `gpu.device.dispose()` is not `gpu.dispose()`: it leaves the `Gpu` active without stopping its loops or canceling its open frames, so their next tick or `submit()` throws `VGPU-DEVICE-DISPOSED`. Tear a `Gpu` down with `gpu.dispose()`.
* `isCompatibilityMode` is only a signal set by the adapter; keep compatibility-specific texture views and WGSL bindings in lockstep yourself.
* **See also:** `Buffer`, `Texture`, `Queue`, `VGPUError`, `VGPUAdapter`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Queue
description: `Queue` is the core wrapper around a raw `GPUQueue`. Use it for explicit buffer writes and for awaiting completion of already-submitted GPU work.
---

# Queue



## Import

```ts
import { Queue } from "vgpu/core";
```

## Signature

```ts
import type { BufferWriteData } from "vgpu/core";

declare class Queue {
  readonly gpu: GPUQueue;
  constructor(gpu: GPUQueue);
  writeBuffer(buffer: GPUBuffer, offset: number, data: BufferWriteData): void;
  flush(): Promise<void>;
}
```

## Parameters

### Constructor

| Param | Type       | Required | Default | Notes                                                                                              |
| ----- | ---------- | -------: | ------- | -------------------------------------------------------------------------------------------------- |
| gpu   | `GPUQueue` |        ✔ | —       | Raw WebGPU queue exposed again as `queue.gpu`. `Device` constructs `new Queue(gpu.queue)` for you. |

### `writeBuffer(buffer, offset, data)`

| Param  | Type                                          | Required | Default | Notes                                                                                   |
| ------ | --------------------------------------------- | -------: | ------- | --------------------------------------------------------------------------------------- |
| buffer | `GPUBuffer`                                   |        ✔ | —       | Raw destination buffer. Pass `buffer.gpu` when you have a vgpu `Buffer`.                |
| offset | `number`                                      |        ✔ | —       | Destination byte offset. Unlike `Buffer.write(...)`, there is no default at this level. |
| data   | `ArrayBuffer \| ArrayBufferView<ArrayBuffer>` |        ✔ | —       | Bytes forwarded to `GPUQueue.writeBuffer(buffer, offset, data)`.                        |

### `flush()`

| Param | Type | Required | Default | Notes                                                      |
| ----- | ---- | -------: | ------- | ---------------------------------------------------------- |
| —     | —    |        — | —       | Takes no parameters. Awaits `gpu.onSubmittedWorkDone?.()`. |

**Returns:**

* `new Queue(gpu)` returns a queue wrapper.
* `writeBuffer(buffer, offset, data)` returns `void`.
* `flush()` returns `Promise<void>` after `GPUQueue.onSubmittedWorkDone()` resolves, or immediately if the queue implementation has no `onSubmittedWorkDone` method.

**Throws:** Native WebGPU validation errors may occur when `writeBuffer(...)` writes beyond the buffer bounds, uses an invalid offset/data size, or targets a buffer without `COPY_DST` usage — fix the buffer descriptor and write range.

## Examples

```ts
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();
const buffer = device.createBuffer({ size: 8, usage: ["copy_dst", "copy_src"] });

device.queue.writeBuffer(buffer.gpu, 0, new Uint32Array([10, 20]));
await device.queue.flush();

const bytes = await buffer.read(8);
console.log(new Uint32Array(bytes)[1]); // 20

device.destroy();
```

```ts
import { Queue } from "vgpu/core";
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();
const queue = new Queue(device.gpu.queue);
await queue.flush();

device.destroy();
```

## Notes

* `Buffer.write(data, offset = 0)` is the safer high-level call for vgpu buffers; it defaults the offset and checks wrapper lifecycle before reaching the queue.
* `Queue.writeBuffer(...)` intentionally accepts raw `GPUBuffer` so it can interoperate with native WebGPU resources.
* `flush()` waits for submitted work; it does not submit command buffers by itself.
* Do not use `flush()` as a per-frame synchronization point unless CPU/GPU synchronization is intentional.
* **See also:** `Device`, `Buffer`, `Texture`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: createRenderBundle
description: Low-level render bundle helper around `GPUDevice.createRenderBundleEncoder`. Prefer main API (`vgpu`) `bundle(gpu, { target }, cb)` when recording main API (`vgpu`) `Draw`/`Effect` commands because it derives formats from `Target` and performs stale-bundle checks (`VGPU-R3-BUNDLE-STALE`).
---

# createRenderBundle



## Import

```ts
import { createRenderBundle, RenderBundleRecorder } from "vgpu/core";
import type { RenderBundleOptions } from "vgpu/core";
```

## Signature

```ts
import type { Buffer } from "vgpu/core";

declare interface RenderPassDrawOptions {
  readonly vertexCount: number;
  readonly instanceCount?: number;
  readonly firstVertex?: number;
  readonly firstInstance?: number;
}

type RenderPassDynamicOffsets = readonly GPUBufferDynamicOffset[] | Uint32Array;

declare interface RenderBundleOptions {
  readonly label?: string;
  readonly colorFormats: readonly (GPUTextureFormat | null)[];
  readonly depthStencilFormat?: GPUTextureFormat;
  readonly sampleCount?: number;
  readonly depthReadOnly?: boolean;
  readonly stencilReadOnly?: boolean;
  readonly record: (bundle: RenderBundleRecorder) => void;
}

declare class RenderBundleRecorder {
  readonly gpu: GPURenderBundleEncoder;
  constructor(gpu: GPURenderBundleEncoder);
  setPipeline(pipeline: GPURenderPipeline): void;
  setBindGroup(index: number, group: GPUBindGroup | null, dynamicOffsets?: RenderPassDynamicOffsets): void;
  setVertexBuffer(slot: number, buffer: Buffer | GPUBuffer | null, offset?: number, size?: GPUSize64): void;
  draw(options: RenderPassDrawOptions): void;
  draw(vertexCount: number, instanceCount?: number, firstVertex?: number, firstInstance?: number): void;
}

declare function createRenderBundle(device: { readonly gpu: GPUDevice }, opts: RenderBundleOptions): GPURenderBundle;
```

## Parameters

| Param                                | Type                                               | Required | Default                      | Notes                                                                               |
| ------------------------------------ | -------------------------------------------------- | -------: | ---------------------------- | ----------------------------------------------------------------------------------- |
| device                               | `{ readonly gpu: GPUDevice }`                      |        ✔ | —                            | Core `Device` or any wrapper exposing a native `GPUDevice` as `.gpu`.               |
| opts                                 | `RenderBundleOptions`                              |        ✔ | —                            | Native render bundle encoder options plus callback.                                 |
| opts.label                           | `string`                                           |        ✖ | `undefined`                  | Passed to `createRenderBundleEncoder` and `finish`.                                 |
| opts.colorFormats                    | `readonly (GPUTextureFormat \| null)[]`            |        ✔ | —                            | Must match the render pass where the bundle will execute.                           |
| opts.depthStencilFormat              | `GPUTextureFormat`                                 |        ✖ | `undefined`                  | Required when the replay pass has depth/stencil.                                    |
| opts.sampleCount                     | `number`                                           |        ✖ | WebGPU encoder default (`1`) | Must match replay pass sample count. main API (`vgpu`) passes `target.sampleCount`. |
| opts.depthReadOnly                   | `boolean`                                          |        ✖ | `undefined`                  | Forwarded to WebGPU encoder descriptor.                                             |
| opts.stencilReadOnly                 | `boolean`                                          |        ✖ | `undefined`                  | Forwarded to WebGPU encoder descriptor.                                             |
| opts.record                          | `(bundle: RenderBundleRecorder) => void`           |        ✔ | —                            | Called synchronously before `encoder.finish()`.                                     |
| recorder.setPipeline.pipeline        | `GPURenderPipeline`                                |        ✔ | —                            | Native pipeline compatible with bundle formats.                                     |
| recorder.setBindGroup.index          | `number`                                           |        ✔ | —                            | Bind group slot.                                                                    |
| recorder.setBindGroup.group          | `GPUBindGroup \| null`                             |        ✔ | —                            | Native bind group or `null`.                                                        |
| recorder.setBindGroup.dynamicOffsets | `readonly GPUBufferDynamicOffset[] \| Uint32Array` |        ✖ | `undefined`                  | Forwarded to `setBindGroup`.                                                        |
| recorder.setVertexBuffer.slot        | `number`                                           |        ✔ | —                            | Vertex buffer slot.                                                                 |
| recorder.setVertexBuffer.buffer      | `Buffer \| GPUBuffer \| null`                      |        ✔ | —                            | Core `Buffer` is unwrapped to `.gpu`; native buffer and `null` pass through.        |
| recorder.setVertexBuffer.offset      | `number`                                           |        ✖ | `0`                          | Byte offset.                                                                        |
| recorder.setVertexBuffer.size        | `GPUSize64`                                        |        ✖ | `undefined`                  | Byte size.                                                                          |
| recorder.draw\.options.vertexCount   | `number`                                           |        ✔ | —                            | Object overload vertex count.                                                       |
| recorder.draw\.options.instanceCount | `number`                                           |        ✖ | `1`                          | Object overload instance count.                                                     |
| recorder.draw\.options.firstVertex   | `number`                                           |        ✖ | `0`                          | Object overload first vertex.                                                       |
| recorder.draw\.options.firstInstance | `number`                                           |        ✖ | `0`                          | Object overload first instance.                                                     |

**Returns:** `createRenderBundle()` returns `GPURenderBundle`; recorder methods return `void`.

**Throws:** No custom `VGPU-*` errors are thrown here. Native WebGPU validation errors occur for incompatible formats, pipelines, bind groups, buffers, or draw parameters. main API (`vgpu`) stale errors (`VGPU-R3-BUNDLE-STALE`, `VGPU-R3-BUNDLE-INVALID`) are available only through `bundle(gpu)` / `FramePass.bundles()`.

## Examples

```ts
import { init } from "vgpu/mock";
import { createRenderBundle } from "vgpu/core";

const gpu = await init();
const bundle = createRenderBundle(gpu.device, {
  label: "empty",
  colorFormats: ["rgba8unorm"],
  sampleCount: 1,
  record(recorder) {
    void recorder;
  },
});
void bundle;
```

```ts
import { init, target } from "vgpu/mock";
import { createRenderBundle } from "vgpu/core";

const gpu = await init();
const colorTarget = target(gpu, { size: [16, 16] });
const bundle = createRenderBundle(gpu.device, {
  colorFormats: colorTarget.colors.map((color) => color.format),
  depthStencilFormat: colorTarget.depth?.format,
  sampleCount: colorTarget.sampleCount,
  record(recorder) {
    recorder.draw({ vertexCount: 0, instanceCount: 0 });
  },
});
void bundle;
```

## Notes

* This helper intentionally does not know about main API (`vgpu`) `Draw`, `Effect`, or `Target`; you must supply formats and native commands yourself.
* Use `bundle(gpu)` for public API examples unless you are already managing native pipelines.
* `RenderBundleRecorder.draw(number, ...)` defaults to `(instanceCount=1, firstVertex=0, firstInstance=0)`; object overload has the same defaults.
* **See also:** `Bundle`, `FramePass.bundles`, `Draw`, `Target`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: StorageBuffer
description: Low-level user-owned storage buffer with a stable bind group at binding `0`. Use it for arrays, large data, compute scratch buffers, or storage-driven rendering when main API (`vgpu`) `storage(gpu)` is not enough.
---

# StorageBuffer



## Import

```ts
import { StorageBuffer } from "vgpu/core";
import type { StorageBufferOptions } from "vgpu/core";
```

## Signature

```ts
import type { Device } from "vgpu/core";

declare interface StorageBufferOptions {
  readonly size: number;
  readonly label?: string;
  readonly access?: "read" | "read-write";
  readonly visibility?: GPUShaderStageFlags;
  readonly bindGroupLayout?: GPUBindGroupLayout;
}

declare class StorageBuffer {
  readonly device: Device;
  readonly size: number;
  readonly access: "read" | "read-write";
  readonly buffer: import("vgpu/core").Buffer;
  readonly bindGroupLayout: GPUBindGroupLayout;
  readonly bindGroup: GPUBindGroup;
  constructor(device: Device, opts: StorageBufferOptions);
  get gpu(): GPUBuffer;
  write(data: BufferSource, offset?: number): void;
  destroy(): void;
  dispose(): void;
}
```

## Parameters

| Param                | Type                     | Required | Default                                                                            | Notes                                                                                                   |
| -------------------- | ------------------------ | -------: | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| device               | `Device`                 |        ✔ | —                                                                                  | Core device, usually `gpu.device`.                                                                      |
| opts                 | `StorageBufferOptions`   |        ✔ | —                                                                                  | Buffer/layout options.                                                                                  |
| opts.size            | `number`                 |        ✔ | —                                                                                  | Byte size. Used for storage buffer allocation and `minBindingSize`.                                     |
| opts.label           | `string`                 |        ✖ | `undefined`                                                                        | Forwarded to buffer label; layout label becomes `${label}.bgl`; bind group label becomes `${label}.bg`. |
| opts.access          | `"read" \| "read-write"` |        ✖ | `"read"`                                                                           | Chooses bind group layout type: `"read-only-storage"` or `"storage"`.                                   |
| opts.visibility      | `GPUShaderStageFlags`    |        ✖ | `GPUShaderStage.FRAGMENT \| GPUShaderStage.COMPUTE` with numeric fallback `2 \| 4` | Ignored when `opts.bindGroupLayout` is supplied. Default intentionally excludes vertex stage.           |
| opts.bindGroupLayout | `GPUBindGroupLayout`     |        ✖ | A new binding-0 storage layout                                                     | Reuse a pipeline-owned layout. Binding `0` must match size/access.                                      |
| storage.write.data   | `BufferSource`           |        ✔ | —                                                                                  | Bytes uploaded with `queue.writeBuffer`.                                                                |
| storage.write.offset | `number`                 |        ✖ | `0`                                                                                | Destination byte offset.                                                                                |

**Returns:** Constructor returns `StorageBuffer`; `gpu` returns the underlying `GPUBuffer`; `write()`, `destroy()`, and `dispose()` return `void`.

**Throws:** No custom `VGPU-*` errors are thrown directly by this class. Native/core validation can fail for invalid size, incompatible reused layouts, or bad writes. Compute aliasing with the same buffer can throw `VGPU-R1-STORAGE-ALIASING` when used through `compute(gpu)`.

## Examples

```ts
import { init, compute } from "vgpu/mock";
import { StorageBuffer } from "vgpu/core";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const values = new StorageBuffer(gpu.device, { size: 4 * 16, label: "values" });
values.write(new Float32Array(16));

const sim = compute(gpu, prepareShader(`
  @group(0) @binding(0) var<storage, read> values: array<f32>;
  @compute @workgroup_size(1)
  fn cs_main(@builtin(global_invocation_id) id: vec3u) { _ = values[id.x]; }
`), { set: { values } });
sim.dispatch(1);
```

```ts
import { init, draw } from "vgpu/mock";
import { StorageBuffer } from "vgpu/core";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const drawable = draw(gpu, { shader: prepareShader(`
  @group(0) @binding(0) var<storage, read> positions: array<vec4f>;
  @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { return positions[vi]; }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }
`) });
const positions = new StorageBuffer(gpu.device, {
  size: 3 * 16,
  visibility: GPUShaderStage.VERTEX,
  bindGroupLayout: drawable.layout(0),
});
positions.write(new Float32Array(12));
drawable.set({ positions });
```

## Notes

* Default visibility is fragment + compute, not vertex. Vertex-stage storage is legal only on adapters with the needed limits; opt in explicitly and request limits when creating the device.
* `access: "read-write"` cannot be used from the vertex stage in WebGPU.
* For main API (`vgpu`) readback and ping-pong helpers, use `storage(gpu)` and `pingPongStorage(gpu)`.
* **See also:** `Compute`, `storage()`, `Uniform`, `UniformPool`, `Draw.set`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: StructuredUniform
description: Low-level structured uniform buffer that computes WGSL-compatible offsets from a schema and writes typed values into one stable uniform buffer. Prefer main API (`vgpu`) `set({ params: ... })` unless you need a reusable resource and generated WGSL struct text.
---

# StructuredUniform



## Import

```ts
import { StructuredUniform } from "vgpu/core";
import type { StructuredUniformOptions, UniformValues, ScalarUniformType, VectorUniformInput, UniformLayoutInfo, UniformField, WgslUniformType } from "vgpu/core";
```

## Signature

```ts
import type { BindVisibility, Device } from "vgpu/core";

type ScalarUniformType = "f32" | "u32" | "i32";
type VectorUniformInput = readonly number[] | Float32Array | Uint32Array | Int32Array;
type WgslUniformType =
  | "f32" | "u32" | "i32"
  | "vec2f" | "vec3f" | "vec4f"
  | "vec2u" | "vec3u" | "vec4u"
  | "vec2i" | "vec3i" | "vec4i"
  | "mat3x3f" | "mat4x4f";

type UniformValues<S extends Record<string, WgslUniformType>> = {
  [K in keyof S]: S[K] extends ScalarUniformType ? number : VectorUniformInput;
};

interface UniformField {
  readonly name: string;
  readonly type: WgslUniformType;
  readonly offset: number;
  readonly size: number;
  readonly align: number;
}

interface UniformLayoutInfo {
  readonly fields: readonly UniformField[];
  readonly offsets: Readonly<Record<string, number>>;
  readonly byteSize: number;
}

interface StructuredUniformOptions<S extends Record<string, WgslUniformType>> {
  readonly schema: S;
  readonly label?: string;
  readonly visibility?: BindVisibility;
}

declare class StructuredUniform<S extends Record<string, WgslUniformType>> {
  readonly device: Device;
  readonly schema: S;
  readonly layout: UniformLayoutInfo;
  readonly byteSize: number;
  readonly offsets: Readonly<Record<keyof S, number>>;
  readonly buffer: import("vgpu/core").Buffer;
  constructor(device: Device, opts: StructuredUniformOptions<S>);
  get gpu(): GPUBuffer;
  get bindGroupLayout(): GPUBindGroupLayout;
  get bindGroup(): GPUBindGroup;
  write(values: Partial<UniformValues<S>>): void;
  wgsl(structName?: string): string;
  destroy(): void;
  dispose(): void;
}
```

## Parameters

| Param           | Type                                        | Required | Default                  | Notes                                                                                              |
| --------------- | ------------------------------------------- | -------: | ------------------------ | -------------------------------------------------------------------------------------------------- |
| device          | `Device`                                    |        ✔ | —                        | Core device.                                                                                       |
| opts            | `StructuredUniformOptions<S>`               |        ✔ | —                        | Schema and optional labels/visibility.                                                             |
| opts.schema     | `S extends Record<string, WgslUniformType>` |        ✔ | —                        | Insertion order is WGSL member order. Empty schema and unsupported type strings are invalid.       |
| opts.label      | `string`                                    |        ✖ | `undefined`              | Buffer label; lazy layout/bind group labels become `${label}.bgl` and `${label}.bg`.               |
| opts.visibility | `BindVisibility`                            |        ✖ | `["vertex", "fragment"]` | Used only by lazy `bindGroupLayout`; ignored until that getter is read.                            |
| write.values    | `Partial<UniformValues<S>>`                 |        ✔ | —                        | Field patch. Scalars require `number`; vectors/matrices require exact-length array or typed array. |
| wgsl.structName | `string`                                    |        ✖ | `"Uniforms"`             | Name for generated WGSL struct text.                                                               |

**Returns:** Constructor returns `StructuredUniform`; `bindGroupLayout` and `bindGroup` lazily create native objects; `write()` returns `void`; `wgsl()` returns WGSL struct source; `destroy()` / `dispose()` return `void`.

**Throws:** `VGPU-CORE-INVALID-USAGE` when schema is empty, contains unsupported types, writing an unknown field, writing a scalar with a non-number, writing vector/matrix data with a non-array, wrong exact length, or using the object after destroy.

## Examples

```ts
import { init } from "vgpu/mock";
import { StructuredUniform } from "vgpu/core";

const gpu = await init();
const params = new StructuredUniform(gpu.device, {
  label: "params",
  schema: { time: "f32", tint: "vec3f", viewProjection: "mat4x4f" },
});
params.write({
  time: 1,
  tint: [1, 0.5, 0.25],
  viewProjection: new Float32Array(16),
});
const wgsl = params.wgsl("Params");
void wgsl;
```

```ts
import { init, draw } from "vgpu/mock";
import { StructuredUniform } from "vgpu/core";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const params = new StructuredUniform(gpu.device, { schema: { value: "f32" } });
const drawable = draw(gpu, { shader: prepareShader(`
  struct Params { value: f32 }
  @group(0) @binding(0) var<uniform> params: Params;
  @vertex fn vs_main() -> @builtin(position) vec4f { return vec4f(0, 0, 0, 1); }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(params.value); }
`) });
params.write({ value: 1 });
drawable.set({ params });
```

## Notes

* `vec3*` fields align to 16 bytes; inspect `offsets` / `layout` instead of assuming tight packing.
* `mat3x3f` stores columns at 16-byte stride and needs exactly 9 values in `write()`.
* `wgsl()` only emits the struct; you still declare the `@group/@binding var<uniform>` line in your shader.
* **See also:** `Uniform`, `SharedUniforms`, `UniformPool`, `Draw.set`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Texture
description: `Texture` is the core wrapper around a `GPUTexture`. Use it for explicit texture allocation through `Device.createTexture(...)`, cached default views, readback, and wrapper-aware teardown. Its allocation and resource identity are fixed for its lifetime; replace and rebind it to change size.
---

# Texture



This is also the canonical reference for `TextureOptions`, `TextureReadOptions`, `TextureShape` and
`TextureUsageName`. These types are re-exported by `vgpu`, `vgpu/node` and `vgpu/mock`; the public
`texture(gpu, opts)` factory uses this same class and contract, with ownership registered on `gpu`.

## Import

```ts
import { Texture } from "vgpu/core";
```

## Signature

```ts
import type { Device, TextureOptions, TextureReadOptions, TextureShape } from "vgpu/core";

declare class Texture {
  constructor(device: Device, gpu: GPUTexture, options: TextureOptions, ownership?: "owned" | "external");
  get gpu(): GPUTexture;
  get options(): TextureOptions;
  get size(): TextureOptions["size"];
  get kind(): TextureShape["kind"];
  get layers(): number;
  get format(): GPUTextureFormat;
  get usage(): TextureOptions["usage"];
  get mipLevelCount(): number;
  get sampleCount(): 1 | 4;
  get dimension(): GPUTextureDimension;
  get viewFormats(): readonly GPUTextureFormat[];
  get label(): string | undefined;
  get view(): GPUTextureView;
  createView(desc?: GPUTextureViewDescriptor): GPUTextureView;
  read(options: TextureReadOptions): Promise<Uint8Array>;
  readFloats(options: TextureReadOptions): Promise<Float32Array>;
  destroy(): void;
  dispose(): void;
}
```

## Shared types

### TextureShape

The discriminated shape uses `kind: "1d"` with `[width]`, `"2d"` with `[width, height]`,
`"3d"` with `[width, height, depth]`, or `"2d-array"` with `[width, height]` and separate `layers`.
Only arrays accept `layers`. Narrow `texture.options.kind` to access shape-specific fields.

### TextureUsageName

The capability names are `"copy_src"`, `"copy_dst"`, `"texture_binding"`, `"storage_binding"` and
`"render_attachment"`. `TextureOptions.usage` requires at least one; no capability is inferred.

### TextureReadOptions

Both fields are required. Origins and extents are mip-relative texels; `"all"` includes every array
layer or 3D slice of the selected mip. Buffer reads are unchanged.

```ts
interface TextureReadOptions {
  readonly mipLevel: number;
  readonly region: "all" | {
    readonly origin: readonly [number, number, number];
    readonly size: readonly [number, number, number];
  };
}
```

## Parameters

### `Device.createTexture(opts)` / `TextureOptions`

| Param              | Type                                                 |   Required | Default              | Notes                                                                                                                                             |
| ------------------ | ---------------------------------------------------- | ---------: | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| opts.kind          | `TextureShape["kind"]`                               |          ✔ | —                    | `"1d"`, `"2d"`, `"3d"` or `"2d-array"`. Same contract as public `texture(gpu, opts)`.                                                             |
| opts.size          | `TextureShape["size"]`                               |          ✔ | —                    | `[width]` for 1D; `[width, height, depth]` for 3D; `[width, height]` for 2D and arrays. Positive safe integers.                                   |
| opts.layers        | `number`                                             | For arrays | —                    | Required positive layer count for `"2d-array"`; forbidden otherwise. Array `.size` stays two-dimensional. `.layers` is 1 for non-array textures.  |
| opts.format        | `GPUTextureFormat`                                   |          ✔ | —                    | Forwarded to `GPUTextureDescriptor.format`. `read()`/`readFloats()` support the color formats listed under [Readback formats](#readback-formats). |
| opts.usage         | `readonly [TextureUsageName, ...TextureUsageName[]]` |          ✔ | —                    | Nonempty explicit capability list. No implicit flags.                                                                                             |
| opts.mipLevelCount | `number`                                             |          ✖ | WebGPU default (`1`) | Only included in the native descriptor when provided; getter returns `opts.mipLevelCount ?? 1`.                                                   |
| opts.sampleCount   | `1 \| 4`                                             |          ✖ | WebGPU default (`1`) | Only included when provided; getter returns `opts.sampleCount ?? 1`. Use `4` for MSAA where WebGPU allows it.                                     |
| opts.viewFormats   | `readonly GPUTextureFormat[]`                        |          ✖ | `[]`                 | Only included when provided; getter returns `opts.viewFormats ?? []`.                                                                             |
| opts.label         | `string`                                             |          ✖ | `undefined`          | Forwarded to `GPUTextureDescriptor.label` and exposed via `texture.label`.                                                                        |

Valid `TextureUsageName` values: `"copy_src"`, `"copy_dst"`, `"texture_binding"`, `"storage_binding"`, `"render_attachment"`.

### Constructor

| Param     | Type                    | Required | Default   | Notes                                                                                                                                                                                  |
| --------- | ----------------------- | -------: | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| device    | `Device`                |        ✔ | —         | Owning device wrapper. Normally supplied by `Device.createTexture(...)`.                                                                                                               |
| gpu       | `GPUTexture`            |        ✔ | —         | Raw WebGPU texture.                                                                                                                                                                    |
| options   | `TextureOptions`        |        ✔ | —         | Copied and frozen, including nested arrays; exposed as `texture.options`. The constructor wraps an existing native resource; prefer `Device.createTexture()` for validated allocation. |
| ownership | `"owned" \| "external"` |        ✖ | `"owned"` | Destroying an owned wrapper releases its native texture. Destroying an external wrapper only invalidates the wrapper and notifies subscribers; native ownership stays external.        |

### Views, resize, readback

Texture allocation is immutable. To resize, create a replacement and rebind it before destroying the previous texture; see the replacement example below. Views and readback operate on the current allocation.

| Param            | Type                                                                                              | Required | Default     | Notes                                                                                                                                                    |
| ---------------- | ------------------------------------------------------------------------------------------------- | -------: | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| desc             | `GPUTextureViewDescriptor`                                                                        |        ✖ | `undefined` | Native view descriptor. Arrays default to dimension `"2d-array"` even with one layer; an explicit `dimension` overrides this. Other fields pass through. |
| options.mipLevel | `number`                                                                                          |        ✔ | —           | Allocated mip index, nonnegative safe integer.                                                                                                           |
| options.region   | `"all" \| { origin: readonly [number, number, number]; size: readonly [number, number, number] }` |        ✔ | —           | Entire selected mip, or a positive in-bounds region in mip-relative texels. Includes all selected layers/slices.                                         |

**Returns:**

* `Device.createTexture(opts)` returns `Texture`.
* `texture.view` returns a cached default `GPUTextureView` matching kind, including one-layer arrays.
* `createView(desc?)` returns a fresh `GPUTextureView`.
* `read(options)` returns `Promise<Uint8Array>` with unpadded texel bytes: selected `width * height * depthOrLayers * bytesPerPixel(format)`, X fastest, then Y, then Z. `bgra*` bytes are swizzled to RGBA order.
* `readFloats(options)` returns `Promise<Float32Array>` with one f32 per component in the same order. Float formats keep their HDR values (no clamping to `[0, 1]`), `unorm8` formats are normalized by `/ 255` without srgb gamma conversion.
* `destroy()` and `dispose()` return `void`.

**Throws:**

* `VGPU-CORE-TEXTURE-READ-INVALID` for absent/invalid selection, missing `copy_src`, multisampling, out-of-bounds regions, or allocations exceeding the device buffer limit or portable host byte limit (`2^32 - 1`). Validation occurs before staging allocation; use a smaller region for large textures. Float reads also validate the decoded allocation size.
* `VGPU-CORE-TEXTURE-DESTROYED` when `view`, `createView(...)`, `read()`, or `readFloats()` is used after `destroy()`/`dispose()` — create a new texture instead.
* `VGPU-CORE-UNSUPPORTED-FORMAT` when `read()`/`readFloats()` is called on a format outside [Readback formats](#readback-formats) (depth/stencil, packed, snorm/uint/sint, and compressed formats) — blit into a supported format first, or read the data through a storage buffer.
* Native WebGPU validation errors may occur for invalid size/format/usage combinations.
* Creation preflight throws `VGPU-TEXTURE-*` errors for invalid kind, size, layers, usage, mip/sample combinations, view-format compatibility, enabled limits or storage capability. It does not replace full native per-format validation.

## Examples

```ts
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();
const target = device.createTexture({
  kind: "2d",
  label: "offscreen-target",
  size: [4, 4],
  format: "rgba8unorm",
  usage: ["render_attachment", "texture_binding", "copy_src"],
});

const defaultView = target.view;
const explicitView = target.createView({ label: "offscreen-target.view" });
console.log(defaultView, explicitView, target.sampleCount); // sampleCount defaults to 1

device.destroy();
```

```ts
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();
let texture = device.createTexture({
  kind: "2d-array",
  size: [1, 1], layers: 6,
  format: "rgba8unorm",
  usage: ["texture_binding", "copy_src"],
});

const previous = texture;
texture = device.createTexture({ ...previous.options, kind: "2d-array", size: [2, 2], layers: 6 });
// Update any bindings to texture before releasing previous.
previous.destroy();
console.log(texture.size); // [2, 2]
console.log(texture.layers); // 6

const pixels = await texture.read({ mipLevel: 0, region: "all" });
console.log(pixels.byteLength); // width * height * layers * 4

device.destroy();
```

```ts
import { createMockAdapter } from "vgpu/mock";

const device = await createMockAdapter().requestDevice();
const hdr = device.createTexture({
  kind: "2d",
  size: [2, 2],
  format: "rgba16float",
  usage: ["render_attachment", "copy_src"],
});

const bytes = await hdr.read({ mipLevel: 0, region: "all" });
console.log(bytes.byteLength); // 2 * 2 * 8 — raw half-float bytes

const floats = await hdr.readFloats({ mipLevel: 0, region: "all" });
console.log(floats.length); // 2 * 2 * 4 — decoded rgba components, values may exceed 1

device.destroy();
```

## Readback formats

| Format                          | Bytes per texel | Components | `readFloats()` decoding                 |
| ------------------------------- | --------------: | ---------: | --------------------------------------- |
| `r8unorm`                       |               1 |          1 | `byte / 255`                            |
| `rg8unorm`                      |               2 |          2 | `byte / 255`                            |
| `rgba8unorm`, `rgba8unorm-srgb` |               4 |          4 | `byte / 255` (no srgb gamma conversion) |
| `bgra8unorm`, `bgra8unorm-srgb` |               4 |          4 | `byte / 255`, channels swizzled to RGBA |
| `r16float`                      |               2 |          1 | binary16 widened to f32                 |
| `rg16float`                     |               4 |          2 | binary16 widened to f32                 |
| `rgba16float`                   |               8 |          4 | binary16 widened to f32                 |
| `r32float`                      |               4 |          1 | verbatim f32                            |
| `rg32float`                     |               8 |          2 | verbatim f32                            |
| `rgba32float`                   |              16 |          4 | verbatim f32                            |

Subnormals, infinities, and NaN survive the binary16 → f32 widening unchanged.

## Notes

* `texture.view` is cached and follows kind. Use `createView(descriptor)` for mip, array-layer, cube, or format-specific views.
* `Texture.resize()` does not exist. Create a replacement and rebind it, or resize the owning Target/core texture ping-pong pair. Replacement discards contents; reseed or copy explicitly when needed.
* Tracked public draw/compute bindings reject a destroyed Texture, even without another `set()` call. Raw `GPUTextureView` bindings do not carry a tracked parent and rely on native WebGPU validation.
* Prefer `texture.destroy()`/`texture.dispose()` over `texture.gpu.destroy()` so the wrapper invalidates cached views and emits lifecycle state correctly.
* Include `"copy_src"` when you plan to read, on both real and mock devices. Multisampled textures must be explicitly resolved first (Target exposes its resolved attachment through `.color`).
* `region: "all"` reads one mip, including every array layer or depth slice. A 3D mip shrinks width, height and depth; arrays shrink width/height but retain their layer count. No mip generation, clipping, or implicit resolve is performed.
* Prefer `readFloats()` for HDR textures (`rgba16float`, `rgba32float`): `read()` hands back the raw half/float bytes, which are only useful after a decode. `read()` remains the right call for `rgba8unorm` snapshots and PNG encoding.
* **See also:** `Device`, `Buffer`, `Queue`, `cubeView`, `layerView`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: UniformPool
description: Dynamic-offset ring allocator for many per-draw uniforms. Allocate a typed `UniformSlot` once, push values each frame, call `endFrame()`, and pass returned offsets through `p.draw(draw, { offsets })`.
---

# UniformPool



## Import

```ts
import { UniformPool } from "vgpu/core";
import type { UniformPoolOptions, UniformLayout, UniformSlot } from "vgpu/core";
```

## Signature

```ts
import type { Device } from "vgpu/core";

interface UniformPoolOptions {
  readonly capacityBytes?: number;
}

interface UniformLayout<T> {
  readonly size: number;
  readonly bindings?: readonly GPUBindGroupLayoutEntry[];
  readonly bindGroupLayout?: GPUBindGroupLayout;
  encode(value: T, dst: ArrayBuffer, byteOffset: number): void;
}

interface UniformSlot<T> {
  readonly pool: UniformPool;
  readonly layout: UniformLayout<T>;
  readonly bindGroup: GPUBindGroup;
  readonly bindGroupLayout: GPUBindGroupLayout;
  readonly gpu: GPUBuffer;
  readonly stride: number;
  push(value: T): number;
  pushBytes(bytes: ArrayBufferView<ArrayBuffer>): number;
}

declare class UniformPool {
  readonly device: Device;
  readonly minOffsetAlignment: number;
  readonly capacityBytes: number;
  readonly maxUniformBindingSize: number;
  readonly cpuMirror: ArrayBuffer;
  readonly gpu: GPUBuffer;
  constructor(device: Device, opts?: UniformPoolOptions);
  get usedBytes(): number;
  get disposed(): boolean;
  alloc<T>(layout: UniformLayout<T>): UniformSlot<T>;
  push<T>(slot: UniformSlot<T>, value: T): number;
  pushBytes(slot: UniformSlot<unknown>, bytes: ArrayBufferView<ArrayBuffer>): number;
  beginFrame(frameIndex: number): void;
  endFrame(): void;
  assertReadyForSubmit(where: string): void;
  dispose(): void;
}
```

## Parameters

| Param                      | Type                                 | Required | Default                                                         | Notes                                                                                                             |
| -------------------------- | ------------------------------------ | -------: | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| device                     | `Device`                             |        ✔ | —                                                               | Core device. Device limits determine alignment and max binding size.                                              |
| opts                       | `UniformPoolOptions`                 |        ✖ | `{}`                                                            | Pool capacity options.                                                                                            |
| opts.capacityBytes         | `number`                             |        ✖ | `4 * 1024 * 1024`                                               | CPU mirror and GPU buffer size.                                                                                   |
| layout.size                | `number`                             |        ✔ | —                                                               | Logical uniform byte size before stride alignment. Must fit both pool capacity and `maxUniformBufferBindingSize`. |
| layout.bindings            | `readonly GPUBindGroupLayoutEntry[]` |        ✖ | Binding `0` uniform, dynamic offset, visibility vertex+fragment | Used only when `layout.bindGroupLayout` is omitted.                                                               |
| layout.bindGroupLayout     | `GPUBindGroupLayout`                 |        ✖ | New layout from `layout.bindings` or default binding `0`        | Usually `draw.layout(group, { dynamicOffsets: true })` so the draw pipeline and slot agree.                       |
| layout.encode              | `(value, dst, byteOffset) => void`   |        ✔ | —                                                               | Writes one value into the pool CPU mirror at `byteOffset`.                                                        |
| alloc.layout               | `UniformLayout<T>`                   |        ✔ | —                                                               | Layout used for one reusable slot. Slot stride is `roundUp(layout.size, minUniformBufferOffsetAlignment)`.        |
| push.slot                  | `UniformSlot<T>`                     |        ✔ | —                                                               | Must be allocated by the same pool.                                                                               |
| push.value                 | `T`                                  |        ✔ | —                                                               | Encoded into the CPU mirror; returned offset is passed as dynamic offset.                                         |
| pushBytes.bytes            | `ArrayBufferView<ArrayBuffer>`       |        ✔ | —                                                               | Must have byte length exactly equal to `slot.layout.size`.                                                        |
| beginFrame.frameIndex      | `number`                             |        ✔ | —                                                               | Currently unused marker; call before pushes to reset the ring head to `0`.                                        |
| assertReadyForSubmit.where | `string`                             |        ✔ | —                                                               | Error context if pushes are unflushed.                                                                            |

**Returns:** Constructor returns `UniformPool`; `alloc()` returns `UniformSlot<T>`; `push()` / `pushBytes()` return the dynamic byte offset; `usedBytes` returns current ring head; lifecycle methods return `void`.

**Throws:** `VGPU-UNIFORM-POOL-OVERFLOW` when a push would exceed `capacityBytes`; `VGPU-UNIFORM-LAYOUT-OVERSIZED` when `layout.size` exceeds pool capacity or device `maxUniformBufferBindingSize`; `VGPU-CORE-INVALID-USAGE` when using a disposed pool, pushing a slot from another pool, `pushBytes` length mismatches, or submitting before `endFrame()` flushes unflushed pushes.

## Examples

```ts
import { init, clock, draw, frame, target } from "vgpu/mock";
import { UniformPool, type UniformLayout } from "vgpu/core";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [32, 32] });
const drawable = draw(gpu, { shader: prepareShader(`
  struct Object { model: mat4x4f }
  @group(0) @binding(0) var<uniform> object: Object;
  @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
    var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
    return object.model * vec4f(p[vi], 0, 1);
  }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }
`) });

type ObjectUniforms = { model: Float32Array };
const objectLayout: UniformLayout<ObjectUniforms> = {
  size: 64,
  bindGroupLayout: drawable.layout(0, { dynamicOffsets: true }),
  encode(value, dst, byteOffset) {
    new Float32Array(dst, byteOffset, 16).set(value.model);
  },
};
const pool = new UniformPool(gpu.device, { capacityBytes: 1 << 20 });
const slot = pool.alloc(objectLayout);
drawable.group(0, slot.bindGroup);

pool.beginFrame(clock(gpu).frameCount);
const offset = slot.push({ model: new Float32Array(16) });
pool.endFrame();
frame(gpu, (currentFrame) => currentFrame.pass({ target: colorTarget }, (pass) => pass.draw(drawable, { offsets: { 0: [offset] } })));
```

```ts
import { init } from "vgpu/mock";
import { UniformPool, type UniformLayout } from "vgpu/core";

const gpu = await init();
const pool = new UniformPool(gpu.device, { capacityBytes: 1024 });
const layout: UniformLayout<Float32Array> = {
  size: 16,
  encode(value, dst, byteOffset) { new Float32Array(dst, byteOffset, 4).set(value); },
};
const slot = pool.alloc(layout);
pool.beginFrame(0);
const offset = slot.pushBytes(new Float32Array([1, 0, 0, 0]));
pool.endFrame();
void offset;
```

## Notes

* Call `beginFrame()` before pushes and `endFrame()` before submitting commands that use the returned offsets.
* A dynamic-offset bind group stores `offset: 0`; the per-draw offset comes from `DrawCallOptions.offsets`.
* The pool is a ring for transient per-frame data, not long-lived storage. Persistent globals usually fit `Uniform` or `SharedUniforms` better.
* **See also:** `Draw.layout`, `DrawCallOptions.offsets`, `FramePass.draw`, `Uniform`, `StructuredUniform`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Uniform
description: Low-level user-owned uniform buffer with a stable bind group at binding `0`. Prefer main API (`vgpu`) `set({ params: ... })` for ordinary values; use `Uniform` when you need byte-level writes or one buffer shared by many draws.
---

# Uniform



## Import

```ts
import { Uniform } from "vgpu/core";
import type { UniformOptions } from "vgpu/core";
```

## Signature

```ts
import type { Device } from "vgpu/core";

declare interface UniformOptions {
  readonly size: number;
  readonly label?: string;
  readonly visibility?: GPUShaderStageFlags;
  readonly bindGroupLayout?: GPUBindGroupLayout;
}

declare class Uniform {
  readonly device: Device;
  readonly size: number;
  readonly buffer: import("vgpu/core").Buffer;
  readonly bindGroupLayout: GPUBindGroupLayout;
  readonly bindGroup: GPUBindGroup;
  constructor(device: Device, opts: UniformOptions);
  get gpu(): GPUBuffer;
  write(data: BufferSource, offset?: number): void;
  destroy(): void;
  dispose(): void;
}
```

## Parameters

| Param                | Type                  | Required | Default                                                                           | Notes                                                                                                   |
| -------------------- | --------------------- | -------: | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| device               | `Device`              |        ✔ | —                                                                                 | Core device, usually `gpu.device` from the main API (`vgpu`) `init()`.                                  |
| opts                 | `UniformOptions`      |        ✔ | —                                                                                 | Buffer/layout options.                                                                                  |
| opts.size            | `number`              |        ✔ | —                                                                                 | Byte size. Used for `device.createBuffer({ usage: ["uniform", "copy_dst"] })` and `minBindingSize`.     |
| opts.label           | `string`              |        ✖ | `undefined`                                                                       | Forwarded to buffer label; layout label becomes `${label}.bgl`; bind group label becomes `${label}.bg`. |
| opts.visibility      | `GPUShaderStageFlags` |        ✖ | `GPUShaderStage.VERTEX \| GPUShaderStage.FRAGMENT` with numeric fallback `1 \| 2` | Ignored when `opts.bindGroupLayout` is supplied.                                                        |
| opts.bindGroupLayout | `GPUBindGroupLayout`  |        ✖ | A new binding-0 uniform layout                                                    | Reuse a pipeline/draw-owned layout. Binding `0` must be a compatible uniform buffer.                    |
| uniform.write.data   | `BufferSource`        |        ✔ | —                                                                                 | Bytes uploaded with `queue.writeBuffer`.                                                                |
| uniform.write.offset | `number`              |        ✖ | `0`                                                                               | Destination byte offset in the buffer.                                                                  |

**Returns:** Constructor returns `Uniform`; `gpu` returns the underlying `GPUBuffer`; `write()`, `destroy()`, and `dispose()` return `void`.

**Throws:** No main API (`vgpu`) `VGPU-*` errors are thrown directly by `Uniform`; invalid sizes, incompatible reused layouts, out-of-range writes, or destroyed-buffer usage can surface as core/native WebGPU validation errors. Binding a `Uniform` through main API (`vgpu`) can still trigger `VGPU-R1-OWNERSHIP-FLIP` if the same shader binding was first set with JS values.

## Examples

```ts
import { init, draw } from "vgpu/mock";
import { Uniform } from "vgpu/core";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const camera = new Uniform(gpu.device, { size: 64, label: "camera" });
camera.write(new Float32Array(16));

const drawable = draw(gpu, { shader: prepareShader(`
  struct Camera { viewProjection: mat4x4f }
  @group(0) @binding(0) var<uniform> camera: Camera;
  @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
    var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
    return camera.viewProjection * vec4f(p[vi], 0, 1);
  }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }
`) });
drawable.set({ camera });
```

```ts
import { init, draw } from "vgpu/mock";
import { Uniform } from "vgpu/core";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const drawable = draw(gpu, { shader: prepareShader(`
  struct Params { value: f32 }
  @group(0) @binding(0) var<uniform> params: Params;
  @vertex fn vs_main() -> @builtin(position) vec4f { return vec4f(0, 0, 0, 1); }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(params.value); }
`) });
const params = new Uniform(gpu.device, { size: 16, bindGroupLayout: drawable.layout(0) });
params.write(new Float32Array([1, 0, 0, 0]));
drawable.set({ params });
```

## Notes

* `Uniform` is user-owned from the first `draw.set({ name: uniform })`; vgpu binds its identity and never packs JS values into it.
* It creates a non-dynamic bind group. For many per-object uniforms with dynamic offsets, use `UniformPool` instead.
* Call `destroy()` / `dispose()` when the buffer lifetime ends.
* **See also:** `SharedUniforms`, `StructuredUniform`, `UniformPool`, `Draw.set`, `Effect.set`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: VGPUAdapter
description: `VGPUAdapter` is the minimal core adapter interface. Use it when code should request a vgpu `Device` without caring whether the backing implementation is browser WebGPU, Node/Dawn, or the mock adapter.
---

# VGPUAdapter



## Import

```ts
import type { VGPUAdapter } from "vgpu/core";
```

## Signature

```ts
import type { Device, RequiredDeviceLimits } from "vgpu/core";

interface CreateDeviceOptions {
  readonly powerPreference?: GPUPowerPreference;
  readonly requiredFeatures?: readonly GPUFeatureName[];
  readonly requiredLimits?: RequiredDeviceLimits;
  readonly label?: string;
}

interface VGPUAdapter {
  requestDevice(opts?: CreateDeviceOptions): Promise<Device>;
}
```

## Parameters

### `requestDevice(opts?)` / `CreateDeviceOptions`

| Param                 | Type                        | Required | Default     | Notes                                                                                                                                                                                                                                                                                                                                                                                     |
| --------------------- | --------------------------- | -------: | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| opts                  | `CreateDeviceOptions`       |        ✖ | `undefined` | Device request options. Concrete adapters may accept additional adapter-specific keys, but this is the core portable subset.                                                                                                                                                                                                                                                              |
| opts.powerPreference  | `GPUPowerPreference`        |        ✖ | `undefined` | Passed to adapter selection by browser/node implementations. The mock adapter ignores it.                                                                                                                                                                                                                                                                                                 |
| opts.requiredFeatures | `readonly GPUFeatureName[]` |        ✖ | `undefined` | Forwarded to native `adapter.requestDevice({ requiredFeatures })` by browser/node implementations after a `validateRequiredFeatures` check against the adapter's supported features (unsupported names throw `VGPU-FEATURE-UNSUPPORTED`). The mock adapter honors it against its declared `createMockAdapter({ features })` set and enables exactly the requested features on the device. |
| opts.requiredLimits   | `RequiredDeviceLimits`      |        ✖ | `undefined` | Forwarded unchanged to native `adapter.requestDevice({ requiredLimits })`; custom/mock adapters receive the same option.                                                                                                                                                                                                                                                                  |
| opts.label            | `string`                    |        ✖ | `undefined` | Node adapter assigns it to `GPUDevice.label`; browser core request path currently does not assign it in `vgpu-api`, and the mock adapter ignores it.                                                                                                                                                                                                                                      |

**Returns:** `requestDevice(opts?)` returns `Promise<Device>` wrapping the raw `GPUDevice` created by the concrete adapter.

**Throws:**

* `VGPU-RING1-UNSUPPORTED` may be thrown by higher-level browser/node initialization paths when no adapter factory or browser adapter is available — provide a concrete adapter such as `createMockAdapter()` or run in a WebGPU-capable environment.
* Adapter-specific `VGPU-*` errors can be thrown before the core `Device` exists, for example Node adapter binary/adapter failures — inspect `.code`, `.message`, and `.fix` on `VGPUError`.
* `VGPU-FEATURE-UNSUPPORTED` is thrown before device creation when `requiredFeatures` names a feature the adapter does not support — remove the unsupported name(s) or use an adapter that supports them.
* Native WebGPU request errors may be thrown when `requiredLimits` values are unsupported — request only capabilities reported by the chosen adapter.

## Examples

```ts
import type { Device, VGPUAdapter } from "vgpu/core";
import { createMockAdapter } from "vgpu/mock";

async function withDevice(adapter: VGPUAdapter): Promise<Device> {
  return adapter.requestDevice({ label: "example-device" });
}

const device = await withDevice(createMockAdapter());
console.log(device.queue.gpu);
device.destroy();
```

```ts
import type { VGPUAdapter } from "vgpu/core";
import { createMockAdapter } from "vgpu/mock";

const adapter: VGPUAdapter = createMockAdapter();
const device = await adapter.requestDevice({
  powerPreference: "high-performance",
  requiredFeatures: [],
  requiredLimits: {},
});

const buffer = device.createBuffer({ size: 4, usage: ["copy_dst", "copy_src"] });
buffer.write(new Uint32Array([42]));
console.log(new Uint32Array(await buffer.read(4))[0]);

device.destroy();
```

## Notes

* `VGPUAdapter` is an interface, not a class. Import it with `import type` unless you only need documentation prose.
* The core interface intentionally has a small portable option set. Concrete adapters can extend it without changing `VGPUAdapter`.
* The mock adapter honors `requiredFeatures` against its declared `createMockAdapter({ features })` set (default none) and ignores the other `CreateDeviceOptions`; do not use a passing mock request as proof that native required features/limits are available.
* Use `Device.features` and `Device.limits` after request to gate optional code paths.
* **See also:** `Device`, `CreateDeviceOptions`, `VGPUError`, `createMockAdapter`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: VGPUError
description: `VGPUError` is the structured error base class used by vgpu. Use it when you need stable machine-readable `code`, `severity`, optional `fix`, `where`, and `cause` fields instead of parsing error messages.
---

# VGPUError



## Import

```ts
import { VGPUError, ValidationError } from "vgpu/core";
```

## Signature

```ts
type VGPUErrorSeverity = "error" | "warning" | "info";

interface VGPUErrorData {
  readonly code: string;
  readonly message: string;
  readonly severity?: VGPUErrorSeverity;
  readonly fix?: string;
  readonly where?: string;
  readonly cause?: unknown;
}

declare class VGPUError extends Error {
  readonly code: string;
  readonly severity: VGPUErrorSeverity;
  readonly fix?: string;
  readonly where?: string;
  readonly cause?: unknown;
  constructor(data: VGPUErrorData);
}

declare class ValidationError extends VGPUError {
  constructor(data: Omit<VGPUErrorData, "severity">);
}
```

## Parameters

### `new VGPUError(data)`

| Param         | Type                             | Required | Default     | Notes                                                                        |
| ------------- | -------------------------------- | -------: | ----------- | ---------------------------------------------------------------------------- |
| data.code     | `string`                         |        ✔ | —           | Stable machine-readable code. Core validation sites use `VGPU-CORE-*` codes. |
| data.message  | `string`                         |        ✔ | —           | Human-readable message passed to `Error`.                                    |
| data.severity | `"error" \| "warning" \| "info"` |        ✖ | `"error"`   | Stored as `.severity`; omitted data becomes an error.                        |
| data.fix      | `string`                         |        ✖ | `undefined` | Optional remediation text.                                                   |
| data.where    | `string`                         |        ✖ | `undefined` | Optional source/context label such as `"Device.createBuffer"`.               |
| data.cause    | `unknown`                        |        ✖ | `undefined` | Forwarded to `Error` via `{ cause }` and stored as `.cause`.                 |

### `new ValidationError(data)`

| Param        | Type      | Required | Default     | Notes                                         |
| ------------ | --------- | -------: | ----------- | --------------------------------------------- |
| data.code    | `string`  |        ✔ | —           | Stable machine-readable validation code.      |
| data.message | `string`  |        ✔ | —           | Human-readable validation message.            |
| data.fix     | `string`  |        ✖ | `undefined` | Optional remediation text.                    |
| data.where   | `string`  |        ✖ | `undefined` | Optional source/context label.                |
| data.cause   | `unknown` |        ✖ | `undefined` | Optional original error or validation detail. |

**Returns:**

* `new VGPUError(data)` returns an `Error` instance with `.name === "VGPUError"`, `.code`, `.severity`, optional `.fix`, optional `.where`, and optional `.cause`.
* `new ValidationError(data)` returns a `VGPUError` subclass with `.name === "ValidationError"` and `.severity === "error"`.

**Throws:** Constructors do not throw vgpu errors. They can only throw if the JavaScript runtime cannot construct `Error` or assign fields.

## Examples

```ts
import { VGPUError } from "vgpu/core";

const error = new VGPUError({
  code: "VGPU-CORE-INVALID-USAGE",
  message: "Buffer size must be greater than zero.",
  severity: "error",
  where: "Device.createBuffer",
  fix: "Pass a positive byte length.",
});

console.log(error.name, error.code, error.severity, error.where);
```

```ts
import { ValidationError } from "vgpu/core";

function requirePositive(value: number): void {
  if (value <= 0) {
    throw new ValidationError({
      code: "VGPU-CORE-INVALID-USAGE",
      message: "Expected a positive value.",
      where: "example.requirePositive",
    });
  }
}

try {
  requirePositive(0);
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.code); // "VGPU-CORE-INVALID-USAGE"
  }
}
```

```ts
import { createMockAdapter } from "vgpu/mock";
import { VGPUError } from "vgpu/core";

const device = await createMockAdapter().requestDevice();

device.pushErrorScope("validation");
device.createBuffer({ size: 0, usage: ["copy_dst"] });
const error = await device.popErrorScope();

if (error instanceof VGPUError) {
  console.log(error.code); // "VGPU-CORE-INVALID-USAGE"
}

device.destroy();
```

## Notes

* Match on `.code`, not `.message`. Messages can become more descriptive; codes are the stable contract.
* `ValidationError` forces severity to `"error"`; use `VGPUError` directly for `"warning"` or `"info"` severities.
* Core currently emits these `VGPU-CORE-*` codes from core layer (`vgpu/core`) code paths: `VGPU-CORE-INVALID-USAGE`, `VGPU-CORE-VALIDATION`, `VGPU-CORE-TEXTURE-DESTROYED`, `VGPU-CORE-TEXTURE-READ-INVALID`, `VGPU-CORE-UNSUPPORTED-FORMAT`, `VGPU-CORE-BIND-GROUP-LAYOUT-REQUIRED`, `VGPU-CORE-SAMPLER-ANISOTROPY-FILTERS`, `VGPU-CORE-BINDING-INVALID`, and `VGPU-CORE-VISIBILITY-INVALID`.
* Native WebGPU errors are converted to `VGPU-CORE-VALIDATION` only by `Device.popErrorScope()`; other native calls may still throw native errors directly.
* **See also:** `Device`, `Buffer`, `Texture`, `bind`, `VGPUAdapter`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: macOS
description: Generate a Swift shader package from WGSL and use its functions, packers, and bindings with your own Metal code.
---

# macOS



Generate a Swift package from WGSL modules, then use its functions and bindings with Metal.
Your application owns the device, pipelines, resources, encoders, synchronization, and presentation.

> Beta: Install the optional `@vgpu/native` companion alongside the same exact RC version of `vgpu`. Native tests
> exercise the direct integration on Apple silicon; they do not establish a release support matrix.

## Start with a draw

[Load Metal functions](/docs/native/macos/metal/functions) explains how to add the generated package to
a Swift consumer and load its selected functions on an existing device.

[Render WGSL with Metal](/docs/native/macos/metal/rendering) connects imported WGSL to an
application-owned pipeline and render encoder. The generated program is neither a view nor a
renderer, and the application decides when to draw.

When a program needs data, follow [Pack uniforms for Metal](/docs/native/macos/metal/uniforms) and
[Bind Metal buffers](/docs/native/macos/metal/bindings). Uniform bytes follow the reflected shader layout,
not the in-memory layout of an arbitrary Swift struct. Bindings accept ordinary Metal buffers with
explicit offsets and lengths.

## Compose programs with native work

The generated API does not restrict the application to a single effect. Use native Metal to
combine programs, select attachments, and schedule work:

* [Use multiple render targets](/docs/native/macos/metal/render/targets) with application-owned textures.
* [Dispatch WGSL compute](/docs/native/macos/metal/compute/dispatch) against explicit storage-buffer ranges.
* [Use prepared compute bindings](/docs/native/macos/metal/compute/prepared-bindings) when managing internal uploads yourself.
* [Encode native indirect dispatch](/docs/native/macos/metal/compute/indirect-dispatch) and replay commands.
* [Render computed data](/docs/native/macos/metal/compute/rendering) without an intermediate CPU readback.

The indirect example is a bounded Metal integration, not a TypeScript render-bundle runtime.
Resource allocation, command lifetime, hazards, and synchronization remain application responsibilities.

## Generate the shader package

[Configure a Metal package](/docs/native/macos/metal/tooling/configuration) selects the WGSL sources,
render or compute entry points, Swift module name, and generated output directory.

The tooling workflow separates [toolchain diagnostics](/docs/native/macos/metal/tooling/doctor),
shader validation, generation, and read-only integrity checks.
[Build and verify a Metal package](/docs/native/macos/metal/tooling/build) defines those commands and
marks what remains under development.
[Resolve shader inputs](/docs/native/macos/metal/tooling/sources) explains imports and captured build inputs.

Add the generated directory as a local Swift package dependency of the consuming application.
The generated package has no external Swift dependencies. Build it through the consuming project,
whose build products stay outside the immutable generated directory.

You can commit or distribute that package with your project so another Swift consumer does not
need Node.js or a WGSL compiler. Regeneration still needs the native build toolchain. See
[Publish generated packages](/docs/native/macos/metal/tooling/publication) for output ownership and recovery.

## Check the current profile

The initial application target is Apple silicon. Generated artifacts declare macOS 14, Swift tools
6.0, and Metal 2.4. These settings are not proof of testing on every matching operating system or
toolchain. Physical Intel and AMD GPU execution is not covered by the current native tests.

Build tooling uses Node.js 22 and a selected Xcode installation with its Metal compiler component.
The application does not require Node.js, Tint, or Xcode at launch.

The current render binding profile covers fixed uniforms with flat float and float-vector fields.
Compute supports the storage layouts and runtime-array ranges listed in its guide. Texture and
sampler bindings, active overrides, and other unsupported shader features fail explicitly; the
compiler does not silently substitute a different program.

This limits the generated integration, not the Metal features available to the rest of the
application. Combine supported generated shaders with your own native resources, pipelines, and
other shader code where needed.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Canvas mouse tracking
description: Track pointer coordinates relative to a canvas layout and drawing buffer.
---

# Canvas mouse tracking



# canvasMouseTracker

Tracks pointer coordinates relative to a canvas layout and drawing buffer.

## Import

```ts
import { canvasMouseTracker } from "@vgpu/render/utils";
```

## Signature

```ts
export function canvasMouseTracker(spec: CanvasMouseTrackerSpec): CanvasMouseTracker;
```

## Parameters

| Param       | Type                   | Required | Default | Notes                    |
| ----------- | ---------------------- | -------- | ------- | ------------------------ |
| spec        | CanvasMouseTrackerSpec | ✔        | —       | Options.                 |
| spec.canvas | HTMLCanvasElement      | ✔        | —       | Event target.            |
| spec.flipY  | boolean                | ✖        | false   | Flips Y in both outputs. |

**Returns:** `CanvasMouseTracker` — live `position` and `dispose()`.

## Examples

```ts
import { canvasMouseTracker } from "@vgpu/render/utils";

const canvas = document.createElement("canvas");
const mouse = canvasMouseTracker({ canvas, flipY: true });

const { normalized, canvasPixels } = mouse.position;
const targetPixels = [normalized[0] * 960, normalized[1] * 540];
console.log(canvasPixels, targetPixels);
```

## Notes

* Positions start at `[0, 0]`. Scale `normalized` for another target; `canvasPixels` uses the canvas buffer.
* **See also:** `canvasResolution`, `frameClock`

***

# CanvasMouseTrackerSpec

Tracker options.

## Fields

| Field  | Type              | Required | Default | Notes                    |
| ------ | ----------------- | -------- | ------- | ------------------------ |
| canvas | HTMLCanvasElement | ✔        | —       | Canvas to track.         |
| flipY  | boolean           | ✖        | false   | Makes Y increase upward. |

***

# CanvasMouseTracker

Pointer tracker.

## Fields

| Field    | Type                | Required | Default | Notes                       |
| -------- | ------------------- | -------- | ------- | --------------------------- |
| position | CanvasMousePosition | ✔        | —       | Frozen coordinate snapshot. |
| dispose  | () => void          | ✔        | —       | Removes the listener.       |

***

# CanvasMousePosition

Pointer coordinates.

## Fields

| Field        | Type                       | Required | Default | Notes                                        |
| ------------ | -------------------------- | -------- | ------- | -------------------------------------------- |
| normalized   | readonly \[number, number] | ✔        | —       | Canvas-relative position, normally `[0, 1]`. |
| canvasPixels | readonly \[number, number] | ✔        | —       | Drawing-buffer position.                     |


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: canvasResolution
description: Reads the current drawing buffer size of a canvas and optionally watches for resize changes. Use it when you need `[width, height]` uniforms without wiring observers manually.
---

# canvasResolution



## Import

```ts
import { canvasResolution } from "@vgpu/render/utils";
```

## Signature

```ts
export function canvasResolution(
  canvas: HTMLCanvasElement,
  opts?: { readonly observe?: boolean },
): CanvasResolution;
```

## Parameters

| Param        | Type                   | Required | Default | Notes                                                                              |
| ------------ | ---------------------- | -------- | ------- | ---------------------------------------------------------------------------------- |
| canvas       | HTMLCanvasElement      | ✔        | —       | Target element; `width`/`height` are read from its drawing buffer, not CSS pixels. |
| opts         | \{ observe?: boolean } | ✖        | `{}`    | Optional behavior flags. Omitted options behave like `{ observe: false }`.         |
| opts.observe | boolean                | ✖        | false   | When true, attaches a `ResizeObserver` that keeps the cached width/height in sync. |

**Returns:** `CanvasResolution` — exposes `width`, `height`, and `dispose()`. Without `observe: true`, `width` and `height` are the initial drawing-buffer snapshot; with `observe: true`, they update when the `ResizeObserver` callback runs.

## Examples

```ts
import { canvasResolution } from "@vgpu/render/utils";

const canvas = document.createElement("canvas");
const effect = { set(values: { readonly resolution: readonly [number, number] }): void { void values; } };
const resolution = canvasResolution(canvas, { observe: true });

function frame() {
  effect.set({ resolution: [resolution.width, resolution.height] });
  requestAnimationFrame(frame);
}

frame();
// Later:
resolution.dispose();
```

## Notes

* When `observe` is `false`, `width`/`height` stay at the values captured when `canvasResolution(...)` was called. Create a new `CanvasResolution` or pass `observe: true` if later canvas attribute changes must be reflected.
* The helper calls `ResizeObserver.observe(canvas)` only when `observe: true`; call `dispose()` before removing the canvas to disconnect the observer.
* The returned values reflect the drawing buffer size (`canvas.width/height`), which already accounts for DPR scaling if you manage it manually.
* **See also:** `canvasMouseTracker`, `frameClock`


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: @vgpu/render/edit — Mesh Editing
description: CPU-side triangle mesh editing built on the render package's half-edge kernel. Use this entrypoint to convert render meshes into `EditableMesh`, select topology, run edit operators, and bake back to render meshes after the edit pipeline.
---

# @vgpu/render/edit — Mesh Editing



## Index

* Creation and conversion: [EditableMesh](#editablemesh), [toEditable](#toeditable), [toEditableWithDiagnostics](#toeditablewithdiagnostics)
* Selection and views: [EditableMeshValue](#editablemeshvalue), [ElementDomain](#elementdomain), [ElementSelection](#elementselection), [ElementSet](#elementset), [ScoredSelection](#scoredselection), [VertexView](#vertexview), [EdgeView](#edgeview), [FaceView](#faceview), [KernelHandle](#kernelhandle)
* Shape editing: [extrude](#extrude), [bevel](#bevel), [inset](#inset)
* Subdivision and cuts: [subdivideEdges](#subdivideedges), [subdivideFaces](#subdividefaces), [loopCut](#loopcut)
* Topology fill/bridge: [bridge](#bridge), [fillHole](#fillhole), [gridFill](#gridfill)
* Dissolve/weld/heal/bake: [dissolveVertices](#dissolvevertices), [dissolveEdges](#dissolveedges), [dissolveFaces](#dissolvefaces), [mergeByDistance](#mergebydistance), [healManifold](#healmanifold), [recomputeNormals](#recomputenormals)
* Diagnostics: [MeshEditError](#meshediterror), [MeshEditWarning](#mesheditwarning)

All imports in this file use the public edit entrypoint:

```ts
import { EditableMesh } from "@vgpu/render/edit";
```

## EditableMesh

Factory object for creating and baking `EditableMeshValue` instances. Use `fromArrays` when you already have typed geometry arrays; use `EditableMesh.toRenderMesh` or `mesh.toRenderMesh` only after the final edit step.

## Import

```ts
import { EditableMesh } from "@vgpu/render/edit";
```

## Signature

```ts
import type { Device } from "@vgpu/core";
import type { EditableMeshValue } from "@vgpu/render/edit";

declare const EditableMesh: {
  fromArrays(opts: {
    readonly positions: Float32Array;
    readonly normals?: Float32Array;
    readonly uvs?: Float32Array;
    readonly colors?: Float32Array;
    readonly indices?: Uint16Array | Uint32Array;
    readonly sharpEdges?: Uint8Array;
    readonly useSmooth?: Uint8Array;
    readonly creaseAngle?: number;
  }): EditableMeshValue;
  toRenderMesh(em: EditableMeshValue, opts: { readonly device: Device }): unknown;
};
```

## Parameters

| Param            | Type                       | Required | Default                                  | Notes                                                                                   |
| ---------------- | -------------------------- | -------- | ---------------------------------------- | --------------------------------------------------------------------------------------- |
| opts.positions   | Float32Array               | ✔        | —                                        | XYZ triples. Vertices with identical XYZ are welded by position during kernel build.    |
| opts.indices     | Uint16Array \| Uint32Array | ✖        | sequential `0..positions.length / 3 - 1` | Triangle indices; length must represent triangles.                                      |
| opts.normals     | Float32Array               | ✖        | omitted                                  | Preserved only as `hasNormals`; edit operators recompute face topology.                 |
| opts.uvs         | Float32Array               | ✖        | omitted                                  | Preserved only as `hasUVs`; operators may drop seams.                                   |
| opts.colors      | Float32Array               | ✖        | omitted                                  | Preserved only as `hasVertexColors`.                                                    |
| opts.sharpEdges  | Uint8Array                 | ✖        | auto from `creaseAngle`                  | Per-edge sharp mask in kernel edge order; if present it overrides auto-sharp detection. |
| opts.useSmooth   | Uint8Array                 | ✖        | all faces smooth (`1`)                   | Per-face smoothing flags.                                                               |
| opts.creaseAngle | number                     | ✖        | `Math.PI / 6`                            | Radians used to auto-mark sharp edges when `sharpEdges` is omitted.                     |
| em               | EditableMeshValue          | ✔        | —                                        | Mesh to bake for static `EditableMesh.toRenderMesh`.                                    |
| opts.device      | Device                     | ✔        | —                                        | Device used to create the render mesh buffers.                                          |

**Returns:** `EditableMeshValue` from `fromArrays`; render `Mesh` from `toRenderMesh`.
**Throws:** — no `MeshEditError` is thrown directly. Invalid or mismatched raw arrays can still produce invalid geometry at JavaScript/WebGPU boundaries.

## Examples

```ts
import { EditableMesh } from "@vgpu/render/edit";

const editableMeshExample = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
  indices: new Uint32Array([0, 1, 2]),
});

const editableFaceCount: number = editableMeshExample.faceCount;
```

## Notes

* The editable kernel is triangle-only; higher-order fills are represented as deterministic triangles.
* Bake once at the end of a pipeline instead of after every operator.
* **See also:** `toEditable`, `toEditableWithDiagnostics`, `EditableMeshValue`, `recomputeNormals`.

## toEditable

Converts a render `Mesh` into an editable half-edge mesh and discards diagnostics. Use when warnings are not important; otherwise call `toEditableWithDiagnostics`.

## Import

```ts
import { toEditable } from "@vgpu/render/edit";
```

## Signature

```ts
import { toEditable } from "@vgpu/render/edit";
import type { EditableMeshValue } from "@vgpu/render/edit";

type EditableInputMesh = Parameters<typeof toEditable>[0];
declare function toEditableSignature(mesh: EditableInputMesh, opts?: { readonly creaseAngle?: number }): EditableMeshValue;
```

## Parameters

| Param            | Type   | Required | Default                                         | Notes                                                                                                                              |
| ---------------- | ------ | -------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| mesh             | Mesh   | ✔        | —                                               | Render mesh-like object with attributes and bounds. Source arrays are used when available; otherwise a bbox box fallback is built. |
| opts.creaseAngle | number | ✖        | `Math.PI / 6` through `EditableMesh.fromArrays` | Radians for auto-sharp edge detection.                                                                                             |

**Returns:** `EditableMeshValue` — editable mesh ready for selections/operators.
**Throws:** — no `MeshEditError` is thrown directly.

## Examples

```ts
import { toEditable } from "@vgpu/render/edit";

const renderMeshForEdit = {
  vertexBuffer: {},
  vertexCount: 3,
  attributes: { stride: 12, position: { offset: 0, format: "float32x3" as const } },
  bbox: { min: new Float32Array([0, 0, 0]), max: new Float32Array([1, 1, 1]) },
} as unknown as Parameters<typeof toEditable>[0];
const toEditableMesh = toEditable(renderMeshForEdit, { creaseAngle: Math.PI / 4 });
```

## Notes

* Tangent-stripping warnings are hidden by this convenience function.
* **See also:** `toEditableWithDiagnostics`, `EditableMesh`, `MeshEditWarning`.

## toEditableWithDiagnostics

Converts a render `Mesh` and returns warnings such as stripped tangents. Use this at import/conversion boundaries so LLM-generated pipelines do not silently lose render-layer data.

## Import

```ts
import { toEditableWithDiagnostics } from "@vgpu/render/edit";
```

## Signature

```ts
import { toEditableWithDiagnostics } from "@vgpu/render/edit";
import type { EditableMeshValue, MeshEditWarning } from "@vgpu/render/edit";

type DiagnosticInputMesh = Parameters<typeof toEditableWithDiagnostics>[0];
declare function toEditableWithDiagnosticsSignature(
  mesh: DiagnosticInputMesh,
  opts?: { readonly creaseAngle?: number },
): { readonly mesh: EditableMeshValue; readonly warnings: readonly MeshEditWarning[] };
```

## Parameters

| Param            | Type   | Required | Default                                         | Notes                                                                                          |
| ---------------- | ------ | -------- | ----------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| mesh             | Mesh   | ✔        | —                                               | Render mesh-like object. If edit-source arrays are absent, bbox fallback arrays are generated. |
| opts.creaseAngle | number | ✖        | `Math.PI / 6` through `EditableMesh.fromArrays` | Radians for auto-sharp edge detection.                                                         |

**Returns:** `{ mesh, warnings }` — `warnings` is an array of `MeshEditWarning` objects.
**Throws:** — no `MeshEditError` is thrown directly.

## Examples

```ts
import { toEditableWithDiagnostics } from "@vgpu/render/edit";

const renderMeshWithDiagnostics = {
  vertexBuffer: {},
  vertexCount: 3,
  attributes: { stride: 12, position: { offset: 0, format: "float32x3" as const } },
  bbox: { min: new Float32Array([0, 0, 0]), max: new Float32Array([1, 1, 1]) },
} as unknown as Parameters<typeof toEditableWithDiagnostics>[0];
const diagnostics = toEditableWithDiagnostics(renderMeshWithDiagnostics);
const diagnosticsWarnings = diagnostics.warnings.map((warning) => warning.code);
```

## Notes

* Current explicit warning source is `TANGENTS_STRIPPED` when `mesh.attributes.tangent` exists.
* **See also:** `toEditable`, `MeshEditWarning`, `EditableMesh`.

## EditableMeshValue

Runtime shape of an editable mesh. It exposes counts, bounds, typed element sets, material/topology flags, hard-edge selection, an opaque kernel handle, and `toRenderMesh`.

## Import

```ts
import type { EditableMeshValue } from "@vgpu/render/edit";
```

## Signature

```ts
import type { Device } from "@vgpu/core";
import type { ElementSelection, ElementSet, KernelHandle } from "@vgpu/render/edit";

type Vec3 = Float32Array;

declare interface EditableMeshValue {
  readonly vertexCount: number;
  readonly edgeCount: number;
  readonly faceCount: number;
  readonly bounds: { readonly min: Vec3; readonly max: Vec3 };
  readonly vertices: ElementSet<"vertex">;
  readonly edges: ElementSet<"edge">;
  readonly faces: ElementSet<"face">;
  readonly isManifold: boolean;
  readonly hasUVs: boolean;
  readonly hasNormals: boolean;
  readonly hasVertexColors: boolean;
  readonly hardEdges: ElementSelection;
  readonly gpu: { readonly halfEdgeKernel: KernelHandle };
  toRenderMesh(opts: { readonly device: Device }): unknown;
}
```

## Parameters

| Field                                 | Type             | Required | Default | Notes                                                                     |
| ------------------------------------- | ---------------- | -------- | ------- | ------------------------------------------------------------------------- |
| vertexCount / edgeCount / faceCount   | number           | ✔        | —       | Counts in the current immutable editable mesh value.                      |
| bounds.min / bounds.max               | Vec3             | ✔        | —       | Axis-aligned bounds computed from positions.                              |
| vertices / edges / faces              | ElementSet       | ✔        | —       | Selection factories and traversal helpers for each domain.                |
| isManifold                            | boolean          | ✔        | —       | `true` only when every edge has two incident faces in the current kernel. |
| hasUVs / hasNormals / hasVertexColors | boolean          | ✔        | —       | Flags copied from input arrays; most operators rebuild topology arrays.   |
| hardEdges                             | ElementSelection | ✔        | —       | Edge selection where the kernel `isSharp` mask is nonzero.                |
| gpu.halfEdgeKernel                    | KernelHandle     | ✔        | —       | Opaque handle; do not construct or mutate directly.                       |
| toRenderMesh                          | function         | ✔        | —       | Bakes the editable mesh with `{ device }`.                                |

**Returns:** N/A — this is an interface/type export.
**Throws:** N/A — `toRenderMesh` can fail at render/WebGPU boundaries if passed an invalid `Device`.

## Examples

```ts
import { EditableMesh, type EditableMeshValue } from "@vgpu/render/edit";

const editableValueExample: EditableMeshValue = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const editableBoundsMin = editableValueExample.bounds.min;
```

## Notes

* Operators return new `EditableMeshValue` objects; do not assume selections from an old mesh are valid on a new mesh unless the result explicitly returns them.
* **See also:** `ElementSet`, `ElementSelection`, `KernelHandle`, `EditableMesh`.

## ElementDomain

String union naming the selectable topology domains.

## Import

```ts
import type { ElementDomain } from "@vgpu/render/edit";
```

## Signature

```ts
export type ElementDomain = "vertex" | "edge" | "face" | "loop";
```

## Parameters

| Variant    | Type          | Required | Default | Notes                                                                               |
| ---------- | ------------- | -------- | ------- | ----------------------------------------------------------------------------------- |
| `"vertex"` | ElementDomain | ✔        | —       | Vertex selections and `VertexView`.                                                 |
| `"edge"`   | ElementDomain | ✔        | —       | Edge selections, loops, rings, bridge/fill boundaries.                              |
| `"face"`   | ElementDomain | ✔        | —       | Face selections for extrusion/inset/dissolve.                                       |
| `"loop"`   | ElementDomain | ✔        | —       | Declared domain variant; public element sets currently operate on vertex/edge/face. |

**Returns:** N/A — type alias.
**Throws:** N/A.

## Examples

```ts
import type { ElementDomain } from "@vgpu/render/edit";

const selectedDomain: ElementDomain = "edge";
```

## Notes

* Operator validation is strict: passing a selection with the wrong domain throws `WRONG_DOMAIN`.
* **See also:** `ElementSelection`, `ElementSet`.

## ElementSelection

Immutable selection object passed to operators. Use `ElementSet` helpers (`mesh.faces.byIndex`, `mesh.edges.loop`, etc.) instead of hand-building selections unless you need an ordered boundary loop.

## Import

```ts
import type { ElementSelection } from "@vgpu/render/edit";
```

## Signature

```ts
import type { ElementDomain } from "@vgpu/render/edit";

declare interface ElementSelection {
  readonly domain: ElementDomain;
  readonly indices: ReadonlyArray<number>;
  readonly count: number;
  readonly ordered?: boolean;
}
```

## Parameters

| Field   | Type                  | Required | Default           | Notes                                                                              |
| ------- | --------------------- | -------- | ----------------- | ---------------------------------------------------------------------------------- |
| domain  | ElementDomain         | ✔        | —                 | Must match the operator target domain.                                             |
| indices | ReadonlyArray<number> | ✔        | —                 | Element indices in the mesh that owns the selection.                               |
| count   | number                | ✔        | —                 | Usually `indices.length`; operators check `count === 0` for empty selections.      |
| ordered | boolean               | ✖        | omitted / `false` | Required as `true` for loop-boundary operators (`bridge`, `fillHole`, `gridFill`). |

**Returns:** N/A — interface.
**Throws:** N/A.

## Examples

```ts
import { EditableMesh, type ElementSelection } from "@vgpu/render/edit";

const selectionMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const oneFaceSelection: ElementSelection = selectionMesh.faces.byIndex([0]);
```

## Notes

* Selections are mesh-local. Do not reuse a selection from the input mesh against an operator result unless the operator returned that selection for the new mesh.
* **See also:** `ElementSet`, `ScoredSelection`, `MeshEditError`.

## ElementSet

Domain-specific helper collection available as `mesh.vertices`, `mesh.edges`, and `mesh.faces`. Use it to create validated selections and compute simple adjacency expansions.

## Import

```ts
import type { ElementSet } from "@vgpu/render/edit";
```

## Signature

```ts
import type { ElementDomain, ElementSelection, EdgeView, FaceView, ScoredSelection, VertexView } from "@vgpu/render/edit";

type ElementView<D extends ElementDomain> = D extends "vertex" ? VertexView : D extends "edge" ? EdgeView : D extends "face" ? FaceView : never;

declare interface ElementSet<D extends ElementDomain> {
  readonly domain: D;
  readonly count: number;
  where(pred: (e: ElementView<D>) => boolean): ElementSelection;
  scoreBy(score: (e: ElementView<D>) => number): ScoredSelection;
  byIndex(indices: readonly number[]): ElementSelection;
  all(): ElementSelection;
  none(): ElementSelection;
  loop(seedEdge: number): D extends "edge" ? ElementSelection : never;
  ring(seedEdge: number): D extends "edge" ? ElementSelection : never;
  grow(sel: ElementSelection, layers?: number): ElementSelection;
  shrink(sel: ElementSelection, layers?: number): ElementSelection;
  boundaryOf(sel: ElementSelection): ElementSelection;
  connectedComponentOf(seed: number): ElementSelection;
}
```

## Parameters

| Method/Field                  | Type               | Required | Default | Notes                                                                                        |
| ----------------------------- | ------------------ | -------- | ------- | -------------------------------------------------------------------------------------------- |
| domain                        | D                  | ✔        | —       | `"vertex"`, `"edge"`, or `"face"` for the owning set.                                        |
| count                         | number             | ✔        | —       | Number of elements in the owning domain.                                                     |
| where.pred                    | function           | ✔        | —       | Called with `VertexView`, `EdgeView`, or `FaceView`; returned indices are sorted/deduped.    |
| scoreBy.score                 | function           | ✔        | —       | Produces a `ScoredSelection` sorted by score descending.                                     |
| byIndex.indices               | readonly number\[] | ✔        | —       | Out-of-range indices are filtered out.                                                       |
| loop.seedEdge / ring.seedEdge | number             | ✔        | —       | For edge sets only; current implementation returns connected edge walk with `ordered: true`. |
| grow\.layers / shrink.layers  | number             | ✖        | `1`     | Number of adjacency layers to expand or contract.                                            |
| boundaryOf.sel                | ElementSelection   | ✔        | —       | Returns an edge selection around face/vertex selections; edge input returns itself.          |
| connectedComponentOf.seed     | number             | ✔        | —       | Flood-fills adjacent elements in the same domain.                                            |

**Returns:** `ElementSelection` or `ScoredSelection` depending on the method.
**Throws:** — no `MeshEditError` is thrown directly by the public methods.

## Examples

```ts
import { EditableMesh } from "@vgpu/render/edit";

const elementSetMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const longEdges = elementSetMesh.edges.where((edge) => edge.length > 0.5);
```

## Notes

* `loop` and `ring` are typed for edge sets; do not call them on `vertices` or `faces`.
* **See also:** `ElementSelection`, `ScoredSelection`, `VertexView`, `EdgeView`, `FaceView`.

## ScoredSelection

Ranked selection helper returned by `ElementSet.scoreBy`. Use it to pick strongest or weakest candidates without manually sorting indices.

## Import

```ts
import type { ScoredSelection } from "@vgpu/render/edit";
```

## Signature

```ts
import type { ElementDomain, ElementSelection } from "@vgpu/render/edit";

declare interface ScoredSelection {
  readonly domain: ElementDomain;
  readonly entries: ReadonlyArray<{ readonly index: number; readonly score: number }>;
  top(): ElementSelection;
  topN(n: number): ElementSelection;
  threshold(min: number): ElementSelection;
  bottom(): ElementSelection;
  bottomN(n: number): ElementSelection;
}
```

## Parameters

| Method/Field       | Type          | Required | Default | Notes                                             |
| ------------------ | ------------- | -------- | ------- | ------------------------------------------------- |
| domain             | ElementDomain | ✔        | —       | Domain of all ranked entries.                     |
| entries            | ReadonlyArray | ✔        | —       | Sorted by score descending, then index ascending. |
| top / bottom       | function      | ✔        | —       | Equivalent to `topN(1)` / `bottomN(1)`.           |
| topN.n / bottomN.n | number        | ✔        | —       | Negative values clamp to `0`.                     |
| threshold.min      | number        | ✔        | —       | Keeps entries with `score >= min`.                |

**Returns:** `ElementSelection` from ranking methods.
**Throws:** — no `MeshEditError` is thrown directly.

## Examples

```ts
import { EditableMesh, type ScoredSelection } from "@vgpu/render/edit";

const scoredMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 2, 0, 0, 0, 1, 0]),
});
const scoredEdges: ScoredSelection = scoredMesh.edges.scoreBy((edge) => edge.length);
const longestEdge = scoredEdges.top();
```

## Notes

* `bottomN` re-sorts ascending at call time; `entries` remains descending.
* **See also:** `ElementSet`, `ElementSelection`.

## VertexView

Read-only per-vertex data passed to vertex `where`/`scoreBy` callbacks.

## Import

```ts
import type { VertexView } from "@vgpu/render/edit";
```

## Signature

```ts
type Vec3 = Float32Array;

declare interface VertexView {
  readonly index: number;
  readonly position: Vec3;
  readonly normal: Vec3;
  readonly valence: number;
  readonly isBoundary: boolean;
  readonly isManifold: boolean;
}
```

## Parameters

| Field      | Type    | Required | Default | Notes                                          |
| ---------- | ------- | -------- | ------- | ---------------------------------------------- |
| index      | number  | ✔        | —       | Vertex index in the current mesh.              |
| position   | Vec3    | ✔        | —       | XYZ position.                                  |
| normal     | Vec3    | ✔        | —       | Kernel-computed vertex normal.                 |
| valence    | number  | ✔        | —       | Number of incident edges.                      |
| isBoundary | boolean | ✔        | —       | True if any incident edge is boundary.         |
| isManifold | boolean | ✔        | —       | True when local incident topology is manifold. |

**Returns:** N/A — interface.
**Throws:** N/A.

## Examples

```ts
import { EditableMesh, type VertexView } from "@vgpu/render/edit";

const vertexViewMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const boundaryVertices = vertexViewMesh.vertices.where((vertex: VertexView) => vertex.isBoundary);
```

## Notes

* Views are snapshots produced by callbacks; do not store them as stable handles across edits.
* **See also:** `ElementSet`, `EdgeView`, `FaceView`.

## EdgeView

Read-only per-edge data passed to edge `where`/`scoreBy` callbacks.

## Import

```ts
import type { EdgeView } from "@vgpu/render/edit";
```

## Signature

```ts
type Vec3 = Float32Array;

declare interface EdgeView {
  readonly index: number;
  readonly midpoint: Vec3;
  readonly length: number;
  readonly direction: Vec3;
  readonly vertexA: number;
  readonly vertexB: number;
  readonly faceA: number | null;
  readonly faceB: number | null;
  readonly isBoundary: boolean;
  readonly isManifold: boolean;
  readonly isSharp: boolean;
}
```

## Parameters

| Field                | Type           | Required | Default | Notes                                                |
| -------------------- | -------------- | -------- | ------- | ---------------------------------------------------- |
| index                | number         | ✔        | —       | Edge index in current mesh.                          |
| midpoint / direction | Vec3           | ✔        | —       | Derived from endpoints.                              |
| length               | number         | ✔        | —       | Euclidean length.                                    |
| vertexA / vertexB    | number         | ✔        | —       | Endpoint vertex indices.                             |
| faceA / faceB        | number \| null | ✔        | —       | Incident faces; `faceB === null` indicates boundary. |
| isBoundary           | boolean        | ✔        | —       | True for one-sided edges.                            |
| isManifold           | boolean        | ✔        | —       | True when the edge has manifold incidence.           |
| isSharp              | boolean        | ✔        | —       | True when the kernel sharp mask is set.              |

**Returns:** N/A — interface.
**Throws:** N/A.

## Examples

```ts
import { EditableMesh, type EdgeView } from "@vgpu/render/edit";

const edgeViewMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const sharpEdges = edgeViewMesh.edges.where((edge: EdgeView) => edge.isSharp);
```

## Notes

* Use `mesh.hardEdges` when you just need the current sharp-edge selection.
* **See also:** `VertexView`, `FaceView`, `bevel`, `subdivideEdges`.

## FaceView

Read-only per-face data passed to face `where`/`scoreBy` callbacks.

## Import

```ts
import type { FaceView } from "@vgpu/render/edit";
```

## Signature

```ts
type Vec3 = Float32Array;

declare interface FaceView {
  readonly index: number;
  readonly center: Vec3;
  readonly normal: Vec3;
  readonly area: number;
  readonly vertexCount: number;
  readonly vertexIndices: ReadonlyArray<number>;
  readonly edgeIndices: ReadonlyArray<number>;
  readonly useSmooth: boolean;
}
```

## Parameters

| Field                       | Type                  | Required | Default | Notes                                             |
| --------------------------- | --------------------- | -------- | ------- | ------------------------------------------------- |
| index                       | number                | ✔        | —       | Face index in current mesh.                       |
| center / normal             | Vec3                  | ✔        | —       | Derived from triangle vertices and face normal.   |
| area                        | number                | ✔        | —       | Triangle area.                                    |
| vertexCount                 | number                | ✔        | —       | Always `3` for the triangle-only editable kernel. |
| vertexIndices / edgeIndices | ReadonlyArray<number> | ✔        | —       | Triangle vertex/edge indices.                     |
| useSmooth                   | boolean               | ✔        | —       | Per-face smoothing flag.                          |

**Returns:** N/A — interface.
**Throws:** N/A.

## Examples

```ts
import { EditableMesh, type FaceView } from "@vgpu/render/edit";

const faceViewMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const upwardFaces = faceViewMesh.faces.where((face: FaceView) => face.normal[2] > 0);
```

## Notes

* `vertexCount` is still exposed so future kernels can remain source-compatible with code that checks it.
* **See also:** `ElementSet`, `extrude`, `inset`, `dissolveFaces`.

## KernelHandle

Opaque branded handle to the internal half-edge kernel. It exists so editable values can carry kernel data without exposing mutation APIs.

## Import

```ts
import type { KernelHandle } from "@vgpu/render/edit";
```

## Signature

```ts
declare const kernelBrand: unique symbol;
export type KernelHandle = { readonly [kernelBrand]: never };
```

## Parameters

| Field            | Type          | Required | Default | Notes                                                          |
| ---------------- | ------------- | -------- | ------- | -------------------------------------------------------------- |
| branded property | unique symbol | ✔        | —       | Compile-time brand only; not constructible through public API. |

**Returns:** N/A — type alias.
**Throws:** N/A.

## Examples

```ts
import { EditableMesh, type KernelHandle } from "@vgpu/render/edit";

const kernelHandleMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const kernelHandle: KernelHandle = kernelHandleMesh.gpu.halfEdgeKernel;
```

## Notes

* Do not serialize or construct a `KernelHandle`; use public operators instead.
* **See also:** `EditableMeshValue`, `EditableMesh`.

## extrude

Extrudes selected faces along their face normals or an explicit direction. Use it for raised panels, shells, and block-out modeling.

## Import

```ts
import { extrude } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface ExtrudeOptions {
  readonly distance: number;
  readonly inset?: number;
  readonly direction?: readonly [number, number, number];
  readonly mode?: "region" | "individual";
}

declare interface ExtrudeResult {
  readonly mesh: EditableMeshValue;
  readonly sideFaces: ElementSelection;
  readonly capFaces: ElementSelection;
  readonly boundaryEdges: ElementSelection;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function extrude(em: EditableMeshValue, faces: ElementSelection, opts: ExtrudeOptions): ExtrudeResult;
```

## Parameters

| Param          | Type                       | Required | Default                     | Notes                                                                 |
| -------------- | -------------------------- | -------- | --------------------------- | --------------------------------------------------------------------- |
| em             | EditableMeshValue          | ✔        | —                           | Source mesh.                                                          |
| faces          | ElementSelection           | ✔        | —                           | Must be a non-empty face selection from `em`.                         |
| opts.distance  | number                     | ✔        | —                           | Offset distance along selected face normal or normalized `direction`. |
| opts.inset     | number                     | ✖        | `0`                         | Fraction toward each face center before lifting. No clamp is applied. |
| opts.direction | `[number, number, number]` | ✖        | selected face normal        | Normalized internally; zero vector behaves as length `1` denominator. |
| opts.mode      | `"region" \| "individual"` | ✖        | accepted but not used in v1 | Current implementation extrudes each selected triangle independently. |

**Returns:** `ExtrudeResult` — edited mesh plus side, cap, and boundary-edge selections on the result mesh.
**Throws:** `MeshEditError` `WRONG_DOMAIN` if `faces.domain !== "face"`; `EMPTY_SELECTION` if `faces.count === 0`.

## Examples

```ts
import { EditableMesh, extrude } from "@vgpu/render/edit";

const extrudeMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const extruded = extrude(extrudeMesh, extrudeMesh.faces.byIndex([0]), { distance: 0.2, inset: 0.1 });
```

## Notes

* Source faces are removed; new side and cap faces are returned for highlighting/chaining.
* **See also:** `inset`, `bevel`, `recomputeNormals`.

## bevel

Bevels selected edges by shrinking incident faces and inserting strip faces. Use it to soften hard edges; v1 supports a single segment.

## Import

```ts
import { bevel } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface BevelOptions {
  readonly offset: number;
  readonly segments?: number;
  readonly profile?: number;
  readonly affect?: "edges" | "vertices";
  readonly markSharp?: boolean;
}

declare interface BevelResult {
  readonly mesh: EditableMeshValue;
  readonly newFaces: ElementSelection;
  readonly originalFaces: ElementSelection;
  readonly profileLoops: readonly ElementSelection[];
  readonly warnings?: readonly MeshEditWarning[];
}

declare function bevel(em: EditableMeshValue, edges: ElementSelection, opts: BevelOptions): BevelResult;
```

## Parameters

| Param          | Type                    | Required | Default                     | Notes                                                                                  |
| -------------- | ----------------------- | -------- | --------------------------- | -------------------------------------------------------------------------------------- |
| em             | EditableMeshValue       | ✔        | —                           | Source mesh.                                                                           |
| edges          | ElementSelection        | ✔        | —                           | Must be a non-empty edge selection.                                                    |
| opts.offset    | number                  | ✔        | —                           | Fraction toward each incident face center; clamped to `[0, 0.49]`.                     |
| opts.segments  | number                  | ✖        | `1`                         | Any value other than `1` emits `BEVEL_SEGMENTS_CLAMPED`; geometry remains one segment. |
| opts.profile   | number                  | ✖        | accepted but not used in v1 | Present in type for future bevel profiles.                                             |
| opts.affect    | `"edges" \| "vertices"` | ✖        | accepted but not used in v1 | Current implementation bevels selected edges/incident faces.                           |
| opts.markSharp | boolean                 | ✖        | `true`                      | Marks selected original/profile edges sharp when true.                                 |

**Returns:** `BevelResult` — edited mesh, strip faces, shrunken original faces, and profile loop edge selections.
**Throws:** `MeshEditError` `WRONG_DOMAIN` if `edges.domain !== "edge"`; `EMPTY_SELECTION` if `edges.count === 0`.

## Examples

```ts
import { EditableMesh, bevel } from "@vgpu/render/edit";

const bevelMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const beveled = bevel(bevelMesh, bevelMesh.edges.byIndex([0]), { offset: 0.05 });
```

## Notes

* Boundary edges are processed on their one incident face and reported with `NON_MANIFOLD_EDGE_SKIPPED` warnings.
* **See also:** `extrude`, `inset`, `EdgeView`.

## inset

Insets selected faces by adding an inner triangle and boundary rim faces. Use it before `extrude` for panel-like forms.

## Import

```ts
import { inset } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface InsetOptions {
  readonly thickness: number;
  readonly depth?: number;
  readonly individual?: boolean;
}

declare interface InsetResult {
  readonly mesh: EditableMeshValue;
  readonly insetFaces: ElementSelection;
  readonly boundaryFaces: ElementSelection;
  readonly rimEdges: ElementSelection;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function inset(em: EditableMeshValue, faces: ElementSelection, opts: InsetOptions): InsetResult;
```

## Parameters

| Param           | Type              | Required | Default                     | Notes                                                                                     |
| --------------- | ----------------- | -------- | --------------------------- | ----------------------------------------------------------------------------------------- |
| em              | EditableMeshValue | ✔        | —                           | Source mesh.                                                                              |
| faces           | ElementSelection  | ✔        | —                           | Must be a non-empty face selection.                                                       |
| opts.thickness  | number            | ✔        | —                           | Fraction toward face center; clamped to `[0, 0.49]`. Clamp emits `INSET_OVERLAP_CLAMPED`. |
| opts.depth      | number            | ✖        | `0`                         | Offset along each face normal after insetting.                                            |
| opts.individual | boolean           | ✖        | accepted but not used in v1 | Current implementation processes selected triangles individually.                         |

**Returns:** `InsetResult` — edited mesh plus inner faces, rim/boundary faces, and rim edges on the result mesh.
**Throws:** `MeshEditError` `WRONG_DOMAIN` if `faces.domain !== "face"`; `EMPTY_SELECTION` if `faces.count === 0`.

## Examples

```ts
import { EditableMesh, inset } from "@vgpu/render/edit";

const insetMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const insetResult = inset(insetMesh, insetMesh.faces.all(), { thickness: 0.2, depth: 0.05 });
```

## Notes

* Follow with `extrude(result.mesh, result.insetFaces, ...)` for raised or recessed panels.
* **See also:** `extrude`, `bevel`, `FaceView`.

## subdivideEdges

Splits selected edges and retriangulates incident triangles. Use it to add local resolution before detailed edits.

## Import

```ts
import { subdivideEdges } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection } from "@vgpu/render/edit";

declare interface SubdivideEdgesOptions { readonly cuts?: number }
declare interface SubdivideEdgesResult {
  readonly mesh: EditableMeshValue;
  readonly newVertices: ElementSelection;
  readonly newEdges: ElementSelection;
}

declare function subdivideEdges(em: EditableMeshValue, edges: ElementSelection, opts?: SubdivideEdgesOptions): SubdivideEdgesResult;
```

## Parameters

| Param     | Type                  | Required | Default | Notes                                                                           |
| --------- | --------------------- | -------- | ------- | ------------------------------------------------------------------------------- |
| em        | EditableMeshValue     | ✔        | —       | Source mesh.                                                                    |
| edges     | ElementSelection      | ✔        | —       | Must be a non-empty edge selection.                                             |
| opts      | SubdivideEdgesOptions | ✖        | `{}`    | Options object may be omitted.                                                  |
| opts.cuts | number                | ✖        | `1`     | Floored and clamped to minimum `1`; inserts this many points per selected edge. |

**Returns:** `SubdivideEdgesResult` — edited mesh with selections for inserted vertices and child edges.
**Throws:** `MeshEditError` `WRONG_DOMAIN` if `edges.domain !== "edge"`; `EMPTY_SELECTION` if `edges.count === 0`.

## Examples

```ts
import { EditableMesh, subdivideEdges } from "@vgpu/render/edit";

const subdivideEdgesMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const edgeSubdivision = subdivideEdges(subdivideEdgesMesh, subdivideEdgesMesh.edges.byIndex([0]), { cuts: 2 });
```

## Notes

* Sharp selected edges propagate sharpness to child edges.
* **See also:** `subdivideFaces`, `loopCut`, `bevel`.

## subdivideFaces

Subdivides selected triangles into four triangles per cut iteration using edge midpoints.

## Import

```ts
import { subdivideFaces } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection } from "@vgpu/render/edit";

declare interface SubdivideFacesOptions { readonly cuts?: number }
declare interface SubdivideFacesResult {
  readonly mesh: EditableMeshValue;
  readonly newFaces: ElementSelection;
  readonly newEdges: ElementSelection;
}

declare function subdivideFaces(em: EditableMeshValue, faces: ElementSelection, opts?: SubdivideFacesOptions): SubdivideFacesResult;
```

## Parameters

| Param     | Type                  | Required | Default | Notes                                                                                     |
| --------- | --------------------- | -------- | ------- | ----------------------------------------------------------------------------------------- |
| em        | EditableMeshValue     | ✔        | —       | Source mesh.                                                                              |
| faces     | ElementSelection      | ✔        | —       | Must be a non-empty face selection.                                                       |
| opts      | SubdivideFacesOptions | ✖        | `{}`    | Options object may be omitted.                                                            |
| opts.cuts | number                | ✖        | `1`     | Floored and clamped to minimum `1`; repeated cut iterations apply to newly-created faces. |

**Returns:** `SubdivideFacesResult` — edited mesh with selections for descendant faces and new edges.
**Throws:** `MeshEditError` `WRONG_DOMAIN` if `faces.domain !== "face"`; `EMPTY_SELECTION` if `faces.count === 0`.

## Examples

```ts
import { EditableMesh, subdivideFaces } from "@vgpu/render/edit";

const subdivideFacesMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const faceSubdivision = subdivideFaces(subdivideFacesMesh, subdivideFacesMesh.faces.all(), { cuts: 1 });
```

## Notes

* Original sharp face edges are split into sharp child edges.
* **See also:** `subdivideEdges`, `loopCut`, `FaceView`.

## loopCut

Attempts to cut an edge loop/ring through coplanar triangle pairs. Falls back to cutting only the seed edge when continuation is ambiguous.

## Import

```ts
import { loopCut } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface LoopCutOptions {
  readonly cuts?: number;
  readonly slide?: number;
  readonly markSharp?: boolean;
}

declare interface LoopCutResult {
  readonly mesh: EditableMeshValue;
  readonly insertedLoop: ElementSelection;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function loopCut(em: EditableMeshValue, seedEdge: number, opts?: LoopCutOptions): LoopCutResult;
```

## Parameters

| Param          | Type              | Required | Default              | Notes                                                                  |
| -------------- | ----------------- | -------- | -------------------- | ---------------------------------------------------------------------- |
| em             | EditableMeshValue | ✔        | —                    | Source mesh.                                                           |
| seedEdge       | number            | ✔        | —                    | Edge index; must be `0 <= seedEdge < em.edgeCount`.                    |
| opts           | LoopCutOptions    | ✖        | `{}`                 | Options object may be omitted.                                         |
| opts.cuts      | number            | ✖        | `1` in fallback only | Used only when ambiguous continuation falls back to `subdivideEdges`.  |
| opts.slide     | number            | ✖        | `0`                  | Maps to split factor `0.5 + slide * 0.5`, clamped to `[0.001, 0.999]`. |
| opts.markSharp | boolean           | ✖        | `false`              | Marks inserted loop edges sharp only in successful ring cuts.          |

**Returns:** `LoopCutResult` — edited mesh plus ordered inserted-loop edge selection.
**Throws:** `MeshEditError` `EMPTY_SELECTION` when `seedEdge` is out of range.

## Examples

```ts
import { EditableMesh, loopCut } from "@vgpu/render/edit";

const loopCutMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const loopCutResult = loopCut(loopCutMesh, 0, { slide: 0.25 });
```

## Notes

* Ambiguous topology returns `LOOP_CUT_AMBIGUOUS_CONTINUATION` and cuts only the seed edge.
* **See also:** `subdivideEdges`, `subdivideFaces`, `EdgeView`.

## bridge

Creates faces between two ordered edge loops in one selection. Use for connecting holes or separated boundary rings.

## Import

```ts
import { bridge } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface BridgeOptions {
  readonly twist?: number;
  readonly mode?: "faces" | "merge";
}

declare interface BridgeResult {
  readonly mesh: EditableMeshValue;
  readonly bridgeFaces: ElementSelection;
  readonly chosenTwist: number;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function bridge(em: EditableMeshValue, sel: ElementSelection, opts?: BridgeOptions): BridgeResult;
```

## Parameters

| Param      | Type                 | Required | Default                                    | Notes                                                                                 |
| ---------- | -------------------- | -------- | ------------------------------------------ | ------------------------------------------------------------------------------------- |
| em         | EditableMeshValue    | ✔        | —                                          | Source mesh.                                                                          |
| sel        | ElementSelection     | ✔        | —                                          | Must be a non-empty ordered edge selection containing two loops.                      |
| opts       | BridgeOptions        | ✖        | `{}`                                       | Options object may be omitted.                                                        |
| opts.twist | number               | ✖        | auto by shortest squared endpoint distance | Shift applied to second loop correspondence; returned as positive modulo loop length. |
| opts.mode  | `"faces" \| "merge"` | ✖        | `"faces"`                                  | `"merge"` throws `UNSUPPORTED_INPUT` in the triangle-only kernel.                     |

**Returns:** `BridgeResult` — edited mesh, bridge face selection, chosen twist, optional length-mismatch warnings.
**Throws:** `MeshEditError` `WRONG_DOMAIN`, `EMPTY_SELECTION`, or `NOT_ORDERED` from loop validation; `AMBIGUOUS_TOPOLOGY` when two loops cannot be split; `UNSUPPORTED_INPUT` for `mode: "merge"`; `DEGENERATE_RESULT` can propagate from invalid loop vertices.

## Examples

```ts
import { EditableMesh, bridge, type ElementSelection } from "@vgpu/render/edit";

const bridgeMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1]),
  indices: new Uint32Array([0, 1, 2, 3, 4, 5]),
});
const twoTriangleLoops: ElementSelection = { domain: "edge", indices: [0, 1, 2, 3, 4, 5], count: 6, ordered: true };
const bridged = bridge(bridgeMesh, twoTriangleLoops, { twist: 0 });
```

## Notes

* Different loop lengths are allowed; modulo correspondence is used and `BRIDGE_LOOP_LENGTH_MISMATCH` is emitted.
* **See also:** `fillHole`, `gridFill`, `ElementSelection`.

## fillHole

Fills an ordered boundary loop with a triangle fan.

## Import

```ts
import { fillHole } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface FillHoleOptions { readonly method?: "triangulate" | "ngon" | "beautify" }
declare interface FillHoleResult {
  readonly mesh: EditableMeshValue;
  readonly newFaces: ElementSelection;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function fillHole(em: EditableMeshValue, boundary: ElementSelection, opts?: FillHoleOptions): FillHoleResult;
```

## Parameters

| Param       | Type                                    | Required | Default         | Notes                                                                                |
| ----------- | --------------------------------------- | -------- | --------------- | ------------------------------------------------------------------------------------ |
| em          | EditableMeshValue                       | ✔        | —               | Source mesh.                                                                         |
| boundary    | ElementSelection                        | ✔        | —               | Must be a non-empty ordered edge loop.                                               |
| opts        | FillHoleOptions                         | ✖        | `{}`            | Options object may be omitted.                                                       |
| opts.method | `"triangulate" \| "ngon" \| "beautify"` | ✖        | `"triangulate"` | Non-triangulate methods still emit a triangle fan and warn `FILL_HOLE_TRIANGULATED`. |

**Returns:** `FillHoleResult` — edited mesh and newly-created faces.
**Throws:** `MeshEditError` `WRONG_DOMAIN`, `EMPTY_SELECTION`, or `NOT_ORDERED` from loop validation; `AMBIGUOUS_TOPOLOGY`/`DEGENERATE_RESULT` can propagate from invalid loop vertices.

## Examples

```ts
import { EditableMesh, fillHole, type ElementSelection } from "@vgpu/render/edit";

const fillHoleMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const triangleBoundary: ElementSelection = { domain: "edge", indices: [0, 1, 2], count: 3, ordered: true };
const filledHole = fillHole(fillHoleMesh, triangleBoundary);
```

## Notes

* Non-planar loops warn `FILL_NON_PLANAR_BOUNDARY` and are still triangulated.
* **See also:** `gridFill`, `bridge`, `ElementSet.boundaryOf`.

## gridFill

Deterministically represents a grid fill as triangles around the boundary center. Use it when callers request grid-fill semantics but the triangle-only kernel is acceptable.

## Import

```ts
import { gridFill } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface GridFillOptions { readonly spanMode?: "auto" | number }
declare interface GridFillResult {
  readonly mesh: EditableMeshValue;
  readonly newFaces: ElementSelection;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function gridFill(em: EditableMeshValue, boundary: ElementSelection, opts?: GridFillOptions): GridFillResult;
```

## Parameters

| Param         | Type               | Required | Default                   | Notes                                                                  |
| ------------- | ------------------ | -------- | ------------------------- | ---------------------------------------------------------------------- |
| em            | EditableMeshValue  | ✔        | —                         | Source mesh.                                                           |
| boundary      | ElementSelection   | ✔        | —                         | Must be a non-empty ordered edge loop.                                 |
| opts          | GridFillOptions    | ✖        | `{}`                      | Options object may be omitted.                                         |
| opts.spanMode | `"auto" \| number` | ✖        | `"auto"` for warning text | Numeric values `< 1` throw `DEGENERATE_RESULT`; all modes triangulate. |

**Returns:** `GridFillResult` — edited mesh, new fan faces, and warnings.
**Throws:** `MeshEditError` `WRONG_DOMAIN`, `EMPTY_SELECTION`, or `NOT_ORDERED` from loop validation; `DEGENERATE_RESULT` for numeric `spanMode < 1`; `AMBIGUOUS_TOPOLOGY` can propagate from invalid loop vertices.

## Examples

```ts
import { EditableMesh, gridFill, type ElementSelection } from "@vgpu/render/edit";

const gridFillMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const gridBoundary: ElementSelection = { domain: "edge", indices: [0, 1, 2], count: 3, ordered: true };
const gridFilled = gridFill(gridFillMesh, gridBoundary, { spanMode: "auto" });
```

## Notes

* Always emits `GRID_FILL_TRIANGULATED`; odd loop lengths also warn with `FILL_NON_PLANAR_BOUNDARY` wording.
* **See also:** `fillHole`, `bridge`, `MeshEditWarning`.

## dissolveVertices

Dissolves selected non-boundary vertices by dissolving their surrounding faces.

## Import

```ts
import { dissolveVertices } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface DissolveVerticesOptions {
  readonly useFaceSplit?: boolean;
  readonly useBoundaryTear?: boolean;
}

declare interface DissolveVerticesResult {
  readonly mesh: EditableMeshValue;
  readonly surroundingFaces: ElementSelection;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function dissolveVertices(em: EditableMeshValue, vertices: ElementSelection, opts?: DissolveVerticesOptions): DissolveVerticesResult;
```

## Parameters

| Param                | Type                    | Required | Default                     | Notes                                        |
| -------------------- | ----------------------- | -------- | --------------------------- | -------------------------------------------- |
| em                   | EditableMeshValue       | ✔        | —                           | Source mesh.                                 |
| vertices             | ElementSelection        | ✔        | —                           | Must be a non-empty vertex selection.        |
| opts                 | DissolveVerticesOptions | ✖        | `{}`                        | Options object may be omitted.               |
| opts.useFaceSplit    | boolean                 | ✖        | accepted but not used in v1 | Present in type only.                        |
| opts.useBoundaryTear | boolean                 | ✖        | accepted but not used in v1 | Boundary vertices are skipped with warnings. |

**Returns:** `DissolveVerticesResult` — edited mesh and resulting surrounding face selection.
**Throws:** `MeshEditError` `WRONG_DOMAIN` if `vertices.domain !== "vertex"`; `EMPTY_SELECTION` if `vertices.count === 0`.

## Examples

```ts
import { EditableMesh, dissolveVertices } from "@vgpu/render/edit";

const dissolveVerticesMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const dissolvedVertices = dissolveVertices(dissolveVerticesMesh, dissolveVerticesMesh.vertices.byIndex([0]));
```

## Notes

* Boundary vertices are skipped with `NON_MANIFOLD_VERTEX_SKIPPED`.
* **See also:** `dissolveEdges`, `dissolveFaces`, `mergeByDistance`.

## dissolveEdges

Removes selected internal edges by merging each adjacent face pair and retriangulating with a deterministic diagonal.

## Import

```ts
import { dissolveEdges } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface DissolveEdgesOptions { readonly useVerts?: boolean }
declare interface DissolveEdgesResult {
  readonly mesh: EditableMeshValue;
  readonly mergedFaces: ElementSelection;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function dissolveEdges(em: EditableMeshValue, edges: ElementSelection, opts?: DissolveEdgesOptions): DissolveEdgesResult;
```

## Parameters

| Param         | Type                 | Required | Default                     | Notes                                                                                    |
| ------------- | -------------------- | -------- | --------------------------- | ---------------------------------------------------------------------------------------- |
| em            | EditableMeshValue    | ✔        | —                           | Source mesh.                                                                             |
| edges         | ElementSelection     | ✔        | —                           | Must be a non-empty edge selection. Boundary/overlapping jobs are skipped with warnings. |
| opts          | DissolveEdgesOptions | ✖        | `{}`                        | Options object may be omitted.                                                           |
| opts.useVerts | boolean              | ✖        | accepted but not used in v1 | Present in type only.                                                                    |

**Returns:** `DissolveEdgesResult` — edited mesh and merged face selection.
**Throws:** `MeshEditError` `WRONG_DOMAIN` if `edges.domain !== "edge"`; `EMPTY_SELECTION` if `edges.count === 0`.

## Examples

```ts
import { EditableMesh, dissolveEdges } from "@vgpu/render/edit";

const dissolveEdgesMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const dissolvedEdges = dissolveEdges(dissolveEdgesMesh, dissolveEdgesMesh.edges.byIndex([0]));
```

## Notes

* Successful jobs emit `DISSOLVE_FACES_RETRIANGULATED` because the merged quad remains two triangles.
* **See also:** `dissolveVertices`, `dissolveFaces`, `EdgeView`.

## dissolveFaces

Removes selected face regions and retriangulates each region boundary as a fan.

## Import

```ts
import { dissolveFaces } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface DissolveFacesResult {
  readonly mesh: EditableMeshValue;
  readonly resultFace: ElementSelection;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function dissolveFaces(em: EditableMeshValue, faces: ElementSelection): DissolveFacesResult;
```

## Parameters

| Param | Type              | Required | Default | Notes                                                                                 |
| ----- | ----------------- | -------- | ------- | ------------------------------------------------------------------------------------- |
| em    | EditableMeshValue | ✔        | —       | Source mesh.                                                                          |
| faces | ElementSelection  | ✔        | —       | Must be a non-empty face selection. Connected components are dissolved independently. |

**Returns:** `DissolveFacesResult` — edited mesh and result face selection.
**Throws:** `MeshEditError` `WRONG_DOMAIN` if `faces.domain !== "face"`; `EMPTY_SELECTION` if `faces.count === 0`.

## Examples

```ts
import { EditableMesh, dissolveFaces } from "@vgpu/render/edit";

const dissolveFacesMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const dissolvedFaces = dissolveFaces(dissolveFacesMesh, dissolveFacesMesh.faces.all());
```

## Notes

* Degenerate regions warn `DEGENERATE_FACE_DROPPED`; multi-face or n-gon regions warn `DISSOLVE_FACES_RETRIANGULATED`.
* **See also:** `dissolveEdges`, `dissolveVertices`, `fillHole`.

## mergeByDistance

Welds vertices whose positions are within a threshold, removes collapsed faces, and returns an old-to-new vertex map.

## Import

```ts
import { mergeByDistance } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, ElementSelection, MeshEditWarning } from "@vgpu/render/edit";

declare interface MergeByDistanceOptions {
  readonly threshold?: number;
  readonly selection?: ElementSelection;
  readonly key?: "position" | "full-vertex";
}

declare interface MergeByDistanceResult {
  readonly mesh: EditableMeshValue;
  readonly mergeMap: ReadonlyMap<number, number>;
  readonly weldedCount: number;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function mergeByDistance(em: EditableMeshValue, opts?: MergeByDistanceOptions): MergeByDistanceResult;
```

## Parameters

| Param          | Type                          | Required | Default                                    | Notes                                                                                                     |
| -------------- | ----------------------------- | -------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------------- |
| em             | EditableMeshValue             | ✔        | —                                          | Source mesh.                                                                                              |
| opts           | MergeByDistanceOptions        | ✖        | `{}`                                       | Options object may be omitted.                                                                            |
| opts.threshold | number                        | ✖        | `1e-4`                                     | Euclidean position distance for clustering.                                                               |
| opts.selection | ElementSelection              | ✖        | `em.vertices.all()`                        | Must be a vertex selection. Only selected vertices are clustered; all faces are remapped.                 |
| opts.key       | `"position" \| "full-vertex"` | ✖        | warning mode equivalent to `"full-vertex"` | Clustering is position-based in v1. `"position"` emits `SEAM_DESTROYED` when UV/normal/color flags exist. |

**Returns:** `MergeByDistanceResult` — welded mesh, old vertex index to new vertex index map (`-1` for unused), and welded count.
**Throws:** `MeshEditError` `WRONG_DOMAIN` if `opts.selection.domain !== "vertex"`; `EMPTY_SELECTION` if `opts.selection.count === 0`.

## Examples

```ts
import { EditableMesh, mergeByDistance } from "@vgpu/render/edit";

const mergeMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 0.00001, 0, 0, 0, 1, 0]),
});
const merged = mergeByDistance(mergeMesh, { threshold: 0.001 });
```

## Notes

* Collapsed faces are removed and reported with `MERGE_DEGENERATE_FACES_REMOVED`.
* **See also:** `healManifold`, `dissolveVertices`, `recomputeNormals`.

## healManifold

Deterministic cleanup pass that removes duplicate, degenerate, and overused-edge faces where possible.

## Import

```ts
import { healManifold } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue, MeshEditWarning } from "@vgpu/render/edit";

declare interface HealManifoldReport {
  readonly nonManifoldEdgesFixed: number;
  readonly nonManifoldVerticesFixed: number;
  readonly holesFixed: number;
  readonly duplicateFacesRemoved: number;
}

declare interface HealManifoldResult {
  readonly mesh: EditableMeshValue;
  readonly report: HealManifoldReport;
  readonly warnings?: readonly MeshEditWarning[];
}

declare function healManifold(em: EditableMeshValue): HealManifoldResult;
```

## Parameters

| Param | Type              | Required | Default | Notes        |
| ----- | ----------------- | -------- | ------- | ------------ |
| em    | EditableMeshValue | ✔        | —       | Source mesh. |

**Returns:** `HealManifoldResult` — cleaned mesh plus report. `nonManifoldVerticesFixed` and `holesFixed` are currently always `0`.
**Throws:** — no `MeshEditError` is thrown directly.

## Examples

```ts
import { EditableMesh, healManifold } from "@vgpu/render/edit";

const healMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
  indices: new Uint32Array([0, 1, 2, 0, 1, 2]),
});
const healed = healManifold(healMesh);
```

## Notes

* Remaining non-manifold residue is reported as `HEAL_NON_MANIFOLD_RESIDUE`.
* **See also:** `mergeByDistance`, `recomputeNormals`, `MeshEditWarning`.

## recomputeNormals

Rebuilds the editable mesh and recomputes face normals using smoothing components and sharp edges or a new crease angle.

## Import

```ts
import { recomputeNormals } from "@vgpu/render/edit";
```

## Signature

```ts
import type { EditableMeshValue } from "@vgpu/render/edit";

declare interface RecomputeNormalsOptions {
  readonly weighting?: "angle" | "area" | "uniform";
  readonly creaseAngle?: number;
}

declare function recomputeNormals(em: EditableMeshValue, opts?: RecomputeNormalsOptions): EditableMeshValue;
```

## Parameters

| Param            | Type                             | Required | Default                          | Notes                                                                                    |
| ---------------- | -------------------------------- | -------- | -------------------------------- | ---------------------------------------------------------------------------------------- |
| em               | EditableMeshValue                | ✔        | —                                | Source mesh. Empty meshes are returned unchanged.                                        |
| opts             | RecomputeNormalsOptions          | ✖        | `{}`                             | Options object may be omitted.                                                           |
| opts.weighting   | `"angle" \| "area" \| "uniform"` | ✖        | `"angle"`                        | Weighting mode for smoothing component normals.                                          |
| opts.creaseAngle | number                           | ✖        | preserve current sharp-edge mask | If provided, rebuilds sharp edges from the crease angle instead of preserving `isSharp`. |

**Returns:** `EditableMeshValue` — new mesh with recomputed kernel face normals, or the same mesh when `faceCount === 0`.
**Throws:** — no `MeshEditError` is thrown directly.

## Examples

```ts
import { EditableMesh, recomputeNormals } from "@vgpu/render/edit";

const normalsMesh = EditableMesh.fromArrays({
  positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]),
});
const normalsRecomputed = recomputeNormals(normalsMesh, { weighting: "area" });
```

## Notes

* Run after topology-changing operators if downstream code relies on smooth normals.
* **See also:** `EditableMesh`, `mergeByDistance`, `healManifold`.

## MeshEditError

Error class thrown by validation and topology operators. Catch by `instanceof MeshEditError` and branch on `code`.

## Import

```ts
import { MeshEditError } from "@vgpu/render/edit";
```

## Signature

```ts
export type MeshEditErrorCode =
  | "NON_MANIFOLD"
  | "STALE_SELECTION"
  | "EMPTY_SELECTION"
  | "WRONG_DOMAIN"
  | "NOT_ORDERED"
  | "DEGENERATE_RESULT"
  | "AMBIGUOUS_TOPOLOGY"
  | "UNSUPPORTED_INPUT";

declare class MeshEditError extends Error {
  readonly code: MeshEditErrorCode;
  readonly suggestion?: string;
  constructor(opts: { readonly code: MeshEditErrorCode; readonly message?: string; readonly suggestion?: string });
}
```

## Parameters

| Param/Field     | Type              | Required | Default           | Notes                                          |
| --------------- | ----------------- | -------- | ----------------- | ---------------------------------------------- |
| opts.code       | MeshEditErrorCode | ✔        | —                 | Machine-readable error code.                   |
| opts.message    | string            | ✖        | `opts.code`       | Error message passed to `Error`.               |
| opts.suggestion | string            | ✖        | omitted           | Optional recovery hint.                        |
| code            | MeshEditErrorCode | ✔        | —                 | Public readonly field copied from constructor. |
| suggestion      | string            | ✖        | omitted           | Public readonly optional field.                |
| name            | string            | ✔        | `"MeshEditError"` | Set by constructor.                            |

**Returns:** `MeshEditError` instance from `new MeshEditError(...)`.
**Throws:** — constructor does not throw.

## Examples

```ts
import { MeshEditError } from "@vgpu/render/edit";

const meshEditError = new MeshEditError({ code: "EMPTY_SELECTION", suggestion: "Select at least one face." });
const meshEditErrorCode = meshEditError.code;
```

## Notes

* Common validation codes: `WRONG_DOMAIN`, `EMPTY_SELECTION`, `NOT_ORDERED`.
* **See also:** `ElementSelection`, `bridge`, `gridFill`.

## MeshEditWarning

Non-fatal diagnostic emitted in operator result `warnings` arrays. Use warnings to explain deterministic fallbacks and data loss.

## Import

```ts
import { MeshEditWarning } from "@vgpu/render/edit";
```

## Signature

```ts
export type MeshEditWarningCode =
  | "NON_MANIFOLD_EDGE_SKIPPED"
  | "NON_MANIFOLD_VERTEX_SKIPPED"
  | "DEGENERATE_FACE_DROPPED"
  | "TANGENTS_STRIPPED"
  | "BEVEL_ACUTE_CLAMPED"
  | "BEVEL_SEGMENTS_CLAMPED"
  | "INSET_OVERLAP_CLAMPED"
  | "SEAM_DESTROYED"
  | "BRIDGE_LOOP_LENGTH_MISMATCH"
  | "FILL_NON_PLANAR_BOUNDARY"
  | "LOOP_CUT_AMBIGUOUS_CONTINUATION"
  | "FILL_HOLE_TRIANGULATED"
  | "GRID_FILL_TRIANGULATED"
  | "DISSOLVE_FACES_RETRIANGULATED"
  | "MERGE_DEGENERATE_FACES_REMOVED"
  | "HEAL_NON_MANIFOLD_RESIDUE";

declare class MeshEditWarning {
  readonly code: MeshEditWarningCode;
  readonly reason: string;
  readonly element?: { readonly domain: "vertex" | "edge" | "face"; readonly index: number };
  constructor(
    code: MeshEditWarningCode,
    reason: string,
    element?: { readonly domain: "vertex" | "edge" | "face"; readonly index: number },
  );
}
```

## Parameters

| Param/Field | Type                                                      | Required | Default | Notes                                                |
| ----------- | --------------------------------------------------------- | -------- | ------- | ---------------------------------------------------- |
| code        | MeshEditWarningCode                                       | ✔        | —       | Machine-readable warning code.                       |
| reason      | string                                                    | ✔        | —       | Human-readable explanation.                          |
| element     | `{ domain: "vertex" \| "edge" \| "face"; index: number }` | ✖        | omitted | Optional source element associated with the warning. |

**Returns:** `MeshEditWarning` instance from `new MeshEditWarning(...)`.
**Throws:** — constructor does not throw.

## Examples

```ts
import { MeshEditWarning } from "@vgpu/render/edit";

const meshEditWarning = new MeshEditWarning("GRID_FILL_TRIANGULATED", "Triangle-only output was used.");
const warningReason = meshEditWarning.reason;
```

## Notes

* Treat warnings as actionable diagnostics, not failures; operators still return a mesh.
* **See also:** `toEditableWithDiagnostics`, `bevel`, `gridFill`, `healManifold`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: frameClock
description: Creates a monotonic time source with pause/resume support for ad-hoc render loops. Use it when you need consistent elapsed seconds outside the built-in `frame()` loop.
---

# frameClock



## Import

```ts
import { frameClock } from "@vgpu/render/utils";
```

## Signature

```ts
export function frameClock(): FrameClock;
```

## Parameters

| Param | Type | Required | Default | Notes                                                                             |
| ----- | ---- | -------- | ------- | --------------------------------------------------------------------------------- |
| —     | —    | —        | —       | `frameClock` does not take arguments; it captures `performance.now()` internally. |

**Returns:** `FrameClock` — exposes `now()`, `delta()`, `reset()`, `pause()`, `resume()`, and an `isPaused` getter. All time values are expressed in seconds.

## Examples

```ts
import { frameClock } from "@vgpu/render/utils";

const clock = frameClock();

function updateScene(elapsed: number, dt: number): void {
  void elapsed;
  void dt;
}

function tick() {
  if (!clock.isPaused) {
    const elapsed = clock.now();
    const dt = clock.delta();
    updateScene(elapsed, dt);
  }
  requestAnimationFrame(tick);
}

tick();
```

## Notes

* `delta()` returns `0` while paused, so you can leave animation code untouched and simply toggle `pause()` / `resume()`.
* `reset()` zeroes both elapsed time and accumulated pause, making it ideal for restarting demos without allocating a new clock.
* Calls to `pause()` are idempotent; repeated calls do nothing until `resume()` runs.
* **See also:** `canvasMouseTracker`, `canvasResolution`


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: InspectMaterial
description: Shape returned by inspect materials such as `wireframeMaterial` and `normalDebugMaterial`. It bundles the configured pipeline, group-0 layout, uniform size, and a helper to encode shared matrices into a uniform buffer.
---

# InspectMaterial



## Import

```ts
import type { InspectMaterial } from "@vgpu/render/inspect";
```

## Signature

```ts
import type { InspectMaterialUniformParams } from "@vgpu/render/inspect";

export interface InspectMaterial {
  readonly pipeline: GPURenderPipeline;
  readonly bindGroupLayout: GPUBindGroupLayout;
  readonly uniformByteSize: number;
  readonly writeUniforms: (
    buffer: GPUBuffer,
    offset: number,
    params: InspectMaterialUniformParams,
  ) => void;
}
```

## Fields

| Field           | Type                                                                                | Required | Default | Notes                                                                                                                                                                                                     |
| --------------- | ----------------------------------------------------------------------------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| pipeline        | `GPURenderPipeline`                                                                 | ✔        | —       | Ready-to-use pipeline configured for the corresponding inspector material.                                                                                                                                |
| bindGroupLayout | `GPUBindGroupLayout`                                                                | ✔        | —       | Group 0 layout with binding 0 as a uniform buffer. Allocate a buffer with at least `uniformByteSize` bytes and bind it with this layout.                                                                  |
| uniformByteSize | `number`                                                                            | ✔        | —       | Exact byte size that `writeUniforms` writes. `normalDebugMaterial()` returns `128`; `wireframeMaterial()` returns `144` because it appends RGB color data.                                                |
| writeUniforms   | `(buffer: GPUBuffer, offset: number, params: InspectMaterialUniformParams) => void` | ✔        | —       | Packs `viewProjectionMatrix` at float offset 0 and `modelMatrix` at float offset 16, then writes bytes with `device.gpu.queue.writeBuffer(...)`. Wireframe materials also write color at float offset 32. |

**Returns:** Not applicable for the interface itself. Inspector factory functions return frozen `InspectMaterial` objects whose fields can be reused across frames.

**Throws:** None from reading the fields. `writeUniforms(...)` itself performs no custom validation; native WebGPU validation can occur if `buffer` is destroyed, too small for `offset + uniformByteSize`, or missing `GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST` compatibility for the caller's bind group/update path.

## Examples

```ts
import { createMockAdapter } from "@vgpu/adapter-mock";
import { normalDebugMaterial } from "@vgpu/render/inspect";

const device = await createMockAdapter().requestDevice();
const material = normalDebugMaterial({ device, targetFormat: "rgba8unorm-srgb" });
const uniformBuffer = device.createBuffer({
  label: "inspect.normal.uniforms",
  size: material.uniformByteSize,
  usage: ["uniform", "copy_dst"],
});

const identity = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
material.writeUniforms(uniformBuffer.gpu, 0, {
  viewProjectionMatrix: identity,
  modelMatrix: identity,
});

uniformBuffer.destroy();
device.destroy();
```

```ts
import { createMockAdapter } from "@vgpu/adapter-mock";
import { wireframeMaterial } from "@vgpu/render/inspect";

const device = await createMockAdapter().requestDevice();
const material = wireframeMaterial({
  device,
  color: [0.25, 0.5, 1],
  targetFormat: "rgba8unorm-srgb",
});

const uniformBuffer = device.createBuffer({ size: material.uniformByteSize, usage: ["uniform", "copy_dst"] });
const identity = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
material.writeUniforms(uniformBuffer.gpu, 0, { viewProjectionMatrix: identity, modelMatrix: identity });

uniformBuffer.destroy();
device.destroy();
```

## Notes

* `writeUniforms` writes the shared camera view-projection and per-mesh model matrices, so every inspect material can share the same uniform allocation logic.
* Reuse one uniform buffer per material instance; pass offsets when interleaving data for multiple meshes.
* `InspectMaterial` is a shared return contract; material-specific defaults live on the factory docs (`wireframeMaterial`, `normalDebugMaterial`).
* **See also:** `InspectMaterialUniformParams`, `wireframeMaterial`, `normalDebugMaterial`

***

# InspectMaterialUniformParams

Uniform inputs shared by all inspect materials. Additional inspector-specific uniforms should extend this interface explicitly.

## Import

```ts
import type { InspectMaterialUniformParams } from "@vgpu/render/inspect";
```

## Signature

```ts
type Mat4 = Float32Array;

export interface InspectMaterialUniformParams {
  readonly viewProjectionMatrix: Mat4;
  readonly modelMatrix: Mat4;
}
```

## Fields

| Field                | Type   | Required | Default | Notes                                                                                     |
| -------------------- | ------ | -------- | ------- | ----------------------------------------------------------------------------------------- |
| viewProjectionMatrix | `Mat4` | ✔        | —       | Combined camera matrix written to the inspector's uniform buffer slots 0–63 bytes.        |
| modelMatrix          | `Mat4` | ✔        | —       | Object transform written immediately after `viewProjectionMatrix`, in slots 64–127 bytes. |

**Returns:** Not applicable. This is a parameter object passed to `InspectMaterial.writeUniforms(...)`.

**Throws:** None by itself. The receiving `writeUniforms(...)` call can surface native WebGPU validation if the destination buffer is invalid.

## Examples

```ts
import type { InspectMaterialUniformParams } from "@vgpu/render/inspect";

const identity = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
const params: InspectMaterialUniformParams = {
  viewProjectionMatrix: identity,
  modelMatrix: identity,
};

params.modelMatrix satisfies Float32Array;
```

## Notes

* The interface is intentionally minimal so different inspectors can share the same math; extend it when a tool needs more uniforms.
* Matrices are expected to be column-major `Float32Array` values matching the mesh layout used elsewhere in vgpu.
* **See also:** `InspectMaterial`, `wireframeMaterial`, `normalDebugMaterial`


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: meshToReadable
description: Promotes a render `Mesh` into a CPU-readable shape by ensuring its vertex buffer has `GPUBufferUsage.COPY_SRC`. Use it before inspection tools (wireframe, byte comparisons) that need to read vertex data.
---

# meshToReadable



## Import

```ts
import { meshToReadable } from "@vgpu/render/inspect";
```

## Signature

```ts
export function meshToReadable(mesh: Mesh, device: Device): Promise<Mesh>;
```

## Parameters

| Param  | Type   | Required | Default | Notes                                                                                        |
| ------ | ------ | -------- | ------- | -------------------------------------------------------------------------------------------- |
| mesh   | Mesh   | ✔        | —       | Source mesh. Must come from `@vgpu/render` helpers or user code with a valid `vertexBuffer`. |
| device | Device | ✔        | —       | Device that owns the target vertex buffer and command encoder used for the copy.             |

**Returns:** `Promise<Mesh>` — resolves to the original mesh when it already has `copy_src` usage or to a frozen clone that shares all metadata but replaces `vertexBuffer` with a readable copy.

**Throws:** `VGPU-CORE-INVALID-USAGE` when the source vertex buffer exposes an invalid `GPUBuffer.usage` mask (non-finite); fix by creating the geometry through `geometry(gpu, ...)` or adding `copy_src` when constructing buffers manually.

## Examples

```ts
import { createMockAdapter } from "@vgpu/adapter-mock";
import { meshToReadable } from "@vgpu/render/inspect";
import { init, geometry } from "vgpu/mock";
import { box } from "vgpu/scene";

async function main(): Promise<void> {
  const adapter = createMockAdapter();
  const gpu = await init({ adapter });
  const geo = geometry(gpu, box({ size: 1 }));

  const readable = await meshToReadable(geo as never, gpu.device);
  const vertices = await readable.vertexBuffer.read(readable.vertexBuffer.options.size);
  console.log("Readable bytes", new Float32Array(vertices));
}

main().catch((error) => {
  console.error(error);
});
```

## Notes

* When the input already includes `copy_src`, the function returns the exact same object; equality checks remain stable.
* Newly created readable buffers add `copy_src` (and `copy_dst` if it was missing) without removing the original usage flags.
* Index buffers and mesh metadata (`vertexCount`, `attributes`, etc.) are preserved by reference; only the vertex buffer identity changes.
* Await `queue.onSubmittedWorkDone()` in environments that expose it to guarantee the copy finished before reading.
* **See also:** `meshToWireframe`, `wireframeMaterial`


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: meshToWireframe
description: Builds a deduplicated line-list index buffer out of a readable triangle-list mesh. Use it alongside `wireframeMaterial` to visualize topology edges during debugging sessions.
---

# meshToWireframe



## Import

```ts
import { meshToWireframe } from "@vgpu/render/inspect";
```

## Signature

```ts
export function meshToWireframe(mesh: Mesh, device: Device): Promise<WireframeMesh>;
```

## Parameters

| Param  | Type   | Required | Default | Notes                                                                                                                  |
| ------ | ------ | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------- |
| mesh   | Mesh   | ✔        | —       | Must have a vertex buffer created with `GPUBufferUsage.COPY_SRC`; otherwise the function cannot read vertex positions. |
| device | Device | ✔        | —       | Supplies the command encoder, index buffer, and queue submit used to bake the wireframe lines.                         |

**Returns:** `Promise<WireframeMesh>` — frozen mesh-like object that reuses the source `vertexBuffer`, exposes a raw `indexBuffer`, reports whether the index data is `uint16` or `uint32`, and includes the deduplicated `lineCount`.

**Throws:** `VGPU-CORE-INVALID-USAGE` when the source mesh lacks a readable vertex buffer; fix by creating the geometry via `geometry(gpu, ...)` or promoting it through `meshToReadable` first.

## Examples

```ts
import { createMockAdapter } from "@vgpu/adapter-mock";
import { meshToReadable, meshToWireframe, wireframeMaterial } from "@vgpu/render/inspect";
import { init, geometry } from "vgpu/mock";
import { box } from "vgpu/scene";

async function main(): Promise<void> {
  const adapter = createMockAdapter();
  const gpu = await init({ adapter });
  const solid = geometry(gpu, box({ size: 1 }));
  const readable = await meshToReadable(solid as never, gpu.device);
  const wireframe = await meshToWireframe(readable, gpu.device);
  const inspector = wireframeMaterial({ device: gpu.device });

  console.log(wireframe.lineCount); // 12 for a cube
  inspector.pipeline; // ready-to-use GPURenderPipeline
}

main().catch((error) => {
  console.error(error);
});
```

## Notes

* The helper quantizes edge endpoints to a `1e-6` grid before it deduplicates them; bake tiny debug meshes at a larger scale if you need finer detail.
* Triangle pairs that share a coplanar face have their diagonal removed by comparing face normals, so smooth surfaces only emit silhouette edges.
* The returned `indexBuffer` is a raw `GPUBuffer`. Destroy it manually when the wireframe is no longer needed or rely on `device.destroy()` during teardown.
* **See also:** `meshToReadable`, `wireframeMaterial`, `InspectMaterial`


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: normalDebugMaterial
description: Creates an `InspectMaterial` that visualizes per-fragment normals as RGB. Use it to confirm vertex normals before passing geometry into lighting passes.
---

# normalDebugMaterial



## Import

```ts
import { normalDebugMaterial } from "@vgpu/render/inspect";
```

## Signature

```ts
export function normalDebugMaterial(spec: NormalDebugMaterialSpec): InspectMaterial;
```

## Parameters

| Param             | Type                    | Required | Default           | Notes                                                                        |
| ----------------- | ----------------------- | -------- | ----------------- | ---------------------------------------------------------------------------- |
| spec              | NormalDebugMaterialSpec | ✔        | —                 | Configuration object used to allocate the material.                          |
| spec.device       | Device                  | ✔        | —                 | Device that owns the pipeline, bind group layout, and uniform buffer writes. |
| spec.targetFormat | GPUTextureFormat        | ✖        | "bgra8unorm-srgb" | Color attachment format; use "rgba8unorm-srgb" if BGRA is unavailable.       |

**Returns:** `InspectMaterial` — exposes the configured `pipeline`, `bindGroupLayout`, 128-byte uniform size, and a writer that uploads view-projection and model matrices.

## Examples

```ts
import { createMockAdapter } from "@vgpu/adapter-mock";
import { InspectMaterial, normalDebugMaterial } from "@vgpu/render/inspect";

const IDENTITY_MATRIX = new Float32Array([
  1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 1,
]);

async function main(): Promise<void> {
  const device = await createMockAdapter().requestDevice();
  const material: InspectMaterial = normalDebugMaterial({ device, targetFormat: "rgba8unorm-srgb" });
  const uniforms = device.createBuffer({ size: material.uniformByteSize, usage: ["uniform", "copy_dst"] });

  material.writeUniforms(uniforms.gpu, 0, {
    viewProjectionMatrix: IDENTITY_MATRIX,
    modelMatrix: IDENTITY_MATRIX,
  });
}

main().catch((error) => {
  console.error(error);
});
```

## Notes

* Renders with `triangle-list` topology, depth testing, and back-face culling so front-facing normals remain visible.
* Outputs `(normal + 1) / 2` in linear space; rotating the model matrix rotates the visualized colors.
* There is no normal-matrix correction: this inspector intentionally shows object-space normals to match authoring errors.
* **See also:** `wireframeMaterial`, `InspectMaterial`


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: @vgpu/render/perf
description: WebGPU verification helpers for the optimize loop. These utilities live under `@vgpu/render/perf`; they are not meant for runtime use.
---

# @vgpu/render/perf



***

# gpuFrameTime

Measures GPU frame time statistics for a render routine. The harness handles warmup, command encoding, submission, and timing (timestamp queries when available, wall clock otherwise).

## Import

```ts
import { gpuFrameTime } from "@vgpu/render/perf";
```

## Signature

```ts
export function gpuFrameTime(
  device: Device,
  encode: GpuFrameEncoder,
  options?: GpuFrameTimeOptions,
): Promise<GpuFrameTimeResult>;
```

## Parameters

| Param                  | Type                | Required | Default             | Notes                                                                                                                                      |
| ---------------------- | ------------------- | -------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| device                 | Device              | ✔        | —                   | Source device used to create command encoders, submit work, and flush the queue. Must expose `timestamp-query` if you want GPU timestamps. |
| encode                 | GpuFrameEncoder     | ✔        | —                   | Callback invoked per frame with a fresh `GPUCommandEncoder`; record passes exactly as in production.                                       |
| options                | GpuFrameTimeOptions | ✖        | `{}`                | Tunables for warmup, sample count, and measurement mode.                                                                                   |
| options.frames         | number              | ✖        | 120                 | Measured frames after warmup. Values below 1 are clamped to 1.                                                                             |
| options.warmup         | number              | ✖        | 30                  | Throws away the first N frames so shader compilation and lazy allocations settle.                                                          |
| options.batch          | number              | ✖        | 8                   | Frames per batch when falling back to wall-clock. Ignored for timestamp queries.                                                           |
| options.forceWallClock | boolean             | ✖        | false               | Forces the wall-clock path even if `timestamp-query` is available. Useful when you intentionally want queue-submit timings.                |
| options.label          | string              | ✖        | "vgpu-gpuFrameTime" | Assigns encoder labels and buffer names to make debugging captures easier.                                                                 |

**Returns:** `Promise<GpuFrameTimeResult>` — resolves with median, mean, min, p95, sample count, and the measurement `method` (`"timestamp-query"` or `"wall-clock"`).

**Throws:** Propagates any error from the encoder callback, queue submission, or timestamp buffer mapping. Timestamp-specific errors automatically fall back to wall-clock before surfacing.

## Examples

```ts
import { gpuFrameTime } from "@vgpu/render/perf";
import { createMockAdapter } from "@vgpu/adapter-mock";

async function bench(): Promise<void> {
  const adapter = createMockAdapter();
  const device = await adapter.requestDevice();
  const renderPassDescriptor: GPURenderPassDescriptor = { colorAttachments: [{ view: {} as GPUTextureView, loadOp: "clear", storeOp: "store" }] };
  const pipeline = device.gpu.createRenderPipeline({
    layout: "auto",
    vertex: { module: device.gpu.createShaderModule({ code: "@vertex fn vs_main() -> @builtin(position) vec4f { return vec4f(); }" }), entryPoint: "vs_main" },
    fragment: { module: device.gpu.createShaderModule({ code: "@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1.0); }" }), entryPoint: "fs_main", targets: [{ format: "bgra8unorm" }] },
    primitive: { topology: "triangle-list" },
  });

  const result = await gpuFrameTime(device, (encoder) => {
    const pass = encoder.beginRenderPass(renderPassDescriptor);
    pass.setPipeline(pipeline);
    pass.draw(3);
    pass.end();
  }, { frames: 60, warmup: 10 });

  console.log(result.method, result.medianMs);
}

bench().catch((error) => {
  console.error(error);
});
```

## Notes

* Timestamp queries run only when the device exposes the `timestamp-query` feature; otherwise wall-clock timings use `device.queue.flush()` to amortize submit latency via batching.
* Warmup still submits commands; budget time for shader compilation before measuring.
* Always compare two runs with identical options; `medianMs` is the headline figure for relative regressions.
* **See also:** `pixelDiff`

***

# GpuFrameTimeOptions

Optional configuration passed to `gpuFrameTime`.

## Fields

| Field          | Type    | Required | Default             | Notes                                                           |
| -------------- | ------- | -------- | ------------------- | --------------------------------------------------------------- |
| frames         | number  | ✖        | 120                 | Number of measured frames (post-warmup). Clamped to at least 1. |
| warmup         | number  | ✖        | 30                  | Frames to submit and discard before measuring.                  |
| batch          | number  | ✖        | 8                   | Wall-clock batch size; ignored for timestamp mode.              |
| forceWallClock | boolean | ✖        | false               | Skip timestamp queries even when supported.                     |
| label          | string  | ✖        | "vgpu-gpuFrameTime" | Label used for encoders and buffers created internally.         |

***

# GpuFrameTimeResult

Return type for `gpuFrameTime`.

## Fields

| Field    | Type                              | Required | Default | Notes                                                                 |
| -------- | --------------------------------- | -------- | ------- | --------------------------------------------------------------------- |
| medianMs | number                            | ✔        | —       | 50th percentile frame time, the main number to compare across builds. |
| meanMs   | number                            | ✔        | —       | Arithmetic mean of collected samples.                                 |
| minMs    | number                            | ✔        | —       | Fastest observed frame.                                               |
| p95Ms    | number                            | ✔        | —       | 95th percentile; highlights long tails.                               |
| samples  | number                            | ✔        | —       | Count of valid samples captured.                                      |
| method   | "timestamp-query" \| "wall-clock" | ✔        | —       | Measurement backend used.                                             |

***

# pixelDiff

Compares two renders byte-for-byte. Accepts either `Texture` instances (will call `read()`) or already read `Uint8Array`s.

## Import

```ts
import { pixelDiff } from "@vgpu/render/perf";
```

## Signature

```ts
export function pixelDiff(
  a: Texture | Uint8Array,
  b: Texture | Uint8Array,
): Promise<PixelDiffResult>;
```

## Parameters

| Param | Type                  | Required | Default | Notes                                                            |
| ----- | --------------------- | -------- | ------- | ---------------------------------------------------------------- |
| a     | Texture \| Uint8Array | ✔        | —       | First render; when a `Texture`, it is read via `Texture.read()`. |
| b     | Texture \| Uint8Array | ✔        | —       | Second render to compare against `a`.                            |

**Returns:** `Promise<PixelDiffResult>` — contains `maxByte`, `meanByte`, `changedBytes`, `totalBytes`, and `changedFraction`.

**Throws:** Propagates any error while reading textures (e.g., unreadable usage flags) or when the inputs cannot be read.

## Examples

```ts
import { pixelDiff } from "@vgpu/render/perf";
import type { Texture } from "@vgpu/core";

async function assertVisualParity(before: Texture, after: Texture): Promise<void> {
  const result = await pixelDiff(before, after);
  if (result.maxByte > 2) {
    throw new Error(`Visual regression detected (max delta ${result.maxByte})`);
  }
}
```

## Notes

* A length mismatch forces `maxByte` to `255`; inspect `totalBytes` before trusting small `maxByte` values.
* Treat `maxByte <= 2` as driver rounding noise on most devices; higher values indicate true visual changes.
* When comparing multiple frames, feed already-read `Uint8Array`s to avoid repeated GPU readbacks.
* **See also:** `gpuFrameTime`

***

# PixelDiffResult

Shape returned by `pixelDiff`.

## Fields

| Field           | Type   | Required | Default | Notes                                                                                                           |
| --------------- | ------ | -------- | ------- | --------------------------------------------------------------------------------------------------------------- |
| maxByte         | number | ✔        | —       | Largest absolute per-byte difference (0–255). Use this as the headline regression metric.                       |
| meanByte        | number | ✔        | —       | Mean absolute per-byte difference across compared buffers.                                                      |
| changedBytes    | number | ✔        | —       | Count of bytes whose value differs at all.                                                                      |
| totalBytes      | number | ✔        | —       | Number of bytes compared (min of both buffer lengths).                                                          |
| changedFraction | number | ✔        | —       | `changedBytes / totalBytes`; near-zero fractions with low `maxByte` typically indicate harmless rounding noise. |


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: wireframeMaterial
description: Creates an `InspectMaterial` configured to render line segments from a readable mesh. Use it with `meshToWireframe` outputs to visualize topology edges while keeping your primary material untouched.
---

# wireframeMaterial



## Import

```ts
import { wireframeMaterial } from "@vgpu/render/inspect";
```

## Signature

```ts
export function wireframeMaterial(spec: WireframeMaterialSpec): InspectMaterial;
```

## Parameters

| Param             | Type                               | Required | Default           | Notes                                                                                                             |
| ----------------- | ---------------------------------- | -------- | ----------------- | ----------------------------------------------------------------------------------------------------------------- |
| spec              | WireframeMaterialSpec              | ✔        | —                 | Configuration object used to allocate the pipeline.                                                               |
| spec.device       | Device                             | ✔        | —                 | Device that owns the pipeline, bind group layout, and uniform buffer writes.                                      |
| spec.color        | readonly \[number, number, number] | ✖        | \[1, 1, 1]        | Linear RGB line color; each component must be between 0 and 1.                                                    |
| spec.targetFormat | GPUTextureFormat                   | ✖        | "bgra8unorm-srgb" | Color attachment format for the fragment target. Use "rgba8unorm-srgb" on implementations that lack BGRA support. |

**Returns:** `InspectMaterial` — exposes the configured `pipeline`, `bindGroupLayout`, uniform byte size (144 bytes), and a writer that packs view-projection, model matrices, and the wire color.

## Examples

```ts
import { createMockAdapter } from "@vgpu/adapter-mock";
import { InspectMaterial, wireframeMaterial } from "@vgpu/render/inspect";

const IDENTITY_MATRIX = new Float32Array([
  1, 0, 0, 0,
  0, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 0, 1,
]);

async function main(): Promise<void> {
  const device = await createMockAdapter().requestDevice();
  const material: InspectMaterial = wireframeMaterial({ device, color: [1, 0.75, 0.5] });
  const uniforms = device.createBuffer({ size: material.uniformByteSize, usage: ["uniform", "copy_dst"] });

  material.writeUniforms(uniforms.gpu, 0, {
    viewProjectionMatrix: IDENTITY_MATRIX,
    modelMatrix: IDENTITY_MATRIX,
  });
}

main().catch((error) => {
  console.error(error);
});
```

## Notes

* Uses `line-list` topology with depth testing enabled and no culling to guarantee all edges stay visible.
* The vertex buffer layout expects interleaved position/normal attributes that match the `meshToWireframe` output stride (24 bytes).
* Uniform writes allocate a temporary `Float32Array`; reuse the same uniform buffer between frames to avoid churn.
* **See also:** `meshToWireframe`, `InspectMaterial`, `normalDebugMaterial`


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: createNodeAdapter
description: `createNodeAdapter()` returns a Dawn-backed `VGPUAdapter` using the `webgpu@0.4.0` API. The native loader resolves Dawn in this order:
---

# createNodeAdapter



1. the file named by `VGPU_DAWN_BINARY`;
2. a verified vgpu prebuild in the versioned user cache;
3. the stock `webgpu` package;
4. on Linux, a lazy download of the vgpu prebuild if stock Dawn cannot load.

A best-effort postinstall download normally fills the cache. It never fails npm
or pnpm installation, and the runtime retry covers `--ignore-scripts` and pnpm
configurations that block lifecycle scripts. Downloads come from the pinned
`vercel-labs/vgpu` GitHub Release and are accepted only when their SHA-256 equals
the hash pinned in `@vgpu/adapter-node`. Private-repository and draft-release
access honors `GH_TOKEN` or `GITHUB_TOKEN`; published public assets are fetched
without a token. Override the cache root with `VGPU_CACHE_DIR` (or
`XDG_CACHE_HOME`). Cache entries must be regular, non-symlink files. Before
native loading, the verified bytes are copied through one open file descriptor
into a private per-process directory and that exact private copy is loaded,
preventing cache replacement between verification and `require()`.

The portable prebuild currently supports Linux arm64 with glibc 2.31 or newer.
Linux musl, other Linux CPUs, and other operating systems continue to try stock
`webgpu`; errors identify an unsupported platform, musl, an offline/blocked
download, or the exact required and detected glibc versions. Manual and CI
installation is available with:

```bash
pnpm exec vgpu install-dawn
# or
npx vgpu install-dawn
```

`VGPU-NODE-PREBUILD-MISSING` includes the failed reason and those remediation
commands. `VGPU-NODE-PREBUILD-CHECKSUM` refuses a corrupt or substituted asset.
`VGPU-NODE-GLIBC-MISMATCH` names both versions when a selected native binary
cannot load. Do not upgrade a host's glibc in place; install the portable
prebuild or provide an audited binary with `VGPU_DAWN_BINARY`.

On Linux the adapter explicitly selects Vulkan by default, even when `DISPLAY`
or `WAYLAND_DISPLAY` is configured. No display server is required. The existing
compatibility feature level is unchanged. macOS/Windows backend selection and
browser WebGPU are unaffected. It keeps a process-wide singleton GPU instance;
conflicting later flags are warned and ignored because Dawn re-init can SIGSEGV.

Install a Vulkan driver for the hardware GPU, or use Mesa/lavapipe for CPU rendering.
For deterministic CI, select the software driver's ICD with `VK_ICD_FILENAMES`.
If discovery fails in auto mode, an already installed portable software renderer
can be used; otherwise `VGPU-NODE-NO-ADAPTER` explains how to install it with
`npx vgpu install-software-renderer`. There is no silent OpenGL fallback and no
automatic driver download. Hardware-only mode still rejects CPU adapters.

Explicit `backend: "opengl"`, `backendFlags`, and `VGPU_DAWN_FLAGS` overrides are
preserved. For example, `VGPU_DAWN_FLAGS=backend=opengl` opts into OpenGL, including
its known Dawn limitation: sampling a restricted mip view can corrupt later storage
writes to another mip of the same texture (upstream issue 392121637).
`VGPU_DAWN_FLAGS` accepts space-separated Dawn flags and replaces default selection.
Existing `backend: "webgpu"` keeps native discovery with the full WebGPU feature level.

A CPU Vulkan device is not necessarily a WebGPU fallback adapter. In current
Dawn builds lavapipe is acquired by the normal request; forcing
`forceFallbackAdapter` can exclude it. If no adapter is found after the retry
window, `VGPU-NODE-NO-ADAPTER` reports the request options and Dawn flags and
points to the Mesa version, Vulkan ICD, and display environment to inspect.

For agentic headless snapshot tests, pair this adapter with an explicit
offscreen `rgba8unorm` render target that includes `"copy_src"`, submit the
render commands, `await device.queue.flush()`, then read pixels through
`Texture.read()`. Keep PNG encoding and pixel comparison in project test tooling
(such as `pngjs`, `pixelmatch`, or existing snapshots), not in the VGPU API. See
`createNodeDevice` for a full native-before/VGPU-after guide.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: createNodeDevice
description: `createNodeDevice(opts?)` is a mechanical convenience that requests a `Device` from the Node adapter directly. Use `createNodeDevice()` for focused scripts, server-side renders, and agentic headless snapshot tests that need one explicit WebGPU device. Application code can also use `init()` from `vgpu/node` for the main API (`vgpu`) facade.
---

# createNodeDevice



## Agentic headless snapshot workflow

A snapshot agent should render a deterministic, named scene into an offscreen
texture, wait for GPU work to finish, read the texture bytes, and hand those
bytes to project-owned PNG or pixel-diff tooling. VGPU does not provide an
image-diff framework and does not drive browser screenshots; it keeps the
WebGPU render target and readback steps small and explicit.

Name the inputs that control the frame (camera, time, seed, viewport, material
fixtures) and keep them stable between runs. Name the render target as well so
native WebGPU validation output points back to the snapshot under test.

### Native WebGPU readback boilerplate

In raw WebGPU, reading an offscreen render target is a separate copy-to-buffer
operation. You must create the target with `COPY_SRC`, align rows to 256 bytes,
copy the texture into a mappable buffer, submit the copy, wait for submitted work,
map the buffer, then strip row padding before comparing pixels:

```text
const width = 256;
const height = 256;
const bytesPerPixel = 4;
const unpaddedBytesPerRow = width * bytesPerPixel;
const bytesPerRow = Math.ceil(unpaddedBytesPerRow / 256) * 256;

const target = gpuDevice.createTexture({
  label: "snapshot.hero.native.target",
  size: { width, height },
  format: "rgba8unorm",
  usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
});

// Render the deterministic frame into `target` here.

const readback = gpuDevice.createBuffer({
  label: "snapshot.hero.native.readback",
  size: bytesPerRow * height,
  usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
});

const encoder = gpuDevice.createCommandEncoder({ label: "snapshot.hero.native.copy" });
encoder.copyTextureToBuffer(
  { texture: target },
  { buffer: readback, bytesPerRow, rowsPerImage: height },
  { width, height, depthOrArrayLayers: 1 },
);
gpuDevice.queue.submit([encoder.finish()]);
await gpuDevice.queue.onSubmittedWorkDone();

await readback.mapAsync(GPUMapMode.READ);
const mapped = new Uint8Array(readback.getMappedRange());
const rgba = new Uint8Array(unpaddedBytesPerRow * height);
for (let y = 0; y < height; y += 1) {
  rgba.set(
    mapped.subarray(y * bytesPerRow, y * bytesPerRow + unpaddedBytesPerRow),
    y * unpaddedBytesPerRow,
  );
}
readback.unmap();
```

`Texture.read()` wraps that readback path for VGPU textures, including the
padding removal, while preserving normal WebGPU rendering and command submission.

### With VGPU in Node

Use the Node adapter, create an explicit offscreen render target, submit your
render commands, flush the queue, then read RGBA bytes. The example uses raw
WebGPU pipeline creation through `.gpu` because VGPU intentionally keeps that
escape hatch available for native interop; wrapper lifecycle methods should still
own teardown.

```text
import { createNodeDevice } from "@vgpu/adapter-node";

const width = 256;
const height = 256;
const format: GPUTextureFormat = "rgba8unorm";

const scene = {
  name: "hero-triangle",
  seed: 7,
  timeSeconds: 0,
  camera: "orthographic-front",
};

const device = await createNodeDevice({ label: `snapshot.${scene.name}.device` });

try {
  const target = device.createTexture({
    kind: "2d",
    label: `snapshot.${scene.name}.target`,
    size: [width, height],
    format,
    usage: ["render_attachment", "copy_src"],
  });

  const shader = device.gpu.createShaderModule({
    label: `snapshot.${scene.name}.shader`,
    code: /* wgsl */ `
      @vertex
      fn vs(@builtin(vertex_index) vertexIndex: u32) -> @builtin(position) vec4f {
        let positions = array<vec2f, 3>(
          vec2f(-0.75, -0.75),
          vec2f( 0.75, -0.75),
          vec2f( 0.00,  0.75),
        );
        return vec4f(positions[vertexIndex], 0.0, 1.0);
      }

      @fragment
      fn fs(@builtin(position) position: vec4f) -> @location(0) vec4f {
        let uv = position.xy / vec2f(${width}.0, ${height}.0);
        return vec4f(uv.x, uv.y, 0.25, 1.0);
      }
    `,
  });

  const pipeline = device.gpu.createRenderPipeline({
    label: `snapshot.${scene.name}.pipeline`,
    layout: "auto",
    vertex: { module: shader, entryPoint: "vs" },
    fragment: { module: shader, entryPoint: "fs", targets: [{ format }] },
    primitive: { topology: "triangle-list" },
  });

  const encoder = device.gpu.createCommandEncoder({ label: `snapshot.${scene.name}.frame` });
  const pass = encoder.beginRenderPass({
    label: `snapshot.${scene.name}.pass`,
    colorAttachments: [{
      view: target.createView(),
      clearValue: { r: 0, g: 0, b: 0, a: 1 },
      loadOp: "clear",
      storeOp: "store",
    }],
  });
  pass.setPipeline(pipeline);
  pass.draw(3);
  pass.end();

  device.queue.gpu.submit([encoder.finish()]);
  await device.queue.flush();

  const rgba = await target.color.read({ mipLevel: 0, region: "all" });
  // Pass `rgba` to project-owned PNG or pixel-diff tooling.

  target.destroy();
} finally {
  device.destroy();
}
```

### Test harness sketch

Keep PNG encoding and image comparison outside the VGPU API. A Vitest/Jest-style
harness can use packages such as `pngjs` and `pixelmatch`, or your repository's
existing snapshot writer:

```text
import { readFileSync, writeFileSync } from "node:fs";
import pixelmatch from "pixelmatch";
import { PNG } from "pngjs";

const actualPng = new PNG({ width, height });
actualPng.data.set(rgba);

if (process.env.VGPU_WRITE_SNAPSHOTS === "1") {
  writeFileSync("snapshots/hero-triangle.png", PNG.sync.write(actualPng));
} else {
  const expected = PNG.sync.read(readFileSync("snapshots/hero-triangle.png"));
  const diff = new PNG({ width, height });
  const mismatched = pixelmatch(
    expected.data,
    actualPng.data,
    diff.data,
    width,
    height,
    { threshold: 0.02 },
  );
  if (mismatched > 0) {
    writeFileSync("snapshots/hero-triangle.diff.png", PNG.sync.write(diff));
    throw new Error(`Snapshot mismatch: ${mismatched} pixels differ`);
  }
}
```

## CI, Docker, and GLIBC notes

On Linux, the stock Dawn binary shipped by `webgpu@0.4.0` targets recent glibc
(2.38 on arm64). vgpu no longer treats that as a hard requirement: when the
stock binary fails to load, the adapter falls back to vgpu's portable Dawn
prebuild — built against GLIBC 2.31, downloaded from GitHub Releases, verified
against a pinned SHA-256, and cached per version. The fallback also runs at
`postinstall` (best-effort, never fails your install) and can be invoked
manually with `npx vgpu install-dawn`. `VGPU_DAWN_BINARY` overrides resolution
entirely for air-gapped hosts. Load failures surface as structured
`VGPU-NODE-*` errors that name the platform, the reason, and the fix.

Docker remains the recommended path when you want a fully pinned rendering
environment — identical Mesa/driver stack for bit-exact snapshots — rather
than as a GLIBC workaround:

```bash
pnpm test:docker
```

The Docker image uses Node 22 on Debian trixie with Vulkan and Mesa/lavapipe for
CPU rendering. Linux users also default to Vulkan, independently of display variables.
The image pins `VK_ICD_FILENAMES` and `VK_DRIVER_FILES` to the installed lavapipe ICD
and sets `XDG_RUNTIME_DIR=/tmp/xdg-runtime`; no Xvfb is needed. To update project snapshots in that
environment, use a project convention such as:

```bash
VGPU_WRITE_SNAPSHOTS=1 pnpm test:docker
```

## Shutting down cleanly

Dawn keeps polling for device events while the device is alive, which keeps
the Node process running after your last render. Dispose the context when you
are done:

```text
try {
  // render, read pixels, write files
  await gpu.settled();
} finally {
  gpu.dispose();
}
```

`gpu.dispose()` destroys the device and stops event polling, letting the
process exit on its own — no `process.exit()` needed.

## Headless rendering without a GPU

vgpu can render on CPU anywhere. Check the machine first:

```bash
npx vgpu doctor
```

If no usable Vulkan driver exists, the fix is one command:

```bash
npx vgpu install-software-renderer
```

This downloads vgpu's portable lavapipe build (Mesa 25, \~20 MB, sha256-verified,
cached next to the Dawn binary) — no root, no system packages. Once cached,
`init()` uses it automatically whenever no other adapter exists. The system
needs a handful of tiny libraries (Vulkan loader, libdrm, zlib, zstd, and
libudev) — doctor checks and prescribes them in one command.

### Reading the startup noise on a machine without a GPU

Dawn, the Vulkan loader and Mesa write their own startup diagnostics straight to
stderr from native code before any JavaScript runs, and they look alarming even
when nothing is wrong:

```text
error: XDG_RUNTIME_DIR is invalid or not set in the environment.
error: XDG_RUNTIME_DIR is invalid or not set in the environment.
Warning: Vulkan shaderUniform*ArrayDynamicIndexing required.
```

Those lines come from the driver stack, not from vgpu; the prebuilt Dawn binding
exposes no logging hook, so vgpu cannot capture or relabel them. Instead, when a
run ends up on the CPU renderer, vgpu prints one labelled notice on stderr —
once per process, after the adapter is known, so it lands *below* the native
lines it explains:

```text
vgpu: notice — no hardware GPU adapter is available; using CPU software renderer (llvmpipe (LLVM 19.1.7, 128 bits)). This is expected on a machine without a usable GPU, and rendering continues normally.
vgpu: notice — Vulkan/XDG_RUNTIME_DIR "error" and "Warning" lines printed above come from the GPU driver stack, not from vgpu, and are harmless. Run `npx vgpu doctor` for details.
```

Explicit `init({ adapter: "software" })` stays silent: choosing the CPU renderer
on purpose needs no explanation.

Prefer your distribution's driver when it is recent (Mesa >= 23 with
`mesa-vulkan-drivers`); the portable build exists for hosts where that is not
an option.

## Choosing an adapter

```ts
import { init } from "vgpu/node";

{ const gpu = await init(); }                        // auto: hardware first, cached software renderer as last resort
{ const gpu = await init({ adapter: "hardware" }); } // require a real GPU — fails loud, never falls back
{ const gpu = await init({ adapter: "software" }); } // force the portable renderer — deterministic pixels on any machine
```

`gpu.adapter` reports what was selected: `{ name, type: "gpu" | "cpu" }`.
The `VGPU_ADAPTER` environment variable overrides the code-level choice and
announces itself on stderr — handy for forcing a mode in CI without editing
code.

## `.gpu` lifecycle guidance

`.gpu` is a raw WebGPU escape hatch. Use it for operations VGPU does not wrap,
such as custom pipelines, render passes, query sets, or native interop. Prefer
VGPU wrapper lifecycle methods for resources VGPU owns: call `texture.destroy()`,
`buffer.destroy()`, and `device.destroy()` rather than `texture.gpu.destroy()` or
`buffer.gpu.destroy()`. Direct raw destruction is reserved for deliberate
escape-hatch/native interop cases where you also own the consequences.

## Troubleshooting snapshot tests

* **Unsupported format**: `Texture.read()` supports the formats documented by
  `Texture` readback, including `rgba8unorm`, `rgba8unorm-srgb`, and the float
  formats `rgba16float` / `rgba32float` (plus their `r`/`rg` variants). Prefer
  `rgba8unorm` for deterministic PNG snapshots; for HDR targets read components
  with `Texture.readFloats()` (a `Float32Array`) instead of decoding the raw
  half/float bytes yourself. Formats outside that table (depth/stencil, packed,
  snorm/uint/sint, compressed) throw `VGPU-CORE-UNSUPPORTED-FORMAT`.
* **Missing `copy_src` usage**: the render target must include `"copy_src"` in
  addition to `"render_attachment"`; otherwise readback copy validation fails.
* **Unflushed queue**: submit the render commands and `await device.queue.flush()`
  before `await target.color.read({ mipLevel: 0, region: "all" })` so the readback observes the completed frame.
* **Non-deterministic inputs**: freeze clock, random seeds, camera, viewport,
  device options, and fixture data. Include those names in labels and snapshot
  filenames.
* **Native environment failures**: Vulkan driver or Mesa setup problems are
  host/container issues — re-run in `pnpm test:docker`. Dawn load errors are
  handled by the adapter's portable-prebuild fallback; if one still surfaces,
  the structured `VGPU-NODE-*` error names the fix (typically
  `npx vgpu install-dawn` or `VGPU_DAWN_BINARY`).

## Related work

This workflow builds on the core readback and Node adapter/Docker work tracked in
\#81 and #82, and it relates to the explicit frame-helper work referenced by #83
when a test wants a higher-level frame abstraction instead of raw command
encoders. It is documentation only and leaves future API changes to separate
issues.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Bundle
description: Main API (`vgpu`) render bundle recorded by `bundle(gpu, { target }, cb)`. Bundles freeze commands, attachment formats, sample count, and bind-group identities for static work; `FramePass.bundles()` checks signature and resource staleness (`VGPU-R3-BUNDLE-STALE`) when replaying. A bundle keeps its own snapshots of what it recorded, so the draws and effects you recorded can be dropped while the bundle keeps replaying; explicitly disposing one of them stales the bundle instead. Drop a bundle you no longer need and it is collected with the rest of your garbage, or call `dispose()` to release it at a known point.
---

# Bundle



## Import

```ts
import type { Bundle, BundleOptions, BundleRecorder } from "vgpu";
```

## Signature

```ts
import type { Draw, DrawCallOptions, Effect, Target, TargetSignature } from "vgpu";

interface BundleOptions {
  readonly target: Target | TargetSignature;
  readonly label?: string;
}

interface BundleRecorder {
  draw(drawable: Draw | Effect, opts?: DrawCallOptions): void;
}

interface Bundle {
  readonly id: string;
  readonly gpu: GPURenderBundle;
  dispose(): void;
}
```

## Parameters

| Param                     | Type                                 | Required | Default                                                          | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ------------------------- | ------------------------------------ | -------: | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| bundle.opts               | `BundleOptions`                      |        ✔ | —                                                                | Recording options.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| opts.target               | `Target \| TargetSignature`          |        ✔ | —                                                                | Formats, depth format, and sample count are recorded. Signature form is `{ colors: [...], depth?, sampleCount? }`; `colors` is required. A live `Surface` is accepted inside or outside a frame: recording reads its configured `format`, resolved depth format, and sample count without acquiring a canvas texture. Before the surface exists, `{ colors: [navigator.gpu.getPreferredCanvasFormat()] }` describes its defaults; include matching `depth` and `sampleCount` when planning depth or MSAA. |
| opts.label                | `string`                             |        ✖ | `` `bundle${n}` ``                                               | Bundle id and GPU label. Auto id increments from `bundle1`.                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| bundle.cb                 | `(recorder: BundleRecorder) => void` |        ✔ | —                                                                | Called immediately to encode commands.                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| recorder.draw\.drawable   | `Draw \| Effect`                     |        ✔ | —                                                                | Draw or fullscreen effect to encode into the bundle.                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| recorder.draw\.opts       | `DrawCallOptions`                    |        ✖ | `{}`                                                             | Counts and offsets captured in the recorded commands. `indirect` records fine — render bundle encoders support `drawIndirect`/`drawIndexedIndirect` — and the GPU re-reads the argument buffer on every replay.                                                                                                                                                                                                                                                                                           |
| bundle.id                 | `string`                             |        — | `opts.label` or `` `bundle${n}` ``                               | Read-only. Stays readable after `dispose()`.                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| bundle.gpu                | `GPURenderBundle`                    |        — | recorded at creation                                             | Read-only native render bundle. Throws `VGPU-BUNDLE-DISPOSED` after `dispose()`. A stale bundle that was not disposed — including one whose recorded draw was disposed — still returns it.                                                                                                                                                                                                                                                                                                                |
| bundle.dispose            | `() => void`                         |        ✖ | not called — the bundle is released when it is garbage-collected | Synchronous and idempotent. Releases the bundle's registrations, captured resource, target, and geometry snapshots, and native handle reference now. Never destroys or disposes the draws, effects, geometry, textures, buffers, or targets it recorded.                                                                                                                                                                                                                                                  |
| framePass.bundles.bundles | `readonly Bundle[]`                  |        ✔ | —                                                                | Replayed bundles; must be created by `bundle()` and not disposed.                                                                                                                                                                                                                                                                                                                                                                                                                                         |

**Returns:** `bundle(gpu)` returns `Bundle` with `id`, native `gpu` render bundle, and `dispose()`; `BundleRecorder.draw()` returns `void`; `Bundle.dispose()` returns `void`; `FramePass.bundles()` returns `void`.

**Throws:**

* `VGPU-R3-BUNDLE-STALE` from `FramePass.bundles()` when the replay target's formats, depth format, or sample count differ from the recorded signature — record a bundle for that signature. The message prints both recorded and actual signature keys. This check runs per replay and does not mark the bundle stale: replaying it later on a matching target works.
* `VGPU-R3-BUNDLE-STALE` from `FramePass.bundles()` when a recorded draw's bound resource identity or claimed group changed after the bundle finished recording — including a rebind made while a different bundle records — or a captured texture, buffer, or target was destroyed, or a sampled `Target` replaced its attachment (for example on `resize()`) — record a new bundle, swap it in, then `dispose()` the old one. Destruction and attachment replacement are detected even after the recorded draw or effect was collected. This staleness is permanent and the message always names the first change, even after later rebinds.
* `VGPU-R3-BUNDLE-STALE` from `FramePass.bundles()` when a recorded draw or effect was disposed with `dispose()`, including during this bundle's own recording callback. The message is `Bundle '<id>' is stale: draw '<label>' was disposed. Create a new draw/effect and re-record the bundle.` — create a new draw or effect, record a new bundle, swap it in, then `dispose()` the old bundle. This staleness is permanent and keeps the first cause; collecting a recorded draw or effect without `dispose()` never stales the bundle.
* The geometry's own liveness error, such as `VGPU-MESH-LAYOUT-INVALID` for a destroyed `geometry(gpu)`, from `FramePass.bundles()` when geometry the bundle recorded was destroyed — create live geometry, then record a new draw and bundle.
* `VGPU-BUNDLE-DISPOSED` from `bundle.gpu` or `FramePass.bundles()` after `dispose()` — record a new bundle before replaying; this bundle was disposed.
* `VGPU-R3-BUNDLE-INVALID` when replay receives an object not created by `bundle()` — pass the value `bundle(gpu, ...)` returned.
* `VGPU-BUNDLE-BLEND-CONSTANT` when recording a draw with `blendConstant` — the blend constant is render-pass state that render bundle encoders cannot set; encode such draws in a frame pass instead.
* `VGPU-BUNDLE-STENCIL-REF` when recording a draw whose `stencil` has `ref` — the stencil reference is likewise render-pass state; stencil state without `ref` records fine.
* `VGPU-SURFACE-DISPOSED` when `opts.target` is a disposed surface, or when replaying against a disposed surface — record and replay against a live `surface(gpu, canvas)`.
* `VGPU-DRAW-DISPOSED` from `recorder.draw(drawable)` when the draw or effect was already disposed — record a live draw or effect.
* Draw binding errors such as `VGPU-R1-BINDING-NEVER-SET` can throw during recording. A recording that throws returns no bundle and leaves nothing registered on the draws or resources it touched.

`FramePass.bundles()` checks every bundle in the list before replaying any: one stale or disposed entry means none of the list replays.

## Examples

```ts
import { init, bundle, draw, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [64, 64] });
const drawable = draw(gpu, { shader: prepareShader(`
  @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
    var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
    return vec4f(p[vi], 0, 1);
  }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1, 1, 0, 1); }
`) });

const statics = bundle(gpu, { target: colorTarget, label: "static" }, (recorded) => {
  recorded.draw(drawable);
});

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: colorTarget }, (pass) => pass.bundles(statics));
});
```

Create a draw or effect inside the function that records it and return only the bundle. The bundle does not need the effect to stay reachable:

```ts
import { init, bundle, effect, frame, target, type Bundle, type Gpu, type Target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const sceneTarget = target(gpu, { size: [64, 64] });

// ---cut---
function recordBackground(gpu: Gpu, sceneTarget: Target): Bundle {
  const background = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.1, 0.2, 0.4, 1); }`));
  return bundle(gpu, { target: sceneTarget, label: "background" }, (recorded) => recorded.draw(background));
} // `background` is unreachable once this returns; the bundle keeps its own snapshots

const backgroundBundle = recordBackground(gpu, sceneTarget);

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: sceneTarget }, (pass) => pass.bundles(backgroundBundle)); // replays without the effect
});
```

Collecting the effect does not make `backgroundBundle` stale. Keep the draw or effect only when you still need to `set()` its uniforms, rebind it, or draw it outside the bundle.

Record for a canvas during loading by passing the live surface as the target, then replay inside a frame. The bundle keeps replaying after the canvas resizes, because the signature does not include size:

```wgsl
// surface-background.wgsl
@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.1, 0.2, 0.4, 1); }
```

```ts
import { init, bundle, effect, frameLoop, surface } from "vgpu";
import backgroundShader from "./surface-background.wgsl";

const gpu = await init();
const canvasSurface = surface(gpu, document.querySelector("canvas")!);
const background = effect(gpu, backgroundShader);

// ---cut---
const statics = bundle(gpu, { target: canvasSurface, label: "surfaceStatics" }, (recorded) => {
  recorded.draw(background);
}); // outside any frame: reads canvasSurface.format, acquires no canvas texture

frameLoop(gpu, (currentFrame) => {
  currentFrame.pass({ target: canvasSurface }, (pass) => pass.bundles(statics)); // no re-record on resize
});
```

Recording reads the surface's configured signature only. It does not acquire the current canvas texture, read or allocate attachments, resize the canvas, notify `onResize` listeners, or submit work.

Replace a bundle when something it samples changes. Record the next bundle first, swap your reference, then dispose the old one — if recording throws, the old bundle is still in place:

```wgsl
// post.wgsl
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var samp: sampler;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(1.0 - textureSampleLevel(src, samp, uv, 0.0).rgb, 1.0);
}
```

```ts
import { init, bundle, effect, frameLoop, sampler, surface, target, type Bundle } from "vgpu";
import postShader from "./post.wgsl";

const gpu = await init();
const canvasSurface = surface(gpu, document.querySelector("canvas")!);
const sceneTarget = target(gpu, { size: [canvasSurface.size[0], canvasSurface.size[1]] });
const postEffect = effect(gpu, postShader);
postEffect.set({ src: sceneTarget, samp: sampler(gpu, { minFilter: "linear", magFilter: "linear" }) });

// ---cut---
let post: Bundle | undefined;

canvasSurface.onResize(({ width, height }) => {
  sceneTarget.resize([width, height]); // new textures: a bundle sampling the old ones is stale
  const next = bundle(gpu, { target: canvasSurface, label: "post" }, (recorded) => {
    recorded.draw(postEffect);
  });
  const previous = post;
  post = next;
  previous?.dispose(); // release the replaced bundle now instead of waiting for collection
}); // fires once immediately, so this also records the first bundle

frameLoop(gpu, (currentFrame) => {
  currentFrame.pass({ target: canvasSurface }, (pass) => pass.bundles(post!));
});
```

```ts
import { init, bundle, clock, effect, frame, pingPong } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const ping = pingPong(gpu, 32, 32);
const shader = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }`));
const even = bundle(gpu, { target: ping.write }, (b) => b.draw(shader));
ping.swap();
const odd = bundle(gpu, { target: ping.write }, (b) => b.draw(shader));
ping.swap();

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: ping.write }, (p) => p.bundles(clock(gpu).frameCount % 2 ? odd : even));
});
```

Dispose on teardown. Disposal does not cancel a frame that already replayed the bundle, and it leaves the recorded effect usable:

```ts
import { prepareShader } from "@vgpu/wgsl/prepare";
import { init, bundle, effect, frame, target } from "vgpu/mock";

const gpu = await init();
const colorTarget = target(gpu, { size: [64, 64] });
const shader = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }`));

// ---cut---
const statics = bundle(gpu, { target: colorTarget, label: "statics" }, (recorded) => recorded.draw(shader));

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: colorTarget }, (pass) => pass.bundles(statics));
  statics.dispose(); // the replay is already encoded; this frame still submits it
});

statics.dispose(); // no-op: dispose() is idempotent
console.log(statics.id); // "statics" — still readable
// statics.gpu and pass.bundles(statics) now throw VGPU-BUNDLE-DISPOSED
shader.draw(colorTarget); // the effect was borrowed, not destroyed
```

## Signature-arm recording

`bundle(gpu, { target: { colors: ["bgra8unorm"], depth: "depth24plus", sampleCount: 4 } }, cb)` records before a target exists. This relaxes only the replay target: any resources sampled by draws still need to be set before recording. Cold signature recording creates missing pipelines synchronously, which can jank; pre-warm first with `await draw.compile(signature)` or `await effect.compile(signature)`.

For future canvas surfaces, use `navigator.gpu.getPreferredCanvasFormat()` when building the signature; for an existing surface, pass the surface itself. A surface and an equivalent signature such as `{ colors: [canvasSurface.format] }` produce the same signature key, so either form records a bundle that replays on that surface. A bundle recorded for `bgra8unorm` will not replay on an `rgba8unorm` surface, and the stale error prints both keys.

## Lifetime

A bundle holds its native render bundle plus independent snapshots of what it recorded: each captured texture, buffer, and target, the attachment of each `Target` it samples, and the geometry it draws. It does not hold the recorded draws or effects, and neither they nor the resources they bind hold the bundle. When your code drops its last reference to a bundle, the bundle becomes unreachable and is collected eventually, like any JavaScript object. vgpu makes no promise about when collection happens or when the driver reclaims the native bundle's memory.

Dropping a recorded draw or effect is not a change to the bundle. If the draw is collected, the bundle keeps replaying, and its snapshots still detect what happens later: destroying a captured texture, buffer, or target, or replacing a sampled `Target`'s attachment, makes replay throw `VGPU-R3-BUNDLE-STALE`; destroying recorded geometry makes replay throw that geometry's liveness error.

Disposing a recorded draw or effect is a change. `draw.dispose()` and `effect.dispose()` permanently stale every bundle that recorded them — including a bundle whose recording callback is still running — and replay throws `VGPU-R3-BUNDLE-STALE` naming the disposed draw. Collection is silent and keeps the bundle; disposal is explicit and retires it. Dispose a draw only when you also replace or drop the bundles that recorded it:

```ts
import { init, bundle, effect, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const sceneTarget = target(gpu, { size: [64, 64] });

// ---cut---
let sky = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.4, 0.6, 0.9, 1); }`), { label: "daySky" });
let skyBundle = bundle(gpu, { target: sceneTarget, label: "day" }, (recorded) => recorded.draw(sky));

function switchToNight(): void {
  const nextSky = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.02, 0.03, 0.1, 1); }`), { label: "nightSky" });
  const nextBundle = bundle(gpu, { target: sceneTarget, label: "night" }, (recorded) => recorded.draw(nextSky));
  const previousSky = sky;
  const previousBundle = skyBundle;
  sky = nextSky;
  skyBundle = nextBundle; // swap only after recording succeeded
  previousSky.dispose(); // permanently stales previousBundle
  previousBundle.dispose(); // then release the stale bundle
}

switchToNight();
frame(gpu, (currentFrame) => {
  currentFrame.pass(sceneTarget, (pass) => pass.bundles(skyBundle)); // replays the night sky
});
```

Between the two `dispose()` calls, replaying the day bundle would throw `VGPU-R3-BUNDLE-STALE` with `Bundle 'day' is stale: draw 'daySky' was disposed.` Disposing the bundle as well releases its snapshots now instead of at collection.

Disposing the draw leaves native work alone. Commands already encoded in a frame still submit, and a `GPURenderBundle` read from `bundle.gpu` before or after the draw's disposal keeps replaying the last uniform contents the draw wrote — vgpu never revalidates or revokes it.

Rebinding is checked per bundle. A draw rebound after a bundle finished recording stales that bundle, even when the rebind happens inside another bundle's recording callback. Within one recording, rebinding between `recorded.draw()` calls is deliberate: each call records the resources bound at that moment, and the bundle validates all of them at replay.

`dispose()` releases vgpu's references and registrations at a point you choose. It is synchronous and idempotent: it unregisters the bundle from the draws and resources it watched, drops its snapshots, and drops its reference to the native render bundle. It never destroys borrowed resources — the draws, effects, geometry, textures, buffers, samplers, and targets stay yours. After disposal, `id` stays readable, and reading `gpu` or replaying the bundle throws `VGPU-BUNDLE-DISPOSED`. Neither garbage collection nor `dispose()` promises when native WebGPU or the driver reclaims memory.

Neither disposal nor collection — of the bundle or of the draws it recorded — reaches work or handles that already left the facade. A frame that replayed the bundle before `dispose()` still submits it. A `GPURenderBundle` you read from `bundle.gpu` stays usable for as long as native WebGPU keeps it valid; vgpu cannot revoke it, and only `FramePass.bundles()` checks staleness — replaying that native handle yourself does not. While you hold the recorded draw and have not disposed it, its `set()` uniform updates keep reaching that native handle too.

A bundle that becomes permanently stale — a captured resource was rebound or destroyed, a sampled `Target` replaced its attachment, or a recorded draw or effect was disposed — detaches from its draws and resources right away, so later `set()` or `destroy()` calls do no work for it. You still `dispose()` it or drop it; until then, replay keeps throwing `VGPU-R3-BUNDLE-STALE` with the first cause.

## Notes

* Bundles match replay targets by render signature, not size. They survive resizing the target they draw onto. Do not re-record because the destination resized.
* Re-record when the bundle samples a resized target; vgpu detects the changed texture identity and reports `VGPU-R3-BUNDLE-STALE`.
* Replace bundles in this order: record the next bundle, swap your reference, then `dispose()` the old one. Disposing first leaves you with nothing to replay if the new recording throws.
* `surface.onResize(...)` fires immediately, so the same re-recording callback can initialize and refresh bundles that sample resized resources.
* Bundles freeze bind group identities, not buffer contents. Updating JS-owned packed values in-place is safe, and `set()` uniform updates on a draw you still hold keep reaching every live bundle that recorded it, including native handles read from `bundle.gpu`, until you dispose the draw. Rebinding a different texture/buffer/sampler after recording stales the bundle.
* Do not keep draws or effects alive only so their bundles keep working. A bundle replays and detects destroyed resources on its own; keep the draw only to update, rebind, or draw it again.
* Do not call `dispose()` on a draw or effect whose bundles you still replay: disposal stales them permanently. To let a draw go while keeping its bundle, drop your reference instead.
* Record against a live `Surface` inside or outside a frame; recording uses its configured signature and never acquires a canvas texture. Replay stays inside `frame(gpu)` or `frameLoop(gpu)`, because `pass.bundles()` exists only on a frame pass. Recording against a disposed surface throws `VGPU-SURFACE-DISPOSED`.
* Neither garbage collection nor `dispose()` frees GPU or driver memory on a schedule. Call `dispose()` when you replace or tear down bundles and want vgpu's references and registrations released synchronously.
* Draws with `blendConstant` cannot be recorded: render bundle encoders have no way to set the pass blend constant. Recording throws `VGPU-BUNDLE-BLEND-CONSTANT`; use `FramePass.draw` for those draws.
* Draws whose `stencil` has `ref` cannot be recorded either: render bundle encoders have no way to set the pass stencil reference. Recording throws `VGPU-BUNDLE-STENCIL-REF`; stencil pipeline state without `ref` records fine.
* **See also:** `FramePass.bundles`, `Draw`, `Effect`, `Surface`, `Target`, `createRenderBundle`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: clock
description: The frame clock of a gpu: elapsed time, last delta, frame count, and the manual `advance()` that lets an external ticker own the clock. Use it whenever a shader, a camera or a simulation needs time; use `advance()` when something else already owns the timeline (GSAP/Motion, an XR frame callback, a fixed-timestep loop, a deterministic replay).
---

# clock



## Import

```ts
import { clock } from "vgpu";
```

## Signature

```ts
import type { Gpu } from "vgpu";

interface Clock {
  readonly time: number;
  readonly deltaTime: number;
  readonly frameCount: number;
  advance(dtSeconds: number): void;
}

declare function clock(gpu: Gpu): Clock;
```

## Parameters

| Param             | Type     | Required | Default | Notes                                                                                                                                            |
| ----------------- | -------- | -------: | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| gpu               | `Gpu`    |        ✔ | —       | The context returned by `init()`. One clock per gpu: `clock(gpu) === clock(gpu)`.                                                                |
| advance.dtSeconds | `number` |        ✔ | —       | Seconds to move the clock forward, finite and `>= 0`. Scale it for a timescale (`dt * 0.5`), or pass a constant for a fixed timestep (`1 / 60`). |

| Property   | Type     | Default | Notes                                                                                                                                |
| ---------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| time       | `number` | `0`     | Seconds since the first frame. Advances once per frame: with the wall-clock delta, or with the value the last `advance()` was given. |
| deltaTime  | `number` | `0`     | Seconds between the last two ticks. Exactly the argument of the last `advance()` when driving the clock manually.                    |
| frameCount | `number` | `0`     | Frames opened by `frame(gpu)` / `frameLoop(gpu)`. `advance()` never counts a frame.                                                  |

**Returns:** `Clock` — a live view of this gpu's frame clock. It reads through to the clock, so a single instance can be captured outside the loop and read inside it.

**Throws:** `VGPU-GPU-DISPOSED` when `clock(gpu)` runs after `gpu.dispose()` — read the clock before disposing, or `init()` a new gpu; `VGPU-GPU-FOREIGN` when the argument was not created by `init()`; `VGPU-CLOCK-DELTA-INVALID` when `advance()` receives a value that is not a finite, non-negative number — pass elapsed seconds, e.g. `advance(1 / 60)`.

## Examples

```wgsl
// wave.wgsl
struct Params { time: f32 }
@group(0) @binding(0) var<uniform> params: Params;
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, sin(params.time) * 0.5 + 0.5, 1.0);
}
```

```ts
import { init, clock, effect, frameLoop, surface } from "vgpu";
import waveShader from "./wave.wgsl";

declare const canvas: HTMLCanvasElement;

const gpu = await init();
const canvasSurface = surface(gpu, canvas);
const wave = effect(gpu, waveShader, { set: { params: { time: 0 } } });

// Automatic: every frame advances the clock with the wall-clock delta.
const time = clock(gpu);
frameLoop(gpu, (frame) => {
  wave.set({ params: { time: time.time } });
  frame.pass(canvasSurface, wave);
});
```

```ts
import { init, clock, effect, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [64, 64] });
const shader = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }`));

// Manual: a fixed timestep makes the render deterministic, run after run.
const time = clock(gpu);
for (let step = 0; step < 120; step++) {
  time.advance(1 / 60);
  frame(gpu, (currentFrame) => currentFrame.pass(scene, shader));
}
console.log(time.time, time.frameCount); // 2, 120
```

```ts
import { init, clock, frameLoop } from "vgpu/mock";

const gpu = await init();
const time = clock(gpu);

// Timescale: the same wall clock, played at half speed. Slow motion is one multiplication.
let previousMs = performance.now();
const timescale = 0.5;
frameLoop(gpu, () => {
  const nowMs = performance.now();
  time.advance(((nowMs - previousMs) / 1000) * timescale);
  previousMs = nowMs;
});
```

## Notes

* One tick per frame, manual first: `frame()` advances the clock with wall-clock time **unless** `advance()` already ran since the last frame. Calling `advance(dt)` and then `frame()` in the same tick advances exactly once, by `dt`.
* `advance()` moves `time` and `deltaTime` immediately, before any frame opens — so code that reads the clock outside a frame (input smoothing, physics substeps) sees the value it is about to render with.
* Mixing is allowed and useful: drive the clock manually while an external ticker runs, then drop back to plain `frame(gpu)` calls and the wall clock takes over again, measured from the last tick.
* The clock is not a global. It belongs to the gpu, and it is created lazily: a program that never opens a frame and never calls `clock(gpu)` never allocates it.
* There is no clock on `Frame`. Pass `clock(gpu)` (or the numbers you read from it) into render helpers instead of reaching for frame state.
* **See also:** `frame`, `frameLoop`, `Gpu`, and the guide *Driving vgpu with an external ticker*.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Compute
description: Compute pipeline created by `compute(gpu)` from a prepared `ShaderSource`. It reads bindings from the artifact's reflection and follows the same `set()` ownership rules as render draws, then `dispatch(x, y?, z?)` — or `dispatch({ indirect })` for GPU-driven counts — encodes and submits one compute pass.
---

# Compute



## Import

```ts
import type { Compute, ComputeOptions, DispatchOptions, StorageAccess, StorageBuffer, StorageOptions } from "vgpu";
```

## Signature

```ts
interface ComputeOptions {
  readonly label?: string;
  readonly set?: Record<string, unknown>;
  readonly constants?: Readonly<Record<string, number | boolean>>;
  readonly entry?: string;
}

interface DispatchOptions {
  readonly indirect: StorageBuffer | { readonly buffer: StorageBuffer; readonly offset?: number };
}

interface Compute {
  dispose(): void;
  set(values: Record<string, unknown>): this;
  compile(): Promise<this>;
  compileSync(): this;
  dispatch(x: number, y?: number, z?: number): void;
  dispatch(opts: DispatchOptions): void;
}

type StorageAccess = "read" | "read-write";

interface StorageOptions {
  readonly access?: StorageAccess;
  readonly indirect?: boolean;
}

interface StorageBuffer {
  readonly size: number;
  readonly access: StorageAccess;
  read(): Promise<ArrayBuffer>;
  write(data: BufferSource): void;
}
```

## Parameters

| Param                          | Type                                          |          Required | Default                                                             | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ------------------------------ | --------------------------------------------- | ----------------: | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| compute.source                 | `ShaderSource`                                |                 ✔ | —                                                                   | Prepared `version: 2` artifact: a `.wgsl` import through the `@vgpu/wgsl` Vite/webpack loader, a prebuilt asset, or `prepareShader(wgsl)` from `@vgpu/wgsl/prepare`. Raw WGSL strings and `version: 1` artifacts are rejected. `compute(gpu)` keeps its own validated snapshot, so changing the artifact object afterwards does not affect an existing compute. Must include at least one `@compute` entry point.                                                                                                                                 |
| compute.opts                   | `ComputeOptions`                              |                 ✖ | `{}`                                                                | Initial compute options.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| opts.label                     | `string`                                      |                 ✖ | `"compute"`                                                         | Used in GPU object labels (shader module and pipeline) and error `where` fields.                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| opts.set                       | `Record<string, unknown>`                     |                 ✖ | `undefined`                                                         | Initial `.set()` call.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| opts.constants                 | `Readonly<Record<string, number \| boolean>>` |                 ✖ | WGSL defaults                                                       | Constructor-only values for WGSL `override` constants, applied to the compute stage. Use them to tune workgroup size per device or workload at pipeline creation: `@workgroup_size(WG)` with `override WG: u32`. Keying (`@id(N)` → decimal string of `N`) and number/boolean conversion match `DrawOptions.constants`.                                                                                                                                                                                                                           |
| opts.entry                     | `string`                                      |                 ✖ | `cs_main` when declared, otherwise first `@compute` entry           | Constructor-only entry point selection when one WGSL module packs several `@compute` kernels sharing structs and bindings (e.g. emit/simulate/compact). The name must exist in the shader with the `@compute` stage. Without a name, a unique compute entry is selected regardless of its name; with several entries, `cs_main` wins when declared, otherwise the first is used. Binding visibility, bind group layouts, and the storage-aliasing preflight follow the selected entry.                                                            |
| compute.set.values             | `Record<string, unknown>`                     |                 ✔ | —                                                                   | Binding values by WGSL variable name. JS values are packed; buffers/resources are bound by identity. A raw `GPUBuffer` or `GPUBufferBinding` (`{ buffer, offset?, size? }`) in a uniform/storage slot binds that byte range as a caller-owned resource, with the same defaults, snapshot, and checks as [`Draw`](/docs/reference/vgpu/draw#draw) (see Notes). `texture_storage_*` bindings take a `Texture` from `texture(gpu)` whose `usage` includes `storage_binding`. A `Surface` is rejected in every slot with `VGPU-SURFACE-NOT-BINDABLE`. |
| compute.dispatch.x             | `number`                                      |                 ✔ | —                                                                   | Workgroup count X passed to `dispatchWorkgroups`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| compute.dispatch.y             | `number`                                      |                 ✖ | `1`                                                                 | Workgroup count Y.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| compute.dispatch.z             | `number`                                      |                 ✖ | `1`                                                                 | Workgroup count Z.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| compute.dispatch.opts.indirect | `StorageBuffer \| { buffer, offset? }`        | ✔ in the overload | —                                                                   | GPU-driven dispatch via `dispatchWorkgroupsIndirect`: the GPU reads `[x, y, z]` workgroup counts (3 tightly packed u32, 12 bytes) from the buffer at the byte `offset` (default `0`). Use it when an earlier pass decides how much work exists — variable particle populations, stream compaction. Requires a buffer created with `storage(gpu, bytes, { indirect: true })`; `offset` must be a multiple of 4 and `offset + 12 <= size`. Cannot be combined with explicit counts.                                                                 |
| compute.dispose                | `() => void`                                  |                 ✖ | not called — a compute you stop referencing is collected without it | Takes no arguments. Synchronous and idempotent; valid after `gpu.dispose()` or device loss. Retires the compute: every later member call throws `VGPU-COMPUTE-DISPOSED`, and it releases its bindings, values, and cached bind groups. Never destroys borrowed storage buffers, textures, `uniforms()` blocks, or the shared pipeline. See Disposal below.                                                                                                                                                                                        |
| storage.bytes                  | `number`                                      |                 ✔ | —                                                                   | Byte size for a main API (`vgpu`) storage buffer.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| storage.access                 | `StorageAccess \| StorageOptions`             |                 ✖ | `"read-write"`                                                      | Access string, or a `StorageOptions` bag with `access` and `indirect`. Stored on the resource facade and used by binding normalization.                                                                                                                                                                                                                                                                                                                                                                                                           |
| storage.access.indirect        | `boolean`                                     |                 ✖ | `false`                                                             | Appends the `"indirect"` buffer usage so the buffer can supply GPU-read draw/dispatch arguments.                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| storage.write.data             | `BufferSource`                                |                 ✔ | —                                                                   | `ArrayBuffer` or `ArrayBufferView`; writes at offset `0` in the public main API (`vgpu`) type.                                                                                                                                                                                                                                                                                                                                                                                                                                                    |

**Returns:** `compute(gpu)` returns `Compute`; `set()` and `compileSync()` return the same `Compute`; `compile()` resolves to that object after successful validation; `dispatch()` returns `void` after submitting; `dispose()` returns `void`; `storage(gpu)` returns a main API (`vgpu`) `StorageBuffer`; `StorageBuffer.read()` resolves an `ArrayBuffer` copy.

**Throws:** `VGPU-COMPUTE-DISPOSED` when any member other than `dispose()` is used after `dispose()` — `set()`, either `dispatch()` overload, `compile()`, `compileSync()`, or `FrameComputePass.dispatch(compute, ...)`. The message is `Compute '<label>' has been disposed.`, `where` is `<label>.<operation>`, and `detail` is `{ label }`. The check runs before this compute's argument, binding, aliasing, and device checks; frame and pass errors keep their own precedence. `compile()` throws synchronously when already disposed, and a pending `compile()` rejects with this code once its preparation settles. Create a new `compute(gpu, ...)`; a disposed compute cannot be reused. `VGPU-RING1-UNSUPPORTED` when the shader has no `@compute` entry point; `VGPU-INDIRECT-INVALID` at dispatch time for a malformed `indirect` (neither a `StorageBuffer` nor `{ buffer, offset? }`), a buffer created without the indirect flag (use `storage(gpu, bytes, { indirect: true })`), an `offset` that is not a non-negative integer multiple of 4, counts that do not fit the buffer (`offset + 12 > size`), or `indirect` combined with explicit workgroup counts in the same call; `VGPU-CONSTANTS-INVALID` for a malformed `constants` option (non-object value, a key that matches no override in the shader — the message lists the available overrides — or a value that is neither a finite number nor a boolean), and for an override declared without a default that `constants` does not provide; `VGPU-ENTRY-INVALID` for a non-string `entry`, a name that matches no entry point in the shader, or a name whose entry point is not `@compute` — the message lists the shader's available entry points with their stages; `VGPU-SET-VALUE-INVALID` when a JS-owned binding has the wrong reflected shape or an out-of-range integer; `VGPU-R1-STORAGE-ALIASING` at `<label>.dispatch`, before any native dispatch, when one underlying `GPUBuffer` allocation is bound to more than one storage binding and at least one of them is writable — the check compares allocations, not ranges, so different offsets, different sizes, disjoint ranges, and a tracked core `Buffer` bound alongside its own raw `buffer.gpu` all count as aliasing; alternate the buffers with `pingPongStorage(gpu)`; `VGPU-R1-BINDING-NEVER-SET`, `VGPU-R1-OWNERSHIP-FLIP`, and `VGPU-R1-BINDING-INCOMPATIBLE-RESOURCE` for binding errors, including storage textures without `storage_binding` usage or whose format/dimension differs from WGSL; `VGPU-R1-BINDING-INCOMPATIBLE-RESOURCE` is also thrown at `set` for tracked `Buffer`, Uniform-like, and provider bindings: native-usage validation remains synchronous, and checkable range validation now makes previously native-only reflected-minimum, granted-maximum, and storage-size failures synchronous too; for a raw `GPUBuffer`/`GPUBufferBinding` it covers a missing `uniform`/`storage` usage, a non-integer, negative, `null`, or out-of-bounds `offset`/`size`, a zero size, an `offset` that is not a multiple of the granted `minUniformBufferOffsetAlignment`/`minStorageBufferOffsetAlignment`, a range smaller than the WGSL type or larger than the granted maximum binding size, or a storage size that is not a multiple of 4 — the message names the binding, group, and binding number, raw-range `fix` gives the required usage and a valid aligned offset/size, and the previous value stays bound; `VGPU-R1-BINDING-DESTROYED` when `set()` receives an already-destroyed tracked `Buffer`, `Uniform`, `uniforms()` block, or `Texture`, or an active tracked resource was destroyed before use — bind a live replacement (direct operations on a destroyed `Buffer`, such as `write()`, still report `VGPU-BUFFER-DISPOSED`; a destroyed raw `GPUBuffer` is reported by native WebGPU validation instead); `VGPU-SURFACE-NOT-BINDABLE` when a `Surface` is passed as a binding value in `opts.set` or a later `set()`, inside or outside a frame — `where` is `<label>.<binding>`, vgpu throws before reading the surface's attachments or acquiring a canvas texture, and the rejected binding keeps its previous value (keys earlier in the same `set()` call are already applied); render to an offscreen target and bind that target or its texture, and use the `Surface` only as a render destination; `VGPU-SHADER-SOURCE-UNPREPARED` when `source` is a raw WGSL string or a `version: 1` artifact (import the `.wgsl` file through a compatible `@vgpu/wgsl` loader, rebuild prebuilt assets, or pass `prepareShader(wgsl)` from `@vgpu/wgsl/prepare`); `VGPU-SHADER-SOURCE-VERSION` when `source.version` is an integer other than `2` (the message names the received version, the supported version, and the artifact's `producer`; align the `@vgpu/wgsl` tooling and `vgpu` runtime versions, then regenerate); `VGPU-SHADER-SOURCE-INVALID` when `source` is not an object, `version` is missing or not an integer, a required field is missing, accessor-backed, or malformed, the reflection metadata is inconsistent, or `sourceChecksum` does not match `wgsl` (structured detail gives the field `path` and the `reason`; regenerate the artifact with a supported producer); these three throw synchronously from `compute(gpu)`, before any compute option is validated; `TypeError` if `StorageBuffer.write()` receives a non-buffer source.

## Examples

```wgsl
// sim.wgsl
@group(0) @binding(0) var<storage, read> src: array<vec4f>;
@group(0) @binding(1) var<storage, read_write> dst: array<vec4f>;
@compute @workgroup_size(1)
fn cs_main(@builtin(global_invocation_id) id: vec3u) {
  dst[id.x] = src[id.x] + vec4f(1.0, 0.0, 0.0, 0.0);
}
```

```ts
import { init, compute, storage } from "vgpu/mock";
import simShader from "./sim.wgsl"; // prepared at build time by the @vgpu/wgsl loader

const gpu = await init();
const bytes = 4 * 16;
const src = storage(gpu, bytes, "read");
const dst = storage(gpu, bytes, "read-write");
src.write(new Float32Array(16));

const sim = compute(gpu, simShader, { label: "sim", set: { src, dst } });

sim.dispatch(4);
```

The loader turns `sim.wgsl` into a prepared `ShaderSource`, so the app bundle ships no WGSL parser. The remaining examples keep their WGSL inline and wrap it in `prepareShader()` from `@vgpu/wgsl/prepare`; calling it in browser code bundles the parser, so prefer `.wgsl` imports for static shaders.

```ts
import { init, compute, pingPongStorage } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const particles = pingPongStorage(gpu, 1024);
const step = compute(gpu, prepareShader(`
  @group(0) @binding(0) var<storage, read> src: array<u32>;
  @group(0) @binding(1) var<storage, read_write> dst: array<u32>;
  @compute @workgroup_size(64)
  fn cs_main(@builtin(global_invocation_id) id: vec3u) { dst[id.x] = src[id.x]; }
`));

step.set({ src: particles.read, dst: particles.write });
step.dispatch(Math.ceil(256 / 64));
particles.swap();
```

```ts
import { init, compute, storage } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const wg = 64; // tune per device or workload without editing WGSL
const data = storage(gpu, 4 * 256);
const scale = compute(gpu, prepareShader(`
  override WG: u32 = 64;
  @group(0) @binding(0) var<storage, read_write> data: array<f32>;
  @compute @workgroup_size(WG)
  fn cs_main(@builtin(global_invocation_id) id: vec3u) { data[id.x] = data[id.x] * 2.0; }
`), { constants: { WG: wg }, set: { data } });

scale.dispatch(Math.ceil(256 / wg));
```

One JS constant drives both the pipeline's workgroup size and the dispatch math, so retuning `wg` cannot desynchronize them.

```ts
import { init, compute, storage } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const alive = storage(gpu, 4, "read");             // live-particle count, e.g. from emission/compaction
const args = storage(gpu, 12, { indirect: true }); // [x, y, z] workgroup counts
const particles = storage(gpu, 4 * 1024);

const prepare = compute(gpu, prepareShader(`
  @group(0) @binding(0) var<storage, read> alive: u32;
  @group(0) @binding(1) var<storage, read_write> args: array<u32, 3>;
  @compute @workgroup_size(1) fn cs_main() {
    args[0] = (alive + 63u) / 64u; args[1] = 1u; args[2] = 1u; // one workgroup per 64 live particles
  }
`), { set: { alive, args } });

const step = compute(gpu, prepareShader(`
  @group(0) @binding(0) var<storage, read_write> particles: array<f32>;
  @compute @workgroup_size(64)
  fn cs_main(@builtin(global_invocation_id) id: vec3u) { particles[id.x] = particles[id.x] + 0.016; }
`), { set: { particles } });

prepare.dispatch(1);               // GPU computes how much work exists
step.dispatch({ indirect: args }); // GPU reads the counts; JS never sees them
```

GPU-driven dispatch: the first pass writes the workgroup counts from GPU-side state, so the population can vary every frame without a readback stall.

## Disposal

`dispose()` is optional. A compute you stop referencing is collected eventually, like any JavaScript object. Call `dispose()` to retire it at a known point: every later call throws `VGPU-COMPUTE-DISPOSED`, and the compute releases its bindings, packed values, and cached bind groups synchronously. It is idempotent and needs no live device, so it is safe after `gpu.dispose()` or device loss.

```ts
import { init, compute, frame, storage } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const particles = storage(gpu, 4 * 256);

// ---cut---
const integrate = compute(gpu, prepareShader(`
  @group(0) @binding(0) var<storage, read_write> particles: array<f32>;
  @group(0) @binding(1) var<uniform> dt: f32;
  @compute @workgroup_size(64)
  fn cs_main(@builtin(global_invocation_id) id: vec3u) { particles[id.x] += dt; }
`), { label: "integrate", set: { particles, dt: 0.016 } });
await integrate.compile();

const pending = frame(gpu); // manual frame: nothing submits until submit()
pending.computePass((pass) => pass.dispatch(integrate, 4)); // captures dt now
integrate.dispose(); // retire the compute before the frame submits
pending.submit(); // the encoded dispatch still runs with dt = 0.016
await pending.done;

particles.write(new Float32Array(256)); // the borrowed storage buffer stays yours
// integrate.set(...), integrate.dispatch(...), and pass.dispatch(integrate, ...) now throw VGPU-COMPUTE-DISPOSED
```

Disposal retires the facade, not the work already handed to WebGPU. An encoded dispatch keeps the uniform values captured when it was encoded, and canceling its frame still discards it. Borrowed storage buffers, textures, and `uniforms()` blocks are never destroyed. The compiled pipeline stays in the device-wide store, so another compute built from the same shader keeps using it.

A `compile()` still pending when you call `dispose()` is not canceled. It settles with the underlying native compilation, then rejects with `VGPU-COMPUTE-DISPOSED` at `<label>.compile`, whether compilation succeeded or failed; a live compute sharing that pipeline resolves normally. That rejection belongs to the promise only and is not delivered again through `gpu.onError`. Neither collection nor `dispose()` promises when GPU memory is reclaimed: a private uniform buffer native work might still reference is released by reference, not destroyed.

## Notes

* `compute(gpu)` never parses WGSL; it reads bindings, entry points, and workgroup sizes from the artifact's reflection. `prepareShader()` runs the parser, so call it once per source revision — outside `frame()`/`frameLoop()` callbacks and hot paths — and reuse the artifact for every compute built from that source.
* An artifact with deeply frozen consumed data (every loader import and `prepareShader()` result) is validated once and reused by later `draw`/`effect`/`compute` calls; mutable ones are revalidated each call; changed source needs a new artifact (`ShaderSource`). Unknown additive fields are ignored. `sourceChecksum` only detects a replaced `wgsl` string, not stale `reflection` produced by older tooling, so regenerate prepared artifacts whenever the WGSL source or `@vgpu/wgsl` tooling changes.
* Use explicit `dispatch(x, y, z)` when the CPU already knows stable workgroup counts. Use `dispatch({ indirect })` when a preceding GPU pass decides the count (compaction, particles), so no CPU readback is needed.
* Declare storage `read` for source-only buffers and `read-write` for state that a kernel updates. For iterative simulation, bind `pingPongStorage(gpu, ...)` read/write pairs and swap after each step instead of aliasing one writable buffer.
* `StorageBuffer.read()` is for tests, snapshots, and diagnostics; avoid awaiting it in a hot loop unless CPU synchronization is intentional.
* Use `pingPongStorage(gpu, bytes)` when a compute step reads previous state and writes next state; binding one storage allocation twice with any writable binding is rejected before dispatch. The check is deliberately conservative: it compares the underlying native `GPUBuffer` allocation, whether you bound it as a tracked buffer or as a raw `GPUBuffer`/`{ buffer, offset, size }`, and not byte ranges, so splitting one buffer into disjoint ranges for `src` and writable `dst` still throws `VGPU-R1-STORAGE-ALIASING` — use two allocations. Binding one allocation to several read-only storage bindings is allowed.
* Raw buffers bind by the [`Draw` raw-buffer rules](/docs/reference/vgpu/draw#draw): `set()` recognizes a raw `GPUBuffer` or `{ buffer: GPUBuffer, offset?, size? }` by shape, so a WGSL struct whose members are named `buffer`, `offset`, or `size` still packs as data. Omitted `offset` is `0` and omitted `size` is `buffer.size - offset`; only `undefined` takes a default. `set()` copies the range, so mutating your descriptor later needs another `set()`. The buffer stays yours — vgpu never destroys it, `dispose()` leaves it alone, and its contents are read live rather than captured per dispatch.
* `set()` binds sampled and storage `Texture` values through views that binding normalization generates — a storage binding uses one mip level — and may reuse a compatible generated view across computes and rebinds. This is internal and has no controls; `Texture.createView(desc)` still returns a fresh view on every call.
* Storage textures come from `texture(gpu, opts)`. `set()` validates their usage, format, and dimension against the reflected `texture_storage_*` declaration; a render `Target` is not accepted, and a `Surface` throws `VGPU-SURFACE-NOT-BINDABLE` in any slot.
* To read a rendered image in a kernel, render it into an offscreen `Target` and bind that target (it follows the attachment across `resize(...)`) or `sceneTarget.color` (that exact texture; rebind after a resize) to a sampled `texture_2d<f32>` binding. To write an image from compute, bind a storage `Texture` created with `usage: ["storage_binding", "texture_binding"]`, then present it by sampling it in an effect drawn into a surface pass.
* Bindings use compute visibility only when statically reachable from the selected compute entry point; unused declarations stay in the layout with visibility `0`.
* `constants` maps to `GPUProgrammableStage.constants` of the compute stage. Options are captured at construction; recreate the compute to change them. Pipeline creation is lazy: use `compile()`, `compileSync()`, or first dispatch.
* Direct dispatch counts must be finite integers from zero through `gpu.device.limits.maxComputeWorkgroupsPerDimension`. Zero is legal. Workgroup axes and their product must fit the granted device limits; unresolved WGSL expressions are validated natively. Default examples use portable sizes. For a larger workgroup, explicitly request the supported axis and `maxComputeInvocationsPerWorkgroup` limits using `init({ requiredLimits: ... })`.
* Write indirect counts from another compute pass (bind the same buffer as storage) or from JS via `write()`. The same option shape drives GPU-driven draws via `DrawCallOptions.indirect`.
* `storage(gpu)` creates storage buffers with `copy_src` and `copy_dst`, so they can be read back and rewritten from JS.
* Standalone `dispatch()` submits immediately, so disposing a compute right after it cannot affect that dispatch. Do not dispose a compute that a running `frameLoop(gpu)` still dispatches; stop the loop first.
* **See also:** `compute`, `ShaderSource`, `prepareShader` (`@vgpu/wgsl/prepare`), `Draw.set`, `SharedUniforms`, `Target`, `StorageBuffer` from `vgpu/core`.

## Preparation and frame-owned execution

`await compute.compile()` uses asynchronous native compilation. Its rejection belongs to the returned promise; handle it with `try`/`catch`. `compileSync()` creates synchronously, but native validation may arrive later through `gpu.onError`. `gpu.settled()` waits for tracked preparation and error delivery and never rejects. Neither `settled()` nor buffer readback proves successful execution.

```ts
import { init, compute, frame, storage } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const data = storage(gpu, 4);
const simulation = compute(gpu, prepareShader(`
  @group(0) @binding(0) var<storage, read_write> data: array<f32>;
  @group(0) @binding(1) var<uniform> dt: f32;
  @compute @workgroup_size(1) fn main() { data[0] += dt; }
`), { set: { data, dt: 0.01 } });
await simulation.compile();
const current = frame(gpu, f => f.computePass({ label: "simulation" }, pass => {
  pass.dispatch(simulation, 1);
  simulation.set({ dt: 0.02 });
  pass.dispatch(simulation, 1);
}));
await current.done;
gpu.dispose();
```

`Frame.computePass()` encodes into the frame's encoder; multiple dispatches and render passes submit once, in pass order. Canceling the frame discards its encoded compute commands. Standalone `simulation.dispatch()` always submits independently, even inside a frame callback.

Each direct frame draw/dispatch captures managed uniform values when encoded. An equal `set()` (same packed bytes) reuses the snapshot already captured in that frame. Storage buffers remain live, so later dispatches observe earlier GPU writes, and every `set()` writes JS-owned storage values even when equal. `uniforms()` adopted as storage, raw buffers, claimed bind groups, and render bundles retain live buffer semantics. Ordinary host writes are not ordered frame commands.

Additional errors: `VGPU-COMPUTE-DISPATCH-INVALID` for invalid direct counts; `VGPU-COMPUTE-WORKGROUP-INVALID` for known workgroup limit violations; `VGPU-COMPILE-FAILED` for pipeline creation/validation failures; `VGPU-COMPUTE-VALIDATION` for asynchronous compute execution validation. Automatic use of a failed pipeline throws; explicit compilation can retry.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Draw
description: Target-agnostic renderable shader unit created by `draw(gpu)`. It reads bindings from a prepared `ShaderSource`, caches pipelines per target format/depth/sample count, and supports geometries, explicit vertex counts, instancing, and raw group claims.
---

# Draw



## Import

```ts
import type { DepthOptions, Draw, DrawOptions, DrawCallOptions, DrawLayoutOptions, GeometryLike, StencilFaceOptions, StencilOptions } from "vgpu";
```

## Signature

```ts
import type { ShaderSource, StorageBuffer, Target, TargetSignature } from "vgpu";

type SetBag = Record<string, unknown>;

type BlendPreset = "alpha" | "additive" | "premultiplied";
interface BlendComponentOptions { readonly src: GPUBlendFactor; readonly dst: GPUBlendFactor; readonly op?: GPUBlendOperation; }
interface BlendOptions { readonly color: BlendComponentOptions; readonly alpha?: BlendComponentOptions; }

interface DepthOptions {
  readonly write?: boolean;
  readonly compare?: GPUCompareFunction;
  readonly bias?: number;
  readonly biasSlopeScale?: number;
  readonly biasClamp?: number;
}

interface StencilFaceOptions {
  readonly compare?: GPUCompareFunction;
  readonly fail?: GPUStencilOperation;
  readonly depthFail?: GPUStencilOperation;
  readonly pass?: GPUStencilOperation;
}

interface StencilOptions {
  readonly front?: StencilFaceOptions;
  readonly back?: StencilFaceOptions;
  readonly readMask?: number;
  readonly writeMask?: number;
  readonly ref?: number;
}

interface DrawOptions {
  readonly shader: ShaderSource;
  readonly geometry?: GeometryLike;
  readonly set?: SetBag;
  readonly label?: string;
  readonly targets?: readonly Target[];
  readonly instances?: number;
  readonly vertices?: number;
  readonly firstInstance?: number;
  readonly blend?: BlendPreset | BlendOptions;
  readonly blendConstant?: readonly [number, number, number, number];
  readonly writeMask?: readonly ("r" | "g" | "b" | "a")[];
  readonly colors?: readonly ({ readonly blend?: BlendPreset | BlendOptions; readonly writeMask?: readonly ("r" | "g" | "b" | "a")[] } | null)[];
  readonly cull?: "none" | "front" | "back";
  readonly frontFace?: "ccw" | "cw";
  readonly unclippedDepth?: boolean;
  readonly depth?: false | DepthOptions;
  readonly stencil?: StencilOptions;
  readonly multisample?: { readonly alphaToCoverage?: boolean; readonly mask?: number };
  readonly constants?: Readonly<Record<string, number | boolean>>;
  readonly entry?: { readonly vertex?: string; readonly fragment?: string };
}

interface DrawCallOptions {
  readonly target?: Target;
  readonly offsets?: readonly number[] | Partial<Record<number, readonly number[]>>;
  readonly instances?: number;
  readonly vertices?: number;
  readonly indices?: number;
  readonly firstVertex?: number;
  readonly firstIndex?: number;
  readonly baseVertex?: number;
  readonly firstInstance?: number;
  readonly indirect?: StorageBuffer | { readonly buffer: StorageBuffer; readonly offset?: number };
}

interface DrawLayoutOptions { readonly dynamicOffsets?: boolean; }

interface GeometryLike {
  readonly vertexCount?: number;
  readonly indexCount?: number;
  readonly instanceCount?: number;
  readonly vertexBuffers?: readonly GPUBuffer[];
  readonly indexBuffer?: GPUBuffer;
  readonly indexFormat?: GPUIndexFormat;
  readonly vertexBufferLayouts?: readonly GPUVertexBufferLayout[];
  readonly topology?: GPUPrimitiveTopology;
  readonly stripIndexFormat?: GPUIndexFormat;
  readonly firstVertex?: number;
  readonly firstIndex?: number;
  readonly baseVertex?: number;
}

interface Draw {
  readonly gpu: GPURenderPipeline | undefined;
  readonly targets: readonly Target[] | undefined;
  dispose(): void;
  set(values: SetBag): this;
  group(n: number, bindGroup: GPUBindGroup): this;
  layout(n: number, opts?: DrawLayoutOptions): GPUBindGroupLayout;
  draw(target?: Target | DrawCallOptions): void;
  compile(target?: Target | TargetSignature): Promise<this>;
  compileSync(target?: Target | TargetSignature): this;
}
```

## Parameters

| Param                            | Type                                                              | Required | Default                                                            | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| -------------------------------- | ----------------------------------------------------------------- | -------: | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| opts.shader                      | `ShaderSource`                                                    |        ✔ | —                                                                  | Prepared `version: 2` artifact: a `.wgsl` import through the `@vgpu/wgsl` Vite/webpack loader, a prebuilt asset, or `prepareShader(wgsl)` from `@vgpu/wgsl/prepare`. Raw WGSL strings and `version: 1` artifacts are rejected. `draw(gpu)` keeps its own validated snapshot, so changing the artifact object afterwards does not affect an existing draw. Must contain compatible vertex/fragment entry points. With no explicit selection, each stage uses its unique entry regardless of name; with multiple entries it prefers `vs_main` / `fs_main`, otherwise its first entry.                                                                                     |
| opts.geometry                    | `GeometryLike`                                                    |        ✖ | `undefined`                                                        | Supplies vertex/index buffers and layouts. Omit for generated vertex-index drawing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| opts.set                         | `Record<string, unknown>`                                         |        ✖ | `undefined`                                                        | Initial `.set()` call.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| opts.label                       | `string`                                                          |        ✖ | `"draw"`                                                           | Debug/error label.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| opts.targets                     | `readonly Target[]`                                               |        ✖ | `undefined`                                                        | Synchronous pre-warm sugar for the listed target signatures. A live `Surface` is accepted outside a frame; its configured signature is used without acquiring a canvas texture. In browser load paths, prefer `await draw.compile(target)`.                                                                                                                                                                                                                                                                                                                                                                                                                             |
| opts.instances                   | `number`                                                          |        ✖ | `1`                                                                | Default instance count. Integer `>= 0`; per-call `instances` overrides.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| opts.vertices                    | `number`                                                          |        ✖ | `3` for non-indexed, unless `geometry.vertexCount` exists          | Default non-indexed vertex count. Ignored by indexed geometries. Integer `>= 0`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| opts.firstInstance               | `number`                                                          |        ✖ | `0`                                                                | Default first instance. Integer `>= 0`; per-call `firstInstance` overrides.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| opts.blend                       | `"alpha" \| "additive" \| "premultiplied" \| BlendOptions`        |        ✖ | `undefined`                                                        | Constructor-only blend state applied uniformly to every color target. Presets resolve at construction; explicit components use `src`/`dst` and optional `op` (`"add"` default). Omitted `alpha` copies `color`.                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| opts.blendConstant               | `readonly [number, number, number, number]`                       |        ✖ | whatever the pass holds — `(0, 0, 0, 0)` at pass start             | Scales `"constant"`/`"one-minus-constant"` blend factors. Use it to fade or crossfade a whole layer per draw without touching per-vertex alpha. Encoder state, not pipeline state (see Notes). Components must be finite; values outside `[0, 1]` are legal. When omitted, no `setBlendConstant` is emitted for this draw, so constant factors read the current pass value: the `(0, 0, 0, 0)` default at the start of the pass, or the value an earlier draw in the same pass set, which persists until the next set. At least one color target's effective blend (`colors[i].blend` when that target has one, else the top-level `blend`) must use a constant factor. |
| opts.writeMask                   | `readonly ("r" \| "g" \| "b" \| "a")[]`                           |        ✖ | all channels                                                       | Constructor-only color channel mask applied uniformly to every color target. Omit to write RGBA; `[]` writes no channels; `["r","g","b"]` skips alpha.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| opts.colors                      | `readonly ({ blend?, writeMask? } \| null)[]`                     |        ✖ | `undefined`                                                        | Per-attachment blend/writeMask overrides for MRT — the deferred-shading case, where one draw writes a G-buffer (`target(gpu, { colors: [...] })`) and each attachment needs different state. One entry per color attachment, aligned by index. Inheritance is per field: `null` entries and omitted fields fall back to the top-level `blend`/`writeMask`; `{ writeMask: [] }` leaves that attachment untouched.                                                                                                                                                                                                                                                        |
| opts.cull                        | `"none" \| "front" \| "back"`                                     |        ✖ | `"none"`                                                           | Skips rasterizing triangles that face away from the chosen side. `"back"`: culls faces pointing away from the viewer; on a closed geometry they are never visible, so the GPU skips roughly half the fragment work. `"front"`: culls faces toward the viewer; used when rendering shadow maps to reduce peter panning. When omitted, no triangles are culled — required for open geometry such as foliage cards.                                                                                                                                                                                                                                                        |
| opts.frontFace                   | `"ccw" \| "cw"`                                                   |        ✖ | `"ccw"`                                                            | Winding order that counts as front-facing — the reference `cull` works against. Set `"cw"` for geometry authored clockwise, or for draws with a negative (mirrored) scale, which flips the on-screen winding. When omitted, counter-clockwise triangles are front.                                                                                                                                                                                                                                                                                                                                                                                                      |
| opts.unclippedDepth              | `boolean`                                                         |        ✖ | `false`                                                            | Disables depth clipping so geometry outside `[near, far]` rasterizes instead of vanishing. Use it for shadow-map pancaking: casters behind the light's near plane flatten onto it instead of being clipped out of the map. Requires the `"depth-clip-control"` device feature. When omitted or `false`, standard clipping applies.                                                                                                                                                                                                                                                                                                                                      |
| opts.depth                       | `false \| DepthOptions`                                           |        ✖ | `{ write: true, compare: "less-equal" }`                           | Depth test/write state for targets with a depth attachment; fields are in the `DepthOptions` table below. `false` disables depth testing for overlays and gizmos that must draw over the scene regardless of distance. When omitted, nearer fragments win and coplanar re-draws still pass; ignored when the target has no depth.                                                                                                                                                                                                                                                                                                                                       |
| opts.stencil                     | `StencilOptions`                                                  |        ✖ | WebGPU pass-through defaults                                       | Masks draws to marked screen regions using the stencil aspect of the depth attachment — portals, mirrors, object outlines, masked UI. Requires a target depth format with a stencil aspect (`depth: "depth24plus-stencil8"`). Fields are in the `StencilOptions` table below.                                                                                                                                                                                                                                                                                                                                                                                           |
| opts.multisample                 | `{ alphaToCoverage?, mask? }`                                     |        ✖ | `{ alphaToCoverage: false, mask: 0xFFFFFFFF }`                     | MSAA state. `alphaToCoverage`: turns fragment alpha into a per-sample coverage mask, so alpha-tested foliage antialiases in any draw order — no blending, no transparency sorting; requires an `msaa: true` target. `mask`: bitmask of samples the draw may write — a niche debugging tool most draws never set. Only the low `sampleCount` bits matter; higher bits are legal and ignored.                                                                                                                                                                                                                                                                             |
| opts.constants                   | `Readonly<Record<string, number \| boolean>>`                     |        ✖ | the WGSL defaults                                                  | Values for WGSL `override` constants, fixed at pipeline creation. Use them to specialize one shader — quality tiers, feature toggles, workgroup-size tuning — without string-templating the WGSL. Key by override name, or by the decimal string of `N` when the declaration has `@id(N)` (the name is not usable then). Booleans become `1`/`0`; every override declared without a default must be provided.                                                                                                                                                                                                                                                           |
| opts.entry                       | `{ vertex?: string; fragment?: string }`                          |        ✖ | `vs_main` / `fs_main` when declared, otherwise first in each stage | Selects which `@vertex`/`@fragment` functions to compile when one WGSL module declares several — variants of one technique sharing helpers, such as depth-only and shaded passes from the same source. Names must exist in the shader with the matching stage. Omitted fields select the sole entry of that stage, or prefer its conventional name when several exist, falling back to the first. Explicit names always take priority and must be valid.                                                                                                                                                                                                                |
| draw\.set.values                 | `Record<string, unknown>`                                         |        ✔ | —                                                                  | Values keyed by WGSL binding variable name. JS objects/numbers are packed; resources are bound by identity. A raw `GPUBuffer` or `GPUBufferBinding` (`{ buffer, offset?, size? }`) in a uniform/storage slot binds that byte range as a caller-owned resource; omitted `offset` is `0` and omitted `size` is `buffer.size - offset` (see Raw buffers and byte ranges). A `Target` follows its attachment across resizes; a `Texture` stays bound to that exact texture. A `Surface` is rejected in every slot with `VGPU-SURFACE-NOT-BINDABLE`.                                                                                                                         |
| draw\.group.n                    | `number`                                                          |        ✔ | —                                                                  | Bind group index to claim for manual bind-group binding (`group(n, bindGroup)`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| draw\.group.bindGroup            | `GPUBindGroup`                                                    |        ✔ | —                                                                  | Must be compatible with `draw.layout(n)` or `draw.layout(n, { dynamicOffsets: true })`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| draw\.layout.n                   | `number`                                                          |        ✔ | —                                                                  | Reflected bind group index.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| draw\.layout.opts.dynamicOffsets | `boolean`                                                         |        ✖ | `false`                                                            | When `true`, returns/reuses a layout whose buffer entries have `hasDynamicOffset: true` and clears cached pipelines.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| draw\.draw\.target               | `Target \| DrawCallOptions`                                       |        ✖ | `{}`                                                               | One-shot draw options. Pass a bare target for the common case, or an options bag when setting counts or offsets.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| opts.target                      | `Target`                                                          |        ✖ | —                                                                  | Required at runtime when an options bag is used. Use an offscreen `Target`, or a `Surface` while a frame is active; outside a frame a surface throws `VGPU-SURFACE-NOT-IN-FRAME`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| opts.offsets                     | `readonly number[] \| Partial<Record<number, readonly number[]>>` |        ✖ | Reflected/claimed fallback offsets                                 | Dynamic offsets for claimed/dynamic groups. Array applies to every group; object keys by group.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| opts.instances                   | `number`                                                          |        ✖ | `DrawOptions.instances ?? geometry.instanceCount ?? 1`             | Per-call instance count; integer `>= 0`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| opts.vertices                    | `number`                                                          |        ✖ | `geometry.vertexCount ?? DrawOptions.vertices ?? 3`                | Per-call non-indexed vertex count; indexed geometries use `geometry.indexCount`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| opts.firstVertex                 | `number`                                                          |        ✖ | `0`                                                                | Non-indexed first vertex; indexed geometries use firstIndex/baseVertex `0`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| opts.firstInstance               | `number`                                                          |        ✖ | `DrawOptions.firstInstance ?? 0`                                   | Per-call first instance.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| opts.indirect                    | `StorageBuffer \| { buffer, offset? }`                            |        ✖ | `undefined`                                                        | GPU-driven draw: the GPU reads the draw arguments from the buffer at byte `offset` (default `0`) instead of CPU-side counts. Use it when a culling compute pass decides what to draw — the arguments are written on the GPU and the CPU never round-trips. Create the buffer with `storage(gpu, bytes, { indirect: true })`; argument layouts are in Notes.                                                                                                                                                                                                                                                                                                             |
| draw\.dispose                    | `() => void`                                                      |        ✖ | not called — a draw you stop referencing is collected without it   | Takes no arguments. Synchronous and idempotent; valid after `gpu.dispose()` or device loss. Retires the draw: every later member call throws `VGPU-DRAW-DISPOSED`, every managed `Bundle` that recorded it goes stale, and the draw releases its bindings, values, claimed groups, and cached bind groups. Never destroys borrowed resources or shared pipelines. See Disposal below.                                                                                                                                                                                                                                                                                   |

**`DepthOptions`** — the object form of `opts.depth`:

| Field          | Type                 | Required | Default        | Notes                                                                                                                                                                                                                                                            |
| -------------- | -------------------- | -------: | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| write          | `boolean`            |        ✖ | `true`         | `false` keeps testing against the depth buffer without writing it. Use it for blended transparents and decals, which must hide behind opaque geometry but not occlude what draws after them.                                                                     |
| compare        | `GPUCompareFunction` |        ✖ | `"less-equal"` | Comparison a fragment must pass against the stored depth. `"greater"` plus `clearDepth: 0` on the pass gives reversed-Z, which spreads floating-point precision evenly across the view distance.                                                                 |
| bias           | `number`             |        ✖ | `0`            | Constant offset added to each fragment's depth. Must be an integer (WebGPU `depthBias` is `i32`). A small positive bias while rendering the shadow map removes shadow acne; a small negative bias lets coplanar decals win the depth test instead of z-fighting. |
| biasSlopeScale | `number`             |        ✖ | `0`            | Extra bias proportional to the polygon's depth slope. Surfaces at glancing angles need more offset than facing ones — pair it with `bias` to remove acne on sloped ground.                                                                                       |
| biasClamp      | `number`             |        ✖ | `0` (no clamp) | Upper bound on the total bias. Caps runaway slope-scaled bias on near-edge-on triangles, which otherwise detaches shadows from their casters (peter panning).                                                                                                    |

**`StencilOptions`** — the fields of `opts.stencil`:

| Field     | Type                 | Required | Default                                              | Notes                                                                                                                                                                                                                        |
| --------- | -------------------- | -------: | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| front     | `StencilFaceOptions` |        ✖ | `{ compare: "always", fail/depthFail/pass: "keep" }` | Test and operations for front-facing triangles; fields are in the `StencilFaceOptions` table below.                                                                                                                          |
| back      | `StencilFaceOptions` |        ✖ | mirrors the normalized `front`                       | Give it explicitly when the two sides must differ — incrementing on front faces and decrementing on back faces to count volume crossings. With `back` given and `front` omitted, the front keeps the WebGPU face defaults.   |
| readMask  | `number`             |        ✖ | `0xFFFFFFFF`                                         | Bits of the stored stencil value visible to `compare`. Integer in `[0, 0xFFFFFFFF]`.                                                                                                                                         |
| writeMask | `number`             |        ✖ | `0xFFFFFFFF`                                         | Bits the face operations may change. Integer in `[0, 0xFFFFFFFF]`. Disjoint masks let several effects share one stencil buffer.                                                                                              |
| ref       | `number`             |        ✖ | pass default `0`                                     | Value `compare` tests against and `"replace"` writes. Integer in `[0, 0xFFFFFFFF]`. Encoder state, not pipeline state (see Notes); an explicit `0` still emits, restoring the pass default after an earlier draw changed it. |

**`StencilFaceOptions`** — the `front` / `back` faces:

| Field     | Type                  | Required | Default    | Notes                                                                                                                                                    |
| --------- | --------------------- | -------: | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| compare   | `GPUCompareFunction`  |        ✖ | `"always"` | Comparison between the masked `ref` and the masked stored value. `"equal"` draws only inside a previously marked region — the portal or mirror interior. |
| fail      | `GPUStencilOperation` |        ✖ | `"keep"`   | Operation when the stencil comparison fails.                                                                                                             |
| depthFail | `GPUStencilOperation` |        ✖ | `"keep"`   | Operation when the stencil comparison passes but the depth test fails.                                                                                   |
| pass      | `GPUStencilOperation` |        ✖ | `"keep"`   | Operation when both comparisons pass. `"replace"` writes `ref`, marking the region for later draws.                                                      |

**Returns:** `draw(gpu)` returns `Draw`; `set()`, `group()`, and `compileSync()` return the same `Draw`; `layout()` returns a `GPUBindGroupLayout`; one-shot `draw()` returns `void`; `compile()` returns `Promise<this>`; `dispose()` returns `void`.

**Throws:** one `VGPU-*` code per condition below. Checks marked † resolve against the target signature at compile/draw time; with `targets: [...]` they surface from `draw(gpu)` itself, because that option compiles at construction.

* `VGPU-LIMIT-STORAGE-VERTEX` / `VGPU-LIMIT-STORAGE-FRAGMENT` — static storage-buffer use by a selected entry point exceeds the granted stage limit. Request the supported `requiredLimits` value, or reduce/move the storage data.
* `VGPU-TARGET-REQUIRED` — `draw.draw()` was called without a target and the draw has none to fall back on. Pass a `Target`, or an options bag with `target`.
* `VGPU-SURFACE-NOT-IN-FRAME` — one-shot `draw.draw()` targets a `Surface` while no frame is active. Encode surface draws inside `frame(gpu, ...)`; `compile(surface)` and `bundle(gpu, { target: surface }, ...)` can prepare outside a frame.
* `VGPU-SURFACE-DISPOSED` — `compile()`, `compileSync()`, or `targets: [...]` received a disposed `Surface`. `compile()` throws synchronously instead of returning a rejected promise. Prepare against a live surface.
* `VGPU-BLEND-INVALID` — unknown blend preset or malformed blend object. Use `"alpha"`, `"additive"`, `"premultiplied"`, or `{ color: { src, dst, op? }, alpha? }`.
* `VGPU-BLEND-CONSTANT-INVALID` — `blendConstant` is not exactly four finite numbers, or no color target's effective blend uses a `"constant"`/`"one-minus-constant"` factor (the value could never apply). The effective blend of a target is its `colors[i].blend` when it has one, else the top-level `blend` — so a top-level constant factor overridden on *every* target is still dead, while a constant factor reached only through `colors[i].blend` is live. Fix the tuple, or add a constant factor to a blend that survives the per-target overrides.
* `VGPU-WRITEMASK-INVALID` — `writeMask` is not an array, or contains a channel outside `"r"`/`"g"`/`"b"`/`"a"`.
* `VGPU-COLORS-INVALID` — `colors` is not an array; an entry is neither `null` nor `{ blend?, writeMask? }`; or † its length differs from the target's color attachment count (both counts are in the message). Give one entry per attachment.
* `VGPU-CULL-INVALID` — `cull` is outside `"none"`/`"front"`/`"back"`.
* `VGPU-FRONTFACE-INVALID` — `frontFace` is outside `"ccw"`/`"cw"`.
* `VGPU-UNCLIPPED-DEPTH-INVALID` — `unclippedDepth` is not a boolean, or is `true` on a device whose `features` lacks `"depth-clip-control"`. Request the feature with `init({ requiredFeatures: ["depth-clip-control"] })` on an adapter that supports it.
* `VGPU-DEPTH-INVALID` — non-boolean `write`; unknown `compare`; non-integer `bias`; non-finite bias values; a nonzero bias value with a `line-*`/`point-*` topology (depth bias is only defined for triangles); or a nonzero `biasClamp` on a compatibility-mode device. Zero the offending field.
* `VGPU-STENCIL-INVALID` — malformed `stencil` (non-object value, malformed `front`/`back` face, unknown `compare` or `fail`/`depthFail`/`pass` operation, or `readMask`/`writeMask`/`ref` outside integer `[0, 0xFFFFFFFF]`); or † any stencil state against a depth format without a stencil aspect. Create the target with `depth: "depth24plus-stencil8"`.
* `VGPU-MULTISAMPLE-INVALID` — malformed `multisample` (non-object value, non-boolean `alphaToCoverage`, or a `mask` outside integer `[0, 0xFFFFFFFF]`); or † `alphaToCoverage: true` against a non-MSAA signature. Create the target with `msaa: true`.
* `VGPU-CONSTANTS-INVALID` — non-object `constants`; a key that matches no override in the shader (the message lists the available ones); a value that is neither a finite number nor a boolean; or an override declared without a default that `constants` does not provide. Add `constants: { "<nameOrId>": value }`.
* `VGPU-ENTRY-INVALID` — non-object `entry` or a non-string `vertex`/`fragment` field; a name that matches no entry point; or a name whose entry point has the wrong stage. The message lists the shader's entry points with their stages.
* `VGPU-R1-DRAW-COUNT` — a count field is not an integer `>= 0`. Use `0` only for a deliberate no-op draw.
* `VGPU-INDIRECT-INVALID` — at call time: `indirect` is neither a `StorageBuffer` nor `{ buffer, offset? }`; the buffer was created without the indirect flag (use `storage(gpu, bytes, { indirect: true })`); `offset` is not a non-negative integer multiple of 4; the arguments overrun the buffer (the message shows the byte math); or `indirect` is combined with `vertices`/`indices`/`instances`/`firstVertex`/`firstIndex`/`baseVertex`/`firstInstance` — the GPU reads those from the buffer, so drop the CPU-side value.
* `VGPU-R1-BINDING-NEVER-SET` — a reflected binding was never provided before drawing. `set()` the named binding, or claim its group with `group(n, bindGroup)`.
* `VGPU-R1-OWNERSHIP-FLIP` — a binding switched between JS-value ownership and resource ownership across `set()` calls. Keep passing the kind its first `set()` used.
* `VGPU-R1-BINDING-INCOMPATIBLE-RESOURCE` — a `set()` value does not satisfy the binding; `where` is `set`, and the message names the binding, its group and binding number, and what it needs. Tracked `Buffer`, Uniform-like, and provider bindings keep their synchronous native-usage validation and now also get checkable range validation at `set()`; previously native-only reflected-minimum, granted-maximum, and storage-size failures are synchronous. For a raw `GPUBuffer`/`GPUBufferBinding` this covers every range fact vgpu can check: a missing `uniform`/`storage` usage; an `offset` or `size` that is not a non-negative safe integer (`null` and numeric strings are rejected; only `undefined` takes the default); a zero `size`, including the default when `offset` equals `buffer.size`; a range past the end of the buffer; an `offset` that is not a multiple of `gpu.gpu.limits.minUniformBufferOffsetAlignment` (uniform) or `minStorageBufferOffsetAlignment` (storage); a range smaller than the WGSL type needs; a range larger than `maxUniformBufferBindingSize`/`maxStorageBufferBindingSize`; or a storage `size` that is not a multiple of 4. Raw-range `fix` names the required usage and a valid aligned offset/size; a tracked usage failure retains vgpu's `usage: ['uniform'|'storage','copy_dst']` vocabulary. The candidate is rejected before it replaces the binding's previous value.
* `VGPU-R1-BINDING-DESTROYED` — `set()` received an already-destroyed tracked resource (a `Buffer`, `Uniform`, `uniforms()` block, `Texture`, or `Target`), or an active binding's tracked resource was destroyed before the draw used it. `where` is `<label>.<binding>`; detail names the binding and resource. Bind a live replacement with `set()` and re-record bundles that captured the old resource. Direct operations on a destroyed `Buffer` itself, such as `write()` or `read()`, still report `VGPU-BUFFER-DISPOSED`; only the binding boundary uses this code. Raw `GPUBuffer` values are not tracked, so a destroyed raw buffer is reported by native WebGPU validation instead.
* `VGPU-SURFACE-NOT-BINDABLE` — a `Surface` was passed as a binding value, in `opts.set` or a later `set()`, inside or outside a frame. `where` is `<label>.<binding>`. vgpu throws before reading the surface's `color`/`colors`/`depth` or acquiring a canvas texture, and the rejected binding keeps its previous value. `set()` applies keys in order, so keys before the rejected one in the same call are already applied. Render to an offscreen target and bind that target or its texture; use the `Surface` only as a render destination.
* `VGPU-SET-VALUE-INVALID` — a JS-owned buffer binding has a missing or unknown struct member, the wrong vector/matrix/array extent, an out-of-range integer, or an invalid runtime-array extent. Structured detail identifies the complete value path and reason. The rejected value does not change that binding's retained host state or packed GPU bytes.
* `VGPU-SET-TEXTURE-FILTERABILITY` — a facade texture format cannot satisfy an ordinarily sampled `float` binding (detail identifies the format, texture, and paired sampler). Use a filterable format, request `float32-filterable`, or rewrite to `textureLoad`.
* `VGPU-R4-GROUP-CLAIMED` — `set()` tried to update a claimed group. Call `set()` before claiming, or keep updating the group yourself from `draw.layout(n)`.
* `VGPU-R4-GROUP-INCOMPATIBLE` — a claimed bind group does not match the draw's layout. Build it from `draw.layout(n, { dynamicOffsets? })` before calling `group(n, bindGroup)`.
* `VGPU-R4-GROUP-VALIDATION` — WebGPU rejected a claimed group at draw time; delivered asynchronously through `gpu.onError`. Build the group from `draw.layout(n)` and pass offsets via the draw call.
* `VGPU-SHADER-SOURCE-UNPREPARED` — `shader` is a raw WGSL string or a `version: 1` artifact. Import the `.wgsl` file through a compatible `@vgpu/wgsl` loader, rebuild prebuilt assets, or wrap the source: `shader: prepareShader(wgsl)` from `@vgpu/wgsl/prepare`.
* `VGPU-SHADER-SOURCE-VERSION` — `shader.version` is an integer other than `2`; the message names the received version, the supported version, and the artifact's `producer`. Align the `@vgpu/wgsl` tooling and `vgpu` runtime versions, then regenerate the artifact.
* `VGPU-SHADER-SOURCE-INVALID` — `shader` is not an object; `version` is missing or not an integer; a required field is missing, accessor-backed, or malformed; the reflection metadata is inconsistent (dangling binding or sampler references, duplicate bindings or entry points, layouts whose offsets, alignment, stride, or size disagree); or `sourceChecksum` does not match `wgsl`. Structured detail gives the field `path` and the `reason`. Regenerate the artifact with a supported producer instead of editing its `reflection`.
* `VGPU-DRAW-DISPOSED` — any member other than `dispose()` was used after `dispose()`: `set()`, `group()`, `layout()`, one-shot `draw()`, `compile()`, `compileSync()`, the `gpu` and `targets` getters, `currentFrame.pass(target, draw)`, `FramePass.draw(drawable)`, or `BundleRecorder.draw(drawable)`. The message is `Draw '<label>' has been disposed.`, `where` is `<label>.<operation>`, and `detail` is `{ label }`. The check runs before this draw's argument, target, binding, and device checks, so a disposed draw always reports this code; frame and pass errors, such as using an ended pass, keep their own precedence. `compile()` throws synchronously when the draw is already disposed, and a `compile()` still pending at `dispose()` rejects with this code once its preparation settles. Create a new `draw(gpu, ...)`; a disposed draw cannot be reused.

The three `VGPU-SHADER-SOURCE-*` errors throw synchronously from `draw(gpu)`, before any other draw option is validated.

## Examples

Static shaders live in `.wgsl` files. The `@vgpu/wgsl` Vite/webpack loader prepares them at build time, so the import is already a `ShaderSource`:

```wgsl
// triangle.wgsl
@vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
  var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
  return vec4f(p[vi], 0, 1);
}
@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0, 1, 0, 1); }
```

```ts
import { init, draw, target } from "vgpu/mock";
import triangleShader from "./triangle.wgsl";

const gpu = await init();
const colorTarget = target(gpu, { size: [64, 64] });
const tri = draw(gpu, {
  label: "tri",
  targets: [colorTarget],
  shader: triangleShader, // prepared by the loader; no WGSL parsing at runtime
});

tri.draw({ target: colorTarget, vertices: 3, instances: 1 });
```

The remaining examples keep the WGSL inline and wrap it in `prepareShader()` from `@vgpu/wgsl/prepare` so the source stays visible. Preparing in browser code bundles the WGSL parser; use it for WGSL you build at runtime, and prefer `.wgsl` imports for static shaders.

Backface culling for a closed imported geometry:

```ts
import { init, draw, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [256, 256], depth: true });
const statue = { vertexCount: 36 }; // closed geometry; vertex data omitted for brevity
const opaque = draw(gpu, {
  shader: prepareShader(`
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi % 3u], 0, 1);
    }
    @fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.8, 0.8, 0.7, 1); }
  `),
  geometry: statue,
  cull: "back",    // closed geometry: faces pointing away are never visible
  frontFace: "cw", // the importer produced clockwise triangles
});
opaque.draw(scene);
```

Culling back faces skips roughly half the fragment work on the closed statue, and `frontFace: "cw"` keeps the imported clockwise winding — or a negative-scale mirror — counting as front-facing.

Shadow map with depth bias and pancaking:

```ts
import { init, createMockAdapter, draw, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init({
  adapter: createMockAdapter({ features: ["depth-clip-control"] }),
  requiredFeatures: ["depth-clip-control"],
});
const shadowMap = target(gpu, { size: [1024, 1024], depth: true });
const casters = draw(gpu, {
  shader: prepareShader(`
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0, 1);
    }
    @fragment fn fs_main() -> @location(0) vec4f { return vec4f(0); }
  `),
  // Nudge stored depth away from the light to stop shadow acne.
  depth: { bias: 2, biasSlopeScale: 2 },
  // Pancake casters behind the light's near plane instead of clipping them away.
  unclippedDepth: true,
});
casters.draw(shadowMap);
```

The bias pair keeps lit surfaces acne-free, and `unclippedDepth` flattens casters between the light and its near plane onto the map instead of losing their shadows.

MRT decal into a G-buffer:

```ts
import { init, draw, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
// Deferred-shading G-buffer: albedo + world-space normals.
const gbuffer = target(gpu, {
  size: [512, 512],
  colors: [{ format: "rgba8unorm" }, { format: "rgba16float" }],
  depth: true,
});
const decal = draw(gpu, {
  shader: prepareShader(`
    struct Frag { @location(0) albedo: vec4f, @location(1) normal: vec4f }
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0, 1);
    }
    @fragment fn fs_main() -> Frag { return Frag(vec4f(0.6, 0.1, 0.1, 0.8), vec4f(0, 1, 0, 0)); }
  `),
  colors: [
    { blend: "alpha" },   // blend the decal into the albedo
    { writeMask: [] },    // leave the normals untouched
  ],
  depth: { write: false }, // the decal sits on existing geometry
});
decal.draw(gbuffer);
```

One draw blends the decal into `gbuffer.colors[0]` while `{ writeMask: [] }` leaves the normals exactly as the opaque pass wrote them — the fragment still outputs `@location(1)`, the mask only blocks the write.

Alpha-tested foliage without transparency sorting:

```ts
import { init, draw, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [256, 256], depth: true, msaa: true });
const foliage = draw(gpu, {
  shader: prepareShader(`
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0, 1);
    }
    // In a real scene, alpha comes from the leaf texture.
    @fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.1, 0.5, 0.1, 0.4); }
  `),
  multisample: { alphaToCoverage: true },
});
foliage.draw(scene);
```

Fragment alpha becomes per-sample coverage, so leaf edges antialias in any draw order — no blending, no transparency sorting.

Stencil-masked portal:

```ts
import { init, draw, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [256, 256], depth: "depth24plus-stencil8" });
// Prepare once, reuse the artifact for both draws.
const SHADER = prepareShader(`
  @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
    var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
    return vec4f(p[vi], 0, 1);
  }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.2, 0.2, 1, 1); }
`);
// Mark the portal's pixels with stencil value 1; write no color, no depth.
const portalMask = draw(gpu, { shader: SHADER, writeMask: [], depth: false, stencil: { front: { pass: "replace" }, ref: 1 } });
// Draw the far world only where the mask matches.
const otherWorld = draw(gpu, { shader: SHADER, stencil: { front: { compare: "equal" }, ref: 1 } });

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: scene }, (pass) => {
    pass.draw(portalMask);
    pass.draw(otherWorld);
  });
});
```

The first draw marks the portal region in the stencil buffer; the second renders only where the stored value equals `ref`, inside one pass so the mask survives.

Per-draw layer fade with the blend constant:

```ts
import { init, draw, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [128, 128] });
const overlay = draw(gpu, {
  shader: prepareShader(`
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0, 1);
    }
    @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1, 0.5, 0, 1); }
  `),
  // Weight the whole layer by the blend constant, not per-vertex alpha.
  blend: { color: { src: "constant", dst: "one-minus-constant" } },
  blendConstant: [0.25, 0.25, 0.25, 0.25], // the layer shows at 25%
});
overlay.draw(colorTarget);
```

The whole overlay fades with one per-draw value — no per-vertex alpha rewrite, and no extra pipeline, because the constant is encoder state.

Pipeline specialization with `constants` and `entry`:

```ts
import { init, draw, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [128, 128] });
// One module, two fragment variants sharing the vertex stage and helpers.
const SOURCE = prepareShader(`
  override STEPS: u32 = 8;
  @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
    var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
    return vec4f(p[vi], 0, 1);
  }
  @fragment fn fs_shaded() -> @location(0) vec4f { return vec4f(f32(STEPS) / 64.0, 0, 0, 1); }
  @fragment fn fs_flat() -> @location(0) vec4f { return vec4f(0.5, 0.5, 0.5, 1); }
`);
const hero = draw(gpu, { shader: SOURCE, constants: { STEPS: 64 } });        // high quality tier
const backdrop = draw(gpu, { shader: SOURCE, entry: { fragment: "fs_flat" } }); // cheap variant

hero.draw(colorTarget);
backdrop.draw(colorTarget);
```

Both draws compile from the same module: `constants` specializes the shaded variant at pipeline creation instead of string-templating WGSL, and `entry` picks the flat fragment for the backdrop.

GPU-driven draw with `indirect`:

```ts
import { init, compute, draw, storage, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [256, 256], depth: true });
// drawIndirect arguments: vertexCount, instanceCount, firstVertex, firstInstance.
const args = storage(gpu, 16, { indirect: true });
const cullPass = compute(gpu, prepareShader(`
  @group(0) @binding(0) var<storage, read_write> args: array<u32, 4>;
  @compute @workgroup_size(1) fn cs_main() {
    args = array<u32, 4>(3u, 1u, 0u, 0u); // survivors of the culling test
  }
`));
cullPass.set({ args });
const grass = draw(gpu, {
  shader: prepareShader(`
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0, 1);
    }
    @fragment fn fs_main() -> @location(0) vec4f { return vec4f(0, 0.6, 0, 1); }
  `),
});
cullPass.dispatch(1);                          // the GPU decides the counts
grass.draw({ target: scene, indirect: args }); // the CPU never reads them back
```

The compute pass writes the draw arguments and the draw consumes them on the GPU — the culling result never round-trips through the CPU.

## Pipeline pre-warm

`draw.compile(target)` asynchronously prepares one target signature and resolves to the same draw. `draw.compileSync(target)` prepares the same signature synchronously; if an async compile for that signature is still pending, the synchronous result wins the race and unblocks later draws. Both methods also accept a target signature object such as `{ colors: ["bgra8unorm"], depth: "depth24plus", sampleCount: 4 }`; `colors` is required and bare strings are rejected.

Pass a live `Surface` to prepare for a canvas during loading. Preparation reads the surface's configured signature — `format`, resolved depth format, and sample count — and does not acquire the canvas texture, resize the canvas, or submit work, so it runs outside any frame:

```wgsl
// prewarm-triangle.wgsl
@vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
  var p = array<vec2f, 3>(vec2f(-0.5, -0.5), vec2f(0.5, -0.5), vec2f(0.0, 0.5));
  return vec4f(p[vi], 0, 1);
}

@fragment fn fs_main() -> @location(0) vec4f {
  return vec4f(1, 0.4, 0.2, 1);
}
```

```ts
import { init, draw, frameLoop, surface } from "vgpu";
import triangleShader from "./prewarm-triangle.wgsl";

const gpu = await init();
const canvasSurface = surface(gpu, document.querySelector("canvas")!);

// ---cut---
const tri = draw(gpu, {
  shader: triangleShader,
});
await tri.compile(canvasSurface); // outside a frame: no canvas texture is acquired

frameLoop(gpu, (currentFrame) => {
  currentFrame.pass(canvasSurface, (pass) => pass.draw(tri)); // rendering stays inside the frame
});
```

The default surface shown above and the equivalent signature `{ colors: [canvasSurface.format] }` share one cached pipeline, and a size-only resize keeps it valid. A surface with `depth` or `msaa` needs the matching `depth` and `sampleCount` in that signature. Prefer `compile(surface)` once the surface exists; use the explicit signature for preparation before it does.

Each color/depth/sample-count variant is a different pipeline. A missed variant sync-compiles on first use, which can jank; fire-and-forget pre-warms should always use `.catch(...)` or `gpu.onError`/`gpu.settled()` will not observe the returned promise rejection. `targets: [target]` is kept as creation-time `compileSync()` sugar for non-browser hot paths.

## Disposal

`dispose()` is optional. A draw you stop referencing is collected eventually, like any JavaScript object, and its bundles keep replaying. Call `dispose()` when you want to retire a draw at a known point: it stops every later call, stales the managed bundles that recorded it, and releases the draw's bindings, values, claimed groups, and cached bind groups synchronously. It is idempotent and needs no live device, so it is safe to call after `gpu.dispose()` or device loss.

```ts
import { init, draw, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const sceneTarget = target(gpu, { size: [64, 64] });

// ---cut---
const marker = draw(gpu, {
  label: "marker",
  shader: prepareShader(`
    struct Params { tint: vec4f }
    @group(0) @binding(0) var<uniform> params: Params;
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0, 1);
    }
    @fragment fn fs_main() -> @location(0) vec4f { return params.tint; }
  `),
  set: { params: { tint: [1, 0, 0, 1] } },
});

const pending = frame(gpu); // manual frame: nothing submits until submit()
pending.pass(sceneTarget, (pass) => pass.draw(marker)); // captures the red tint now
marker.dispose(); // retire the draw before the frame submits
pending.submit(); // still draws red: encoded work keeps its captured values
await pending.done;

marker.dispose(); // no-op: dispose() is idempotent
// marker.set(...), marker.draw(...), and marker.gpu now throw VGPU-DRAW-DISPOSED
```

Disposal retires the facade, not the work it already handed to WebGPU. A frame pass that drew the draw before `dispose()` still submits with the uniform values captured when it was encoded, and canceling that frame still discards it.

What disposal releases and what it leaves alone:

* **Borrowed resources stay yours.** Textures, buffers, targets, geometry, `uniforms()` blocks, samplers, and bind groups passed to `group(n, bindGroup)` are never destroyed. Pipelines, shader modules, and layouts live in device-wide stores, so another draw built from the same shader keeps using its compiled pipeline.
* **Managed bundles go stale.** `FramePass.bundles()` throws `VGPU-R3-BUNDLE-STALE` with `Bundle '<id>' is stale: draw '<label>' was disposed. Create a new draw/effect and re-record the bundle.` for every bundle that recorded the draw, including a bundle still recording when `dispose()` runs. Dropping the draw without disposing it does not stale its bundles.
* **Native handles keep their own lifetime.** A `GPURenderBundle` read from `bundle.gpu` keeps replaying the last uniform contents the draw wrote; `set()` updates stop because `set()` now throws. vgpu cannot revoke that handle or revalidate already encoded commands.
* **Memory is not reclaimed on a schedule.** A private uniform buffer that native work might still reference is released by reference rather than destroyed, so its memory returns when native WebGPU drops it. Neither collection nor `dispose()` promises when the GPU or driver frees memory.

A `compile()` still pending when you call `dispose()` is not canceled. It settles with its underlying preparation, then rejects with `VGPU-DRAW-DISPOSED` at `<label>.compile`, whether native compilation succeeded or failed. The shared pipeline is not poisoned: another live draw compiling the same shader and signature resolves normally and keeps the pipeline. The disposed draw's rejection belongs to its promise only — it is not delivered again through `gpu.onError`, so handle it with `.catch(...)` like any compile.

## Raw buffers and byte ranges

Bind a raw `GPUBuffer` you created on `gpu.gpu` (the shared `GPUDevice`) when you manage its memory yourself — one allocation holding several uniform blocks, or a buffer another library owns. `set()` recognizes a raw buffer or a `GPUBufferBinding` (`{ buffer, offset?, size? }`) in a reflected uniform/storage slot by its shape, before it considers packing the value, so an ordinary WGSL struct with members named `buffer`, `offset`, or `size` still packs as data:

```ts
import { init, draw, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const sceneTarget = target(gpu, { size: [64, 64] });

// ---cut---
const UNIFORM = 0x40; // GPUBufferUsage.UNIFORM — WebGPU fixes the flag values; Node has no global
const COPY_DST = 0x08; // GPUBufferUsage.COPY_DST
const TINT_BYTES = 16; // struct Tint { color: vec4f }
const alignment = gpu.gpu.limits.minUniformBufferOffsetAlignment; // the granted limit — never assume 256
const coolOffset = Math.ceil(TINT_BYTES / alignment) * alignment; // first aligned offset after the warm tint

const palette = gpu.gpu.createBuffer({ label: "palette", size: coolOffset + TINT_BYTES, usage: UNIFORM | COPY_DST });
gpu.gpu.queue.writeBuffer(palette, 0, new Float32Array([1, 0.4, 0.2, 1])); // warm tint
gpu.gpu.queue.writeBuffer(palette, coolOffset, new Float32Array([0.2, 0.5, 1, 1])); // cool tint

const stripeShader = prepareShader(`
  struct Tint { color: vec4f }
  struct Stripe { offset: f32, size: f32, buffer: f32 } // plain data that shares member names with a buffer binding
  @group(0) @binding(0) var<uniform> tint: Tint;
  @group(0) @binding(1) var<uniform> stripe: Stripe;

  @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
    var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
    return vec4f(p[vi], 0, 1);
  }
  @fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {
    let gap = abs(position.y - stripe.offset);
    let coverage = 1.0 - smoothstep(stripe.size, stripe.size + stripe.buffer, gap);
    return vec4f(tint.color.rgb, coverage);
  }
`);

const coolRange: GPUBufferBinding = { buffer: palette, offset: coolOffset }; // size defaults to the remaining 16 bytes
const warmStripe = draw(gpu, {
  label: "warm-stripe",
  shader: stripeShader,
  blend: "alpha",
  set: {
    tint: { buffer: palette, size: TINT_BYTES }, // raw range; offset defaults to 0
    stripe: { offset: 20, size: 6, buffer: 4 }, // numbers, so this packs like any struct
  },
});
const coolStripe = draw(gpu, {
  label: "cool-stripe",
  shader: stripeShader,
  blend: "alpha",
  set: { tint: coolRange, stripe: { offset: 44, size: 6, buffer: 4 } },
});

coolRange.offset = 0; // no effect: set() copied { buffer, offset, size } when it ran

const rendered = frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: sceneTarget, clear: [0, 0, 0, 1] }, (pass) => {
    pass.draw(warmStripe); // reads palette bytes [0, 16)
    pass.draw(coolStripe); // reads palette bytes [coolOffset, coolOffset + 16)
  });
});
await rendered.done;
palette.destroy(); // the raw buffer is yours: vgpu never destroys it
```

Both draws read one allocation through different aligned ranges, while `stripe` packs as an ordinary uniform because its `buffer` member is a number, not a buffer. Mutating `coolRange` after `set()` changes nothing; call `coolStripe.set({ tint: { buffer: palette, offset: 0, size: TINT_BYTES } })` to bind a different range.

The rules for raw buffer bindings:

* **Defaults apply only to `undefined`.** An omitted `offset` is `0`; an omitted `size` is `buffer.size - offset`. A bare `GPUBuffer` binds the whole buffer. `null` or a numeric string is rejected, not defaulted.
* **Equivalent spellings are one binding.** `buffer`, `{ buffer }`, `{ buffer, offset: 0 }`, and `{ buffer, offset: 0, size: buffer.size }` normalize to the same `{ buffer, offset, size }` and share one bind group. Another offset or size creates a new bind group, and a `Bundle` recorded with the old range throws `VGPU-R3-BUNDLE-STALE` until you re-record it.
* **The range is snapshotted on `set()`.** vgpu stores its own `{ buffer, offset, size }` copy, so mutating your descriptor object has no effect until you pass it to `set()` again.
* **Ranges are checked at `set()`.** Usage, bounds, offset alignment against the granted `gpu.gpu.limits`, the WGSL type's minimum size, the granted maximum binding size, and the storage multiple-of-4 rule throw `VGPU-R1-BINDING-INCOMPATIBLE-RESOURCE` with a fix (see **Throws**). A rejected range leaves the binding's previous value in place.
* **The buffer stays caller-managed.** vgpu neither tracks nor destroys a raw buffer, and `dispose()` leaves it alone. Only what vgpu cannot see is left to native WebGPU validation when the work runs: a destroyed or mapped buffer, or one created on another device.
* **Contents are live.** vgpu never packs, captures, or uploads a raw range, unlike managed uniform values captured per frame: work reads whatever the buffer holds when the GPU executes it, so `queue.writeBuffer` updates reach later submissions and saved bundles.
* **Ownership follows the first `set()`.** A raw buffer or range is resource ownership; switching that binding to a JS value later throws `VGPU-R1-OWNERSHIP-FLIP`, and the reverse does too.

## Notes

* `draw(gpu)` never parses WGSL: it validates the prepared artifact and reads its `reflection`, so draws built from loader-imported or prebuilt shaders keep the WGSL parser out of your bundle. `prepareShader()` runs the parser wherever you call it — prepare once per source revision, outside `frame(gpu)` and `frameLoop(gpu)` callbacks, and pass the same artifact to every draw built from that source.
* An artifact with deeply frozen consumed data (every loader import and `prepareShader()` result) is validated once and reused by later `draw`/`effect`/`compute` calls; mutable ones are revalidated each call; changed source needs a new artifact (`ShaderSource`). Unknown extra fields are ignored. `sourceChecksum` only detects a `wgsl` string replaced after preparation; it does not prove `reflection` matches the WGSL, so regenerate artifacts whenever the source or the `@vgpu/wgsl` tooling changes.
* Choose blend by use case: omit it for opaque geometry; use `"alpha"`/`"premultiplied"` for ordinary composition and `"additive"` for glow. Reserve explicit equations for special effects. `blendConstant` is persistent pass state (not pipeline state and not bundle state), so set it when fading or crossfading a layer.
* For MRT, use `colors[i]` to inherit or override blend/write masks per attachment. Use `cull: "back"` on closed geometries, `"none"` on foliage/cards, and `"front"` for shadow passes; pair negative scales with `frontFace: "cw"`. Disable depth for overlays and depth writes for transparent/decals. Stencil needs a depth-stencil target; `multisample.alphaToCoverage` is for alpha-tested foliage with MSAA, not general blending.
* Use indirect draws when compute produces arguments in storage buffers marked `{ indirect: true }`; this avoids CPU readback and keeps culling GPU-driven.
* Count precedence is per-call option, then draw option, then geometry/default. `instances: 0` and `vertices: 0` are valid no-op draws.
* Blend, write masks, `colors`, `cull`, `frontFace`, `unclippedDepth`, `depth`, `stencil` (all but `ref`), `multisample`, `constants`, and `entry` are immutable pipeline state, fixed at `draw(gpu)`; draws that differ in any of them compile distinct pipelines. Absent options and their explicit no-op spellings — `unclippedDepth: false`, `multisample: {}`, `constants: {}`, an all-defaults `stencil`, `entry` naming the same functions selected by default — keep byte-identical descriptors and cache keys.
* WebGPU mapping: `cull`/`frontFace`/`unclippedDepth` → `GPUPrimitiveState`; `depth` → `GPUDepthStencilState` (`write` → `depthWriteEnabled`, `compare` → `depthCompare`, the bias family → `depthBias`/`depthBiasSlopeScale`/`depthBiasClamp`); `stencil` → its stencil members (`fail` → `failOp`, `depthFail` → `depthFailOp`, `pass` → `passOp`); `multisample` → `GPUMultisampleState`, with the sample `count` always taken from the target's `sampleCount`; `constants` → `GPUProgrammableStage.constants` on both stages.
* `depth: false` compiles `{ depthWriteEnabled: false, depthCompare: "always" }` because WebGPU cannot omit depth state when the pass has a depth attachment. `stencil` merges into the same depth-stencil state; stencil without a `depth` option keeps the depth defaults.
* `unclippedDepth` disables clipping only; fragment depth is still clamped to the viewport `[minDepth, maxDepth]` range at output.
* With `alphaToCoverage` on, WebGPU additionally requires the first color target to be blendable with an alpha channel and forbids a fragment `sample_mask` output; native validation reports those.
* WebGPU matches `constants` keys against the module's override declarations, not per entry point, so one record serves both stages even when an override is referenced by only one of them.
* `entry` selection happens at construction: binding visibility, bind group layouts, vertex input layouts (the selected vertex entry's inputs drive geometry attribute matching), and storage-stage limit checks all reflect the chosen variant. Unused declarations keep visibility `0` in reflected layouts, so build claimed bind groups from `draw.layout(n)` rather than guessing a raw layout.
* `blendConstant` and `stencil.ref` are encoder state: emitted as `setBlendConstant`/`setStencilReference` after `setPipeline` and before the draw, so draws that differ only in them share pipelines. Both are *pass* state and persist: a value set by one draw stays in effect for every later draw in the same pass that does not set its own. The `(0, 0, 0, 0)` blend-constant default therefore only holds until the first draw in the pass sets one — pass `blendConstant` explicitly on any draw in a pass that must not inherit a previous draw's value (`stencil.ref` behaves the same, and an explicit `0` re-emits). Render bundle encoders cannot set render-pass state, so `bundle()` rejects such draws with `VGPU-BUNDLE-BLEND-CONSTANT`/`VGPU-BUNDLE-STENCIL-REF`; encode them in a frame pass instead.
* Blend presets: `"alpha"` uses source alpha over, `"premultiplied"` uses premultiplied source over, and `"additive"` uses one-plus-one additive blending for color and alpha. In explicit blends, `op` defaults to `"add"` and omitted `alpha` copies `color`.
* `indirect` argument layouts: a non-indexed geometry (or no geometry) encodes `drawIndirect` — 4 u32 values, `vertexCount, instanceCount, firstVertex, firstInstance` (16 bytes); an indexed geometry still sets its index buffer and encodes `drawIndexedIndirect` — 5 32-bit values, `indexCount, instanceCount, firstIndex, baseVertex (signed), firstInstance` (20 bytes). Write them from a compute shader (bind the same buffer as storage) or from JS via `write()`. Indirect draws record fine into `bundle()`: `drawIndirect`/`drawIndexedIndirect` exist on render bundle encoders.
* A non-zero `firstInstance` inside the buffered indirect arguments silently turns the draw into a no-op unless the device has the `"indirect-first-instance"` feature. The value lives on the GPU, so vgpu cannot validate it — request the feature with `init({ requiredFeatures: ["indirect-first-instance"] })` when you need it.
* One-shot `draw.draw()` has no implicit target and returns `void`; raw claimed-group validation errors are delivered through `gpu.onError`, and tests can `await gpu.settled()`.
* `set()` binds a `Texture` or `Target` through views that binding normalization generates — the default view, a depth-only view for depth-stencil formats — and may reuse a compatible generated view across draws and rebinds. This is internal and has no controls. `Texture.createView(desc)` still returns a fresh view on every call.
* Changing resource identity after a draw is recorded in a `Bundle` marks that bundle stale; changing JS values in-place does not. `dispose()` marks every bundle that recorded the draw stale too; letting the draw be collected does not.
* Do not dispose a draw whose bundles you still replay through `FramePass.bundles()`. Create the replacement draw, record its bundle, swap your references, then dispose the old draw and bundle.
* Bind an offscreen `Target` (`set({ source: sceneTarget })`) when the draw should follow its attachment: after `sceneTarget.resize(...)`, the binding switches to the replacement texture. Bind a `Texture` (`set({ source: sceneTarget.color })`) to keep that exact texture and its lifetime; it does not follow resize, so rebind the replacement after `sceneTarget.resize(...)` — the released attachment fails at draw time. Do not bind a `Surface` — render into a `Target` and present it with a surface pass; see `Surface` for the full producer → present example.
* **See also:** `ShaderSource`, `prepareShader` (`@vgpu/wgsl/prepare`), `Effect`, `Compute`, `FramePass.draw`, `Bundle`, `Surface`, `Target`, `SharedUniforms`.

## Compilation validation and uniform capture

`compile()` waits for native validation even after `compileSync()` created a candidate or took over a pending asynchronous compile. Synchronous creation failures throw; asynchronous validation from synchronous preparation uses `gpu.onError`. A failed pipeline throws on automatic reuse; explicitly compile again to retry.

Direct frame draws capture managed uniform values when encoded, matching compute dispatches. Later `set()` calls — and `dispose()` — do not alter earlier commands. Storage bindings, raw/low-level buffers, claimed bind groups, and render bundles retain their live buffer contents.

Managed uniforms are JS values on a `var<uniform>` binding and `uniforms(gpu)` objects adopted as uniform. `set()` validates, packs and stores the CPU value on every call. Frame-only values upload through captured frame pages; one-shot draws upload pending values when used. When the packed bytes equal the previous ones (bitwise: an in-place typed-array change is detected, `+0` and `-0` differ), the update is not a new revision: later commands in the same frame reuse its snapshot, and a pending upload stays pending. You never need to compare values yourself; skipping a redundant `set()` saves only CPU work. Storage bindings and live uniforms (recorded into a bundle, or exposed through `.buffer`/`.gpu`) still write on every `set()`.

Captures live in pooled uniform pages. A page belongs to one frame until its GPU work completes or the frame is canceled, so frames in flight never share pages. Bind groups follow the physical page range, so frames that repeat the same draws in the same order reuse them; reordering or culling draws can create some again. Idle retention is bounded and `gpu.dispose()` frees the pages. Each frame still uploads its own captured pages.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Effect
description: Fullscreen-fragment render unit created by `effect(gpu)`. Use it for post-processing, gradients, blurs, and screen/target copies; use `draw(gpu)` for meshes, vertex buffers, instancing, or explicit vertex counts.
---

# Effect



## Import

```ts
import type { Effect, EffectOptions } from "vgpu";
```

## Signature

```ts
import type { DrawCallOptions, Target, TargetSignature } from "vgpu";

type SetBag = Record<string, unknown>;

type BlendPreset = "alpha" | "additive" | "premultiplied";
interface BlendComponentOptions { readonly src: GPUBlendFactor; readonly dst: GPUBlendFactor; readonly op?: GPUBlendOperation; }
interface BlendOptions { readonly color: BlendComponentOptions; readonly alpha?: BlendComponentOptions; }

interface EffectOptions {
  readonly set?: SetBag;
  readonly label?: string;
  readonly entry?: { readonly fragment?: string };
  readonly blend?: BlendPreset | BlendOptions;
  readonly writeMask?: readonly ("r" | "g" | "b" | "a")[];
}

interface Effect {
  readonly gpu: GPURenderPipeline | undefined;
  dispose(): void;
  set(values: SetBag): this;
  draw(target?: Target | DrawCallOptions): void;
  compile(target?: Target | TargetSignature): Promise<this>;
  compileSync(target?: Target | TargetSignature): this;
}
```

## Parameters

| Param               | Type                                                       | Required | Default                                                             | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ------------------- | ---------------------------------------------------------- | -------: | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| effect.source       | `ShaderSource`                                             |        ✔ | —                                                                   | Prepared `version: 2` artifact: a `.wgsl` import through the `@vgpu/wgsl` Vite/webpack loader, a prebuilt asset, or `prepareShader(wgsl)` from `@vgpu/wgsl/prepare`. Raw WGSL strings and `version: 1` artifacts are rejected. `effect(gpu)` keeps its own validated snapshot, so changing the artifact object afterwards does not affect an existing effect. Fragment selection prefers `fs_main` when several fragment entries exist, otherwise uses the first; a single entry can have any name. If the source declares no `@vertex` entry, vgpu pairs the fragment with a fixed fullscreen-triangle vertex stage that outputs `@location(0) uv`; if it declares one, that authored vertex stage is used instead. |
| effect.opts         | `EffectOptions`                                            |        ✖ | `{}`                                                                | Initial options. Passing a `geometry` property is rejected; effects have no vertex buffers.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| opts.set            | `Record<string, unknown>`                                  |        ✖ | `undefined`                                                         | Same as one initial `.set(opts.set)` call: establishes first-set binding ownership and validates reflected bindings.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| opts.label          | `string`                                                   |        ✖ | `"effect"`                                                          | Used in GPU object labels (shader modules and pipelines) and `VGPU-*` error `where` fields.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| opts.entry          | `{ fragment?: string }`                                    |        ✖ | `fs_main` when declared, otherwise first fragment                   | Constructor-only selection. An explicit name overrides the default and must identify a declared `@fragment`. Omission, `{}`, and `{ fragment: undefined }` use automatic selection. Vertex overrides are not supported.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| opts.blend          | `"alpha" \| "additive" \| "premultiplied" \| BlendOptions` |        ✖ | `undefined`                                                         | Constructor-only blend state passed through to the fullscreen draw. Presets and defaults match `DrawOptions.blend`; omitted explicit `alpha` copies `color`, and `op` defaults to `"add"`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| opts.writeMask      | `readonly ("r" \| "g" \| "b" \| "a")[]`                    |        ✖ | all channels                                                        | Constructor-only color channel mask. Omit for RGBA; `[]` writes no channels; `["r","g","b"]` skips alpha.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| effect.set.values   | `Record<string, unknown>`                                  |        ✔ | —                                                                   | Binding values by WGSL variable name. JS values are lib-owned; resources are user-owned. A raw `GPUBuffer` or `GPUBufferBinding` (`{ buffer, offset?, size? }`) in a uniform/storage slot binds that byte range as a caller-owned resource, with the same defaults, snapshot, and checks as [`Draw`](/docs/reference/vgpu/draw#draw) (see Notes). A `Target` follows its attachment across resizes; a `Texture` stays bound to that exact texture. A `Surface` is rejected in every slot with `VGPU-SURFACE-NOT-BINDABLE`.                                                                                                                                                                                           |
| effect.draw\.target | `Target \| DrawCallOptions`                                |        ✖ | `{}`                                                                | One-shot render pass. Pass a bare target for the common case, or an options bag when setting per-call draw options.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| opts.target         | `Target`                                                   |        ✖ | —                                                                   | Required at runtime when an options bag is used. Use an offscreen `Target`, or a `Surface` while a frame is active; outside a frame a surface throws `VGPU-SURFACE-NOT-IN-FRAME`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| effect.dispose      | `() => void`                                               |        ✖ | not called — an effect you stop referencing is collected without it | Takes no arguments. Synchronous and idempotent; valid after `gpu.dispose()` or device loss. Retires the effect and its one underlying draw: every later member call throws `VGPU-DRAW-DISPOSED`, every managed `Bundle` that recorded it goes stale, and its bindings, values, and cached bind groups are released. Never destroys borrowed resources or shared pipelines. See Disposal below.                                                                                                                                                                                                                                                                                                                       |

The `uv` varying that the fixed fullscreen stage outputs is top-origin: `(0, 0)` is the
top-left corner and `v` grows downward — the same convention as WebGPU texture
coordinates, `@builtin(position)`, and `target.color.read({ mipLevel: 0, region: "all" })`. Sampling any texture
with this `uv` needs no flip: a pass that samples `src` at `uv` reproduces the
image exactly. If you are porting a WebGL or Shadertoy shader that assumes
`v` grows upward, invert once at the boundary (`1.0 - uv.y`) and keep
everything else flip-free.

**Returns:** `effect(gpu)` returns `Effect`; `effect.set()` and `effect.compileSync()` return the same `Effect`; `effect.compile()` returns `Promise<this>`; `effect.draw()` returns `void` after starting a one-shot draw path; `effect.dispose()` returns `void`.

**Throws:** `VGPU-DRAW-DISPOSED` when any member other than `dispose()` is used after `dispose()` — `set()`, one-shot `draw()`, `compile()`, `compileSync()`, the `gpu` getter, `FramePass.draw(effect)`, the `currentFrame.pass(target, effect)` shorthand, or `BundleRecorder.draw(effect)`. An effect shares the draw error family: the message is `Draw '<label>' has been disposed.`, `where` is `<label>.<operation>`, and `detail` is `{ label }`, with the effect's label. The check runs before argument normalization and this effect's target, binding, and device checks; frame and pass errors keep their own precedence. `compile()` throws synchronously when already disposed, and a pending `compile()` rejects with this code once its preparation settles. Create a new `effect(gpu, ...)`; a disposed effect cannot be reused. `VGPU-ENTRY-INVALID` for malformed `entry`, a vertex override, or a fragment name that is not a string, does not exist, or belongs to another stage; `VGPU-TARGET-REQUIRED` when `effect.draw()` or compile pre-warm is called without `target`; `VGPU-SURFACE-NOT-IN-FRAME` when one-shot `effect.draw()` targets a `Surface` while no frame is active — encode surface draws inside `frame(gpu, ...)`, while `compile(surface)` and `bundle(gpu, { target: surface }, ...)` can prepare outside a frame; `VGPU-SURFACE-DISPOSED` when `compile()` or `compileSync()` receives a disposed `Surface` (`compile()` throws synchronously instead of rejecting) — prepare against a live surface; `VGPU-BLEND-INVALID` for an unknown blend preset or malformed blend object; `VGPU-WRITEMASK-INVALID` for a non-array or unknown write mask channel; `VGPU-RING1-UNSUPPORTED` when `effect(gpu)` receives mesh/vertex data; `VGPU-SHADER-SOURCE-UNPREPARED` when `source` is a raw WGSL string or a `version: 1` artifact (import the `.wgsl` file through a compatible `@vgpu/wgsl` loader, rebuild prebuilt assets, or pass `prepareShader(wgsl)` from `@vgpu/wgsl/prepare`); `VGPU-SHADER-SOURCE-VERSION` when `source.version` is an integer other than `2` (the message names the received version, the supported version, and the artifact's `producer`; align the `@vgpu/wgsl` tooling and `vgpu` runtime versions, then regenerate); `VGPU-SHADER-SOURCE-INVALID` when `source` is not an object, `version` is missing or not an integer, a required field is missing, accessor-backed, or malformed, the reflection metadata is inconsistent, or `sourceChecksum` does not match `wgsl` (structured detail gives the field `path` and the `reason`; regenerate the artifact with a supported producer); these three throw synchronously from `effect(gpu)`; `VGPU-SET-VALUE-INVALID` when a JS-owned binding has the wrong structure/vector/matrix/fixed-array shape or an out-of-range integer (structured detail contains `reason` and the complete `path`); `VGPU-R1-BINDING-NEVER-SET` when a reflected binding has no value at draw time; `VGPU-R1-OWNERSHIP-FLIP` when a binding switches between JS-value and resource ownership; `VGPU-R1-BINDING-INCOMPATIBLE-RESOURCE` at `set` when a resource does not satisfy the binding — tracked `Buffer`, Uniform-like, and provider bindings keep synchronous native-usage validation and now also receive checkable range validation there; previously native-only reflected-minimum, granted-maximum, and storage-size failures are synchronous; for a raw `GPUBuffer`/`GPUBufferBinding` this includes a missing `uniform`/`storage` usage, a non-integer, negative, `null`, or out-of-bounds `offset`/`size`, a zero size, an `offset` that is not a multiple of the granted `minUniformBufferOffsetAlignment`/`minStorageBufferOffsetAlignment`, a range smaller than the WGSL type or larger than the granted maximum binding size, and a storage size that is not a multiple of 4; the message names the binding, group, and binding number, raw-range `fix` gives the required usage and a valid aligned offset/size, and the previous value stays bound; `VGPU-R1-BINDING-DESTROYED` when `set()` receives an already-destroyed tracked `Buffer`, `Uniform`, `uniforms()` block, `Texture`, or `Target`, or an active tracked resource was destroyed before use — bind a live replacement and re-record bundles that captured it (direct operations on a destroyed `Buffer`, such as `write()`, still report `VGPU-BUFFER-DISPOSED`; a destroyed raw `GPUBuffer` is reported by native WebGPU validation instead); `VGPU-SET-TEXTURE-FILTERABILITY` when an ordinarily sampled facade texture is not filterable (structured detail names its format/binding and paired sampler; use a filterable format, request `float32-filterable`, or use `textureLoad` without a sampler); `VGPU-SURFACE-NOT-BINDABLE` when a `Surface` is passed as a binding value in `opts.set` or a later `set()`, inside or outside a frame — `where` is `<label>.<binding>`, vgpu throws before reading the surface's attachments or acquiring a canvas texture, and the rejected binding keeps its previous value (keys earlier in the same `set()` call are already applied); render to an offscreen target and bind that target or its texture, and use the `Surface` only as a render destination. Asynchronous draw validation errors are delivered through `gpu.onError`; tests can `await gpu.settled()`.

Managed uniform `set()` calls validate and pack on every call and always update the stored CPU value. Frame-only values upload through captured frame pages; one-shot draws upload pending values when used. When the newly packed bytes equal the previous bytes, the update is not a new revision, so later draws in the same frame reuse the snapshot already captured. Storage bindings and live uniforms (recorded into a bundle, or a `uniforms(gpu)` object whose `.buffer`/`.gpu` was accessed) still write on every `set()`.

## Examples

Static shaders live in `.wgsl` files. The `@vgpu/wgsl` Vite/webpack loader prepares them at build time, so the import is already a `ShaderSource`:

```wgsl
// wave.wgsl
struct Params { time: f32, speed: f32 }
@group(0) @binding(0) var<uniform> params: Params;

@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, sin(params.time * params.speed) * 0.5 + 0.5, 1);
}
```

```ts
import { init, clock, effect, frame, target } from "vgpu/mock";
import waveShader from "./wave.wgsl";

const gpu = await init();
const colorTarget = target(gpu, { size: [64, 64] });
const wave = effect(gpu, waveShader, { label: "wave", set: { params: { time: 0, speed: 2 } } });

wave.set({ params: { time: clock(gpu).time, speed: 2 } });
frame(gpu, (currentFrame) => currentFrame.pass(colorTarget, wave));
```

`wave.wgsl` declares only a fragment entry, so the effect runs it over the fixed fullscreen triangle and feeds it `@location(0) uv`.

For WGSL you build or receive at runtime, prepare it once with `prepareShader()` from `@vgpu/wgsl/prepare`. This bundles the WGSL parser into that consumer, so keep static shaders in `.wgsl` files:

```ts
import { init, effect, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [32, 32] });
const uvShader = prepareShader(`
  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return vec4f(uv.x, uv.y, 0.0, 1.0);
  }
`);
const uvGradient = effect(gpu, uvShader); // before: effect(gpu, wgslString)
uvGradient.draw(colorTarget);
```

Select an alternative fragment from the same module:

```ts
import { effect, frame, init, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const output = target(gpu, { size: [4, 4] });
const shader = prepareShader(`
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }
  @fragment fn mask() -> @location(0) vec4f { return vec4f(0, 0, 0, 1); }
`);
const mask = effect(gpu, shader, { entry: { fragment: "mask" } });
frame(gpu, f => f.pass(output, mask));
gpu.dispose();
```

## Pipeline pre-warm

Effects compile lazily for the target signature they draw into. Use `await effect.compile(target)` during loading to pre-warm without blocking, or `effect.compileSync(target)` when synchronous creation is acceptable. Signature objects follow the same shape as draws: `colors` is required, `depth` and `sampleCount` are optional.

A live `Surface` is a valid preparation target outside a frame. `compile()` reads its configured signature — `format`, resolved depth format, and sample count — without acquiring the canvas texture, resizing the canvas, or submitting work:

```wgsl
// gradient.wgsl
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return vec4f(uv, 0.6, 1);
}
```

```ts
import { init, effect, frameLoop, surface } from "vgpu";
import gradientShader from "./gradient.wgsl";

const gpu = await init();
const canvasSurface = surface(gpu, document.querySelector("canvas")!);

// ---cut---
const gradient = effect(gpu, gradientShader);
await gradient.compile(canvasSurface); // during loading, outside any frame

frameLoop(gpu, (currentFrame) => currentFrame.pass(canvasSurface, gradient)); // drawing stays in the frame
```

Before the surface exists, compile against `{ colors: [navigator.gpu.getPreferredCanvasFormat()] }` for a surface with the default format, no depth, and one sample. A surface created later with those defaults shares that cached pipeline. Include the planned `depth` format and `sampleCount` for a surface using those options, or prefer `compile(surface)` once it exists.

## Disposal

`dispose()` is optional. An effect you stop referencing is collected eventually, like any JavaScript object, and bundles that recorded it keep replaying. Call `dispose()` to retire an effect at a known point — unmounting a component, swapping a post-processing chain. It delegates to the effect's one underlying draw, so it has exactly the [`Draw` disposal](/docs/reference/vgpu/draw#draw) behavior and the same `VGPU-DRAW-DISPOSED` error. It is synchronous, idempotent, and valid after `gpu.dispose()` or device loss.

Stop whatever still calls the effect before you dispose it — the frame loop and any resize subscription that calls `set()`:

```ts
import { init, effect, frameLoop, surface } from "vgpu";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const canvasSurface = surface(gpu, document.querySelector("canvas")!);

// ---cut---
const vignette = effect(gpu, prepareShader(`
  struct Params { width: f32, height: f32 }
  @group(0) @binding(0) var<uniform> params: Params;

  @fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {
    let centered = position.xy / vec2f(params.width, params.height) - 0.5;
    return vec4f(vec3f(1.0 - length(centered)), 1.0);
  }
`), { label: "vignette" });

const unsubscribe = canvasSurface.onResize(({ width, height }) => {
  vignette.set({ params: { width, height } });
}); // fires once immediately with the current size
const loop = frameLoop(gpu, (currentFrame) => currentFrame.pass(canvasSurface, vignette));

function teardown(): void {
  loop.stop(); // no more frames draw the effect
  unsubscribe(); // no more resize callbacks call set()
  vignette.dispose(); // then retire the effect
}
```

After `teardown()`, the canvas surface and everything the effect sampled stay usable; `dispose()` never destroys borrowed targets, textures, buffers, samplers, or shared pipelines. Work already encoded keeps its captured uniform values, managed bundles that recorded the effect throw `VGPU-R3-BUNDLE-STALE` on replay, and a native `GPURenderBundle` read from `bundle.gpu` keeps its last uniform contents. A pending `compile()` settles with its preparation, then rejects with `VGPU-DRAW-DISPOSED`; a live effect or draw sharing that pipeline is unaffected. Neither collection nor `dispose()` promises when GPU memory is reclaimed.

## Notes

* When the source already has vertex entries, the unique entry is used regardless of name; with several entries, `vs_main` is preferred, otherwise the first is used. These preferred names are vgpu conventions, not WGSL requirements.
* A fragment-only effect is internally a `Draw` whose vertex stage is the fixed fullscreen triangle. That stage is a separate private shader module, shared through the gpu's shader-module cache by every fragment-only effect; your WGSL and its reflection are used unchanged, so your code cannot reference the fixed stage's declarations — read its output through `@location(0) uv: vec2f`. The fixed stage has no bindings, vertex buffers, or overrides. Fragment-only resources receive fragment visibility only, so storage does not consume `maxStorageBuffersInVertexStage`.
* A fragment input the fixed stage does not output — any `@location(n)` other than `0`, or `@location(0)` with a type other than `vec2f` — fails native render-pipeline validation. Declare your own `@vertex` entry when the fragment needs other varyings.
* `effect(gpu)` never parses WGSL: it validates the prepared artifact and reads its `reflection`, so effects built from loader-imported or prebuilt shaders keep the WGSL parser out of your bundle. Prepare runtime WGSL once per source revision, outside `frame(gpu)` and `frameLoop(gpu)` callbacks. An artifact with deeply frozen consumed data (every loader import and `prepareShader()` result) is validated once and reused by later `draw`/`effect`/`compute` calls; mutable ones are revalidated each call; changed source needs a new artifact (`ShaderSource`). `sourceChecksum` only detects a replaced `wgsl` string, not stale `reflection`, so regenerate artifacts when the source or the `@vgpu/wgsl` tooling changes.
* `entry`, `blend`, and `writeMask` are immutable pipeline state, fixed at `effect(gpu)` construction, and apply uniformly to every color target. Use them for overlays, glow, UI, and other loaded-pass compositing. For explicit blends, `op` defaults to `"add"` and omitted `alpha` copies `color`.
* One-shot `effect.draw()` does not join a surrounding frame. Inside `frame(gpu)`, draw through `frame.pass()`.
* There is no implicit screen target. Browser code should create a `Surface` and pass it as `target`.
* A `Surface` is only a destination. To post-process the screen image, render the scene into an offscreen `Target`, bind that target to the post effect, and draw the effect into a surface pass; see `Surface` for the full example. Binding the `Target` follows its attachment after `resize(...)`; binding `sceneTarget.color` keeps that exact texture, so rebind it after a resize.
* Do not rely on implicit uniforms like time or resolution; pass `clock(gpu).time`, `target.size`, or `target.texelSize` explicitly through `set()`.
* JS-owned values pack with the intrinsic `wgsl-host-shareable-v1` layout. Vectors, flattened column-major matrices, and fixed arrays require exact lengths; `i32`/`u32` require integral in-range numbers; padding is zero; and f16 conversion rounds to nearest with ties to even. A first complete binding object supplies every field. Later object updates merge over the last accepted value, while member-name shorthand starts unspecified siblings at WGSL zero. Each candidate is validated into temporary bytes before that binding's retained state or GPU bytes change.
* Raw buffers bind by the [`Draw` raw-buffer rules](/docs/reference/vgpu/draw#draw): `set()` recognizes a raw `GPUBuffer` or `{ buffer: GPUBuffer, offset?, size? }` by shape, so a WGSL struct whose members are named `buffer`, `offset`, or `size` still packs as data. Omitted `offset` is `0` and omitted `size` is `buffer.size - offset`; only `undefined` takes a default. `set()` copies the range, so mutating your descriptor later needs another `set()`. The buffer stays yours — vgpu never destroys it, `dispose()` leaves it alone, and its contents are read live rather than captured per frame.
* `set()` binds a `Texture` or `Target` through views that binding normalization generates and may reuse a compatible generated view across effects and rebinds. This is internal and has no controls; `Texture.createView(desc)` still returns a fresh view on every call.
* **See also:** `effect`, `ShaderSource`, `prepareShader` (`@vgpu/wgsl/prepare`), `Draw`, `FramePass.draw`, `Surface`, `Target`, `SharedUniforms`.

## Compilation validation and uniform capture

`compile()` waits for native validation even after `compileSync()` created a candidate or took over a pending asynchronous compile. Synchronous creation failures throw; asynchronous validation from synchronous preparation uses `gpu.onError`. A failed pipeline throws on automatic reuse; explicitly compile again to retry.

Direct frame draws capture managed uniform values when encoded, matching compute dispatches. Later `set()` calls do not alter earlier commands. Storage bindings, raw/low-level buffers, claimed bind groups, and render bundles retain their live buffer contents.

Packed-byte equality, pooled frame pages and their bind-group reuse work as described for `Draw` in "Compilation validation and uniform capture". Raw `GPUBuffer` and `{ buffer, offset?, size? }` bindings follow "Raw buffers and byte ranges" in `Draw`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Frame
description: `frame()` is both a callable one-frame submit helper and a `FrameRunner`. It creates one command encoder, lets you encode any number of explicit-target render passes and compute passes, then submits once. Frame callbacks are synchronous: await preparation first, then call `frame(gpu, cb)` or register `frameLoop(gpu, cb)`.
---

# Frame



## Import

```ts
import { frame, frameLoop } from "vgpu";
import type { Frame, FramePass, FramePassOptions, FrameComputePass, FrameComputePassOptions, FrameLoopCallback, FrameLoopHandle, FrameLoopOptions, FrameRunner } from "vgpu";
```

## Signature

```ts
import type { Compute, DispatchOptions, Bundle, ClearColor, Draw, DrawCallOptions, Effect, Gpu, Target, TimerSpan, Visibility, VisibilityQuery } from "vgpu";

// Private inference guards, shown only to explain the overloads — vgpu does not export them.
// A known Promise/PromiseLike return collapses to `never`; erased `any` is checked at runtime.
type IsAny<T> = 0 extends (1 & T) ? true : false;
type SyncFrameCallback<R> = ((frame: Frame) => R)
  & (IsAny<R> extends true
    ? unknown
    : [Extract<R, PromiseLike<unknown>>] extends [never] ? unknown : never);

declare function frame(gpu: Gpu): Frame;
declare function frame<R>(gpu: Gpu, cb: SyncFrameCallback<R> | undefined): Frame;
declare function frameLoop<R>(gpu: Gpu, cb: SyncFrameCallback<R>, opts?: FrameLoopOptions): FrameLoopHandle;

interface FramePassOptions {
  readonly target: Target;
  readonly clear?: boolean | ClearColor;
  readonly clearDepth?: number;
  readonly clearStencil?: number;
  readonly depthReadOnly?: boolean;
  readonly viewport?: {
    readonly x?: number;
    readonly y?: number;
    readonly width: number;
    readonly height: number;
    readonly minDepth?: number;
    readonly maxDepth?: number;
  };
  readonly scissor?: readonly [number, number, number, number];
  readonly timer?: TimerSpan;
  readonly visibility?: Visibility;
}

interface FrameLoopHandle { stop(): void; }
interface FrameLoopOptions { readonly fps?: number; }
type FrameLoopCallback = (frame: Frame) => void;

declare class Frame {
  done: Promise<void>;
  pass(target: Target, body: Effect | Draw | ((pass: FramePass) => void)): void;
  pass(options: FramePassOptions, body: Effect | Draw | ((pass: FramePass) => void)): void;
  computePass(body: (pass: FrameComputePass) => void): void;
  computePass(options: FrameComputePassOptions, body: (pass: FrameComputePass) => void): void;
  submit(): void;
  cancel(): void;
}

interface FrameComputePassOptions { readonly label?: string; }
interface FrameComputePass {
  dispatch(pipeline: Compute, x: number, y?: number, z?: number): void;
  dispatch(pipeline: Compute, options: DispatchOptions): void;
}

declare class FramePass {
  readonly target: Target;
  draw(drawable: Draw | Effect, opts?: DrawCallOptions): void;
  occlusion(query: VisibilityQuery, body: Draw | Effect | (() => void)): void;
  bundles(...bundles: readonly Bundle[]): void;
}

declare class FrameRunner {
  frame(): Frame;
  frame<R>(cb: SyncFrameCallback<R> | undefined): Frame;
  loop<R>(cb: SyncFrameCallback<R>, opts?: FrameLoopOptions): FrameLoopHandle;
}
```

## Parameters

| Param                | Type                                                                                                    | Required | Default        | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| -------------------- | ------------------------------------------------------------------------------------------------------- | -------: | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| frame.cb             | `SyncFrameCallback<R> \| undefined` — a synchronous `(frame: Frame) => R`                               |        ✖ | `undefined`    | If supplied, the frame submits when the callback returns a non-thenable result (the value itself is ignored) and is canceled when it throws or returns a thenable. An inferred `Promise`/`PromiseLike` return, or a union containing one, fails to typecheck; a thenable that reaches runtime throws `VGPU-ASYNC-FRAME-CALLBACK`. If omitted — `frame(gpu)` or `frame(gpu, undefined)` — submit or cancel manually.                                                                                                                                                                                                                                                                                                                                                    |
| target.clearColor    | `ClearColor`                                                                                            |        ✖ | `[0, 0, 0, 1]` | Writable default clear color of the pass target, used when pass `clear` is omitted or `true`. Set it at creation (`surface(gpu, canvas, { clearColor })`, `target(gpu, { size, clearColor })`) or assign it later. Assign a `GPUColor` object or `[r, g, b, a]`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| frame.pass.target    | `Target \| FramePassOptions`                                                                            |        ✔ | —              | Pass a bare target for the allocation-free common case, or an options bag when customizing clear/preserve behavior.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| opts.target          | `Target`                                                                                                |        ✔ | —              | Required inside `FramePassOptions`. Use a `Surface` from `surface(gpu, canvas)` or an offscreen `Target` from `target(gpu, { size })`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| opts.clear           | `boolean \| ClearColor`                                                                                 |        ✖ | `true`         | Omitted or `true` clears with `target.clearColor`; `false` preserves existing color and depth with load ops; a color clears this pass with that color.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| opts.clearDepth      | `number`                                                                                                |        ✖ | `1`            | Depth clear value used when the pass clears, in `[0, 1]`. Clear to `0` and give draws `depth: { compare: "greater" }` for reversed-Z, which evens out float depth precision and cuts distant z-fighting. Invalid alongside `clear: false`, which preserves depth, and on a target without depth (the value would have nowhere to land).                                                                                                                                                                                                                                                                                                                                                                                                                                |
| opts.clearStencil    | `number`                                                                                                |        ✖ | `0`            | Stencil clear value used when the pass clears; integer in `[0, 0xFFFFFFFF]`, masked to the stencil aspect's bit width by taking the LSBs (values above `0xFF` are legal on 8-bit aspects). Clear to `0` before stencil-masking draws mark pixels via `DrawOptions.stencil` — portals, mirrors, UI cutouts. Requires a target depth format with a stencil aspect (e.g. `depth: "depth24plus-stencil8"`). Invalid alongside `clear: false`, which preserves stencil.                                                                                                                                                                                                                                                                                                     |
| opts.depthReadOnly   | `boolean`                                                                                               |        ✖ | `false`        | Opens the pass with a read-only depth attachment: draws depth-test against it and may sample `target.depth` in the same pass — the soft-particles/SSAO setup. Every draw in the pass needs `depth: { write: false }` (or `depth: false`); the default depth state writes and throws `VGPU-PASS-DEPTH-READONLY` at encode. Effects always keep the writing default, so an `Effect` cannot run in a depthReadOnly pass on a depth target. Combined depth-stencil formats mark the stencil aspect read-only too. Requires a target with depth; invalid alongside `clearDepth`/`clearStencil` (color `clear` still applies), and invalid on MSAA targets and `msaa` surfaces, whose depth aspect is stored with `storeOp: "discard"` — there is no retained depth to read. |
| opts.viewport        | `{ x?, y?, width, height, minDepth?, maxDepth? }`                                                       |        ✖ | full target    | Restricts rasterization to a sub-rectangle for every draw in this pass. Use it for split-screen views, minimaps, and picture-in-picture insets. Floats (fractional values allowed); defaults `x`/`y` `0`, `minDepth` `0`, `maxDepth` `1`. May extend past the target — validated at pass open against device limits, not the attachment.                                                                                                                                                                                                                                                                                                                                                                                                                               |
| opts.scissor         | `readonly [number, number, number, number]`                                                             |        ✖ | full target    | Clips every draw in this pass to `[x, y, width, height]`. Use it for UI clipping and partial redraw of damaged regions. Non-negative integers; `x + width` and `y + height` must fit the target's **current** pixel size at pass open (targets are resizable). Never affects the clear — `loadOp: "clear"` fills the whole attachment; to clear a sub-rectangle, draw it inside a scissored pass.                                                                                                                                                                                                                                                                                                                                                                      |
| opts.timer           | `TimerSpan`                                                                                             |        ✖ | `undefined`    | Times this pass on the GPU: pass `timer.span(name)` from a `timer(gpu)` (needs the `"timestamp-query"` device feature). See `Timer` for results, capacity, and feature gating.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| opts.visibility      | `Visibility`                                                                                            |        ✖ | `undefined`    | Enables occlusion queries in this pass: pass a `visibility(gpu)` instance, then wrap proxy draws in `pass.occlusion(handle, body)`. Requires a target with a depth attachment. See `Visibility` for handle semantics and capacity.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| frame.pass.body      | `Effect \| Draw \| ((pass: FramePass) => void)`                                                         |        ✔ | —              | Pass a drawable directly for a single draw, or a callback to encode multiple draw and bundle commands.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| pass.draw\.drawable  | `Draw \| Effect`                                                                                        |        ✔ | —              | A main API (`vgpu`) draw or fullscreen effect.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| pass.draw\.opts      | `DrawCallOptions`                                                                                       |        ✖ | `{}`           | Per-call counts and dynamic offsets. Target is the frame pass target.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| pass.occlusion.query | `VisibilityQuery`                                                                                       |        ✔ | —              | Stable handle from `vis.query(label)` of the same visibility instance the pass was opened with. One use per handle per frame, across passes too.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| pass.occlusion.body  | `Draw \| Effect \| (() => void)`                                                                        |        ✔ | —              | Wrapped in `beginOcclusionQuery`/`endOcclusionQuery`. The body ALWAYS executes — it is the proxy the GPU measures; condition your real draws on `q.hidden` outside the scope.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| pass.bundles.bundles | `readonly Bundle[]`                                                                                     |        ✔ | —              | Bundles recorded by `bundle(gpu, { target }, cb)`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| runner.loop.cb       | `SyncFrameCallback<R>` — a synchronous `(frame: Frame) => R`; an exported `FrameLoopCallback` also fits |        ✔ | —              | Called on each scheduled frame with the `frame(gpu, cb)` rule: submit on a non-thenable return, cancel on throw or thenable result; a failing tick also stops the loop. Registration never calls the callback, so it cannot throw a future tick's error. Surface auto-resize runs before this callback.                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| runner.loop.opts.fps | `number`                                                                                                |        ✖ | `0` (uncapped) | Positive values cap by minimum frame interval `1000 / fps`; omitted or non-positive uses every rAF/timer tick.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

**Returns:** `frame(gpu)` / `frame(gpu, cb)` / `FrameRunner.frame()` return `Frame`; `Frame.pass()`, `Frame.submit()`, and `Frame.cancel()` return `void`; `FramePass.draw()`, `.occlusion()`, and `.bundles()` return `void`; `frameLoop(gpu, cb)` / `loop()` return `FrameLoopHandle` with `stop()`.

**Throws:**

* `VGPU-ASYNC-FRAME-CALLBACK` when a `frame(gpu, cb)` / `frameLoop(gpu, cb)` callback (or its `FrameRunner` equivalent) returns a thenable — any object or function with a callable `then`, such as the `Promise` of an `async` callback. It is thrown synchronously before the implicit submit, with `where` set to `"frame"` or `"frameLoop"`; a still-open frame is canceled first and a loop stops on that tick. Await preparation before `frame()`/`frameLoop()`; keep the frame callback synchronous. If reading the result's `then` property itself throws, that original error propagates instead, after the same cleanup.
* `VGPU-TARGET-REQUIRED` — a runtime JS call omitted the frame pass target. Name a `Surface` or offscreen `Target` in every `frame.pass`.
* `VGPU-CLEAR-COLOR-INVALID` — `target.clearColor` / `surface.clearColor` (at creation or on assignment) or a pass clear color is not four finite numbers. Assign `[r, g, b, a]` or a `GPUColor` object.
* `VGPU-PASS-PRESERVE-MSAA` — `clear: false` on an MSAA target or `msaa` surface; multisample attachments use `storeOp: "discard"`, so there is nothing to preserve. Render accumulation/preserve passes into a non-MSAA target.
* `VGPU-PASS-CLEARDEPTH-INVALID` — `clearDepth` is not a number in `[0, 1]`, or the target has no depth attachment (the option would have no effect). Create the target or surface with `depth: true`, or drop `clearDepth`.
* `VGPU-PASS-PRESERVE-CLEARDEPTH` — `clearDepth` combined with `clear: false`; preserved depth is never cleared. Drop one of the two.
* `VGPU-PASS-CLEARSTENCIL-INVALID` — `clearStencil` is not an integer in `[0, 0xFFFFFFFF]`, or the target's depth format has no stencil aspect (the option would have no effect). Create the target with `depth: "depth24plus-stencil8"`.
* `VGPU-PASS-PRESERVE-CLEARSTENCIL` — `clearStencil` combined with `clear: false`; preserved stencil is never cleared. Drop one of the two.
* `VGPU-PASS-DEPTH-READONLY` — `depthReadOnly` is not a boolean, is set on a target without depth, or is combined with `clearDepth`/`clearStencil` (read-only aspects omit their load/store ops and are never cleared). Also thrown at encode when a draw writes depth — add `depth: { write: false }` — or writes stencil (a draw writes stencil when any stencil op on an unculled face is not `"keep"` and its stencil `writeMask` is nonzero — use `"keep"` ops or `writeMask: 0`); and when `pass.bundles(...)` is called in such a pass — `bundle()` records writable depth/stencil, and WebGPU only executes read-only-recorded bundles there, so encode those draws with `pass.draw(...)` instead.
* `VGPU-PASS-DEPTH-READONLY-MSAA` — `depthReadOnly` on an MSAA target or `msaa` surface; multisampled depth is stored with `storeOp: "discard"`, so a read-only pass would depth-test against discarded contents instead of failing loudly. Use a single-sample target or surface for read-only depth.
* `VGPU-PASS-VIEWPORT-INVALID` — `viewport` is malformed or outside device limits: `width`/`height` in `[0, maxTextureDimension2D]`, `x`/`y` at least `-2 × maxTextureDimension2D` with `x + width`/`y + height` at most `2 × maxTextureDimension2D − 1`, `minDepth`/`maxDepth` in `[0, 1]` with `minDepth <= maxDepth`. The message names the offending field.
* `VGPU-PASS-SCISSOR-INVALID` — `scissor` is malformed or exceeds the target's current pixel size. Shrink the rectangle, or resize it from `surface.onResize(...)`.
* `VGPU-TIMER-INVALID` — `timer` is not a `TimerSpan` from `timer.span(name)`, repeats a span name within one frame, or belongs to a different gpu's or disposed timer.
* `VGPU-TIMER-CAPACITY` — one frame timed more spans than the per-frame limit (see `Timer`).
* `VGPU-VIS-INVALID` — `visibility` is not a `Visibility` from this gpu's `visibility(gpu)`, or `occlusion()` received a non-`VisibilityQuery` value or a handle of a different visibility instance.
* `VGPU-VIS-NO-DEPTH` — `visibility` on a pass whose target has no depth attachment; nothing is depth-tested, so every query would report visible. Create the target or surface with `depth: true`.
* `VGPU-VIS-DISPOSED` — the visibility instance or the handle is disposed.
* `VGPU-VIS-CAPACITY` — the `occlusion()` call exceeded the declared capacity. Raise `VisibilityOptions.capacity`.
* `VGPU-QUERY-NO-VISIBILITY` — `occlusion()` in a pass opened without `visibility`. Pass the instance in `FramePassOptions.visibility`.
* `VGPU-QUERY-NESTED` — `occlusion()` inside an active `occlusion()` body; one scope at a time. Close the outer scope first.
* `VGPU-QUERY-DUPLICATE` — a handle used twice within one frame, across passes too (see `Visibility`). Create one handle per queried object.
* `VGPU-DEVICE-LOST` — work after loss, including an open manual frame's `submit()`. Recreate with `init()`; see `Gpu` ("Device loss").
* `VGPU-FRAME-REENTRANT` — a frame started from another frame or from a surface resize callback. Encode everything in one frame callback.
* `VGPU-FRAME-CANCELED` — a `frame.pass(...)`, a `frame.computePass(...)`, or a retained `FramePass` operation, on a frame closed by `cancel()` — including a frame vgpu canceled for `VGPU-ASYNC-FRAME-CALLBACK`, reached from that callback's async continuation; its command encoder was dropped, so the work would never run. Open a new `frame(gpu)`.
* `VGPU-FRAME-PASS-ACTIVE` — `frame.cancel()` from inside that frame's active pass callback. Return from `frame.pass(...)` first, then cancel, so resources referenced by the native pass descriptor stay alive until the pass closes.
* `VGPU-FRAME-SUBMITTED` — `frame.cancel()` on a frame that was already submitted; queued GPU work cannot be taken back, and the frame needs no cleanup. Cancel only frames you decided not to submit.
* `VGPU-R3-BUNDLE-STALE` / `VGPU-R3-BUNDLE-INVALID` — replaying a bundle whose recorded resources changed identity, or a value not created by `bundle()`. Re-record the bundle.
* Binding errors such as `VGPU-R1-BINDING-NEVER-SET` propagate during encoding. Raw claimed-group validation is delivered asynchronously through `gpu.onError`.

## Examples

```ts
import { init, draw, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [64, 64], format: "rgba8unorm", clearColor: [0.02, 0.02, 0.04, 1] });
scene.clearColor = [0.02, 0.02, 0.04, 1]; // and it stays writable at runtime
const drawable = draw(gpu, { shader: prepareShader(`
  @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
    var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
    return vec4f(p[vi], 0, 1);
  }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.2, 0.4, 1.0, 1.0); }
`) });

frame(gpu, (currentFrame) => {
  currentFrame.pass(scene, (pass) => pass.draw(drawable)); // clears with scene.clearColor
});
```

```ts
import { init, effect, frameLoop, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [16, 16] });
const shader = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }`));
const handle = frameLoop(gpu, (frame) => {
  frame.pass({ target: colorTarget, clear: false }, shader); // preserve color and depth
}, { fps: 30 });
handle.stop();
```

```ts
import { init, effect, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const screen = target(gpu, { size: [640, 360] });
const p1View = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.1, 0.3, 0.6, 1); }`));
const p2View = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.6, 0.3, 0.1, 1); }`));

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: screen, viewport: { width: 320, height: 360 } }, p1View); // player 1, left half
  currentFrame.pass({ target: screen, clear: false, viewport: { x: 320, width: 320, height: 360 } }, p2View); // player 2, right half
});
```

Split-screen: the first pass clears the whole target and rasterizes one camera into the left viewport; the second preserves it (`clear: false`) and rasterizes the other camera into the right viewport.

```ts
import { init, draw, effect, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [256, 256], depth: true });
const opaque = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.2, 0.5, 0.2, 1); }`));
const particles = draw(gpu, {
  shader: prepareShader(`
    @group(0) @binding(0) var sceneDepth: texture_depth_2d;
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0.4, 1);
    }
    @fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f {
      let d = textureLoad(sceneDepth, vec2i(pos.xy), 0);
      let fade = clamp((d - pos.z) * 32.0, 0.0, 1.0); // fade out where the particle nears geometry
      return vec4f(0.9, 0.6, 0.3, 1.0) * fade;
    }
  `),
  depth: { write: false }, // required: the pass depth is read-only
  blend: "additive",
  set: { sceneDepth: scene.depth },
});

frame(gpu, (currentFrame) => {
  currentFrame.pass(scene, opaque); // pass 1: opaque geometry writes depth
  currentFrame.pass({ target: scene, clear: false, depthReadOnly: true }, particles); // pass 2: test + sample that depth
});
```

Soft particles: pass 2 depth-tests against the opaque depth while sampling the same `scene.depth` texture, which WebGPU only allows because the attachment is read-only.

```ts
import { init, effect, frame, target, visibility } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [64, 64], depth: true });
const vis = visibility(gpu);
const proxy = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }`));

const currentFrame = frame(gpu); // manual frame: nothing submits it for you
currentFrame.pass({ target: scene, visibility: vis }, (pass) => pass.occlusion(vis.query("statue"), proxy));

if (sceneChangedUnderneath()) {
  currentFrame.cancel(); // no GPU work runs, and the occlusion query set stops being retained for this frame
  vis.dispose(); // released now instead of at gpu.dispose()
} else {
  currentFrame.submit();
}

function sceneChangedUnderneath(): boolean { return true; }
```

Cancelling a manual frame: `cancel()` drops the encoder and releases the telemetry retains the frame took, so a `timer(gpu)` / `visibility(gpu)` can be disposed for good without submitting work you no longer want.

Keeping partial work when a later step throws: a `frame(gpu, cb)` callback that throws is canceled, so nothing it encoded runs. Submit explicitly before rethrowing to present what was encoded so far.

```ts
import { init, frame, target, type Frame } from "vgpu/mock";

const gpu = await init();
const scene = target(gpu, { size: [64, 64] });
function encode(currentFrame: Frame): void { currentFrame.pass(scene, () => undefined); }

frame(gpu, (currentFrame) => {
  try {
    encode(currentFrame);
  } catch (error) {
    currentFrame.submit(); // opt in: what was encoded so far is presented anyway
    throw error;
  }
});
```

Async preparation and teardown: await everything asynchronous before the frame and after it returns, and keep the callback itself synchronous.

```ts
import { init, compute, effect, frame, storage, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [64, 64] });
const particles = storage(gpu, 64 * 16);
const simulation = compute(gpu, prepareShader(`
  @group(0) @binding(0) var<storage, read_write> particles: array<vec4f>;
  @compute @workgroup_size(64) fn main(@builtin(global_invocation_id) id: vec3u) {
    particles[id.x] += vec4f(0.0, -0.01, 0.0, 0.0);
  }
`), { set: { particles } });
const shade = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.1, 0.2, 0.4, 1); }`));

await simulation.compile(); // async preparation happens before the frame

const currentFrame = frame(gpu, (encoding) => {
  encoding.computePass((pass) => pass.dispatch(simulation, 1)); // synchronous encoding only
  encoding.pass(scene, shade);
});

await currentFrame.done; // async teardown happens after frame() returned
gpu.dispose();
```

`frame(gpu, cb)` returns only after the callback finished and the frame submitted, so `await currentFrame.done` outside the callback waits for that work to complete.

Async callbacks are rejected. This is the shape to avoid:

```ts illustrative
frame(gpu, async (currentFrame) => { // type error: the callback returns a Promise
  await simulation.compile();         // at runtime: VGPU-ASYNC-FRAME-CALLBACK, frame canceled
  currentFrame.computePass((pass) => pass.dispatch(simulation, 1)); // continuation: VGPU-FRAME-CANCELED
});
```

The callback returns its `Promise` at the first `await`, so the frame would otherwise submit before the continuation encodes anything. vgpu throws `VGPU-ASYNC-FRAME-CALLBACK` before that implicit submit and cancels the frame; the continuation still runs later, and its `computePass(...)` throws `VGPU-FRAME-CANCELED`. vgpu consumes the rejection of the returned promise, so that later error reaches neither `gpu.onError` nor an unhandled-rejection handler.

## Notes

* `Frame`, `FramePass`, and `FrameRunner` are type-only public exports. Create frames through `frame()`, not `new Frame(...)`.
* There is no default target and no implicit canvas target; every `frame.pass` names its target.
* Omitted `clear` and `clear: true` clear with `target.clearColor`. Pass a color to clear one pass with that color without changing the target default: pass color > `target.clearColor` > the built-in `[0, 0, 0, 1]`.
* Draws replayed via `pass.bundles(...)` inside an occlusion scope count toward the active query — render bundles have no query methods, but their draws execute inside the scope.
* `viewport` and `scissor` are set once right after the pass opens and apply to every draw in the pass, including replayed bundles. Both are in physical pixels: surfaces size their textures by `devicePixelRatio`, so a CSS-pixel rectangle must be scaled by dpr.
* `clear: false` loads color/depth. Surface passes share a frame's canvas image; clear the first pass because color is fresh but depth persists. See `Surface` for lifetimes.
* **Hot loops:** options bags and pass callbacks are read synchronously, so you can hoist and reuse them. For zero-per-frame-JS-cost replay, record stable work with `bundle()` and replay the bundle.
* `frame.cancel()` discards a frame you decided not to submit: its command encoder is dropped, so nothing it encoded ever runs, and every `timer(gpu)` / `visibility(gpu)` attached to it releases the query set it was holding for that frame — no result, no phantom timing, no phantom `"hidden"`. It is the explicit way out of the retain a manual `frame(gpu)` otherwise keeps until `gpu.dispose()`: a frame is never assumed abandoned, because an old frame can still be submitted.
* Frames run by `frame(gpu, cb)` / `frameLoop(gpu, cb)` close themselves, atomically with respect to their command buffer: the frame submits once when the callback returns, and is canceled when the callback throws or returns a thenable (`VGPU-ASYNC-FRAME-CALLBACK`) — no command buffer is submitted, the telemetry retains its passes took are released, and a thrown error is rethrown as-is. A callback that already called `frame.submit()` keeps that work on the queue and its error is rethrown without a cancel attempt (never masked by `VGPU-FRAME-SUBMITTED`); one that already called `frame.cancel()` stays canceled. Only the command buffer is covered: the frame clock has already advanced, CPU-side mutations (`effect.set(...)`, buffer writes) stay applied, and one-shot draws or other frames submitted from inside the callback have already reached the queue. If a pass already targeted a `Surface`, the canvas still presents that browser frame — as an empty texture, since nothing was drawn into it. A `frameLoop` tick that throws or returns a thenable also stops the loop, because the error escapes the animation-frame callback; start a new `frameLoop(gpu, cb)` once you have recovered.
* Implicit-submit errors propagate. `gpu.dispose()` cancels the frame; `gpu.device.dispose()` does not.
* Loss stops loops before `gpu.lost` handlers; manual frames stay open. See `Gpu` ("Device loss").
* **Callbacks are synchronous.** Synchronous callbacks are accepted — a block body, a `void` expression such as `(currentFrame) => currentFrame.pass(scene, shade)`, a helper with a concrete non-Promise return type (its value is ignored), or one that only throws. Helpers with those concrete return types need no rewrite. TypeScript rejects a single callback whose inferred return type is a `Promise`, a `PromiseLike`, or a return union containing one (`void | Promise<void>`): `frame` reports it as not assignable to a parameter of type `undefined`, `frameLoop` as not assignable to `never`.
* The type check cannot see a return type that was already erased: a callback stored as `FrameLoopCallback`, `(frame: Frame) => unknown`, or `(frame: Frame) => any`, a cast, a return-type-erasing wrapper, or plain JavaScript still compiles. A union of callback function types with a void member may also erase its Promise-returning member during inference and compile. vgpu checks the actual result at runtime instead: an object or function with a callable `then` throws `VGPU-ASYNC-FRAME-CALLBACK` before the implicit submit, cancels a still-open frame, and stops a `frameLoop` on that tick under the same rule as a throw. vgpu attaches a handler to the result so its rejection is observed silently — no `gpu.onError` delivery, no unhandled rejection, nothing added to `gpu.settled()` — and never waits for it, so a promise that never settles does not delay the error. `Frame.done` of the canceled frame still resolves; it never rejects.
* Forwarding helpers whose callback return remains an unresolved generic `R`, including `R extends void`, no longer typecheck: the frame API cannot prove that return synchronous. If a helper intentionally ignores callback returns, accept `FrameLoopCallback` or `(frame: Frame) => void` and pass that callback directly to the frame API, so the runtime can still inspect its actual result.
* Do not hide async frame work behind `void`, a cast, or a return-type-erasing wrapper. The thenable check is a safety net, not a scheduling mechanism: cancellation does not undo a `frame.submit()` the callback already called (that work stays on the queue and the error is still thrown), one-shot `draw()` / `dispatch()` calls that already submitted on their own, CPU-side mutations, or the async continuation itself — it still runs, and any encoding it attempts on the canceled frame throws `VGPU-FRAME-CANCELED`. Await preparation before `frame()` / `frameLoop()` and teardown after it returns.
* `VGPU-ASYNC-FRAME-CALLBACK` covers only the `frame` / `frameLoop` callback. Compute-pass callbacks keep their own `VGPU-COMPUTE-PASS-ASYNC` check (see below); render-pass bodies and `bundle()` record callbacks do not run this check.
* Cancelling is idempotent, like submitting: a second `cancel()` does nothing, and `submit()` after `cancel()` is a no-op — so calling `cancel()` in a `frame(gpu, cb)` callback after its `frame.pass(...)` calls have returned is safe, the implicit submit simply finds a closed frame. `cancel()` from inside an active pass callback throws `VGPU-FRAME-PASS-ACTIVE`, because the native pass descriptor still references its telemetry resources; return from `frame.pass(...)` before canceling. The reverse is also an error: `cancel()` after `submit()` throws `VGPU-FRAME-SUBMITTED` (the work is already on the queue and cannot be taken back), and `pass()` or a retained `FramePass` operation after `cancel()` throws `VGPU-FRAME-CANCELED` (it would encode into a dropped encoder and silently never run).
* `frame.done` is resolve-only. Await it as a completion/timing signal for readbacks, benchmarks, deterministic tests, or teardown; use `gpu.onError` plus `await gpu.settled()` for asynchronous errors.
* Do not `await frame.done` inside a RAF/frame loop. Schedule the next frame as soon as `frame(gpu)` returns, or you serialize CPU and GPU work.
* **See also:** `frame`, `Surface`, `Effect`, `Draw`, `Bundle`, `Target`, `Timer`, `Visibility`.

## Compute passes and captured uniforms

Use `frame.computePass(pass => pass.dispatch(simulation, x, y, z))` to encode compute work in the same command buffer as render passes. An optional `{ label }` identifies the native compute pass. `pass.dispatch(simulation, { indirect: args })` uses GPU-produced counts. One callback opens one compute pass, and can contain several dispatches.

Compute-pass callbacks are synchronous: await pipeline preparation before the frame. Passes cannot nest; submit or cancel only after a pass ends. A retained compute-pass object throws `VGPU-COMPUTE-PASS-CLOSED` after its callback. A foreign pipeline throws `VGPU-COMPUTE-DEVICE-MISMATCH`; a thenable callback result throws `VGPU-COMPUTE-PASS-ASYNC`. A canceled/submitted frame rejects new passes.

Direct `pass.draw()` and compute `pass.dispatch()` capture JS-owned uniform values and `uniforms()` uniform bindings at encoding time. Changing values later in the callback does not alter earlier commands. Uploads are released after completion or abandonment. Storage/raw buffers, claimed groups and bundles retain live-buffer semantics; host writes and CPU changes are not rolled back by cancellation.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: geometry()
description: Creates an immutable vertex/index layout plus mutable GPU buffers for `draw(gpu)`. The v2 descriptor form accepts named attributes, multiple vertex streams, instancing streams, indices, topology, writes, and slices. Existing scene geometry descriptors such as `box()` continue to work as primitive sugar.
---

# geometry()



## Import

```ts
import type { Geometry, GeometryOptions, GeometryBufferOptions, GeometrySliceOptions } from "vgpu";
import { box } from "vgpu/scene";
```

## Signature

```ts
interface Gpu {
  geometry(geometry: import("vgpu/scene").SceneGeometry): Geometry;
  geometry(options: GeometryOptions): Geometry;
}

type GeometryData = ArrayBuffer | ArrayBufferView;
type GeometryAttributes = {
  readonly [name: string]: GPUVertexFormat | GeometryAttributeOverride;
};

interface GeometryAttributeOverride {
  readonly format: GPUVertexFormat;
  readonly offset?: number;
  readonly location?: number;
}

interface GeometryBufferOptions {
  readonly attributes: GeometryAttributes;
  readonly data?: GeometryData;
  readonly buffer?: GPUBuffer;
  readonly stride?: number;
  readonly stepMode?: GPUVertexStepMode;
  readonly label?: string;
}

interface GeometryOptions {
  readonly buffers: readonly GeometryBufferOptions[];
  readonly vertexCount?: number;
  readonly instanceCount?: number;
  readonly indices?: Uint16Array | Uint32Array | readonly number[];
  readonly indexBuffer?: GPUBuffer;
  readonly indexFormat?: GPUIndexFormat;
  readonly indexCount?: number;
  readonly topology?: GPUPrimitiveTopology;
  readonly label?: string;
}

interface GeometryBuffer {
  readonly gpu: GPUBuffer;
  readonly stride: number;
  readonly stepMode: GPUVertexStepMode;
  write(data: GeometryData, byteOffset?: number): void;
}

interface GeometrySliceOptions {
  readonly firstIndex?: number;
  readonly indexCount?: number;
  readonly baseVertex?: number;
  readonly firstVertex?: number;
  readonly vertexCount?: number;
  readonly instanceCount?: number;
  readonly label?: string;
}

interface Geometry {
  readonly vertexCount?: number;
  readonly indexCount?: number;
  readonly instanceCount?: number;
  readonly vertexBuffers?: readonly GPUBuffer[];
  readonly indexBuffer?: GPUBuffer;
  readonly indexFormat?: GPUIndexFormat;
  readonly vertexBufferLayouts?: readonly GPUVertexBufferLayout[];
  readonly topology: GPUPrimitiveTopology;
  readonly buffers: readonly GeometryBuffer[];
  slice(opts?: GeometrySliceOptions): GeometrySlice;
  write(data: GeometryData, byteOffset?: number): void;
  writeIndices(data: Uint16Array | Uint32Array, byteOffset?: number): void;
  destroy(): void;
}

interface GeometrySlice extends GeometryLike {
  readonly geometry: Geometry;
  readonly firstIndex?: number;
  readonly indexCount?: number;
  readonly baseVertex?: number;
  readonly firstVertex?: number;
  readonly vertexCount?: number;
  readonly instanceCount?: number;
}

interface DrawCallOptions {
  /** Non-indexed count. Precedence: call > slice > geometry > DrawOptions > 3. */
  readonly vertices?: number;
  /** Non-indexed start. Precedence: call > slice > 0. */
  readonly firstVertex?: number;
  /** Indexed count. Precedence: call > slice > geometry. */
  readonly indices?: number;
  /** Indexed start. Precedence: call > slice > 0. */
  readonly firstIndex?: number;
  /** Indexed base vertex. Precedence: call > slice > 0. */
  readonly baseVertex?: number;
}
```

## Parameters

| Field                      | Type                                              | Required | Default                       | Notes                                                                                                                                                                                                                                                                                  |
| -------------------------- | ------------------------------------------------- | -------: | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| geometry                   | `SceneGeometry`                                   |        ✔ | —                             | v1 primitive sugar path. Emits pinned locations: `position` → `@location(0)`, `normal` → `@location(1)`, `uv` → `@location(2)`.                                                                                                                                                        |
| options.buffers            | `readonly GeometryBufferOptions[]`                |        ✔ | —                             | Vertex buffer streams. Maximum 8.                                                                                                                                                                                                                                                      |
| buffer.attributes          | `GeometryAttributes`                              |        ✔ | —                             | Record form only. Key is the WGSL vertex input name unless `location` is specified. Maximum 16 attributes total.                                                                                                                                                                       |
| attribute format           | `GPUVertexFormat`                                 |        ✔ | —                             | Shorthand value: `{ position: "float32x3" }`.                                                                                                                                                                                                                                          |
| attribute.offset           | `number`                                          |        ✖ | tight-packed order            | Byte offset within the stream. Integer-like attribute keys are rejected to avoid JavaScript key reordering.                                                                                                                                                                            |
| attribute.location         | `number`                                          |        ✖ | shader name match             | Explicit shader location. When present, the record key is only a label.                                                                                                                                                                                                                |
| buffer.data                | `GeometryData`                                    |        ✖ | —                             | Creates an owned `["vertex", "copy_dst"]` buffer and uploads the initial data. Mutually exclusive with `buffer`.                                                                                                                                                                       |
| buffer.buffer              | `GPUBuffer`                                       |        ✖ | —                             | Caller-owned escape hatch. Mutually exclusive with `data`; not destroyed by `geometry.destroy()`.                                                                                                                                                                                      |
| buffer.stride              | `number`                                          |        ✖ | `roundUp4(sum(format sizes))` | Explicit stride for padded/interleaved data. Must be valid for WebGPU vertex buffers.                                                                                                                                                                                                  |
| buffer.stepMode            | `"vertex" \| "instance"`                          |        ✖ | `"vertex"`                    | Instance streams derive `geometry.instanceCount` from the first instance buffer with data.                                                                                                                                                                                             |
| options.vertexCount        | `number`                                          |        ✖ | derived                       | Derived from the first vertex-step buffer with data.                                                                                                                                                                                                                                   |
| options.instanceCount      | `number`                                          |        ✖ | derived                       | Draw default after `DrawCallOptions.instances` and `DrawOptions.instances`.                                                                                                                                                                                                            |
| options.indices            | `Uint16Array \| Uint32Array \| readonly number[]` |        ✖ | —                             | Creates an owned `["index", "copy_dst"]` index buffer. `Uint16Array` infers `"uint16"`; otherwise `"uint32"`. An odd-length `Uint16Array` is zero-padded to a 4-byte multiple for the initial upload only; `indexFormat`, `indexCount`, and the logical byte length stay the source's. |
| options.indexBuffer        | `GPUBuffer`                                       |        ✖ | —                             | Caller-owned index buffer escape hatch. Pair with `indexFormat` and `indexCount`.                                                                                                                                                                                                      |
| options.topology           | `GPUPrimitiveTopology`                            |        ✖ | `"triangle-list"`             | Pipeline-affecting geometry topology. Strip topologies derive `stripIndexFormat` from `indexFormat`.                                                                                                                                                                                   |
| geometry.slice.opts        | `GeometrySliceOptions`                            |        ✖ | full range                    | Frozen range view sharing buffers and layout identity with the parent geometry.                                                                                                                                                                                                        |
| geometry.write.data        | `GeometryData`                                    |        ✔ | —                             | Writes to buffer 0 using `queue.writeBuffer`. No resize.                                                                                                                                                                                                                               |
| geometry.writeIndices.data | `Uint16Array \| Uint32Array`                      |        ✔ | —                             | Writes to an index buffer owned from `options.indices`. Write caller-owned `indexBuffer` objects directly. No resize. Capacity is the logical index size.                                                                                                                              |

**Returns:** `geometry(gpu)` returns `Geometry`; `geometry.slice()` returns `GeometrySlice`; `write()`, `writeIndices()`, and `destroy()` return `void`.

## Error codes

| Code                            | When                                                                                                                      | Fix                                                                                |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `VGPU-MESH-LAYOUT-INVALID`      | Invalid stride/offset/format, both `data` and `buffer`, or integer-like attribute key.                                    | Use record keys that are names, align offsets/strides, and choose one data source. |
| `VGPU-MESH-LIMIT-EXCEEDED`      | More than 8 buffers or 16 attributes.                                                                                     | Split draws or reduce streams/attributes.                                          |
| `VGPU-MESH-LOCATION-CONFLICT`   | Duplicate explicit `location` values.                                                                                     | Give each explicit shader location once.                                           |
| `VGPU-MESH-DATA-MISALIGNED`     | Data byte length is not divisible by stride, or index bytes do not match format.                                          | Repack data or pass an explicit `stride`.                                          |
| `VGPU-MESH-RANGE-INVALID`       | Slice or draw-time range is negative, non-integer, outside parent counts, or uses index ranges on non-indexed geometries. | Clamp ranges and use indexed fields only with indexed geometries.                  |
| `VGPU-MESH-WRITE-RANGE`         | `write()` or `writeIndices()` would overflow the fixed logical size, or is not 4-byte aligned.                            | Create a larger geometry; writes do not resize buffers.                            |
| `VGPU-MESH-ATTRIBUTE-UNMATCHED` | Named geometry attribute has no vertex-stage shader input.                                                                | Rename the attribute or specify `location`.                                        |
| `VGPU-MESH-INPUT-MISSING`       | Shader declares an uncovered `@location` input.                                                                           | Add the geometry attribute or remove the shader input.                             |
| `VGPU-MESH-FORMAT-MISMATCH`     | Vertex format base type does not match the WGSL input base type.                                                          | Use a compatible `GPUVertexFormat`; width differences are allowed by WebGPU.       |

## Examples

```ts
import { init, geometry } from "vgpu/mock";

const gpu = await init();
const positions = new Float32Array([
  -1, -1, 0,
   1, -1, 0,
   0,  1, 0,
]);

const triangle = geometry(gpu, {
  buffers: [{
    data: positions,
    attributes: { position: "float32x3" },
  }],
});
```

```ts
import { init, geometry } from "vgpu/mock";

const gpu = await init();
const ledVertices = new Float32Array(6 * 6);
const ledGeometry = geometry(gpu, {
  label: "triangle-led-front-led-emitters",
  buffers: [{
    data: ledVertices,
    stride: 24,
    attributes: {
      position: "float32x2",
      local: "float32x2",
      led_index: "float32",
    },
  }],
});
```

```ts
import { init, geometry } from "vgpu/mock";

const gpu = await init();
const quadCorners = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);
const instanceData = new Float32Array(4 * 10);
const particles = geometry(gpu, {
  topology: "triangle-strip",
  buffers: [
    { data: quadCorners, attributes: { corner: "float32x2" } },
    { stepMode: "instance", data: instanceData, attributes: {
      i_pos: "float32x3",
      i_color: { format: "unorm8x4", location: 5 },
    } },
  ],
});
```

```ts
import { init, draw, geometry } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const vertexData = new Float32Array(3 * 4500);
const allIndices = new Uint32Array(4500);
const gltfGeometry = geometry(gpu, {
  buffers: [{ data: vertexData, attributes: { position: "float32x3" } }],
  indices: allIndices,
});
const hull = gltfGeometry.slice({ firstIndex: 0, indexCount: 3600 });
const glass = gltfGeometry.slice({ firstIndex: 3600, indexCount: 900, label: "glass" });
const pbrShader = prepareShader("@vertex fn vs_main(@location(0) position: vec3f) -> @builtin(position) vec4f { return vec4f(position, 1); }");

draw(gpu, { shader: pbrShader, geometry: hull }); // one prepared shader, reused by both slices
draw(gpu, { shader: pbrShader, geometry: glass, blend: "alpha" });
```

```ts
import { init, draw, geometry, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const glyphQuads = new Float32Array(4 * 4);
const quadIndices = new Uint16Array([0, 1, 2, 2, 1, 3]);
const text = geometry(gpu, {
  buffers: [{ data: glyphQuads, attributes: { pos: "float32x2", uv: "float32x2" } }],
  indices: quadIndices,
});
const sdfTextShader = prepareShader("@vertex fn vs_main(@location(0) pos: vec2f, @location(1) uv: vec2f) -> @builtin(position) vec4f { return vec4f(pos, 0, 1); }");
const textDraw = draw(gpu, { shader: sdfTextShader, geometry: text });
const colorTarget = target(gpu, { size: [640, 480] });

text.write(new Float32Array(4 * 4));
text.writeIndices(new Uint16Array([0, 1, 2, 2, 1, 3]));
textDraw.draw({ target: colorTarget, indices: 6 });
```

```ts
import { init, geometry } from "vgpu/mock";
import { box } from "vgpu/scene";

const gpu = await init();
const cube = geometry(gpu, box({ size: 2 }));
```

## Notes

* Layout is immutable; data is mutable. Changing formats, strides, topology, index format, or buffer identities requires a new geometry and a new draw.
* Auto stride is tight-packed and rounded up to 4 bytes. It never guesses padded data; pass `stride` when a writer emits padding.
* Slices share parent buffers and the same `vertexBufferLayouts` array identity so pipelines are shared.
* Draw-time range overrides use `DrawCallOptions.indices`, `firstIndex`, and `baseVertex`; non-indexed draws use existing `vertices` and `firstVertex`.
* Bundles bake counts and ranges at record time. Dynamic per-frame ranges need direct draws or bundle re-recording.
* Index padding is never drawn or written, and writes stay 4-byte aligned, so `writeIndices()` cannot rewrite the last index of an odd-length `Uint16Array`. To keep every index rewritable, pass an even-length array and set `indexCount` to the draw count.
* `destroy()` only destroys buffers owned from `data`/`indices`; caller-owned `buffer` and `indexBuffer` remain caller-owned.
* For repeated scene objects, [`instanceGeometry()`](/docs/reference/vgpu-scene-gpu/instance-geometry) borrows a live base mesh and adds an owned instance buffer. Destroying that bridge leaves the base mesh alive; destroying the base invalidates its composed draws and recorded bundles. Recreate affected draws/bundles before reuse. Known-dead geometry and slices are checked at encoding and bundle replay; raw `GPUBuffer.destroy()` outside the geometry lifecycle cannot be intercepted.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Gpu
description: The main API (`vgpu`) context returned by `init()`. It owns device lifetime and the frame clock; every resource — canvas surfaces, offscreen targets, render, compute, storage, uniforms, samplers, and bundles — is created by a free function that takes the `Gpu` as its first argument.
---

# Gpu



## Import

```ts
import type { Gpu } from "vgpu";
import { init } from "vgpu/mock";
```

## Signature

```ts
import type { Bundle, BundleOptions, BundleRecorder, Clock, Compute, ComputeOptions, Draw, DrawOptions, Effect, EffectOptions, Frame, FrameLoopHandle, FrameLoopOptions, Geometry, GeometryOptions, GeometryRecipe, GpuErrorListener, PingPongStorage, PingPongTargets, SharedUniforms, StorageAccess, StorageBuffer, StorageOptions, Surface, SurfaceOptions, Target, TargetOptions, TargetTextureOptions, Texture, TextureOptions, Timer, Visibility, VisibilityOptions } from "vgpu";
import type { Device } from "vgpu/core";
import type { ShaderSource } from "vgpu";

interface Gpu {
  readonly device: Device;
  readonly gpu: GPUDevice;
  /** Stable, never rejects. Resolves once with the native info when vgpu observes device loss while this gpu is active; stays pending otherwise. */
  readonly lost: Promise<GPUDeviceLostInfo>;
  /** True once `dispose()` ran. Reads stay legal; new work does not. */
  readonly disposed: boolean;
  dispose(): void;
  onError(cb: GpuErrorListener): () => void;
  /** Resolves once the queue work, error deliveries, and in-flight sources captured at call time complete. Never rejects; not a success signal. */
  settled(): Promise<void>;
}

// The creation API: named exports of `vgpu`, `vgpu/node` and `vgpu/mock`, all gpu-first.
declare function surface(gpu: Gpu, canvas: HTMLCanvasElement | OffscreenCanvas, opts?: SurfaceOptions): Surface;
declare function effect(gpu: Gpu, source: ShaderSource, opts?: EffectOptions): Effect;
declare function draw(gpu: Gpu, opts: DrawOptions): Draw;
declare function target(gpu: Gpu, opts: TargetOptions): Target;
declare function texture(gpu: Gpu, opts: TextureOptions): Texture;
// Private inference guard (not exported): rejects callbacks whose inferred return contains a Promise/PromiseLike.
type IsAny<T> = 0 extends (1 & T) ? true : false;
type SyncFrameCallback<R> = ((frame: Frame) => R)
  & (IsAny<R> extends true
    ? unknown
    : [Extract<R, PromiseLike<unknown>>] extends [never] ? unknown : never);
declare function frame(gpu: Gpu): Frame;
declare function frame<R>(gpu: Gpu, cb: SyncFrameCallback<R> | undefined): Frame;
declare function frameLoop<R>(gpu: Gpu, cb: SyncFrameCallback<R>, opts?: FrameLoopOptions): FrameLoopHandle;
declare function sampler(gpu: Gpu, desc?: GPUSamplerDescriptor): GPUSampler;
declare function geometry(gpu: Gpu, input: GeometryOptions | GeometryRecipe): Geometry;
declare function compute(gpu: Gpu, source: ShaderSource, opts?: ComputeOptions): Compute;
declare function storage(gpu: Gpu, bytes: number, access?: StorageAccess | StorageOptions): StorageBuffer;
declare function timer(gpu: Gpu): Timer;
declare function visibility(gpu: Gpu, options?: VisibilityOptions): Visibility;
declare function pingPong(gpu: Gpu, width: number, height: number, opts?: TargetTextureOptions): PingPongTargets;
declare function pingPongStorage(gpu: Gpu, bytes: number): PingPongStorage;
declare function uniforms<T extends Record<string, unknown>>(gpu: Gpu, values: T): SharedUniforms<T>;
declare function bundle(gpu: Gpu, opts: BundleOptions, record: (recorder: BundleRecorder) => void): Bundle;
declare function clock(gpu: Gpu): Clock;
```

## Parameters

`Gpu` is an object, not a callable constructor: it carries no creation methods. Every factory below takes it as `gpu`, its first argument.

| Param                 | Type                                                                      |         Required | Default        | Notes                                                                                                                                                                                                                                                                                                                                                         |                                                                                 |
| --------------------- | ------------------------------------------------------------------------- | ---------------: | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| surface.canvas        | `HTMLCanvasElement \| OffscreenCanvas`                                    |                ✔ | —              | Canvas-like object with a `webgpu` context. A canvas may have one live `Surface`.                                                                                                                                                                                                                                                                             |                                                                                 |
| surface.opts          | `SurfaceOptions`                                                          |                ✖ | `{}`           | Per-surface canvas format, size, DPR, and auto-resize behavior.                                                                                                                                                                                                                                                                                               |                                                                                 |
| effect.source         | `ShaderSource`                                                            |                ✔ | —              | Prepared `version: 2` artifact: a `.wgsl` import through the `@vgpu/wgsl` loader, a prebuilt artifact, or `prepareShader(wgsl)` from `@vgpu/wgsl/prepare` for runtime WGSL. Raw strings are rejected.                                                                                                                                                         |                                                                                 |
| effect.opts           | `EffectOptions`                                                           |                ✖ | `{}`           | `label` defaults to `"effect"`; `set` defaults to no initial bindings.                                                                                                                                                                                                                                                                                        |                                                                                 |
| draw\.opts            | `DrawOptions`                                                             |                ✔ | —              | Includes required `shader`, a prepared `ShaderSource` like `effect.source`; see `DrawOptions`.                                                                                                                                                                                                                                                                |                                                                                 |
| target.opts           | `TargetOptions`                                                           |                ✔ | —              | Offscreen target options. `size` is required.                                                                                                                                                                                                                                                                                                                 |                                                                                 |
| texture.opts          | `TextureOptions`                                                          |                ✔ | —              | Standalone sampled/storage texture. `size` and `format` are required; usage defaults to sampled, storage, and copy usage.                                                                                                                                                                                                                                     |                                                                                 |
| frame.cb              | `SyncFrameCallback<R> \| undefined` — a synchronous `(frame: Frame) => R` |                ✖ | `undefined`    | If provided, submits when the callback returns a non-thenable result and cancels (submits nothing) when it throws or returns a thenable (`VGPU-ASYNC-FRAME-CALLBACK`). Inferred `Promise`/`PromiseLike` returns fail to typecheck. If omitted — `frame(gpu)` or `frame(gpu, undefined)` — caller must call `frame.submit()` or `frame.cancel()`. See `Frame`. |                                                                                 |
| frameLoop.cb          | `SyncFrameCallback<R>` — a synchronous `(frame: Frame) => R`              |                ✔ | —              | Runs once per animation frame with the `frame.cb` rule; a tick that throws or returns a thenable stops the loop. Registration does not run the callback. See `Frame`.                                                                                                                                                                                         |                                                                                 |
| frameLoop.opts        | `FrameLoopOptions`                                                        |                ✖ | `{}`           | `fps` caps the tick rate; omitted runs every animation frame.                                                                                                                                                                                                                                                                                                 |                                                                                 |
| sampler.desc          | `GPUSamplerDescriptor`                                                    |                ✖ | `undefined`    | Cached by descriptor. `sampler(gpu)` is the canonical default sampler.                                                                                                                                                                                                                                                                                        |                                                                                 |
| geometry.input        | \`GeometryOptions \\                                                      | GeometryRecipe\` | ✔              | —                                                                                                                                                                                                                                                                                                                                                             | A raw buffer descriptor, or a `vgpu/scene` recipe such as `box()` or `plane()`. |
| compute.source        | `ShaderSource`                                                            |                ✔ | —              | Prepared artifact, as for `effect.source`. Must contain a `@compute` entry point.                                                                                                                                                                                                                                                                             |                                                                                 |
| compute.opts          | `ComputeOptions`                                                          |                ✖ | `{}`           | `label` defaults to `"compute"`; `set` defaults to no initial bindings.                                                                                                                                                                                                                                                                                       |                                                                                 |
| storage.bytes         | `number`                                                                  |                ✔ | —              | Byte size for a main API (`vgpu`) storage buffer.                                                                                                                                                                                                                                                                                                             |                                                                                 |
| storage.access        | `StorageAccess \| StorageOptions`                                         |                ✖ | `"read-write"` | Access string, or a `StorageOptions` bag `{ access?, indirect? }`. See `Compute` for storage buffer semantics, including `{ indirect: true }` for GPU-driven draw/dispatch arguments.                                                                                                                                                                         |                                                                                 |
| timer                 | —                                                                         |                — | —              | No parameters. GPU pass timing; needs the `"timestamp-query"` device feature. See `Timer` for feature gating, spans, and result delivery.                                                                                                                                                                                                                     |                                                                                 |
| visibility.options    | `VisibilityOptions`                                                       |                ✖ | `{}`           | Occlusion queries for visibility culling — core WebGPU, no device feature required. See `Visibility` for capacity and handle semantics.                                                                                                                                                                                                                       |                                                                                 |
| pingPong.width        | `number`                                                                  |                ✔ | —              | Floored and clamped to at least `1`.                                                                                                                                                                                                                                                                                                                          |                                                                                 |
| pingPong.height       | `number`                                                                  |                ✔ | —              | Floored and clamped to at least `1`.                                                                                                                                                                                                                                                                                                                          |                                                                                 |
| pingPong.opts         | `TargetTextureOptions`                                                    |                ✖ | `{}`           | Texture/attachment options only; size comes from positional width/height.                                                                                                                                                                                                                                                                                     |                                                                                 |
| pingPongStorage.bytes | `number`                                                                  |                ✔ | —              | Creates two `"read-write"` storage buffers.                                                                                                                                                                                                                                                                                                                   |                                                                                 |
| uniforms.values       | `Record<string, unknown>`                                                 |                ✔ | —              | Cloned initial JS values; WGSL layout is adopted when first bound.                                                                                                                                                                                                                                                                                            |                                                                                 |
| bundle.opts           | `BundleOptions`                                                           |                ✔ | —              | Requires a `target` or target signature.                                                                                                                                                                                                                                                                                                                      |                                                                                 |
| bundle.cb             | `(recorder: BundleRecorder) => void`                                      |                ✔ | —              | Records bundle commands immediately.                                                                                                                                                                                                                                                                                                                          |                                                                                 |
| onError.cb            | `GpuErrorListener`                                                        |                ✔ | —              | Receives asynchronous vgpu errors; returns an unsubscribe function.                                                                                                                                                                                                                                                                                           |                                                                                 |
| clock                 | —                                                                         |                — | —              | No parameters. The frame clock of this gpu: `{ time, deltaTime, frameCount, advance(dtSeconds) }`, one instance per gpu. See `Clock`.                                                                                                                                                                                                                         |                                                                                 |

**Returns:** each factory returns the resource named in its signature. `dispose()` returns `void`. Frame callbacks are synchronous: a non-thenable return value is ignored. `onError(cb)` returns its unsubscribe function. `settled()` returns a `Promise<void>` that always fulfills — see "Wait for submitted work" below. `gpu.lost` is a property, not a method: the same `Promise<GPUDeviceLostInfo>` on every read — see "Device loss" below.

**Throws:** `VGPU-GPU-DISPOSED` when any factory (or `clock(gpu)`) runs after `gpu.dispose()` — the device and everything it owned are gone, so the handle it would return could only fail later; create resources before disposing, or `init()` a new gpu; `VGPU-DEVICE-LOST` when any factory (or `clock(gpu)`, `frame(gpu)`, `frameLoop(gpu)`) runs on an active gpu after vgpu observed device loss — thrown at the call, before the frame clock advances or surface auto-resize runs, with `cause` set to the native `GPUDeviceLostInfo`; create a new Gpu with `init()`, then recreate its resources and restart the loop (after `gpu.dispose()`, `VGPU-GPU-DISPOSED` takes precedence); `VGPU-GPU-FOREIGN` when the first argument was not created by `init()` (a plain object, a `GPUDevice`, a gpu from another library): it carries no vgpu kernel, so pass the object returned by `init()` from `vgpu`, `vgpu/node` or `vgpu/mock`; `VGPU-LIMIT-STORAGE-VERTEX` / `VGPU-LIMIT-STORAGE-FRAGMENT` when a selected render entry exceeds its granted storage-buffer limit. The structured detail reports `stage`, `entryPoint`, `count`, `limit`, and each counted binding's `name`, `group`, and `binding`; request a supported limit or reduce/move the data; `VGPU-SHADER-SOURCE-UNPREPARED` when `effect`, `draw`, or `compute` receives a raw WGSL string or a `version: 1` artifact — import the `.wgsl` file through a compatible `@vgpu/wgsl` loader, rebuild prebuilt assets, or pass `prepareShader(wgsl)` from `@vgpu/wgsl/prepare`; `VGPU-SHADER-SOURCE-VERSION` when the artifact's `version` is an integer other than `2` — the message names the received version, the supported version, and the artifact's `producer`; align the `@vgpu/wgsl` tooling and `vgpu` runtime versions, then regenerate; `VGPU-SHADER-SOURCE-INVALID` when the artifact is not an object, a required field is missing, accessor-backed, or malformed, the reflection metadata is inconsistent, or `sourceChecksum` does not match `wgsl` — the structured detail gives the field `path` and the `reason`; regenerate with a supported producer. All three throw synchronously from the factory; `VGPU-SET-VALUE-INVALID` when a JS-owned buffer value does not exactly match its reflected WGSL shape, integer range, or runtime extent; `VGPU-SET-TEXTURE-FILTERABILITY` when a known facade texture format cannot satisfy an ordinarily sampled float binding (detail reports format, texture binding/name/label, and paired sampler identity); `VGPU-RING1-UNSUPPORTED` for unsupported effect/compute/target cases; `VGPU-TARGET-REQUIRED` when one-shot drawing needs an explicit target; `VGPU-TARGET-SIZE-REQUIRED` for runtime JS calls to `target(gpu)` without `size`; `VGPU-SURFACE-*` errors from `surface()`, surface resize, surface readback, or using disposed surfaces; `VGPU-ASYNC-FRAME-CALLBACK` when a `frame(gpu, cb)` / `frameLoop(gpu, cb)` callback returns a thenable — the open frame is canceled before its implicit submit, so await preparation before `frame()`/`frameLoop()` and keep the frame callback synchronous; plus method-specific `VGPU-R1-*`, `VGPU-R3-*`, and `VGPU-R4-*` errors documented on `Effect`, `Draw`, `Compute`, `Frame`, `Bundle`, `Target`, and `SharedUniforms`.

## Examples

```ts
import { init, draw, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [128, 128], depth: true });
const drawable = draw(gpu, {
  shader: prepareShader(`
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0, 1);
    }
    @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1, 0, 1, 1); }
  `), // no loader in tests: prepare the runtime WGSL once
  // optional sync pre-warm; `await draw.compile(target)` is preferred during browser load
  targets: [colorTarget],
});

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: colorTarget, clear: [0, 0, 0, 1] }, (pass) => pass.draw(drawable));
});
```

```ts
import { init, effect, frameLoop, surface } from "vgpu";
import waveShader from "./wave.wgsl"; // prepared at build time by the @vgpu/wgsl loader

declare const canvas: HTMLCanvasElement;

const gpu = await init();
const canvasSurface = surface(gpu, canvas, { dpr: [1, 2] });
const wave = effect(gpu, waveShader);

frameLoop(gpu, (frame) => {
  frame.pass({ target: canvasSurface }, (pass) => pass.draw(wave));
});
```

## Error delivery

`gpu.onError(cb)` subscribes to asynchronous vgpu errors and returns an unsubscribe function. Listeners run in subscription order; removing one stops future deliveries; a throwing listener is reported to `console.error` without stopping the rest. If no listener is registered, vgpu reports the error to `console.error` by default.

`gpu.settled()` resolves after the work captured when you call it completes: GPU queue work already submitted, pending error deliveries, and in-flight pipeline work. This includes compute compilation and native compute validation through error delivery, so `onError` listeners for those failures have already run when it fulfills. It never rejects, so it is safe for deterministic tests and teardown. It is not a successful-execution assertion: await a pipeline’s `compile()` to handle compilation rejection and subscribe to `onError` for asynchronous execution failures.

## Wait for submitted work

`settled()` takes a snapshot synchronously, before it awaits anything, and waits for exactly that snapshot:

* **Submitted queue work.** While the gpu is active, the call captures a WebGPU `queue.onSubmittedWorkDone()` fence. It covers everything already submitted to the device queue: `frame(gpu, cb)` callbacks that returned, `frame.submit()`, one-shot `drawable.draw(target)` and `compute.dispatch()` calls, and raw `gpu.gpu.queue.submit()` calls on the same queue.
* **Pending error deliveries** queued for `onError`.
* **In-flight sources** tracked by vgpu at call time, such as pipeline compilation and native validation. Errors these sources report through `onError` are delivered before the call fulfills.

Work that starts after the call returns does not extend it: later submissions, new pipelines, and deliveries unrelated to the captured sources belong to the next `settled()` call. A manual `frame(gpu)` that is still open — not yet submitted or cancelled — is not queue work, so `settled()` neither waits for it nor submits it.

```ts
import { init, draw, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [64, 64] });
const triangle = draw(gpu, {
  shader: prepareShader(`
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0, 1);
    }
    @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1, 0.5, 0, 1); }
  `),
});

// ---cut---
triangle.draw(colorTarget); // one-shot draw: encodes and submits immediately
const drawDone = gpu.settled(); // captures the queue fence for that submission now
triangle.draw(colorTarget); // submitted after the call — not part of drawDone
await drawDone;
```

`drawDone` fulfills once the first submission completes on the GPU. The second draw is outside its snapshot; call `settled()` again to wait for it.

Because `settled()` waits for the GPU to finish queued work, it can take as long as that work takes — longer than awaiting deliveries and pipelines alone. Fulfillment means completion, not success: a failed submission, an invalid pipeline, or a lost device still fulfills it, and failures stay on their existing channels.

* `settled()` never rejects and never reports an error of its own. When the queue has no `onSubmittedWorkDone()` method (some mocks), the method throws synchronously, or its promise rejects, `settled()` skips that fence and still fulfills — `onError` receives nothing extra.
* A pipeline's `compile()` rejection stays on that `compile()` promise. `settled()` waits for the compilation without turning its rejection into an `onError` delivery; handle rejection on the `compile()` promise itself.
* Asynchronous execution and validation failures arrive once, through `onError`, whether or not you await `settled()`.

### After device loss or `dispose()`

When vgpu has already observed device loss, or `gpu.dispose()` already ran, `settled()` creates no new queue fence: there is no usable queue to wait on. It still waits for the deliveries and sources vgpu is tracking at that moment. `dispose()` stops tracking in-flight pipeline compilations as part of normal teardown, so after `dispose()` the call waits only for deliveries that were already pending.

Loss or disposal that happens after the call does not shorten it: a fence and sources already captured keep their wait. `settled()` does not wait for device loss, and it does not restart or recover a lost device.

### Choose compile, settled, or readback

Await only the promise that answers your question:

| You need                                                                                                                     | Await                                                                                                                                                             | What it waits for                                                      |
| ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| A pipeline ready before its first frame, or its compilation failure as a rejection                                           | `drawable.compile(target)`, `fullscreenEffect.compile(target)`, `simulation.compile()`                                                                            | That one pipeline. Rejects on compilation failure.                     |
| The pixels or bytes a GPU pass produced                                                                                      | `colorTarget.color.read({ mipLevel: 0, region: "all" })`, `colorTarget.color.readFloats({ mipLevel: 0, region: "all" })`, `particles.read()` on a `StorageBuffer` | The copy it issues, which runs after the work that wrote the resource. |
| Submitted queue work and tracked asynchronous work to finish: before assertions on `onError`, between tests, before teardown | `gpu.settled()`                                                                                                                                                   | The call-time snapshot above. Never rejects.                           |

If you only need pixels or bytes, await the readback directly: its copy is ordered after earlier queue work. Await `settled()` separately when you also need its tracked error deliveries or pipeline work. Keep these waits outside frame callbacks; waiting after every frame serializes encoding with GPU completion and reduces the overlap between CPU encoding and GPU execution.

### Teardown

Subscribe to `onError` for asynchronous failures, await `compile()` for compilation failures, then `await gpu.settled()` before `gpu.dispose()` so submitted work and pending deliveries finish first:

```ts
import { init, effect, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const errors: string[] = [];
gpu.onError((error) => errors.push(error.code)); // asynchronous failures arrive here, once

const colorTarget = target(gpu, { size: [64, 64] });
const tint = await effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.2, 0.4, 1.0, 1.0); }`)).compile(colorTarget); // compilation failures reject here

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: colorTarget, clear: [0, 0, 0, 1] }, (pass) => pass.draw(tint));
});

await gpu.settled(); // the submitted frame and pending deliveries have completed
console.log(errors); // every error reported for that work has been delivered
gpu.dispose();
```

`settled()` fulfills even if the frame failed; read `errors` to find out. `dispose()` is the teardown signal — it stops loops and releases resources; do not wait for device loss to tear down a gpu you own. For a gpu from `initFromDevice(device)`, `dispose()` releases the vgpu wrapper and leaves the borrowed device to its owner.

## Device loss

`gpu.lost` is a loss-only notification. It is one stable `Promise<GPUDeviceLostInfo>` — every read returns the same promise — that resolves once, with the native `GPUDeviceLostInfo`, when vgpu observes native device loss while the gpu is active. It never rejects, even when the native `GPUDevice.lost` promise rejects. If the device is never lost, or `gpu.dispose()` runs first, it stays pending forever.

When vgpu observes the loss, it stops every running `frameLoop(gpu, cb)` first and only then resolves `gpu.lost`, so your handlers run after the loops are already stopped: no further tick runs, and no tick throws `VGPU-DEVICE-LOST`. Nothing else happens automatically:

* The gpu is not disposed: `gpu.disposed` stays `false`, and `gpu.dispose()`, `gpu.onError(cb)`, and `gpu.settled()` stay callable.
* Resources are not destroyed. vgpu does not release your targets, surfaces, or pipelines for you; `gpu.dispose()` does that.
* Nothing is delivered to `gpu.onError` for the loss itself. Errors already in flight — a `frame.done` validation, a pipeline compilation — keep their existing channels and arrive at most once, as before.
* Nothing recovers. The lost device cannot be reused.

New work on the lost gpu throws `VGPU-DEVICE-LOST` at the call: every factory, `clock(gpu)`, `frame(gpu)`, and `frameLoop(gpu, cb)`. `frame(gpu)` and `frameLoop(gpu, cb)` throw before the frame clock advances and before surface auto-resize runs. A manual `frame(gpu)` that was open when the device was lost stays open: its `submit()` throws `VGPU-DEVICE-LOST` with `cause` set to the native info, until `gpu.dispose()` cancels it and `submit()` becomes a no-op.

The implicit submit reports its own failures: whatever `frame.submit()` throws after a `frame(gpu, cb)` callback returns escapes `frame(gpu, cb)`, and a loop tick that fails this way stops the loop and rethrows, like a throwing callback. vgpu no longer swallows a `VGPU-DEVICE-LOST` or `VGPU-DEVICE-DISPOSED` raised there. Calling `gpu.dispose()` from inside the callback is still safe: `dispose()` cancels the open frame and stops the loop, so the implicit submit is a no-op. Disposing the core device directly (`gpu.device.dispose()`) is not `gpu.dispose()` — it cancels nothing, so the implicit submit throws `VGPU-DEVICE-DISPOSED`; tear down with `gpu.dispose()`.

### Recover from device loss

Recovery is explicit: dispose the lost gpu, create a new one with `init()`, recreate its resources, and restart the loop.

```wgsl
// background.wgsl
@fragment fn fs_main() -> @location(0) vec4f {
  return vec4f(0.1, 0.3, 0.6, 1.0);
}
```

```ts
import { init, effect, frameLoop, surface } from "vgpu";
import backgroundShader from "./background.wgsl";

const canvas = document.querySelector("canvas")!;
const statusBanner = document.querySelector("#gpu-status")!;

// ---cut---
async function start(): Promise<void> {
  const gpu = await init();
  const canvasSurface = surface(gpu, canvas);
  const background = effect(gpu, backgroundShader);
  frameLoop(gpu, (currentFrame) => {
    currentFrame.pass(canvasSurface, background);
  });

  void gpu.lost
    .then((info) => {
      // the loop already stopped; gpu.disposed is still false
      statusBanner.textContent = `GPU lost (${info.reason}), restarting…`;
      gpu.dispose(); // release the old surface before a new gpu configures the canvas
      return start(); // new Gpu, new resources, new loop
    })
    .catch((error: unknown) => {
      statusBanner.textContent = "The GPU could not be restarted.";
      console.error(error);
    });
}

await start();
```

`gpu.lost` cannot reject, but your handler can: `init()` may reject on the restart, and DOM code may throw. The `.catch()` handles failures of your recovery path, not of `gpu.lost`. Dispose the lost gpu before creating the new surface — disposing a surface unconfigures its canvas, so disposing the old gpu afterwards would unconfigure the canvas under the new one.

<Callout type="warn">
  Warning: Do not `await gpu.lost` to tear down. It stays pending for a healthy device and after `gpu.dispose()`, so teardown would hang. Normal unmount is unchanged: stop the loop, `await gpu.settled()` when you need submitted work and deliveries to finish, then `gpu.dispose()`.
</Callout>

### Loss versus disposal

`gpu.dispose()` is your own teardown, not loss. What decides the outcome is whether vgpu observed the loss before `dispose()` ran — vgpu reads the native `GPUDevice.lost` promise asynchronously — not the native `reason`:

| Sequence                                                                                                          | `gpu.lost`                           | `gpu.disposed` | Loops                                  | Open manual frame's `submit()` | Native device                                        |
| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------ | -------------- | -------------------------------------- | ------------------------------ | ---------------------------------------------------- |
| Native loss observed while the gpu is active                                                                      | Resolves with the native info        | `false`        | Stopped before `gpu.lost` handlers run | Throws `VGPU-DEVICE-LOST`      | Lost                                                 |
| `gpu.dispose()` before vgpu observes loss, including a loss the native promise reported but vgpu had not read yet | Stays pending                        | `true`         | Stopped by `dispose()`                 | No-op: `dispose()` canceled it | Owned: destroyed by `dispose()`. Borrowed: untouched |
| `gpu.dispose()` after observed loss                                                                               | Keeps its resolved value             | `true`         | Already stopped                        | No-op: `dispose()` canceled it | Owned: not destroyed again. Borrowed: untouched      |
| The owner destroys a borrowed device while the wrapper is active                                                  | Resolves, with `reason: "destroyed"` | `false`        | Stopped before `gpu.lost` handlers run | Throws `VGPU-DEVICE-LOST`      | Destroyed by its owner                               |

For a gpu from `initFromDevice(device)`, `gpu.dispose()` never destroys the borrowed device, and a loss that arrives after it is not reported. A destroy by the device's owner while the wrapper is active is a loss like any other, even though its reason is `"destroyed"`.

`gpu.settled()` never waits for `gpu.lost`. A `settled()` call made before the loss keeps the queue fence, deliveries, and sources it already captured; one made after the loss or after `dispose()` creates no new fence — see "After device loss or `dispose()`" above.

## Notes

* There is no implicit screen property and no implicit default target. Pass `target` explicitly to frame passes and one-shot draws.
* Canvas-specific `size`, `dpr`, and `autoResize` live on `surface(gpu, canvas, opts)`, not on `init()`.
* Time is explicit JS state, and it lives on the clock, not on the context: read `clock(gpu).time` / `.deltaTime` / `.frameCount` and pass them through `set()` or `SharedUniforms` when shaders need them.
* Await asynchronous setup — `await init()`, `await simulation.compile()` on a `Compute`, asset loading — before `frame(gpu, cb)` or `frameLoop(gpu, cb)`, and run async teardown such as `await gpu.settled()` after the frame returns or the loop is stopped. The frame callback itself stays synchronous.
* Every factory rejects a disposed gpu with `VGPU-GPU-DISPOSED`, an active gpu whose device loss vgpu observed with `VGPU-DEVICE-LOST`, and an object vgpu did not create with `VGPU-GPU-FOREIGN`. All three are thrown synchronously, from the call that made the mistake.
* Subscribe to `gpu.lost`, not to the native `gpu.gpu.lost`, when you need the loops stopped first. Only `gpu.lost` handlers are guaranteed to run after vgpu stops the loops; a handler on the native promise — for example one the owner of a borrowed device attached before `initFromDevice(device)` — can run first.
* There is no lifecycle-state getter, no loss event channel, and no public way to simulate loss in `vgpu/mock`. Read `gpu.disposed` for your own teardown and subscribe to `gpu.lost` for loss.
* **See also:** `init`, `Device`, `Clock`, `Surface`, `Effect`, `Draw`, `Compute`, `Frame`, `Target`, `Bundle`, `SharedUniforms`, `Timer`, `Visibility`.

## Sampled float texture layouts

vgpu infers sampled-texture layouts per selected WGSL entry point. A non-multisampled `texture_*<f32>` used by `textureSample*` or `textureGather*` with an ordinary sampler receives WebGPU `sampleType: "float"`; a texture used only by `textureLoad` remains `"unfilterable-float"`. Calls through helper functions are included.

The WGSL `f32` scalar type does not make every concrete texture format filterable. In particular, `r32float`, `rg32float`, and `rgba32float` require the device's `float32-filterable` feature for ordinary sampling. Use a filterable format, request that feature when supported, or use `textureLoad` without a sampler.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: init
description: Creates the public `Gpu` context. `init()` creates the device only; canvas-backed rendering is explicit through `surface(gpu, canvas, opts)`.
---

# init



## Import

```ts
import { init } from "vgpu";
```

Browser code imports from `vgpu`; Node GPU tests import from `vgpu/node`; deterministic unit tests import from `vgpu/mock`.

## Signature

```ts
import type { Gpu } from "vgpu";
import type { RequiredDeviceLimits, VGPUAdapter } from "vgpu/core";

declare function init(options?: InitOptions): Promise<Gpu>;

interface InitOptions {
  readonly adapter?: VGPUAdapter;
  readonly powerPreference?: GPUPowerPreference;
  readonly requiredFeatures?: readonly GPUFeatureName[];
  readonly requiredLimits?: RequiredDeviceLimits;
  readonly label?: string;
}
```

## Parameters

| Param                    | Type                        | Required | Default     | Notes                                                                                                                                                                                                                                                                                                                                                          |
| ------------------------ | --------------------------- | -------: | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| options                  | `InitOptions`               |        ✖ | `{}`        | Device creation options only. Canvas size, DPR, and auto-resize belong to `surface(gpu, canvas, opts)`.                                                                                                                                                                                                                                                        |
| options.adapter          | `VGPUAdapter`               |        ✖ | `undefined` | Explicit adapter. If omitted in `vgpu`, `navigator.gpu.requestAdapter()` is used; `vgpu/node` and `vgpu/mock` provide adapter factories.                                                                                                                                                                                                                       |
| options.powerPreference  | `GPUPowerPreference`        |        ✖ | `undefined` | Forwarded to `navigator.gpu.requestAdapter({ powerPreference })`.                                                                                                                                                                                                                                                                                              |
| options.requiredFeatures | `readonly GPUFeatureName[]` |        ✖ | `undefined` | Optional device features to enable, forwarded to `adapter.requestDevice` (e.g. `"depth-clip-control"` for `DrawOptions.unclippedDepth`). Checked against the adapter's supported features first: a name the adapter lacks fails init with `VGPU-FEATURE-UNSUPPORTED` instead of a native rejection. `device.features` reflects exactly the requested features. |
| options.requiredLimits   | `RequiredDeviceLimits`      |        ✖ | `undefined` | Forwarded unchanged to `adapter.requestDevice`. Unsupported names/values reject device creation.                                                                                                                                                                                                                                                               |
| options.label            | `string`                    |        ✖ | `undefined` | Reserved public option; current main API (`vgpu`) device creation does not use it as a debug label.                                                                                                                                                                                                                                                            |

**Returns:** `Promise<Gpu>` — the context every factory takes first: `surface(gpu, ...)`,
`target(gpu, ...)`, `draw(gpu, ...)`, `effect(gpu, ...)`, `compute(gpu, ...)`, `geometry(gpu, ...)`,
`frame(gpu, cb)` / `frameLoop(gpu, cb)`, `storage(gpu, ...)`, `uniforms(gpu, ...)`,
`sampler(gpu, ...)`, and `bundle(gpu, ...)`. Each call returns an independent `Gpu` with its own
device and its own `gpu.lost` promise.

**Throws:** `VGPU-RING1-UNSUPPORTED` when WebGPU is unavailable, adapter request returns `null`, or an entrypoint lacks an adapter factory — use `vgpu/mock` in tests, `vgpu/node` in Node, or pass a valid adapter; `VGPU-FEATURE-UNSUPPORTED` when `requiredFeatures` names a feature the adapter does not support — remove the unsupported name(s) or run on an adapter that supports them.

## Examples

```ts
import { init, effect, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [64, 64], format: "rgba8unorm" });
const shader = effect(gpu, prepareShader(`
  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return vec4f(uv, 0.0, 1.0);
  }
`));

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: colorTarget }, (p) => p.draw(shader));
});
```

```wgsl
// surface-white.wgsl
@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }
```

```ts
import { init, effect, frame, surface } from "vgpu";
import whiteShader from "./surface-white.wgsl";

declare const canvas: HTMLCanvasElement;

const gpu = await init({
  // Request only when a vertex entry actually reads storage and the adapter supports it.
  requiredLimits: { maxStorageBuffersInVertexStage: 1 },
});
const canvasSurface = surface(gpu, canvas, { dpr: [1, 2] });
const shader = effect(gpu, whiteShader);

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: canvasSurface }, (p) => p.draw(shader));
});
```

```ts
import { init, createMockAdapter, timer } from "vgpu/mock";

// Feature-gated device: GPU pass timing needs "timestamp-query".
const gpu = await init({
  adapter: createMockAdapter({ features: ["timestamp-query"] }),
  requiredFeatures: ["timestamp-query"],
});
const gpuTimer = timer(gpu);
gpuTimer.onResults((spans) => console.table(spans));
```

The granted feature makes `timer(gpu)` succeed. In a browser, drop the `adapter` option — `requiredFeatures` is forwarded to the real adapter the same way.

## Notes

* Choose the entrypoint for the runtime: use `vgpu` in browsers with WebGPU; use `vgpu/node` for headless Node rendering with a real adapter; use `vgpu/mock` for deterministic tests that do not require a GPU. Keep application code on the same `init(options?)` shape so the switch is local.
* Request optional features only when a code path uses them: `"timestamp-query"` enables `timer(gpu)`, `"depth-clip-control"` enables `DrawOptions.unclippedDepth`, and `"indirect-first-instance"` enables indirect draws that provide a non-zero first instance. Do not request features speculatively; unsupported names fail `init`.
* In tests, declare and request a mock feature explicitly: `init({ adapter: createMockAdapter({ features: ["timestamp-query"] }), requiredFeatures: ["timestamp-query"] })` lets you exercise feature gates instead of silently relying on defaults.
* `init(canvas)` is intentionally not supported. Create surfaces explicitly with `surface(gpu, canvas)`.
* `size`, `dpr`, and `autoResize` are `SurfaceOptions`, not `InitOptions`.
* The browser, node, and mock entrypoints all use the same `init(options?)` shape.
* `init()` is also how you recover from device loss. vgpu never replaces a lost device: when `gpu.lost` resolves, the loops are already stopped and new work on that gpu throws `VGPU-DEVICE-LOST`. Dispose it, call `init()` again, recreate the resources on the new gpu, and restart the loop. See `Gpu` ("Device loss") for the full sequence.
* In `vgpu/mock`, the default adapter declares no optional features. Pass `adapter: createMockAdapter({ features: [...] })` to test feature-gated paths deterministically; `requiredFeatures` outside that set fails with `VGPU-FEATURE-UNSUPPORTED`, and granted features appear on `gpu.device.features`.
* **See also:** `Gpu`, `Surface`, `Target`, `FrameRunner`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Surface
description: Canvas-backed render target created by `surface(gpu, canvas, opts)`. Use it for browser canvases, `OffscreenCanvas`, multi-canvas rendering, and resize-driven derived targets. Opt into an owned depth attachment and 4× MSAA with `depth` and `msaa` to render depth-tested, antialiased 3D straight to the canvas.
---

# Surface



## Import

```ts
import type { Surface, SurfaceOptions, SurfaceResizeEvent } from "vgpu";
```

## Signature

```ts
import type { ClearColor, Target } from "vgpu";

interface SurfaceOptions {
  readonly autoResize?: boolean;
  readonly clearColor?: ClearColor;
  readonly dpr?: number | readonly [number, number];
  readonly size?: readonly [number, number];
  readonly format?: GPUTextureFormat;
  readonly alphaMode?: GPUCanvasAlphaMode;
  readonly colorSpace?: PredefinedColorSpace;
  readonly depth?: boolean | GPUTextureFormat;
  readonly msaa?: boolean | 4;
  readonly label?: string;
}

interface SurfaceResizeEvent {
  readonly width: number;
  readonly height: number;
  readonly dpr: number;
  readonly surface: Surface;
}

interface Surface extends Target {
  readonly canvas: HTMLCanvasElement | OffscreenCanvas;
  readonly context: GPUCanvasContext;
  readonly autoResize: boolean;
  readonly layoutBacked: boolean;
  readonly dpr: number;
  readonly disposed: boolean;
  onResize(cb: (event: SurfaceResizeEvent) => void): () => void;
  dispose(): void;
}
```

## Parameters

| Param               | Type                                   | Required | Default                                                                                                            | Notes                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| ------------------- | -------------------------------------- | -------: | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| surface.canvas      | `HTMLCanvasElement \| OffscreenCanvas` |        ✔ | —                                                                                                                  | Must return a `GPUCanvasContext` from `getContext("webgpu")`.                                                                                                                                                                                                                                                                                                                                                                                                     |
| surface.opts        | `SurfaceOptions`                       |        ✖ | `{}`                                                                                                               | Canvas configuration, attachments, and resize behavior. Canvas configuration and depth/MSAA options are fixed at construction; see individual fields for resize behavior.                                                                                                                                                                                                                                                                                         |
| opts.autoResize     | `boolean`                              |        ✖ | `true` for layout-backed canvases, `false` when `size` is provided or when the canvas has no numeric `clientWidth` | Auto-resize is checked at the frame boundary before user frame callbacks. Explicit `true` on buffer-only canvases throws.                                                                                                                                                                                                                                                                                                                                         |
| opts.dpr            | `number \| readonly [number, number]`  |        ✖ | `globalThis.devicePixelRatio ?? 1`                                                                                 | Number fixes DPR. Tuple clamps runtime DPR to `[min, max]`; layout-backed surfaces re-read DPR each frame.                                                                                                                                                                                                                                                                                                                                                        |
| opts.size           | `readonly [number, number]`            |        ✖ | Layout-backed: `clientWidth/clientHeight × dpr`; buffer-only: existing `canvas.width/height`                       | Physical pixel size. When provided, initial canvas buffer is set and `autoResize` defaults to `false`.                                                                                                                                                                                                                                                                                                                                                            |
| opts.format         | `GPUTextureFormat`                     |        ✖ | `navigator.gpu.getPreferredCanvasFormat() ?? "bgra8unorm"`                                                         | Canvas swapchain format. Also the format of the private MSAA color attachment when `msaa` is enabled.                                                                                                                                                                                                                                                                                                                                                             |
| opts.alphaMode      | `GPUCanvasAlphaMode`                   |        ✖ | `"premultiplied"`                                                                                                  | Passed to `GPUCanvasContext.configure`.                                                                                                                                                                                                                                                                                                                                                                                                                           |
| opts.colorSpace     | `PredefinedColorSpace`                 |        ✖ | `"srgb"`                                                                                                           | Passed to `GPUCanvasContext.configure`.                                                                                                                                                                                                                                                                                                                                                                                                                           |
| opts.clearColor     | `ClearColor`                           |        ✖ | `[0, 0, 0, 1]`                                                                                                     | Default clear color of this surface, used by passes that clear without naming one. Writable at runtime as `surface.clearColor`; a pass `clear` color still wins for that pass. Four finite numbers, or a `GPUColor` object.                                                                                                                                                                                                                                       |
| opts.depth          | `boolean \| GPUTextureFormat`          |        ✖ | `undefined` — no depth attachment                                                                                  | `true` allocates an owned `"depth24plus"` attachment. A string selects `"depth16unorm"`, `"depth24plus"`, `"depth24plus-stencil8"`, `"depth32float"`, or `"depth32float-stencil8"`; any other value, including color formats and stencil-only `"stencil8"`, throws `VGPU-SURFACE-DEPTH-INVALID`. `false` is the same as omitting it. Native format features still apply: `"depth32float-stencil8"` needs `init({ requiredFeatures: ["depth32float-stencil8"] })`. |
| opts.msaa           | `boolean \| 4`                         |        ✖ | `undefined` — sample count `1`                                                                                     | `true` or `4` renders through a private 4-sample color attachment that resolves into the canvas texture, and gives the depth attachment 4 samples. `false` is the same as omitting it. Any other value, including `1`, `2`, `8`, and `"4"`, throws `VGPU-SURFACE-MSAA-INVALID`. There is no `sampleCount` option; `surface.sampleCount` reports the resolved `1` or `4`.                                                                                          |
| opts.label          | `string`                               |        ✖ | `undefined`                                                                                                        | Used in error messages and texture labels.                                                                                                                                                                                                                                                                                                                                                                                                                        |
| onResize.cb         | `(event: SurfaceResizeEvent) => void`  |        ✔ | —                                                                                                                  | Called synchronously immediately on subscription and after future size changes.                                                                                                                                                                                                                                                                                                                                                                                   |
| event.width         | `number`                               |        ✔ | —                                                                                                                  | Physical pixel width, equal to `surface.size[0]` and `canvas.width`.                                                                                                                                                                                                                                                                                                                                                                                              |
| event.height        | `number`                               |        ✔ | —                                                                                                                  | Physical pixel height, equal to `surface.size[1]` and `canvas.height`.                                                                                                                                                                                                                                                                                                                                                                                            |
| event.dpr           | `number`                               |        ✔ | —                                                                                                                  | Effective DPR used for the current size.                                                                                                                                                                                                                                                                                                                                                                                                                          |
| event.surface       | `Surface`                              |        ✔ | —                                                                                                                  | Surface that resized, useful for shared handlers.                                                                                                                                                                                                                                                                                                                                                                                                                 |
| surface.resize.size | `readonly [number, number]`            |        ✔ | —                                                                                                                  | Manual physical pixel size. Values are floored and clamped to at least `1`.                                                                                                                                                                                                                                                                                                                                                                                       |

**Returns:** `surface(gpu)` returns `Surface`; `onResize()` returns an unsubscribe function; `dispose()` returns `void`. `surface.depth` is the owned depth `Texture`, or `undefined` without `depth`; `surface.sampleCount` is `1` or `4`; `surface.color` is the current canvas texture, always single-sample.

**Throws:**

* `VGPU-SURFACE-CONTEXT` when `getContext("webgpu")` returns `null` — pass a canvas that supports WebGPU.
* `VGPU-SURFACE-DUPLICATE` when a live surface already owns the canvas — call `dispose()` on the old surface first.
* `VGPU-SURFACE-AUTORESIZE-UNSUPPORTED` for explicit `autoResize: true` on a buffer-only canvas — omit it and call `surface.resize(...)`.
* `VGPU-SURFACE-DEPTH-INVALID` when `depth` is not `false`, `true`, or one of the five depth-aspect formats above — use `depth: true`, a format such as `"depth24plus"`, or omit `depth`.
* `VGPU-SURFACE-MSAA-INVALID` when `msaa` is not `false`, `true`, or `4` — use `msaa: true` or `4` for four samples, or omit it for one.
* `VGPU-SURFACE-DISPOSED` when using a disposed surface, including as a `compile()`, `compileSync()`, `targets: [...]`, or `bundle()` preparation target, and for `resize()` — create a new surface.
* `VGPU-SURFACE-NOT-IN-FRAME` when a one-shot `draw.draw(surface)` / `effect.draw(surface)` runs while no frame is active, or a frame that already submitted opens a surface pass — encode surface draws inside `frame(gpu, ...)`, while `compile(surface)` and `bundle(gpu, { target: surface }, ...)` can prepare outside a frame.
* `VGPU-SURFACE-RESIZE-REENTRANT` when the same surface is resized from its own resize notification, including the immediate `onResize` fire on subscription — resize derived targets only.
* `VGPU-FRAME-REENTRANT` when `frame(gpu)` is called from any `onResize` callback, including the immediate fire on subscription — call `frame(gpu)` before subscribing or from code outside the callback.
* `VGPU-PASS-PRESERVE-MSAA` for `clear: false` on an `msaa` surface, and `VGPU-PASS-DEPTH-READONLY-MSAA` for `depthReadOnly` on one — multisample attachments are discarded at the end of each pass; use a single-sample surface or target.
* `VGPU-R1-BINDING-DESTROYED` at draw time when a binding still holds a `surface.depth` texture that a resize or `dispose()` destroyed — rebind the current `surface.depth` and re-record bundles that captured the old one.
* `VGPU-SURFACE-NOT-BINDABLE` when the surface itself is an input binding (see below).
* Native WebGPU validation still applies to the configured formats, features, and compatibility-mode restrictions; synchronous allocation errors propagate unchanged.

A surface is never a valid input binding. Passing one as a binding value to `draw(gpu)`, `effect(gpu)`, or `compute(gpu)` — in the constructor `set` option or a later `.set()`, inside or outside a frame — throws `VGPU-SURFACE-NOT-BINDABLE` from that call. The error names the binding and drawable in `where` (for example `post.source`). vgpu rejects the surface before it reads `color`, `colors`, or `depth`, so no canvas texture is acquired; that holds for disposed surfaces too. Fix: “Render to an offscreen target and bind that target or its texture. Use Surface only as a render destination.”

A live surface is a valid preparation target outside a frame. `draw.compile(surface)`, `effect.compile(surface)`, `compileSync(surface)`, `draw(gpu, { targets: [surface] })`, and `bundle(gpu, { target: surface }, ...)` read the surface's configured render signature — `format`, the resolved depth format (none unless `depth` is set), and the sample count (`1` unless `msaa` is set). They do not acquire the current canvas texture, read or allocate attachments, resize the canvas, notify `onResize` listeners, or submit work. Rendering to the surface — pass draws and bundle replay — stays inside `frame(gpu)` or `frameLoop(gpu)`.

## Examples

```wgsl
// surface-color.wgsl
@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.2, 0.6, 1, 1); }
```

```ts
import { init, effect, frame, surface } from "vgpu";
import surfaceColorShader from "./surface-color.wgsl";

declare const canvas: HTMLCanvasElement;

const gpu = await init();
const canvasSurface = surface(gpu, canvas, { dpr: [1, 2] });
const wave = effect(gpu, surfaceColorShader);

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: canvasSurface }, (pass) => pass.draw(wave));
});
```

### Render 3D directly to the canvas

With `depth` and `msaa`, depth-tested and antialiased geometry needs no offscreen target. This draws two published scene instances straight to the canvas:

```wgsl
// crates.wgsl
struct CameraData { viewProjection: mat4x4f }
@group(0) @binding(0) var<uniform> camera: CameraData;
struct VertexOut { @builtin(position) clip: vec4f, @location(0) normal: vec3f }

@vertex fn vs_main(
  @location(0) position: vec3f, @location(1) normal: vec3f,
  @location(3) world0: vec4f, @location(4) world1: vec4f,
  @location(5) world2: vec4f, @location(6) world3: vec4f,
) -> VertexOut {
  let world = mat4x4f(world0, world1, world2, world3);
  var out: VertexOut;
  out.clip = camera.viewProjection * world * vec4f(position, 1.0);
  out.normal = (world * vec4f(normal, 0.0)).xyz;
  return out;
}

@fragment fn fs_main(@location(0) normal: vec3f) -> @location(0) vec4f {
  let light = max(dot(normalize(normal), normalize(vec3f(1.0, 1.0, 1.0))), 0.15);
  return vec4f(vec3f(0.9, 0.5, 0.1) * light, 1.0);
}
```

```ts
import { draw, frameLoop, geometry, init, surface } from "vgpu";
import { box, composeMatrix, instances, orbitRig, perspective, rigPose, viewMatrices } from "vgpu/scene";
import { instanceGeometry } from "vgpu/scene/gpu";
import crateShader from "./crates.wgsl";

declare const canvas: HTMLCanvasElement;

const gpu = await init();
const canvasSurface = surface(gpu, canvas, { depth: true, msaa: true }); // owned depth24plus, 4 samples

const crates = instances({ capacity: 2 });
crates.setWorld(crates.add(), composeMatrix({ position: [-0.6, 0, 0] }, new Float32Array(16)));
crates.setWorld(crates.add(), composeMatrix({ position: [0.6, 0, -1] }, new Float32Array(16)));
const crateBridge = instanceGeometry(gpu, crates, { mesh: geometry(gpu, box()) });

const crateDraw = draw(gpu, {
  geometry: crateBridge.geometry,
  cull: "back",
  shader: crateShader,
});

const rig = orbitRig({ yaw: 0.6, pitch: 0.4, distance: 4 });
const pose = { position: new Float32Array(3), quaternion: new Float32Array(4) };
const projection = new Float32Array(16);
const matrices = { view: new Float32Array(16), viewProjection: new Float32Array(16) };

canvasSurface.onResize(({ width, height }) => { // fires now, then after every resize
  perspective({ fov: 45, near: 0.1, far: 100 }, width / height, projection);
  viewMatrices(rigPose(rig, pose), projection, matrices);
  crateDraw.set({ camera: { viewProjection: matrices.viewProjection } }); // set() packs now
});
const crateCount = crateBridge.publish(); // CPU records -> instance buffer

frameLoop(gpu, (currentFrame) => {
  currentFrame.pass({ target: canvasSurface, clear: [0.05, 0.05, 0.07, 1] }, (pass) => {
    pass.draw(crateDraw, { instances: crateCount }); // depth-tested, resolved into the canvas texture
  });
});
```

The pass clears depth to `1` and stencil to `0` unless you pass `clearDepth` / `clearStencil`. Camera, uniforms, publication, and the instance count stay yours; the surface only owns the attachments. The draw's default depth state (`write: true`, `compare: "less-equal"`) applies because the pass target now has depth.

### Sample an image after you render it

To sample a rendered image — post-processing, feedback, compositing — render it into an offscreen `Target` first, bind that target, and present the result to the surface:

```wgsl
// scene.wgsl
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f { return vec4f(uv, 0.5, 1); }
```

```wgsl
// present.wgsl
@group(0) @binding(0) var sceneTexture: texture_2d<f32>;
@group(0) @binding(1) var sceneSampler: sampler;
@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
  return textureSample(sceneTexture, sceneSampler, uv);
}
```

```ts
import { init, effect, frame, sampler, surface, target } from "vgpu";
import presentShader from "./present.wgsl";
import sceneShader from "./scene.wgsl";

declare const canvas: HTMLCanvasElement;

const gpu = await init();
const canvasSurface = surface(gpu, canvas);
const sceneTarget = target(gpu, { size: canvasSurface.size }); // offscreen, sampleable, same size as the canvas
const scene = effect(gpu, sceneShader);
const present = effect(gpu, presentShader, { set: { sceneTexture: sceneTarget, sceneSampler: sampler(gpu) } }); // bind the Target, never the Surface

canvasSurface.onResize(({ width, height }) => sceneTarget.resize([width, height])); // the binding follows the new attachment

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: sceneTarget }, (pass) => pass.draw(scene)); // produce offscreen
  currentFrame.pass({ target: canvasSurface }, (pass) => pass.draw(present)); // present to the canvas
});
```

The surface appears only as a pass `target`. Because `present` binds `sceneTarget` itself, the binding picks up the replacement attachment after every `sceneTarget.resize(...)`; no rebind is needed. Binding `{ sceneTexture: canvasSurface }` instead throws `VGPU-SURFACE-NOT-BINDABLE`.

### Read the surface depth

A single-sample depth surface stores its depth, so a later pass in the same frame can depth-test against it and read it. Bind `surface.depth` explicitly and rebind it after every resize:

```wgsl
// opaque.wgsl
@vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
  var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
  return vec4f(p[vi], 0.25, 1);
}

@fragment fn fs_main() -> @location(0) vec4f {
  return vec4f(0.2, 0.5, 0.2, 1);
}
```

```wgsl
// haze.wgsl
@group(0) @binding(0) var sceneDepth: texture_2d<f32>; // unfilterable float view, compatibility-safe

@vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
  var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
  return vec4f(p[vi], 0.0, 1);
}

@fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {
  let depth = textureLoad(sceneDepth, vec2i(position.xy), 0).x;
  return vec4f(0.7, 0.8, 0.9, 1.0) * depth * 0.3;
}
```

```ts
import { draw, frame, init, surface } from "vgpu";
import hazeShader from "./haze.wgsl";
import opaqueShader from "./opaque.wgsl";

declare const canvas: HTMLCanvasElement;

const gpu = await init();
const canvasSurface = surface(gpu, canvas, { depth: true }); // no msaa: depth is stored and readable
const opaque = draw(gpu, { shader: opaqueShader });
const haze = draw(gpu, {
  shader: hazeShader,
  depth: { write: false }, // depth-test without writing the read-only depth
  blend: "additive",
});

canvasSurface.onResize(() => haze.set({ sceneDepth: canvasSurface.depth! })); // fires now; resize destroys the old depth

frame(gpu, (currentFrame) => {
  currentFrame.pass(canvasSurface, opaque); // writes depth
  currentFrame.pass({ target: canvasSurface, clear: false, depthReadOnly: true }, haze); // tests and reads the same depth
});
```

`surface.depth` is a plain `Texture` with `render_attachment` and `texture_binding` usage, so the binding keeps that exact texture. The `onResize` rebind keeps it current for explicit and automatic resizes; direct canvas writes need an explicit rebind after reconciliation (see [Resize transaction](#resize-transaction)). A draw that still holds a destroyed depth throws `VGPU-R1-BINDING-DESTROYED`. An `msaa` surface's depth has 4 samples and is discarded after each pass, so it cannot be read this way.

### Derived targets, multiple canvases, and `OffscreenCanvas`

```ts
import { init, effect, frame, surface, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
declare const canvas: HTMLCanvasElement;
const canvasSurface = surface(gpu, canvas);

const bloomSize = (w: number, h: number): [number, number] => [w / 2, h / 2];
const bloom = target(gpu, { size: bloomSize(canvasSurface.size[0], canvasSurface.size[1]) });
const brightPass = effect(gpu, prepareShader(`
  struct Params { resolution: vec2f }
  @group(0) @binding(0) var<uniform> params: Params;
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }
`), { set: { params: { resolution: bloom.size } } });
const composite = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }`));

canvasSurface.onResize(({ width, height }) => {
  bloom.resize(bloomSize(width, height));
  brightPass.set({ params: { resolution: bloom.size } });
});

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: bloom }, (pass) => pass.draw(brightPass));
  currentFrame.pass({ target: canvasSurface }, (pass) => pass.draw(composite));
});
```

```wgsl
// shared.wgsl
@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }
```

```ts
import { init, effect, frame, surface } from "vgpu";
import sharedShader from "./shared.wgsl";

declare const canvasA: HTMLCanvasElement;
declare const canvasB: HTMLCanvasElement;

const gpu = await init();
const main = surface(gpu, canvasA);
const preview = surface(gpu, canvasB, { autoResize: false, size: [320, 180] });
const shader = effect(gpu, sharedShader);

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: main }, (p) => p.draw(shader));
  currentFrame.pass({ target: preview }, (p) => p.draw(shader));
});
```

```ts
import { init, surface, target } from "vgpu";

declare const offscreen: OffscreenCanvas;
declare function postMessage(message: unknown): void;

const gpu = await init();
const canvasSurface = surface(gpu, offscreen);
const half = target(gpu, { size: [Math.max(1, canvasSurface.size[0] / 2), Math.max(1, canvasSurface.size[1] / 2)] });

canvasSurface.onResize(({ width, height }) => {
  half.resize([width / 2, height / 2]);
  postMessage({ type: "resized", width, height });
});

canvasSurface.resize([640, 360]);
```

### Prepare before the first frame

Prepare pipelines and bundles for the surface during loading, then render inside the frame loop:

```wgsl
// prewarm-background.wgsl
@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.1, 0.2, 0.4, 1); }
```

```ts
import { init, bundle, effect, frameLoop, surface } from "vgpu";
import backgroundShader from "./prewarm-background.wgsl";

declare const canvas: HTMLCanvasElement;

const gpu = await init();
const canvasSurface = surface(gpu, canvas, { depth: true, msaa: true });
const background = effect(gpu, backgroundShader);

await background.compile(canvasSurface); // outside a frame: format + depth24plus + 4 samples, no canvas texture acquired
const statics = bundle(gpu, { target: canvasSurface }, (recorded) => recorded.draw(background)); // also outside a frame

frameLoop(gpu, (currentFrame) => {
  currentFrame.pass({ target: canvasSurface }, (pass) => pass.bundles(statics)); // replay stays inside the frame
});
```

The signature here is `{ colors: [canvasSurface.format], depth: "depth24plus", sampleCount: 4 }`; compiling against that object warms the same cached pipeline. Resizing the surface changes only its size, so the compiled pipeline and the recorded bundle keep matching its render signature. Normal bundle staleness still applies: a bundle that samples a resized `Target`, or that bound an old `surface.depth`, must be re-recorded.

## Attachments and lifetimes

* **Color.** `surface.color` wraps the canvas's current texture, single-sample in `surface.format`. The browser replaces it after each presentation, and vgpu never destroys it. With `msaa`, each pass renders into a private 4-sample color attachment and resolves into that texture; the multisample attachment has no public handle.
* **Depth.** `surface.depth` is owned by the surface, with the surface's sample count. The same `Texture` stays valid until the surface resizes or is disposed; then it is destroyed.
* **Pass semantics.** Single-sample depth is stored at the end of each pass, so `clear: false` and `depthReadOnly` work on it. It is not replaced per frame: a `clear: false` first pass of a new frame loads the previous frame's depth over fresh canvas color, so clear the first surface pass of each frame. With `msaa`, color and depth are discarded after the pass: every surface pass must clear, so encode a frame's draws into one surface pass.
* **Construction.** `surface()` allocates every owned attachment before it returns. If an allocation throws, vgpu destroys the partial attachments, unconfigures the context, restores the canvas size it changed, and rethrows; the canvas can take a new surface.
* **Dispose.** `dispose()` unconfigures the context, frees the canvas for a new surface, and destroys the owned depth and MSAA attachments even when an `onDestroy` listener throws; the first listener error is rethrown afterwards. A second `dispose()` does nothing.

## Resize transaction

`resize()`, automatic layout/DPR resizes at the frame boundary, and reconciliation of a canvas you resized yourself all replace attachments in four steps:

1. **Prepare.** Allocate the replacement MSAA color and depth at the new size. If an allocation throws synchronously, vgpu destroys the partial replacements and rethrows; the canvas size, DPR, attachments, and existing bindings stay exactly as they were, and no callback runs.
2. **Commit.** Publish the new canvas size, DPR, and attachments together.
3. **Notify.** Run internal attachment-replacement listeners, then public `onResize` callbacks for explicit or automatic resizes. Every callback already sees the new `surface.size`, `dpr`, and `surface.depth`.
4. **Release.** Destroy the previous owned attachments.

A throwing callback does not stop the remaining callbacks or the release step; the first error is rethrown after both, and the new generation stays committed. The reentrancy guard covers steps 2–4, including an `onResize` subscription made inside a replacement callback: resizing the same surface there throws `VGPU-SURFACE-RESIZE-REENTRANT`, and `frame(gpu)` throws `VGPU-FRAME-REENTRANT`.

A resize matching both the canvas buffer and the attachment generation allocates nothing and notifies nobody. After a direct canvas write, `surface.resize(surface.size)` replaces stale owned attachments and notifies listeners so they can rebind; a default surface with no owned attachments keeps its existing no-op behavior. A library change to the canvas buffer size notifies in either case.

If you write `canvas.width` / `canvas.height` directly between frames, vgpu reconciles attachments at the next frame boundary, before your callback encodes any passes, including for `OffscreenCanvas` and `autoResize: false`. Reconciliation itself does not notify public `onResize` listeners; internal texture-replacement notifications still invalidate references to old attachments. Automatic layout resizing retains its usual notifications. Rebind a captured depth texture to the current `surface.depth` before using it. Prefer `surface.resize(...)` before the frame so replacement, rebinding, and public notifications happen together.

The pass descriptor also reconciles dimensions changed during a frame, before acquiring the canvas texture. This does not preserve commands that already reference old attachments: resize before encoding them, and submit any older manual frames first. If replacement allocation throws, the frame boundary or pass throws before user encoding or texture acquisition respectively; `surface.size` reports your written size, the old attachments stay live, and the next attempt retries. vgpu does not roll back your canvas write. Late native validation or out-of-memory errors arrive through normal WebGPU error reporting without rollback; this is not an async resize API.

## Notes

* Use a `Surface` for the swapchain/backbuffer: it renders the current browser frame, including direct 3D with `depth` and `msaa`. Use `target(gpu, ...)` for intermediate, reusable, sampleable/readable images — post-processing, history, ping-pong; see `Target` for the contrast.
* A surface pass may be the final presentation pass; do not use a surface as a ping-pong resource. For post-processing, render into a `Target`, then sample it in a draw or effect targeting the surface in the same frame.
* Do not bind a surface: `set({ source: canvasSurface })` throws `VGPU-SURFACE-NOT-BINDABLE` in every resource slot (sampled color or depth, storage texture, sampler, buffer). Bind an offscreen `Target` to follow its attachment across resizes, or bind an explicit `Texture` such as `sceneTarget.color` or a single-sample `canvasSurface.depth` to keep that exact texture until you rebind it.
* `surface.color` is still a `Texture`, but it wraps the canvas's current texture, which the browser replaces after each presentation. Binding it explicitly is not a substitute for an offscreen target: the binding does not follow later frames and is not safe to reuse after the frame presents.
* Prepare against the surface itself once it exists; it reports the exact depth format and sample count. Keep a signature such as `{ colors: [navigator.gpu.getPreferredCanvasFormat()] }` — plus `depth` / `sampleCount: 4` when the surface will enable them — for preparation before `surface(gpu, canvas)` runs. Do not hardcode `bgra8unorm` or `rgba8unorm` for a canvas.
* Layout-backed detection is structural: `typeof canvas.clientWidth === "number"`; it does not use `instanceof`.
* Resize callbacks run in surface creation order at the frame boundary, before the user frame callback.
* Manual `surface.resize()` fires callbacks synchronously at the call site and works for `OffscreenCanvas`.
* `surface.color.read({ mipLevel: 0, region: "all" })` reads the canvas texture current when you call it — with `msaa`, the resolved single-sample image; vgpu keeps no copy of an earlier presented frame. To read a rendered image back later, render it into a `Target` and read `target.color`. It returns RGBA bytes. Canvas formats `bgra8unorm` and `bgra8unorm-srgb` are supported and swizzled to RGBA, which matters on platforms where `navigator.gpu.getPreferredCanvasFormat()` returns BGRA.
* `surface.color.readFloats({ mipLevel: 0, region: "all" })` returns the same pixels decoded to a `Float32Array` of components (`unorm8` canvas formats normalized to `[0, 1]`); it is the readback to use if a surface is ever configured with a float format.
* A canvas can have only one live surface. Call `surface.dispose()` before creating another one for the same canvas.
* **See also:** `init`, `surface`, `Target`, `Frame`, `Bundle`, `instanceGeometry`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Target
description: Offscreen render target abstraction used by passes, draws, bundles, and ping-pong resources. Targets own size, color formats, optional depth, MSAA resolve textures, and readback. Canvas-backed targets are `Surface` instances created with `surface(gpu, canvas)`; they accept opt-in `depth` / `msaa` options for direct 3D rendering, but their color is the canvas's current presentation texture and the surface itself is never an input binding.
---

# Target



## Import

```ts
import type { Target, TargetOptions, TargetTextureOptions, PingPongTargets, PingPongStorage } from "vgpu";
```

## Signature

```ts
import type { ClearColor } from "vgpu";
import type { ResourceDestroyCallback, ResourceIdentity, Texture, UnsubscribeResourceDestroy } from "vgpu/core";

interface TargetTextureOptions {
  readonly format?: GPUTextureFormat;
  readonly colors?: readonly { readonly format: GPUTextureFormat }[];
  readonly depth?: boolean | GPUTextureFormat;
  readonly msaa?: boolean | 4;
  readonly label?: string;
}

interface TargetOptions extends TargetTextureOptions {
  readonly size: readonly [number, number];
}

interface Target {
  readonly gpu: unknown;
  readonly size: readonly [number, number];
  readonly texelSize: readonly [number, number];
  readonly color: Texture;
  readonly colors: readonly [Texture, ...Texture[]];
  readonly depth?: Texture;
  readonly format: GPUTextureFormat;
  readonly sampleCount: 1 | 4;
  readonly resourceIdentity: ResourceIdentity;
  resize(size: readonly [number, number]): void;
  onDestroy(cb: ResourceDestroyCallback<Target>): UnsubscribeResourceDestroy;
  renderPassDescriptor(opts?: {
    readonly clear?: ClearColor;
    readonly preserve?: boolean;
    readonly clearDepth?: number;
    readonly clearStencil?: number;
    readonly depthReadOnly?: boolean;
  }): GPURenderPassDescriptor;
}

interface PingPongTargets { readonly read: Target; readonly write: Target; swap(): void; }
interface PingPongStorage { readonly read: import("vgpu").StorageBuffer; readonly write: import("vgpu").StorageBuffer; swap(): void; }
```

## Parameters

| Param                                     | Type                                      | Required | Default                                     | Notes                                                                                                                                                                                                                                                                                                          |
| ----------------------------------------- | ----------------------------------------- | -------: | ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| target.opts                               | `TargetOptions`                           |        ✔ | —                                           | Creates an offscreen target. `size` is mandatory.                                                                                                                                                                                                                                                              |
| opts.size                                 | `readonly [number, number]`               |        ✔ | —                                           | Initial offscreen texture size in physical pixels.                                                                                                                                                                                                                                                             |
| opts.format                               | `GPUTextureFormat`                        |        ✖ | `"rgba8unorm"`                              | Used for single-color targets when `colors` is omitted.                                                                                                                                                                                                                                                        |
| opts.colors                               | `readonly { format: GPUTextureFormat }[]` |        ✖ | `[{ format: opts.format ?? "rgba8unorm" }]` | Multiple render targets (MRT): one attachment per entry, all written by one pass — the G-buffer layout for deferred shading. `target.color` is `colors[0]`.                                                                                                                                                    |
| opts.depth                                | `boolean \| GPUTextureFormat`             |        ✖ | `undefined`                                 | `true` means `"depth24plus"`; a string uses that depth format; omitted means no depth. The depth texture also has `texture_binding` usage, so later passes can sample it. Combined depth-stencil formats such as `"depth24plus-stencil8"` are supported; stencil-only `"stencil8"` is rejected.                |
| opts.msaa                                 | `boolean \| 4`                            |        ✖ | `false` / sample count `1`                  | Only `true` or `4` enables MSAA, creating color/depth attachments with sample count `4` and resolving to sampleable `.color(s)`.                                                                                                                                                                               |
| opts.clearColor                           | `ClearColor`                              |        ✖ | `[0, 0, 0, 1]`                              | Default clear color of this target, used by passes that clear without naming one. Writable at runtime as `target.clearColor`; a pass `clear` color still wins for that pass. Four finite numbers, or a `GPUColor` object.                                                                                      |
| opts.label                                | `string`                                  |        ✖ | `undefined`                                 | Prefix for created texture labels.                                                                                                                                                                                                                                                                             |
| target.resize.size                        | `readonly [number, number]`               |        ✔ | —                                           | Two positive safe integers. Recreates offscreen textures unless size is unchanged. Synchronous preparation failure preserves the old size and attachments.                                                                                                                                                     |
| target.onDestroy.cb                       | `ResourceDestroyCallback<Target>`         |        ✔ | —                                           | Subscribes to target destruction.                                                                                                                                                                                                                                                                              |
| target.renderPassDescriptor.clear         | `ClearColor`                              |        ✖ | `[0, 0, 0, 1]`                              | Clear color for all color attachments unless `preserve` is true. `Frame.pass` supplies `target.clearColor` for omitted/`true` clears and a per-pass color when provided.                                                                                                                                       |
| target.renderPassDescriptor.preserve      | `boolean`                                 |        ✖ | `false`                                     | Optional implementer hook used by `Frame.pass({ clear: false })`; when true, color and depth attachments should load existing contents and omit clear values.                                                                                                                                                  |
| target.renderPassDescriptor.clearDepth    | `number`                                  |        ✖ | `1`                                         | Depth clear value used when the pass clears. `Frame.pass` supplies `FramePassOptions.clearDepth`; ignored while preserving and on targets without depth.                                                                                                                                                       |
| target.renderPassDescriptor.clearStencil  | `number`                                  |        ✖ | `0`                                         | Stencil clear value used when the pass clears. `Frame.pass` supplies `FramePassOptions.clearStencil`; ignored while preserving and on targets whose depth format has no stencil aspect.                                                                                                                        |
| target.renderPassDescriptor.depthReadOnly | `boolean`                                 |        ✖ | `false`                                     | When true, the depth-stencil attachment is built with `depthReadOnly: true` and omits `depthLoadOp`/`depthStoreOp`, as WebGPU requires for read-only aspects; formats with a stencil aspect also set `stencilReadOnly: true` and omit the stencil ops. `Frame.pass` supplies `FramePassOptions.depthReadOnly`. |
| pingPong.width                            | `number`                                  |        ✔ | —                                           | Floored and clamped to at least `1`.                                                                                                                                                                                                                                                                           |
| pingPong.height                           | `number`                                  |        ✔ | —                                           | Floored and clamped to at least `1`.                                                                                                                                                                                                                                                                           |
| pingPong.opts                             | `TargetTextureOptions`                    |        ✖ | `{}`                                        | Texture options for both targets. Size is intentionally not accepted; positional width/height win.                                                                                                                                                                                                             |
| pingPongStorage.bytes                     | `number`                                  |        ✔ | —                                           | Creates two `"read-write"` storage buffers.                                                                                                                                                                                                                                                                    |

**Returns:** `target(gpu)` returns `Target`; `resize()` returns `void`; `renderPassDescriptor(opts?)` returns a WebGPU render pass descriptor; `pingPong(gpu)` returns `PingPongTargets`; `pingPongStorage(gpu)` returns `PingPongStorage`. For readback, select `.color` or `.colors[index]` and use `Texture.read(options)` / `Texture.readFloats(options)`.

**Throws:** `VGPU-CORE-UNSUPPORTED-FORMAT` when `read()` / `readFloats()` runs on a color format outside the readback table (see `Texture`); `VGPU-TARGET-SIZE-REQUIRED` when runtime JS calls `target(gpu)` without `size`; `VGPU-R1-BINDING-INCOMPATIBLE-RESOURCE` when a `texture_depth_*` binding receives a target without a depth attachment; `VGPU-TARGET-MSAA-INVALID` when runtime JS passes an unsupported `msaa` value (only `true` / `4` are accepted); `VGPU-TARGET-DEPTH-STENCIL-ONLY` when `depth` receives the stencil-only `"stencil8"` format (stencil-only depth targets are not supported yet); `VGPU-RING1-UNSUPPORTED` when `msaa: true` / `4` with `rgba16float` is used on a Dawn compatibility-mode device; underlying core texture/readback operations can throw native WebGPU validation errors.

## Examples

```ts
import { init, effect, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [128, 128], format: "rgba16float", depth: true, msaa: true });
const post = effect(gpu, prepareShader(`
  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f { return vec4f(uv, 0, 1); }
`));

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: scene, clear: [0, 0, 0, 1] }, (pass) => pass.draw(post));
});
```

```ts
import { init, draw, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
// G-buffer for deferred shading: albedo, normals, material parameters.
const gbuffer = target(gpu, {
  size: [512, 512],
  colors: [{ format: "rgba8unorm" }, { format: "rgba16float" }, { format: "rgba8unorm" }],
  depth: true,
});
const fill = draw(gpu, {
  shader: prepareShader(`
    @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
      var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
      return vec4f(p[vi], 0, 1);
    }
    struct GBuffer { @location(0) albedo: vec4f, @location(1) normal: vec4f, @location(2) material: vec4f }
    @fragment fn fs_main() -> GBuffer {
      return GBuffer(vec4f(0.8, 0.2, 0.2, 1), vec4f(0, 0, 1, 0), vec4f(0.5, 0.1, 0, 0));
    }
  `),
});

frame(gpu, (currentFrame) => {
  currentFrame.pass(gbuffer, fill); // one draw fills all three attachments
});
```

One geometry pass fills every G-buffer attachment; a later lighting effect samples them as `gbuffer.colors[0]`–`[2]`. Per-attachment blend/write-mask overrides for MRT draws live on `DrawOptions.colors`.

```ts
import { init, effect, surface, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const canvasSurface = surface(gpu, mockCanvas());
const bloomSize = (w: number, h: number): [number, number] => [w / 2, h / 2];
const bloom = target(gpu, { size: bloomSize(canvasSurface.size[0], canvasSurface.size[1]) });
const bright = effect(gpu, prepareShader(`
  struct Params { resolution: vec2f }
  @group(0) @binding(0) var<uniform> params: Params;
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }
`), { set: { params: { resolution: bloom.size } } });

canvasSurface.onResize(({ width, height }) => {
  bloom.resize(bloomSize(width, height));
  bright.set({ params: { resolution: bloom.size } });
});

function mockCanvas(): HTMLCanvasElement {
  return {
    width: 10,
    height: 10,
    clientWidth: 10,
    clientHeight: 10,
    getContext() { return { configure() {}, unconfigure() {}, getCurrentTexture() { return { createView: () => ({}) }; } }; },
  } as unknown as HTMLCanvasElement;
}
```

```ts
import { init, effect, frame, target } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
// HDR target: readFloats() decodes the half-float texels, read() would hand back raw bytes.
const hdr = target(gpu, { size: [64, 64], format: "rgba16float" });
const bloom = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(4.0, 2.0, 1.0, 1.0); }`));

frame(gpu, (currentFrame) => currentFrame.pass(hdr, bloom));

const floats = await hdr.color.readFloats({ mipLevel: 0, region: "all" }); // Float32Array, 64 * 64 * 4 components
console.log(floats[0]); // 4 — values above 1 survive the readback
```

```ts
import { init, effect, frame, pingPong } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const pair = pingPong(gpu, 32.9, 32.1, { format: "rgba8unorm" });
const blur = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }`));

frame(gpu, (currentFrame) => {
  currentFrame.pass({ target: pair.write, clear: false }, (pass) => pass.draw(blur));
});
pair.swap();
```

## Sampling depth

`target.depth` is a `Texture` with `render_attachment` and `texture_binding` usage. Bind it, or the `Target` itself, to a `texture_depth_2d` binding. Depth textures are not filterable: use `textureLoad`, or pair `textureSample` with `sampler(gpu, { minFilter: "nearest", magFilter: "nearest" })`; vgpu declares that sampler slot as `non-filtering` automatically. A comparison sampler also works with `textureSampleCompare`. Combined depth-stencil formats are exposed through a depth-only view. A target without `depth` is rejected with a fix-it.

A `Surface` has no follow-resize binding: bind its single-sample `surface.depth` explicitly and rebind it from `onResize`, because resize destroys the old depth texture. See `Surface` for the read-only pass example.

## Notes

* Choose `Target` for offscreen intermediates that must be reused, sampled, read back, or ping-ponged; choose `Surface` only for the canvas swapchain (see `Surface`). A target can be rendered in multiple passes and sampled by later effects. Depth-tested 3D that is only presented does not need a target: render it to `surface(gpu, canvas, { depth: true, msaa: true })`.
* Use simple `format` for one color attachment. Use `colors` when a pass writes multiple attachments (MRT/G-buffer), then consume `target.colors[i]` in later lighting/post passes.
* Set `depth: true` for ordinary z-testing; choose `depth: "depth24plus-stencil8"` when stencil masking is required. Enable `msaa: true`/`4` for anti-aliased 3D geometry, but do not combine MSAA with `clear: false` preservation or `depthReadOnly`: the internal multisample render attachments (including depth) are discarded, while the resolved `.color(s)` remain sampleable/readable. The same pass restrictions apply to an `msaa` surface.
* `target.color.read({ mipLevel: 0, region: "all" })` / `target.color.readFloats({ mipLevel: 0, region: "all" })` are intended for tests, snapshots, and diagnostics—not a per-frame hot path. For iterative simulation or post-processing, use `pingPong(gpu, ...)` and swap targets instead of readback.
* There is no global resolution binding. Pass `target.size` or `target.texelSize` explicitly to shaders.
* `Surface.color` wraps the canvas current texture; offscreen target colors are stable until resize/destroy. `Surface.depth` is owned and stable until resize/dispose like a target depth, while a surface's MSAA color stays private.
* Offscreen resize prepares all color/MSAA/depth replacements before publishing them. Synchronous preparation failure cleans partial allocations and leaves old attachments and bindings intact. Late native validation/out-of-memory errors use normal WebGPU reporting without rollback; this is not an async resize API.
* Successful resize publishes one coherent attachment generation, notifies Target bindings, then releases old textures. Subscriber failures do not roll back an already committed replacement; other subscribers and cleanup still run. Recursive resize inside replacement callbacks is rejected. Destroyed targets cannot be resized, including to the same size.
* Binding `target.color`/`target.depth` retains that exact attachment; it does not follow resize. Rebind the replacement after resizing, or bind the Target itself to follow its selected color/depth attachment. Tracked destroyed references fail at draw/dispatch; recorded bundles must be re-recorded.
* As an input binding value, only offscreen and custom targets are bindable as a `Target`. A `Surface` passed to `set()` or a constructor `set` option of `draw(gpu)`, `effect(gpu)`, or `compute(gpu)` throws `VGPU-SURFACE-NOT-BINDABLE` before any canvas texture is acquired. Surfaces remain render destinations: render the image into an offscreen target, bind that target or its texture, and present it with a surface pass; see `Surface` for the example. An explicit single-sample `surface.depth` texture is bindable; the surface object is not.
* `target.color.read({ mipLevel: 0, region: "all" })` and `surface.color.read({ mipLevel: 0, region: "all" })` return raw texel bytes in the target's own color format, with row padding removed and BGRA canvas formats swizzled to RGBA. For `rgba8unorm` targets that is exactly the previous RGBA byte layout.
* Float targets (`rgba16float`, `rgba32float`, `r16float`, `r32float`, `rg16float`, `rg32float`) read back through `target.color.readFloats({ mipLevel: 0, region: "all" })`, which decodes half/float texels into a `Float32Array` of components — HDR values above `1` and negatives are preserved. `readFloats()` also works on `unorm8` targets (normalized to `[0, 1]`), so tooling can stay format-agnostic.
* `Target` and `Surface` have no read methods. Select `.color` or `.colors[index]`, then use that texture's required mip/region selection. Custom implementations expose attachments, not readback delegates.
* Size-dependent targets derived from a surface should be created from the real initial `surface.size` and resized from `surface.onResize(...)`.
* Custom `Target` implementers should honor the optional `renderPassDescriptor(opts?)` options-bag fields to participate in `Frame.pass({ clear: false })`, `FramePassOptions.clearDepth`, `FramePassOptions.clearStencil`, and `FramePassOptions.depthReadOnly`; implementations that ignore a field will clear (with depth `1`, stencil `0`) instead.
* Depth formats with a stencil aspect (`"depth24plus-stencil8"`, `"depth32float-stencil8"`) emit `stencilLoadOp`/`stencilStoreOp` on the pass depth-stencil attachment, mirroring the depth load/store behavior with `stencilClearValue` from `FramePassOptions.clearStencil` (default `0`), as WebGPU requires when the stencil aspect is writable.
* `target.depth` is created with `texture_binding` usage in addition to `render_attachment`, so it can be bound with `set()` as a sampled depth texture — including inside the same pass when it opened with `FramePassOptions.depthReadOnly`.
* **See also:** `Surface`, `FramePassOptions`, `Effect`, `Draw`, `Bundle`, `Compute` storage ping-pong.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Texture
description: Creates a standalone sampleable/storage texture from the main API (`vgpu`). Use it when a shader needs a texture that is not a render target: compute-written storage textures, 3D lookup tables, texture arrays, or mipmapped inputs. Render outputs still use `target(gpu)`.
---

# Texture



## Import

```ts
import type { Texture, TextureOptions, TextureReadOptions, TextureShape, TextureUsageName } from "vgpu";
import { init, texture } from "vgpu/mock";
```

## Signature

```ts
import type { Texture } from "vgpu";
import type { Gpu } from "vgpu";

type TextureUsageName = "copy_src" | "copy_dst" | "texture_binding" | "storage_binding" | "render_attachment";

type TextureShape =
  | { readonly kind: "1d"; readonly size: readonly [width: number]; readonly layers?: never }
  | { readonly kind: "2d"; readonly size: readonly [width: number, height: number]; readonly layers?: never }
  | { readonly kind: "3d"; readonly size: readonly [width: number, height: number, depth: number]; readonly layers?: never }
  | { readonly kind: "2d-array"; readonly size: readonly [width: number, height: number]; readonly layers: number };

type TextureOptions = TextureShape & {
  readonly format: GPUTextureFormat;
  readonly usage: readonly [TextureUsageName, ...TextureUsageName[]];
  readonly mipLevelCount?: number;
  readonly sampleCount?: 1 | 4;
  readonly viewFormats?: readonly GPUTextureFormat[];
  readonly label?: string;
};

declare function texture(gpu: Gpu, opts: TextureOptions): Texture;

interface TextureReadOptions {
  readonly mipLevel: number;
  readonly region: "all" | {
    readonly origin: readonly [number, number, number];
    readonly size: readonly [number, number, number];
  };
}
```

## Parameters

| Param              | Type                                                 |   Required | Default     | Notes                                                                                                                    |
| ------------------ | ---------------------------------------------------- | ---------: | ----------- | ------------------------------------------------------------------------------------------------------------------------ |
| opts.kind          | `TextureShape["kind"]`                               |          ✔ | —           | Explicit `"1d"`, `"2d"`, `"3d"` or `"2d-array"`.                                                                         |
| opts.size          | `TextureShape["size"]`                               |          ✔ | —           | Positive safe integers; one, two or three spatial dimensions according to kind. Arrays use two.                          |
| opts.layers        | `number`                                             | For arrays | —           | Required positive integer for `"2d-array"`; forbidden for other kinds.                                                   |
| opts.format        | `GPUTextureFormat`                                   |          ✔ | —           | Must support the requested usages with the device's enabled features. Native WebGPU performs full per-format validation. |
| opts.usage         | `readonly [TextureUsageName, ...TextureUsageName[]]` |          ✔ | —           | Nonempty list. No sampling, storage or copy flags are added implicitly.                                                  |
| opts.mipLevelCount | `number`                                             |          ✖ | `1`         | Extra levels are not generated; write them from compute or copies.                                                       |
| opts.sampleCount   | `1 \| 4`                                             |          ✖ | `1`         | MSAA needs a 2D render attachment with one mip and no storage usage. No automatic resolve.                               |
| opts.viewFormats   | `readonly GPUTextureFormat[]`                        |          ✖ | `[]`        | Explicit compatible alternate view formats; no conversion or automatic expansion.                                        |
| opts.label         | `string`                                             |          ✖ | `undefined` | Used for the GPU texture label and in error `where` fields.                                                              |

**Returns:** `Texture` from the core layer — bind it with `set({ name: texture })`, read it back with `texture.read({ mipLevel: 0, region: "all" })`, and release it with `texture.destroy()`. Sampled bindings (`texture_2d<f32>`, `texture_3d<f32>`, `texture_2d_array<f32>`) accept it when `usage` includes `texture_binding`; storage bindings (`texture_storage_2d<...>`, `texture_storage_3d<...>`) accept it when `usage` includes `storage_binding`.

**Throws:** `VGPU-TEXTURE-SIZE-REQUIRED` when `size` is missing or has a non-positive entry — pass `[width, height]` or `[width, height, depth]`; `VGPU-TEXTURE-STORAGE-FORMAT` when `usage` includes `storage_binding` and `format` is not storage-capable — pick a storage-capable format or pass `usage` without `storage_binding`.

## Examples

```ts
import { compute, effect, init, sampler, texture } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
// 32x32x32 rgba16float lookup table written by compute and sampled by a fragment shader.
const lut = texture(gpu, { kind: "3d", size: [32, 32, 32], format: "rgba16float", usage: ["storage_binding", "texture_binding"], label: "lut" });

const fill = compute(gpu, prepareShader(`
  @group(0) @binding(0) var lut: texture_storage_3d<rgba16float, write>;
  @compute @workgroup_size(4, 4, 4)
  fn main(@builtin(global_invocation_id) id: vec3u) {
    textureStore(lut, id, vec4f(vec3f(id) / 31.0, 1.0));
  }
`), { label: "fill-lut", set: { lut } });
fill.dispatch(8, 8, 8);

const view = effect(gpu, prepareShader(`
  @group(0) @binding(0) var lut: texture_3d<f32>;
  @group(0) @binding(1) var linear: sampler;
  @fragment fn main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return textureSample(lut, linear, vec3f(uv, 0.5));
  }
`), { label: "view-lut", set: { lut, linear: sampler(gpu) } });
```

```ts
import { init, texture } from "vgpu/mock";

const gpu = await init();
// Uploadable and sampled, with no storage or readback capability requested.
const atlas = texture(gpu, { kind: "2d-array", size: [256, 256], layers: 8, format: "bgra8unorm", usage: ["texture_binding", "copy_dst"] });
atlas.destroy();
```

### Write a selected mip from compute

Binding a `Texture` directly to a storage slot selects mip 0. To write another allocated mip,
bind a native view that selects exactly one level:

```ts
import { compute, init, texture } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const image = texture(gpu, {
  kind: "2d", size: [8, 8], format: "rgba16float", mipLevelCount: 2,
  usage: ["storage_binding", "copy_src"],
});
const fill = compute(gpu, prepareShader(`
  @group(0) @binding(0) var dst: texture_storage_2d<rgba16float, write>;
  @compute @workgroup_size(1)
  fn main(@builtin(global_invocation_id) id: vec3u) {
    textureStore(dst, id.xy, vec4f(1.0));
  }
`), { set: { dst: image.createView({ baseMipLevel: 1, mipLevelCount: 1 }) } });
fill.dispatch(4, 4); // Mip 1 of an 8x8 texture is 4x4.
const pixels = await image.readFloats({ mipLevel: 1, region: "all" });
gpu.dispose();
```

This is a raw `GPUTextureView`, not a managed view. It bypasses wrapper-aware binding validation and
lifetime tracking; native WebGPU validates the view. Keep its parent texture alive, and recreate/rebind
the view (and re-record any bundles that captured it) after replacing the parent. No automatic mip
generation or content preservation occurs.

## Notes

* Texture structure is fixed: there is no `Texture.resize()`. Create a replacement, call `set()` with it and destroy the old resource. Tracked sampled/storage bindings throw `VGPU-R1-BINDING-DESTROYED` with the binding and resource context on subsequent use; already-recorded bundles become stale and must be re-recorded.
* `set({ src: target })` follows successful Target attachment replacement. `set({ src: target.color })` retains that exact texture and must be updated after resize. Raw views and direct native destruction bypass parent-aware diagnostics; native WebGPU validation remains the fallback.
* `TextureOptions`, `TextureReadOptions`, `TextureShape` and `TextureUsageName` are re-exported from core through `vgpu`, `vgpu/node` and `vgpu/mock`. Their canonical documentation is the core `Texture` page. Both creation paths use the same validation; `texture(gpu, opts)` additionally registers ownership with `gpu`. Options and nested arrays are copied and frozen. Array `.size` stays `[width, height]`; `.layers` reports the separate count. `.dimension` remains the derived native WebGPU dimension for interop.
* Default views follow kind: a one-layer `"2d-array"` still has an array view. Use an explicit `createView({ dimension: "2d", arrayLayerCount: 1 })` or `layerView` when a layer needs a plain 2D view.
* Storage texture bindings are validated at `set()` time: the texture must carry `storage_binding` usage, its `format` must equal the format declared in WGSL, and its shape must match the binding (`texture_storage_3d` needs `kind: "3d"`). Mismatches throw `VGPU-R1-BINDING-INCOMPATIBLE-RESOURCE` with a fix-it naming the expected value.
* A `Target` cannot satisfy a storage texture binding; render attachments are not storage textures. Write into `texture(gpu)` from compute and sample it from the render pass instead.
* Direct `Texture` storage bindings select mip level `0`. A native `createView({ baseMipLevel, mipLevelCount: 1 })` can select another allocated level; see the example and raw-view lifetime limitations above.
* `rgba32float`, `rg32float`, and `r32float` textures need the `float32-filterable` feature for `textureSample`; prefer `rgba16float` for lookup tables that are sampled with a filtering sampler.
* **See also:** `target`, `compute`, `Compute.set`, `Texture` from `vgpu/core`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Timer
description: GPU pass timer created by `timer(gpu)`; requires the `"timestamp-query"` device feature. Use it to find the expensive pass before optimizing: encoders only record, so CPU timing says nothing about GPU cost. Mark a pass with `FramePassOptions.timer` and the GPU brackets it with a begin/end timestamp pair. Decoded durations land in `timer.onResults`, in milliseconds, 1–2 frames after submit.
---

# Timer



## Import

```ts
import type { Timer, TimerSpan } from "vgpu";
```

## Signature

```ts
interface TimerSpan {
  readonly name: string;
}

interface Timer {
  span(name: string): TimerSpan;
  onResults(cb: (spans: Readonly<Record<string, number>>) => void): () => void;
  dispose(): void;
}
```

## Parameters

| Param              | Type                                                | Required | Default | Notes                                                                                                          |
| ------------------ | --------------------------------------------------- | -------: | ------- | -------------------------------------------------------------------------------------------------------------- |
| timer()            | —                                                   |        — | —       | No parameters.                                                                                                 |
| timer.span.name    | `string`                                            |        ✔ | —       | Non-empty result key. Spans are memoized per name, so `timer.span("shadows")` is allocation-free in hot loops. |
| timer.onResults.cb | `(spans: Readonly<Record<string, number>>) => void` |        ✔ | —       | Receives one frozen `name → milliseconds` record per timed frame.                                              |

**Returns:** `timer(gpu)` returns `Timer`; `span()` returns a `TimerSpan` to pass as `FramePassOptions.timer`; `onResults()` returns an unsubscribe function; `dispose()` returns `void`.

**Throws:**

* `VGPU-TIMER-INVALID` when `timer(gpu)` runs on a device without `"timestamp-query"` — request it: `init({ requiredFeatures: ["timestamp-query"] })`.
* `VGPU-TIMER-INVALID` for an empty or non-string span name — name each timed pass, e.g. `timer.span("shadows")`.
* `VGPU-TIMER-INVALID` for a span name reused within one frame (each name holds one begin/end pair per frame) — give the second pass its own span.
* `VGPU-TIMER-INVALID` for a non-`TimerSpan` `FramePassOptions.timer` value, or a span used with another gpu's frames — pass only `timer.span(name)` results, one timer per gpu.
* `VGPU-TIMER-INVALID` for any use of a disposed timer or its spans — create a new timer with `timer(gpu)`.
* `VGPU-TIMER-CAPACITY` when one frame times more than 2048 spans; a timer owns one timestamp query set and WebGPU `createQuerySet` caps `count` at 4096 (2 queries per span) — time fewer passes, or spread timing across frames.

## Examples

```ts
import { init, createMockAdapter, effect, frameLoop, target, timer } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init({ adapter: createMockAdapter({ features: ["timestamp-query"] }), requiredFeatures: ["timestamp-query"] });
const shadowMap = target(gpu, { size: [512, 512], depth: true });
const scene = target(gpu, { size: [256, 256], depth: true });
const casters = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0); }`));
const world = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }`));

const gpuTimer = timer(gpu);
gpuTimer.onResults((spans) => {
  console.log(`shadows ${spans.shadows}ms, main ${spans.main}ms`);
});

const loop = frameLoop(gpu, (f) => {
  f.pass({ target: shadowMap, timer: gpuTimer.span("shadows") }, (p) => p.draw(casters));
  f.pass({ target: scene, timer: gpuTimer.span("main") }, (p) => p.draw(world));
});
loop.stop();
```

```ts
import { init, timer } from "vgpu";

// Optional timing: only request the feature when the adapter has it.
const gpu = await init({ requiredFeatures: ["timestamp-query"] });
const gpuTimer = gpu.device.features.has("timestamp-query") ? timer(gpu) : undefined;
gpuTimer?.onResults((spans) => console.table(spans));
```

## Notes

* Start with a `Timer` before optimizing a suspected bottleneck: CPU wall-clock timings measure submission/encoding, not GPU execution. Results are asynchronous and normally arrive one to two frames after submit, so use them as a rolling signal rather than an immediate branch condition.
* Results are GPU durations decoded from timestamp pairs: `(end - begin)` nanosecond ticks converted to milliseconds. Timestamp values are implementation-defined, and WebGPU notes the counter "may reset ... which can result in unexpected values such as negative deltas"; vgpu clamps negative deltas to `0` instead of reporting garbage.
* Readback never blocks a frame: results resolve through rotated staging buffers, and when readbacks lag more frames than the ring holds, that frame's results are dropped rather than awaited. A dropped frame is dropped **whole** — no resolve is encoded at all, `onResults` simply does not fire for it, and nothing is merged or partially applied; the next frame that finds a free staging buffer reports again. `await gpu.settled()` covers pending readbacks for deterministic tests and teardown.
* One timer can be used from several frames that are open at the same time, but results stay scoped to the newest one: opening a frame retargets the timer's per-frame bookkeeping, so an older frame submitted afterwards encodes no resolve and reports nothing (its spans are dropped, never merged into the newer frame's results). Submitting it is always safe, however long it stayed open — the query set it referenced is kept alive for it.
* A manual `frame(gpu)` that attached a span holds the timer's query set until you `submit()` or `cancel()` it (a `frame(gpu, cb)` whose callback throws is canceled and releases it too). Dropping such a frame without either leaks those resources for the lifetime of the gpu — the same leak as a native `GPUCommandEncoder` you never `finish()` — because a frame is never assumed abandoned: it could still be submitted. Always close the frames you open — `submit()` them, or `frame.cancel()` the ones you decided not to submit, which releases the query set without encoding a resolve or reporting a result — or let `frame(gpu, cb)` do it for you; `gpu.dispose()` (or device loss) is the backstop.
* Results apply in submission order; a stale readback that lands after a newer one is discarded **entirely** — the whole set of spans from that frame is thrown away, never merged into the newer results. A readback that fails outright (device lost while mapping) is discarded the same way and reported on `gpu.onError` as `VGPU-QUERY-READBACK`; it never rejects a frame or `gpu.settled()`.
* Capacity starts at 32 spans per frame and grows only at frame boundaries — a pass that overflows the current query set goes untimed for that frame, and the next frame's larger set covers it. For the hard per-frame limit, see `VGPU-TIMER-CAPACITY` above.
* `dispose()` releases the timer's query set and resolve/staging buffers after in-flight readbacks settle. Calling it mid-frame is safe: every frame that attached a span still references the query set from its pass descriptors, so destruction is deferred until each of those frames reports back — submitted, failed or abandoned — including when several manual `frame(gpu)`s are open at once, each of which holds its own reference. In-flight readbacks still apply, so results already submitted are not lost. `gpu.dispose()` disposes the timers that gpu created. Create the timer once and reuse its spans.
* Timing granularity is the render pass: the pair lands in the pass descriptor's `timestampWrites` (`beginningOfPassWriteIndex`/`endOfPassWriteIndex`), so a span measures the whole pass, not individual draws.
* **See also:** `timer`, `Frame`, `FramePassOptions.timer`, `init`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Uniform
description: Low-level user-owned uniform buffer with a stable bind group at binding `0`. Prefer main API (`vgpu`) `set({ params: ... })` for ordinary values; use `Uniform` when you need byte-level writes or one buffer shared by many draws.
---

# Uniform



## Import

```ts
import { Uniform } from "vgpu/core";
import type { UniformOptions } from "vgpu/core";
```

## Signature

```ts
import type { Device } from "vgpu/core";

declare interface UniformOptions {
  readonly size: number;
  readonly label?: string;
  readonly visibility?: GPUShaderStageFlags;
  readonly bindGroupLayout?: GPUBindGroupLayout;
}

declare class Uniform {
  readonly device: Device;
  readonly size: number;
  readonly buffer: import("vgpu/core").Buffer;
  readonly bindGroupLayout: GPUBindGroupLayout;
  readonly bindGroup: GPUBindGroup;
  constructor(device: Device, opts: UniformOptions);
  get gpu(): GPUBuffer;
  write(data: BufferSource, offset?: number): void;
  destroy(): void;
  dispose(): void;
}
```

## Parameters

| Param                | Type                  | Required | Default                                                                           | Notes                                                                                                   |
| -------------------- | --------------------- | -------: | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| device               | `Device`              |        ✔ | —                                                                                 | Core device, usually `gpu.device` from the main API (`vgpu`) `init()`.                                  |
| opts                 | `UniformOptions`      |        ✔ | —                                                                                 | Buffer/layout options.                                                                                  |
| opts.size            | `number`              |        ✔ | —                                                                                 | Byte size. Used for `device.createBuffer({ usage: ["uniform", "copy_dst"] })` and `minBindingSize`.     |
| opts.label           | `string`              |        ✖ | `undefined`                                                                       | Forwarded to buffer label; layout label becomes `${label}.bgl`; bind group label becomes `${label}.bg`. |
| opts.visibility      | `GPUShaderStageFlags` |        ✖ | `GPUShaderStage.VERTEX \| GPUShaderStage.FRAGMENT` with numeric fallback `1 \| 2` | Ignored when `opts.bindGroupLayout` is supplied.                                                        |
| opts.bindGroupLayout | `GPUBindGroupLayout`  |        ✖ | A new binding-0 uniform layout                                                    | Reuse a pipeline/draw-owned layout. Binding `0` must be a compatible uniform buffer.                    |
| uniform.write.data   | `BufferSource`        |        ✔ | —                                                                                 | Bytes uploaded with `queue.writeBuffer`.                                                                |
| uniform.write.offset | `number`              |        ✖ | `0`                                                                               | Destination byte offset in the buffer.                                                                  |

**Returns:** Constructor returns `Uniform`; `gpu` returns the underlying `GPUBuffer`; `write()`, `destroy()`, and `dispose()` return `void`.

**Throws:** No main API (`vgpu`) `VGPU-*` errors are thrown directly by `Uniform`; invalid sizes, incompatible reused layouts, out-of-range writes, or destroyed-buffer usage can surface as core/native WebGPU validation errors. Binding a `Uniform` through main API (`vgpu`) can still trigger `VGPU-R1-OWNERSHIP-FLIP` if the same shader binding was first set with JS values.

## Examples

```ts
import { init, draw } from "vgpu/mock";
import { Uniform } from "vgpu/core";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const camera = new Uniform(gpu.device, { size: 64, label: "camera" });
camera.write(new Float32Array(16));

const drawable = draw(gpu, { shader: prepareShader(`
  struct Camera { viewProjection: mat4x4f }
  @group(0) @binding(0) var<uniform> camera: Camera;
  @vertex fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f {
    var p = array<vec2f, 3>(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
    return camera.viewProjection * vec4f(p[vi], 0, 1);
  }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }
`) });
drawable.set({ camera });
```

```ts
import { init, draw } from "vgpu/mock";
import { Uniform } from "vgpu/core";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const drawable = draw(gpu, { shader: prepareShader(`
  struct Params { value: f32 }
  @group(0) @binding(0) var<uniform> params: Params;
  @vertex fn vs_main() -> @builtin(position) vec4f { return vec4f(0, 0, 0, 1); }
  @fragment fn fs_main() -> @location(0) vec4f { return vec4f(params.value); }
`) });
const params = new Uniform(gpu.device, { size: 16, bindGroupLayout: drawable.layout(0) });
params.write(new Float32Array([1, 0, 0, 0]));
drawable.set({ params });
```

## Notes

* `Uniform` is user-owned from the first `draw.set({ name: uniform })`; vgpu binds its identity and never packs JS values into it.
* It creates a non-dynamic bind group. For many per-object uniforms with dynamic offsets, use `UniformPool` instead.
* Call `destroy()` / `dispose()` when the buffer lifetime ends.
* **See also:** `SharedUniforms`, `StructuredUniform`, `UniformPool`, `Draw.set`, `Effect.set`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: SharedUniforms
description: Values-first shared uniform/storage object created by `uniforms(gpu, values)`. It adopts binary WGSL layout lazily from the first compatible shader binding and reuses one stable buffer across shaders.
---

# SharedUniforms



## Import

```ts
import type { SharedUniforms } from "vgpu";
```

## Signature

```ts
interface SharedUniforms<T extends Record<string, unknown> = Record<string, unknown>> {
  set(values: Partial<T>): void;
}
```

## Parameters

| Param             | Type                                | Required | Default | Notes                                                                                                                   |
| ----------------- | ----------------------------------- | -------: | ------- | ----------------------------------------------------------------------------------------------------------------------- |
| uniforms.values   | `T extends Record<string, unknown>` |        ✔ | —       | Initial values are cloned. Layout and buffer are not created until first binding to a reflected uniform/storage buffer. |
| shared.set.values | `Partial<T>`                        |        ✔ | —       | Deep-merges plain objects and clones arrays/typed arrays before writing current values to the adopted layout.           |

**Returns:** `uniforms(gpu)` returns `SharedUniforms<T>`; `shared.set()` returns `void`.

**Throws:** `VGPU-R1-SHARED-UNIFORMS-LAYOUT-MISMATCH` when a later shader declares a structurally different layout for the same shared object; `VGPU-RING1-UNSUPPORTED` when address spaces differ, the binding is not a buffer, the binding has no host-shareable layout, or the layout is runtime-sized; `VGPU-SET-VALUE-INVALID` when the merged value has the wrong reflected shape or an out-of-range integer. Its structured detail includes the failure `reason` and complete value `path`.

## Examples

```ts
import { init, clock, effect, frame, target, uniforms } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const colorTarget = target(gpu, { size: [64, 64] });
const globals = uniforms(gpu, { time: 0, mouse: [0, 0] });
const wave = effect(gpu, prepareShader(`
  struct Globals { time: f32, mouse: vec2f }
  @group(0) @binding(0) var<uniform> globals: Globals;
  @fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
    return vec4f(uv, sin(globals.time) * 0.5 + 0.5, 1);
  }
`), { set: { globals } });

globals.set({ time: clock(gpu).time });
frame(gpu, (currentFrame) => currentFrame.pass({ target: colorTarget }, (pass) => pass.draw(wave)));
```

```ts
import { init, uniforms } from "vgpu/mock";

const gpu = await init();
const globals = uniforms(gpu, { exposure: 1, tint: [1, 1, 1] });
globals.set({ exposure: 1.25 });
```

## Frame value capture

When used in the uniform address space, direct frame draws and compute dispatches capture the current values. Calling `set()` between operations changes only later operations. The same revision can share an upload slice across pipelines in a frame.

`set()` validates and packs the merged values on every call and always updates the stored CPU values, so partial updates merge over the latest call. Frame-only consumers upload through the frame's captured pages instead of also writing the stable backing buffer. One-shot draws and dispatches flush pending stable-buffer values when used; repeated calls without an update do not upload them again. Canceled frames leave CPU updates applied but do not upload their captured pages.

When the newly packed bytes equal the previous ones, the update is not a new revision: later operations in the same frame reuse the snapshot already captured, and a pending upload stays pending (it is still flushed or retried on next use). Equality is bitwise on the packed bytes: re-setting an in-place-mutated typed array is detected, `+0` and `-0` differ, and values that round to the same `f32` are equal. You never need to compare values yourself; skipping a redundant `set()` saves only CPU work.

When adopted as storage, this object keeps a live backing buffer so GPU-written state persists, and every `set()` writes it, even with equal bytes, because the GPU may have changed it. Render bundles, raw/low-level resources and claimed bind groups also retain live contents; they do not acquire per-operation uniform snapshots.

Once a uniform is recorded in a render bundle, later updates keep its stable buffer live, including for raw WebGPU bundle replay. Accessing the implementation's `.buffer` or `.gpu` handle likewise flushes pending values and preserves immediate future writes for direct consumers; those handles are not part of the public `SharedUniforms` type. These live uniforms also write on every `set()`, even with equal bytes.

Frame captures live in pooled uniform pages owned by one frame until its GPU work completes or it is canceled; frames that repeat the same draws in the same order reuse their bind groups (see `Draw`). Each frame still uploads its own captured pages.

## Notes

* The first shader to bind the object chooses the WGSL layout. Keep struct member names/types/order aligned for every later shader that reuses it.
* Values must contain only members of that reflected struct. When spreading a shared settings object, select the fields for this binding; unrelated settings are rejected, not ignored. Validation of initial values happens when the first binding adopts its layout.
* Use shared uniforms for values like time, mouse, camera, exposure, and viewport data consumed by many passes.
* If one shader needs a different layout, create a second `uniforms(gpu)` object rather than mutating the first layout.
* `set()` clones and merges into a candidate, packs that candidate into temporary bytes, and commits only after validation succeeds. A rejected update leaves both the retained values and GPU bytes unchanged.
* **See also:** `uniforms`, `Effect.set`, `Draw.set`, `Uniform`, `StructuredUniform`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Visibility
description: GPU occlusion query handles created by `visibility(gpu)`; core WebGPU, no device feature required. Use them for occlusion culling: skipping expensive draws behind occluders in urban streets, interiors, and dense foliage. The pattern is two-phase culling. This frame, draw a cheap proxy under a query; next frame, skip the real object once confirmed hidden. Open the pass with `FramePassOptions.visibility`, wrap proxies in `pass.occlusion(handle, body)`, and gate real draws on `handle.hidden`. Results latch into the handle 1–2 frames after submit.
---

# Visibility



## Import

```ts
import type { Visibility, VisibilityOptions, VisibilityQuery } from "vgpu";
```

## Signature

```ts
interface VisibilityOptions {
  readonly capacity?: number;
}

interface Visibility {
  query(label: string): VisibilityQuery;
  reset(): void;
  dispose(): void;
}

interface VisibilityQuery {
  readonly label: string;
  readonly hidden: boolean;
  readonly state: "visible" | "hidden" | "unknown";
  readonly age: number;
  reset(): void;
  dispose(): void;
}
```

## Parameters

| Param              | Type                                 | Required | Default     | Notes                                                                                                                                                                                                                                          |
| ------------------ | ------------------------------------ | -------: | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visibility.options | `VisibilityOptions`                  |        ✖ | `{}`        | Optional; `visibility(gpu)` equals `visibility(gpu, {})`.                                                                                                                                                                                      |
| options.capacity   | `number`                             |        ✖ | `64`        | Query slots per frame — the size of the one occlusion query set this instance owns. It never grows: the set is bound to pass descriptors mid-frame, so capacity is a declared contract. Size it to the number of handles queried in one frame. |
| vis.query.label    | `string`                             |        ✔ | —           | Non-empty result key. Handles are stable — create them once outside the loop. A label stays claimed until its handle is disposed.                                                                                                              |
| query.hidden       | `boolean`                            |        — | `false`     | `true` only when a completed query confirmed zero passing samples (and no reset since). `"unknown"` and `"visible"` read as `false`: the safe default is to draw.                                                                              |
| query.state        | `"visible" \| "hidden" \| "unknown"` |        — | `"unknown"` | Latched result. `"visible"`: the last completed query saw at least one passing sample. `"unknown"`: no result since creation or the last reset.                                                                                                |
| query.age          | `number`                             |        — | `Infinity`  | Frames since the last applied result; `Infinity` before the first. Use it to distrust stale answers after the camera moved.                                                                                                                    |

**Returns:** `visibility(gpu)` returns `Visibility`; `query()` returns a stable `VisibilityQuery` handle; `reset()` and `dispose()` return `void`.

**Throws:**

* `VGPU-VIS-CAPACITY-LIMIT` when `capacity` is not an integer in `[1, 4096]` (WebGPU `createQuerySet` caps `count` at 4096) — lower it, or create several visibility instances.
* `VGPU-VIS-LABEL-DUPLICATE` when `vis.query()` receives a label that is already live — reuse the existing handle, or `dispose()` the old one first.
* `VGPU-VIS-DISPOSED` for any use of a disposed handle or instance — create a fresh one with `vis.query(label)` / `visibility(gpu)`.
* `VGPU-VIS-INVALID` for an empty or non-string label — label each queried object, e.g. `vis.query("statue")`.
* `VGPU-VIS-INVALID` for mismatched plumbing: a non-`Visibility` pass option, a non-`VisibilityQuery` `occlusion()` argument, a handle from another instance, or an instance used with another gpu's frames — keep one instance per gpu and pass only its own handles.
* Pass-side errors (`VGPU-VIS-NO-DEPTH`, `VGPU-VIS-CAPACITY`, `VGPU-QUERY-NO-VISIBILITY`, `VGPU-QUERY-NESTED`, `VGPU-QUERY-DUPLICATE`) are documented on `Frame`.

## Examples

```ts
import { init, draw, effect, frameLoop, target, visibility } from "vgpu/mock";
import { prepareShader } from "@vgpu/wgsl/prepare";

const gpu = await init();
const scene = target(gpu, { size: [256, 256], depth: true });
const world = effect(gpu, prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(1); }`));
const statue = draw(gpu, { shader: prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0.5); }`) });
const statueProxy = draw(gpu, {
  shader: prepareShader(`@fragment fn fs_main() -> @location(0) vec4f { return vec4f(0); }`),
  writeMask: [],           // write no color channels
  depth: { write: false }, // test depth, never write it
});

const vis = visibility(gpu, { capacity: 8 });
const qStatue = vis.query("statue");

const loop = frameLoop(gpu, (f) => {
  f.pass({ target: scene, visibility: vis }, (p) => {
    p.draw(world);                       // occluders fill depth first
    p.occlusion(qStatue, statueProxy);   // bounding proxy under the query
    if (!qStatue.hidden) p.draw(statue); // skip the real draw once confirmed hidden
  });
});
loop.stop();
```

The proxy must test against the scene without touching it: `writeMask: []` writes no color and `depth: { write: false }` tests but never writes depth — a writing proxy would stamp its pixels into the image. The query counts samples that pass the tests, so a non-writing draw still measures visibility; once a readback confirms zero passing samples, `qStatue.hidden` flips and the statue is skipped.

```ts
import { init, visibility } from "vgpu/mock";

// Camera cut / teleport: last frame's occlusion answers are meaningless — reset to "unknown"
// so everything draws until fresh results land.
const gpu = await init();
const vis = visibility(gpu);
const q = vis.query("statue");

function onCameraTeleport(): void {
  vis.reset(); // every handle: state "unknown", hidden false, age Infinity
}
onCameraTeleport();
console.log(q.state, q.hidden, q.age); // "unknown" false Infinity
```

## Notes

* Use visibility for scenes with many expensive objects and large occluders (interiors, city blocks, dense foliage). It is a cheap proxy, not a universal culling system: small/overlapping occluders can produce popping, and every query requires a depth-enabled target.
* Results are **zero vs non-zero only**, mirroring WebGPU occlusion query semantics: a resolved value of `0` means no samples passed depth testing inside the scope; any non-zero value is unspecified. vgpu decodes that to `"hidden"` / `"visible"` and never exposes a sample count.
* The occlusion scope body **always executes** — the proxy draw is what the GPU measures, so it cannot be skipped. Cull the real draws outside the scope by checking `q.hidden`.
* Latch contract: handle state changes only between frames (when a readback applies) and through `reset()`, so `hidden`/`state`/`age` are stable while a frame callback runs. Expect one frame of popping when an object comes back into view; oversized proxies soften popping at the cost of overdraw — the looser the proxy, the more the real object draws.
* `reset()` (per handle or whole instance) discards readbacks from pre-reset frames completely — every pre-reset result is dropped, not just downgraded, so a stale in-flight result can never resurrect after a camera cut.
* Slots are allocated per frame in `occlusion()` call order and resolved as one contiguous range appended to the frame encoder before submit; readback never blocks a frame: when readbacks lag more frames than the staging ring holds, that frame's resolve is skipped and its results are dropped **whole** — no handle is updated, all of them keep their previous state, and nothing is partially applied. A readback that lands stale (after a newer one already applied) or fails outright (device lost while mapping) is discarded the same way; failures are reported on `gpu.onError` as `VGPU-QUERY-READBACK` and never reject a frame or `gpu.settled()`, and a dropped result never degrades a handle to `"hidden"`. `await gpu.settled()` covers pending readbacks for deterministic tests and teardown.
* One instance can be used from several frames open at the same time, but results stay scoped to the newest one: opening a frame restarts slot allocation, so an older frame submitted afterwards encodes no resolve and updates no handle — its results are dropped whole rather than latching a stale `"hidden"`. Submitting it is always safe, however long it stayed open — the query set it referenced is kept alive for it.
* A manual `frame(gpu)` that opened a visibility pass holds the query set until you `submit()` or `cancel()` it (a `frame(gpu, cb)` whose callback throws is canceled and releases it too). Dropping such a frame without either leaks those resources for the lifetime of the gpu — the same leak as a native `GPUCommandEncoder` you never `finish()` — because a frame is never assumed abandoned: it could still be submitted. Always close the frames you open — `submit()` them, or `frame.cancel()` the ones you decided not to submit, which releases the query set without encoding a resolve or latching any handle — or let `frame(gpu, cb)` do it for you; `gpu.dispose()` (or device loss) is the backstop.
* `handle.dispose()` frees the label for reuse immediately. This is safe because in-flight readbacks resolve to handle object references captured per frame — never by label — and a disposed handle discards late results, so a new same-label handle can never observe the old handle's stale state.
* The pass target needs a depth attachment: without depth testing every rasterized sample passes and each query would report `"visible"`, useless for culling (`VGPU-VIS-NO-DEPTH`). MSAA targets and `depthReadOnly` passes both work — read-only depth still tests.
* One visibility instance owns one occlusion query set plus resolve/staging buffers; `dispose()` releases them once in-flight readbacks settle. Calling it mid-frame is safe: every frame that opened a visibility pass still references the query set from its pass descriptors, so destruction is deferred until each of those frames reports back — submitted, failed or abandoned — including when several manual `frame(gpu)`s are open at once, each of which holds its own reference. `gpu.dispose()` disposes the visibility instances that gpu created. Create the instance once and reuse it across frames.
* **See also:** `visibility`, `Frame`, `FramePassOptions.visibility`, `FramePass.occlusion`.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Bind Metal buffers
description: Validate explicit uniform ranges and use generated slot metadata with your own Metal encoder.
---

# Bind Metal buffers



The generated binding helper connects application-owned buffers to a program's Metal slots.
It does not own a pipeline, resource pool, or command buffer. You can use the helper for ordinary
render encoding or read the same slot metadata from your own native code.

<Callout type="warn">
  Warning: Native build tooling is under development. The `vgpu native` shim exists, but its
  operational companion and complete installed workflow are provided by the optional beta companion.
  The fixed-uniform render path is tested through the internal compiler adapter and native
  consumers. Device execution coverage is Apple silicon; this is not a release support matrix.
</Callout>

## Describe the uniform region

Use the `Gradient` shader and packed buffer from [Pack uniforms for Metal](/docs/native/macos/metal/uniforms).
Load the functions on the same device that created the buffer:

```swift
let gradient = try Gradient.load(device: device)
let layout = Gradient.Uniforms.params

let bindings = Gradient.Bindings(
  params: ShaderBufferRange(
    buffer: uniforms,
    offset: offset,
    length: layout.byteCount
  )
)
```

`ShaderBufferRange` stores immutable `buffer`, `offset`, and `length` properties. Constructing it
does not encode commands or validate it against a program. `Bindings` also stores immutable
properties; create another value when you want to select a different region or buffer.

The range retains its buffer reference. The application still owns GPU lifetime and synchronization,
including command buffers configured not to retain their resources. A retained Swift value does
not prove that earlier GPU work has finished reading the bytes.

## Validate before encoding

With the matching pipeline and vertex stream already selected, bind the uniforms before drawing:

```swift
try gradient.bind(bindings, to: encoder)
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
```

`bind` checks the full binding set and the encoder's device before calling any Metal setters.
It rejects negative offsets or lengths, ranges extending beyond their buffers, ranges smaller
than the shader's required size, misaligned offsets, and resources from another Metal device.
Containment checks do not add untrusted integers in a way that can overflow.

Validation failures throw `ShaderBindingError`. Its cases distinguish `invalidRange`,
`insufficientRange`, `misalignedOffset`, `resourceDeviceMismatch`, and `encoderDeviceMismatch`.
The first four identify the authored binding name; size and alignment failures include the
required and supplied values. No slots have been changed when one of these checks fails.

The required buffer-offset alignment covers both the shader layout and native binding constraints.
The candidate uses the Apple GPU family's four-byte constant-buffer minimum and a conservative
256-byte fallback outside that tested device family, combined with the layout's alignment. That
fallback is a compatibility policy, not a claim that every Metal GPU requires 256 bytes or that
Intel support has been verified. See Apple's
[Metal feature set tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf).

This requirement is not the same property as `layout.alignment`, which describes WGSL packing.
Do not infer an application's allocation strategy from a shader's group or binding number.

After validation, the helper sets only the program's recorded shader buffer slots. It does not
clear unrelated slots, change a pipeline, supply vertex data, draw, end encoding, or submit work.
Call it again after selecting another binding set or after native code overwrites one of those slots.

## Use the slot metadata directly

You do not need to use the convenience encoder method. Validate without encoding, then set the
same buffers yourself:

```swift
try gradient.validate(bindings)

for slot in layout.slots {
  switch slot.stage {
  case .vertex:
    encoder.setVertexBuffer(bindings.params.buffer, offset: bindings.params.offset, index: slot.index)
  case .fragment:
    encoder.setFragmentBuffer(bindings.params.buffer, offset: bindings.params.offset, index: slot.index)
  case .compute:
    preconditionFailure("This example selects a render program")
  }
}
```

`layout.slots` is an immutable array of stage-qualified `ShaderBufferSlot` values, each with
`stage` and `index` properties. A WGSL `@group(0) @binding(0)` declaration does not promise Metal
index `0`; use the generated mapping. A binding read by both stages has a mapping for each stage.

`validate` checks resources against the loaded program's device. Unlike `bind`, it does not have
an encoder to check: native code must use a compatible encoder and pipeline. Neither method
can inspect your current vertex descriptor, vertex stream slots, attachment formats, resource
contents, or application synchronization.

Vertex streams and shader buffers share the vertex stage's buffer namespace. Keep your vertex
stream slots disjoint from the generated vertex-stage slots. Fragment-stage slots are independent.

## Keep the boundary explicit

The first binding profile covers fixed-size uniform buffers in render programs without effective
compiler-internal payloads. It does not accept textures, storage buffers, runtime-sized arrays,
compute encoders, or compiler-specific data merely because Metal has a setter for them.

An explicit `length` is host-side metadata. Metal's direct buffer setters bind a buffer and an
offset, not a hardware-enforced bounded subrange. This helper does not provide memory isolation
between regions of a buffer.

Shared, managed, and private buffers remain native resources. Pack into CPU-visible memory;
for private storage, perform your own staging copy. Apply any synchronization required by your
chosen storage mode, and do not overwrite a region while submitted GPU work reads it.

The direct slot metadata is useful outside convenience rendering, but it is not a general indirect
command buffer contract. Indirect commands also require compatible pipelines, resource residency,
and any compiler-required internal data. Those capabilities need their own documented integration.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Load Metal functions
description: Load generated shader programs on your Metal device and use their functions in native pipelines.
---

# Load Metal functions



A generated shader package gives your Metal code access to selected shader functions without
requiring a vgpu renderer. You create the device, resources, pipelines, encoders, and command buffers.
vgpu generates the package and resolves its compiled function names.

<Callout type="warn">
  Warning: This is the direct Metal API under development. The command shim exists, but its
  operational companion and complete installed workflow are provided by the optional beta companion. This page defines
  the first function-loading slice; generated uniform packing and resource binding helpers are
  separate work, not APIs implemented by this example.
</Callout>

## Add the generated package

One generated configuration produces one Swift package with one library product and one `.metallib`
resource. Add that local package to your application and select its library product. For a module
named `AppShaders`, your Swift files import `AppShaders`.

The first package is self-contained: it depends on system frameworks, not `VGPUABI`, a vgpu context,
or a separately installed Swift support package. Independent shader packages can coexist in an app.
Qualify program names with their module when two modules define the same name.

Each package needs a distinct module identity. Module and program names must be supported Swift
identifiers and must not collide with generated declarations, imported module names, or another
generated file on a case-insensitive filesystem. Generation reports a naming error instead of
silently renaming a program.

The build tool records the selected emitted function names and the library's expected SHA-256 in
generated Swift. Those names and resource paths are implementation details, not arguments the
application must supply. Keep the generated source and its library together; do not edit either file.

## Load a render program

Assume your generated package contains a render program named `Triangle` with a selected vertex
and fragment entry point:

```swift
import Metal
import AppShaders

let triangle = try Triangle.load(device: device)

let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = triangle.vertex
descriptor.fragmentFunction = triangle.fragment
descriptor.colorAttachments[0].pixelFormat = .bgra8Unorm

let pipeline = try device.makeRenderPipelineState(descriptor: descriptor)
```

`device` is the application's existing `MTLDevice`. `Triangle.load(device:)` returns
`Triangle.Functions` with nonoptional `vertex` and `fragment` properties. Both conform to
`MTLFunction`. The loader verifies their stages before returning; Swift's Metal API does not give
vertex and fragment functions different static protocol types.

A program with only a selected vertex or fragment stage exposes only that stage's property. A
compute program exposes `compute`. Missing selected functions fail loading rather than returning
optional properties that the caller must unwrap.

The application configures vertex layouts, attachment formats, blending, depth, sample count, and
pipeline options. Loading a shader does not create a pipeline or decide whether that pipeline is
compatible with the application's render pass.

## Load a compute program

A generated compute program uses the same loading pattern:

```swift
let step = try StepParticles.load(device: device)
let pipeline = try device.makeComputePipelineState(function: step.compute)
```

You create the compute encoder, bind resources, and dispatch work through Metal. Loading functions
does not dispatch anything. Uniform packing, shader resource slots, and compiler-required internal
data must be handled by the matching binding integration; this loading API alone does not establish
that arbitrary shader resources have been bound correctly.

Shader overrides are selected before compilation. This slice does not perform runtime Metal
function-constant specialization. It rejects any remaining function-constant metadata, including
constants with defaults, rather than implicitly selecting a different specialization policy.

## Keep ownership explicit

Load once for a program and device, then retain the returned functions or the pipeline you create
from them. Each `load` call may load the packaged library again; there is no global library cache,
device registry, or hidden context. Reuse is controlled by your application.

The loader reads its private package resource, checks the library bytes, and asks the supplied
device to create a Metal library. Returned functions belong to that device. It creates no other
GPU resources, queues, pipelines, command buffers, submissions, or completion observers.

You own the lifetime and synchronization of resources used by your commands. This API neither
tracks external work nor replaces Metal completion handling. Swift build still requires Swift
tooling, but the built application needs no Node.js, Tint, or Apple shader compiler at runtime.

## Handle loading errors

The generated module exposes `ShaderLoadError`. Errors distinguish an unavailable or unreadable
library file inside the package resource bundle, changed library bytes, a Metal library creation failure, a missing selected
function, an unexpected function stage, and unsupported function-constant specialization.
Function errors identify the authored program and selected stage; system failures retain their
underlying error. Do not parse diagnostic strings or rely on a physical resource path.

Include the complete SwiftPM resource bundle when distributing your application. If the entire
bundle is missing, SwiftPM's generated `Bundle.module` accessor can terminate the process before
the loader can return `ShaderLoadError`. The loader uses standard SwiftPM resource lookup; it does
not recover from an incorrectly packaged application by searching arbitrary filesystem locations.

```swift
do {
  let triangle = try Triangle.load(device: device)
  // Use triangle.vertex and triangle.fragment in your native pipeline.
} catch let error as AppShaders.ShaderLoadError {
  // Report the shader-loading failure through your application's error UI.
  print(error)
}
```

An integrity hash detects accidental changes or crossed package contents; it is not a signature
that authenticates an untrusted package. Use trusted package sources. Failures from creating or
executing your Metal pipeline remain Metal errors, not loading errors from this generated module.

## Continue with Metal

See [Render WGSL with Metal](/docs/native/macos/metal/rendering) for an imported WGSL program consumed
by an application-owned vertex descriptor, buffer, and render pipeline.

Loaded functions can be used in compatible native pipelines, including multiple color outputs.
The loader does not impose a single-color target, a frame loop, or an encoder abstraction.
Native indirect command buffers have their own pipeline, resource, and device requirements; this
loader does not implement TypeScript render-bundle semantics or a general ICB binding adapter.

The initial deployment target is macOS 14 on Apple silicon. The exact supported Swift/Xcode matrix
still needs release validation; successfully loading a function on one machine is not that matrix.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Render WGSL with Metal
description: Compile imported WGSL into a generated package and draw with your own Metal pipeline, vertex buffer, and render pass.
---

# Render WGSL with Metal



Write shader behavior in WGSL. Your Swift code chooses the vertex data, target formats, pipeline,
and commands. The generated package connects the compiled shader functions to that native code;
it does not introduce an effect, frame, or renderer object.

<Callout type="warn">
  Warning: Native build tooling is under development. The `vgpu native` shim exists, but its
  operational companion and complete installed workflow are provided by the optional beta companion.
  This guide's Triangle example is exercised through the internal compiler adapter. The configuration
  format and local companion are implemented; separate installed-candidate coverage builds and runs
  the documented Count and Gradient programs. The compiler also supports the fixed uniform profile described in
  [Pack uniforms for Metal](/docs/native/macos/metal/uniforms).
</Callout>

## Share shader code

Create a pure module containing the color calculation:

```wgsl
// shaders/palette.wgsl
export fn color() -> vec4f {
  return vec4f(1.0, 0.0, 0.0, 1.0);
}
```

Import it from the entry shader:

```wgsl
// shaders/triangle.wgsl
import { color } from "./palette.wgsl";

@vertex
fn vertex_main(@location(0) position: vec2f) -> @builtin(position) vec4f {
  return vec4f(position, 0.0, 1.0);
}

@fragment
fn fragment_main() -> @location(0) vec4f {
  return color();
}
```

These are the same [WGSL modules](/docs/concepts/wgsl-modules) used by the TypeScript API. Resolution
follows the imports before Tint validates and translates the selected entry points. Changing the
imported function changes the generated shader; Swift does not need a copy of that calculation.

The vertex input at location `0` is supplied by a native vertex descriptor. It is not a WGSL
`@group`/`@binding` resource. This example needs no generated resource-binding helper.

## Select the program

Select the two entry points that form the program:

```json
{
  "moduleName": "AppShaders",
  "programs": [
    {
      "name": "Triangle",
      "source": "shaders/triangle.wgsl",
      "entryPoints": {
        "vertex": "vertex_main",
        "fragment": "fragment_main"
      }
    }
  ]
}
```

Source paths are relative to the configuration. Imports remain relative to their importing module.
The compiler checks the selected stages and records their shader interfaces before building a
library. Your call to `makeRenderPipelineState` validates the native pipeline configuration,
including its stage compatibility. The compiler does not infer a renderer from the program's name
or put target formats in the shader configuration.

The internal adapter currently receives the source modules explicitly. Reading a configuration
from disk, installing the compiler, and publishing output directories are separate command work.
Generation returns a complete package's files only after translation and offline compilation
succeed. A failed compile does not return Swift paired with an older library.

## Create a native pipeline

After adding the generated package, load the selected functions on your application's `device`:

```swift
import Metal
import AppShaders

let triangle = try Triangle.load(device: device)

let vertices = MTLVertexDescriptor()
vertices.attributes[0].format = .float2
vertices.attributes[0].offset = 0
vertices.attributes[0].bufferIndex = 0
vertices.layouts[0].stride = 8
vertices.layouts[0].stepFunction = .perVertex

let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = triangle.vertex
descriptor.fragmentFunction = triangle.fragment
descriptor.vertexDescriptor = vertices
descriptor.colorAttachments[0].pixelFormat = .rgba8Unorm

let pipeline = try device.makeRenderPipelineState(descriptor: descriptor)
```

`attributes[0]` matches the shader's `@location(0)`. Each vertex contains two 32-bit floats, so
the stride is eight bytes. The vertex stream uses Metal buffer index `0`, chosen by the application.
That choice is valid for this resource-free program; a program with shader buffers must keep
vertex streams disjoint from the generated vertex-stage shader and internal buffer slots.
Fragment-stage buffer slots use a separate namespace.

The pipeline format must match the actual attachment. Loading the functions does not validate
your vertex buffer, create a target, or choose blending, depth, sample count, or culling.

## Provide vertex data

A full-screen triangle needs three positions:

```swift
let positions: [Float] = [-1, -1, 3, -1, -1, 3]
let vertexBuffer = positions.withUnsafeBufferPointer { pointer in
  device.makeBuffer(
    bytes: pointer.baseAddress!,
    length: pointer.count * MemoryLayout<Float>.stride,
    options: .storageModeShared
  )!
}
```

This is application-owned vertex data with an explicitly configured Metal format, not a copy of
a Swift struct into a WGSL uniform layout. The short example assumes allocation succeeds; handle
Metal's optional allocation results in application code.

## Encode the draw

Use your existing render command encoder, whose attachment matches the pipeline:

```swift
encoder.setRenderPipelineState(pipeline)
encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
```

The application creates the render pass and command buffer, ends encoding, and submits the work.
For this shader, a covered pixel is opaque red. Changing the imported helper to return
`vec4f(0.0, 1.0, 0.0, 1.0)` makes it green after regeneration, without changing the Swift draw code.

Do not overwrite shared vertex bytes while submitted GPU work still reads them. Native command
completion and pipeline-execution errors remain the application's responsibility, including when
it mixes generated shaders with other Metal commands.

## Keep the compiler profile explicit

The render compiler adapter requires one selected vertex and one selected fragment stage per
program. Resources can be fixed uniform structs containing `f32`, `vec2f`, `vec3f`, and `vec4f`
members. Active overrides, other resource kinds, and effective compiler-required internal buffers
or storage-size payloads are rejected. Source features outside this profile
fail explicitly; the compiler does not produce a package whose required data cannot be supplied.

If translation reports an effective internal payload, assuming that the missing bytes would be
zero does not make that shader safe to use. Support follows a generated binding contract and an
executed test, not just successful MSL generation. The check uses the compiler's actual metadata;
it does not infer payload requirements merely from the presence of a built-in such as `vertex_index`.

This compiler boundary is narrower than the [function loader](/docs/native/macos/metal/functions),
which can already expose a selected compute function or a single render stage from a compiled
library. Storage buffers, textures, specialization, and compiler-supported language
features are added through their own documented integration, without adding a Swift renderer.

Compiler failures identify their stage: source resolution, native validation/translation, or
offline Metal compilation. Authored locations are reported only when a real source mapping is
available; a resolved-source diagnostic is not relabeled as an authored line number. An unknown
worker, mismatched response identity, unsupported metadata, cancellation, or failed compiler
process fails the build instead of returning an unchecked package.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Pack uniforms for Metal
description: Write generated Swift values into application-owned memory using the shader's binding layout.
---

# Pack uniforms for Metal



A WGSL uniform describes bytes, not a Swift memory layout. The generated package gives you an
ordinary Swift value and a binding-specific packer. You decide where the bytes live and when the
GPU can read them.

<Callout type="warn">
  Warning: Native build tooling is under development. The `vgpu native` shim exists, but its
  operational companion and complete installed workflow are provided by the optional beta companion.
  This example is tested through the internal compiler adapter: WGSL reflection, generated Swift
  packing and bindings, and a native render pass with GPU pixel readback. The current profile
  covers fixed uniform structs with flat `f32`, `vec2f`, `vec3f`, and `vec4f` members.
</Callout>

## Declare shader data

Keep the data declaration beside the entry shader that uses it:

```wgsl
struct Params {
  accent: vec3f,
  gain: f32,
  phase: vec2f,
}

@group(0) @binding(0) var<uniform> params: Params;

@vertex
fn vertex_main(@location(0) position: vec2f) -> @builtin(position) vec4f {
  return vec4f(position, 0.0, 1.0);
}

@fragment
fn fragment_main() -> @location(0) vec4f {
  let color = params.accent * params.gain;
  return vec4f(color + vec3f(params.phase, 0.0), 1.0);
}
```

Name this program `Gradient` in the same build input used by
[the rendering guide](/docs/native/macos/metal/rendering). The generated value is `Gradient.Params`;
the packer for the `params` binding is `Gradient.Uniforms.params`.

Layout belongs to the binding, not to Swift's `MemoryLayout<Gradient.Params>`. For this shader,
`accent` starts at byte `0`, `gain` at byte `12`, and `phase` at byte `16`. The binding occupies
`32` bytes with an alignment of `16`. The packer writes each float at its reflected WGSL offset
and fills padding with zero.

A generated value type can be shared by bindings with the same fields. Each binding still has
its own packer and physical layout; use the packer for the destination binding.

## Pack into CPU memory

Use a generated value to supply fields by name:

```swift
import AppShaders

let layout = Gradient.Uniforms.params
let params = Gradient.Params(
  accent: SIMD3<Float>(0.35, 0.55, 1.0),
  gain: 0.8,
  phase: SIMD2<Float>(0.0, 0.0)
)

var bytes = [UInt8](repeating: 0, count: layout.byteCount)
try bytes.withUnsafeMutableBytes { destination in
  try layout.pack(params, into: destination)
}
```

`pack` works with a writable raw byte span. It does not need a Metal device, create a buffer, or
retain the destination. The span can start at an unaligned CPU address: individual scalar bytes
are written without treating the destination as a Swift struct.

The destination must contain at least `layout.byteCount` bytes. A shorter span throws
`ShaderPackingError.destinationTooSmall(required:actual:)` before changing any bytes. A larger
span is allowed; bytes after `layout.byteCount` remain untouched. Only pass memory that is valid
and writable for the duration of the call.

The first packing profile covers flat structs containing `f32`, `vec2f`, `vec3f`, and `vec4f`.
Nested structs, arrays, matrices, integer fields, and runtime-sized storage need their own
validated packing support; an unsupported layout fails generation instead of using a guessed
Swift representation.

## Write a shared Metal buffer

The same packer can write into a region of an application-owned buffer:

```swift
import Metal

let offset = 256
let uniforms = device.makeBuffer(
  length: offset + layout.byteCount,
  options: .storageModeShared
)!

try layout.pack(
  params,
  into: UnsafeMutableRawBufferPointer(
    start: uniforms.contents().advanced(by: offset),
    count: layout.byteCount
  )
)
```

This short example assumes allocation succeeds. The prefix before `offset` is not modified.
The example's offset is an allocation choice, not a claim that all Metal buffers require
256-byte offsets. `layout.alignment` describes WGSL layout; the native binding must also satisfy
the buffer-offset requirements for the device and address space. See Apple's
[Metal feature set tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf).

Packing does not synchronize access. Wait until earlier GPU work has finished reading a shared
region before writing it again, or use another region. For a private buffer, pack into CPU-visible
staging memory and encode your own copy. Do not call `contents()` on a private buffer.

## Bind an explicit region

The generated binding helper takes a buffer, offset, and visible length:

```swift
let gradient = try Gradient.load(device: device)
let bindings = Gradient.Bindings(
  params: ShaderBufferRange(
    buffer: uniforms,
    offset: offset,
    length: layout.byteCount
  )
)

try gradient.bind(bindings, to: encoder)
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
```

The application has already selected a matching pipeline, supplied its vertex stream, and
created the render pass. `bind` validates every supplied range before setting any shader buffer
slots. It does not allocate persistent GPU resources, change the pipeline, draw, or submit work.

The range's `length` is host-side validation metadata, not a Metal memory-access boundary.
Metal's direct buffer setters receive a buffer and offset, not a bounded range. Keep the full
buffer alive and synchronize its use as you would for handwritten Metal commands.

See [Bind Metal buffers](/docs/native/macos/metal/bindings) for validation guarantees and direct
stage-qualified slot access. A vertex-stage slot and a fragment-stage slot with the same index
do not collide. A native vertex stream must avoid the generated vertex-stage buffer slots.

Direct packing and direct Metal resources are the integration boundary. They do not require
vgpu to own a frame loop, resource pool, renderer, or SwiftUI view.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Render to multiple textures
description: Connect WGSL fragment outputs to application-owned Metal color attachments, including sparse locations.
---

# Render to multiple textures



A fragment shader can write more than one result in a draw. Declare the outputs in WGSL, then
connect each output location to the same color-attachment index in your Metal pipeline and render
pass. The generated package exposes the functions; your application owns the textures and pass.

<Callout type="warn">
  Warning: Native build tooling is under development. The `vgpu native` shim exists, but its
  operational companion and complete installed workflow are provided by the optional beta companion.
  The example below and its sparse-location variant are tested through the internal compiler
  adapter and a generated Swift package, with both textures read back from Metal on Apple silicon.
</Callout>

## Declare two outputs

```wgsl
// shaders/layers.wgsl
struct LayersOutput {
  @location(0) color: vec4f,
  @location(1) mask: vec4f,
}

@vertex
fn vertex_main(@location(0) position: vec2f) -> @builtin(position) vec4f {
  return vec4f(position, 0.0, 1.0);
}

@fragment
fn fragment_main() -> LayersOutput {
  return LayersOutput(vec4f(1.0, 0.0, 0.0, 1.0), vec4f(0.0, 1.0, 0.0, 1.0));
}
```

Select `vertex_main` and `fragment_main` in a program named `Layers`, as in
[Render WGSL with Metal](/docs/native/macos/metal/rendering). That guide also supplies the `device`,
two-component `vertices` descriptor, and fullscreen `vertexBuffer` used below.

## Match the pipeline attachments

```swift
import Metal
import AppShaders

let layers = try Layers.load(device: device)
let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = layers.vertex
descriptor.fragmentFunction = layers.fragment
descriptor.vertexDescriptor = vertices
descriptor.colorAttachments[0].pixelFormat = .rgba8Unorm
descriptor.colorAttachments[1].pixelFormat = .rgba8Unorm
let pipeline = try device.makeRenderPipelineState(descriptor: descriptor)
```

Each format describes a target, not a generated resource. The format must be compatible with the
shader output and the texture attached when you draw. Configure blending and write masks through
the same native descriptors when needed. See Apple's
[pipeline color attachments](https://developer.apple.com/documentation/metal/mtlrenderpipelinedescriptor/colorattachments).

Create the two textures on your device:

```swift
let target = MTLTextureDescriptor.texture2DDescriptor(
  pixelFormat: .rgba8Unorm,
  width: 64,
  height: 64,
  mipmapped: false
)
target.storageMode = .private
target.usage = [.renderTarget]
let color = device.makeTexture(descriptor: target)!
let mask = device.makeTexture(descriptor: target)!
```

The short example assumes allocation succeeds. Both textures use the same dimensions and sample
count. Add the native usage flags required by later work, such as `.shaderRead` for sampling.

## Draw into both textures

With an application-owned `commandBuffer`, attach the textures and encode one draw:

```swift
let pass = MTLRenderPassDescriptor()
pass.colorAttachments[0].texture = color
pass.colorAttachments[0].loadAction = .clear
pass.colorAttachments[0].storeAction = .store
pass.colorAttachments[1].texture = mask
pass.colorAttachments[1].loadAction = .clear
pass.colorAttachments[1].storeAction = .store

let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass)!
encoder.setRenderPipelineState(pipeline)
encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 0)
encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
encoder.endEncoding()
```

After successful submission and completion, covered pixels are opaque red in `color` and opaque
green in `mask`. The application decides whether to sample, copy, present, or keep these textures.
Neither output has to be a drawable or pass through a vgpu-owned target object.

The pipeline describes formats; the [render pass attachments](https://developer.apple.com/documentation/metal/mtlrenderpassdescriptor/colorattachments)
select actual textures, load actions, and store actions. Loading the functions does not validate
your future attachments, and successful pipeline creation alone does not prove every shader
output will be stored. Keep all intended output locations configured in both descriptors.

## Preserve sparse locations

Locations are indices, not the order of present outputs. If the shader changes its two locations
to `1` and `4`, change the pipeline and pass attachment indices to `1` and `4` as well. Leave the
unused pipeline formats at `.invalid` and the unused pass textures unset. Do not compact the two
outputs back to `0` and `1`.

This example does not add dual-source blending, multisampling, or depth/stencil support to the
declared compiler profile. Those features have separate language, pipeline, and device contracts.
Multiple color outputs need no new Swift renderer primitive: the composition remains ordinary
Metal code around the generated functions.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Build and verify a Metal package
description: Check the native toolchain, validate shaders, regenerate an owned Swift package, and detect stale or modified output.
---

# Build and verify a Metal package



Native tooling runs on the machine that generates the shaders. The Swift application consumes the
resulting package without running Node.js or translating WGSL at launch.

> Beta: The grammar, help, lazy dispatch, `doctor`,
> `check`, `build`, and `verify` are implemented. These commands have real local-tarball coverage with an offline
> installation and dependency install scripts disabled; build coverage publishes to an initially
> absent destination and independently checks the resulting files and hashes. Verification succeeds
> without compiler or temporary-directory prerequisites and leaves parent recovery files untouched.
> An external Swift consumer builds those published payloads, relocates its build tree, and executes
> the documented compute and render programs on this host. The companion is an optional public beta.
> See [Local installed qualification](/docs/native/macos/metal/tooling/publication#local-installed-qualification)
> for replacement, interruption and recovery coverage and the separate cold-cache RC candidate check.
> Broader platform compatibility and release support remain unqualified.

## Prepare the build machine

Keep build tooling in development dependencies and pin both packages to the same exact RC:

```bash
npm install --save-dev --save-exact vgpu@next @vgpu/native@next
npx vgpu native doctor
```

Check that both resolved versions match. The `0.0.1` native bootstrap has no functionality.
The worker is bundled in npm; consumers do not download or build Tint separately.
This beta uses an ad hoc signed worker without Developer ID signing or notarization.
Validate it on the intended Apple Silicon development/CI hosts without disabling system
security protections. Stable compatibility, Intel GPU support and a minimum-OS matrix
are not promised. APIs, generated Swift and toolchain requirements may change during beta.

`doctor` checks the supported Node version, selected Xcode/SDK and Swift tools, the authenticated
vgpu-owned Tint worker, and Apple's Metal compiler. It compiles and links a small Metal probe;
finding `xcrun` is not enough to prove that the downloadable Metal compiler component works.

The command needs no project configuration and writes no project output. It may use temporary
files for its probe, which it cleans up. It does not install components, change the selected Xcode,
download an unpinned compiler, or bypass macOS security settings. Missing prerequisites produce
a failing exit status with an actionable diagnostic.

A successful toolchain probe is not GPU execution coverage. Real shader tests and the release's
physical-device matrix remain separate checks.

See [Check the native toolchain](/docs/native/macos/metal/tooling/doctor) for the findings, selected-Xcode
behavior, and diagnostic boundaries.

## Validate before generating

After [configuring a package](/docs/native/macos/metal/tooling/configuration), run:

```bash
npx vgpu native check
```

`check` reads the configuration and resolved WGSL inputs, validates selected stages and supported
resource layouts, and runs the pinned semantic and Metal-translation boundary. It stops before
Apple's offline compiler and does not write the configured output.

Each invocation captures the configuration and complete imported source graph once. Validation
uses that captured input even if an editor changes a file while the compiler is running. A check
does not inspect, create, or repair the output directory; checking a project with no generated
package is valid.

The check uses the same supported compiler profile as `build`. It does not retry a rejected shader
with extra language features or infer missing application state. Reported locations distinguish
resolved WGSL from authored source; the tool does not invent an original line number when no mapping
is available.

A successful check writes a human-readable report to standard output. It identifies the module,
lists programs in name order with their selected stages, and reports the captured input fingerprint.
For the documented `AppShaders` configuration, the report has this shape; the actual fingerprint
is 64 lowercase hexadecimal characters:

```text
Native shaders: valid
Module: AppShaders
[ok] Count: compute
[ok] Gradient: vertex, fragment
Input fingerprint: ...
```

Success exits `0`. A failed check exits `1` with a diagnostic on standard error instead of a
successful report. Cancellation retains the CLI's signal exit statuses. Neither a successful
check nor its fingerprint claims that an output package exists, is intact, or is current.

When Tint supplies structured diagnostics, the failure report begins with `Native shaders: invalid`
and preserves each diagnostic's severity, code, phase, and message in its original order. Multiline
messages are indented beneath the first line. If a diagnostic includes a location, a separate
indented line identifies it explicitly as resolved WGSL. For example, the shape is:

```text
Native shaders: invalid
[error] VGPU-NATIVE-WGSL-INVALID (wgsl): ...
  Resolved WGSL: Intermediate/resolved.wgsl:<line>:<column>
```

The line and UTF-8 byte column are one-based positions in the virtual WGSL document passed to Tint,
not positions in an authored shader file. No authored filename or line is inferred from that range,
and no location line is added when the compiler supplies none. The report stays on standard error,
with empty standard output and exit status `1`; it does not print a successful program summary or
input fingerprint. Other failures retain their ordinary error diagnostic.

## Generate the package

```bash
npx vgpu native build
```

The build validates the inputs, translates every selected stage, compiles and links the Metal
library, and generates the Swift package. It completes a sibling staging directory before
publishing it to the configured output.

A WGSL rejection during preparation uses the same structured Tint failure report as `check`,
including severity, code, phase, message and any resolved-WGSL location. It exits `1` with that
diagnostic on standard error and no successful report. It does not label this compiler failure
as a publication outcome or report existing sibling recovery paths: preparation failed before
entering the publisher. The existing package and recovery files remain untouched.

The library, generated Swift, and ownership record come from the same captured project. Editing
a shader during compilation does not splice newer source into part of that package. A later
verification can report the captured generation as stale against those edits.

The build captures its selected tool environment before awaiting project work. Relative
`DEVELOPER_DIR` and `TMPDIR` selections keep their meaning from that invocation's working directory;
changing the process environment later does not switch the Apple compiler halfway through the build.
These host settings are not copied into the generated package or its logical input fingerprint.

A successful build writes a human-readable publication report to standard output and exits `0`.
The module and input fingerprint identify the captured project; the absolute output path and
ownership-record hash come from the checked publication receipt. The report has this shape:

```text
Native package: published
Module: AppShaders
Output: /absolute/path/to/Generated/AppShaders
Input fingerprint: ...
Record SHA-256: ...
```

Both hashes are 64 lowercase hexadecimal characters. Compilation or staging alone is not success:
the command reports publication only after the publisher returns its checked receipt. A failure
does not print this successful report; the diagnostic retains any known publication outcome.

A failed program, cancelled build before publication, or rejected output boundary leaves the last
valid package unchanged. Publishing replaces the directory as one operation: the output path names
a complete old or new package, never a partially written package. If the destination filesystem
cannot provide the required operation, the build fails without replacing the package.

Finish generation before starting a Swift build, and do not edit generated output concurrently.
Cancellation after the commit point may leave the complete new package in place. The diagnostic
must retain that publication outcome, including when cleanup fails or an interrupted helper leaves
the outcome unknown.

See [Publish generated packages](/docs/native/macos/metal/tooling/publication) for safe parent creation,
physical-directory locking, atomic replacement, and recovery. These operations do not silently
discard unrelated files or interrupted transactions.

Add the generated package to your Swift project and use its functions, packers, and bindings.
The application still creates its pipelines, buffers, textures, encoders, and submissions. A build
does not launch the application or prove that its native pipeline state is compatible.

## Verify an existing package

```bash
npx vgpu native verify
```

`verify` checks the ownership record, supported artifact format, generated file set and hashes,
and whether the current configuration and resolved source inputs match the recorded logical build
inputs. It does not regenerate output or invoke Tint, `metal`, or `metallib`.

Verification first captures the current project inputs, then checks the existing package's owner
and integrity, and finally compares its recorded fingerprint with the captured inputs. A package
can be intact and owned by the project but still stale. That result is a failure with a request to
build again, not permission to modify the record or a claim that verification generated anything.

A successful verification writes a human-readable report to standard output and exits `0`:

```text
Native package: current
Module: AppShaders
Output: /absolute/path/to/Generated/AppShaders
Input fingerprint: ...
```

The absolute output path, module and 64-character lowercase hexadecimal fingerprint come from the
verified package and captured project. `current` means the observed package passed ownership,
integrity and input-freshness checks; it does not mean this invocation published or executed it.
A failed verification exits `1` with a diagnostic on standard error and no successful report.
The command needs no compiler or temporary compiler directory and does not repair files. Recovery
records beside the output are not package contents: successful verification leaves them untouched
and does not establish an earlier publication outcome or authorize their removal.

Before inspecting the package, verification checks the original output path components as described
in [Configure a Metal package](/docs/native/macos/metal/tooling/configuration). A symlink hidden by `..`
is an invalid destination, even when a package at the simplified path would be intact. This path
check does not reopen captured shader inputs; freshness still uses the one captured graph.

The hidden `.vgpu-native-output.json` record belongs to the tool. It identifies the artifact format,
owning configuration relative to the package, logical input fingerprint, and exact generated file
hashes. Ownership does not change when you edit a shader: an unchanged old package can be replaced
by its owning configuration even when its input fingerprint is stale. Do not edit the record to
bypass a conflict. It is integrity metadata, not a signature or an application runtime dependency.
The record is versioned UTF-8 JSON no larger than 64 KiB; unsupported or malformed records fail
validation before their file list is used.

One publication accepts exactly `Package.swift`, generated Swift, `Shaders.metallib`, and that
ownership record, with a combined 128 MiB limit. Payload transport uses chunks no larger than
64 KiB; it does not encode the complete library into a control message. See
[Publish generated packages](/docs/native/macos/metal/tooling/publication) for staging verification and
transaction-record limits.

Changing an imported helper makes the output stale even if its entry file did not change. Editing
only a comment in that helper still changes the captured source bytes. If the owned package remains
intact, the diagnostic is `Generated output is stale; build the Metal package again` on standard
error, with exit status `1` and no successful report. Verification leaves both the changed source
and the old package untouched; it does not regenerate or repair either one.

Editing generated Swift, replacing the library, removing a generated file, or adding an unexpected file
also fails verification. The initial policy treats this directory as an immutable generated
package: build it as a dependency of your consuming Swift project, whose build products live
outside this directory. A `.build` directory created by building the generated package directly
is still an unexpected addition; the tool reports it instead of deleting it.

For example, modifying the generated Swift in `AppShaders` reports
`Generated file has changed: Sources/AppShaders/Shaders.generated.swift` on standard error with
exit status `1` and no successful report. This is an integrity failure even when the configured
WGSL inputs have not changed. Verification preserves the modified file and its original ownership
record; it does not rewrite either one to accept the edit.

The package must contain ordinary directories and regular, unlinked files. Symbolic links,
hard-linked files, special files, and unexpected empty directories fail verification too. The
verifier reads the limited ownership record before using its file list, then hashes payloads in
small chunks. Cancelling stops the inspection without changing the package. Verification is a
read-only observation, not a lock or permission to replace the directory: builds must repeat the
ownership checks inside their publication boundary.

Hash checks detect mismatches. They are not a signature proving who authored a package, and a
library hash does not promise byte-identical Apple compiler output across toolchain versions.
Verification also does not execute shaders or validate the application's resource contents.

Commit the generated package when another build machine must consume it without Node.js or the
Metal compiler. Regenerate it intentionally when changing shaders or compiler versions, and review
the generated diff together with the source change.

## Consume the generated package

Add the generated local package as a dependency of your Swift project and select its library
product. Use the [function loaders](/docs/native/macos/metal/functions) and binding helpers with your
own Metal device, resources, pipelines, encoders, and command buffers. Build the consuming project,
not the immutable generated directory, and distribute its complete SwiftPM resource bundle.

The local installed test uses the actual published `Package.swift`, generated Swift, and
`Shaders.metallib` together in an external Swift consumer, checking their hashes and sizes before
copying them. It does not substitute output from a separate source-level compiler call. The
ownership record and recovery files stay in the original build project, whose files and retained
identities remain unchanged after consumption.

For the imported `Count` shader in [Resolve shader inputs](/docs/native/macos/metal/tooling/sources),
one `(2, 1, 1)` workgroup writes `[100, 101]`. This is distinct from the runtime-array example in
the compute-dispatch guide. The documented `Gradient` uniforms produce an RGBA pixel approximately
`[0.28, 0.44, 0.8, 1]`. Checking these GPU results connects the installed tooling's output to the
application-facing Swift API, beyond merely validating files and hashes.

A local test that builds and relocates the consumer and guards generation-tool lookup through
`PATH` is still not a clean-machine test: it does not block absolute executable paths or SDK
discovery. The generated package has no external Swift dependencies, but the consumer build still
requires Swift and system frameworks. Release support and execution on a machine without the
generation toolchain require their own qualification.

## Use the commands in automation

Run `vgpu native` or `vgpu native --help` to list the four commands. Each command accepts `--help`
or `-h`. Help does not load the native companion package, inspect a project, or require a working
Metal toolchain.

The `vgpu` command loads the optional `@vgpu/native` companion only for a valid native operation.
An absent or incompatible companion fails with an installation or compatibility diagnostic.
Other vgpu commands do not load it. Native execution uses the supported Node 22 build-host profile;
displaying help does not enforce that toolchain profile.

Project commands accept one `--config <file>`; use the same file for `check`, `build`, and `verify`.
Relative config arguments are resolved from the invocation's working directory. Omitting the
option selects `vgpu.native.json` in that directory, without searching ancestors. `doctor` does
not accept `--config`.

Unknown commands or options, repeated `--config`, missing values, and positional arguments are
usage errors, including when combined with `--help`. The initial commands have no `--target`,
`--json`, `--force`, or custom-worker option.

A successful command exits `0`. Usage errors exit `2`; missing prerequisites, unsupported shaders,
stale output, and verification failures exit `1`. An interrupted invocation waits for its cleanup
and exits `130` for SIGINT or `143` for SIGTERM. A post-publication interruption still reports that
the new package was published; it does not imply that the old package remains in place.

The initial command surface is deliberately four operations. Watching files, scaffold generation,
pixel-comparison commands, editor plugins, and automated publication are separate integrations.
The native test suite still compares real GPU results even without a public comparison command.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Configure a Metal package
description: Select WGSL entry points and an owned output directory for a generated Swift package.
---

# Configure a Metal package



A native configuration selects the shader programs that ship together in one Swift package.
It does not describe your application's pipelines, resource allocations, render passes, or frame loop.

> Beta: The parser, help, lazy dispatch, `doctor`,
> `check`, `build`, and `verify` are implemented. Local-tarball tests install offline with dependency install
> scripts disabled and exercise build publication to an initially absent destination. An external
> Swift consumer executes the resulting compute and render programs on this host. The companion
> is an optional public beta. See
> [Local installed qualification](/docs/native/macos/metal/tooling/publication#local-installed-qualification)
> for replacement and recovery coverage; broad release compatibility remains unqualified.

## Select the programs

Create `vgpu.native.json` beside your shader directory. The configuration must be a regular UTF-8
JSON file no larger than one MiB:

```json
{
  "schemaVersion": 1,
  "moduleName": "AppShaders",
  "programs": [
    {
      "name": "Gradient",
      "source": "shaders/gradient.wgsl",
      "entryPoints": {
        "vertex": "vertex_main",
        "fragment": "fragment_main"
      }
    },
    {
      "name": "Count",
      "source": "shaders/count.wgsl",
      "entryPoints": { "compute": "count_main" }
    }
  ],
  "output": "Generated/AppShaders"
}
```

Use the `Gradient` source from [Pack uniforms for Metal](/docs/native/macos/metal/uniforms) and the small
imported `Count` source from [Resolve shader inputs](/docs/native/macos/metal/tooling/sources).
[Dispatch WGSL compute](/docs/native/macos/metal/compute/dispatch) provides a separate runtime-array
`Count` variant with different bindings and results. Each guide identifies its implemented profile
and remaining validation work.

`moduleName` names the Swift module and library product. A program's `name` names its generated
Swift type: `Gradient.load(device:)` and `Count.load(device:)` in this example. Names must be safe,
unambiguous Swift identifiers; unsupported names fail validation instead of being silently renamed.

A render program selects exactly one vertex and one fragment entry. A compute program selects
exactly one compute entry. Entry names are authored WGSL names, not emitted Metal function names.
You cannot combine render and compute stages in the same program record.

The versioned configuration rejects unknown fields. This initial command profile does not configure
shader overrides, extra language features, custom compiler binaries, or an alternative backend.
Those options need explicit compiler contracts, not passthrough flags.

## Resolve paths from the configuration

`source` and `output` are relative to the configuration's directory, regardless of the shell's
working directory. Use forward slashes in configuration paths. Relative WGSL imports remain
relative to the module that imports them. Imported modules follow vgpu's purity rules; resource
and entry declarations stay in the entry shader.

See [Resolve shader inputs](/docs/native/macos/metal/tooling/sources) for how captured source bytes,
package imports, and dependency changes become build inputs.

Project commands use `./vgpu.native.json` by default. They do not search parent directories.
Select a file explicitly in a monorepo:

```bash
npx vgpu native check --config ./apps/example/vgpu.native.json
```

Validation uses the selected programs and their resolved dependencies. A file that is not in that
graph is not automatically another program. Referencing a shader from Swift also does not remove
the other configured programs from the compiled library: one configuration is one shader payload.
Use separate configurations and output directories when you need separate packages.

## Reserve a generated directory

The output directory belongs to the tool. Keep handwritten Swift and other application files
outside it. The build writes the package source, compiled library, and a hidden ownership and
integrity record as one output.

The first build accepts a missing or empty destination. Replacing a nonempty directory requires a
matching ownership record and an unchanged set of tool-owned files. Modified generated files and
unexpected files are reported instead of being discarded. There is no force flag that bypasses
ownership checks.

Filesystem roots, the home directory, the configuration directory or its ancestors, an ancestor of
any resolved source input, and symlinked output paths are not valid destinations. These checks
include the physical targets of input aliases and every existing component of the output path.
Components are checked before simplifying `.` or `..`: `Link/../Generated` is rejected when `Link`
is a symbolic link, even if the simplified destination would be safe. A regular file in that
position is rejected too. Missing components do not end the inspection; a later `..` can return
to an existing directory whose next component still needs checking. This preflight creates nothing.
A valid destination boundary does not establish ownership of an existing package; replacement
still requires the unchanged ownership and file checks above. Changing the configured output does not
delete the previous directory. Move or remove an old package yourself after updating its consumers.

## Keep toolchain targets explicit

The current generated package declares Swift tools version `6.0` and macOS `14` as its deployment
floor. Offline compilation targets Metal `2.4`. These are artifact settings, not evidence that every
machine at those versions has passed testing. The release matrix must separately establish build-host,
consumer-toolchain, and physical GPU coverage.

The package has no external Swift dependencies. Its app-facing contents are generated Swift and
a compiled `.metallib`; Node.js and the WGSL translator remain build-time tools. See
[Load Metal functions](/docs/native/macos/metal/functions) for adding it to a Swift consumer, then
[Build and verify a Metal package](/docs/native/macos/metal/tooling/build) for regeneration and checks.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Check the native toolchain
description: Diagnose the build host, selected Apple tools, pinned WGSL compiler, and offline Metal compilation without a shader project.
---

# Check the native toolchain



Before investigating a project shader, check that the machine can run the native build tools:

```bash
npx vgpu native doctor
```

<Callout type="warn">
  Warning: `vgpu native doctor` is implemented and exercised from real local package tarballs,
  installed offline with dependency install scripts disabled. It uses the packaged pinned worker
  and Apple's offline compiler. The same installed workflow checks shaders, builds a package at
  an initially absent destination, and verifies that package without compiler prerequisites. A separate
  Swift consumer executes the published compute and render programs on this host; that GPU coverage
  comes from the consumer, not the doctor probe. The companion is an optional public beta.
  See [Local installed qualification](/docs/native/macos/metal/tooling/publication#local-installed-qualification)
  for replacement/recovery coverage and the separate cold-cache RC candidate check.
  Neither establishes clean-OS, signing or broad release compatibility qualification.
</Callout>

The command needs no `vgpu.native.json`, does not read project shaders, and writes no generated
package. It reports evidence and a suggested next action for each failed prerequisite.
The pinned compiler is a private asset of the optional native companion. Diagnosis does not search
the current directory or developer checkout for a worker, download one, or accept a worker override.

## Read the findings

The initial checks run in a fixed order:

| Check | What it establishes                                                                                               |
| ----- | ----------------------------------------------------------------------------------------------------------------- |
| Node  | A stable Node.js 22 release is running, matching the current build-tooling profile.                               |
| Host  | The build host is macOS; the report records the operating system and process architecture.                        |
| Xcode | A selected developer directory provides usable Xcode command-line tools.                                          |
| SDK   | The selected tools can identify the macOS SDK and its version.                                                    |
| Swift | The selected toolchain provides Swift 6 or newer, as required by the generated package manifest.                  |
| Tint  | The authenticated pinned worker validates and translates a fixed WGSL probe.                                      |
| Metal | Apple's compiler compiles and links a fixed kernel with the same Metal and deployment settings as package builds. |

Finding a tool's executable is not enough for the last two checks. Tint must answer the checked
compiler protocol, and Metal must produce a nonempty compiled library. These probes do not create
a render or compute pipeline, acquire a GPU, or run the application.

Each finding is successful, failed, or skipped because a prerequisite is unavailable. The overall
result is healthy only when every required check succeeds. A skipped check is not evidence of
support. A healthy result does not establish the release's build-host, Swift-consumer, or physical
GPU compatibility matrix; those require separate tests.

The human-readable report begins with `Native toolchain: healthy` or `Native toolchain: unhealthy`,
followed by one finding for each check in the order above. For example, its shape on a healthy host
is shown below; the actual evidence contains the detected versions, paths, and probe results:

```text
Native toolchain: healthy
[ok] node: ...
[ok] host: ...
[ok] xcode: ...
[ok] sdk: ...
[ok] swift: ...
[ok] tint: ...
[ok] metal: ...
```

Unsuccessful findings use `[fail]` or `[skip]`. Multiline evidence is indented beneath its finding;
a suggested remedy, when available, appears on an indented `Next:` line. The report goes to standard
output, including failed findings. Exit status is `0` only for a healthy report and `1` for an
unhealthy report or a failure that prevents diagnosis. Failures that prevent a report go to standard
error. Cancellation still waits for owned cleanup; the CLI preserves its signal exit statuses.

## Use the selected Apple tools

The diagnostic honors `DEVELOPER_DIR` when it is set; otherwise it uses the selected Xcode developer
directory. It keeps that selection consistent for the run without changing the machine's default.
See Apple's [command-line tools settings](https://developer.apple.com/documentation/xcode/configuring-command-line-tools-settings)
for selecting the intended Xcode installation.

An installed Xcode may still need its optional Metal Toolchain. The diagnostic reports that failure
and suggests installing the component yourself. Apple's
[component installation guide](https://developer.apple.com/documentation/xcode/downloading-and-installing-additional-xcode-components)
describes the Xcode settings and command-line options.

The diagnostic never installs components, switches Xcode, accepts licenses, runs privileged repair
commands, downloads a different compiler, or bypasses macOS security settings.

## Keep probes bounded

Discovery commands have short deadlines and bounded output. Compiler probes also have deadlines;
a hung subprocess cannot leave the diagnostic waiting indefinitely. Cancelling stops further
probes and cleans up the temporary files owned by the run.

The diagnostic captures its temporary-directory selection when the invocation starts; a relative
`TMPDIR` belongs to that invocation's working directory. Both Tint and Apple probes keep that
captured context even if the process environment changes while diagnosis is running.

Temporary-file or cleanup failures are reported as failures, not a healthy result. The diagnostic
does not remove unrelated files or clean interrupted project builds. After the toolchain passes,
continue with [Build and verify a Metal package](/docs/native/macos/metal/tooling/build).


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Publish generated packages
description: Understand output ownership, atomic replacement, cancellation, and recovery when a Metal package is generated.
---

# Publish generated packages



A generated package contains Swift code and a compiled library that must agree. The build prepares
them together, then replaces the output directory as one operation.

<Callout type="warn">
  Warning: The companion is an optional public beta. The local qualification below uses
  an offline local-tarball installation with a warm dependency store and dependency install scripts
  disabled. The separate RC candidate check below covers a cold npm cache and normal install scripts.
  Neither qualifies signing, quarantine, other hosts or filesystems, or a release compatibility matrix.
  Fault instrumentation does not establish ordinary loader behavior. Pin exact matching RC versions and validate your build environment.
</Callout>

## Local installed qualification

The installed public command has representative coverage for seven publication and recovery families:

1. **Normal replacement:** missing and ordinary empty destinations, followed by owned rebuilds with
   unchanged inputs and changed module/shader contents. Each actual generation has independently
   checked files, hashes, ownership record and current verification. Old files are removed through
   checked cleanup without changing their bytes. This is not a binary reproducibility guarantee.
2. **Integrity conflicts:** an in-place edit to `Package.swift` is rejected without changing the
   conflicting bytes, original ownership record or identities, or creating transaction state.
3. **Real signals:** pre-commit SIGINT exits `130` / `not-published` without confirmation, retaining
   a complete prepared stage and journal with output absent. Post-acknowledgment SIGTERM exits
   `143` / `published` / `acknowledged`, completes cleanup and leaves current output.
4. **Lost owned-exchange acknowledgment:** actual helper death before exchange yields `not-published`
   without confirmation; death after the real exchange yields `published` / `reconciled`.
   One uninjected read-only reconciliation preserves the original error, both complete generations
   and the original journal. Ordinary verification checks the old or new current output respectively.
5. **Inconclusive reconciliation:** after pre-exchange helper death, test instrumentation changes one
   old payload byte in place. The command reports `unknown` without confirmation, retaining the
   original helper error and reconciliation-failure context, exact changed output, complete new
   stage and unchanged journal. It neither retries publication nor deletes the evidence.
6. **Post-publication cleanup refusal:** an unexpected test-created entry in the old stage prevents
   finalization cleanup. The failed command reports `published` / `acknowledged` and `cleanup-failed`,
   retaining all four old files, the unexpected entry and journal. The complete new output verifies
   as current; there is no rollback or reconciliation. This checks integrity-based cleanup refusal,
   not every possible unlink, permission or disk failure.
7. **Subsequent invocations:** unrecognized recovery records remain conflicts. A later ordinary build
   recognizes the journal retained after an actual missing-destination publication with lost
   acknowledgment and reports that earlier transaction without changing its package or evidence.
   Its `not-published` outcome concerns the new invocation, not the earlier publication.

Complementary lower-level native tests cover staging, missing/empty publication and read-only
reconciliation, byte-identical and changed-module owned exchanges, owned recovery before and after
exchange, and rejection of an old generated subtree on another filesystem device. These bounded
representatives do not establish every fault combination or a broader platform support matrix.

## Cold-cache RC candidate qualification

The `0.5.0-rc.1` candidate installs eight matching tarballs outside the checkout with an empty
npm cache, normal lifecycle scripts, no workspace links or overrides, and verified versions/hashes.
Installed native commands and the relocated compute/render consumer run with network denied.
Swift compilation keeps its normal SwiftPM sandbox without outer network denial; no system
security is disabled. This covers one Apple Silicon host (macOS 26.6.2, Node22.19.0, Xcode26.2),
not a clean OS or compatibility matrix. After publication, check npm against exact CI tarballs.

## Reserve the destination

Keep handwritten files outside the configured output. The first build accepts a missing or empty
directory. Replacing a nonempty directory requires the owning configuration's unchanged package,
including its exact file set and integrity record. A stale input fingerprint does not remove that
ownership; modified or unexpected output does.

The package records a relative path back to its owning configuration. Ownership compares the
current configuration files, not their path spelling or contents. An accepted alias to the same
configuration, an earlier atomic save, or moving the project and package together does not by
itself transfer ownership. A different configuration with identical contents is still a different
owner. The old generated module name and fingerprint need not match the new generation.

The build checks the original output path and every captured source path before preparing to
publish. It must not overwrite its configuration, shaders, or their physical ancestors. See
[Configure a Metal package](/docs/native/macos/metal/tooling/configuration) for path restrictions and
[Build and verify a Metal package](/docs/native/macos/metal/tooling/build) for integrity checks.

After compilation succeeds, the build can create missing container directories such as `Generated`
in `Generated/AppShaders`. It checks components without following symbolic links. New container
directories are not generated package contents and remain in place if a later operation fails;
the build does not recursively remove their ancestors during cleanup.

## Prepare one generation

On macOS, publication uses a small filesystem helper compiled locally from the installed tool's
source with the selected Xcode C compiler. This helper is a build-time component, not part of the
generated Swift package or application. It needs no separate binary download or persistent cache.
Its compilation and execution can fail without replacing the package.

The helper holds a lock on the physical output parent while the build checks ownership, stages
the generation, publishes, and cleans up. Sibling outputs in the same parent also conflict.
Alternate spellings of that physical directory do not provide independent locks. A second build
reports the conflict instead of interleaving writes.

Output-adjacent writes stay relative to the opened directory, including staging, the recovery
record, and cleanup. Checking a path once and later reopening it by name would not provide that
boundary. If the parent changes, the tool does not follow its replacement to publish elsewhere.

A hidden parent-scoped recovery record identifies the transaction before staging is created.
Before replacement, it records the expected old and new directory identities and package records.
The staged generation must contain the complete checked file set; a directory name alone is not
proof that its contents are tool-owned.

The recovery record is separate from `.vgpu-native-output.json`, which remains inside each
generated package. Neither is an application runtime dependency or an author signature. An
unrecognized file occupying a reserved recovery name is a conflict, not a file to overwrite.

For an owned replacement, the helper opens the old package under the same physical parent lock
and reads its bounded integrity record before creating transaction state. The tool validates that
record and its configuration ownership, then the helper checks the old package's complete tree
and actual bytes through the retained directories. The new generation does not supply the old
module's paths, lengths, or hashes. Ownership and integrity are rechecked before exchange; old
package cleanup uses its own verified file set, with the recovery record removed last.

Before creating transaction state for an owned replacement, every generated directory and all four
old package files must be on the same filesystem device as the retained package root and physical
output parent. A generated subtree mounted from another device is a conflict, even when its file
names, bytes, and ownership record otherwise match. It is not adopted for replacement or cleanup.
This device boundary applies to generated contents, not the owning configuration: an accepted
configuration alias may resolve to another device. Matching device identities do not by themselves
prove the absence of every possible mount or alias topology.

### Bound one transaction

Publication accepts exactly the four generated files described in
[Build and verify a Metal package](/docs/native/macos/metal/tooling/build). Their combined raw byte size
must not exceed 128 MiB. This is a tooling safety boundary, not a promise that every package below
that size will compile or load on every device. For an owned replacement, this limit applies
separately to each generation.

The helper receives file contents in chunks no larger than 64 KiB and writes each chunk relative
to the retained staging directory. It does not place the complete library in a JSON or base64
message. The generated ownership record and the separate transaction recovery record are each
bounded to 64 KiB of UTF-8 data.

Output, module, staging, and recovery names must be single valid filesystem components: no slash,
NUL, control characters, `.` or `..`. Their UTF-8 bytes must fit the opened parent filesystem's
reported name limit. The build does not truncate, normalize, case-fold, or silently choose another
name when a value is invalid or reserved.

Before a generation is called prepared, the helper reopens every staged file through retained
directory descriptors. It requires ordinary single-link files, the exact four-file tree, declared
lengths, and matching SHA-256 hashes after reading the bytes back. The intent record exists before
the staging directory, and the staging directory's actual identity is recorded before payload
transfer begins.

## Replace the directory

The helper classifies the destination under the physical parent lock before staging starts.
That choice remains fixed for the transaction: a missing destination is not reclassified as empty
if another directory appears while publication is in progress.

The operation depends on that observed destination:

| Destination             | Publication behavior                                                                                |
| ----------------------- | --------------------------------------------------------------------------------------------------- |
| Missing                 | Publish exclusively; a destination that appears meanwhile causes a conflict.                        |
| Empty directory         | Replace only if it is still an ordinary empty directory.                                            |
| Unchanged owned package | Exchange the complete directories, leaving the old package at the staging name for checked cleanup. |

The tool verifies the expected directory identities before replacement. The destination filesystem
must provide the required atomic operation; unsupported filesystems fail without a copy-and-delete
fallback. There is no force flag that bypasses ownership or identity checks.

The output path names a complete old or new package, never a partially written package. Finish
generation before a Swift build or another consumer that opens several package files. Atomic
directory replacement is not a snapshot across separate file opens: a reader spanning the exchange
could otherwise read one file from each version.

Do not edit generated output or move its parent concurrently with the build. The ownership checks
do not guarantee safety against a process deliberately changing files between validation and
replacement. Atomic namespace replacement also does not by itself promise persistence after
power loss.

### Repeat a build

Use the same `vgpu native build` command for the first generation and later rebuilds. An ordinary
empty output directory can receive the first package; it does not need an ownership record yet.
A nonempty output must instead be an intact generated package owned by the selected configuration.
Both a current package and an intact package made stale by shader changes can be rebuilt.

A successful rebuild reports `Native package: published`. The new output contains only its new
generation's files, even when the generated module name changed. Cleanup uses the old generation's
recorded paths; it does not keep obsolete generated files or remove unrelated files from the parent.
Run `vgpu native verify` with the same configuration to check that the resulting package is current.
Verification does not establish whether a directory exchange occurred or clean recovery files.

Modified generated files, additional handwritten files, or a different owning configuration prevent
ordinary replacement. Rejection preserves the conflicting file bytes and original ownership record;
the build does not repair them or rewrite the record to accept the edit. There is no force option
that discards those conflicts. A retained transaction also prevents an ordinary retry:
follow [Recover without guessing](#recover-without-guessing) before
deciding what to do with that evidence.

## Interpret an interruption

Successful replacement is the commit point. Diagnostics distinguish three outcomes:

* **Not published:** the tool knows replacement did not happen. A previously valid output remains
  unchanged, although newly created container directories or recovery state may remain.
* **Published:** replacement succeeded. A cancellation or cleanup problem cannot turn that result
  into a claim that the old package is unchanged. A later parent change is reported separately;
  successful replacement does not assert that the original path still names that directory.
* **Outcome unknown:** a replacement request may have reached the helper, but its result was not
  confirmed. The recorded transaction and actual directory identities need inspection before retry.

Cancellation stops work before the commit request when possible. After that request, the build
must preserve publication evidence while it finishes or reports recovery. It never automatically
rolls a published package back because a later cleanup step failed.

A pre-commit SIGINT can leave a complete prepared staging package and its recovery record while
reporting `not-published` and exiting `130`. There is no publication confirmation in that report.
The retained paths are evidence to inspect, not permission to retry or delete the staged package.

If SIGTERM arrives after an acknowledged publication, the interrupted command exits `143` while
reporting `published` and `Confirmation: acknowledged`. Completed cleanup can leave no retained
paths to report; the interruption still does not roll back the complete published package.

If the live invocation loses publication confirmation, it makes one bounded, read-only
reconciliation attempt after the original helper exits. It reacquires the physical parent lock
and compares the recorded transaction,
original destination classification, expected directory identities, and complete package contents
with the generation it prepared. It does not send another commit request, recreate a missing
parent, or remove recovery state.

The complete new package at the destination must retain the prepared directory's identity to
prove publication. For a transaction that originally targeted a missing destination, that same
intact directory still at staging with the destination absent can instead establish that publication
did not happen. For an empty-directory replacement, proving non-publication requires both the
intact prepared directory still at staging and the original destination directory still present
and exactly empty. A missing destination or a different empty directory does not provide that proof.

For an owned exchange, reconciliation establishes that publication happened when
the complete new package is at the destination with its original prepared directory identity,
exact file set, lengths, and hashes. Its generated directories and files must remain on the physical
parent's filesystem device. The recorded plan must match the original live transaction, including
the old module, file manifest, integrity record, and configuration identity accepted before exchange.
This is historical publication evidence, not a fresh ownership or input-freshness check.

Proving that an owned exchange did not happen requires both original generations: the complete old
package must remain at the destination with its original directory identity, and the complete new
package must remain at staging with its prepared identity. Each package is checked against its own
module, exact file set, lengths, and hashes; both retained directory trees and all generated files
must stay on the physical parent's filesystem device. A missing destination, a substituted root,
or an incomplete or modified generation leaves the outcome unknown, even when the other package
appears intact. Equal content hashes alone do not establish either directory's identity.
An in-place edit to an old payload prevents this negative proof even when its directory and file
identities and its byte length have not changed.
The two module names may differ. An intact old package can provide this historical evidence even
though it no longer matches the current project's module or input fingerprint.

An old package left at staging is recovery evidence, not permission to delete it. Its contents are
not required to prove publication of the complete new generation at the destination. Reconciliation
does not downgrade that proof because old staging bytes have changed. It does not clean either
generation or the journal, reopen the current configuration, or authorize
another exchange. The original failure is still reported after a proved non-publication, without
a publication receipt.

A conclusive reconciliation refines the reported outcome; it does not turn the failed invocation
into a successful build. The diagnostic preserves the original error and distinguishes reconciled
publication from an acknowledged commit. If the lock, identities, record, or contents cannot be
verified, the outcome remains unknown. An already requested cancellation does not skip this
bounded evidence check.

If reconciliation itself fails, the command reports the original publication error alongside
the reconciliation failure. The original failure remains visible. Failure to establish a checked
outcome must not add a publication confirmation.

When a failed invocation carries a checked publication receipt, its command report prints
`Confirmation: acknowledged` or `Confirmation: reconciled` immediately after the publication
outcome. The value comes from that receipt: `acknowledged` means the live helper's response was
checked; `reconciled` means the later read-only evidence check established publication. No
confirmation line is added without a receipt, and the command does not infer one from a directory
name or matching hashes.

For example, losing the helper response after a real publication can produce this failure report:

```text
Native publication: published
Confirmation: reconciled
[error] helper-failed: Metal publication published: Invalid publication staging helper response
Inspect retained paths (not cleanup authority):
  /absolute/output/parent/.vgpu-native-publication.json
  /absolute/output/parent/AppShaders
```

This remains a failed invocation with empty standard output, not a successful build report or
permission to remove the retained files. The original error and paths remain in the report;
the additional confirmation describes the evidence behind the publication outcome. Ordinary
failure exits `1`, while cancellation retains the documented signal exit status.

## Recover without guessing

A new build encountering an interrupted transaction reports the recorded output and recovery
paths. The initial workflow does not silently discard an earlier transaction. Preserve its files
until their relationship to the recorded generation has been established; an unknown or modified
directory is not eligible for cleanup.

A recognized record must be well-formed and match the locked physical parent. Its diagnostic
identifies the earlier transaction and recorded output, even when the current configuration names
a different sibling output. Recognizing the record does not establish package integrity or the
outcome of publication. Unrecognized or inconsistent records remain conflicts and are left intact.

For example, an ordinary later build can encounter the prepared journal retained after a previous
invocation published but lost its helper acknowledgment. If staging and the journal-update file
are absent, the recognized-transaction report lists only the remaining journal:

```text
Native publication: not-published
[error] interrupted-transaction: Metal publication not-published: Interrupted publication <transaction-id> for /absolute/output/parent/AppShaders
Inspect retained paths (not cleanup authority):
  /absolute/output/parent/.vgpu-native-publication.json
```

The transaction and output in this message come from the recognized earlier record. `not-published`
describes this new invocation: it does not contradict an earlier `published` / `reconciled` report.
This invocation has no publication receipt and adds no confirmation line. It exits `1` with empty
standard output and leaves the earlier package and recovery evidence intact; recognizing the
transaction does not authorize another publication, cleanup, or reconstruction of its outcome.

When an unrecognized recovery record prevents this invocation from publishing, the command reports
`not-published`, its error code and original message, and the retained paths on standard error.
For an unrecognized record beside a retained staging directory, the report has this shape:

```text
Native publication: not-published
[error] conflict: Metal publication not-published: Unrecognized publication recovery record
Inspect retained paths (not cleanup authority):
  /absolute/output/parent/.vgpu-native-stage
  /absolute/output/parent/.vgpu-native-publication.json
```

This failure exits `1` with empty standard output. The outcome describes the current invocation;
it does not establish what an earlier transaction did or imply that no output package exists.
The report preserves the retained paths supplied by the publisher in their original order, rather
than deriving them from the current configuration or guessing a missing transaction. Inspect these
locations before deciding how to recover. The command does not delete or repair them, retry the
build, or print a successful publication report. Signal exit statuses remain as described in
[Build and verify a Metal package](/docs/native/macos/metal/tooling/build).

Matching content hashes are not enough to identify which directory was exchanged: rebuilding
unchanged inputs can produce identical records. Recovery also checks the expected directory
identities. Names, modification times, and a staging-name prefix do not authorize deletion.

Normal cleanup removes only the unchanged, transaction-owned staging and recovery state. If
cleanup fails, the diagnostic retains the original failure and identifies the exact remaining
path. It must not remove unrelated files in the parent.

For an acknowledged owned exchange, an unexpected old-stage entry discovered by finalization's
tree check prevents cleanup before the old generated files are removed. The failed invocation
still reports `published` and `Confirmation: acknowledged`; the new package is not rolled back.
The old staging package, including the unexpected entry, and recovery record remain for inspection.

If a transfer ends partway through a file, the live helper can clean it only after verifying the
file's identity and the bytes actually written. The planned complete-file hash does not describe
that partial file. Changed or unknown contents remain with the recovery record; a later build
does not inherit the interrupted process's permission to clean them.

`check` and `doctor` are not recovery commands. `verify` can inspect an existing package's integrity
and input freshness, but a successful verification does not authorize deleting recovery state or
establish the outcome of an interrupted publication. None of these read-only operations repairs
or removes files.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Resolve shader inputs
description: Capture configured WGSL programs and their imports once, then validate and compile the same source graph.
---

# Resolve shader inputs



A native build uses the configured entry shaders and every module they import. Capturing that
graph keeps the source bytes and import choices together: checking one set of files and compiling
a later reread would not validate the same input.

<Callout type="warn">
  Warning: The snapshot helpers are implemented and tested, including serialized replay, package
  imports, relocation, and bounded direct file reads. The internal Metal compiler accepts captured
  graphs as well as explicit module maps, with real compute and render tests. Native doctor, check,
  build, and verify also run from real local tarballs installed offline with dependency install scripts
  disabled; build coverage publishes to an initially absent destination, and an external Swift
  consumer executes those actual published compute and render programs on this host. The companion
  is an optional public beta. See
  [Local installed qualification](/docs/native/macos/metal/tooling/publication#local-installed-qualification)
  for replacement and recovery coverage; the broad release compatibility remains unqualified.
</Callout>

## Keep imports in WGSL

Use the same relative and installed-package imports as the TypeScript tooling:

```wgsl
// shaders/count.wgsl
import { width } from "./dimensions.wgsl";

@group(0) @binding(0) var<storage, read_write> output: array<u32, 2>;

@compute @workgroup_size(width)
fn count_main(@builtin(local_invocation_index) index: u32) {
  output[index] = 100u + index;
}
```

```wgsl
// shaders/dimensions.wgsl
export const width: u32 = 2u;
```

Relative imports resolve from their importing module. The `@/` alias resolves from the
configuration directory. Installed-package imports use vgpu's existing package resolution and
export rules; configuration does not replace them with another package map. Imported modules
remain pure: declare resources and entry points in entry shaders.

The graph includes imported modules even when a declaration is later removed as unused. A source
change can therefore make verification stale without changing the emitted shader.

## Capture the source graph

The intended command performs this step for you. Build-tool integrations can use the WGSL helpers
directly, without importing the Metal compiler:

```ts
import { resolve } from "node:path";
import { captureShaderGraph, resolveShaderSnapshot } from "@vgpu/wgsl/runtime";

const rootDir = resolve(".");
const snapshot = await captureShaderGraph({
  rootDir,
  entries: { Count: resolve(rootDir, "shaders/count.wgsl") },
});

const shader = await resolveShaderSnapshot(snapshot, {
  entry: snapshot.entries.Count,
  validate: false,
  minify: false,
});
```

`entries` maps stable caller keys to absolute entry-file paths. `rootDir` is an absolute directory
for root-relative imports. Capture accepts an optional `AbortSignal` as `signal` and an optional
`onDependency(path)` callback for discovered imported files; the callback does not report entries
or promise that a discovered module loaded successfully.

Capture returns a `ShaderGraphSnapshot` with `schemaVersion: 1` and three fields:

* `entries` maps caller keys to opaque virtual module IDs.
* `modules` maps each ID to its original `source` text and an `imports` map from authored specifier
  to target ID. Different importer contexts keep their own resolved edges.
* `inputs` records each module's ID, `physicalPath`, and source `sha256` for input checks and diagnostics.

The snapshot owns its captured values. IDs follow sorted entry keys and authored import order;
do not construct or interpret them in application code. Physical paths do not belong in the
logical shader fingerprint. Moving an otherwise identical project does not change its logical
graph merely because its absolute checkout path changed.

Snapshots are versioned data, not handles tied to the process that captured them. A JSON round
trip or `structuredClone` can be replayed. Replay validates the snapshot's shape, source hashes,
and complete import edges before using it; malformed or unsupported snapshots fail without falling
back to the filesystem. Hash validation checks consistency, not who authored the source.

Tooling that accepts a mutable snapshot can first call `copyShaderGraphSnapshot(snapshot)` from
`@vgpu/wgsl/runtime`. It synchronously validates the data shape, source limits and hashes, then
returns an owned, deeply frozen copy before asynchronous work begins. Accessor properties and
custom object prototypes are not snapshot data. Copying does not replace replay's import-graph,
purity, and shader checks.

`resolveShaderSnapshot` uses only captured source and edges. It performs ordinary import, purity,
emission, and reflection checks without reading files or resolving packages again. Its `validate`
and `minify` options have the same meaning as `resolveShader`; native tooling disables WebGPU
validation and minification before running the pinned Metal compiler boundary. Capture itself
does not validate WGSL semantics or prove that a shader belongs to the supported Metal profile.

The initial snapshot records source and import choices, not a package-resolution warning log.
Replay reports the WGSL diagnostics it can reproduce from that data; it does not recreate warnings
about a package's conditional exports. The existing filesystem `resolveShader` API retains those
package-resolution diagnostics.

## Bound input reads

Source files must be regular, valid UTF-8 files without NUL bytes. The initial capture limits are
four MiB per source module, thirty-two MiB of captured module bytes, 1,024 graph modules, and 128
modules along an import chain. Package manifests read directly by vgpu must be regular UTF-8 JSON
files no larger than one MiB. Exceeding a limit fails the capture; it does not truncate source or
return a partial graph. These limits are not command-line tuning flags.

Fallbacks delegated to Node or package-manager resolver hooks retain those resolvers' own I/O
behavior. The direct-read limits do not establish bounded execution or compatibility for every
package manager, virtual filesystem, or custom hook.

Capturing is not an atomic snapshot of the entire filesystem. Finish edits and dependency
installation before running a native command. Capture reads each resolved module once per call
and retains those bytes, while preserving distinct import contexts for aliases. A later command
captures again instead of trusting modification times or a previous dependency list.

`check` and `build` resolve the same captured graph. `verify` captures current inputs and compares
the logical configuration, source hashes, and resolved edges with the recorded generation; it
does not invoke Tint or Apple's compiler. Continue with
[Build and verify a Metal package](/docs/native/macos/metal/tooling/build).

## Identify a generation

The input fingerprint describes the module name, selected programs and entry points, captured
source hashes and import edges, and the native generation profile. The profile includes the pinned
WGSL compiler and protocol, artifact format, generation revision, and Metal, Swift, and deployment
settings that affect the generated package.

Absolute checkout paths, the output destination, configuration formatting, and program listing
order do not make otherwise identical inputs stale. The owning configuration is checked separately
from this fingerprint. Changing a shader, a captured logical import edge, an entry point, or the generation
profile does make the output stale, including changes to imported declarations that are unused.

Generation revisions track changes to source resolution, shader interpretation, bindings, or Swift
emission. A documentation-only or command-line-only tooling update does not require regeneration
just because its npm version changed. Verification does not run the installed Apple tools to
compare their versions; the fingerprint does not promise identical compiled library bytes across
different Xcode or Metal compiler versions.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Dispatch WGSL compute
description: Run a generated compute function with application-owned Metal buffers, a pipeline, and an explicit workgroup grid.
---

# Dispatch WGSL compute



A generated compute program exposes a Metal function, its WGSL workgroup size, and helpers for
binding its resources. Your application creates the pipeline and decides when and how much work
to dispatch.

<Callout type="warn">
  Warning: The internal compiler and generated bindings execute this guide in native tests on
  Apple silicon, including GPU readback for both visible ranges. The command shim exists; the
  generated package, operational companion, and complete installed workflow are provided by the optional beta companion.
  These tests do not establish the release support matrix.
</Callout>

## Read a bounded storage view

This shader reports how many particles are visible through a binding and the last particle's ID:

```wgsl
// shaders/count.wgsl
struct Particle {
  @size(8) mass: u32,
  id: u32,
}

struct Values {
  prefix: u32,
  particles: array<Particle>,
}

@group(0) @binding(0) var<storage, read> values: Values;
@group(0) @binding(1) var<storage, read_write> output: array<u32, 2>;

@compute @workgroup_size(1)
fn count_main() {
  let count = arrayLength(&values.particles);
  output[0] = count;
  output[1] = 0u;
  if (count > 0u) {
    output[1] = values.particles[count - 1u].id;
  }
}
```

The prefix occupies four bytes. Each particle occupies twelve: four for `mass`, four bytes of
padding from `@size(8)`, and four for `id`. A visible range of `28` bytes contains the prefix and
two particles. A range of `52` bytes contains the prefix and four particles. The fixed output
array requires eight bytes for its two results.

Select the compute entry point in the proposed
[build configuration](/docs/native/macos/metal/tooling/configuration):

```json
{
  "schemaVersion": 1,
  "moduleName": "AppShaders",
  "programs": [
    {
      "name": "Count",
      "source": "shaders/count.wgsl",
      "entryPoints": { "compute": "count_main" }
    }
  ],
  "output": "Generated/AppShaders"
}
```

A compute program selects one compute entry point, not a vertex/fragment pair. It uses the same
WGSL module resolver and generated Swift package as the render integration.

## Create the native pipeline

```swift
import Metal
import AppShaders

let count = try Count.load(device: device)
let pipeline = try device.makeComputePipelineState(function: count.compute)
```

`Count.workgroupSize` is an `MTLSize` containing the authenticated, fixed WGSL dimensions.
For this shader it is `(1, 1, 1)`. Pass those dimensions as `threadsPerThreadgroup`; they are part
of the shader's execution contract, not a suggested tuning parameter or a grid size.

The application checks the native pipeline and device limits. The initial compute profile uses
compile-time workgroup dimensions without overrides and complete threadgroups; specialized sizes and partial
threadgroup dispatch need separate support.

## Provide the storage bytes

For this small integer-only fixture, write the declared layout explicitly. This is not a general
packer or a copy of a Swift struct:

```swift
let offset = 256
let words: [UInt32] = [
  99,          // prefix
  1, 0, 101,   // mass, padding, id
  2, 0, 202,
  3, 0, 303,
  4, 0, 404,
]
let valuesBuffer = device.makeBuffer(length: offset + 52, options: .storageModeShared)!
for (index, word) in words.enumerated() {
  valuesBuffer.contents().storeBytes(
    of: word.littleEndian,
    toByteOffset: offset + index * 4,
    as: UInt32.self
  )
}
let outputBuffer = device.makeBuffer(length: 8, options: .storageModeShared)!
```

The short example assumes allocations succeed. The buffer holds all four particles, but the
binding below exposes only its first `28` bytes from `offset`:

```swift
let bindings = Count.Bindings(
  values: ShaderBufferRange(buffer: valuesBuffer, offset: offset, length: 28),
  output: ShaderBufferRange(buffer: outputBuffer, offset: 0, length: 8)
)
```

The generated integration derives runtime-array size data from `length`. It does not substitute
`valuesBuffer.length - offset`, which would expose all four particles to `arrayLength`.

## Encode and submit

On your application's compute command encoder:

```swift
encoder.setComputePipelineState(pipeline)
try count.bind(bindings, to: encoder)
encoder.dispatchThreadgroups(
  MTLSize(width: 1, height: 1, depth: 1),
  threadsPerThreadgroup: Count.workgroupSize
)
```

This dispatch runs one complete workgroup. Larger kernels usually derive their grid from the
application's data and perform shader-side bounds checks. See Apple's
[dispatchThreadgroups reference](https://developer.apple.com/documentation/metal/mtlcomputecommandencoder/dispatchthreadgroups\(_:threadsperthreadgroup:\)).

End encoding and submit your command buffer. After successful GPU completion, the two output
words are `[2, 202]`. Construct bindings with `length: 52` and dispatch again to produce
`[4, 404]`. Neither the backing allocation nor the shader needs to change.

A range may end partway through another element. For example, `length: 31` still produces
`[2, 202]`: the remaining three bytes do not form a complete particle. The offset must satisfy the
buffer layout's alignment; the length does not need to be a multiple of four.

Do not read the output before completion or overwrite input bytes still in use by submitted work.
The application owns command failures, synchronization, pipeline state, and resource lifetime.

## Keep compiler data consistent with bindings

`bind` validates the entire resource set and the encoder's device before setting anything. For
this profile, it also supplies effective compiler-required size bytes through Metal's inline-byte
binding. It does not allocate persistent buffers or infer application state that is absent from
the binding set.

You can prepare the resource snapshot and internal bytes explicitly, then either reuse the
convenience helper or upload them yourself. Continue with
[Use prepared compute bindings](/docs/native/macos/metal/compute/prepared-bindings).

The explicit range is not a hardware-enforced Metal memory boundary. It supplies validation and
compiler metadata for the supported shader profile; it does not provide isolation between buffers
or validate arbitrary native commands.

## Stay within the initial resource profile

Compute programs currently support read-only and read/write storage buffers with `f32`, `i32`,
and `u32` scalars, vectors, float matrices, fixed arrays, and fixed nested structs. A runtime array
can be the binding's root type or the final member of its root struct. The application writes
storage bytes using the WGSL layout; this profile does not generate storage packers.

Active uniform buffers, textures, atomics, `f16`, and shader overrides fail compilation in this
profile. Fixed workgroup sizes can use constants from imported modules. A generated package may
contain both render and compute programs, with each program's resource profile checked separately.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Encode native indirect dispatch
description: Use generated functions and prepared binding data in an application-owned Metal indirect command buffer.
---

# Encode native indirect dispatch



An application can keep Metal command encoding outside vgpu. This example takes the `Count`
shader and buffer ranges from [Dispatch WGSL compute](/docs/native/macos/metal/compute/dispatch), then
encodes one reusable indirect compute command. There is no generated command-buffer wrapper.

<Callout type="warn">
  Warning: Native tests on Apple silicon execute this CPU-encoded command, replay it, and reset it
  for changed buffer ranges. This is a bounded composition example, not general indirect-command
  support. The command shim exists; the generated package, operational companion, and complete
  installed workflow are provided by the optional beta companion.
</Callout>

## Create a compatible pipeline

Use the same loaded `count` functions and `bindings` as the dispatch guide. Replace its ordinary
pipeline creation with a descriptor that enables indirect commands:

```swift
let pipelineDescriptor = MTLComputePipelineDescriptor()
pipelineDescriptor.computeFunction = count.compute
pipelineDescriptor.supportIndirectCommandBuffers = true
let pipeline = try device.makeComputePipelineState(
  descriptor: pipelineDescriptor,
  options: [],
  reflection: nil
)
let prepared = try count.prepare(bindings)
```

Preparation validates the ranges and computes the compiler-required bytes. It does not establish
indirect pipeline support; the native pipeline creation above can fail. See Apple's
[indirect pipeline setting](https://developer.apple.com/documentation/metal/mtlcomputepipelinedescriptor/supportindirectcommandbuffers).

## Encode one command

This command stores its own pipeline and buffers rather than inheriting them from the encoder.
Reserve the generated buffer-slot range, including internal slots:

```swift
let slots = Count.Storage.values.slots
  + Count.Storage.output.slots
  + prepared.internalData.map(\.slot)
precondition(slots.allSatisfy { $0.stage == .compute })

let descriptor = MTLIndirectCommandBufferDescriptor()
descriptor.commandTypes = .concurrentDispatch
descriptor.inheritPipelineState = false
descriptor.inheritBuffers = false
descriptor.maxKernelBufferBindCount = (slots.map(\.index).max() ?? -1) + 1
let indirectCommands = device.makeIndirectCommandBuffer(
  descriptor: descriptor,
  maxCommandCount: 1,
  options: []
)!
let indirect = indirectCommands.indirectComputeCommandAt(0)
indirect.reset()
indirect.setComputePipelineState(pipeline)

for slot in Count.Storage.values.slots {
  indirect.setKernelBuffer(prepared.bindings.values.buffer, offset: prepared.bindings.values.offset, at: slot.index)
}
for slot in Count.Storage.output.slots {
  indirect.setKernelBuffer(prepared.bindings.output.buffer, offset: prepared.bindings.output.offset, at: slot.index)
}

var internalUploads: [any MTLBuffer] = []
for payload in prepared.internalData {
  let buffer = payload.bytes.withUnsafeBytes { bytes in
    device.makeBuffer(bytes: bytes.baseAddress!, length: bytes.count, options: .storageModeShared)!
  }
  indirect.setKernelBuffer(buffer, offset: 0, at: payload.slot.index)
  internalUploads.append(buffer)
}
indirect.concurrentDispatchThreadgroups(
  MTLSize(width: 1, height: 1, depth: 1),
  threadsPerThreadgroup: Count.workgroupSize
)
```

The short example assumes allocations succeed. Internal uploads use offset `0`, satisfying their
alignment. They contain the bytes from `prepare`; the application does not construct a Tint size
table. Indirect commands accept buffers, so the ordinary `count.bind` convenience is not used.
See Apple's [indirect compute command reference](https://developer.apple.com/documentation/metal/mtlindirectcomputecommand).

## Execute and retain the resources

Declare access to the indirectly referenced buffers on the executing encoder:

```swift
let commandBuffer = queue.makeCommandBuffer()!
let encoder = commandBuffer.makeComputeCommandEncoder()!
encoder.useResource(prepared.bindings.values.buffer, usage: .read)
encoder.useResource(prepared.bindings.output.buffer, usage: .write)
for buffer in internalUploads {
  encoder.useResource(buffer, usage: .read)
}
encoder.executeCommandsInBuffer(indirectCommands, range: 0..<1)
encoder.endEncoding()
withExtendedLifetime((pipeline, prepared, indirectCommands, internalUploads)) {
  commandBuffer.commit()
  commandBuffer.waitUntilCompleted()
}
precondition(commandBuffer.status == .completed, String(describing: commandBuffer.error))
```

Waiting here makes the small example's lifetime explicit; a frame loop would retain these objects
until its completion callback. Read the shared output buffer only after completion. The expected
results remain `[2, 202]` for a `28`-byte input view and `[4, 404]` for a `52`-byte view.

The encoded command can be executed again with the same binding snapshot and retained uploads.
To change a visible range, prepare new bindings and reset and encode the command again after its
previous execution completes. Do not rewrite an in-flight command, upload, or resource range.

This example covers one CPU-encoded command, shared storage, fixed workgroup dimensions, and
explicit pipeline and buffer state. It does not establish GPU-authored commands, multiple-command
barriers, arbitrary argument buffers, cross-queue synchronization, or TypeScript render-bundle
semantics. Those remain application-owned Metal integrations with their own tests.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Use prepared compute bindings
description: Keep resource ranges and compiler-required bytes together, with a direct Metal path for uploading and binding them yourself.
---

# Use prepared compute bindings



Some translated shaders need compiler-generated data alongside application buffers. A runtime
array's visible length is one example. Preparing a binding set keeps its ranges and these bytes
together so native code does not accidentally combine a new range with an old size table.

<Callout type="warn">
  Warning: Native tests on Apple silicon execute both the prepared helper and manual upload path
  with the exact WGSL from the dispatch guide. The command shim exists; the generated package,
  operational companion, and complete installed workflow are provided by the optional beta companion. A separate
  [indirect dispatch example](/docs/native/macos/metal/compute/indirect-dispatch) tests
  a bounded native command-buffer integration.
</Callout>

## Prepare one binding snapshot

Continue with the shader, loaded functions, and resources from
[Dispatch WGSL compute](/docs/native/macos/metal/compute/dispatch):

```swift
let prepared = try count.prepare(bindings)
```

The result is a program-specific `Count.PreparedBindings`. It has no public initializer and
exposes immutable `bindings` and `internalData` properties. `bindings` contains the same typed
`ShaderBufferRange` values that were validated. `internalData` contains owned CPU bytes and the
stage-qualified slots needed by this compiled program.

Preparation validates the full set, including device identity, range containment, required size,
alignment, and whether visible lengths fit the compiler's size representation. It returns no
partially prepared value on failure. It does not write application memory, create GPU resources,
or encode commands. Only lengths included in an effective compiler size table must fit `UInt32`;
a fixed buffer that does not contribute a size word has no additional `UInt32` length limit.

Invalid ranges use the shared `ShaderBindingError` cases described in
[Bind Metal buffers](/docs/native/macos/metal/bindings). A size-table length that cannot be represented
throws `unrepresentableLength(binding:maximum:actual:)` before conversion or encoding.

The snapshot retains resource references; it does not freeze buffer contents or prove their GPU
lifetime. Changing a buffer's bytes can be intentional, but changing a visible range requires a
new binding value and another call to `prepare`.

## Reuse the convenience helper

```swift
encoder.setComputePipelineState(pipeline)
try count.bind(prepared, to: encoder)
encoder.dispatchThreadgroups(
  MTLSize(width: 1, height: 1, depth: 1),
  threadsPerThreadgroup: Count.workgroupSize
)
```

`count.bind(bindings, to: encoder)` is the short form that prepares and binds once. Use the
prepared form when you need to inspect or reuse the CPU description. Encoder-device validation
still happens before any setter; preparation does not validate a future encoder or pipeline.

The prepared value belongs to the actual Metal device used to load its program. Binding it through
functions loaded on a different device throws `preparedDeviceMismatch` before any setter.
Reloading the same program on the same device does not invalidate the snapshot.

Preparing fixed-uniform-only render bindings is not required by this compute API. The additional
snapshot exists to keep resource-dependent compiler bytes and their source ranges consistent.

## Upload internal bytes yourself

Each `ShaderInternalBufferData` value exposes `slot`, `bytes`, and `offsetAlignment`.
`slot` is a `ShaderBufferSlot`; `bytes` is an immutable `[UInt8]`; `offsetAlignment` is the required
alignment if you place those bytes in a region of a native buffer. An empty effective internal
payload produces no entry. The metadata does not invent an allocation for every reserved slot.
For example, a shader that reads only a runtime-array struct's fixed prefix may need no size table.
When a table is needed, its entries preserve physical buffer-slot indices, including zero-filled
holes. Application code should upload the provided bytes without constructing that table itself.

Allocate the upload buffers using your own Metal device:

```swift
var internalUploads: [any MTLBuffer] = []
for payload in prepared.internalData {
  precondition(payload.slot.stage == .compute)
  let buffer = payload.bytes.withUnsafeBytes { bytes in
    device.makeBuffer(bytes: bytes.baseAddress!, length: bytes.count, options: .storageModeShared)!
  }
  encoder.setBuffer(buffer, offset: 0, index: payload.slot.index)
  internalUploads.append(buffer)
}
```

This short example assumes allocation succeeds. Offset `0` satisfies each upload's alignment;
for a suballocated region, satisfy `offsetAlignment`, copy exactly `bytes.count` bytes, and bind
that region's offset. Keep the upload buffers alive until the GPU has finished with them.

Set the application buffers from the same prepared value:

```swift
for slot in Count.Storage.values.slots {
  encoder.setBuffer(prepared.bindings.values.buffer, offset: prepared.bindings.values.offset, index: slot.index)
}
for slot in Count.Storage.output.slots {
  encoder.setBuffer(prepared.bindings.output.buffer, offset: prepared.bindings.output.offset, index: slot.index)
}
```

Use a compatible compute encoder and pipeline, then dispatch as in the first guide. Both this
manual path and `count.bind(prepared, to: encoder)` must produce `[2, 202]` for the `28`-byte view
and `[4, 404]` for the `52`-byte view. No application code writes Tint-private offsets or size words.

## Keep advanced Metal work explicit

The first profile handles internal size data derived entirely from validated buffer ranges.
An internal role that also depends on dispatch or other application state needs an explicit input
and a tested contract; missing state is not silently replaced with zero.

Ordinary encoding can copy these small payloads through Metal's inline-byte API. Native indirect
compute commands instead expose buffer arguments, which is why the prepared bytes are available
for caller-owned uploads. See Apple's
[MTLIndirectComputeCommand reference](https://developer.apple.com/documentation/metal/mtlindirectcomputecommand).

This does not make an arbitrary pipeline or resource set safe for indirect commands. The
application still configures indirect pipeline support, buffer inheritance, resource residency,
barriers, storage-mode synchronization, and lifetime. Continue with
[Encode native indirect dispatch](/docs/native/macos/metal/compute/indirect-dispatch) for the tested
CPU-encoded, shared-buffer example and its limits.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)

---
title: Render computed data
description: Write a native buffer with a WGSL compute shader, then read it from a render shader in the same Metal command buffer.
---

# Render computed data



A generated binding accepts an ordinary Metal buffer. The same allocation can be written by one
shader and consumed by another without reading it back to the CPU between passes.

<Callout type="warn">
  Warning: Native tests on Apple silicon execute this example and verify every target pixel. They
  also compose application-owned blits before and after the passes. This is a bounded integration
  test, not a device support matrix. The command shim exists; the generated package, operational
  companion, and complete installed workflow are provided by the optional beta companion.
</Callout>

## Share the shader layout

Both programs import this small type:

```wgsl
// shaders/color.wgsl
export struct Color {
  rgba: vec4<f32>,
}
```

The compute program writes it as storage:

```wgsl
// shaders/fill.wgsl
import { Color } from "./color.wgsl";

@group(0) @binding(0) var<storage, read_write> color: Color;

@compute @workgroup_size(1)
fn fill_main() {
  color.rgba = vec4<f32>(0.25, 0.5, 0.75, 1.0);
}
```

The render program reads it as a uniform:

```wgsl
// shaders/display.wgsl
import { Color } from "./color.wgsl";

@group(0) @binding(0) var<uniform> color: Color;

@vertex
fn vertex_main(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
  let positions = array<vec2<f32>, 3>(
    vec2<f32>(-1.0, -1.0), vec2<f32>(3.0, -1.0), vec2<f32>(-1.0, 3.0)
  );
  return vec4<f32>(positions[index], 0.0, 1.0);
}

@fragment
fn fragment_main() -> @location(0) vec4<f32> {
  return color.rgba;
}
```

This `Color` has the same sixteen-byte layout in both address spaces. Do not assume that arbitrary
storage and uniform layouts are interchangeable. The compiler checks each program's supported
layout; the application decides whether sharing a resource is valid.

Configure `FrameShaders` with a `Fill` compute program selecting `fill_main` from
`shaders/fill.wgsl`, and a `Display` render program selecting `vertex_main` and `fragment_main`
from `shaders/display.wgsl`. See [Configure a Metal package](/docs/native/macos/metal/tooling/configuration).

## Allocate one private buffer

Use your application's device, queue, and an `rgba32Float` render-target texture named `target`:

```swift
import Metal
import FrameShaders

let fill = try Fill.load(device: device)
let display = try Display.load(device: device)
let byteCount = Display.Uniforms.color.byteCount
let colorBuffer = device.makeBuffer(
  length: byteCount,
  options: [.storageModePrivate, .hazardTrackingModeTracked]
)!
let range = ShaderBufferRange(buffer: colorBuffer, offset: 0, length: byteCount)
let fillBindings = Fill.Bindings(color: range)
let displayBindings = Display.Bindings(color: range)
```

The example assumes allocations succeed. Private storage has no CPU packing step here: the compute
shader writes all sixteen bytes. Offset `0` satisfies both programs' binding alignment.

Create the application-owned pipelines:

```swift
let fillPipeline = try device.makeComputePipelineState(function: fill.compute)
let descriptor = MTLRenderPipelineDescriptor()
descriptor.vertexFunction = display.vertex
descriptor.fragmentFunction = display.fragment
descriptor.colorAttachments[0].pixelFormat = target.pixelFormat
let displayPipeline = try device.makeRenderPipelineState(descriptor: descriptor)
```

## Encode the producer before the consumer

Use ordinary Metal encoders on one command buffer:

```swift
let commandBuffer = queue.makeCommandBuffer()!
let compute = commandBuffer.makeComputeCommandEncoder()!
compute.setComputePipelineState(fillPipeline)
try fill.bind(fillBindings, to: compute)
compute.dispatchThreadgroups(
  MTLSize(width: 1, height: 1, depth: 1),
  threadsPerThreadgroup: Fill.workgroupSize
)
compute.endEncoding()

let pass = MTLRenderPassDescriptor()
pass.colorAttachments[0].texture = target
pass.colorAttachments[0].loadAction = .clear
pass.colorAttachments[0].storeAction = .store
pass.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 1)
let render = commandBuffer.makeRenderCommandEncoder(descriptor: pass)!
render.setRenderPipelineState(displayPipeline)
try display.bind(displayBindings, to: render)
render.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3)
render.endEncoding()

withExtendedLifetime((colorBuffer, target, fillPipeline, displayPipeline)) {
  commandBuffer.commit()
  commandBuffer.waitUntilCompleted()
}
precondition(commandBuffer.status == .completed, String(describing: commandBuffer.error))
```

With a tracked resource and an ordinary `MTLCommandQueue`, Metal handles the buffer hazard between
these ordered passes. This is not a guarantee for untracked heaps, concurrent encoders, another
queue, or Metal 4 command submission. Those need their own synchronization. See Apple's
[resource synchronization guide](https://developer.apple.com/documentation/metal/resource-synchronization).

Every target pixel should contain `(0.25, 0.5, 0.75, 1.0)` after completion. The only wait above is
after both passes; there is no intermediate CPU readback or second submission. A frame loop can
retain resources until a completion callback instead of waiting synchronously.

The generated helpers bind each program's recorded slots. They do not create a render graph,
schedule passes, choose storage modes, or insert application synchronization. Continue using
native Metal for those responsibilities.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)