Skip to content

ModuleCore / Passes and targetsConcept: Scenes and passes

Cameras

Orbit, flat, custom and layered cameras with shader accessors, eased motion and last-frame views.

import
import { cameras } from '@typegpu/kit'
call
cameras.custom(root, options?) → CustomCameraalso layered · turn · pan · cameras.eyeOf · cameras.orbit · cameras.flat · cameras.hitHeight
facts
injectshook
reference
Every call, option and member 27 options · 37 membersHow to read this
On this page

A camera keeps a goal that your input handlers and game logic can change. Once a , update(dt) eases the view towards it and writes the uniform only if the view moved. Shaders read it through one cameras.current , whichever kind of camera filled it.

An orbit camera eases toward its goal, in two views

Try Drag either view to move the goal marked by the dashed ring. Each frame calls update(dt) and writes the uniform only while the camera moves.
import {
import cameras
cameras
} from '@typegpu/kit';
const
const view: cameras.OrbitCamera
view
=
import cameras
cameras
.
function orbit(root: TgpuRoot, options: cameras.OrbitOptions): cameras.OrbitCamera

Creates a perspective camera that orbits a target and eases towards a goal set by input.

@returns ― a camera you update every frame

orbit
(
const root: TgpuRoot
root
, {
OrbitOptions.size: SizeSource

Supplies the size used for the aspect ratio, such as the canvas surface.

size
:
const surface: web.Surface
surface
,
OrbitOptions.target: readonly [number, number, number]

Sets the initial point that the camera orbits and looks at. Change it through goal.target.

target
: [0, 1, 0],
OrbitOptions.distance: number

Sets the initial distance from the target to the eye, in world units. Change it through goal.distance.

distance
: 12 });
import web
web
.
function orbitControls(orbit: {
readonly goal: web.OrbitGoal;
}, element: HTMLElement, options?: web.OrbitControlsOptions): web.OrbitControls

Connects pointer input to an orbit camera's goal. Drag to orbit and use the wheel or pinch to zoom. With pan, drag the other button to move the target. update eases the camera towards the goal. Throws if pan is enabled but the goal has no target.

@param ― orbit an orbit camera, whose goal it writes

@param ― element what takes the drag, the wheel and the pinch

@returns ― the controls, which you destroy to remove the listeners

orbitControls
(
const view: cameras.OrbitCamera
view
,
const canvas: HTMLCanvasElement
canvas
); // drag writes view.goal
const view: cameras.OrbitCamera
view
.goal.
Orbit.yaw: number
yaw
+=
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.PI: number

Pi. This is the ratio of the circumference of a circle to its diameter.

PI
/ 2; // or turn it from game logic
OrbitCamera.goal: cameras.Orbit

Sets the desired camera pose. update eases the view towards it.

import frames
frames
.
function create(root: TgpuRoot, record: Recorder): frames.Frames

Records a frame into one encoder and submits once, with a clock. Borrows the root. The synchronous recorder borrows each frame's encoder.

@submits ― always once a frame after your recorder returns, and again at each frame.submit()

@param ― record your frame, recorded into each frame's encoder

@returns ― a loop you run with each frame's time and destroy

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const view: cameras.OrbitCamera
view
.
OrbitCamera.update(dt: number): void

Eases towards the goal by dt seconds and writes the uniform if the view changed. Call once per frame.

update
(
frame: frames.Frame
frame
.
Frame.dt: number

Reports seconds since the previous submitted frame. The first frame has a dt of zero.

dt
); // eases, and writes the uniform if the view moved
// ..
});
  • Following Write goal.target to follow something; the target option is only where it starts. A knob that writes goal.fov eases like the rest.
  • Pose Read pose for CPU work that has to match the frame, such as a pan.
  • Easing update(dt) multiplies the gap by e−damping·dt. At the default damping of 14, half the gap closes every 50 ms at any frame rate. A gap under 1e-5 snaps shut.
  • Cuts Use jump() for a camera cut or a view drawn on demand. It preserves the view it replaced as last frame’s view.
  • Writes The camera writes its current-view uniform at creation and whenever the view or projection changes. The queue write lands before the frame’s commands. A still camera costs a few comparisons and allocates nothing.
  • Yaw Yaw eases along the shorter arc. A small change that crosses from near π to near −π in Math.atan2 still turns the camera only a little. A goal a whole number of turns away leaves the view where it is.
  • Ranges pitchRange and distanceRange clamp the orbit goal at creation and in update and jump. Input can write past them, and the camera clamps the result.
  • Floor floor(x, z) returns the lowest height the eye may reach over a point, such as the ground there plus a margin. At creation and in update and jump, the camera raises the goal’s pitch as far as needed to clear that height, up to the top of pitchRange.
  • Reach reach(target, yaw, pitch) returns how far the eye may go from the target along a direction, such as to a room’s wall less a margin. update and jump pull the pose’s distance in to it. goal.distance keeps the viewer’s zoom, so the eye comes back out as it turns away from the wall. Cloister keeps its eye inside the court this way.

A pan moves the target by the distance the finger moves over the ground. pan below works out that distance from the camera’s pose:

/** Moves the target by a drag of `dx`, `dy` pixels on a view `height` pixels tall. */
function
function pan(dx: number, dy: number, height: number): void

Moves the target by a drag of dx, dy pixels on a view height pixels tall.

pan
(
dx: number
dx
: number,
dy: number
dy
: number,
height: number
height
: number) {
const {
const yaw: number
yaw
,
const distance: number
distance
,
const fov: number
fov
} =
const view: cameras.OrbitCamera
view
.
OrbitCamera.pose: {
readonly yaw: number;
readonly pitch: number;
readonly distance: number;
readonly fov: number;
readonly target: readonly [number, number, number];
}

Reports the eased pose, the view as drawn while it approaches the goal.

pose
;
const
const scale: number
scale
= (2 *
const distance: number
distance
*
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.tan(x: number): number

Returns the tangent of a number.

@param ― x A numeric expression that contains an angle measured in radians.

tan
(
const fov: number
fov
/ 2)) /
height: number
height
;
const
const cos: number
cos
=
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.cos(x: number): number

Returns the cosine of a number.

@param ― x A numeric expression that contains an angle measured in radians.

cos
(
const yaw: number
yaw
);
const
const sin: number
sin
=
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.sin(x: number): number

Returns the sine of a number.

@param ― x A numeric expression that contains an angle measured in radians.

sin
(
const yaw: number
yaw
);
const view: cameras.OrbitCamera
view
.
OrbitCamera.goal: cameras.Orbit

Sets the desired camera pose. update eases the view towards it.

goal
.
Orbit.target: [number, number, number]

Sets the point that the camera orbits and looks at.

target
[0] -= (
const cos: number
cos
*
dx: number
dx
+
const sin: number
sin
*
dy: number
dy
) *
const scale: number
scale
;
const view: cameras.OrbitCamera
view
.
OrbitCamera.goal: cameras.Orbit

Sets the desired camera pose. update eases the view towards it.

goal
.
Orbit.target: [number, number, number]

Sets the point that the camera orbits and looks at.

target
[2] -= (
const cos: number
cos
*
dy: number
dy
-
const sin: number
sin
*
dx: number
dx
) *
const scale: number
scale
;
}

