Skip to content

Concept2 of 5

Modules

The contract every TypeGPU Kit module follows, and how to write one.

Read firstHow the kit works, for the frame and the seven rules every module follows

On this page

Every has a , create(root, options), that allocates resources and returns them with shader functions and recording methods. How the kit works introduces the rules modules follow. This page covers the details you rely on when using or writing one.

GPU resources across the flow field's lifetime

Follow resources from creation to teardown. Frames after the first allocate nothing, destroy() frees the particle buffer, and the borrowed surface remains. Scroll the figure sideways to see the later steps.
  • initAsync() compiles every pipeline. It is optional. Without it, each pipeline compiles when it is first used, which stalls that and is slow on WebKit.
  • A few setup calls submit on their own, such as meshPool.add(shape) and meshes.bake given nothing to record into. Their cards mark them submits setup. Call them while loading, or hand them the frame’s encoder.
  • A handle has destroy() when its module made textures, non-uniform buffers, query sets or other modules. It frees those and nothing the module borrowed. Uniforms, , , layouts and pipelines are left to the garbage collector. [Symbol.dispose], where present, is the same function.
  • The card’s owns lists what a module allocates, and lifecycle shows whether it has destroy(). built by a has its own drawn.destroy().
  • Stop using a module before you destroy it, and call destroy() once.

Compile the pipelines before the first frame with an explicit list for pipelines.compile, and free what the scene made in its destroy:

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, 0.4, 0],
OrbitOptions.distance: number

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

distance
: 5 });
const
const canvas: passes.Description<{
readonly color: typeof passes.color;
}>
canvas
=
import passes
passes
.
function create(root: TgpuRoot, screen: passes.Screen, options?: passes.Options): passes.Description<{
readonly color: typeof passes.color;
}> (+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 surface: web.Surface
surface
).
Description<{ readonly color: typeof color; }>.pipe(fill: Inject): passes.Description<{
readonly color: typeof passes.color;
}>

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 view: cameras.OrbitCamera
view
.
CameraBase.inject(): Inject

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

inject
());
const
const time: TgpuUniform<d.F32>
time
=
const root: TgpuRoot
root
.
TgpuRoot.createUniform<d.F32>(typeSchema: d.F32, initial?: number | ((buffer: TgpuBuffer<NoInfer<d.F32>>) => void) | undefined): TgpuUniform<d.F32> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader. Read-only on the GPU, optimized for small 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)

createUniform
(
import d
d
.
const f32: d.F32
export f32

A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)

Can also be called to cast a value to an f32.

@example const value = f32(); // 0

@example const value = f32(1.23); // 1.23

@example const value = f32(true); // 1

f32
);
const
const sparks: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
sparks
=
import particles
particles
.
function create(root: TgpuRoot, camera: cameras.CameraBase, options: particles.Options & {
readonly particle?: typeof particles.Particle;
}): particles.Particles (+1 overload)

Creates a GPU particle pool. CPU bursts and kernel emit calls allocate ring slots. Fixed steps move particles, and live lists list only live particles for drawing.

@injects ― member emit and the pool, which read its own buffers in any pipeline

@binds ― 2 storage: emit, the pool and its ring counter

@binds ― 1 storage: alive or particle, the pool

@binds ― 1 storage, 1 uniform: drawnAt, the pool and the last compact's ahead

@owns ― 6 buffers, 2 pipelines, liveLists: the pool, its ring counter, the burst queue and three uniforms; the live lists list the live particles. Each description drawing is added to builds its pipeline.

@records ― spawn once a submission before compact, step once per fixed step, compact once after the steps, then the draw a description added drawing as; clear whenever you like.

@param ― camera the camera the quads face unless place says otherwise; the callbacks read it too

@param ― options.update a 'use gpu' function; it and the other callbacks carry the fills of what they read beside the camera, such as tgpu.fn(rise).pipe(noise.inject())

@returns ― a system you destroy

