# API reference

Every public export of nanoraster — the two render calls, the renderer handle, the request and result types, the failure codes, and the validation constants.

Canonical page: https://www.nanoraster.xyz/docs/api

Every export on this page comes from `nanoraster`. The call owns the GLB
bytes that you pass in. Returned bytes are newly allocated, and you own them.

## Every option and its default [#every-option-and-its-default]

```typescript
import { renderImage } from 'nanoraster';

const image = await renderImage(glb, {
  format: 'webp', // required: 'png' | 'webp' | 'jpeg' | 'jpg' | 'raw'
  width: 768, // default
  height: 432, // default
  quality: 1, // webp default (lossless); jpeg defaults to 0.92; png and raw ignore it
  lineWidth: 3, // output pixels; default
  surfaces: true, // default
  lines: true, // default
  visiblePrimitives: undefined, // default (all reachable primitives)
  sections: undefined, // default (no section view)
  world: undefined, // default (glTF +Y up, +Z forward, metres)
  background: undefined, // default (transparent)
  axes: false, // default
  scaleBar: false, // default
  lighting: 'studio', // default
  label: undefined, // default (no label drawn)
  camera: undefined, // default fitted three-quarter perspective camera
});
```

`renderImages` accepts the same shared keys, except `label` and the singular
`camera`. It adds `views: [{ id, label?, camera?, width?, height?, format?, quality? }]`,
one entry per image in result order. It accepts `timings: true` to
attach stage timings.

## Render [#render]

### `renderImage` [#renderimage]

Render one GLB camera view to one owned output.

```typescript
export declare const renderImage: (
  glb: Uint8Array<ArrayBuffer>,
  options: RenderImageOptions,
) => Promise<RenderedImageFile>;
```

* **Parameters:** owned GLB bytes and one validated render request.
* **Returns:** a newly allocated `render.<format>` file with the resolved
  width and height.
* **Throws:** `RenderError` for invalid requests, malformed GLB data, GPU faults,
  or encoding failures.

```typescript
import { renderImage } from 'nanoraster';

const image = await renderImage(glb, { format: 'webp', width: 512 });
```

### `renderImages` [#renderimages]

Parse and upload a GLB once, then render an ordered set of identified views.
This is the plan call. Each view can override the shared `width`, `height`,
`format` and `quality`.

```typescript
export declare const renderImages: <const Options extends RenderImagesOptions>(
  glb: Uint8Array<ArrayBuffer>,
  options: StrictRenderImagesOptions<Options>,
) => Promise<RenderedImagesResult<Options>>;
```

* **Parameters:** owned GLB bytes and shared settings with a non-empty view tuple.
* **Returns:** a tuple that preserves the input view IDs and order. Each
  entry's MIME type follows its own `format` override.
* **Throws:** the same errors as `renderImage`, plus an error when the
  requested views and the returned images do not match.

```typescript
import { renderImages } from 'nanoraster';

const [iso, front] = await renderImages(glb, {
  format: 'webp',
  views: [{ id: 'iso' }, { id: 'front', camera: { framing: 'fit', direction: [1, 0, 0] } }],
});
```

## Encode pixels [#encode-pixels]

### `encodeRgbaWebp` [#encodergbawebp]

Encode tightly packed RGBA8 pixels as WebP without creating a GPU renderer.

```typescript
export declare const encodeRgbaWebp: (
  rgba: Uint8Array<ArrayBuffer>,
  options: EncodeRgbaWebpOptions,
) => Promise<Uint8Array<ArrayBuffer>>;
```

The input is top-row-first sRGB. Set `alpha` to describe whether its RGB
channels are straight or premultiplied; the encoder snapshots the input before
starting asynchronous work.

### `EncodeRgbaWebpOptions` [#encodergbawebpoptions]

**`EncodeRgbaWebpOptions`** — Options for encoding caller-owned RGBA8 pixels as WebP.

- **`width`** (`number`, required) — Output width in pixels.
- **`height`** (`number`, required) — Output height in pixels.
- **`quality`** (`number | undefined`, optional) — WebP quality from 0 to 1. One selects lossless VP8L.
- **`alpha`** (`"straight" | "premultiplied"`, required) — Whether RGB channels are independent of alpha or already multiplied by it.

## Renderer reuse [#renderer-reuse]