The stampede keeps the eye 1.2 m above its hills, however low input turns it:

const
const view: cameras.OrbitCamera
view
=
import cameras
cameras
.
function orbit(root: TgpuRoot, options: cameras.OrbitOptions): cameras.OrbitCamera

Creates a perspective camera that orbits a target and eases towards a goal set by input.

@returns ― a camera you update every frame

orbit
(
const root: TgpuRoot
root
, {
OrbitOptions.size: SizeSource

Supplies the size used for the aspect ratio, such as the canvas surface.

size
: {
SizeSource.width: number

Reports the width in pixels.

width
: 8,
SizeSource.height: number

Reports the height in pixels.

height
: 6 },
OrbitOptions.target: readonly [number, number, number]

Sets the initial point that the camera orbits and looks at. Change it through goal.target.

target
: [0, 2, 0],
OrbitOptions.distance: number

Sets the initial distance from the target to the eye, in world units. Change it through goal.distance.

distance
: 40,
OrbitOptions.floor?: ((x: number, z: number) => number) | undefined

Returns the lowest height the eye may reach at a point x, z, in world units, such as a terrain's height plus a margin. update and jump raise the goal pitch, within pitchRange, until the eye is at or above it. Default no floor.

@cpu

floor
: (
x: number
x
,
z: number
z
) =>
function heightAt(x: number, z: number): number
heightAt
(
x: number
x
,
z: number
z
) + 1.2,
});

cameras.eyeOf(pose, out) writes an orbit camera’s eye position for either goal or pose. Use it for CPU work at the eye, such as placing a sound.

root.pipe(view.inject()) fills the cameras.current accessor from @typegpu/kit with the camera’s uniform:

Field Type Meaning
viewProjection mat4x4f World to clip space.
position vec3f The eye, in world space.
right, up vec3f The view’s x and y axes in world space, for quads that face the screen.

cameras.toClip(point) returns a world point in clip space, the position a vertex shader returns. It reads cameras.current itself. Code that projects with a view of its own, such as a shadow’s, multiplies by that view’s viewProjection.

A function of your own that takes cameras.current.$ types that parameter as cameras.Camera. These 'use gpu' functions take it and derive the rest:

  • Forward cameras.forwardOf(view) returns the direction the view looks in.
  • Lens cameras.lensOf(view) returns the projection’s x and y scales.
  • Ray cameras.rayOf(view, ndc) returns an origin and a unit direction through a screen point. ndc ranges from −1 to 1 with +y up. Orbit rays start at the eye. Flat rays are parallel and start at their screen points. To go back to the screen, multiply a point on the ray, such as origin + direction, by viewProjection and divide by w.
  • To the viewer cameras.towards(view, point) returns the unit direction from a point to the viewer for shading. For a flat camera it is the opposite of the view direction.
  • Distance cameras.distanceOf(view, depth) returns the distance along the view direction to the point a depth value holds, for orbit and flat cameras alike. Read depth from the depth target the view drew. Depth of field, ambient occlusion and the night market’s focus pull read distance this way.

forwardOf returns cross(up, right), so right, up and the view direction form a right-handed basis. A Camera you build in a shader must keep that basis. A view of a reflection must also mirror the image, as the fireworks lake does. Read what it drew with u mirrored.

import {
import cameras
cameras
} from '@typegpu/kit';
/** Where the pointer's ray meets the ground, y = 0. */
const
const ground: () => d.v3f

Where the pointer's ray meets the ground, y = 0.

ground
= () => {
'use gpu';
const
const ray: {
origin: d.v3f;
direction: d.v3f;
}
ray
=
import cameras
cameras
.
const rayOf: (view: cameras.Camera, ndc: d.v2f) => {
origin: d.v3f;
direction: d.v3f;
}

Returns the ray through ndc, with coordinates from -1 to 1 and +y up. Perspective rays start at the eye. Orthographic rays, such as those from cameras.flat, are parallel and start at their screen points at the depth of the eye. To go back to the screen, multiply a point on the ray by viewProjection and divide by w.

rayOf
(
import cameras
cameras
.
const current: TgpuAccessor<d.WgslStruct<{
viewProjection: d.Mat4x4f;
position: d.Vec3f;
right: d.Vec3f;
up: d.Vec3f;
}>>

Provides the camera for a pipeline. A camera's inject() fills it with the camera uniform.

current
.
TgpuAccessor<WgslStruct<{ viewProjection: Mat4x4f; position: Vec3f; right: Vec3f; up: Vec3f; }>>.$: {
viewProjection: d.m4x4f;
position: d.v3f;
right: d.v3f;
up: d.v3f;
}
$
,
const pointer: TgpuUniform<d.WgslStruct<{
ndc: d.Vec2f;
}>>
pointer
.
TgpuUniform<WgslStruct<{ ndc: Vec2f; }>>.$: {
ndc: d.v2f;
}
$
.
ndc: d.v2f
ndc
);
return
const ray: {
origin: d.v3f;
direction: d.v3f;
}
ray
.
origin: d.v3f
origin
+
const ray: {
origin: d.v3f;
direction: d.v3f;
}
ray
.
direction: d.v3f

Gives the unit ray direction.

direction
* (-
const ray: {
origin: d.v3f;
direction: d.v3f;
}
ray
.
origin: d.v3f
origin
.
v3f.y: number
y
/
const ray: {
origin: d.v3f;
direction: d.v3f;
}
ray
.
direction: d.v3f

Gives the unit ray direction.

direction
.
v3f.y: number
y
);
};

cameras.sees(view, center, radius) returns false only when a sphere lies wholly outside one of the view’s six planes. It can accept a sphere beyond a corner. Use it in the alive callback of live lists with the camera’s fill:

// Balls, each a centre and a radius in a vec4f
const
const balls: TgpuReadonly<d.WgslArray<d.Vec4f>>
balls
=
const root: TgpuRoot
root
.
TgpuRoot.createReadonly<d.WgslArray<d.Vec4f>>(typeSchema: d.WgslArray<d.Vec4f>, initial?: ((buffer: TgpuBuffer<NoInfer<d.WgslArray<d.Vec4f>>>) => void) | d.InferInput<NoInfer<d.WgslArray<d.Vec4f>>> | undefined): TgpuReadonly<d.WgslArray<d.Vec4f>> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader. Read-only on the GPU, optimized for large data. For a general-purpose buffer, use

TgpuRoot.createBuffer

.

@param ― typeSchema The type of data that this buffer will hold.

@param ― initial Either initial value of the buffer, or an initializer to execute on the mapped buffer. (optional)

createReadonly
(
import d
d
.
arrayOf<d.Vec4f>(elementType: d.Vec4f, elementCount: number): d.WgslArray<d.Vec4f> (+2 overloads)
export arrayOf

@location ― . Wrap align/size in a struct instead, e.g. d.arrayOf(d.struct({ value: d.align(16, d.u32) }), n).

arrayOf
(
import d
d
.
const vec4f: d.Vec4f
vec4f
, 256));
const
const seen: liveLists.LiveLists
seen
=
import liveLists
liveLists
.
function create(root: TgpuRoot, options: liveLists.Options): liveLists.LiveLists