create
(
const root: TgpuRoot
root
,
const view: cameras.OrbitCamera
view
, {
Options<S extends Schema = WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.capacity: number

Limits the number of particles alive at once. Each emitted particle takes the next ring slot.

capacity
: 2048,
Options<S extends Schema = WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.step: number

Sets the length of a step in seconds, such as a fixed-step clock's sim.step. Each step advances by it.

step
:
const sim: clock.FixedStep
sim
.
FixedStep.step: number

Sets the step duration in seconds. A new value applies from the next update: unstepped time carries over, capped at maxSteps new steps, and time keeps the seconds already stepped. Particles and machines take its value when created and keep it. Throws unless the value is finite and above 0.

step
,
Options<S extends Schema = WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.blend?: "add" | "over" | "translucent" | GPUBlendState | undefined

Selects add for sparks and glow, over for dust, translucent for the passes' translucency targets, or a custom blend state. Default add.

blend
: 'add' });
const
const drawn: passes.Drawn[]
drawn
= [
const canvas: passes.Description<{
readonly color: typeof passes.color;
}>
canvas
.
Into<{ readonly color: typeof color; }>.add<d.WgslStruct<{
position: d.Vec4f;
world: d.Vec3f;
local: d.Vec2f;
slot: d.U32;
}>, {
world: d.v3f;
color: d.v4f;
}>(drawing: passes.Drawing<d.WgslStruct<{
position: d.Vec4f;
world: d.Vec3f;
local: d.Vec2f;
slot: d.U32;
}>, {
world: d.v3f;
color: d.v4f;
}>): passes.Drawn (+1 overload)

Builds a pipeline for drawing that writes every described output and returns its draw methods. If the drawing cannot supply the fields an output reads, type checking fails with that target's name and those fields. Use without to leave it out or instead to replace it.

add
(
const sparks: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
sparks
.
System.drawing: passes.Drawing<d.WgslStruct<{
position: d.Vec4f;
world: d.Vec3f;
local: d.Vec2f;
slot: d.U32;
}>, {
world: d.v3f;
color: d.v4f;
}>

Provides the particle drawing for pass descriptions, as in scene.add(system.drawing). It supplies colour, world position and corner data to outputs, tests depth without writing it and draws the list from the last compact. The description initAsync also compiles system kernels.

drawing
)];
await
import pipelines
pipelines
.
function compile(from: readonly pipelines.Warmable[] | Owner, options?: pipelines.CompileOptions): Promise<void>

Starts compiling every item the list holds at the call, yielding to the event loop past the time budget so the page's other work, such as a loading animation, keeps running. Use before the frame loop starts. Waits for every item to finish, then rejects if any failed.

@param ― from a list of pipelines and modules that compile their own, or an owner that took them

@returns ― a promise that resolves once every item has compiled

compile
([
const canvas: passes.Description<{
readonly color: typeof passes.color;
}>
canvas
]);
const
const scene: {
view: cameras.OrbitCamera;
frame(frame: Frame): void;
destroy(): void;
}
scene
= {
view: cameras.OrbitCamera
view
,
function frame(frame: Frame): void
frame
(
frame: Frame
frame
:
(alias) interface Frame
import Frame

Represents one frame being recorded. Each run creates a separate object, so modules can compare frames by identity.

Frame
) {
const time: TgpuUniform<d.F32>
time
.
TgpuBufferBindingBase<F32>.write(data: number, options?: BufferWriteOptions): void
write
(
frame: Frame
frame
.
Frame.time: number

Reports seconds since the first submitted frame.

time
);
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: Frame
frame
.
Frame.dt: number

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

dt
);
const canvas: passes.Description<{
readonly color: typeof passes.color;
}>
canvas
.
Description<{ readonly color: typeof color; }>.record(frame: Frame | TgpuCommandEncoder, drawn: passes.Drawn | readonly passes.Drawn[], options?: passes.BeginOptions<{
readonly color: typeof passes.color;
}> | undefined): void

Begins a pass, draws drawn or each drawing in a list in order, then ends the pass. Reuse the list to avoid allocating each frame. Call begin yourself when you need to choose drawings per frame. Records nothing while enabled is false.

record
(
frame: Frame
frame
,
const drawn: passes.Drawn[]
drawn
);
},
function destroy(): void
destroy
() {
const sparks: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
sparks
.
System.destroy(): void

Destroys the pool, its counter, the burst queue and the live lists.

destroy
();
},
};
  • With several things to free, loop over a list: for (const made of [screen, sparks, glow]) made.destroy().
  • sparks.destroy() frees the particles’ resources. The description holds nothing that needs freeing here, so the scene leaves it out. A description whose drawings build resources of their own frees them in its destroy().
  • When a resize replaces a texture or buffer, free the old one at that moment. Free the current one in destroy.
  • Leave out what the scene borrows: the root, the surface and the ’s resources.