The one-shot functions share one renderer per process. The first call creates
it, and nothing disposes it.
Create your own renderer to control lifetime or power preference.
[Reuse the renderer](https://www.nanoraster.xyz/docs/guides/reuse-the-renderer.mdx) covers when and how.

### `createRenderer` [#createrenderer]

Create a renderer that keeps the GPU device, shader and pipelines alive across
calls.

```typescript
export declare const createRenderer: (options?: CreateRendererOptions) => Promise<Renderer>;
```

* **Parameters:** optional GPU selection hints.
* **Returns:** a [`Renderer`](#renderer) bound to one warm device.
* **Throws:** `RenderError` with code `adapter-unavailable` when no compatible
  adapter exists, or `parse` for invalid options.

```typescript
import { createRenderer } from 'nanoraster';

using renderer = await createRenderer({ powerPreference: 'low-power' });
const image = await renderer.renderImage(glb, { format: 'webp' });
```

### `Renderer` [#renderer]

[`createRenderer`](#createrenderer) returns this persistent handle. Its two
render methods mirror the module-level functions exactly: same options, same
results, and byte-identical pixels on the same adapter.

```typescript
export type Renderer = {
  readonly renderImage: (
    glb: Uint8Array<ArrayBuffer>,
    options: RenderImageOptions,
  ) => Promise<RenderedImageFile>;
  readonly renderImages: <const Options extends RenderImagesOptions>(
    glb: Uint8Array<ArrayBuffer>,
    options: StrictRenderImagesOptions<Options>,
  ) => Promise<RenderedImagesResult<Options>>;
  readonly dispose: () => void;
  readonly [Symbol.dispose]: () => void;
};
```

* A renderer is **single-realm**. Create it inside the worker that uses it.
  Bytes cross `postMessage`; handles do not.
* Calls on one renderer run **in sequence**. Send a declared set of images
  through one `renderImages` call, not a loop.
* The next call **recovers device loss**: it rebuilds the device and uploads
  again.
* `dispose()` marks the renderer disposed at once. It is idempotent and
  backs `using` through `Symbol.dispose`. Every later call rejects with
  `RenderError` code `'gpu'`, so create a new renderer instead of retrying.
  GPU teardown follows the queued calls, with no completion signal.

### `CreateRendererOptions` [#createrendereroptions]

**`CreateRendererOptions`** — Options accepted by {@link createRenderer} and {@link describeAdapter }.

- **`powerPreference`** (`"high-performance" | "low-power" | undefined`, optional, default `'high-performance'`) — GPU selection hint. On dual-GPU machines `'high-performance'` prefers the discrete GPU; small, frequent renders should prefer `'low-power'`. Pixel output is identical either way on a given adapter.

### `describeAdapter` [#describeadapter]

Describe the adapter that a renderer with these options would bind. Pass the
`powerPreference` that you would pass to `createRenderer`.

```typescript
export declare const describeAdapter: (options?: CreateRendererOptions) => Promise<AdapterInfo | undefined>;
```

`deviceType === 'cpu'` means software rasterisation, an order of magnitude
slower. Use it as the preflight when performance matters.
Native hosts report the full device class. Browsers report `'unknown'` unless
the adapter declares itself a fallback. When no adapter exists, the call
resolves `undefined`. Only invalid options reject.

### `AdapterInfo` [#adapterinfo]

**`AdapterInfo`** — The GPU adapter a renderer binds.

- **`backend`** (`"metal" | "vulkan" | "dx12" | "webgpu"`, required) — Graphics API in use. Browsers always report `'webgpu'`.
- **`name`** (`string`, required) — Device name, or `''` when the runtime withholds it.
- **`deviceType`** (`"discrete-gpu" | "integrated-gpu" | "virtual-gpu" | "cpu" | "unknown"`, required) — Device class. `'cpu'` is software rasterization (SwiftShader, lavapipe, WARP); `'unknown'` means the runtime withholds it, as browsers do for every adapter that is not a declared fallback.

## Options held in a variable [#options-held-in-a-variable]

A variable widens `'webp'` to `string` and the view IDs with it, so the
result tuple loses its names. `as const satisfies` keeps the literals and
still checks the keys, at compile time only.

```typescript
import { renderImages, type RenderImagesOptions } from 'nanoraster';

const options = {
  format: 'webp',
  views: [{ id: 'iso' }],
} as const satisfies RenderImagesOptions;

const [iso] = await renderImages(glb, options);
```

`satisfies RenderImageOptions` does the same for the singular call.

## Options [#options]

[Frame the model](https://www.nanoraster.xyz/docs/guides/frame-the-model.mdx) and [Place the camera](https://www.nanoraster.xyz/docs/guides/place-the-camera.mdx)
show these fields in use.

### `RenderVector3` [#rendervector3]

```typescript
export type RenderVector3 = readonly [x: number, y: number, z: number];
```

A Cartesian vector in the request's caller-world frame, which is glTF world
space when the request omits `world`. Direction and up vectors accept any
finite non-zero magnitude, and the renderer normalizes them.

### `RenderWorldAxis` [#renderworldaxis]

```typescript
export type RenderWorldAxis = '+x' | '-x' | '+y' | '-y' | '+z' | '-z';
```

One signed principal axis in the caller-world frame.

### `RenderWorld` [#renderworld]

```typescript
export type RenderWorld = {
  readonly up?: RenderWorldAxis;
  readonly forward?: RenderWorldAxis;
  readonly unit?: 'meter' | 'millimeter';
};
```

Declares the coordinate frame for camera, section, world-light, axes, and
scale-bar values. It does not change the submitted GLB. The defaults are glTF
`+Y` up, `+Z` forward, and metres. Up and forward must name distinct axes and
form a right-handed frame. Every view in a batch shares the setting.

### `RenderPrimitiveReference` [#renderprimitivereference]

```typescript
export type RenderPrimitiveReference = {
  readonly nodeIndex: number;
  readonly meshIndex: number;
  readonly primitiveIndex: number;
};
```

One reachable primitive instance in the submitted glTF document. All three
indices are non-negative safe integers. See [Choose visible geometry](https://www.nanoraster.xyz/docs/guides/choose-visible-geometry.mdx).

### `RenderSectionPlane` [#rendersectionplane]

```typescript
export type RenderSectionPlane = {
  readonly point: RenderVector3;
  readonly normal: RenderVector3;
};
```

The normal points into the retained world-space half-space. The renderer
normalizes it.

### `RenderSections` [#rendersections]

```typescript
export type RenderSections = {
  readonly planes: readonly [RenderSectionPlane, ...RenderSectionPlane[]];
  readonly clipSurfaces?: boolean;
  readonly clipLines?: boolean;
};
```

The request shares one to `renderImageMaxSections` planes. Both clip flags
default to `true`. [Cut section views](https://www.nanoraster.xyz/docs/guides/render-section-views.mdx) covers
caps, outlines, and multiple retained half-spaces. A successful closed-surface
cut contains every cap. A failed cut returns `parse`.

### `RenderCamera` [#rendercamera]

The tagged camera contract. A fit camera supplies orientation, and nanoraster
solves a geometry-tight optical target, distance, and clipping. A fixed camera
preserves the caller-owned pose and projection. Perspective is rectilinear
and preserves the requested field of view exactly.

```typescript
export type RenderCamera =
  | {
      readonly framing: 'fit';
      readonly direction?: RenderVector3;
      readonly up?: RenderVector3;
      readonly margin?: number;
      readonly projection?:
        | { readonly kind: 'perspective'; readonly verticalFieldOfView?: number }
        | { readonly kind: 'orthographic' };
    }
  | {
      readonly framing: 'fixed';
      readonly position: RenderVector3;
      readonly target: RenderVector3;
      readonly up: RenderVector3;
      readonly projection?:
        | { readonly kind: 'perspective'; readonly verticalFieldOfView?: number; readonly zoom?: number }
        | { readonly kind: 'orthographic'; readonly verticalSpan: number; readonly zoom?: number };
      readonly clipping?: { readonly near: number; readonly far: number };
    };
```

The default fit camera looks from 45 degrees azimuth and 30 degrees
elevation in the declared world, and its `up` is `world.up`. In
glTF world, that direction is `[0.6123724357, 0.5, 0.6123724357]` and that up
is `[0, 1, 0]`. The minimum margin defaults to `0.1`, the perspective field of
view to `45`, and the zoom to `1`. `direction` fixes the orientation from the
subject toward the camera. The fit can translate the optical axis to balance
the projected geometry.

A fixed camera requires a position and target that do not coincide. A view
collinear with `up` names no roll. Screen-up then becomes `world.forward`, or
`world.up` along forward. Omitted clipping derives safe planes from referenced
geometry. The renderer tightens an explicit range outside the referenced
subject, without changing the visible geometry.

### `RenderOrbit` [#renderorbit]

```typescript
export type RenderOrbit = {
  readonly elevation: number;
  readonly azimuth: number;
};
```

A viewing direction as two angles in degrees around the caller world.
`elevation` is the angle above the world horizontal plane, from `-90` to `90`.
`azimuth` is the angle in that plane, zero on `world.forward` and positive
toward the viewer's right.

### `directionFromOrbit` [#directionfromorbit]

```typescript
export declare const directionFromOrbit: (orbit: RenderOrbit, world?: RenderWorld) => RenderVector3;
```

* **Parameters:** the orbit angles, and the world they are measured in. Pass
  the request's `world`, or omit it for the glTF default.
* **Returns:** the unit `direction` that a fitted camera takes.
* **Throws:** `TypeError` for a non-finite azimuth, an elevation outside
  `-90` to `90`, or an invalid world.

```typescript
import { directionFromOrbit } from 'nanoraster';

const world = { up: '+z', forward: '-y' } as const;
const direction = directionFromOrbit({ azimuth: 45, elevation: 30 }, world);
```

### `orbitFromDirection` [#orbitfromdirection]

```typescript
export declare const orbitFromDirection: (direction: RenderVector3, world?: RenderWorld) => RenderOrbit;
```

* **Parameters:** any finite non-zero direction, and the world it is
  expressed in. The function ignores the magnitude.
* **Returns:** the orbit angles that reproduce the direction. The result
  exactly inverts [`directionFromOrbit`](#directionfromorbit) in the same
  world. The azimuth is above `-180` and up to `180`. At the poles, elevation
  `-90` or `90`, the azimuth is undefined and reported as `0`.
* **Throws:** `TypeError` for a zero or non-finite direction, or an invalid
  world.

### `RenderImageOptions` [#renderimageoptions]

```typescript
export type RenderImageOptions = RenderImageSharedOptions & RenderCameraOptions;
```

`RenderImageSharedOptions` and `RenderCameraOptions` are internal composition
types.

**`RenderImageOptions`** — Options for one rendered image.

- **`format`** (`"png" | "webp" | "jpeg" | "jpg" | "raw"`, required) — Required output format. `jpg` is an alias for `jpeg`. `'raw'` skips the encoder and returns the frame itself: straight-alpha, sRGB-encoded RGBA8, exactly `width * height * 4` bytes, row-major with the top row first, four bytes per pixel and no padding, owned by the caller.
- **`width`** (`number | undefined`, optional, default `768`) — Output width in pixels, inclusive range 16–8192.
- **`height`** (`number | undefined`, optional, default `432`) — Output height in pixels, inclusive range 16–8192.
- **`quality`** (`number | undefined`, optional, default `0.92 (jpeg), 1 (webp)`) — Encoder quality from 0 to 1. For WebP, 1 is lossless and anything lower encodes lossy, following Chrome's canvas `toBlob` semantics. PNG and raw ignore quality.
- **`world`** (`RenderWorld | undefined`, optional, default `glTF world`) — Caller coordinate system for spatial request values and presentation.
- **`lineWidth`** (`number | undefined`, optional, default `3`) — Edge line width in output pixels, from 0.25 to 16.
- **`surfaces`** (`boolean | undefined`, optional, default `true`) — Draw triangle primitives.
- **`lines`** (`boolean | undefined`, optional, default `true`) — Draw authored line primitives.
- **`visiblePrimitives`** (`readonly RenderPrimitiveReference[] | undefined`, optional, default `all`) — Exact source primitive instances to render. Omit for all; an empty array renders none.
- **`sections`** (`RenderSections | undefined`, optional, default `disabled`) — World-space section planes. Omit to disable sections.
- **`background`** (`string | readonly [number, number, number, number] | undefined`, optional, default `transparent`) — Transparent by default; otherwise `#RRGGBB`, `#RRGGBBAA`, or normalized sRGB straight-alpha RGBA. The image is blended onto it in sRGB, as a browser shows the transparent image over that colour.
- **`lineColor`** (`string | readonly [number, number, number, number] | undefined`, optional, default `authored colours`) — Replace every authored line colour; `#RRGGBB`, `#RRGGBBAA`, or normalized sRGB straight-alpha RGBA.
- **`axes`** (`boolean | undefined`, optional, default `false`) — Draw the bottom-right camera-aware XYZ indicator and front-on depth marker.
- **`scaleBar`** (`boolean | undefined`, optional, default `false`) — Draw a bottom-left physical scale bar. Perspective labels identify the subject-center measurement plane with `@ center`; orthographic scale is depth-invariant.
- **`lighting`** (`RenderLighting | undefined`, optional, default `'studio'`) — Studio preset by default; a supplied rig replaces the direct lights and inherits the other studio values. Determinism is unchanged: a fixed rig gives fixed pixels.
- **`ao`** (`RenderAmbientOcclusion | undefined`, optional, default `enabled`) — Opaque-surface contact shadows. Use intensity 0 to disable.
- **`toneMapping`** (`"neutral" | "aces" | "linear" | "none" | undefined`, optional, default `'neutral'`) — Display transform from scene radiance to output colour, matching the three.js operators: `'neutral'` (Khronos PBR Neutral), `'aces'` (ACES Filmic), `'linear'` (exposure, then clamp) or `'none'` (radiance as it is; like three's `NoToneMapping` it ignores `lighting.exposure`).
- **`label`** (`string | undefined`, optional) — Screen-upright text drawn top-left; 1–64 supported Unicode code points. Omit it to draw no label.
- **`camera`** (`RenderCamera | undefined`, optional) — Camera framing. Omit it for the default fitted three-quarter view.

### `RenderImageView` [#renderimageview]

```typescript
export type RenderImageView<Id extends string = string> = {
  readonly id: Id;
  readonly visiblePrimitives?: readonly RenderPrimitiveReference[];
  readonly label?: string;
  readonly camera?: RenderCamera;
  readonly width?: number;
  readonly height?: number;
  readonly format?: 'png' | 'webp' | 'jpeg' | 'jpg' | 'raw';
  readonly quality?: number;
};
```

IDs must be unique within a request. `visiblePrimitives` draws and fits to
this view's exact source instances; omit it to inherit the shared selection.
An empty selection needs a fixed camera, and per-view selection with
`sections` is unsupported. The four per-view output overrides
default to the shared value, follow the same validation, and flow into that
entry's filename and MIME type. A view also
accepts `format: 'raw'`. An omitted `camera` means the default fitted camera.

**`RenderImageView`** — One identified camera in a multi-image request: camera identity plus optional per-view output overrides. An override defaults to the shared call-level value, so one plan call can render a whole resolution or format ladder of the same subject.

- **`id`** (`Id`, required) — Unique result and filename identity matching `[A-Za-z0-9][A-Za-z0-9_-]{0,63}`.
- **`visiblePrimitives`** (`readonly RenderPrimitiveReference[] | undefined`, optional) — Exact source primitive instances to draw and fit for this view. Omit to inherit the shared selection. An empty array has no fitted bounds and requires a fixed camera. Per-view selection with sections is unsupported.
- **`label`** (`string | undefined`, optional) — Screen-upright caller-authored text rendered verbatim. Its presence draws this view's label.
- **`camera`** (`RenderCamera | undefined`, optional) — Camera framing. Omit it for the default fitted three-quarter view.
- **`width`** (`number | undefined`, optional, default `the shared `width``) — Output width override for this view, inclusive range 16–8192.
- **`height`** (`number | undefined`, optional, default `the shared `height``) — Output height override for this view, inclusive range 16–8192.
- **`format`** (`"png" | "webp" | "jpeg" | "jpg" | "raw" | undefined`, optional, default `the shared `format``) — Output format override for this view, `'raw'` included.
- **`quality`** (`number | undefined`, optional, default `the shared `quality``) — Encoder quality override for this view with the shared semantics (WebP: 1 is lossless, below 1 is lossy).

### `RenderImagesOptions` [#renderimagesoptions]

```typescript
export type RenderImagesOptions<Views extends readonly RenderImageView[] = readonly RenderImageView[]> =
  RenderImageSharedOptions & {
    readonly timings?: boolean;
    readonly views: Views;
  };
```

`views` must be a non-empty ordered tuple with unique IDs. A view has a label
only when its own entry sets `label`. `timings: true` attaches a
[`RenderTimings`](#rendertimings) to the result. It does not change what the
call renders.

**`RenderImagesOptions`** — Shared settings plus an ordered collection of camera views.

- **`format`** (`"png" | "webp" | "jpeg" | "jpg" | "raw"`, required) — Required output format. `jpg` is an alias for `jpeg`. `'raw'` skips the encoder and returns the frame itself: straight-alpha, sRGB-encoded RGBA8, exactly `width * height * 4` bytes, row-major with the top row first, four bytes per pixel and no padding, owned by the caller.
- **`width`** (`number | undefined`, optional, default `768`) — Output width in pixels, inclusive range 16–8192.
- **`height`** (`number | undefined`, optional, default `432`) — Output height in pixels, inclusive range 16–8192.
- **`quality`** (`number | undefined`, optional, default `0.92 (jpeg), 1 (webp)`) — Encoder quality from 0 to 1. For WebP, 1 is lossless and anything lower encodes lossy, following Chrome's canvas `toBlob` semantics. PNG and raw ignore quality.
- **`world`** (`RenderWorld | undefined`, optional, default `glTF world`) — Caller coordinate system for spatial request values and presentation.
- **`lineWidth`** (`number | undefined`, optional, default `3`) — Edge line width in output pixels, from 0.25 to 16.
- **`surfaces`** (`boolean | undefined`, optional, default `true`) — Draw triangle primitives.
- **`lines`** (`boolean | undefined`, optional, default `true`) — Draw authored line primitives.
- **`visiblePrimitives`** (`readonly RenderPrimitiveReference[] | undefined`, optional, default `all`) — Exact source primitive instances to render. Omit for all; an empty array renders none.
- **`sections`** (`RenderSections | undefined`, optional, default `disabled`) — World-space section planes. Omit to disable sections.
- **`background`** (`string | readonly [number, number, number, number] | undefined`, optional, default `transparent`) — Transparent by default; otherwise `#RRGGBB`, `#RRGGBBAA`, or normalized sRGB straight-alpha RGBA. The image is blended onto it in sRGB, as a browser shows the transparent image over that colour.
- **`lineColor`** (`string | readonly [number, number, number, number] | undefined`, optional, default `authored colours`) — Replace every authored line colour; `#RRGGBB`, `#RRGGBBAA`, or normalized sRGB straight-alpha RGBA.
- **`axes`** (`boolean | undefined`, optional, default `false`) — Draw the bottom-right camera-aware XYZ indicator and front-on depth marker.
- **`scaleBar`** (`boolean | undefined`, optional, default `false`) — Draw a bottom-left physical scale bar. Perspective labels identify the subject-center measurement plane with `@ center`; orthographic scale is depth-invariant.
- **`lighting`** (`RenderLighting | undefined`, optional, default `'studio'`) — Studio preset by default; a supplied rig replaces the direct lights and inherits the other studio values. Determinism is unchanged: a fixed rig gives fixed pixels.
- **`ao`** (`RenderAmbientOcclusion | undefined`, optional, default `enabled`) — Opaque-surface contact shadows. Use intensity 0 to disable.
- **`toneMapping`** (`"neutral" | "aces" | "linear" | "none" | undefined`, optional, default `'neutral'`) — Display transform from scene radiance to output colour, matching the three.js operators: `'neutral'` (Khronos PBR Neutral), `'aces'` (ACES Filmic), `'linear'` (exposure, then clamp) or `'none'` (radiance as it is; like three's `NoToneMapping` it ignores `lighting.exposure`).
- **`timings`** (`boolean | undefined`, optional, default `false`) — Attach stage timings and resource counters to the result as a `timings` property. Rendering is unchanged.
- **`views`** (`Views`, required) — Non-empty ordered view tuple with unique IDs.

### `RenderAmbientOcclusion` [#renderambientocclusion]

Contact shadows default on for opaque surfaces.
`ao: { intensity: 0 }` skips AO passes. Optional fields tune the radius
in output pixels, visibility exponent, falloff, thickness, denoise
tolerance, samples and resolution. AO uses the
same profile for every view in a batch and leaves authored material factors
unchanged. See [AO defaults and output limits](https://www.nanoraster.xyz/docs/guides/light-the-subject.mdx#ambient-occlusion).

**`RenderAmbientOcclusion`** — Screen-space ambient occlusion for contact shadows in opaque geometry: the three.js GTAO estimator with an edge-aware denoise, configured like the Tau viewer by default. Enabled by default; use intensity 0 to skip its render passes.

- **`radiusPixels`** (`number | undefined`, optional, default `max(1% of image diagonal, 4)`) — Sampling radius in output pixels, from 1 to 128.
- **`intensity`** (`number | undefined`, optional, default `0.75`) — Visibility exponent, from 0 to 8; 0 skips the AO passes.
- **`distanceFalloff`** (`number | undefined`, optional, default `1`) — GTAO distance falloff, from 0.01 to 1; lower values weight distant horizon samples more.
- **`thicknessRatio`** (`number | undefined`, optional, default `1 / 0.09 (≈ 11.11)`) — Depth acceptance as a multiple of the world-space sampling radius, from 0.1 to 100: a horizon sample further than `radius × thicknessRatio` in front of or behind the surface is ignored. The Tau viewer's `gtaoThicknessToRadiusRatio`.
- **`denoiseDepthTolerance`** (`number | undefined`, optional, default `0.1`) — Plane-distance tolerance of the denoise and upsample filters as a fraction of the world-space sampling radius, from 0.01 to 10. Neighbours further than this from the centre's tangent plane do not contribute.
- **`samples`** (`number | undefined`, optional, default `16`) — Horizon samples per pixel, an integer from 1 to 64, split as three.js `GTAONode` splits them: 3 slices below 30 samples and 5 from 30, each marching `ceil(samples / slices)` steps.
- **`resolutionScale`** (`number | undefined`, optional, default `0.5`) — Resolution of the estimate and denoise passes as a fraction of the output size, from 0.25 to 1, rounded per axis; the result is upsampled with depth and normal guidance.

### `StrictRenderImagesOptions` [#strictrenderimagesoptions]

The exact parameter type of [`renderImages`](#renderimages) and
`Renderer.renderImages`. It narrows `RenderImagesOptions` so that extra keys,
empty view tuples, and per-view settings at call level are compile errors.
Callers pass plain `RenderImagesOptions` literals. Name it only when you
forward the plan call through a generic wrapper:

```typescript
import { renderImages, type RenderImagesOptions, type StrictRenderImagesOptions } from 'nanoraster';

const renderCatalogue = async <const Options extends RenderImagesOptions>(
  glb: Uint8Array<ArrayBuffer>,
  options: StrictRenderImagesOptions<Options>,
) => renderImages(glb, options);
```

### `RenderLighting` [#renderlighting]

```typescript
export type RenderLighting = 'studio' | RenderLightingRig;
```

The studio preset by name, or a rig. Three requests render the same bytes:
omit `lighting`, pass `'studio'`, or state the studio values in full. One rig
applies to every view of a batch. [Light the subject](https://www.nanoraster.xyz/docs/guides/light-the-subject.mdx)
shows each field in use.

### `RenderLightingRig` [#renderlightingrig]

A rig inherits every studio value it leaves out; `lights` without `headlamp`
also drops the headlamp. Directions are view-space by default: `+x` right,
`+y` up, `+z` toward the viewer. `space: 'world'` uses the declared caller
world.

**`RenderLightingRig`** — Explicit rig. Omitted fields inherit the studio values, except that a `lights` array given without `headlamp` replaces the studio headlamp too.

- **`lights`** (`readonly RenderLight[] | undefined`, optional, default `[]`) — Directional lights beside the headlamp; with it, at most `renderImageMaxLights` in all. An empty array and no headlamp renders from the environment alone.
- **`headlamp`** (`RenderHeadlamp | undefined`, optional, default `{ intensity: 1.5, rightOffset: 2, upOffset: 2 }`) — Camera-relative key light.
- **`ambient`** (`number | undefined`, optional, default `0.036605637`) — Flat ambient multiplier on the diffuse color, from 0 to 4: an ambient light's intensity divided by π. The default is the Tau viewer's dark-scheme ambient, `0.1 × 1.15 / π`.
- **`environment`** (`"studio" | "none" | RenderEnvironment | undefined`, optional, default `'studio'`) — `'studio'` is Three.js's neutral room (`RoomEnvironment`), the Tau viewer's default; `'none'` removes environment light; an object sets its intensity or prefilters it from light cards.
- **`space`** (`"view" | "world" | undefined`, optional, default `'view'`) — Frame the directions are authored in. `'world'` fixes the lights to the request's caller world whatever camera is used, so views of one subject stop being comparably lit.
- **`exposure`** (`number | undefined`, optional, default `1`) — Linear multiplier applied before tone mapping, from 0.01 to 16.

### `RenderHeadlamp` [#renderheadlamp]

The camera-relative key light.

**`RenderHeadlamp`** — Camera-relative key light, placed like the Tau viewer's headlamp: offset to the camera's right and up by multiples of the scene radius and aimed two radii ahead of the camera. Its view-space direction is therefore `[rightOffset, upOffset, 2]` whatever the scene's size, distance or projection, and it ignores `lighting.space`.

- **`intensity`** (`number | undefined`, optional, default `1.5`) — White linear radiance within `renderImageLightColorRange`; 0 switches the headlamp off.
- **`rightOffset`** (`number | undefined`, optional, default `2`) — Camera-right offset in scene radii, within `renderImageRigExtentRange`.
- **`upOffset`** (`number | undefined`, optional, default `2`) — Camera-up offset in scene radii, within `renderImageRigExtentRange`.

### `RenderEnvironment` [#renderenvironment]

Environment intensity, or light cards replacing the room.

**`RenderEnvironment`** — Environment settings. The environment supplies specular reflection and diffuse irradiance, prefiltered as Three.js's PMREM.

- **`cards`** (`readonly RenderLightCard[] | undefined`, optional) — Rectangular emitters to prefilter the environment from, at most `renderImageMaxLightCards`, over black. Omitted keeps the neutral room. Each distinct card set is prefiltered once per renderer and reused.
- **`intensity`** (`number | undefined`, optional, default `1`) — Multiplier on environment radiance within `renderImageEnvironmentIntensityRange`.

### `RenderLightCard` [#renderlightcard]

One rectangular emitter, like a drei `Lightformer`.

**`RenderLightCard`** — One rectangular emitter of a card environment, as drei's `Lightformer` with `form="rect"` places it in the Tau viewer's studio. Lengths are in scene radii. The environment turns with the camera, so the axes are view space: `+x` right, `+y` up, `+z` toward the viewer.

- **`position`** (`readonly [number, number, number]`, required) — Card center; each axis within `renderImageRigExtentRange`, not the scene center itself.
- **`size`** (`readonly [number, number]`, required) — Width and height, each above 0 and at most the top of `renderImageRigExtentRange`.
- **`intensity`** (`number`, required) — Linear radiance of the card's white face within `renderImageLightCardIntensityRange`.
- **`rotation`** (`readonly [number, number, number] | undefined`, optional) — Euler XYZ rotation in radians. Omitted turns the card's face toward the scene center, as `Lightformer`'s default target does.

### `RenderLight` [#renderlight]

One directional light. `direction` points from the surface toward the light,
and the renderer normalises it. `color` is linear RGB radiance, unitless. Each
channel is within `renderImageLightColorRange`.

**`RenderLight`** — One directional light.

- **`direction`** (`readonly [number, number, number]`, required) — Direction from the surface toward the light — the vector dotted with the surface normal. Any finite non-zero vector is accepted and normalized by the renderer. View-space axes: `+x` right, `+y` up, `+z` toward the viewer.
- **`color`** (`readonly [number, number, number]`, required) — Linear RGB radiance, unitless, each channel within `renderImageLightColorRange`.

## Results [#results]

### `RenderedImageFile` [#renderedimagefile]

[`renderImage`](#renderimage) returns this type, and every batch entry carries
it as `file`. `width` and `height` are the resolved request dimensions. With
`format: 'raw'`, `bytes` is the frame itself: straight-alpha sRGB
RGBA8, `width * height * 4` bytes, top row first. Its `mimeType` is then
`application/octet-stream`. [Work with raw pixels](https://www.nanoraster.xyz/docs/guides/work-with-raw-pixels.mdx)
has the layout in full.

**`RenderedImageFile`** — Named image bytes returned by nanoraster. The `Format` parameter narrows `mimeType` when the requesting format is known as a literal. For `format: 'raw'` the bytes are the frame itself rather than an encoded file: straight-alpha, sRGB-encoded RGBA8, exactly `width * height * 4` bytes, row-major with the top row first, four bytes per pixel and no padding — which is what a canvas `ImageData` expects after a `Uint8ClampedArray` wrap.

- **`name`** (`string`, required) — Canonical output filename: `render.<format>` or `render-<id>.<format>`.
- **`bytes`** (`Uint8Array<ArrayBuffer>`, required) — Newly allocated image bytes owned by the caller.
- **`mimeType`** (`{ readonly png: "image/png"; readonly webp: "image/webp"; readonly jpeg: "image/jpeg"; readonly jpg: "image/jpeg"; readonly raw: "application/octet-stream"; }[Format]`, required) — MIME type matching the output format; `'application/octet-stream'` for raw.
- **`width`** (`number`, required) — Pixel width this view was rendered at, resolved from the request.
- **`height`** (`number`, required) — Pixel height this view was rendered at, resolved from the request.

```typescript
import { renderImage } from 'nanoraster';

import { writeFile } from 'node:fs/promises';

const image = await renderImage(glb, { format: 'webp' });
await writeFile(image.name, image.bytes);
```

### `RenderedImage` [#renderedimage]

One identified entry in a batch result. The `id` is the literal from the
matching view.

**`RenderedImage`** — One identified rendered file.

- **`id`** (`Id`, required) — Stable identity copied from the corresponding input view.
- **`file`** (`RenderedImageFile<Format>`, required) — Owned output file for this view.

### `RenderedImages` [#renderedimages]

The ordered tuple inside every plan-call result.

```typescript
export type RenderedImages<
  Views extends readonly RenderImageView[],
  SharedFormat extends ImageFormat = ImageFormat,
> = {
  readonly [Index in keyof Views]: Views[Index] extends RenderImageView<infer Id>
    ? RenderedImage<Id, ViewOutputFormat<Views[Index], SharedFormat>>
    : never;
};
```

This mapped tuple preserves each input view's literal ID, position and length.
It narrows each entry's MIME type through the view's `format` override,
falling back to the shared format. Entry files are named
`render-<id>.<format>`.

### `RenderedImagesResult` [#renderedimagesresult]

The type that [`renderImages`](#renderimages) resolves to. It is the
[`RenderedImages`](#renderedimages) tuple, plus a
[`RenderTimings`](#rendertimings) on `timings` when the options literal set
`timings: true`. A read of `timings` without that request is a compile error.

```typescript
import { renderImages, type RenderedImagesResult, type RenderImagesOptions } from 'nanoraster';

const options = {
  format: 'webp',
  timings: true,
  views: [{ id: 'iso' }],
} as const satisfies RenderImagesOptions;

const result: RenderedImagesResult<typeof options> = await renderImages(glb, options);
console.log(result[0].file.name, result.timings.parse); // 'render-iso.webp' 0.42
```

### `RenderTimings` [#rendertimings]

A plan call's result carries this type when the options set `timings: true`.
The fields map onto the [pipeline stages](https://www.nanoraster.xyz/docs/how-it-works.mdx): parse, shared
cap-build, source upload, then per-view rasterise, annotate and encode.
Resource counters show which work the call acquired. `presentationBuilds` is
`1` for one plan.

**`RenderTimings`** — Stage timings for one timed plan call. The fields map onto the render pipeline's stages and reports the resources acquired by this call.

- **`parse`** (`number`, required) — Milliseconds. GLB parse, validation, and world-bounds computation.
- **`setup`** (`number`, required) — Milliseconds. Renderer acquisition plus all presentation and upload work.
- **`capBuild`** (`number`, required) — Milliseconds. Visibility resolution, section-cap construction, and cap upload.
- **`upload`** (`number`, required) — Milliseconds. Source triangle and authored-line upload.
- **`peakReadbackBytes`** (`number`, required) — Largest readback allocation required by one view, in bytes.
- **`glbParses`** (`number`, required) — GLB parses performed by this call.
- **`adapterDeviceRequests`** (`number`, required) — Adapter/device acquisitions performed by this call.
- **`pipelineSets`** (`number`, required) — Pipeline sets created by this call.
- **`presentationBuilds`** (`number`, required) — Shared presentation plans built by this call.
- **`sceneUploads`** (`number`, required) — Source scenes uploaded by this call.
- **`targetAllocations`** (`number`, required) — Render targets allocated by this call.
- **`views`** (`readonly RenderViewTimings[]`, required) — Per-view render/overlay/encode timings in plan order.
- **`sections`** (`readonly RenderSectionSourceTimings[]`, required) — Section outcome per plane and cut source, in plane then source order. Empty without sections.

### `RenderViewTimings` [#renderviewtimings]

One view's stage timings within a [`RenderTimings`](#rendertimings), in plan
order.

**`RenderViewTimings`** — Stage timings for one rendered view within a timed plan call.

- **`id`** (`string`, required) — Identity copied from the corresponding input view.
- **`render`** (`number`, required) — Milliseconds. GPU render, resolve, and pixel readback for this view.
- **`overlay`** (`number`, required) — Milliseconds. Annotation stamping (zero when no annotations were requested).
- **`encode`** (`number`, required) — Milliseconds. Image encoding in the requested format.

### `RenderSectionSourceTimings` [#rendersectionsourcetimings]

How one plane capped one source primitive it cuts, in
[`RenderTimings`](#rendertimings) `sections`. `certified` is `false` when the
source was sliced directly; `openChains` counts the cut outlines that do not
close. [Cut section views](https://www.nanoraster.xyz/docs/guides/render-section-views.mdx#read-the-cap) explains
both.

**`RenderSectionSourceTimings`** — How one section plane capped one source primitive it cuts. Sources the plane does not reach are omitted. An uncertified source is never an error.

- **`plane`** (`number`, required) — Index into `sections.planes`.
- **`nodeIndex`** (`number`, required) — Source node index of the cut primitive instance.
- **`meshIndex`** (`number`, required) — Source mesh index referenced by the node.
- **`primitiveIndex`** (`number`, required) — Source primitive index within the mesh.
- **`certified`** (`boolean`, required) — `true` when the source certified as closed, consistently oriented manifold shells and was capped exactly; `false` when it was sliced directly, filling its closed loops and outlining its open chains.
- **`closedLoops`** (`number`, required) — Closed cut loops on this plane, each filled with the striped cap.
- **`openChains`** (`number`, required) — Open or branched cut chains on this plane, outlined and left unfilled.

### `imageMimeTypes` [#imagemimetypes]

The readonly runtime map from output format to emitted MIME type.

```typescript
export declare const imageMimeTypes: {
  readonly png: 'image/png';
  readonly webp: 'image/webp';
  readonly jpeg: 'image/jpeg';
  readonly jpg: 'image/jpeg';
  readonly raw: 'application/octet-stream';
};
```

## Errors [#errors]

Rendering rejects with `RenderError`. Parse and encode failures are
deterministic for the same request. GPU faults can succeed after the host
recovers, so [Handle render failures](https://www.nanoraster.xyz/docs/guides/handle-render-failures.mdx) retries
them.

### `RenderFailureCode` [#renderfailurecode]

```typescript
export type RenderFailureCode =
  | 'adapter-unavailable'
  | 'device-lost'
  | 'driver-unsupported'
  | 'gpu'
  | 'parse'
  | 'encode'
  | 'unknown';
```

| Value                 | Meaning                                                      | Retry guidance                                              |
| --------------------- | ------------------------------------------------------------ | ----------------------------------------------------------- |
| `adapter-unavailable` | No compatible GPU adapter was available.                     | Keep the last image and retry after host recovery.          |
| `device-lost`         | The GPU device was lost during rendering.                    | Keep the last image and retry with a new device.            |
| `driver-unsupported`  | The host's GPU driver faults mid-render on 32-bit ARM Linux. | Render on another driver, or set the documented opt-out.    |
| `gpu`                 | Another adapter, driver, or render-pass failure occurred.    | Treat as transient unless host diagnostics prove otherwise. |
| `parse`               | GLB bytes or request options violated the input contract.    | Fix the input before retrying.                              |
| `encode`              | The selected encoder could not produce the requested image.  | Fix the format or background before retrying.               |
| `unknown`             | The thrown value had no recognised failure tag.              | Inspect `message` and preserve the original context.        |

### `RenderError` [#rendererror]

`RenderError` extends `Error` and adds this public surface:

```typescript
export declare class RenderError extends Error {
  readonly code: RenderFailureCode;
  constructor(code: RenderFailureCode, message: string);
  static from(error: unknown): RenderError;
  get isGpuFault(): boolean;
}
```

`RenderError.from(error)` returns an existing `RenderError` unchanged and
classifies any other thrown value. It never throws. `isGpuFault` is
`true` for `adapter-unavailable`, `device-lost` and `gpu`.

```typescript
import { RenderError, renderImage } from 'nanoraster';

try {
  await renderImage(glb, { format: 'webp' });
} catch (error) {
  const failure = RenderError.from(error);
  if (!failure.isGpuFault) throw failure;
}
```

## Constants [#constants]

Every bound and pattern that the validator applies, as the exact runtime
values. Import them instead of restating values, so caller-side checks cannot
drift.

| Export                                 | Runtime value                             | Unit or syntax              | Affected field              |
| -------------------------------------- | ----------------------------------------- | --------------------------- | --------------------------- |
| `renderImageDimensionRange`            | `readonly [16, 8192]`                     | pixels                      | `width`, `height`           |
| `renderImageQualityRange`              | `readonly [0, 1]`                         | normalised encoder quality  | `quality`                   |
| `renderImageMarginRange`               | `readonly [0, 0.5]`                       | minimum empty fraction      | `camera.margin`             |
| `renderImageVerticalFieldOfViewRange`  | `readonly [1, 179]`                       | degrees                     | `verticalFieldOfView`       |
| `renderImageZoomRange`                 | `readonly [0.01, 100]`                    | magnification               | `zoom`                      |
| `renderImageLineWidthRange`            | `readonly [0.25, 16]`                     | output pixels               | `lineWidth`                 |
| `renderImageAnnotatedMinDimension`     | `192`                                     | pixels                      | annotated `width`, `height` |
| `renderImageLabelMaxLength`            | `64`                                      | Unicode code points         | `label`                     |
| `renderImageLabelPattern`              | `/^[\u0020-\u007E\u00B5\u2014\u2212]+$/u` | supported characters        | `label`                     |
| `renderImageViewIdPattern`             | `/^[\dA-Za-z][\w-]{0,63}$/u`              | identifier syntax           | `id`                        |
| `renderImageBackgroundPattern`         | `/^#[\dA-Fa-f]{6}(?:[\dA-Fa-f]{2})?$/u`   | hexadecimal colour          | `background`                |
| `renderImageMaxLights`                 | `8`                                       | lights per rig              | `lighting.lights`           |
| `renderImageMaxLightCards`             | `16`                                      | cards per environment       | `environment.cards`         |
| `renderImageRigExtentRange`            | `readonly [-64, 64]`                      | scene radii                 | headlamp offsets, cards     |
| `renderImageLightCardIntensityRange`   | `readonly [0, 4096]`                      | linear radiance             | `cards[].intensity`         |
| `renderImageEnvironmentIntensityRange` | `readonly [0, 16]`                        | linear multiplier           | `environment.intensity`     |
| `renderImageMaxSections`               | `8`                                       | planes per request          | `sections.planes`           |
| `renderImageLightColorRange`           | `readonly [0, 32]`                        | linear radiance per channel | `lighting.lights[].color`   |
| `renderImageAmbientRange`              | `readonly [0, 4]`                         | diffuse multiplier          | `lighting.ambient`          |
| `renderImageExposureRange`             | `readonly [0.01, 16]`                     | linear multiplier           | `lighting.exposure`         |

```typescript
import { renderImageDimensionRange } from 'nanoraster';

const [min, max] = renderImageDimensionRange;

const clamp = (value: number): number => Math.min(Math.max(value, min), max);
```

### `renderImageDimensionRange` [#renderimagedimensionrange]

Inclusive bounds for both image dimensions.

### `renderImageMarginRange` [#renderimagemarginrange]

Inclusive minimum fitted-margin bounds.

### `renderImageVerticalFieldOfViewRange` [#renderimageverticalfieldofviewrange]

Inclusive vertical perspective field-of-view bounds.

### `renderImageZoomRange` [#renderimagezoomrange]

Inclusive perspective and orthographic magnification bounds.

### `renderImageLineWidthRange` [#renderimagelinewidthrange]

Inclusive authored-edge line-width bounds.

### `renderImageAnnotatedMinDimension` [#renderimageannotatedmindimension]

Minimum width and height when any annotation is enabled.

### `renderImageQualityRange` [#renderimagequalityrange]

Inclusive encoder-quality bounds. JPEG treats the value as a compression
level, with default `0.92`. WebP defaults to `1`, lossless, and treats any
lower value as lossy. PNG and raw ignore the value.

### `renderImageBackgroundPattern` [#renderimagebackgroundpattern]

The hex clear-colour syntax. It does not cover normalised straight-alpha RGBA
backgrounds.

### `renderImageLabelMaxLength` [#renderimagelabelmaxlength]

Maximum label length.

### `renderImageLabelPattern` [#renderimagelabelpattern]

Supported label characters: printable ASCII plus the micro sign, em dash, and
minus sign.

### `renderImageViewIdPattern` [#renderimageviewidpattern]

The view identifier syntax. IDs become filenames, so the pattern restricts
the first character.

### `renderImageMaxLights` [#renderimagemaxlights]

The directional-light cap for one rig.

### `renderImageMaxLightCards` [#renderimagemaxlightcards]

The light-card cap for one environment.

### `renderImageRigExtentRange` [#renderimagerigextentrange]

Bounds for headlamp offsets and card positions and sizes.

### `renderImageLightCardIntensityRange` [#renderimagelightcardintensityrange]

Bounds for a light card's radiance.

### `renderImageEnvironmentIntensityRange` [#renderimageenvironmentintensityrange]

Bounds for the environment radiance multiplier.

### `renderImageMaxSections` [#renderimagemaxsections]

The simultaneous retained-half-space plane cap for one request.

### `renderImageLightColorRange` [#renderimagelightcolorrange]

Inclusive per-channel bounds for a light's radiance.

### `renderImageAmbientRange` [#renderimageambientrange]

Inclusive bounds for the rig's flat ambient multiplier.

### `renderImageExposureRange` [#renderimageexposurerange]

Inclusive bounds for the pre-tone-map exposure multiplier.