Creates a list of live slots and an indirect draw per group. Each group reserves capacity slots. A shader finds rows with live.slot(group, i) using a captured group index. With firstInstance, it can use live.instanceSlot(instanceIndex) instead. Throws if the groups, draws or workgroup size are invalid, the slot buffer exceeds maxStorageBufferBindingSize, compact over the capacity needs more than maxComputeWorkgroupsPerDimension workgroups, or firstInstance lacks its required feature.

@param ― options.alive whether a slot holds a live row, carrying the fills of what it reads, such as a table's from rows.live(), spread into the options with its capacity

@param ― options.draws one draw per group

@returns ― live lists you run every frame and destroy

create
(
const root: TgpuRoot
root
, {
ListOptions.capacity: number

Sets the number of slots, including dead slots. Indices range from 0 to capacity - 1.

capacity
: 256,
ListOptions.draws?: readonly liveLists.IndirectDraw[] | undefined

Provides one draw per group. Requires 1 to 256 draws. Default an empty draw for each of groups, for lists that only dispatch.

draws
: [{
vertexCount: number
vertexCount
: 36 }],
alive: (i: number) => boolean

Tests whether slot i holds a live row. A table supplies this through live(). Default every slot is live.

@gpu

alive
:
const tgpu: {
const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
init: typeof import("node_modules/typegpu/core/root/init").init;
initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
... 10 more ...;
'~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
}

@module ― typegpu

tgpu
.
fn: <(i: number) => boolean>(inner: (i: number) => boolean) => TgpuGenericFn<(i: number) => boolean> (+2 overloads)
fn
((
i: number
i
: number) => {
'use gpu';
const
const ball: d.v4f
ball
=
const balls: TgpuReadonly<d.WgslArray<d.Vec4f>>
balls
.
TgpuReadonly<WgslArray<Vec4f>>.$: d.v4f[]
$
[
i: number
i
];
return
import cameras
cameras
.
const sees: (view: cameras.Camera, center: d.v3f, radius: number) => boolean

Tests whether a world-space sphere may be visible. Returns false only when the whole sphere lies outside one of the six view planes. A sphere beyond a corner can still return true. Use it for culling, such as in live lists' alive function with the camera piped in: sees(cameras.current.$, center, radius).

sees
(
import cameras
cameras
.
const current: TgpuAccessor<d.WgslStruct<{
viewProjection: d.Mat4x4f;
position: d.Vec3f;
right: d.Vec3f;
up: d.Vec3f;
}>>

Provides the camera for a pipeline. A camera's inject() fills it with the camera uniform.

current
.
TgpuAccessor<WgslStruct<{ viewProjection: Mat4x4f; position: Vec3f; right: Vec3f; up: Vec3f; }>>.$: {
viewProjection: d.m4x4f;
position: d.v3f;
right: d.v3f;
up: d.v3f;
}
$
,
const ball: d.v4f
ball
.
xyz: d.v3f
xyz
,
const ball: d.v4f
ball
.
v4f.w: number
w
);
})
.
TgpuGenericFn<(i: number) => boolean>.pipe(transform: (cfg: Configurable) => Configurable): TgpuGenericFn<(i: number) => boolean>

Applies a configuration transform to the slots and accessors this function reads, as root.pipe does to a pipeline's.

pipe
(
const view: cameras.OrbitCamera
view
.
CameraBase.inject(): Inject

Fills cameras.current for the pipelines created from the configuration it is piped into.

inject
()),
});

To find what is under a pointer among things that move on the GPU, use picker, which projects each candidate with this camera.

view.previous holds last frame’s view. Code compiled with history.previously reads it through cameras.current for motion vectors and reprojection. toClip compiled this way finds where a world position appeared on screen last frame:

const clipBefore = history.previously(cameras.toClip);

The orbit and flat cameras write previous in update and jump. When they move, they store the view they replace. On the frame after they stop, they store the current view.

Each kit camera keeps a CPU copy of the view its uniform holds, for CPU work that has to match the frame. None of these calls allocates:

  • Surface points view.projectAt and view.rayAt take points of the surface, x and y from 0 to 1 with +y down, as web.pointer reports them. A point from projectAt gives rayAt a ray through the world point.
  • Level planes cameras.hitHeight(ray, height, out) writes where a ray meets the level plane at height and returns how far along the ray that is. It returns undefined, writing nothing, for a ray that runs level or points away. With { grazing }, it also rejects rays whose absolute y direction is at or below grazing. Rays this close to level can hit far beyond the scene, near the horizon.
  • Terrain height can also be a function of x and z, such as a terrain’s height. hitHeight searches along the ray up to reach. It starts with step and grows the step by 4% each time. When a step reaches the ground or goes below it, the function bisects that interval 16 times. An infinite reach searches until a hit and needs a step. It allocates nothing, so a pointer can find the hills under it every frame, as in the stampede.
const
const at: number[]
at
= [0, 0, 0];
const
const ray: {
origin: number[];
direction: number[];
}
ray
= {
origin: number[]
origin
: [0, 0, 0],
direction: number[]
direction
: [0, 0, 0] };
// A label over a point, in CSS pixels of an 800 by 600 canvas
if (
const view: cameras.OrbitCamera
view
.
CpuView.projectAt(point: ArrayLike<number>, out: cameras.Out3): boolean

Projects a world point to a point of the surface, as rayAt takes it. Writes x and y from 0 to 1 across the surface with +y down, as pointer handlers receive them, and depth from 0 to 1 in z. Returns false without changing out for a point behind the eye or before the first write.

projectAt
([0, 2, 0],
const at: number[]
at
)) {
const label: HTMLElement
label
.
ElementCSSInlineStyle.style: CSSStyleDeclaration
style
.
CSSStyleProperties.translate: string

The translate CSS property allows you to specify translation transforms individually and independently of the transform property. This maps better to typical user interface usage, and saves having to remember the exact order of transform functions to specify in the transform value.

MDN Reference

translate
= `${
const at: number[]
at
[0] * 800}px ${
const at: number[]
at
[1] * 600}px`;
}
// The ground under the pointer, y = 0; a miss leaves `aim` where it was
const
const aim: number[]
aim
= [0, 0, 0];
const
const pointing: {
move(x: number, y: number): void;
}
pointing
= {
function move(x: number, y: number): void
move
(
x: number
x
: number,
y: number
y
: number) {
const view: cameras.OrbitCamera
view
.
CpuView.rayAt(x: number, y: number, out: cameras.CpuRay): void

Writes the ray through a point of the surface into out, as ray does. x and y range from 0 to 1 across the surface with +y down, as pointer handlers receive them.

rayAt
(
x: number
x
,
y: number
y
,
const ray: {
origin: number[];
direction: number[];
}
ray
);
import cameras
cameras
.
function hitHeight(ray: cameras.CpuRay<ArrayLike<number>>, height: number | ((x: number, z: number) => number), out?: cameras.Out3, options?: cameras.HitOptions): number | undefined

Finds where a ray, such as one from view.rayAt, meets the ground at height, such as the ground under a pointer. A height function, such as a terrain's, is searched in growing steps up to reach, then refined by halving the last step. Writes the point into out when given. Allocates nothing.

@param ― ray an origin and a unit direction

@param ― height the y of a level plane, or of the ground at each x and z

@param ― out where the point goes

@returns ― the distance along the ray, or undefined for a ray that misses

hitHeight
(
const ray: {
origin: number[];
direction: number[];
}
ray
, 0,
const aim: number[]
aim
, {
HitOptions.grazing?: number | undefined

Misses rays whose direction's y is nearer 0 than this, so a ray near the horizon finds no hit far away. Default 0, which misses only rays parallel to a level plane.

grazing
: 0.01 });
},
};