A method takes the smallest piece of the frame it needs, so the call site shows the pass structure.

Method Takes When
step(pass) TgpuComputePass compute , in a pass you share between modules
draw(pass) TgpuRenderCommands draws into your attachments, or into a render bundle you replay
record(frame) Frame or TgpuCommandEncoder passes or copies of its own, such as a shadow map, a post chain or a ’s flush
capture(frame) Frame work after the submit too, through frame.afterSubmit
update(dt) numbers maths on the CPU over time, such as a camera easing towards its goal

A method that records passes or copies of its own takes either the frame or its encoder, so a frame’s code passes frame to each. A description that draws into a surface takes only the frame, which holds view.

const compute = frame.encoder.beginComputePass();
particles.step(compute);
wind.step(compute);
compute.end();
light.shadow.record(frame, casters); // opens and ends its own depth pass
const pass = scene.begin(frame);
terrain.draw(pass); // what scene.add(drawing) built
embers.draw(pass);
pass.end();
  • A returns a drawing. A description of passes builds it with scene.add(drawing), which returns a handle with draw(pass).
  • step runs one and can run several times in a pass. Compute work that runs once per frame has a specific name, such as ’ compact or the particles’ spawn.

Bind a pipeline’s groups at setup, then set it on the pass and draw through the pass. Each .with(...) returns a new object. If the pipeline object changes from one draw to the next, the pass sets the pipeline, groups and buffers again:

pipeline.with(group).with(pass).draw(3); // in the frame: a new object and all state on every draw
const bound = pipeline.with(group); // at setup
pass.setPipeline(bound); // in the frame
pass.draw(3); // a later draw with the same pipeline sets nothing
  • A pass.setBindGroup or setVertexBuffer between draws makes the next draw set everything again.
  • A group that follows a replaced texture comes from memo. The pipeline bound to that group can come from memo too, as finish’s does.
  • A module sets only its pipeline on the caller’s pass. It makes no other state changes such as pass.setBindGroup there, because later draws would inherit them. Your frame code can make those changes.

draw takes a render pass or a render bundle encoder. pass.executeBundles([bundle]) replays the recorded draws in one call, which saves per-draw JS work on Hermes:

const bundler = root['~unstable'].createRenderBundleEncoder({
colorFormats: [format],
depthStencilFormat: 'depth24plus',
});
terrain.draw(bundler);
props.draw(bundler);
const bundle = bundler.finish();
// each frame
pass.executeBundles([bundle]);
embers.draw(pass);
  • A bundle replays fixed draw calls while buffer contents can change. Record it again when the draw calls or resources change. need this when a mesh without instances gains one, or when a mesh’s textures arrive. Finish needs it when bloom replaces its output.
  • A method that sets a viewport or a scissor can’t go in a bundle. It takes a pass, or it takes the frame and opens its own passes, as bloom’s record does.

This module damps a buffer of velocities. Its rate is a setting; its step length is fixed at creation:

