A glTF village with shadows, occlusion, TAA and bloom
24 × 24 px
Try Drag to look round, and turn each stage off to see what it adds. The loupe shows TAA on the roof edges.
A lighting and a set of instances draw glTF models lit by the sun and the sky. On their own they look flat. Every surface gets light from the whole sky. Nothing seems to rest on the ground. Edges step and shimmer as the view turns. Four stages finish the picture:
The sun’s shadows, in cascades fitted to the view, set each model on the ground.
Ambient occlusion darkens the sky light where nearby surfaces hide the sky: under eaves, between trees and where a wall meets the grass.
TAA smooths edges and thin parts by taking a sample at a different offset each .
Bloom spreads light brighter than white, and the final pass tone maps and grades the picture.
The program splits into three files. look.ts holds the lighting and every pass from the prepass to the canvas, so another program can copy it whole. The package ships it and props.ts whole in docs/recipes/lit-models/:
scene.tscreateScene with the camera, the props, the look and the frame
look.tscreateLook with the lighting, the passes and the post-processing
props.tscreateProps with the mesh pool and the instances
Put every model in one mesh pool and every piece in one set of . In each pass, the set issues one draw per mesh that has instances. One house and a thousand copies of the same house take the same number of draw calls:
props.ts
import{
import instances
instances,
import meshPool
meshPool}from'@typegpu/kit';
importtype{
(alias)interfaceTgpuRoot
importTgpuRoot
TgpuRoot}from'typegpu';
/** A piece of the scene: a model by name, and its row's values. */
exportinterface
interfacePlacement
A piece of the scene: a model by name, and its row's values.
Placement{
readonly
Placement.model: string
model:string;
/** Its position, rotation, scale and any material field, such as `emission`. */
readonly
Placement.values: {
readonly position?: FieldInput<Vec3f>;
readonly rotation?: FieldInput<Vec4f>;
readonly scale?: number | FieldInput<Vec3f>;
readonly color?: FieldInput<Vec3f>;
readonly roughness?: number;
readonly metallic?: number;
readonly emission?: FieldInput<Vec3f>;
readonly opacity?: number;
}
Its position, rotation, scale and any material field, such as emission.
These values set the transform, material and custom fields in add and write. All are
optional. Vectors also take any array of numbers, such as a Float32Array from a math library.
You can spread in a value from materials. Omitted fields keep their values. On creation, the
transform is the identity and material factors come from the mesh, with white chalk for shapes.
Mesh textures multiply these factors.
Values;
}
/** One pool of every model and shape, and one set of instances placing them. */
Creates shared vertex storage and an index buffer, with bounds and textures per mesh. One
pipeline can draw any mesh. Each vertex uses 12 bytes for position and 8 for normal and UV
coordinates, and 8 for a second uv set with uvs1. Skinned models add 8 bytes for joints and
weights. Extras add the size of their struct per vertex.
@unstable
@injects ― definition the vertices vertexAt, positionAt and uv1At read, the joints and
weights influencesAt reads, and the boxes boundsOf reads
@injects ― member the extras pool.extra reads
@binds ― 1 storage: positionAt, the positions
@binds ― 2 storage: vertexAt, the positions and the normals and uvs
@binds ― 1 storage: uv1At, the second uvs, in a pool made with uvs1
@binds ― 1 storage: influencesAt, the joints and weights
@binds ― 1 storage: boundsOf, every mesh's box
@binds ― 1 storage: pool.extra, every vertex's extras
@binds ― 1 uniform: pool.texturesOf(index) for materials, beside its textures and sampler, in
the fragment stage
@submits ― setup a shape added without an encoder bakes in a compute pass of its own, submitted at
once, and a model's images generate their mips as they decode
@owns ― 5 to 7 buffers, a uniform per way of reading textures, a uniform per shape added, a
pipeline per pair of shape functions, textures, samplers, bind groups, what images makes:
positions, normals and uvs, indices and boxes, second uvs with uvs1, joints and weights once a
skinned model comes, and the extras when extra names any; a bake per vertexAt and indexAt
it bakes, and per shape added the uniform of its ranges and their group; each image decoded once
per format it is read in, and a group per set of a mesh's textures
@returns ― a pool you add meshes and models to and destroy
Sizes a pool to hold exactly items: models such as impostors.CARD, their meshes, shapes, and
counts. Spread it into the options: meshPool.create(root, meshPool.roomFor([...])). It keeps a
second uv set when one of the meshes carries uvs1.
@param ― items what the pool will hold
@returns ― the capacity, vertices and indices they take, and uvs1: true when a mesh needs it
roomFor(
var Object:ObjectConstructor
Provides functionality common to all JavaScript objects.
Uploads each mesh into the next free ranges and decodes images in the background. Each image
decodes once per pool and format, and pixels and bitmaps upload during the call. The first skinned mesh allocates a joint-and-weight buffer
for the full vertex capacity. Throws if the pool is full, the model has no meshes, its
arrays disagree or encoded images other than HDR have no decoder.
Bakes a shape into the next free ranges in a compute pass. Given a frame or an encoder, it
records there; otherwise, it submits at once. The bake's pipeline inlines the shape's
vertexAt and indexAt, and compiles, blocking, the first time the pool bakes those
functions, unless initAsync compiled it for the shapes option. Throws when the pool is
full.
add(
item:meshPool.Shape
item)],
ready:Promise<void>
ready:
var Promise:PromiseConstructor
Represents the completion of an asynchronous operation
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
@returns ― Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@param ― callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
@param ― initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
reduce((
sum: number
sum,{
model: string
model})=>
sum: number
sum+
constmodelOf:(name:string)=>meshPool.Model
modelOf(
model: string
model).
Model.meshes: readonly meshPool.Mesh[]
meshes.
ReadonlyArray<Mesh>.length: number
Gets the length of the array. This is a number one higher than the highest element defined in an array.
Creates a set of mesh instances with transforms, materials and optional custom fields. Each
instance uses a row, and renderers draw one list of live rows per mesh.
@param ― pool the mesh pool whose meshes it draws
@param ― options.kind a kind from instances.define
@returns ― a set of instances you flush every frame and destroy
create(
root: TgpuRoot
root,
constpool:meshPool.MeshPool<{}>
pool,{
Options<K extends AnyKind = Plain>.capacity: number
Limits the number of rows. A mesh instance uses one row; a model instance uses one row per
mesh.
capacity:
constrows:number
rows});
for(const{
constmodel:string
model,
constvalues:{
readonly position?:FieldInput<Vec3f>;
readonly rotation?:FieldInput<Vec4f>;
readonly scale?:number|FieldInput<Vec3f>;
readonly color?:FieldInput<Vec3f>;
readonly roughness?:number;
readonly metallic?:number;
readonly emission?:FieldInput<Vec3f>;
readonly opacity?:number;
}
Its position, rotation, scale and any material field, such as emission.
Adds an instance of a mesh, model or group of meshes from the pool. Each mesh uses a row,
and all rows move and change together under one id. values may be a function of each mesh,
to give a model's meshes values of their own. Throws if a mesh belongs to another pool, the
group is empty, a posed kind receives a mesh without joints or the set is full. When values
or a write throws, it adds no row and rethrows.
add(
constmodelOf:(name:string)=>meshPool.Model
modelOf(
constmodel:string
model),
constvalues:{
readonly position?:FieldInput<Vec3f>;
readonly rotation?:FieldInput<Vec4f>;
readonly scale?:number|FieldInput<Vec3f>;
readonly color?:FieldInput<Vec3f>;
readonly roughness?:number;
readonly metallic?:number;
readonly emission?:FieldInput<Vec3f>;
readonly opacity?:number;
}
Its position, rotation, scale and any material field, such as emission.
Creates a renderer for colour and shadow pass descriptions, lit by the lighting each
description gives through beneath. Use pipe to fill resources read by kind callbacks, or
another lighting.
renderer(),
/** Settles once every model's textures are on the GPU. */
ready:Promise<void[]>
Settles once every model's textures are on the GPU.
ready:
var Promise:PromiseConstructor
Represents the completion of an asynchronous operation
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map((
model:meshPool.Model
model)=>
model:meshPool.Model
model.
Model.ready: Promise<void>
Resolves when all textures have decoded and uploaded, at once for a model whose materials
name none. Until then, meshes draw without textures. Rejects if image decoding fails or the
pool is destroyed before upload. A destroyed pool uploads nothing.
Uploads changed rows. When instances are added or removed, it also uploads live rows per
mesh and updates draw counts. Call this once per frame before drawing. HistoryInstances
take the frame or its encoder and throw without one.
flush(),
functiondestroy():void
destroy(){
constprops:instances.Instances<Plain>
props.
functiondestroy():void
Destroys the storage buffers.
destroy();
constpool:meshPool.MeshPool<{}>
pool.
MeshPool<{}>.destroy(): void
Destroys the buffers and textures.
destroy();
},
};
}
meshPool.roomFor sizes the pool for every model’s vertices and indices. A shape such as meshes.cylinder() goes in models beside the glTF models, as the figure’s lantern posts do.
A starts with its mesh’s material from the file. Values you give replace it, so a lantern’s glass takes an emission above 1 and glows through the bloom.
Pieces with shaders of their own, such as turning sails or lit windows, take a kind in a second set from the same pool. The look draws that set’s the same way.
Each placement carries the values its row starts with:
/** A turn of `yaw` radians round +y, as a quaternion. */
Ambient occlusion reads a depth texture drawn before the scene shades. The look draws every solid prop into a half-resolution prepass and traces the occlusion from it. The lighting’s ambient dims the sky light by the occlusion. The sun’s shadow fits two cascades to the view:
look.ts
/** Sky light, dimmed where nearby surfaces hide the sky. */
Sky light, dimmed where nearby surfaces hide the sky.
occludedSky=(
material:{
color:d.v3f;
roughness: number;
emission:d.v3f;
metallic: number;
occlusion: number;
}
material:
import shading
shading.
typeMaterial={
color:d.v3f;
roughness:number;
emission:d.v3f;
metallic:number;
occlusion:number;
}
This schema describes a surface with the glTF metallic-roughness model. New fields are only
appended, each off at zero. Make one with a materials preset or copy one with Material(m),
then assign the fields you set: a struct literal stops compiling when a field is added.
Material,
point:{
position:d.v3f;
normal:d.v3f;
view:d.v3f;
uv:d.v2f;
uv1:d.v2f;
}
point:
import shading
shading.
typePoint={
position:d.v3f;
normal:d.v3f;
view:d.v3f;
uv:d.v2f;
uv1:d.v2f;
}
This schema describes a point being shaded in world space. New fields are only appended, each
off at zero. Make one with pointAt, a copy Point(p) or a zero Point(), then assign the
fields you set: a struct literal stops compiling when a field is added.
Computes ambient light by blending sky and ground colours according to the surface normal.
Reflections sample the sky in the reflection direction. Roughness blends them towards diffuse
light, and skyReflection scales them. The material's occlusion darkens both.
hemisphere(
material:{
color:d.v3f;
roughness: number;
emission:d.v3f;
metallic: number;
occlusion: number;
}
material,
point:{
position:d.v3f;
normal:d.v3f;
view:d.v3f;
uv:d.v2f;
uv1:d.v2f;
}
point)*
import ao
ao.
constat:(position:d.v3f)=>number
Returns the visibility of sky light at a world position, from 0 in a closed crease to 1 in the
open. It projects the position through cameras.current and blends the 4 nearest texels whose eye
distance matches. Where none matches, such as on a translucent surface in front of the opaque
one, it returns 1. Call it from shading, such as an ambient hook, in a description that shares
the occlusion's part.
at(
point:{
position:d.v3f;
normal:d.v3f;
view:d.v3f;
uv:d.v2f;
uv1:d.v2f;
}
point.
position:d.v3f
position);
};
/** The lighting and every pass from the prepass to the canvas, seen through `view`. */
The lighting and every pass from the prepass to the canvas, seen through view.
createLook(
root: TgpuRoot
root:
(alias)interfaceTgpuRoot
importTgpuRoot
TgpuRoot,
surface:targets.Surface
surface:
(alias)interfaceSurface
importSurface
Provides a destination for frames, such as a canvas from web.surface or native.surface, or a
texture from offscreenSurface in a test. Pass the frame to view for code that works with
every destination.
Surface,
view:cameras.OrbitCamera
view:
import cameras
cameras.
interfaceOrbitCamera
OrbitCamera,
options: LookOptions
options:
interfaceLookOptions
LookOptions,
){
const{
conststages:Stages
The stages that run, read every frame. Call apply after changing taa or bloom.
stages}=
options: LookOptions
options;
// Half-resolution depth of the solid props, drawn first for the occlusion to read
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
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(
view:cameras.OrbitCamera
view.
CameraBase.inject(): Inject
Fills cameras.current for the pipelines created from the configuration it is piped into.
Creates ground-truth ambient occlusion (GTAO) from a depth texture drawn before shading. As
Jimenez and others describe it in 2016, a trace walks slices directions per pixel with 3 steps
each way and XeGTAO's falloff, and a denoise blurs 3 × 3 pixels of the same surface. Shading reads the result through
ao.at, usually in an ambient hook: (material, point) => shading.hemisphere(material, point) * ao.at(point.position), in a description that shares the occlusion's part.
@injects ― hook the texture and region ao.at reads, from the part
@binds ― 0 storage, 1 uniform: ao.at, the region and frame, beside the texture
@allocates ― on resize: two textures for a new depth size and the bind groups of its passes; so
does a new depth or normal texture
@owns ― targets, 2 or 3 buffers, 2 pipelines, 2 bind groups: the raw and the denoised occlusion;
the settings, the region and frame, and with temporal the frame indices; the trace and the
denoise, with a group each
@records ― record after the pass that draws depth, before the passes that shade; with
temporal, a copy advances the frame.
@param ― view the camera that drew depth, which shading's cameras.current must match
@param ― options.depth the depth drawn before shading, read at every record
@param ― options.normal normals from ao.normal drawn with depth, read at every record
@param ― options.region the part of the depth that holds the picture, read at every record
@returns ― occlusion you record every frame and destroy
create(
root: TgpuRoot
root,
view:cameras.OrbitCamera
view,{
Options.depth: ()=>targets.Depth
Returns a sampled depth texture drawn before shading, such as a half-resolution prepass.
record reads it on every call. Its size sets the size of the occlusion.
Sets initial values over defaults. Default defaults, with radius 0.5 and power 2.2.
settings:{
radius: number
radius:
options: LookOptions
options.
LookOptions.crease: number
The size of the gaps the occlusion darkens, in world units.
crease,
power: number
power:3},
Options.enabled?:(()=> boolean)|undefined
Controls whether record traces in the current frame. When false, the first record clears
output to full visibility and later ones record nothing. Skip the prepass yourself. The
textures and pipelines stay allocated. Default always.
@cpu
enabled:()=>
conststages:Stages
The stages that run, read every frame. Call apply after changing taa or bloom.
Creates lighting with a sun, sky and fog. It can also read point lights from a table or a
function and cast shadows. Pipe its injection into each pipeline that uses it. Throws if
points names no source or more than one, a light function has neither count nor
candidates, a table comes with count, or candidates.ranges is anything other than a
positive integer.
@injects ― hook the shading hooks its options name: reflect, ambient, fog, sunShadow and
attenuation
@injects ― definition the sun, sky and fog, the shadows and the point lights, which shading
reads
@binds ― 1 uniform: shading.shade, the sun, sky and fog
@binds ― 2 storage, 1 uniform: shading.shade with a table of point lights
@binds ― 3 storage, 1 uniform: shading.shade with a table of lights whose positions are on the
device, the table's two parts
@binds ― 1 uniform: shading.shade with points.light or points.spot, plus what the function
binds
@binds ― 0 storage: shading.shade with points.candidates, plus what their functions bind, 2
storage for a neighbour grid's range and slot
@binds ― 1 uniform: shading.shade with a shadow, the sun's light space and cascades, beside the
depth array and its comparison sampler
@binds ― 1 uniform: shading.shade with pointShadow, each shadow's light, layers and views,
beside their depth array and the comparison sampler
@owns ― 1 to 3 buffers, a sampler, targets, a cameras.layered, passes: the sun, sky and fog; with a
shadow, its light space, the views of its cascades, a comparison sampler, the depth array and
the passes that draw it; with pointShadow, the same for the lights' faces
@records ― shadow.record and pointShadow.record with what was added to them, before the passes
that shade
@param ― options.shadow the sun's shadow, with a depth pass per cascade
@param ― options.pointShadow shadows from pointShadow.define that cast gives to lights of
points.table, with a depth pass per face
@param ― options.points point lights from a table or a 'use gpu' function. Every lit point visits
each slot up to the table's highest live one, or count with a function, unless candidates
names the slots that may reach it
Sky light, dimmed where nearby surfaces hide the sky.
occludedSky},
shadow:{
readonly eye:cameras.OrbitCamera;
readonly cascades:2;
readonly far: number;
readonly filter:9;
readonly enabled:()=> boolean;
}&lighting.FittedShadowOptions
Enables and configures the shadow from the sun. Default none.
shadow:{
eye:cameras.OrbitCamera&cameras.CpuView
Fits the map to this camera's view, in cascades layers that reach far from the eye. Each
record fits them again, so the map follows the camera without follow. Default none, a
fixed map.
eye:
view:cameras.OrbitCamera
view,
cascades:2
Splits the view into 1 to 4 cascades, each a layer of the map drawn in a pass of its own.
Nearer cascades cover less ground, so their shadows are sharper. Needs an eye. Default 1.
cascades:2,
far: number
Sets how far from the eye the cascades reach, in world units. Change it with setFar. Needs an
eye. Default 50.
far:
options: LookOptions
options.
LookOptions.far: number
How far the sun's shadow reaches, a little past the farthest prop the view shows.
far,
filter:9
Sets the number of comparisons per shaded point to 1, 4 or 9. Each comparison filters four
texels. Default 4.
filter:9,
enabled:(()=> boolean)&(()=> boolean)
Controls whether record draws the shadow in the current frame. When false, it records no
depth pass and shading treats every point as sunlit. The map and pipelines stay allocated.
Default always.
@cpu
enabled:()=>
conststages:Stages
The stages that run, read every frame. Call apply after changing taa or bloom.
Holds the sun, sky and fog values from defaults and the settings option. Use patch to
upload only the fields you supply. The shadow's next record follows a sunDirection written
here.
Set far a little past the farthest prop the view shows. The cascades spread the same over far, so a longer reach blurs every shadow. See cascades fitted to the view.
Set crease near the size of the gaps the occlusion should darken. The figure uses 0.7 world units for houses about one unit tall.
The occlusion dims only the sky light. Sunlit faces keep their brightness, and the sun’s shadow keeps its own edge.
For reflections of a sky panorama, call environment.occluded with the same ao.at in place of shading.hemisphere, as shading with an environment shows.
The scene shades into an rgba16float target through the lighting, offset by TAA’s jitter. It takes the occlusion’s part as shared. The supplies what ao.at reads, and keeps the pipelines working when a resize replaces the occlusion’s texture. TAA blends the current frame with its accumulated history into a smooth picture. The bloom and the final pass both read that picture. Inside createLook, after the lighting:
look.ts
/** Cools the shadows and warms the lights after the tone curve. */
const
constdusk:(color:d.v3f,_uv:d.v2f)=>d.v3f
Cools the shadows and warms the lights after the tone curve.
dusk=(
color:d.v3f
color:
import d
d.
export v3f
Interface representing its WGSL vector type counterpart: vec3f or vec3.
A vector with 3 elements of type f32
v3f,
_uv:d.v2f
_uv:
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
constlight:number
light=
import std
std.
functionsaturate(value:number):number(+1overload)
export saturate
saturate(
import tone
tone.
constluminance:(color:d.v3f)=>number
Returns the relative luminance of a linear colour.
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 temporal antialiasing from subpixel-jittered frames. The resolve blends each frame
with history sampled where motion, or depth and camera movement, place the preceding pixel.
Without either, it samples history at the same pixel. It clamps history colour to
the local colour spread to reduce trails and weights by brightness to reduce bright-pixel
flicker. With size, it resolves a smaller source up to that size: each output pixel rebuilds
the current frame from the nine source pixels around it with Lanczos-2 weights placed by this
frame's jitter, and blends less of it where those weights add up to less. Record its single
pass after scene passes and before the final pass reads output.
@allocates ― on resize: targets for the new size and the bind groups of its passes; so does a new
source, motion, depth or reactive texture
@owns ― targets, 4 buffers, a sampler, a pipeline, 2 to 4 bind groups: two histories, each frame
written into one from the other, the settings, the region and whether to blend, the jitter and
its sequence, a group each for the frames that read either history with the source and
motion, one for depth and one for reactive
@binds ― 1 uniform: jitter, this frame's offset
@records ― record after the passes that draw the source and the motion, before what reads
output.
@param ― options.source this frame's picture, drawn through jitter, read at every record
@param ― options.motion how far each pixel's surface moved since last frame, read at every
record; without it, pixels move only with the camera
@param ― options.depth the scene's depth, for the motion of the nearest surface around each pixel
and for motion from the camera, or null
@returns ― a resolve you record every frame and destroy
create(
root: TgpuRoot
root,{
Options.source: Source
Provides the current linear-colour picture, drawn through jitter: a function returning a
texture, such as () => screen.textures.hdr, or a rendered picture. record reads it on
every call.
Provides the current textures. A size change replaces them.
textures.
hdr:targets.Target<{
readonly format:"rgba16float";
readonly sampled:true;
}>
hdr,
Options.depth: (()=>targets.Depth)|null
Returns sampled scene depth without stencil, or null for a picture drawn without depth.
Motion then follows the nearest surrounding surface to avoid smearing moving edges over the
background. record reads it on every call. Unused without motion or camera. With null,
motion is read at each pixel.
Provides the current textures. A size change replaces them.
textures.
depth:targets.Target<{
readonly format:"depth24plus";
readonly sampled:true;
}>
depth,
Options.camera?:cameras.CameraBase|undefined
Supplies the scene camera with its preceding view, such as cameras.orbit. With depth,
pixels without renderer-written motion reconstruct motion from depth and camera movement.
Without both, these pixels stay in place. Default none.
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(
root: TgpuRoot
root,
constscreen:targets.Targets<Specs<{
readonly hdr:{
readonly format:"rgba16float";
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.
color,
depth:typeofpasses.depth
depth:
import passes
passes.
constdepth:typeofpasses.depth
Marks the depth target.
depth},
{
Options.jitter?: Position |undefined
Moves clip positions for rasterisation. Outputs read the original vertex positions. Use for a
sub-pixel offset in temporal antialiasing. Default none.
@gpu
jitter:
constaa:taa.Taa
aa.
Taa.jitter: (position:d.v4f)=>d.v4f
Offsets vertices by a different fraction of a source pixel each frame so frames sample the
whole pixel together: 8 offsets in turn, or at size 8 for each output pixel a source pixel
covers, 18 at 1.5 times per side. Supply this as jitter in passes.create.
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.
shared:{
ao: Part<Entries>
ao:
constocclusion:ao.Ao
occlusion.
Ao.part: Part<Entries>
Provides the texture and its region for ao.at. Share it before creating the pipelines that
shade, so a new depth size replaces the texture without replacing pipelines: give
passes.create{ shared: { ao: occlusion.part } }, or call bindings.share(root, { ao: occlusion.part }) for passes of your own. A pipeline that reads ao.at without the share
throws as 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(
view:cameras.OrbitCamera
view.
CameraBase.inject(): Inject
Fills cameras.current for the pipelines created from the configuration it is piped into.
Adds fill after the fills given to earlier beneath calls and returns a description of the
same passes. A drawing's own fills take precedence over these, and piped fills over both, so
beneath supplies defaults such as a lighting. A compound drawing that passes its own from
to pipeline gets them by starting from with inject().
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(
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.
Creates the final pass of a frame. It reads the source, adds glow, tone maps, grades, applies
the vignette, encodes and dithers. It draws one triangle into the caller pass.
@allocates ― on resize: a bind group for a new source or glow
@owns ― 2 buffers, a sampler, a pipeline, 2 bind groups: the settings, the regions it reads, a
group for the glow and one for each texture the source returns
@records ― record into a pass of its own on the view you give, usually the canvas's, or draw
into the caller's pass, after the bloom's record.
@param ― options.source the picture, rendered or a texture, read at every draw
@param ― options.region the part of the source that holds the picture, read at every draw
@param ― options.glow a bloom, or a glow of your own, added before tone mapping
@param ― options.exposure an adapted exposure, read on the GPU
@returns ― a final pass you draw every frame
create(
root: TgpuRoot
root,{
Options.format: GPUTextureFormat
Sets the output format, such as the canvas format.
format:
surface:targets.Surface
surface.
Surface.format: GPUTextureFormat
Reports the format of its textures, which pipelines that draw into it target.
format,
Options.source: Source
Provides the picture at any size: a rendered picture, such as aa or blur, or a function
returning a texture, such as () => screen.textures.hdr. draw reads it on every call, so
the texture can be rebuilt.
@cpu
source:
constaa:taa.Taa
aa,
Options.glow?: Rendered |undefined
Adds a bloom, or a glow of your own such as an emission target, before tone mapping. draw
reads its output and region on every call. Default none.
Grades or tints the colour after tone mapping and before the vignette, encoding and dither.
It receives the colour and output UV coordinates from 0 to 1. Read other pixels with
finish.picture(uv) and glow with finish.glow(uv). Default none.
@gpu
grade:
constdusk:(color:d.v3f,_uv:d.v2f)=>d.v3f
Cools the shadows and warms the lights after the tone curve.
dusk});
TAA reprojects last frame’s picture by the camera’s motion and the scene’s depth, so its depth target is sampled. Props that hold still need nothing more.
Props that move need motion of their own. Give the scene a motion: taa.motion target, TAA its texture as motion, and the moving set history: true.
The bloom spreads only light above its threshold, 1 by default. A lit wall stays below it, and a lantern’s glass at emission 6 glows.
grade runs inside the final pass, after the , on colours in display range. See grading.
The look adds each renderer to the three passes that draw it. It records the shadow, the prepass and the occlusion before shading. Then it records TAA, bloom and the final pass in that order. Inside createLook, after the final pass:
/** Draws `renderer` in the prepass, the sun's shadow and the scene. */
functionadd(renderer:instances.Renderer):void
Draws renderer in the prepass, the sun's shadow and the scene.
add(
renderer:instances.Renderer
renderer:
import instances
instances.
interfaceRenderer
This renderer draws a set into pass descriptions. Add it to a colour description with
scene.add(renderer) or a depth-only description with light.shadow.add(renderer). Each
description builds pipelines for its camera and, with cull, keeps its own visibility list.
A renderer draws the meshes that have instances, in the order they gained them: without
culling one direct draw each, with culling one indirect draw each. Render bundles also draw
indirectly so replay reads live instance counts. A bundle draws the meshes that had instances
when it was recorded; record it again after a mesh without instances gains one, and once a
model's ready resolves. Meshes with
the same back-face, alpha-mask and texture settings share pipelines. Indirect draws without
indirect-first-instance use a pipeline of their own that reads the mesh from a bind group, or
one per mesh where the pipeline has no group left.
Renderer){
constshapes:passes.Drawn[]
shapes.
Array<Drawn>.push(...items: passes.Drawn[]): number
Appends new elements to the end of an array, and returns the new length of the array.
@param ― items New elements to add to the array.
push(
constprepass:passes.Description<{
readonly depth:typeofpasses.depth;
}>
prepass.
Into<{ readonly depth:typeof depth;}>.add<{
color:d.v4f;
},{
position:d.v4f;
world:d.v3f;
normal:d.v3f;
uv:d.v2f;
uv1:d.v2f;
row:number;
}>(drawing:passes.Compound<{
color:d.v4f;
},{
position:d.v4f;
world:d.v3f;
normal:d.v3f;
uv:d.v2f;
uv1:d.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.
add(
renderer:instances.Renderer
renderer));
constcasters:passes.Drawn[]
casters.
Array<Drawn>.push(...items: passes.Drawn[]): number
Appends new elements to the end of an array, and returns the new length of the array.
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(
renderer:instances.Renderer
renderer));
},
/** Applies `stages` to TAA and the final pass, which keep their own state. */
functionapply():void
Applies stages to TAA and the final pass, which keep their own state.
apply(){
constaa:taa.Taa
aa.
Taa.enable(on: boolean): void
Enables or disables TAA. When disabled, jitter is zero from the next frame, record records
nothing and output returns the source. Enabling it again resets history.
enable(
conststages:Stages
The stages that run, read every frame. Call apply after changing taa or bloom.
stages.
Stages.taa: boolean
taa);
constfinal:finish.Finish
final.
Finish.settings: TgpuUniform<d.WgslStruct<{
exposure:d.F32;
vignette:d.F32;
dither:d.F32;
glowIntensity:d.F32;
}>>
Holds defaults with overrides from settings. Use patch to upload only the fields you
supply.
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
Rebuilds all textures if the source size changed, destroying the old textures first. Updates
regions for the current resolution. Returns true after a rebuild so callers can update bind
groups that hold old textures. Call before recording passes that use the targets. A rebuild
that throws destroys what it made and leaves the set unfitted, so the next call rebuilds it.
Rebuilds all textures if the source size changed, destroying the old textures first. Updates
regions for the current resolution. Returns true after a rebuild so callers can update bind
groups that hold old textures. Call before recording passes that use the targets. A rebuild
that throws destroys what it made and leaves the set unfitted, so the next call rebuilds it.
Clears the map in a depth pass per cascade that redraw picks and draws the casters built by
add. Call this while recording each frame, before drawing shaded surfaces. When disabled, it
draws nothing and makes every point sunlit. A frame that draws no cascade writes a timer's
timestamps from an empty compute pass.
record(
frame: Frame
frame,
constcasters:passes.Drawn[]
casters);// a depth pass per cascade
if(
conststages:Stages
The stages that run, read every frame. Call apply after changing taa or bloom.
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.
Records the trace and the denoise after the pass that draws depth, before the passes that
shade, into a frame's encoder, read at the call, or into an encoder. Optional timer writes
measure both passes. When disabled, it writes no timestamps, so use a profiler timer around
it only while enabled is true.
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.
Records the resolve after source and motion passes, then sets jitter for the next frame.
Records nothing while disabled. Optional timer writes measure the resolve. Given a frame, a
resolve that never submits leaves the history as it was.
record(
frame: Frame
frame);
if(
conststages:Stages
The stages that run, read every frame. Call apply after changing taa or bloom.
Opens a pass on view, such as surface.view(frame), draws into it and ends it. A
viewport draws the picture into that rectangle and clears the rest, transparent with
alpha: 'premultiplied' and black otherwise. Optional timer writes measure the pass.
record(
frame: Frame
frame,
surface:targets.Surface
surface.
Surface.view(frame: Frame): GPUTextureView
Returns a view of the current texture, created once per texture. React Native requires the
frame to present after submission.
Destroys drawings added to this description or descriptions derived with pipe, without and
instead. Frees resources that compound drawings built for them, such as lists of visible
objects. Keeps the caller's targets alive. When a drawing throws, destroys the rest, then
throws its error, or an AggregateError of all of them with the first one's message.
Destroys drawings added to this description or descriptions derived with pipe, without and
instead. Frees resources that compound drawings built for them, such as lists of visible
objects. Keeps the caller's targets alive. When a drawing throws, destroys the rest, then
throws its error, or an AggregateError of all of them with the first one's message.
initAsync lists the and whose pipelines it compiles. destroy frees their , buffers and . Each description frees the drawings added to it, and the lighting frees its shadow casters.
scene.ts composes the parts. It owns the camera, hands it to the look, and adds the props’ renderer:
scene.ts
import{
import cameras
cameras,
import pipelines
pipelines,type
(alias)interfaceFrame
importFrame
Represents one frame being recorded. Each run creates a separate object, so modules can
compare frames by identity.
Frame,type
import gltf
gltf,type
(alias)interfaceSurface
importSurface
Provides a destination for frames, such as a canvas from web.surface or native.surface, or a
texture from offscreenSurface in a test. Pass the frame to view for code that works with
every destination.
Construct a type with a set of properties K of type T
Record<string,
import gltf
gltf.
interfaceModelData<Nameextendsstring=never>
This type contains binary glTF data as arrays ready for meshPool.add. Materials, textures and
samplers hold every field, with glTF defaults for omitted values.
ModelData>>;
readonly
SceneOptions.placements: readonly Placement[]
placements:readonly
(alias)interfacePlacement
importPlacement
A piece of the scene: a model by name, and its row's values.
Provides a destination for frames, such as a canvas from web.surface or native.surface, or a
texture from offscreenSurface in a test. Pass the frame to view for code that works with
every destination.
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
A game adds its own parts beside the props, such as a picker for the piece under the pointer or lines for a selection outline. Record the picker in a compute pass. To draw the outline with the props, add the line drawing to the scene description in createLook. To draw it over the finished picture, add it to a separate pass description, record that after look.record and load the canvas colour.
Shadows draw every caster once per cascade. The map’s 2048-texel layers take 8 MB each in the default depth16unorm, and filter: 9 takes nine comparisons per shaded pixel. One cascade suits a view that shows a small board from one height.
Occlusion draws every solid prop again into the half-resolution prepass, then traces and denoises at half resolution, a quarter of the pixels.
TAA takes one full-screen pass and two rgba16float history textures. FXAA costs one pass on the finished 8-bit picture and keeps no history. It smooths steps in a still frame but leaves thin parts shimmering as the view turns. Prefer it on the weakest phones.
Bloom draws six levels down and five up, each half the size of the one before.
The final pass tone maps, adds the glow and grades in one full-screen pass.
A stage turns off without rebuilding anything. The look reads its stages every frame. It switches the shadow and the occlusion through their enabled options, and turns off the prepass and the bloom by skipping their recording. TAA and the glow keep state of their own, so apply passes a change to them through aa.enable and the final pass’s glowIntensity. The figure above is this look, with buttons that flip its stages.
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 →
instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
rowA row is one object's values in a buffer, such as one enemy, one particle or one light.Objects are rows in buffers →
rendererA renderer draws one sort of thing, such as instances or particles, by handing a pass description a drawing.Every renderer is a drawing →
hookA hook is a placeholder that each pipeline fills with its own choice, such as the camera it draws through.Members and placeholders →
texelA texel is one cell of a texture, as a pixel is one cell of the screen.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 →
tone curveA tone curve maps light of any brightness into the range a screen can show, keeping detail in the bright parts.Words →
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 →
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 →
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 →