Both read the view the frame draws, as the last update, write or jump left it. They ignore the goal. A custom camera projects nothing before its first write. A function that takes the ray types it as cameras.CpuRay.

A that reads a camera of its own takes it as an argument and pipes it in, as particles.create does. Meshes shows a vertex shader that reads it.

web.orbitControls(view, element, { sensitivity, zoomSpeed, button, pan, page, pointer, onChange }) writes the goal from the pointer.

  • Orbit and zoom A drag with the primary button orbits by sensitivity radians per pixel, 0.008 by default, and keeps going outside the element. The wheel and a pinch zoom without scrolling the page. The wheel multiplies the distance by edeltaY·zoomSpeed, with a default zoomSpeed of 0.001. A two-finger pinch multiplies the distance by the ratio of the previous finger spread to the new one.
  • Other buttons With button: 'secondary' or 'middle', that button orbits. Without panning enabled, two fingers also orbit as their midpoint moves during a pinch. The primary button and one finger stay free for the scene, such as for strokes from web.pointer that paint.
  • Panning With pan: true, the secondary button pans the target as cameras.pan does. When the secondary button orbits, the middle one pans instead. Two fingers moving together pan too. Buttons the controls use open no context menu and start no autoscroll.
  • In a page With page: true, vertical swipes and the wheel scroll the page. Horizontal drags turn the camera. Pinches and wheel events with Ctrl or ⌘ held zoom it. Trackpad pinches send those wheel events. Use it for a canvas inside a page that scrolls.
  • Changes onChange runs after each input that wrote the goal, for a view that draws only when asked.
  • Touch action It sets the element’s touch-action to none, or pan-y with page. destroy(), or [Symbol.dispose], removes listeners and restores the original value. Create controls in attach on a hosted page to dispose them with the scene.
  • Beside a pointer On an element that a web.pointer also follows, pass it as pointer. The pointer then sets touch-action from its own page and captures each press. The controls’ page decides only the wheel. Destroy the controls before the pointer.
  • Taps The controls leave taps to the app. Listen on the same element and count a release within a few pixels of its press as a tap, such as one that places a tower on a board the drag orbits.

Here the primary button paints through the pointer and the secondary button orbits:

const
const brush: web.Pointer
brush
=
import web
web
.
function pointer(element: HTMLElement, options?: web.PointerOptions): web.Pointer

Follows the mouse, touch or pen on an element in the coordinates rayAt takes, 0 to 1 across the element with +y down. Read the position each frame or take each move, press, release and zoom. A button pressed on the element keeps the pointer until it comes up, so a drag continues outside and its positions run past 0 and 1.

@param ― element what the pointer moves over, usually the canvas

@returns ― the pointer, which you destroy to remove the listeners

pointer
(
const canvas: HTMLCanvasElement
canvas
, {
PointerOptions.move?: web.PointerHandler | undefined

Runs as the pointer moves over the element, or anywhere while it holds a button down. Default none.

@cpu

move
: (
x: number
x
,
y: number
y
,
event: PointerEvent
event
) => {
if (
event: PointerEvent
event
.
MouseEvent.buttons: number

The MouseEvent.buttons read-only property indicates which buttons are pressed on the mouse (or other input device) when a mouse event is triggered.

MDN Reference

buttons
=== 1)
function paint(x: number, y: number): void
paint
(
x: number
x
,
y: number
y
);
},
});
import web
web
.
function orbitControls(orbit: {
readonly goal: web.OrbitGoal;
}, element: HTMLElement, options?: web.OrbitControlsOptions): web.OrbitControls

Connects pointer input to an orbit camera's goal. Drag to orbit and use the wheel or pinch to zoom. With pan, drag the other button to move the target. update eases the camera towards the goal. Throws if pan is enabled but the goal has no target.

@param ― orbit an orbit camera, whose goal it writes

@param ― element what takes the drag, the wheel and the pinch

@returns ― the controls, which you destroy to remove the listeners

orbitControls
(
const view: cameras.OrbitCamera
view
,
const canvas: HTMLCanvasElement
canvas
, {
OrbitControlsOptions.button?: "primary" | "secondary" | "middle" | undefined

Orbits with this mouse button. 'secondary' and 'middle' leave the primary button and one finger to other listeners, such as strokes that paint, and two fingers orbit by the move of their midpoint. Default 'primary'.

button
: 'secondary',
OrbitControlsOptions.pointer?: web.Pointer | undefined

Leaves the element's touch-action and pointer capture to this pointer on the same element, which sets them from its own page. Destroy the controls before the pointer. Default none, so the controls set both.

pointer
:
const brush: web.Pointer
brush
});

For a the controls don’t offer, write the goal yourself. cameras.turn(goal, dx, dy, { sensitivity }) turns it by a drag as the controls do. cameras.pan(goal, dx, dy, { height }) pans it, where height is the view’s height in the units of the drag. Here a drag turns the view, a drag with Shift held pans it and the wheel zooms:

import web
web
.
function pointer(element: HTMLElement, options?: web.PointerOptions): web.Pointer

Follows the mouse, touch or pen on an element in the coordinates rayAt takes, 0 to 1 across the element with +y down. Read the position each frame or take each move, press, release and zoom. A button pressed on the element keeps the pointer until it comes up, so a drag continues outside and its positions run past 0 and 1.

@param ― element what the pointer moves over, usually the canvas

@returns ― the pointer, which you destroy to remove the listeners