import {
import d
d
,
import std
std
,
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
, type
(alias) interface TgpuComputePass
import TgpuComputePass

A compute pass recording into a

TgpuCommandEncoder

.

Dispatch either by binding TypeGPU pipelines to it (pipeline.with(pass).dispatchWorkgroups(...)), or proxy-style via pass.setPipeline(pipeline) followed by pass.dispatchWorkgroups(...).

Call end() when done recording.

TgpuComputePass
, type
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
} from 'typegpu';
const
const DampingSettings: d.WgslStruct<{
rate: d.F32;
}>
DampingSettings
=
import d
d
.
struct<{
rate: d.F32;
}>(props: {
rate: d.F32;
}): d.WgslStruct<{
rate: d.F32;
}>
export struct

Creates a struct schema that can be used to construct GPU buffers. Ensures proper alignment and padding of properties (as opposed to a d.unstruct schema). The order of members matches the passed in properties object.

@example const CircleStruct = d.struct({ radius: d.f32, pos: d.vec3f });

@param ― props Record with string keys and TgpuData values, each entry describing one struct member.

struct
({
rate: d.F32
rate
:
import d
d
.
const f32: d.F32
export f32

A schema that represents a 32-bit float value. (equivalent to f32 in WGSL)

Can also be called to cast a value to an f32.

@example const value = f32(); // 0

@example const value = f32(1.23); // 1.23

@example const value = f32(true); // 1

f32
}); // no root needed
interface
interface DampingOptions
DampingOptions
{
readonly
DampingOptions.count: number
count
: number;
/** Seconds per `step`. */
readonly
DampingOptions.step: number

Seconds per step.

step
: number;
}
export function
function createDamping(root: TgpuRoot, options: DampingOptions): {
settings: TgpuUniform<d.WgslStruct<{
rate: d.F32;
}>>;
velocities: TgpuMutable<d.WgslArray<d.Vec2f>>;
initAsync: () => Promise<void>;
step(pass: TgpuComputePass): void;
destroy: () => void;
[Symbol.dispose]: () => void;
}
createDamping
(
root: TgpuRoot
root
:
(alias) interface TgpuRoot
import TgpuRoot
TgpuRoot
,
options: DampingOptions
options
:
interface DampingOptions
DampingOptions
) {
const {
const count: number
count
,
const step: number

Seconds per step.

step
} =
options: DampingOptions
options
;
const
const settings: TgpuUniform<d.WgslStruct<{
rate: d.F32;
}>>
settings
=
root: TgpuRoot
root
.
TgpuRoot.createUniform<d.WgslStruct<{
rate: d.F32;
}>>(typeSchema: d.WgslStruct<{
rate: d.F32;
}>, initial?: ((buffer: TgpuBuffer<NoInfer<d.WgslStruct<{
rate: d.F32;
}>>>) => void) | d.InferInput<NoInfer<d.WgslStruct<{
rate: d.F32;
}>>> | undefined): TgpuUniform<d.WgslStruct<{
rate: d.F32;
}>> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader. Read-only on the GPU, optimized for small 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)

createUniform
(
const DampingSettings: d.WgslStruct<{
rate: d.F32;
}>
DampingSettings
, {
rate: number
rate
: 2 });
const
const velocities: TgpuMutable<d.WgslArray<d.Vec2f>>
velocities
=
root: TgpuRoot
root
.
TgpuRoot.createMutable<d.WgslArray<d.Vec2f>>(typeSchema: d.WgslArray<d.Vec2f>, initial?: ((buffer: TgpuBuffer<NoInfer<d.WgslArray<d.Vec2f>>>) => void) | d.InferInput<NoInfer<d.WgslArray<d.Vec2f>>> | undefined): TgpuMutable<d.WgslArray<d.Vec2f>> (+1 overload)

Allocates memory on the GPU, allows passing data between host and shader. Can be mutated in-place on the GPU. 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)

