TAA needs motion vectors and a pick of your own needs ids at each pixel. Every must write these alongside colour. Implementing separately in every renderer duplicates shader code. Renderers that lack an output’s data, such as particles without ids, also need a rule for what that target gets.
latticeThin beams and rising embers, smoothed over time with TAA.
The sky, beams and embers share one for colour, TAA motion and depth. The description
runs taa.motion for each drawing. Grey means still, colour means motion and black means no
motion output. Drag horizontally to turn the camera. Put the embers in scene.without('motion')
to keep the motion beneath them. Only the beams appear in depth, because the sky and embers test
depth without writing it.
passes.create defines what each target holds. A renderer supplies a drawing, which holds a vertex function, a draw call and a pixelOf function. pixelOf gives the renderer’s data at each pixel, such as colour or id. scene.add(drawing) builds a pipeline that computes every output from that data. scene.record(frame, drawn) draws it into the .
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
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(
constroot:TgpuRoot
root,
constscreen:targets.Targets<Specs<{
readonly hdr:{
readonly format:"rgba16float";
readonly sampled:true;
};
readonly motion:{
readonly format:"rg16float";
readonly sampled:true;
};
readonly depth:{
readonly format:"depth24plus";
readonly sampled:true;
};
}>>
screen,{
hdr:typeofpasses.color
hdr:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
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(
constview:cameras.OrbitCamera
view.
CameraBase.inject(): Inject
Fills cameras.current for the pipelines created from the configuration it is piped into.
inject());
// What each vertex carries to its pixels, and what the renderer knows at a pixel
const
constCorner:d.WgslStruct<{
position:d.Vec4f;
world:d.Vec3f;
}>
Corner=
import d
d.
struct<{
position:d.Vec4f;
world:d.Vec3f;
}>(props:{
position:d.Vec4f;
world:d.Vec3f;
}):d.WgslStruct<{
position:d.Vec4f;
world:d.Vec3f;
}>
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.
@param ― props Record with string keys and TgpuData values,
each entry describing one struct member.
struct({
position:d.Vec4f
position:
import d
d.
constvec4f:d.Vec4f
vec4f,
world:d.Vec3f
world:
import d
d.
constvec3f:d.Vec3f
vec3f});
const
constSeen:d.WgslStruct<{
color:d.Vec4f;
}>
Seen=
import d
d.
struct<{
color:d.Vec4f;
}>(props:{
color:d.Vec4f;
}):d.WgslStruct<{
color:d.Vec4f;
}>
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.
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.
@exampleconst value = f32(); // 0
@exampleconst value = f32(1.23); // 1.23
@exampleconst value = f32(true); // 1
f32(
instanceIndex: number
instanceIndex)*3,0,0);
return
constCorner:d.WgslStruct
(props?:{
position:d.v4f;
world: d.v3f;
}|undefined)=>{
position:d.v4f;
world:d.v3f;
}
Corner({
position:d.v4f
position:
import cameras
cameras.
consttoClip:(point:d.v3f)=>d.v4f
Returns a world point in clip space, as a vertex shader's position. It reads cameras.current;
code that projects with a view of its own multiplies by that view's viewProjection.
toClip(
constworld:d.v3f
world),
world:d.v3f
world});
};
const
constpixelOf:(corner:d.Infer<typeof Corner>)=>{
color:d.v4f;
}
pixelOf=(
corner:{
position:d.v4f;
world:d.v3f;
}
corner:
import d
d.
typeInfer<T>=Textends{
readonly[$repr]:inferTRepr;
}?TRepr:T
export Infer
Extracts the inferred representation of a resource.
For inferring types as seen by the GPU, see
InferGPU
@exampletype A = Infer // => number
type B = Infer<WgslArray> // => number[]
type C = Infer<Atomic> // => number
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.
Computes data at a pixel from the interpolated vertex. position is the pixel position.
Required for descriptions that write colour or outputs, and for depthOf and sampleMask.
Records a draw into the pass, on which the description has set the pipeline it built. That
pipeline binds indices if supplied. drawIndexed throws without an index buffer. A group
the drawing sets with pass.setBindGroup stays for later drawings in the pass that read its
layout, so give such a layout to one drawing.
Runs the loop on each scheduled frame. Time advances by at most maxDt per frame, never steps
back, and stops while the surface is paused. Destroying the animation keeps the loop alive.
Another animation on the same loop continues from its recorded time. A frame error, or a run
that returns false because the loop was destroyed, stops the animation.
@param ― loop the loop to run on each unpaused frame. Continues from its seconds if it ran before
@returns ― an animation you destroy to stop the frames
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:frames.Frame
frame,
consttriangles:passes.Drawn
triangles)));
passes.create(root, surface) draws each renderer’s colour into the canvas without extra targets or outputs.
passes.create takes a target set or a surface. A surface is { format, view(frame), width, height }, with an optional pixelRatio. The surface form is for textures created outside the kit, such as a canvas. A texture you create to draw into and sample elsewhere, such as a label, a decal or a mirror, is a target set. targets.create takes any { width, height } and sizes a fixed set once, when it is created:
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
Creates labels drawn from a baked MSDF font atlas. The CPU lays out each string, and instanced
glyph quads place it in world or screen space. Throws unless capacity and length are
integers of at least 1.
@injects ― member move, setLabel, setQuad, quadAt and erase, which write its own
buffers in any pipeline
@owns ― 2 buffers, a sampler: the quads and the labels
@binds ― 3 storage, 1 uniform: the drawing, the quads, the labels and the font's glyphs, and
passes.viewport with text.screen or text.pinned
@binds ― 1 storage: move or setLabel, the labels
@binds ― 1 storage: setQuad, quadAt or erase, the quads
@records ― drawing, added to passes, after the passes that move the labels.
@param ― font the font it draws with, which it borrows
@param ― options.place a 'use gpu' function; it and shade carry the fills of what they read
beside the camera, such as tgpu.fn(lifted).pipe(scene.inject())
@returns ― a set of labels you destroy before its font
create(
constroot:TgpuRoot
root,
constfont:Font
font,{
Options.capacity: number
Sets the number of labels to an integer of at least 1.
capacity:1,
Options.length: number
Limits glyphs drawn per label to an integer of at least 1. Spaces use no glyph slot; glyphs
beyond the limit are omitted.
length:3,
Options.place?:text.Place|undefined
Places glyph corners with facing, ground, pinned, screen or a custom function. Default
facing.
@gpu
place:
import text
text.
constscreen:(position:v3f,offset:v2f)=>v4f
Places text on screen with position in pixels from the top-left of the region the pass draws.
em uses points, the pass's passes.viewport pixels per point, to preserve label size across
pixel densities.
screen});
const
constpaint:passes.Description<{
readonly ink:typeofpasses.color;
}>
paint=
import passes
passes.
functioncreate<Specs<{
readonly ink:{
readonly format:"rgba8unorm";
readonly sampled:true;
};
}>,{
readonly ink:typeofpasses.color;
}>(root:TgpuRoot,screen:targets.Targets<Specs<{
readonly ink:{
readonly format:"rgba8unorm";
readonly sampled:true;
};
}>>,writes:{
readonly ink:typeofpasses.color;
},options?:passes.TargetOptions<Specs<{
readonly ink:{
readonly format:"rgba8unorm";
readonly sampled:true;
};
}>>|undefined):passes.Description<{
readonly ink:typeofpasses.color;
}>(+1overload)
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(
constroot:TgpuRoot
root,
constpage:targets.Targets<Specs<{
readonly ink:{
readonly format:"rgba8unorm";
readonly sampled:true;
};
}>>
page,{
ink:typeofpasses.color
ink:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
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(
consttags:text.TextSet
tags.
TextSet.drawing: passes.Drawing<WgslStruct<{
position:Vec4f;
uv:Vec2f;
bounds:Vec4f;
color:Vec4f;
label:U32;
glyph:U32;
local:Vec2f;
}>,{
label: number;
color: v4f;
}>
Draws all labels when added to a canvas or scene pass description. It tests depth without
writing it.
drawing);
consttags:text.TextSet
tags.
TextSet.labels: TgpuBuffer<WgslArray<WgslStruct<{
position:Vec3f;
color:Vec4f;
}>>>& StorageFlag
Holds label anchors and colours, initially at the origin and white. Use TypeGPU patch to
upload selected fields, or move and setLabel to write from a kernel.
Lays out and uploads only the specified label. Use write(label, '') to empty it. Returns
the layout, valid until the next write. Throws for a label outside the set or an em value
that is not greater than 0.
write(0,'42',{
Options.em: number
Sets positive units per em. World text uses world units. Text placed with screen or
pinned uses points, scaled by the text set pixelRatio.
em:180,
Options.align?:"right"|"left"|"center"|undefined
Sets the anchor position along each line. Default center.
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(
constframe:Frame
frame,
constdrawn:passes.Drawn
drawn);
// Sample it from another shader, such as a floor's
of one pipeline is a plain object, a passes.Drawing<Vertex, Pixel>. It needs a Vertex, an at that makes one and a draw. A drawing that writes colour or outputs also needs pixelOf, and color when the description has a passes.color target. The other fields are optional. The kit’s drawings have a label, and scene.add({ ...sparks.drawing, label: 'sparks' }) renames one. A blended drawing that tests the depth without writing it sets depthWriteEnabled: false in its depthStencil.
passes.fullScreen is the Vertex and at of one triangle that covers the screen at depth 0, drawn with draw(3). passes.drawing({ … }) returns the drawing you pass unchanged and infers its vertex and pixel types. at, pixelOf and draw then need no annotations. A function that takes any drawing types it as passes.AnyDrawing.
Pipelines Each description a drawing is added to builds a pipeline of its own, for its targets, jitter, samples and fills. A renderer gives its drawing, scene.add(particles.drawing), and holds no pipeline.
Sample count Every target in a description has the same sample count. passes.create reads it once to build pipelines. To change MSAA, create another target set and description, then add each drawing again. Destroy the old description to free its compound drawings’ per-view work.
Missing fields A drawing whose pixel or vertex lacks a field an output reads fails to type-check at add. The error names the target and the fields its output reads. without leaves the output out.
What add returnsadd returns a passes.Drawn. drawn.draw(pass) records into a pass from begin. drawn.destroy() removes it from the description’s compilation list and frees its per-view resources.
draw receives TypeGPU’s render commands, so it can issue an indirect draw. pass.drawIndirect(buffer, offset) reads its counts from a buffer with indirect usage, at offset bytes. With storage usage too, a decides how much to draw and the CPU never reads the count:
const
constDraw:d.WgslStruct<{
vertexCount:d.Atomic<d.U32>;
instanceCount:d.U32;
firstVertex:d.U32;
firstInstance:d.U32;
}>
Draw=
import d
d.
struct<{
vertexCount:d.Atomic<d.U32>;
instanceCount:d.U32;
firstVertex:d.U32;
firstInstance:d.U32;
}>(props:{
vertexCount:d.Atomic<d.U32>;
instanceCount:d.U32;
firstVertex:d.U32;
firstInstance:d.U32;
}):d.WgslStruct<{
vertexCount:d.Atomic<d.U32>;
instanceCount:d.U32;
firstVertex:d.U32;
firstInstance:d.U32;
}>
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.
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.
Records a draw into the pass, on which the description has set the pipeline it built. That
pipeline binds indices if supplied. drawIndexed throws without an index buffer. A group
the drawing sets with pass.setBindGroup stays for later drawings in the pass that read its
layout, so give such a layout to one drawing.
Draws primitives using parameters read from a buffer.
The buffer must contain 4 consecutive u32 values (vertexCount, instanceCount, firstVertex, firstInstance).
To get the correct offset within complex data structures, use d.memoryLayoutOf(...).
@param ― indirectBuffer - Buffer marked with 'indirect' usage containing draw parameters or raw GPUBuffer
@param ― indirectOffset - PrimitiveOffsetInfo pointing to the first draw parameter. If not provided, starts at offset 0. To obtain safe offsets, use d.memoryLayoutOf(...).
drawIndirect(
constargs:TgpuBuffer<d.WgslStruct<{
vertexCount:d.Atomic<d.U32>;
instanceCount:d.U32;
firstVertex:d.U32;
firstInstance:d.U32;
}>>&StorageFlag&IndirectFlag
args)});
Zero the count before the kernel runs each , such as with args.patch({ vertexCount: 0 }).
Each record takes 16 bytes. To draw record k from a buffer of records, pass 16 * k to drawIndirect as its byte offset. at receives vertex indices from firstVertex on, so records can split one list of vertices.
pass.drawIndexedIndirect(buffer, offset) reads 20-byte records of indexCount, instanceCount, firstIndex, baseVertex and firstInstance, and needs the drawing’s indices.
A description whose only target is passes.depth draws depth alone, as a shadow map or a depth prepass does. Its drawings need no pixelOf or color, and one without depthOf, cutout or sampleMask builds a pipeline with no fragment stage. A description with any other target requires pixelOf, even from a drawing with writeMask: 0. A full-screen sea can sample the scene depth in its colour pass. That pass cannot also write to the depth it samples. To write the sea’s depth to the same texture, add its shape to a separate description of depth alone:
const
constCorner:d.WgslStruct<{
position:d.Vec4f;
}>
Corner=
import d
d.
struct<{
position:d.Vec4f;
}>(props:{
position:d.Vec4f;
}):d.WgslStruct<{
position:d.Vec4f;
}>
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.
@param ― props Record with string keys and TgpuData values,
each entry describing one struct member.
struct({
position:d.Vec4f
position:
import d
d.
constvec4f:d.Vec4f
vec4f});
const
constlevel:passes.Description<{
readonly depth:typeofpasses.depth;
}>
level=
import passes
passes.
functioncreate<{
hdr:{
format:"rgba16float";
};
depth:{
format:"depth24plus";
sampled:true;
};
},{
readonly depth:typeofpasses.depth;
}>(root:TgpuRoot,screen:targets.Targets<{
hdr:{
format:"rgba16float";
};
depth:{
format:"depth24plus";
sampled:true;
};
}>,writes:{
readonly depth:typeofpasses.depth;
},options?:passes.TargetOptions<{
hdr:{
format:"rgba16float";
};
depth:{
format:"depth24plus";
sampled:true;
};
}>|undefined):passes.Description<{
readonly depth:typeofpasses.depth;
}>(+1overload)
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
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(
constview:cameras.OrbitCamera
view.
CameraBase.inject(): Inject
Fills cameras.current for the pipelines created from the configuration it is piped into.
inject());
// The sea's plane at y = 0, with no pixel function
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.
Computes the vertex for a vertex and instance index, as a 'use gpu' function.
at:(
vertexIndex: number
vertexIndex:number)=>{
'use gpu';
const
constcorners:d.v2f[]
corners=[
import d
d.
constvec2f:d.Vec2f
(x:number,y:number)=>d.v2f(+3 overloads)
vec2f(-1,-1),
import d
d.
constvec2f:d.Vec2f
(x:number,y:number)=>d.v2f(+3 overloads)
vec2f(1,-1),
import d
d.
constvec2f:d.Vec2f
(x:number,y:number)=>d.v2f(+3 overloads)
vec2f(-1,1),
import d
d.
constvec2f:d.Vec2f
(x:number,y:number)=>d.v2f(+3 overloads)
vec2f(1,1)];
const
constxz:d.v2f
xz=
constcorners:d.v2f[]
corners[
vertexIndex: number
vertexIndex]*500;
return
constCorner:d.WgslStruct
(props?:{
position:d.v4f;
}|undefined)=>{
position:d.v4f;
}
Corner({
position:d.v4f
position:
import cameras
cameras.
consttoClip:(point:d.v3f)=>d.v4f
Returns a world point in clip space, as a vertex shader's position. It reads cameras.current;
code that projects with a view of its own multiplies by that view's viewProjection.
Records a draw into the pass, on which the description has set the pipeline it built. That
pipeline binds indices if supplied. drawIndexed throws without an index buffer. A group
the drawing sets with pass.setBindGroup stays for later drawings in the pass that read its
layout, so give such a layout to one drawing.
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.
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.
color requires an output. Passing a function such as color: (s) => s.color fails to type-check at add. passes.shaded writes the pixel’s color field as it is. Any other colour is an output of your own whose write reads the pixel’s data:
// The pixel's colour, premultiplied for `pipelines.blend.over`
Defines how a pass writes one target from renderer data. write takes the renderer's data at
a pixel, and its parameter type declares the fields it needs. For vertex data, supply varyings and
vary. vary runs per vertex, and its interpolated result reaches write. With previous: true, vary also receives the previous frame's vertex. Throws if vary has no varyings
schema, previous has no vary, or vary takes two parameters without previous: true.
@param ― schema what the target holds per pixel, such as d.vec2f for an rg16float target
@param ― spec write, which gives the value at a pixel, and what it clears to and carries from the
vertex
@returns ― an output to give a target in passes.create
output(
import d
d.
constvec4f:d.Vec4f
vec4f,{
write:(pixel:{
readonly color:d.v4f;
},carried:undefined)=>d.v4f
write:(
pixel:{
readonly color:d.v4f;
}
pixel:{readonly
color:d.v4f
color:
import d
d.
export v4f
Interface representing its WGSL vector type counterpart: vec4f or vec4.
A vector with 4 elements of type f32
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.
A renderer with several pipelines or per-view resources supplies a passes.Compound object with build(into). Per-view resources can include a list of objects visible to a camera. Each description calls build once, so the shadow and scene get separate pipelines. build receives a passes.Into: the description’s targets and outputs, , and pipeline, add, without and instead. It creates the pipelines with into.pipeline(drawing) and returns a passes.Built with draw, initAsync and an optional destroy for per-view cleanup. The description’s destroy calls every drawing’s destroy, even after one of them throws. Instances renderers use this form.
These drawings share a vertex function. Their two pipelines draw a fill, then an outline:
const
constoutlined:passes.Compound<Seen,{
position:d.v4f;
}>
outlined:
import passes
passes.
interfaceCompound<P=never,X=never>
Builds several pipelines or resources for each description, such as a list of visible objects.
Each description calls build with itself. The drawing creates its pipelines through
into.pipeline.
Compound<
typeSeen={
readonly color:d.v4f;
}
Seen,
import d
d.
typeInfer<T>=Textends{
readonly[$repr]:inferTRepr;
}?TRepr:T
export Infer
Extracts the inferred representation of a resource.
For inferring types as seen by the GPU, see
InferGPU
@exampletype A = Infer // => number
type B = Infer<WgslArray> // => number[]
type C = Infer<Atomic> // => number
Builds the pipelines and resources for one description, which calls it when the drawing is
added.
build(
into:passes.Into<passes.Writes>
into){
const
constfilling:TgpuRenderPipeline<never>
filling=
into:passes.Into<passes.Writes>
into.
Into<Writes>.pipeline<d.WgslStruct<{
position:d.Vec4f;
}>, Seen>(drawing:passes.Shaders<d.WgslStruct<{
position:d.Vec4f;
}>,Seen>,from?:WithBinding):TgpuRenderPipeline
Builds a pipeline from drawing using from and the description's piped fills. from
defaults to the root with the fills given to beneath. Compound drawings use this method, and
their initAsync compiles the resulting pipelines.
pipeline(
constfill:passes.Drawing<d.WgslStruct<{
position:d.Vec4f;
}>,Seen>
fill);
const
constrimming:TgpuRenderPipeline<never>
rimming=
into:passes.Into<passes.Writes>
into.
Into<Writes>.pipeline<d.WgslStruct<{
position:d.Vec4f;
}>, Seen>(drawing:passes.Shaders<d.WgslStruct<{
position:d.Vec4f;
}>,Seen>,from?:WithBinding):TgpuRenderPipeline
Builds a pipeline from drawing using from and the description's piped fills. from
defaults to the root with the fills given to beneath. Compound drawings use this method, and
their initAsync compiles the resulting pipelines.
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(
constoutlined:passes.Compound<Seen,{
position:d.v4f;
}>
outlined);
into.pipeline(drawing, from) builds from a configuration of your own, such as root.pipe(into.inject()).with(slot, value), to fill a differently in each pipeline.
In a description with layers, into.layers is how many there are, for per-layer work such as a visible list for each. The built draw(pass, layer) receives the layer of the pass it draws into, to pick that layer’s work.
passes.output(schema, spec) defines the value each renderer writes per pixel to one target:
Writingwrite(pixel, carried) runs per pixel and returns a value of schema. Its first parameter types the data it reads. (pixel: { id: number }) requires an id, so only drawings whose pixelOf returns that field can write it.
Varyingvary(vertex, before) runs per vertex and returns a varyings struct. The rasteriser interpolates it for write’s carried parameter. With previous: true, before holds last frame’s vertex. The renderer’s vertex code compiles again with history.previously to read last frame’s camera and other temporal fills.
Clearingclear is what the target holds where nothing drew, zero by default. The color target clears to the description’s clear option instead.
Integers Integers go between the stages flat.
// Where what each pixel shows was last frame, in UV
const
constClips:d.WgslStruct<{
now:d.Vec4f;
before:d.Vec4f;
}>
Clips=
import d
d.
struct<{
now:d.Vec4f;
before:d.Vec4f;
}>(props:{
now:d.Vec4f;
before:d.Vec4f;
}):d.WgslStruct<{
now:d.Vec4f;
before:d.Vec4f;
}>
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.
@param ― props Record with string keys and TgpuData values,
each entry describing one struct member.
struct({
now:d.Vec4f
now:
import d
d.
constvec4f:d.Vec4f
vec4f,
before:d.Vec4f
before:
import d
d.
constvec4f:d.Vec4f
vec4f});
const
constmotion:passes.Output<unknown,{
position:d.v4f;
}>
motion=
import passes
passes.
functionoutput<d.Vec2f,unknown,{
position:d.v4f;
},d.WgslStruct<{
now:d.Vec4f;
before:d.Vec4f;
}>>(schema:d.Vec2f,spec:{
readonly clear?:d.v2f|undefined;
readonly varyings?:d.WgslStruct<{
now:d.Vec4f;
before:d.Vec4f;
}>|undefined;
readonly vary?:((current:{
position:d.v4f;
},previous:{
position:d.v4f;
})=>{
now:d.v4f;
before:d.v4f;
})|undefined;
readonly previous?:boolean;
readonlywrite:(pixel:unknown,carried:{
now:d.v4f;
before:d.v4f;
})=>d.v2f;
}):passes.Output<unknown,{
position:d.v4f;
}>
Defines how a pass writes one target from renderer data. write takes the renderer's data at
a pixel, and its parameter type declares the fields it needs. For vertex data, supply varyings and
vary. vary runs per vertex, and its interpolated result reaches write. With previous: true, vary also receives the previous frame's vertex. Throws if vary has no varyings
schema, previous has no vary, or vary takes two parameters without previous: true.
@param ― schema what the target holds per pixel, such as d.vec2f for an rg16float target
@param ― spec write, which gives the value at a pixel, and what it clears to and carries from the
vertex
@returns ― an output to give a target in passes.create
output(
import d
d.
constvec2f:d.Vec2f
vec2f,{
varyings?:d.WgslStruct<{
now:d.Vec4f;
before:d.Vec4f;
}>|undefined
varyings:
constClips:d.WgslStruct<{
now:d.Vec4f;
before:d.Vec4f;
}>
Clips,
previous?: boolean |undefined
Passes the previous frame's vertex as the second argument to vary. Without it, the second
argument is zero. This must be explicit because tgpu.fn and pipe hide the parameters of
vary. Default false.
previous:true,
vary?:((current:{
position:d.v4f;
},previous:{
position:d.v4f;
})=>{
now:d.v4f;
before:d.v4f;
})|undefined
vary:(
now:{
position:d.v4f;
}
now:{
position:d.v4f
position:
import d
d.
export v4f
Interface representing its WGSL vector type counterpart: vec4f or vec4.
A vector with 4 elements of type f32
v4f},
before:{
position:d.v4f;
}
before:{
position:d.v4f
position:
import d
d.
export v4f
Interface representing its WGSL vector type counterpart: vec4f or vec4.
A vector with 4 elements of type f32
Defines how a pass writes one target from renderer data. write takes the renderer's data at
a pixel, and its parameter type declares the fields it needs. For vertex data, supply varyings and
vary. vary runs per vertex, and its interpolated result reaches write. With previous: true, vary also receives the previous frame's vertex. Throws if vary has no varyings
schema, previous has no vary, or vary takes two parameters without previous: true.
@param ― schema what the target holds per pixel, such as d.vec2f for an rg16float target
@param ― spec write, which gives the value at a pixel, and what it clears to and carries from the
vertex
@returns ― an output to give a target in passes.create
output(
import d
d.
constu32:d.U32
export u32
A schema that represents an unsigned 32-bit integer value. (equivalent to u32 in WGSL)
Can also be called to cast a value to an u32 in accordance with WGSL casting rules.
@exampleconst value = u32(); // 0
@exampleconst value = u32(7); // 7
@exampleconst value = u32(3.14); // 3
@exampleconst value = u32(-1); // 4294967295
@exampleconst value = u32(-3.1); // 0
u32,{
clear?: number |undefined
Sets the value where nothing drew, as a value of schema. A drawing's color writes into
the description's color target, which uses the description's clear instead. Default
zero.
clear:0xffffffff,// nothing here
write:(pixel:{
id:number;
},carried:undefined)=> number
write:(
pixel:{
id: number;
}
pixel:{
id: number
id:number})=>{
'use gpu';
return
pixel:{
id: number;
}
pixel.
id: number
id;
},
});
passes.color marks the target for each renderer’s colour. passes.depth marks the depth target. A description allows at most one of each and leaves unlisted targets untouched. A key the set lacks fails to type-check at the key. An output comes only from passes.output and has no to read.
scene.without('id') omits the id output and its varyings for drawings that can’t supply it. scene.instead({ motion: skyMotion }) writes an output of the drawing’s own into that target. Both draw into the pass scene.begin starts:
Its depth, or depthOf’s, as its depthStencil state says: tested and written by default.
An output
The output’s write, from its pixel data and the output’s varyings. Outputs such as motion and ids don’t blend. A blended drawing replaces the value wherever it draws, even at its transparent corners.
Every bell, oral arm and tentacle is a translucent drawing. Turn off oit to draw them into a
description without the two targets. They then blend over in draw order, and the moon jelly behind
the sea nettle covers it.
Blending translucent drawings over each other looks right only when they draw from far to near. That needs sorting every frame, and still fails where two surfaces cross. A drawing with translucent: true needs no order. Give the description two more targets, one marked passes.accumulation and one marked passes.revealage. Each translucent pixel adds its colour into the first, weighted by its alpha and by distance so that nearer layers count most. It also multiplies the second by the share of what lies behind it that still shows. scene.composite(frame) then lays the average over the colour target in a pass of its own:
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
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(
constroot:TgpuRoot
root,
constscreen:targets.Targets<Specs<{
readonly hdr:{
readonly format:"rgba16float";
readonly sampled:true;
};
readonly accum:{
readonly format:"rgba16float";
readonly sampled:true;
};
readonly reveal:{
readonly format:"r16float";
readonly sampled:true;
};
readonly depth:{
readonly format:"depth24plus";
};
}>>
screen,{
hdr:typeofpasses.color
hdr:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
color,
accum:passes.Output<unknown,{
readonly position:d.v4f;
}>
accum:
import passes
passes.
constaccumulation:passes.Output<unknown,{
readonly position:d.v4f;
}>
Marks the target that translucent drawings add their colour into, weighted by their distance
from the eye, so that the nearest layers count most. Use an rgba16float target with
sampled: true, beside targets marked passes.color and passes.revealage. Clears to zero.
accumulation,
reveal:passes.Output<unknown, unknown>
reveal:
import passes
passes.
constrevealage:passes.Output<unknown,unknown>
Marks the target where translucent drawings multiply the share of what lies behind them that
shows through. Use an r16float or r8unorm target with sampled: true, beside targets marked
passes.color and passes.accumulation. Clears to one.
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(
constview:cameras.OrbitCamera
view.
CameraBase.inject(): Inject
Fills cameras.current for the pipelines created from the configuration it is piped into.
inject());
// The opaque ground first, then the translucent bells
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.
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.
Draws the color output, premultiplied by its alpha, as a translucent layer. With targets
marked passes.accumulation and passes.revealage, it adds into them in any order and
composite lays the result over the colour target. Elsewhere it blends over the colour target
in draw order. Tests depth without writing it, so draw it after the opaque drawings. Takes no
blend, and a description of depth alone refuses it. Default false.
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.
Lays what translucent drawings added to the targets marked passes.accumulation and
passes.revealage over the colour target, or over its resolve destination, in a pass of its
own. Call it after the pass that drew them and before anything reads the colour. Records
nothing while enabled is false. Throws without those targets.
composite(
frame:frames.Frame
frame);
});
Colour A translucent drawing’s color output is premultiplied, d.vec4f(rgb * alpha, alpha). Colour with an alpha of 0 adds light, as a glow does.
Depth It tests the depth that opaque drawings wrote before it and writes none. Draw it after them, in any order among the translucent ones.
Opaque drawings Opaque drawings leave the two targets alone. Outputs such as motion take a translucent drawing’s value as they take a blended one’s.
Without the targets In a description without the two targets, the same drawing blends over the colour target in draw order. The jellies keep a second description to turn the targets off.
Compositingcomposite reads both targets as textures, so each needs sampled: true.
Instances An instances renderer with blend: 'translucent' or 'clear' draws translucent.
pipe(fill) adds a fill to every pipeline built from the returned description. It applies after the drawing’s fill and takes precedence. passes.create(…).pipe(view.inject()) uses view as its camera. A shadow map uses a description of depth alone, viewed from the sun.
beneath(fill) adds a fill that applies before the drawing’s fill, as a default the drawing can override. scene.beneath(light.inject()) lights every drawing that doesn’t fill the lighting’s itself. Fills given to beneath and to pipe each apply in call order.
A compound drawing that builds pipelines from its own configuration, such as an instances renderer, starts from inject() and applies its own fills over it. beneath then lights it too.
A line two points wide or a label pinned beside a star needs the size of what the pass draws into. That size differs between the canvas, a low-resolution target and a shadow map. Every description fills passes.viewport in each pipeline and kernel it builds. It holds the drawn region’s size in pixels and its pixelRatio, the pixels a point takes:
import{
import cameras
cameras,
import passes
passes}from'@typegpu/kit';
/** Where a world point lands on the target, moved `offset` points right and up. */
Where a world point lands on the target, moved offset points right and up.
besideInPoints=(
world:d.v3f
world:
import d
d.
export v3f
Interface representing its WGSL vector type counterpart: vec3f or vec3.
A vector with 3 elements of type f32
v3f,
offset:d.v2f
offset:
import d
d.
export v2f
Interface representing its WGSL vector type counterpart: vec2f or vec2.
A vector with 2 elements of type f32
v2f)=>{
'use gpu';
const
constview:{
size:d.v2f;
pixelRatio:number;
}
view=
import passes
passes.
constviewport:TgpuAccessor<d.WgslStruct<{
size:d.Vec2f;
pixelRatio:d.F32;
}>>
Holds the region the pass draws into, in every pipeline and kernel a description builds. Each
description writes it as a pass begins, when the region has changed. Drawings that size things
in pixels or points read it, such as lines and screen text.
Returns a world point in clip space, as a vertex shader's position. It reads cameras.current;
code that projects with a view of its own multiplies by that view's viewProjection.
Holds pixels per point: the surface's pixelRatio, scaled with a target's resolution, so a
one-point line keeps its size in a low-resolution target. 1 for targets that follow a size
without a ratio, such as a shadow map.
pixelRatio)/
constview:{
size:d.v2f;
pixelRatio:number;
}
view.
size:d.v2f
Holds the width and height of the drawn region in pixels.
size)*
constclip:d.v4f
clip.
v4f.w: number
w,
constclip:d.v4f
clip.
zw:d.v2f
zw);
};
Size and ratio Over a surface, size is and pixelRatio its pixelRatio. Over targets, size is the drawn region, and pixelRatio is the source’s, scaled by the region. A point then keeps its size at a lower resolution or through targets.scaled. A source without a ratio, such as a shadow map’s fixed size, has a pixelRatio of 1.
Updatesbegin and record write it when the region has changed. A pipeline from pipeline() that draws into a pass you began yourself reads the region of the last begin. So does a kernel built from inject() in a frame where the description begins no pass.
Bindings Each description holds its own uniform, even beside another over the same targets. A pipeline that reads it binds 1 uniform.
Slots Descriptions also fill two slots: passes.sampleCount with the samples per pixel, and passes.depthOnly with whether they draw into depth alone. A drawing reads them to cut its own edges where there is one sample, or to leave out what only shows in colour, such as an antialiased edge in a shadow map.
A drawing’s shaders read buffers, textures and through , which its inject() fills. The description builds each pipeline from that fill, so a draw binds no group of yours:
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)
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({
...
import passes
passes.
constfullScreen:{
Vertex:d.WgslStruct<{
position:d.Vec4f;
uv:d.Vec2f;
}>;
at:(vertexIndex:number,_instanceIndex:number)=>{
position:d.v4f;
uv:d.v2f;
};
}
Provides Vertex and at for a renderer that covers the screen with one triangle at depth 0.
Draw it with draw(3). Use { ...passes.fullScreen, pixelOf, color, draw }.
Computes data at a pixel from the interpolated vertex. position is the pixel position.
Required for descriptions that write colour or outputs, and for depthOf and sampleMask.
pixelOf:(
corner:{
position:d.v4f;
uv:d.v2f;
}
corner:
import d
d.
typeInfer<T>=Textends{
readonly[$repr]:inferTRepr;
}?TRepr:T
export Infer
Extracts the inferred representation of a resource.
For inferring types as seen by the GPU, see
InferGPU
@exampletype A = Infer // => number
type B = Infer<WgslArray> // => number[]
type C = Infer<Atomic> // => number
Infer<typeof
import passes
passes.
constfullScreen:{
Vertex:d.WgslStruct<{
position:d.Vec4f;
uv:d.Vec2f;
}>;
at:(vertexIndex:number,_instanceIndex:number)=>{
position:d.v4f;
uv:d.v2f;
};
}
Provides Vertex and at for a renderer that covers the screen with one triangle at depth 0.
Draw it with draw(3). Use { ...passes.fullScreen, pixelOf, color, draw }.
Records a draw into the pass, on which the description has set the pipeline it built. That
pipeline binds indices if supplied. drawIndexed throws without an index buffer. A group
the drawing sets with pass.setBindGroup stays for later drawings in the pass that read its
layout, so give such a layout to one drawing.
Shaders can read tintBuffer.$ and view.$ without accessors. The resources become fixed in each pipeline’s automatic group.
A kernel of your own reads them the same way, created from root.pipe(fill), with scene.inject() piped in too when it reads the camera.
WebGPU forbids read-write storage in a vertex stage. Fill an accessor that a kernel writes and a vertex stage reads with byStage(buffer), read-write in compute and read-only elsewhere.
cfg.with takes a slot or accessor and its value. Passing a as cfg.with(group) fails with TS2554.
A resource you swap without new pipelines, such as a texture that follows the canvas, goes in a bindings.layout part. Give the description its parts by key as shared. It shares them in one layout, and every pass it begins sets that layout’s group:
import{
import bindings
bindings}from'@typegpu/kit';
const
constbackdropBindings:bindings.Layout<{
readonly picture:{
readonly texture:d.WgslTexture2d<d.F32>;
};
readonly smooth:{
readonly sampler:"filtering";
};
}>
backdropBindings=
import bindings
bindings.
functionlayout<{
readonly picture:{
readonly texture:d.WgslTexture2d<d.F32>;
};
readonly smooth:{
readonly sampler:"filtering";
};
}>(entries:{
readonly picture:{
readonly texture:d.WgslTexture2d<d.F32>;
};
readonly smooth:{
readonly sampler:"filtering";
};
}):bindings.Layout<{
readonly picture:{
readonly texture:d.WgslTexture2d<d.F32>;
};
readonly smooth:{
readonly sampler:"filtering";
};
}>
Declares bindings for module shaders from the entries that tgpu.bindGroupLayout takes. Define
the layout once beside the shaders. A part made with bind can bind its resources directly.
Call share before creating pipelines to put the part in a shared layout.
@param ― entries the bindings, as tgpu.bindGroupLayout takes them
@returns ― a layout whose bind makes a part from resources
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(
constroot:TgpuRoot
root,
constscreen:targets.Targets<{
hdr:{
format:"rgba16float";
};
}>
screen,{
hdr:typeofpasses.color
hdr:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
Shares these parts, by key, in one layout the description owns: every pass begin and
record start sets its group, and every pipeline the description builds reads the parts
through it. Takes the result of bindings.share instead when another description or a pass of
your own reads the same parts. Create the description before any other pipeline that reads
the parts. Default none.
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({
...
import passes
passes.
constfullScreen:{
Vertex:d.WgslStruct<{
position:d.Vec4f;
uv:d.Vec2f;
}>;
at:(vertexIndex:number,_instanceIndex:number)=>{
position:d.v4f;
uv:d.v2f;
};
}
Provides Vertex and at for a renderer that covers the screen with one triangle at depth 0.
Draw it with draw(3). Use { ...passes.fullScreen, pixelOf, color, draw }.
Computes data at a pixel from the interpolated vertex. position is the pixel position.
Required for descriptions that write colour or outputs, and for depthOf and sampleMask.
pixelOf:(
corner:{
position:d.v4f;
uv:d.v2f;
}
corner:
import d
d.
typeInfer<T>=Textends{
readonly[$repr]:inferTRepr;
}?TRepr:T
export Infer
Extracts the inferred representation of a resource.
For inferring types as seen by the GPU, see
InferGPU
@exampletype A = Infer // => number
type B = Infer<WgslArray> // => number[]
type C = Infer<Atomic> // => number
Infer<typeof
import passes
passes.
constfullScreen:{
Vertex:d.WgslStruct<{
position:d.Vec4f;
uv:d.Vec2f;
}>;
at:(vertexIndex:number,_instanceIndex:number)=>{
position:d.v4f;
uv:d.v2f;
};
}
Provides Vertex and at for a renderer that covers the screen with one triangle at depth 0.
Draw it with draw(3). Use { ...passes.fullScreen, pixelOf, color, draw }.
Records a draw into the pass, on which the description has set the pipeline it built. That
pipeline binds indices if supplied. drawIndexed throws without an index buffer. A group
the drawing sets with pass.setBindGroup stays for later drawings in the pass that read its
layout, so give such a layout to one drawing.
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.
Replaces resources without creating pipelines. The next shared group uses the replacements.
Resources the part already binds change nothing. Throws if a pipeline already binds the
resources directly, because that pipeline would keep the old resources.
shared also fills every in the pipelines the description builds, so a drawing or a callback needs no inject for them.
Create the description before any other pipeline that reads its parts builds. A pipeline built before then holds the part as fixed bindings, and passes.create throws.
A pipeline the description builds that reads a shared part it wasn’t given throws as it builds, and names the shared to add.
When two descriptions or a pass of your own read the same parts, call bindings.share once and give its result to each description as shared. A pass you open yourself sets the group with pass.setBindGroup(shared.layout, shared.group()).
record(frame, drawn) draws one handle or a list in order in a pass of its own. Create the list at setup. Use begin(frame) to choose drawings per frame or set a bind group of your own before drawing.
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.
Marks the pass for timing in this frame and returns timestamp writes, or undefined without
timestamp-query. Only marked passes are read back, because skipped passes keep stale
timestamps, and a marked pass whose timestamps haven't changed adds no sample. Call in every
frame that records the pass, as you record it: a timing starts no earlier than the one marked
before it.
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.
Selects targets to clear. Use true for all, false to preserve all, or a list of target keys to
clear. Default true.
clear:false});// over what the scene drew
consttiming:profiler.Profiler
timing.
Profiler.capture(frame: frames.Frame): void
Resolves the frame's timestamps and maps them after the submit. Call it after the timed passes.
A second call in the same frame, or a call after destroy, records nothing.
capture(
frame:frames.Frame
frame);
});
Clearing Output targets clear to their output’s clear. The colour target uses the description’s clear, which the pass reads at each begin. Depth uses depthClear, which defaults to 1. Stencil uses stencilClear.
Keeping contentsclear: false keeps what every target holds, so a later pass, such as the glows after the scene, draws over the colour and depth already there. clear: ['hdr'] clears the targets it names and keeps the rest, such as the depth an earlier pass drew.
Transient targets A transient target can’t retain its contents between passes. begin throws if asked to keep it. Set transient: false in its spec to retain contents. Multisampled targets are transient by default.
Storing Each pass stores what it drew with 'store'. A transient target uses 'discard' instead, so only what it resolves to another target survives the pass.
TimingtimestampWrites times the pass with a profiler.
Jitter The jitter option moves each vertex where the rasteriser sees it and nowhere else. Outputs read where the vertex is, so motion holds no jitter. Temporal antialiasing sets it.
Disabled descriptionsrecord and composite skip a disabled description; begin does not.
Standard depth puts the near plane at 0 and the far plane at 1. With perspective and a float depth target, that leaves less precision for distant surfaces, which can z-fight. Reversed depth puts the near plane at 1 and the far plane at 0. Set it up in two places: the description clears depth to 0 and keeps the greater depth, and the camera projects reversed depth.
The depth values a 32-bit float can hold, by distance from the eye
near plane
Try Drag the two surfaces along the axis, then pull the near plane in. Each tick stands for a million of the values a depth32float target can hold.
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
Sets the initial point that the camera orbits and looks at. Change it through goal.target.
target:[0,0,0],
OrbitOptions.distance: number
Sets the initial distance from the target to the eye, in world units. Change it through
goal.distance.
distance:6,
DepthOptions.reversed?: boolean |undefined
Projects reversed depth, 1 at the near plane and 0 at the far plane, for a description created
with depthClear: 0 and depthCompare: 'greater'. inject() fills cameras.reversed with
it. Default false.
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(
constroot:TgpuRoot
root,
constscreen:targets.Targets<Specs<{
readonly hdr:{
readonly format:"rgba16float";
readonly sampled:true;
};
readonly depth:{
readonly format:"depth32float";
readonly sampled:true;
};
}>>
screen,
{
hdr:typeofpasses.color
hdr:
import passes
passes.
constcolor:typeofpasses.color
Marks the target that receives each renderer's colour.
color,
depth:typeofpasses.depth
depth:
import passes
passes.
constdepth:typeofpasses.depth
Marks the depth target.
depth},
{
Options.depthClear?: number |undefined
Sets the depth clear value. For reversed depth, use depthClear: 0 and depthCompare: 'greater', with a camera created with reversed: true. Default 1.
Sets the depth comparison. Drawings test depth with it unless their depthStencil state
overrides it. With 'greater' or 'greater-equal', drawings that place themselves at the far
plane, such as environment.background, place themselves at depth 0. Default 'less'.
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(
constview:cameras.OrbitCamera
view.
CameraBase.inject(): Inject
Fills cameras.current for the pipelines created from the configuration it is piped into.
inject());
Depth test The kit’s drawings test depth with the description’s depthCompare. environment.background sits at depth 0 and draws where depth still holds it.
Depth readers The camera’s inject() fills cameras.reversed, so TAA, depth of field, ambient occlusion and the picker read the depth that camera drew the reversed way. Give TAA reversed: true when it has no camera.
Custom cameras A custom camera takes reversed: true too. Write a reversed projection into it, such as mat4.perspectiveReverseZ(fov, aspect, near, far).
Your own shaders A shader of your own that reads the depth starts from cameras.farDepth() and keeps the nearer of two depths with cameras.nearerDepth()(a, b), through the camera’s fills.
Unchanged values A drawing’s own depthStencil compare, passes.fullScreen’s depth of 0 and the depth text.screen takes stay as you write them. Give them reversed values yourself.
ShadowsShadows draw into maps of their own with standard depth, whatever the scene uses.
A shadow map in cascades, one per distance, draws the same casters into several layers of one texture, each through its own view. Give targets.create a target with layers, and the description draws a pass into each. cameras.layered holds a view per layer:
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
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
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(
constroot:TgpuRoot
root,
constmaps:targets.Targets<Specs<{
readonly depth:{
readonly format:"depth16unorm";
readonly layers:3;
readonly sampled:true;
};
}>>
maps,{
depth:typeofpasses.depth
depth:
import passes
passes.
constdepth:typeofpasses.depth
Marks the depth target.
depth},{
Options.bias?:{
readonly constant?: number;
readonly slope?: number;
}|undefined
Adds a depth bias to every pipeline, in depth-format steps and per unit of slope, as
depthBias and depthBiasSlopeScale. Use for shadow maps to prevent surfaces from shadowing
themselves. Default none.
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(
constviews: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
constdrawn:passes.Drawn
drawn=
constcasters:passes.Description<{
readonly depth:typeofpasses.depth;
}>
casters.
Into<{ readonly depth:typeof depth;}>.add<{
color:v4f;
},{
position:v4f;
world:v3f;
normal:v3f;
uv:v2f;
uv1:v2f;
row:number;
}>(drawing:passes.Compound<{
color:v4f;
},{
position:v4f;
world:v3f;
normal:v3f;
uv:v2f;
uv1:v2f;
row:number;
}>):passes.Drawn(+1overload)
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.
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.
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:frames.Frame
frame,
constdrawn:passes.Drawn
drawn);// a pass into each layer
});
One pipeline The description builds each pipeline once, for all layers. Each pass sets a uniform holding its layer, which shaders read as passes.layer.$. cameras.layered reads it to give cameras.current.$ the layer’s view. Data of your own per layer can be indexed by it too.
Recordingrecord draws a pass into each layer, in order, with the same options. record(frame, drawn, { layer }) draws into one. begin(frame, { layer }) begins one and throws without a layer when there are several.
Timing With timestampWrites, the first layer’s pass writes the start and the last layer’s pass writes the end.
Layer counts Every target a description draws into needs the same layers, or passes.create throws naming each target and its count. Translucency targets and resolves aren’t drawn into layers.
Render bundles A render bundle can’t draw into a description of 2 or more layers, and draw throws for one. Record the drawing into the passes that record or begin opens.
Kit drawings Drawings of one pipeline, particles, trails and text draw the same way into each layer, through the layer’s view. An instances renderer with cull: true keeps a visible list per layer and culls every layer in one pair of . Impostors and poses draw through an instances renderer.
Kernels A kernel built from a layered description’s inject() runs outside its passes, so it fills passes.layer itself. The instances culling fills it from each invocation’s y.
Bindings The layer takes 1 uniform and one of WebGPU’s 4 bind groups in each pipeline that reads passes.layer. With cameras.layered, a caster binds 2 uniforms: the views and the layer.
Bind groups A pipeline a description builds uses up to three of WebGPU’s four bind groups: one for its fixed bindings, one for the shared parts and one for the layer. One is left for a group of your own.
Fragment inputs The fragment inputs to a drawing’s pixelOf are its vertex’s fields and the pixel’s position. WebGPU’s other fragment inputs, such as frontFacing, aren’t available to it.
Derivatives In pixelOf, take std.fwidth, std.dpdx and std.dpdy before any branch or return that depends on the pixel. WGSL rejects a derivative in control flow that varies between pixels.
Large coordinates A few thousand units from the origin, a 32-bit float steps by about 0.0002, too coarse for derivatives of a world position or for noise coordinates across a pixel. Carry world - cameras.current.$.position in the vertex, and add the eye’s position back in pixelOf where it needs the world position.
Varying names Each output’s varyings go between the stages as <target>_<n>, numbered from 0 in the order of its varyings struct. A name a vertex field already has gets a number added. They count towards WebGPU’s 16 inter-stage variables, with the vertex’s own fields.
Previous frame An output with previous: true runs the renderer’s at twice per vertex, and binds last frame’s uniforms beside this frame’s.
Overlapping layers Translucent layers that overlap in depth average their colours by weight, so a layer close behind another shows through more than it would in order. The weight suits distances from the eye of about 0.1 to 500.
Translucent motion A translucent drawing’s motion is that of the layer drawn last where it shows, so TAA can smear what lies behind it. Leave it out of motion with without('motion') to keep the motion beneath it.
Blended drawingsParticles, trails and text drawings set a blend and draw over in order. To draw one of these in any order, make a drawing of your own from it. Leave out its blend, set translucent: true and supply premultiplied colour. Use a description with accumulation and revealage targets.
rendererA renderer draws one sort of thing, such as instances or particles, by handing a pass description a drawing.Every renderer is a drawing →
outputAn output is a value every drawing writes at each pixel beside its colour, such as motion or an id.Outputs every drawing writes →
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 →
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 →
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 →
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 →
rowA row is one object's values in a buffer, such as one enemy, one particle or one light.Objects are rows in buffers →
tableA table is a buffer of rows with named fields, some written by the CPU and the others by kernels.Rows →
slotA slot is a row's place in its buffers, which a new row can take once the first is removed.Row ids →
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 →
instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
hookA hook is a placeholder that each pipeline fills with its own choice, such as the camera it draws through.Members and placeholders →
surfaceA surface is a canvas set up for your root, which keeps its drawing buffer the size the page shows it at.Surfaces →
samplerA sampler tells the GPU how to read a texture between its texels and past its edges, such as smoothly or in blocks.Words →
accessorAn accessor is a typed value that shader code reads and that each pipeline can fill with a different resource.Modules connect through TypeGPU →
bindingA binding is one buffer, texture or sampler in a bind group, which a shader reads by its place there.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 →
partA part is a set of resources that can be replaced, such as a texture that follows the screen size, which pipelines read through a layout they share.Resources that are replaced →
dispatchA dispatch runs a kernel once over a number of threads, inside a compute pass.Words →
Shares these parts, by key, in one layout the description owns: every pass begin and record start sets its group, and every pipeline the description builds reads the parts through it.Default none.
Shares these parts, by key, in one layout the description owns: every pass begin and record start sets its group, and every pipeline the description builds reads the parts through it.Default none.
Lays what translucent drawings added to the targets marked passes.accumulation and passes.revealage over the colour target, or over its resolve destination, in a pass of its own.
Interpolates these vertex fields linearly in screen space, without perspective correction, such as a distance measured across a shape extruded on screen.
begin from the frame, with the shared group set, then each drawing's draw from add into the pass; into targets with layers, record does so once per layer. composite records a pass of its own.
the pipelines add builds ·until the drawing or description is destroyed ·a pipeline per description that composites ·bind groups ·a buffer per layer ·a buffer per viewport its pipelines read ·bindings when given parts as shared
WebGPU pipelines and bind groups need no destruction. Compound drawings free the resources they built for the description. composite lays translucent drawings over the colour with that pipeline and a bind group per pair of textures. A description drawn into layers holds each layer's index in a uniform with a bind group.