pointer
(
const canvas: HTMLCanvasElement
canvas
, {
PointerOptions.move?: web.PointerHandler | undefined

Runs as the pointer moves over the element, or anywhere while it holds a button down. Default none.

@cpu

move
(
_x: number
_x
,
_y: number
_y
,
event: PointerEvent
event
) {
if (
event: PointerEvent
event
.
MouseEvent.buttons: number

The MouseEvent.buttons read-only property indicates which buttons are pressed on the mouse (or other input device) when a mouse event is triggered.

MDN Reference

buttons
!== 1) return;
const {
MouseEvent.movementX: number

The movementX read-only property of the MouseEvent interface provides the difference in the X coordinate of the mouse (or pointer) between the given move event and the previous move event of the same type.

MDN Reference

movementX
:
const dx: number

The movementX read-only property of the MouseEvent interface provides the difference in the X coordinate of the mouse (or pointer) between the given move event and the previous move event of the same type.

MDN Reference

dx
,
MouseEvent.movementY: number

The movementY read-only property of the MouseEvent interface provides the difference in the Y coordinate of the mouse (or pointer) between the given move event and the previous move event of the same type.

MDN Reference

movementY
:
const dy: number

The movementY read-only property of the MouseEvent interface provides the difference in the Y coordinate of the mouse (or pointer) between the given move event and the previous move event of the same type.

MDN Reference

dy
} =
event: PointerEvent
event
;
if (
event: PointerEvent
event
.
MouseEvent.shiftKey: boolean

The MouseEvent.shiftKey read-only property is a boolean value that indicates whether the shift key was pressed or not when a given mouse event occurs.

MDN Reference

shiftKey
)
import cameras
cameras
.
function pan<cameras.Orbit>(goal: cameras.Orbit, dx: number, dy: number, options: cameras.PanOptions): cameras.Orbit

Pans an orbit's goal by a drag: the target moves across the view against the drag, one camera distance per height dragged, so the scene follows the pointer. web.orbitControls pans by it.

@param ― goal an orbit camera's goal, whose target it writes

@param ― dx the drag to the right, in pixels or points

@param ― dy the drag down, in pixels or points

@returns ― goal

pan
(
const view: cameras.OrbitCamera
view
.
OrbitCamera.goal: cameras.Orbit

Sets the desired camera pose. update eases the view towards it.

goal
,
const dx: number

The movementX read-only property of the MouseEvent interface provides the difference in the X coordinate of the mouse (or pointer) between the given move event and the previous move event of the same type.

MDN Reference

dx
,
const dy: number

The movementY read-only property of the MouseEvent interface provides the difference in the Y coordinate of the mouse (or pointer) between the given move event and the previous move event of the same type.

MDN Reference

dy
, {
PanOptions.height: number

Sets the view's height in the units of the drag, one camera distance of panning.

height
:
const canvas: HTMLCanvasElement
canvas
.
Element.clientHeight: number

The clientHeight read-only property of the Element interface is zero for elements with no CSS or inline layout boxes; otherwise, it's the inner height of an element in pixels. It includes padding but excludes borders, margins, and horizontal scrollbars (if present).

MDN Reference

clientHeight
});
else
import cameras
cameras
.
function turn<cameras.Orbit>(goal: cameras.Orbit, dx: number, dy: number, options?: cameras.TurnOptions): cameras.Orbit

Turns an orbit's goal by a drag: a drag to the right turns the eye left around the target, and a drag down raises it. web.orbitControls turns by it.

@param ― goal an orbit camera's goal, whose yaw and pitch it writes

@param ― dx the drag to the right, in pixels or points

@param ― dy the drag down, in pixels or points

@returns ― goal

turn
(
const view: cameras.OrbitCamera
view
.
OrbitCamera.goal: cameras.Orbit

Sets the desired camera pose. update eases the view towards it.

goal
,
const dx: number

The movementX read-only property of the MouseEvent interface provides the difference in the X coordinate of the mouse (or pointer) between the given move event and the previous move event of the same type.

MDN Reference

dx
,
const dy: number

The movementY read-only property of the MouseEvent interface provides the difference in the Y coordinate of the mouse (or pointer) between the given move event and the previous move event of the same type.

MDN Reference

dy
);
},
PointerOptions.zoom?: ((by: number) => void) | undefined

Runs as the wheel turns or two fingers pinch on the element, with the factor to scale a distance by, above 1 farther: e^(deltaY × 0.001) for the wheel, and the ratio of the fingers' last spread to the new one for a pinch. Default none.

@cpu

zoom
: (
by: number
by
) => {
const view: cameras.OrbitCamera
view
.
OrbitCamera.goal: cameras.Orbit

Sets the desired camera pose. update eases the view towards it.

goal
.
Orbit.distance: number
distance
*=
by: number
by
;
},
});

WebKit and Firefox for Android report movementX and movementY as 0 for touch, so a binding for fingers takes the change in clientX and clientY between moves, as the controls do.

On React Native, write goal from gesture handlers. Here the scene runs on the JS thread and height is the view’s height in points. One finger turns the view and two pan it:

const orbit = Gesture.Pan()
.runOnJS(true)
.maxPointers(1)
.onChange((event) => {
cameras.turn(view.goal, event.changeX, event.changeY);
});
const pan = Gesture.Pan()
.runOnJS(true)
.minPointers(2)
.onChange((event) => {
cameras.pan(view.goal, event.changeX, event.changeY, { height });
});
const zoom = Gesture.Pinch()
.runOnJS(true)
.onChange((event) => {
view.goal.distance /= event.scaleChange;
});

A handler can’t access a scene on another . Write cumulative gesture values to a runtimes.cell. Each frame, have the scene move the goal by the change in those values.

cameras.flat(root, { size, height }) gives an orthographic view height world units tall, with +y up and z from −1 to 1. snap rounds the drawn centre to a grid, such as one of a pixel-art target, so the art doesn’t shimmer as the view follows a hero. Pass that target as size.

fit: { width, height, mode } replaces height with a world rectangle centred on the view. 'cover' fills the view with it and crops its longer side; 'contain' shows all of it and leaves bands. At creation and whenever the aspect changes, the camera sets goal.height and its eased height at once. A zoom you write still eases, until the next resize sets the height again. The ember mirror covers the screen with its camera feed this way.

cameras.custom(root) takes matrices you supply for a follow camera, a scripted shot or a repeatable benchmark view. Pass write(view, projection) a view matrix containing rotation and translation, such as one from mat4.lookAt, and a projection matrix. It derives the eye and screen axes and fills cameras.current. The orbit and flat cameras use this implementation.

import {
import cameras
cameras
} from '@typegpu/kit';
import {
const mat4: {
add: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(a: Mat4Arg, b: Mat4Arg, dst?: T | undefined) => T;
aim: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(position: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: T | undefined) => T;
axisRotate: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(m: Mat4Arg, axis: Vec3Arg, angleInRadians: number, dst?: T | undefined) => T;
... 44 more ...;
uniformScaling: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(s: number, dst?: T | undefined) => T;
}

4x4 Matrix functions that default to returning Float32Array

@namespace

mat4
} from 'wgpu-matrix';
const
const chase: cameras.CustomCamera
chase
=
import cameras
cameras
.
function custom(root: TgpuRoot, options?: cameras.DepthOptions): cameras.CustomCamera

Creates a camera from view and projection matrices that you write. Use it for a follow camera, a scripted camera or another rig. It fills cameras.current and holds zeros until the first write.

@returns ― a camera you write