createMutable
(
import d
d
.
arrayOf<d.Vec2f>(elementType: d.Vec2f, elementCount: number): d.WgslArray<d.Vec2f> (+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 vec2f: d.Vec2f
vec2f
,
const count: number
count
));
const
const kernel: TgpuComputeFn<{
gid: d.BuiltinGlobalInvocationId;
}>
kernel
=
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
.
computeFn: <{
gid: d.BuiltinGlobalInvocationId;
}>(options: {
in: {
gid: d.BuiltinGlobalInvocationId;
};
workgroupSize: number[];
}) => TgpuComputeFnShell<{
gid: d.BuiltinGlobalInvocationId;
}> (+1 overload)
computeFn
({
workgroupSize: number[]
workgroupSize
: [64],
in: {
gid: d.BuiltinGlobalInvocationId;
}
in
: {
gid: d.BuiltinGlobalInvocationId
gid
:
import d
d
.
const builtin: {
readonly vertexIndex: d.BuiltinVertexIndex;
readonly instanceIndex: d.BuiltinInstanceIndex;
readonly clipDistances: d.BuiltinClipDistances;
readonly position: d.BuiltinPosition;
readonly frontFacing: d.BuiltinFrontFacing;
readonly fragDepth: d.BuiltinFragDepth;
readonly primitiveIndex: d.BuiltinPrimitiveIndex;
readonly sampleIndex: d.BuiltinSampleIndex;
... 11 more ...;
readonly numSubgroups: d.BuiltinNumSubgroups;
}
export builtin
builtin
.
globalInvocationId: d.BuiltinGlobalInvocationId
globalInvocationId
},
})(({
gid: d.v3u
gid
}) => {
'use gpu';
if (
gid: d.v3u
gid
.
v3u.x: number
x
>=
const count: number
count
) return;
const
const decay: number
decay
=
import std
std
.
function exp(value: number): number (+1 overload)
export exp
exp
(-
const settings: TgpuUniform<d.WgslStruct<{
rate: d.F32;
}>>
settings
.
TgpuUniform<WgslStruct<{ rate: F32; }>>.$: {
rate: number;
}
$
.
rate: number
rate
*
const step: number

Seconds per step.

step
);
const velocities: TgpuMutable<d.WgslArray<d.Vec2f>>
velocities
.
TgpuMutable<WgslArray<Vec2f>>.$: d.v2f[]
$
[
gid: d.v3u
gid
.
v3u.x: number
x
] *=
const decay: number
decay
;
});
const
const pipeline: TgpuComputePipeline
pipeline
=
root: TgpuRoot
root
.
WithBinding.createComputePipeline<{
gid: d.BuiltinGlobalInvocationId;
}>(descriptor: TgpuComputePipeline.Descriptor<{
gid: d.BuiltinGlobalInvocationId;
}>): TgpuComputePipeline
createComputePipeline
({
compute: TgpuComputeFn<{
gid: d.BuiltinGlobalInvocationId;
}>
compute
:
const kernel: TgpuComputeFn<{
gid: d.BuiltinGlobalInvocationId;
}>
kernel
});
const
const destroy: () => void
destroy
= () => {
const velocities: TgpuMutable<d.WgslArray<d.Vec2f>>
velocities
.
TgpuMutable<WgslArray<Vec2f>>.buffer: TgpuBuffer<d.WgslArray<d.Vec2f>> & StorageFlag
buffer
.
TgpuBuffer<WgslArray<Vec2f>>.destroy(): void
destroy
();
};
return {
settings: TgpuUniform<d.WgslStruct<{
rate: d.F32;
}>>
settings
,
velocities: TgpuMutable<d.WgslArray<d.Vec2f>>
velocities
,
initAsync: () => Promise<void>
initAsync
: () =>
const pipeline: TgpuComputePipeline
pipeline
.
TgpuComputePipeline.initAsync(): Promise<void>

Immediately resolves the pipeline, then awaits device.createComputePipelineAsync(). NOTE: it is not necessary to initialize pipelines manually.

initAsync
(),
function step(pass: TgpuComputePass): void
step
(
pass: TgpuComputePass
pass
:
(alias) interface TgpuComputePass
import TgpuComputePass

A compute pass recording into a

TgpuCommandEncoder

.

Dispatch either by binding TypeGPU pipelines to it (pipeline.with(pass).dispatchWorkgroups(...)), or proxy-style via pass.setPipeline(pipeline) followed by pass.dispatchWorkgroups(...).

Call end() when done recording.

TgpuComputePass
) {
pass: TgpuComputePass
pass
.
TgpuComputePass.setPipeline(pipeline: TgpuComputePipeline): void

Sets the current

TgpuComputePipeline

for subsequent dispatches

setPipeline
(
const pipeline: TgpuComputePipeline
pipeline
);
pass: TgpuComputePass
pass
.
TgpuComputePass.dispatchWorkgroups(x: number, y?: number, z?: number): void
dispatchWorkgroups
(
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.ceil(x: number): number

Returns the smallest integer greater than or equal to its numeric argument.

@param ― x A numeric expression.

ceil
(
const count: number
count
/ 64));
},
destroy: () => void
destroy
,
[
var Symbol: SymbolConstructor
Symbol
.
SymbolConstructor.dispose: typeof Symbol.dispose

A method that is used to release resources held by an object. Called by the semantics of the using statement.

dispose
]:
const destroy: () => void
destroy
,
};
}
export type
type Damping = {
settings: TgpuUniform<d.WgslStruct<{
rate: d.F32;
}>>;
velocities: TgpuMutable<d.WgslArray<d.Vec2f>>;
initAsync: () => Promise<void>;
step(pass: TgpuComputePass): void;
destroy: () => void;
[Symbol.dispose]: () => void;
}
Damping
=
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any

Obtain the return type of a function type

ReturnType
<typeof
function createDamping(root: TgpuRoot, options: DampingOptions): {
settings: TgpuUniform<d.WgslStruct<{
rate: d.F32;
}>>;
velocities: TgpuMutable<d.WgslArray<d.Vec2f>>;
initAsync: () => Promise<void>;
step(pass: TgpuComputePass): void;
destroy: () => void;
[Symbol.dispose]: () => void;
}
createDamping
>;
  • Schemas and shader functions that capture no instance’s resources live at module scope.
  • destroy frees the velocity buffer.
  • Validation and allocation happen in the factory; recording methods only record.
  • Some factories infer the type of their options literal, as targets.create infers its specs. Such a factory types its options parameter Checked<O, Options>. A misspelt option then reports one error at its key, naming the option, as in 'smapled is not an option here'. What the factory returns keeps its type.
  • A test builds it on recordingRoot and checks what it records.
  • d.struct rejects WGSL’s reserved words as field names, such as type and target.
  • unplugin-typegpu doesn’t transform a 'use gpu' object shorthand method, { alive(i) { 'use gpu'; … } }. Write it as a property: alive: (i) => { 'use gpu'; … }.
  • Shift a u32 right with >>>: d.u32(0x32) >>> corner. TypeGPU warns about >> on a u32, and a bare literal on the left of a shift is an i32.
  • Code that runs on React Native follows the platform rules, such as copying an array before sorting it.
Error Cause
Missing value for 'slot:wind' a pipeline reads a nothing filled; pipe the inject() that fills it into the pipeline’s root
The pipeline is missing a fill for `cameras.current`. … the same, for an whose default is unfilled; it names the inject()
A pipeline reads the shared part 'ao', … a description builds a pipeline that reads a part it wasn’t given; it names the shared to add
Missing bind groups for layouts a pipeline reads a shared layout, and a pass you opened has no group set for it
readonly buffers cannot be mutated a render pipeline writes a buffer it binds read-only, such as a table’s device
bindGroupLayoutCount (5) is larger than the maximum allowed (4) the pipeline uses more bind groups than the device allows; a census counts them
Found duplicate TypeGPU version two copies of TypeGPU loaded; see Setting up a project