custom
(
const root: TgpuRoot
root
);
const
const eye: Float32Array<ArrayBuffer>
eye
= new
var Float32Array: Float32ArrayConstructor
new (length: number) => Float32Array<ArrayBuffer> (+6 overloads)
Float32Array
(3);
const
const up: number[]
up
= [0, 1, 0];
const
const view: Float32Array<ArrayBufferLike>
view
=
const mat4: {
add: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(a: Mat4Arg, b: Mat4Arg, dst?: T | undefined) => T;
aim: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(position: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: T | undefined) => T;
axisRotate: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(m: Mat4Arg, axis: Vec3Arg, angleInRadians: number, dst?: T | undefined) => T;
... 44 more ...;
uniformScaling: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(s: number, dst?: T | undefined) => T;
}

4x4 Matrix functions that default to returning Float32Array

@namespace

mat4
.
create: (v0?: number, v1?: number, v2?: number, v3?: number, v4?: number, v5?: number, v6?: number, v7?: number, v8?: number, v9?: number, v10?: number, v11?: number, v12?: number, v13?: number, v14?: number, v15?: number) => Float32Array<ArrayBufferLike>
create
();
const
const projection: Float32Array<ArrayBufferLike>
projection
=
const mat4: {
add: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(a: Mat4Arg, b: Mat4Arg, dst?: T | undefined) => T;
aim: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(position: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: T | undefined) => T;
axisRotate: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(m: Mat4Arg, axis: Vec3Arg, angleInRadians: number, dst?: T | undefined) => T;
... 44 more ...;
uniformScaling: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(s: number, dst?: T | undefined) => T;
}

4x4 Matrix functions that default to returning Float32Array

@namespace

mat4
.
perspective: <Float32Array<ArrayBufferLike>>(fieldOfViewYInRadians: number, aspect: number, zNear: number, zFar: number, dst?: Float32Array<ArrayBufferLike> | undefined) => Float32Array<ArrayBufferLike>
perspective
(0.8,
const aspect: number
aspect
, 0.1, 500);
// after the hero moves
const eye: Float32Array<ArrayBuffer>
eye
[0] =
const hero: Float32Array<ArrayBufferLike>
hero
[0];
const eye: Float32Array<ArrayBuffer>
eye
[1] =
const hero: Float32Array<ArrayBufferLike>
hero
[1] + 3;
const eye: Float32Array<ArrayBuffer>
eye
[2] =
const hero: Float32Array<ArrayBufferLike>
hero
[2] + 6;
const chase: cameras.CustomCamera
chase
.
CustomCamera.write(view: Mat4Arg, projection: Mat4Arg): void

Writes the camera from a view matrix and a projection matrix. The view matrix, such as one from mat4.lookAt, supplies the eye position and screen axes. Moves the current view to previous. Call once per frame, even when the view is still. Repeated writes of the same view write nothing once previous matches it. Throws for a view that mirrors the world. Mirror the image too, with mat4.multiply(mat4.scaling([-1, 1, 1]), view). Write a reversed projection, such as one from mat4.perspectiveReverseZ, into a camera created with reversed: true.

write
(
const mat4: {
add: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(a: Mat4Arg, b: Mat4Arg, dst?: T | undefined) => T;
aim: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(position: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: T | undefined) => T;
axisRotate: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(m: Mat4Arg, axis: Vec3Arg, angleInRadians: number, dst?: T | undefined) => T;
... 44 more ...;
uniformScaling: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(s: number, dst?: T | undefined) => T;
}

4x4 Matrix functions that default to returning Float32Array

@namespace

mat4
.
lookAt: <Float32Array<ArrayBufferLike>>(eye: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: Float32Array<ArrayBufferLike> | undefined) => Float32Array<ArrayBufferLike>
lookAt
(
const eye: Float32Array<ArrayBuffer>
eye
,
const hero: Float32Array<ArrayBufferLike>
hero
,
const up: number[]
up
,
const view: Float32Array<ArrayBufferLike>
view
),
const projection: Float32Array<ArrayBufferLike>
projection
);
  • Skipping write while the view is still leaves previous stale.
  • Until the first write the uniform holds zeros, and nothing drawn with it shows.
  • write throws for a view matrix that mirrors the world. For a reflection, mirror the image too with mat4.multiply(mat4.scaling([-1, 1, 1]), view). Triangles then keep their winding.

cameras.layered(root, n) holds n views in one uniform array, one for each layer of a description drawn into layers, such as a shadow cascade each. write(k, view, projection) writes layer k from the same matrices as a custom camera’s write. cameras.current.$ in a pass into layer k is view k:

import {
import cameras
cameras
} from '@typegpu/kit';
import {
const mat4: {
add: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(a: Mat4Arg, b: Mat4Arg, dst?: T | undefined) => T;
aim: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(position: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: T | undefined) => T;
axisRotate: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(m: Mat4Arg, axis: Vec3Arg, angleInRadians: number, dst?: T | undefined) => T;
... 44 more ...;
uniformScaling: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(s: number, dst?: T | undefined) => T;
}

4x4 Matrix functions that default to returning Float32Array

@namespace

mat4
} from 'wgpu-matrix';
const
const views: cameras.LayeredCamera
views
=
import cameras
cameras
.
function layered(root: TgpuRoot, count: number): cameras.LayeredCamera

Creates a view for each layer of a description drawn into layers, in one uniform array. It keeps no previous views, so cameras.current.$ reads the current view in code compiled with history.previously.

@param ― root the root that owns the uniform

@param ― count the number of layers, the layers of the targets the description draws into

@returns ― views you write

layered
(
const root: TgpuRoot
root
, 2);
const
const casters: passes.Description<{
readonly depth: typeof passes.depth;
}>
casters
=
import passes
passes
.
function create<{
depth: {
format: "depth16unorm";
layers: 2;
};
}, {
readonly depth: typeof passes.depth;
}>(root: TgpuRoot, screen: Targets<{
depth: {
format: "depth16unorm";
layers: 2;
};
}>, writes: {
readonly depth: typeof passes.depth;
}, options?: passes.TargetOptions<{
depth: {
format: "depth16unorm";
layers: 2;
};
}> | undefined): passes.Description<{
readonly depth: typeof passes.depth;
}> (+1 overload)

Describes the targets and outputs for scene passes. With a surface such as the canvas, writes only each renderer's colour. With a target set, writes colour into the target marked color, depth into the target marked depth, and other outputs into their named targets. Multisampled targets resolve according to resolve. Targets with layers draw one pass per layer, and every target the description draws into needs the same layers. add builds a renderer's drawing. begin starts a pass. pipe supplies fills such as a camera.

@param ― screen the surface, or the targets, which give the formats; each one the description names is drawn into

@param ― writes what fills each target, by its key in screen

@returns ― a description you destroy, which holds the pipelines it builds

create
(
const root: TgpuRoot
root
,
const maps: Targets<{
depth: {
format: "depth16unorm";
layers: 2;
};
}>
maps
, {
depth: typeof passes.depth
depth
:
import passes
passes
.
const depth: typeof passes.depth

Marks the depth target.

depth
}).
Description<{ readonly depth: typeof depth; }>.pipe(fill: Inject): passes.Description<{
readonly depth: typeof passes.depth;
}>

Adds fill after existing fills and returns a description of the same passes. Piped fills take precedence over a drawing's own. For example, passes.create(…).pipe(view.inject()) uses the camera from view.

pipe
(
const views: cameras.LayeredCamera
views
.
LayeredCamera.inject(): Inject

Fills cameras.current with the view of the layer drawn, read through passes.layer. Pipe it into a description of targets with as many layers; a pipeline of a description drawn into another number of layers throws as it builds. In other pipelines cameras.current.$ is view 0.

inject
());
const
const sun: Float32Array<ArrayBufferLike>
sun
=
const mat4: {
add: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(a: Mat4Arg, b: Mat4Arg, dst?: T | undefined) => T;
aim: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(position: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: T | undefined) => T;
axisRotate: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(m: Mat4Arg, axis: Vec3Arg, angleInRadians: number, dst?: T | undefined) => T;
... 44 more ...;
uniformScaling: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(s: number, dst?: T | undefined) => T;
}

4x4 Matrix functions that default to returning Float32Array

@namespace

mat4
.
lookAt: <Float32Array<ArrayBufferLike>>(eye: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: Float32Array<ArrayBufferLike> | undefined) => Float32Array<ArrayBufferLike>
lookAt
([20, 40, 20], [0, 0, 0], [0, 1, 0]);
const views: cameras.LayeredCamera
views
.
LayeredCamera.write(layer: number, view: Mat4Arg, projection: Mat4Arg): void

Writes the view of layer from a view matrix and a projection matrix, as a custom camera's write does. Writes nothing when the layer's view is unchanged. Throws for a view that mirrors the world and for a layer out of range.

write
(0,
const sun: Float32Array<ArrayBufferLike>
sun
,
const mat4: {
add: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(a: Mat4Arg, b: Mat4Arg, dst?: T | undefined) => T;
aim: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(position: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: T | undefined) => T;
axisRotate: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(m: Mat4Arg, axis: Vec3Arg, angleInRadians: number, dst?: T | undefined) => T;
... 44 more ...;
uniformScaling: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(s: number, dst?: T | undefined) => T;
}

4x4 Matrix functions that default to returning Float32Array

@namespace

mat4
.
ortho: <BaseArgType>(left: number, right: number, bottom: number, top: number, near: number, far: number, dst?: BaseArgType | undefined) => BaseArgType
ortho
(-10, 10, -10, 10, 0, 200)); // near
const views: cameras.LayeredCamera
views
.
LayeredCamera.write(layer: number, view: Mat4Arg, projection: Mat4Arg): void

Writes the view of layer from a view matrix and a projection matrix, as a custom camera's write does. Writes nothing when the layer's view is unchanged. Throws for a view that mirrors the world and for a layer out of range.

write
(1,
const sun: Float32Array<ArrayBufferLike>
sun
,
const mat4: {
add: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(a: Mat4Arg, b: Mat4Arg, dst?: T | undefined) => T;
aim: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(position: Vec3Arg, target: Vec3Arg, up: Vec3Arg, dst?: T | undefined) => T;
axisRotate: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(m: Mat4Arg, axis: Vec3Arg, angleInRadians: number, dst?: T | undefined) => T;
... 44 more ...;
uniformScaling: <T extends Mat4Arg = Float32Array<ArrayBufferLike>>(s: number, dst?: T | undefined) => T;
}

4x4 Matrix functions that default to returning Float32Array

@namespace

mat4
.
ortho: <BaseArgType>(left: number, right: number, bottom: number, top: number, near: number, far: number, dst?: BaseArgType | undefined) => BaseArgType
ortho
(-40, 40, -40, 40, 0, 200)); // far
  • It keeps no last frame’s views, so code compiled with history.previously reads the current view.
  • It has no CPU project, ray or rayAt.
  • Snapping A gap under 1e-5 snaps shut in any unit. That suits radians and scenes a few units to a few hundred across.
  • Copies goal.target is an array, so a goal copied with a spread shares its target.
  • Projection lensOf, rayOf, ray and rayAt assume a projection centred on the view axis.
  • Flat rays rayOf tells a flat camera from an orbit one by the matrix’s last row, (0, 0, 0, 1) under an orthographic projection. A custom camera’s rays follow the same test.
  • Fixed struct Camera is one fixed struct with no inverse view-projection. Put other values per view in a uniform of your own, split by how often they change.
  • Other cameras A camera implementing CameraBase works with every module that reads the camera in shaders. It needs no project, ray or previous, which belong to the kit’s cameras. A fitted sun shadow’s eye needs a CpuView, which has them. Without a temporal fill, history.previously reads the same camera uniform as current-frame code, so motion vectors omit camera motion.
frameA frame is one turn of the loop, and the object your function gets for it, which holds the encoder, the time and the time since the last frame.You own the frame →
accessorAn accessor is a typed value that shader code reads and that each pipeline can fill with a different resource.Modules connect through TypeGPU →
moduleA module is one piece of GPU work, made by a factory that borrows your root and returns resources, shader functions and methods that record into your frame.A module borrows →
bindingA binding is one buffer, texture or sampler in a bind group, which a shader reads by its place there.Words →
runtimeA runtime is one JavaScript thread with its own memory, such as the page, a worker or a React Native worklet thread.Words →
texelA texel is one cell of a texture, as a pixel is one cell of the screen.Words →

Reference

kit.cameras

moduleHow to read this card

Callsborrows, never destroystakesreturns

cameras.custom(root, options?) → CustomCamera

root
the root
CustomCamera
a camera you write
takes

DepthOptions

1 field
reversed?

boolean

Projects reversed depth, 1 at the near plane and 0 at the far plane, for a description created with depthClear: 0 and depthCompare: 'greater'.Default false.

returns

CustomCamera

8 members
write(view, projection)

Writes the camera from a view matrix and a projection matrix.

uniform

TgpuUniform<Camera>

Holds the camera view from creation onwards.

inject()

Fills cameras.current for the pipelines created from the configuration it is piped into.

project(point, out)

Projects a world point to screen coordinates.

projectAt(point, out)

Projects a world point to a point of the surface, as rayAt takes it.

ray(x, y, out)

Writes the ray through the screen point x, y into out, as rayOf computes it on the GPU.

rayAt(x, y, out)

Writes the ray through a point of the surface into out, as ray does.

previous

TgpuUniform<Camera>

Holds the previous frame's view for motion vectors and reprojection.

cameras.layered(root, count) → LayeredCamera

root
the root that owns the uniform
count
the number of layers, the layers of the targets the description draws into
LayeredCamera
views you write
returns

LayeredCamera

4 members
layers

number

Reports the number of views.

uniform

TgpuUniform<d.WgslArray<Camera>>

Holds the views, one Camera per layer, zeros until written.

inject()

Fills cameras.current with the view of the layer drawn, read through passes.layer.

write(layer, view, projection)

Writes the view of layer from a view matrix and a projection matrix, as a custom camera's write does.

cameras.turn(goal, dx, dy, options?) → G

goal
an orbit camera's goal, whose yaw and pitch it writes
dx
the drag to the right, in pixels or points
dy
the drag down, in pixels or points
G
goal
takes

TurnOptions

1 field
sensitivity?

number | undefined