Write a module builds a module step by step, from its first to its test.

If your program makes many resources, you can collect them with the optional owner helper and free them with one call:

const
const own: Owner
own
=
function owner(message?: string): Owner

Collects what a scene or module makes, to compile and free it all in one call each. Pass each thing through it as you make it, pipelines and pass descriptions too, and return its destroy as your own. Take a resource that is replaced during the module's life, such as a texture that follows the canvas size, as one cleanup that frees the current one. What it takes after destroy, such as a model that finished loading late, it frees at once.

const own = owner('The swarm was destroyed.');
const screen = own(targets.create(root, surface, { hdr }));
const settings = own(root.createUniform(Settings));
const kernel = own(root.createComputePipeline({ compute: step }));
own(() => {
for (const buffer of reads) buffer.destroy();
});
return {
initAsync: () => pipelines.compile(own),
step(pass) { own.usable(); … },
destroy: own.destroy,
[Symbol.dispose]: own.destroy,
};

@param ― message what usable throws, naming the module: "The table was destroyed."

@returns ― an owner you pass each thing to and destroy

owner
();
const
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
=
const own: Owner
<targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>>(item: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>) => targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>

Takes item to free at destroy and returns it. Passes undefined through. Frees a fixed resource, such as one from root.createUniform, through its buffer, and runs a cleanup function. Lists an item with initAsync in warmables. After destroy, frees item at once.

own
(
import targets
targets
.
function create<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>(root: TgpuRoot, source: targets.SizeSource, specs: {
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}, options?: targets.Options): targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>

Creates render targets that follow a size. Replaces the whole set when the size changes. Put targets needed only sometimes in their own set and create that set when needed. Throws for transient targets with sampling, storage or mip levels, for multisampled targets with storage or mip levels, and for layered targets that are multisampled, mipped or have more layers than the device allows.

@param ― source the size it follows, such as a surface

@param ― specs a format and options per target, by name

@param ― options.resolution the fraction of each side drawn, which changes without allocating

@returns ― a set of targets you fit every frame and destroy

create
(
const root: TgpuRoot
root
,
const surface: web.Surface
surface
, {
hdr: {
readonly format: "rgba16float";
readonly sampled: true;
}
hdr
: {
format: "rgba16float"
format
: 'rgba16float',
sampled: true
sampled
: true } }),
);
const
const glow: bloom.Bloom
glow
=
const own: Owner
<bloom.Bloom>(item: bloom.Bloom) => bloom.Bloom

Takes item to free at destroy and returns it. Passes undefined through. Frees a fixed resource, such as one from root.createUniform, through its buffer, and runs a cleanup function. Lists an item with initAsync in warmables. After destroy, frees item at once.

own
(
import bloom
bloom
.
function create(root: TgpuRoot, options: bloom.Options): bloom.Bloom

Creates bloom from a chain of half-size textures. Each level downsamples with 13 taps, then a tent filter adds it to the next larger level. The result is mip 0 of output, at half the source size. With region, passes draw and sample only that region; changing the region allocates nothing.

@allocates ― on resize: a new chain and the bind groups of its passes; so does a new source

@owns ― targets, a sampler, 3 pipelines, 2 bind groups and a buffer per level: the chain of glow levels, the settings, a group for each pass, and the region each pass reads

@records ― record after whatever wrote the source; then output holds the glow.

@param ― options.source the HDR picture, read at every record

@param ― options.region the part of the source that holds the picture, read at every record

@returns ― a bloom you record every frame and destroy

create
(
const root: TgpuRoot
root
, {
Options.source: Source

Provides the HDR picture: a rendered picture, such as aa, or a function returning a texture, such as () => screen.textures.hdr. record reads it on every call, so the texture can be rebuilt.

@cpu

source
: () =>
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
readonly sampled: true;
};
}>>
screen
.
Targets<Specs<{ readonly hdr: { readonly format: "rgba16float"; readonly sampled: true; }; }>>.textures: {
readonly hdr: targets.Target<{
readonly format: "rgba16float";
readonly sampled: true;
}>;
}

Provides the current textures. A size change replaces them.

textures
.
hdr: targets.Target<{
readonly format: "rgba16float";
readonly sampled: true;
}>
hdr
}));
await
import pipelines
pipelines
.
function compile(from: readonly pipelines.Warmable[] | Owner, options?: pipelines.CompileOptions): Promise<void>