Sets the radians a dragged pixel or point turns.Default 0.008.

cameras.pan(goal, dx, dy, { height }) → G

goal
an orbit camera's goal, whose target it writes
dx
the drag to the right, in pixels or points
dy
the drag down, in pixels or points
G
goal
takes

PanOptions

1 field
height

number

Sets the view's height in the units of the drag, one camera distance of panning.

and cameras.eyeOf, cameras.orbit, cameras.flat, cameras.hitHeight

takes

OrbitOptions

orbit · 14 fields
size

SizeSource

Supplies the size used for the aspect ratio, such as the canvas surface.

target

[number, number, number]

Sets the initial point that the camera orbits and looks at.

distance

number

Sets the initial distance from the target to the eye, in world units.

yaw?

number

Sets the initial yaw in radians around +y.Default 0.

pitch?

number

Sets the initial pitch in radians above the horizon.Default 0.6.

fov?

number

Sets the initial vertical field of view in radians.Default 0.8.

near?

number

Sets the initial distance from the eye to the near clipping plane, in world units.Default 0.1.

far?

number

Sets the initial distance from the eye to the far clipping plane, in world units.Default 500.

pitchRange?

[number, number]

Limits the goal pitch to this range, in radians.Default -1.5 to 1.5.

distanceRange?

[number, number]

Limits the goal distance to this range, in world units.Default near * 2 to far / 2, using the option values.

floor?

(x: number, z: number) => number

Returns the lowest height the eye may reach at a point x, z, in world units, such as a terrain's height plus a margin.Default no floor.

reach?

(target: ArrayLike<number>, yaw: number, pitch: number) => number

Returns how far the eye may go from target along a yaw and pitch, such as the distance to a room's wall less a margin.Default no limit.

damping?

number

Controls how fast the view approaches the goal.Default 14.

reversed?

boolean

Projects reversed depth, 1 at the near plane and 0 at the far plane, for a description created with depthClear: 0 and depthCompare: 'greater'.Default false.

takes

FlatOptions

flat · 7 fields
size

SizeSource

Supplies the size used for the aspect ratio, such as the canvas surface or a low-resolution target.

height?

number

Sets the initial view height in world units, required without fit.Default the height fit gives.

fit?

{ width: number; height: number; mode: 'cover' | 'contain' }

Fits a width × height world rectangle centred on the view: cover fills the view with it, cropping its longer side, and contain shows all of it, leaving bands.Default none.

center?

[number, number]

Sets the initial view center in world units with +y up.Default the origin.

snap?

number

Rounds the view center to multiples of this distance in world units, such as one texel of a pixel-art target.Default 0, which disables rounding.

damping?

number

Controls how fast the view approaches the goal.Default 8.

reversed?

boolean

Projects reversed depth, 1 at the near plane and 0 at the far plane, for a description created with depthClear: 0 and depthCompare: 'greater'.Default false.

takes

HitOptions

hitHeight · 3 fields
grazing?

number

Misses rays whose direction's y is nearer 0 than this, so a ray near the horizon finds no hit far away.Default 0, which misses only rays parallel to a level plane.

reach?

number

With a height function, the farthest distance along the ray to search, including a hit exactly there.Default 1000.

step?

number

With a height function, the first step of the search along the ray.Default reach / 1000.

returns

OrbitCamera

orbit · 13 members
goal

Orbit

Sets the desired camera pose.

pose

{ yaw: number; pitch: number; distance: number; fov: number; target: [number, number, number] }

Reports the eased pose, the view as drawn while it approaches the goal.

clip

{ near: number; far: number }

Sets the distances from the eye to the clipping planes, in world units.

aspect

number

Reports the width divided by the height of the current view, from size at the last move.

update(dt)

Eases towards the goal by dt seconds and writes the uniform if the view changed.

jump()

Moves the view to the goal at once and writes the uniform if the view changed.

uniform

TgpuUniform<Camera>

Holds the camera view from creation onwards.

inject()

Fills cameras.current for the pipelines created from the configuration it is piped into.

project(point, out)

Projects a world point to screen coordinates.

projectAt(point, out)

Projects a world point to a point of the surface, as rayAt takes it.

ray(x, y, out)

Writes the ray through the screen point x, y into out, as rayOf computes it on the GPU.

rayAt(x, y, out)

Writes the ray through a point of the surface into out, as ray does.

previous

TgpuUniform<Camera>

Holds the previous frame's view for motion vectors and reprojection.

returns

FlatCamera

flat · 12 members
goal

{ x: number; y: number; height: number }

Sets the desired center in world units with +y up, and the desired view height.

pose

{ x: number; y: number; height: number }

Reports the eased center and height, the view as drawn while it approaches the goal.

aspect

number

Reports the width divided by the height of the current view, from size at the last move.

update(dt)

Eases towards the goal by dt seconds and writes the uniform if the view changed.

jump()

Moves the view to the goal at once and writes the uniform if the view changed.

uniform

TgpuUniform<Camera>

Holds the camera view from creation onwards.

inject()

Fills cameras.current for the pipelines created from the configuration it is piped into.

project(point, out)

Projects a world point to screen coordinates.

projectAt(point, out)

Projects a world point to a point of the surface, as rayAt takes it.

ray(x, y, out)

Writes the ray through the screen point x, y into out, as rayOf computes it on the GPU.

rayAt(x, y, out)

Writes the ray through a point of the surface into out, as ray does.

previous

TgpuUniform<Camera>

Holds the previous frame's view for motion vectors and reprojection.

In a frame

records

update(dt) once a frame, to ease the view towards its goal, or jump() to go there.

Holds

owns

2 buffers

The current and previous camera uniforms. Writes when the view or size changes and once more in the next frame. cameras.layered owns 1 buffer, writing a layer's view when it changes.

binds
  • 1 uniform

    cameras.current.$, the camera's matrices.

  • 1 uniform

    cameras.current.$ reads the previous matrices in code compiled with history.previously.

  • 1 uniform

    cameras.layered, every layer's view, beside the layer its description binds.

Connects to

injects
  • hook

    cameras.current, for every shader that projects, and cameras.reversed from a camera created with reversed: true.

Exports

GPU functions
toClip farDepth nearerDepth forwardOf lensOf distanceOf rayOf towards sees
accessors
current reversed
schemas
Camera Ray
types
Out3 CpuRay CpuView CameraBase Orbit
schema

Camera

4 fields
viewProjection

d.mat4x4f

Transforms world coordinates to clip space.

position

d.vec3f

Gives the eye position in world space.

right

d.vec3f

Gives the unit x and y axes of the view in world space, for quads that face the screen.

up

d.vec3f

schema

Ray

2 fields
origin

d.vec3f

direction

d.vec3f

Gives the unit ray direction.

used byAfterimageBenthosBlockfallCenserClassroomCloisterDomino runEmber mirrorFalling sandFireworksFish tankForestHex isleJelliesJelly worldKineticLatticeNight marketOceanPlatformerQuiver treesRaymarchRobot armSkeletonsSolar systemSPH sculptSpiderStampedeStar mapSurvey modelevery example page