Starts compiling every item the list holds at the call, yielding to the event loop past the time budget so the page's other work, such as a loading animation, keeps running. Use before the frame loop starts. Waits for every item to finish, then rejects if any failed.

@param ― from a list of pipelines and modules that compile their own, or an owner that took them

@returns ― a promise that resolves once every item has compiled

compile
(
const own: Owner
own
);
// when the program closes
const own: Owner
own
.
Owner.destroy(): void

Frees everything it took, the last taken first, once; later calls do nothing. When one throws, frees the rest, then throws its error, or an AggregateError of all of them with the first one's message. Also [Symbol.dispose].

destroy
();

own(item) returns the item. own.destroy() frees the last item taken first. An item taken after own.destroy() is freed at once. If async work can finish after destroy(), call own.usable() after the await and before using the resources. It throws if the owner has been destroyed. The reference card lists the helper’s .

A package exports each module as a namespace. The module’s file calls its factory create and its options Options, and the package entry re-exports the file:

index.ts
// damping.ts: export function create(…), export interface Options, export type Damping
export * as damping from './damping.ts';
export type { Damping } from './damping.ts';

Call damping.create(root, options) and name the result for what it holds, as in const drag = damping.create(...). frames.create and bloom.create follow the same convention. A module in your own program can stay a plain createDamping.

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 →
factoryA factory is the function that creates a module, which allocates what the module needs and returns its resources, functions and recording methods.A module borrows →
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 →
samplerA sampler tells the GPU how to read a texture between its texels and past its edges, such as smoothly or in blocks.Words →
bind groupA bind group is a set of buffers, textures and samplers that a pipeline reads, and a pipeline has room for four.Words →
drawingA drawing is what a renderer hands to a pass description: what each vertex carries to its pixels, what a pixel looks like and the draw call.Every renderer is a drawing →
pass descriptionA pass description says once which textures a pass draws into and what each holds, and builds the pipeline for every drawing added to it.Scenes and passes →
hostA host runs a scene for you, which means it makes the device, the surface and the frame loop and frees them in order.Hosting scenes →
dispatchA dispatch runs a kernel once over a number of threads, inside a compute pass.Words →
tableA table is a buffer of rows with named fields, some written by the CPU and the others by kernels.Rows →
surfaceA surface is a canvas set up for your root, which keeps its drawing buffer the size the page shows it at.Surfaces →
rendererA renderer draws one sort of thing, such as instances or particles, by handing a pass description a drawing.Every renderer is a drawing →
fixed stepA fixed step advances a simulation by one set length of time, and each frame runs a whole number of them, so the result is the same at any frame rate.A fixed step →
live listA live list is a list of the live rows of one group, made on the GPU each frame so that a draw covers only them.Only what is alive →
instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
placeholderA placeholder is an accessor with no resource of its own, which each pipeline fills through the inject() of the module it reads.Members and placeholders →
accessorAn accessor is a typed value that shader code reads and that each pipeline can fill with a different resource.Modules connect through TypeGPU →
rowA row is one object's values in a buffer, such as one enemy, one particle or one light.Objects are rows in buffers →
kernelA kernel is a compute function that the GPU runs many times at once, each run on its own thread.A frame in plain TypeGPU →
memberA member is a function or accessor on what a factory returns that reads that instance's own resources, so a pipeline that uses it needs no fill.Members and placeholders →