Skip to content
import
import { lighting } from '@typegpu/kit'
call
lighting.create(root, { points?, shadow?, pointShadow?, … }?) → Lightingalso fitSlices
facts
recordsencoderlifecycleinitAsync()destroy()injectshookdefinition

Copying a light loop into each fragment shader duplicates work. Lights compiled in as constants need a new pipeline whenever one moves or is added. Store the sun, sky, fog and point lights as data in a lighting. Fill it into each pipeline and call shading.shade(material, point).

Four material presets under one sun

  • matte
  • glossy
  • metal
  • glow
Try Lower roughness to shrink and brighten highlights. Select lambert to remove highlights and give even metals diffuse lighting.
import {
import lighting
lighting
,
import materials
materials
,
import shading
shading
,
import table
table
} from '@typegpu/kit';
const
const lamps: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>
lamps
=
import table
table
.
function create<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>(root: TgpuRoot, def: table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>, options: table.Options<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>): table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>> (+1 overload)

Allocates GPU buffers and a CPU copy of host rows. Throws unless capacity is an integer in [1, 2^20].

@param ― def the definition its shaders were written against, from table.define

@returns ― a table you destroy

create
(
const root: TgpuRoot
root
,
import lighting
lighting
.
const PointLight: table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>
PointLight
, {
Options<T extends AnyTableDef>.capacity: number

Sets the table capacity for its lifetime. Must be an integer in [1, 2^20], with slots from 0 to capacity - 1. A row id uses enough bits for the slot and the rest for its generation. The generation has 29 bits at 8 rows and 12 bits at 2^20 rows.

capacity
: 16,
Options<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.defaults?: table.Values<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>> | undefined

Sets values for fields omitted by add. Without defaults, every field starts at zero. Default none.

defaults
: { ...
import lighting
lighting
.
const WHITE: {
readonly intensity: number;
readonly color: d.v3f;
readonly range: number;
}

Holds white, intensity 1 and range 10, for the defaults of a table of point lights, since table fields start at zero: table.create(root, lighting.PointLight, { capacity, defaults: { ...lighting.WHITE } }).

WHITE
},
});
const lamps: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>
lamps
.
Table<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.add(values?: table.Values<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>> | undefined): table.RowId<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>

Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is full, or when a value fails to write, which leaves the slot free.

add
({
position?: ArrayLike<number> | d.InferInput<d.Vec3f> | undefined
position
: [1.5, 1, 1],
color?: ArrayLike<number> | d.InferInput<d.Vec3f> | undefined

Sets the light colour in linear colour space.

color
: [1, 0.6, 0.3],
intensity?: number | undefined

Multiplies color.

intensity
: 3,
range?: number | undefined

Sets the distance in world units where light intensity reaches zero.

range
: 5 });
const
const light: lighting.Lighting
light
=
import lighting
lighting
.
function create<{
readonly settings: {
readonly sunDirection: [0.4, 1, 0.3];
readonly sunIntensity: 2;
};
readonly points: {
readonly table: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>;
};
}>(root: TgpuRoot, options?: ({
readonly settings: {
readonly sunDirection: [0.4, 1, 0.3];
readonly sunIntensity: 2;
};
readonly points: {
readonly table: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>;
};
} & lighting.Options) | undefined): lighting.Lighting

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
settings: {
readonly sunDirection: [0.4, 1, 0.3];
readonly sunIntensity: 2;
} & (Partial<d.InferInput<d.WgslStruct<{
sunDirection: d.Vec3f;
sunIntensity: d.F32;
sunColor: d.Vec3f;
skyIntensity: d.F32;
skyTop: d.Vec3f;
fogDensity: d.F32;
skyBottom: d.Vec3f;
fogFalloff: d.F32;
fogColor: d.Vec3f;
skyReflection: d.F32;
fogStart: d.F32;
}>>> | undefined)

Sets initial sun, sky and fog values over defaults. Default defaults, which has no fog.

settings
: {
sunDirection: [0.4, 1, 0.3]
sunDirection
: [0.4, 1, 0.3],
sunIntensity: 2
sunIntensity
: 2 },
points: {
readonly table: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>;
} & lighting.TablePoints

Enables point lights from a table or a function. Default none.

points
: {
table: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>> & lighting.LightTable

Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE. Flush and destroy it yourself. Default none, lights from light or spot.

table
:
const lamps: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>
lamps
},
});
const
const fragment: TgpuFragmentFn<{
world: d.Vec3f;
normal: d.Vec3f;
}, d.Vec4f>
fragment
=
const tgpu: {
const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
init: typeof import("node_modules/typegpu/core/root/init").init;
initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
... 10 more ...;
'~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
}

@module ― typegpu

tgpu
.
fragmentFn: <{
world: d.Vec3f;
normal: d.Vec3f;
}, d.Vec4f>(options: {
in: {
world: d.Vec3f;
normal: d.Vec3f;
};
out: d.Vec4f;
}) => TgpuFragmentFnShell<{
world: d.Vec3f;
normal: d.Vec3f;
}, d.Vec4f> (+1 overload)
fragmentFn
({
in: {
world: d.Vec3f;
normal: d.Vec3f;
}
in
: {
world: d.Vec3f
world
:
import d
d
.
const vec3f: d.Vec3f
vec3f
,
normal: d.Vec3f
normal
:
import d
d
.
const vec3f: d.Vec3f
vec3f
},
out: d.Vec4f
out
:
import d
d
.
const vec4f: d.Vec4f
vec4f
,
})(({
world: d.v3f
world
,
normal: d.v3f
normal
}) => {
'use gpu';
const
const brick: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
brick
=
import materials
materials
.
const glossy: (color: d.v3f, roughness: number) => {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}

Creates a dielectric with specular highlights, such as paint, plastic or wet stone.

glossy
(
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0.62, 0.24, 0.16), 0.4);
return
import d
d
.
const vec4f: d.Vec4f
(v0: AnyNumericVec3Instance, w: number) => d.v4f (+9 overloads)
vec4f
(
import shading
shading
.
const shade: (material: shading.Material, point: shading.Point) => d.v3f

Computes the final surface colour. It combines ambient light, shadowed sunlight, live point lights and emission, then applies fog. Every channel stays at or below 65 504, the largest half float. Create the pipeline from root.pipe(light.inject()) after injecting the kit camera.

shade
(
const brick: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
brick
,
import shading
shading
.
const pointAt: (position: d.v3f, normal: d.v3f) => {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}

Creates a point at position with surface normal normal, viewed from the kit camera.

pointAt
(
world: d.v3f
world
,
normal: d.v3f
normal
)), 1);
});
const
const pipeline: TgpuRenderPipeline<d.Vec4f>
pipeline
=
const root: TgpuRoot
root
.
WithBinding.pipe(transform: (cfg: Configurable) => Configurable): WithBinding
pipe
(
const view: cameras.OrbitCamera
view
.
CameraBase.inject(): Inject

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

inject
())
.
WithBinding.pipe(transform: (cfg: Configurable) => Configurable): WithBinding
pipe
(
const light: lighting.Lighting
light
.
Lighting.inject(): Inject

Fills the shading hooks and resources for pipelines created from the configuration you pipe it into.

inject
())
.
WithBinding.createRenderPipeline<{}, {}, {
world: d.Vec3f;
normal: d.Vec3f;
}, d.Vec4f>(descriptor: TgpuRenderPipeline<in Targets = never>.DescriptorBase & {
attribs?: {} | undefined;
vertex: TgpuVertexFn<{}, {
world: d.Vec3f;
normal: d.Vec3f;
}> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>);
fragment: TgpuFragmentFn<{
world: d.Vec3f;
normal: d.Vec3f;
} & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<...>) => d.v4f | (AnyAutoCustoms & Partial<...>));
targets?: TgpuColorTargetState;
}): TgpuRenderPipeline<...> (+2 overloads)
createRenderPipeline
({
vertex: TgpuVertexFn<{}, {
world: d.Vec3f;
normal: d.Vec3f;
}> | ((input: AutoVertexIn<InferGPURecord<AttribRecordToDefaultDataTypes<{}>>>) => AutoVertexOut<AnyAutoCustoms>)
vertex
,
fragment: TgpuFragmentFn<{
world: d.Vec3f;
normal: d.Vec3f;
} & Record<string, AnyFragmentInputBuiltin>, d.Vec4f> | ((input: AutoFragmentIn<InferGPURecord<{
world: d.Vec3f;
normal: d.Vec3f;
}>>) => d.v4f | (AnyAutoCustoms & Partial<InferGPURecord<{
readonly $fragDepth: import("node_modules/typegpu/builtin").BuiltinFragDepth;
readonly $sampleMask: import("node_modules/typegpu/builtin").BuiltinSampleMask;
}>>))
fragment
,
targets?: TgpuColorTargetState
targets
: {
format?: GPUTextureFormat | undefined

The

GPUTextureFormat

of this color target. The pipeline will only be compatible with

GPURenderPassEncoder

s which use a

GPUTextureView

of this format in the corresponding color attachment.

@default ― navigator.gpu.getPreferredCanvasFormat()

format
: 'rgba16float' } });
import frames
frames
.
function animate(loop: Pick<frames.Frames, "run"> & Partial<Pick<frames.Frames, "seconds">>, options?: frames.AnimateOptions): frames.Animation
export animate

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

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

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

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

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

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

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const lamps: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>
lamps
.
Table<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.flush(target?: frames.Frame | TgpuCommandEncoder): void

Uploads changes since the last flush with queue.writeBuffer. Writes reach the queue before the next submit. Call once per frame before passes that read the table. A HistoryTable takes the frame or its encoder and throws without one.

flush
(); // uploads lamps changed since the last frame
// Record passes here
}),
);
  • What shade adds shade sums ambient sky light, sunlight past its shadow, live point lights and emission, and applies fog last. The result is linear and can exceed 1 for bloom and tone mapping. Every channel stays at or below 65 504, the largest half float.
  • The camera shading.pointAt reads the kit’s cameras.current to find the direction toward the eye. Fill the camera into the pipeline too.
  • Cost A lighting without a shadow or point lights holds only its settings uniform. Shading a surface of your own, such as a raymarched field, then takes one small buffer.
  • Other light Light from a panorama or a sky goes through the ambient as an environment. Supply other baked or changing light through it too. See Light from textures.
  • Units Intensity 1 lights a white matte surface facing the light to about 1, with no exposure, so daylight and lamps share units. The kit’s lights leave out the 1/π factor. Divide intensities taken from a that keeps it by π.
import
import { materials } from '@typegpu/kit'
GPU functions
matteglossymetalglowuvOftexturedand 3 more
facts
readsmeshPool

A material uses glTF’s metallic-roughness model, with , roughness, metallic factor, emission and occlusion. Presets run on the CPU as well as the GPU.

Preset
matte(color) Diffuse reflection for chalk, clay and cloth.
glossy(color, roughness) A dielectric with a highlight, such as paint, plastic or wet stone.
metal(color, roughness) Tints its reflections and has no diffuse colour.
glow(color, strength) Gives off strength times color, and reflects almost nothing.

Make a material with a preset, then assign the fields you change:

const
const ember: (heat: number) => {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
ember
= (
heat: number
heat
: number) => {
'use gpu';
const
const lit: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
lit
=
import materials
materials
.
const matte: (color: d.v3f) => {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}

Creates a diffuse material, such as chalk, clay or cloth.

matte
(
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0.3, 0.1, 0.05));
const lit: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
lit
.
emission: d.v3f

Sets the emitted light in linear colour space. Shading adds it after lighting.

emission
=
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(1, 0.4, 0.1) *
heat: number
heat
;
return
const lit: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
lit
;
};
  • Struct literals Build a shading.Material and a shading.Point this way, never with a struct literal such as shading.Material({ color, roughness, … }). Both structs gain fields only at their end, and each added field does nothing at zero. A literal stops compiling when a field is added. Copy one you were given with shading.Material(m) or shading.Point(p) before assigning to it.
  • Screen colours Convert screen colours to linear light first with srgbToLinear from @typegpu/color.
  • Occlusion occlusion is the share of ambient light that reaches the surface, from 0 in a crevice to 1 in the open. hemisphere and an environment’s ambient apply it; presets set 1.
  • The point A shading.Point gives the shading position in world space, unit normal and view toward the eye, and uv and uv1 coordinates, the second from a mesh’s uvs1. shading.pointAt(position, normal) normalizes the normal and sets uv and uv1 to zero, and shading.Point() is all zeros. An ’s material function receives mesh UV coordinates.
  • Model textures Apply model textures with materials.textured, mappedNormal and masked. textured reads occlusion from the red channel of glTF’s occlusion texture. See mesh-pool textures.
  • Small highlights A smooth surface’s highlight can be smaller than a pixel and sparkle as it moves. materials.antialiased(material, normal) widens roughness where the normal turns within a pixel. Kit renderers apply it unless their specularAntialiasing option is false; call it in your own fragment shaders.

Point lights ride balls that one kernel moves

Try Change range to set where light falls to zero. Each ball carries a row of a lighting.MovingPointLight table, and one kernel moves balls and lights without CPU position writes.

points reads lights from a table you own or from a function. Without points, the shader has no point-light loop. A ’s fields start at zero, so give it lighting.WHITE as defaults: white, intensity 1 and range 10.

const
const lamps: table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
=
import table
table
.
function create<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>(root: TgpuRoot, def: table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>, options: table.Options<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>): table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> (+1 overload)

Allocates GPU buffers and a CPU copy of host rows. Throws unless capacity is an integer in [1, 2^20].

@param ― def the definition its shaders were written against, from table.define

@returns ― a table you destroy

create
(
const root: TgpuRoot
root
,
import lighting
lighting
.
const PointLight: table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>
PointLight
, {
Options<T extends AnyTableDef>.capacity: number

Sets the table capacity for its lifetime. Must be an integer in [1, 2^20], with slots from 0 to capacity - 1. A row id uses enough bits for the slot and the rest for its generation. The generation has 29 bits at 8 rows and 12 bits at 2^20 rows.

capacity
: 16,
Options<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.defaults?: table.Values<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> | undefined

Sets values for fields omitted by add. Without defaults, every field starts at zero. Default none.

defaults
: { ...
import lighting
lighting
.
const WHITE: {
readonly intensity: number;
readonly color: v3f;
readonly range: number;
}

Holds white, intensity 1 and range 10, for the defaults of a table of point lights, since table fields start at zero: table.create(root, lighting.PointLight, { capacity, defaults: { ...lighting.WHITE } }).

WHITE
},
});
const
const light: lighting.Lighting
light
=
import lighting
lighting
.
function create<{
readonly points: {
readonly table: table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
}>(root: TgpuRoot, options?: ({
readonly points: {
readonly table: table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
} & lighting.Options) | undefined): lighting.Lighting

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
points: {
readonly table: table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
} & lighting.TablePoints

Enables point lights from a table or a function. Default none.

points
: {
table: table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> & lighting.LightTable

Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE. Flush and destroy it yourself. Default none, lights from light or spot.

table
:
const lamps: table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
} });
const
const torch: table.RowId<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
torch
=
const lamps: table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.add(values?: table.Values<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> | undefined): table.RowId<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>

Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is full, or when a value fails to write, which leaves the slot free.

add
({
position?: ArrayLike<number> | InferInput<Vec3f> | undefined
position
: [0, 2, 0],
color?: ArrayLike<number> | InferInput<Vec3f> | undefined

Sets the light colour in linear colour space.

color
: [1, 0.55, 0.2],
intensity?: number | undefined

Multiplies color.

intensity
: 4 });
const lamps: table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.fields: table.Fields<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>

Provides one handle per field. Keep a handle outside a loop instead of reading fields.x inside it.

fields
.
position: table.HostField<Vec3f, table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
position
.
function set(id: table.RowId<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>, x: number, y: number, z: number): void
set
(
const torch: table.RowId<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
torch
, 0.5, 2, 0);
const lamps: table.Table<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.remove(id: table.RowId<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>): void

Frees the row slot and makes its id stale.

remove
(
const torch: table.RowId<table.TableDef<"PointLight", {
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
torch
);
  • Call lamps.flush() each before shading. and destroy the table yourself.
  • A light falls off with the inverse square of distance, eased to zero at range.
  • shading.falloff and shading.beam run on the CPU as well as in shaders. Code outside shaders then gets the same numbers as the GPU for how much of a light reaches a point, before shadows.

A table of lighting.MovingPointLight keeps positions on the GPU for to write. The balls in the figure use this. A kernel writes them through lamps.gpu, and the CPU finds with lamps.slotOf(id).

const {
const MovingPointLight: table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>

This point-light table stores positions in a device field. Kernels write positions through MovingPointLight.device.$[slot].position.

MovingPointLight
} =
import lighting
lighting
;
const
const lamps: table.Table<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>
lamps
=
import table
table
.
function create<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>(root: TgpuRoot, def: table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>, options: table.Options<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>): table.Table<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>> (+1 overload)

Allocates GPU buffers and a CPU copy of host rows. Throws unless capacity is an integer in [1, 2^20].

@param ― def the definition its shaders were written against, from table.define

@returns ― a table you destroy

create
(
const root: TgpuRoot
root
,
const MovingPointLight: table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>

This point-light table stores positions in a device field. Kernels write positions through MovingPointLight.device.$[slot].position.

MovingPointLight
, {
Options<T extends AnyTableDef>.capacity: number

Sets the table capacity for its lifetime. Must be an integer in [1, 2^20], with slots from 0 to capacity - 1. A row id uses enough bits for the slot and the rest for its generation. The generation has 29 bits at 8 rows and 12 bits at 2^20 rows.

capacity
: 64,
Options<TableDef<"MovingPointLight", { range: F32; color: Vec3f; intensity: F32; }, { position: Vec3f; }>>.defaults?: table.Values<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>> | undefined

Sets values for fields omitted by add. Without defaults, every field starts at zero. Default none.

defaults
: { ...
import lighting
lighting
.
const WHITE: {
readonly intensity: number;
readonly color: d.v3f;
readonly range: number;
}

Holds white, intensity 1 and range 10, for the defaults of a table of point lights, since table fields start at zero: table.create(root, lighting.PointLight, { capacity, defaults: { ...lighting.WHITE } }).

WHITE
},
});
const
const light: lighting.Lighting
light
=
import lighting
lighting
.
function create<{
readonly points: {
readonly table: table.Table<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>;
};
}>(root: TgpuRoot, options?: ({
readonly points: {
readonly table: table.Table<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>;
};
} & lighting.Options) | undefined): lighting.Lighting

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
points: {
readonly table: table.Table<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>;
} & lighting.TablePoints

Enables point lights from a table or a function. Default none.

points
: {
table: table.Table<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>> & lighting.LightTable

Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE. Flush and destroy it yourself. Default none, lights from light or spot.

table
:
const lamps: table.Table<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>
lamps
} });
const
const circle: TgpuComputeFn<{
id: d.BuiltinGlobalInvocationId;
}>
circle
=
const tgpu: {
const: typeof import("node_modules/typegpu/core/constant/tgpuConstant").constant;
fn: typeof import("node_modules/typegpu/core/function/tgpuFn").fn;
comptime: typeof import("node_modules/typegpu/core/function/comptime").comptime;
resolve: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolve;
resolveWithContext: typeof import("node_modules/typegpu/core/resolve/tgpuResolve").resolveWithContext;
init: typeof import("node_modules/typegpu/core/root/init").init;
initFromDevice: typeof import("node_modules/typegpu/core/root/init").initFromDevice;
slot: typeof import("node_modules/typegpu/core/slot/slot").slot;
lazy: typeof import("node_modules/typegpu/core/slot/lazy").lazy;
... 10 more ...;
'~unstable': typeof import("node_modules/typegpu/tgpuUnstable");
}

@module ― typegpu

tgpu
.
computeFn: <{
id: d.BuiltinGlobalInvocationId;
}>(options: {
in: {
id: d.BuiltinGlobalInvocationId;
};
workgroupSize: number[];
}) => TgpuComputeFnShell<{
id: d.BuiltinGlobalInvocationId;
}> (+1 overload)
computeFn
({
workgroupSize: number[]
workgroupSize
: [64],
in: {
id: d.BuiltinGlobalInvocationId;
}
in
: {
id: d.BuiltinGlobalInvocationId
id
:
import d
d
.
const builtin: {
readonly vertexIndex: d.BuiltinVertexIndex;
readonly instanceIndex: d.BuiltinInstanceIndex;
readonly clipDistances: d.BuiltinClipDistances;
readonly position: d.BuiltinPosition;
readonly frontFacing: d.BuiltinFrontFacing;
readonly fragDepth: d.BuiltinFragDepth;
readonly primitiveIndex: d.BuiltinPrimitiveIndex;
readonly sampleIndex: d.BuiltinSampleIndex;
... 11 more ...;
readonly numSubgroups: d.BuiltinNumSubgroups;
}
export builtin
builtin
.
globalInvocationId: d.BuiltinGlobalInvocationId
globalInvocationId
} })(({
id: d.v3u
id
,
}) => {
'use gpu';
if (
id: d.v3u
id
.
v3u.x: number
x
>=
const lamps: table.Table<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>
lamps
.
Table<TableDef<"MovingPointLight", { range: F32; color: Vec3f; intensity: F32; }, { position: Vec3f; }>>.gpu: GpuMembers<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>

Provides the definition's shader members bound to this table, such as reds.gpu.position(i) and reds.gpu.device.$[i]. A shader reads several tables of one definition through their gpu members, with nothing piped.

gpu
.
span: TgpuGenericFn
() => number

Returns the highest live slot plus one.

span
()) return;
const
const angle: number
angle
=
const time: TgpuUniform<d.F32>
time
.
TgpuUniform<F32>.$: number
$
+
import d
d
.
function f32(v?: number | boolean): number
export f32

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

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

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

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

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

f32
(
id: d.v3u
id
.
v3u.x: number
x
);
const lamps: table.Table<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>
lamps
.
Table<TableDef<"MovingPointLight", { range: F32; color: Vec3f; intensity: F32; }, { position: Vec3f; }>>.gpu: GpuMembers<table.TableDef<"MovingPointLight", {
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {
position: d.Vec3f;
}>>

Provides the definition's shader members bound to this table, such as reds.gpu.position(i) and reds.gpu.device.$[i]. A shader reads several tables of one definition through their gpu members, with nothing piped.

gpu
.
device: TgpuAccessor<table.Rows<{
position: d.Vec3f;
}>>

Provides GPU-written rows with read-write access in compute pipelines and read-only access in render pipelines.

device
.
TgpuAccessor<Rows<{ position: Vec3f; }>>.$: {
position: d.v3f;
}[]
$
[
id: d.v3u
id
.
v3u.x: number
x
].
position: d.v3f
position
=
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(
import std
std
.
function cos(value: number): number (+1 overload)
export cos
cos
(
const angle: number
angle
) * 4, 2,
import std
std
.
function sin(value: number): number (+1 overload)
export sin
sin
(
const angle: number
angle
) * 4);
});
const
const circling: TgpuComputePipeline
circling
=
const root: TgpuRoot
root
.
WithBinding.createComputePipeline<{
id: d.BuiltinGlobalInvocationId;
}>(descriptor: TgpuComputePipeline.Descriptor<{
id: d.BuiltinGlobalInvocationId;
}>): TgpuComputePipeline
createComputePipeline
({
compute: TgpuComputeFn<{
id: d.BuiltinGlobalInvocationId;
}>
compute
:
const circle: TgpuComputeFn<{
id: d.BuiltinGlobalInvocationId;
}>
circle
});
  • A position supplied to add or write overwrites the kernel’s. Colour and intensity updates leave it unchanged.
  • The CPU can’t read a moving light’s position back.
fireworksFireworks over a castle lake. Every burst lights up everything around it.
Click the sky to launch a shell, change the rate, or lower burst light. Each flash lights the castle and the smoke, and the lake reflects it; the readout counts live lights.

If another buffer already stores lights, supply points.light, a 'use gpu' function that returns a lighting.Light per slot, and count, the slots to visit. A range of 0 disables a slot. Use pipe to fill its dependencies. These flashes read their particles directly without a table or copy:

const
const lightOf: (slot: number) => {
position: d.v3f;
range: number;
color: d.v3f;
intensity: number;
}
lightOf
= (
slot: number
slot
: number) => {
'use gpu';
const
const flash: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
flash
=
const flashes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
flashes
.
Particles<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.particle: (i: number) => {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}

Reads the particle in slot i, which must be below span.

particle
(
slot: number
slot
);
return
import lighting
lighting
.
function Light(props?: {
position: d.v3f;
range: number;
color: d.v3f;
intensity: number;
} | undefined): {
position: d.v3f;
range: number;
color: d.v3f;
intensity: number;
}
export Light

This schema holds a point light with a position, range, linear colour and intensity.

Light
({
position: d.v3f
position
:
const flash: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
flash
.
position: d.v3f
position
,
range: number

Sets the distance in world units where light intensity reaches zero.

range
:
import std
std
.
function select(f: number, t: number, cond: boolean): number (+2 overloads)
export select

Returns t if cond is true, and f otherwise. Component-wise if cond is a vector.

@example select(1, 2, false) // returns 1 select(1, 2, true) // returns 2 select(vec2i(1, 2), vec2i(3, 4), true) // returns vec2i(3, 4) select(vec2i(1, 2), vec2i(3, 4), vec2b(false, true)) // returns vec2i(1, 4)

select
(
import d
d
.
function f32(v?: number | boolean): number
export f32

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

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

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

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

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

f32
(0), 320,
const flashes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
flashes
.
System.alive: (i: number) => boolean

Returns whether slot i is alive, in any shader.

alive
(
slot: number
slot
)),
color: d.v3f

Sets the light colour in linear colour space.

color
:
const flash: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
flash
.
color: d.v4f

Holds linear colour with opacity in w.

color
.
xyz: d.v3f
xyz
,
intensity: number

Multiplies color.

intensity
:
import std
std
.
function exp(value: number): number (+1 overload)
export exp
exp
(-
const flash: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
flash
.
age: number

Holds particle age in seconds.

age
* 3) *
const flash: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
flash
.
size: number

Sets the particle width in world units.

size
*
const flash: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
flash
.
size: number

Sets the particle width in world units.

size
,
});
};
const
const light: lighting.Lighting
light
=
import lighting
lighting
.
function create<{
readonly points: {
readonly light: (slot: number) => {
position: d.v3f;
range: number;
color: d.v3f;
intensity: number;
};
readonly count: number;
};
}>(root: TgpuRoot, options?: ({
readonly points: {
readonly light: (slot: number) => {
position: d.v3f;
range: number;
color: d.v3f;
intensity: number;
};
readonly count: number;
};
} & lighting.Options) | undefined): lighting.Lighting

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
points: {
readonly light: (slot: number) => {
position: d.v3f;
range: number;
color: d.v3f;
intensity: number;
};
readonly count: number;
} & lighting.LightPoints

Enables point lights from a table or a function. Default none.

points
: {
light: ((slot: number) => {
position: d.v3f;
range: number;
color: d.v3f;
intensity: number;
}) & ((slot: number) => lighting.Light)

Returns the light at a slot. Default none, lights from table or spot.

@gpu

light
:
const lightOf: (slot: number) => {
position: d.v3f;
range: number;
color: d.v3f;
intensity: number;
}
lightOf
,
count: number

Sets how many slots, from 0, every lit point visits. Required unless candidates names them. A light with range 0 lights nothing. Default none, the slots candidates names.

count
:
const flashes: particles.Particles<d.WgslStruct<{
position: d.Vec3f;
age: d.F32;
velocity: d.Vec3f;
life: d.F32;
color: d.Vec4f;
size: d.F32;
seed: d.F32;
}>>
flashes
.
System.span: number

Gives the dispatch range for kernels over the pool. It includes every slot because any slot can hold a particle and the CPU does not track live slots.

span
},
});

To light particles in a kernel, such as the smoke beside the flashes, call shading.incoming(position) in a pipeline filled with light.inject(). It returns the light arriving at the position from every direction. That light is the sun past its shadow, each point light through attenuation, and the mean sky. Multiply a colour by it.

To light them by the point lights without the sun, fill shading.sunShadow with 0 on their pipeline alone. The fireworks’ smoke shows only in the bursts’ light this way, while the moon still lights the lake:

const
const sunless: shading.SunShadowHook
sunless
:
import shading
shading
.
type SunShadowHook = (point: shading.Point) => number

Returns the share of sunlight that reaches a point, as sunShadowed does. A value of 0 means full shadow and 1 means full light. Values above 1 can model focused light.

SunShadowHook
= () => {
'use gpu';
return
import d
d
.
function f32(v?: number | boolean): number
export f32

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@returns ― a system you destroy

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

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

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

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

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

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

step
,
Options<WgslStruct<{ position: Vec3f; age: F32; velocity: Vec3f; life: F32; color: Vec4f; size: F32; seed: F32; }>>.update?: ((particle: NoInfer<{
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}>, dt: number, slot: number) => NoInfer<{
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}>) | undefined

Updates every live particle at the start of each step, including its first, before gravity, drag and motion. dt is the step duration in seconds. Use the slot for related data, such as pushing a trail point. Return the particle to keep, or set life to 0 to end it. The step kernel binds 1 storage buffer, the pool, so update and died share the other 7 of a stage. Default none, which leaves it unchanged.

@gpu

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

@module ― typegpu

tgpu
.
fn: <(puff: Particle) => {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}>(inner: (puff: Particle) => {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}) => TgpuGenericFn<(puff: Particle) => {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}> (+2 overloads)
fn
((
puff: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
puff
:
type Particle = {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}

This type describes a particle in shaders.

Particle
) => {
'use gpu';
let
let next: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
next
=
function Particle(props?: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
} | undefined): {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}

This type describes a particle in shaders.

Particle
(
puff: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
puff
);
let next: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
next
.
color: d.v4f

Holds linear colour with opacity in w.

color
=
import d
d
.
const vec4f: d.Vec4f
(v0: AnyNumericVec3Instance, w: number) => d.v4f (+9 overloads)
vec4f
(
import shading
shading
.
const incoming: (position: d.v3f) => d.v3f

Returns the light arriving at position from every direction, for a particle or a volume lit the same from all sides: the sun through sunShadow, each point light through attenuation, and the mean of the sky and ground colours. Multiply a colour by it. Hooks receive a point with a zero normal and view, so a lift along the normal does nothing. It runs in any stage, kernels included, of a pipeline filled with light.inject(). Fill sunShadow with 0 on that pipeline to leave the sun out.

incoming
(
puff: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
puff
.
position: d.v3f
position
) * 0.6,
puff: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
puff
.
color: d.v4f

Holds linear colour with opacity in w.

color
.
v4f.w: number
w
);
return
let next: {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}
next
;
})
.
TgpuGenericFn<(puff: Particle) => { position: v3f; age: number; velocity: v3f; life: number; color: v4f; size: number; seed: number; }>.pipe(transform: (cfg: Configurable) => Configurable): TgpuGenericFn<(puff: Particle) => {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}>

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

pipe
(
const light: lighting.Lighting
light
.
Lighting.inject(): Inject

Fills the shading hooks and resources for pipelines created from the configuration you pipe it into.

inject
())
.
Withable<TgpuGenericFn<(puff: Particle) => { position: v3f; age: number; velocity: v3f; life: number; color: v4f; size: number; seed: number; }>>.with<shading.SunShadowHook>(slot: TgpuSlot<shading.SunShadowHook>, value: Eventual<shading.SunShadowHook>): TgpuGenericFn<(puff: Particle) => {
position: d.v3f;
age: number;
velocity: d.v3f;
life: number;
color: d.v4f;
size: number;
seed: number;
}> (+2 overloads)
with
(
import shading
shading
.
const sunShadow: TgpuSlot<shading.SunShadowHook>
sunShadow
,
const sunless: shading.SunShadowHook
sunless
),
});

The mean sky still arrives, as skyIntensity sets it.

Every lit pixel visits each light slot, up to a table’s highest live slot or the count slots of a function. Out-of-range lights still cost loads and a distance test, so size tables to the lights you use. If many lights each cover a small area, supply points.candidates to visit only slots that may reach the point.

A neighbour grid with sight at least the longest light range finds nearby lamps in 27 cells:

const
const lamps: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>
lamps
=
import table
table
.
function create<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>(root: TgpuRoot, def: table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>, options: table.Options<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>): table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>> (+1 overload)

Allocates GPU buffers and a CPU copy of host rows. Throws unless capacity is an integer in [1, 2^20].

@param ― def the definition its shaders were written against, from table.define

@returns ― a table you destroy

create
(
const root: TgpuRoot
root
,
import lighting
lighting
.
const PointLight: table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>
PointLight
, {
Options<T extends AnyTableDef>.capacity: number

Sets the table capacity for its lifetime. Must be an integer in [1, 2^20], with slots from 0 to capacity - 1. A row id uses enough bits for the slot and the rest for its generation. The generation has 29 bits at 8 rows and 12 bits at 2^20 rows.

capacity
: 64,
Options<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.defaults?: table.Values<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>> | undefined

Sets values for fields omitted by add. Without defaults, every field starts at zero. Default none.

defaults
: { ...
import lighting
lighting
.
const WHITE: {
readonly intensity: number;
readonly color: d.v3f;
readonly range: number;
}

Holds white, intensity 1 and range 10, for the defaults of a table of point lights, since table fields start at zero: table.create(root, lighting.PointLight, { capacity, defaults: { ...lighting.WHITE } }).

WHITE
,
color?: ArrayLike<number> | d.InferInput<d.Vec3f> | undefined

Sets the light colour in linear colour space.

color
: [1, 0.8, 0.6],
range?: number | undefined

Sets the distance in world units where light intensity reaches zero.

range
: 8 },
});
const
const cells: grid.Grid<never>
cells
=
import grid
grid
.
function create<never>(root: TgpuRoot, options: grid.Options<never>): grid.Grid<never>

Creates a grid that sorts items by cell so kernels can find nearby items. Walks visit the home cell first and choose directions at random, for boids, crowds or collisions. Throws unless sight is above 0, and when the capacity, 64 to a workgroup, needs more than the device's maxComputeWorkgroupsPerDimension workgroups.

@injects ― member walk, around, range, neighbour, slot, slotAt, neighbourAt, count, holds and block, which read its own buffers in any pipeline

@binds ― 1 uniform: walk or around, the box

@binds ― 2 storage: range and neighbour or neighbourAt, each cell's sorted range and each item's copy

@binds ― 1 storage: slot or slotAt, the sorted slots

@binds ― 1 storage: count, the sorted count

@binds ― 3 storage: holds and block, which blocks hold items, the sort count and their list

@owns ― buffers, a uniform, pipelines, bind groups, a sorter with radix: each cell's sorted range, the blocks holding items, with item each item's copy in sorted order, the dispatches, the box, the binning's resources

@records ― sort in a compute pass each step, before the kernels that walk

@param ― options.sight the cell side length. A walk finds every item within this distance

@param ― options.alive tests whether a slot holds an item. It, position and itemOf need fills for the resources they read. Spread a table's rows.live() into the options to include its live test, capacity and span

@returns ― a grid you sort each step and destroy

create
(
const root: TgpuRoot
root
, {
...
const lamps: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>
lamps
.
Table<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.live(): table.Live

Returns the capacity and live test for live lists, a grid, a picker or state machines. Use liveLists.create(root, { ...coins.live(), draws }).

live
(),
GridOptions.low: d.v3f

Sets the initial lower corner of the grid box. move changes it. Items outside the box belong to the nearest cell.

low
:
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(-40, 0, -40),
GridOptions.size: d.v3f

Sets the box extent along x, y and z for the lifetime of the grid. A side within a thousandth of a cell of a whole number of cells takes that number.

size
:
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(80, 8, 80),
GridOptions.sight: number

Sets the cell side length. A walk finds every item within this distance.

sight
: 8, // must cover every lamp's range
GridOptions.position: (i: number) => d.v3f

Returns the position of item i.

@gpu

position
:
const lamps: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>
lamps
.
Table<TableDef<"PointLight", { position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.gpu: GpuMembers<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>

Provides the definition's shader members bound to this table, such as reds.gpu.position(i) and reds.gpu.device.$[i]. A shader reads several tables of one definition through their gpu members, with nothing piped.

gpu
.
position: table.Getter<d.Vec3f>
position
,
});
const
const light: lighting.Lighting
light
=
import lighting
lighting
.
function create<{
readonly points: {
readonly table: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>;
readonly candidates: grid.Candidates;
};
}>(root: TgpuRoot, options?: ({
readonly points: {
readonly table: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>;
readonly candidates: grid.Candidates;
};
} & lighting.Options) | undefined): lighting.Lighting

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
points: {
readonly table: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>;
readonly candidates: grid.Candidates;
} & lighting.TablePoints

Enables point lights from a table or a function. Default none.

points
: {
table: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>> & lighting.LightTable

Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE. Flush and destroy it yourself. Default none, lights from light or spot.

table
:
const lamps: table.Table<table.TableDef<"PointLight", {
position: d.Vec3f;
range: d.F32;
color: d.Vec3f;
intensity: d.F32;
}, {}>>
lamps
,
candidates: grid.Candidates

Limits the loop to lights that may reach each shaded point, as grid.Candidates name them. Default every live slot.

candidates
:
const cells: grid.Grid<never>
cells
.
Grid<never>.candidates(): grid.Candidates

Returns nearby ranges, for a lighting's points.candidates when the items are lights and sight covers every light range.

candidates
() },
});
  • Each frame Call lamps.flush() and then cells.sort(pass) in a compute pass before shading.
  • The candidates cells.candidates() returns nine ranges covering the surrounding cells. Its range and slot add two to each shading stage.
  • Beyond sight Lights beyond sight can be missed.
  • Repeated slots Repeating a slot in candidates adds its light twice.
  • Your own candidates Custom candidates are a grid.Candidates: ranges, a range(position, r) function returning first and count, and slot(index) to map indices to light slots. They also work with a light function. For a single list, return one range with lighting.Span({ first: 0, count }).

A spot light is a point light with a cone. A table of lighting.SpotLight gives every light an aim and a cone, so points and spots share one table, one loop and one candidate list:

import {
import lighting
lighting
,
import table
table
} from '@typegpu/kit';
const
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
=
import table
table
.
function create<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>(root: TgpuRoot, def: table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>, options: table.Options<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>): table.Table<...> (+1 overload)

Allocates GPU buffers and a CPU copy of host rows. Throws unless capacity is an integer in [1, 2^20].

@param ― def the definition its shaders were written against, from table.define

@returns ― a table you destroy

create
(
const root: TgpuRoot
root
,
import lighting
lighting
.
const SpotLight: table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>
SpotLight
, {
Options<T extends AnyTableDef>.capacity: number

Sets the table capacity for its lifetime. Must be an integer in [1, 2^20], with slots from 0 to capacity - 1. A row id uses enough bits for the slot and the rest for its generation. The generation has 29 bits at 8 rows and 12 bits at 2^20 rows.

capacity
: 32,
Options<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.defaults?: table.Values<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> | undefined

Sets values for fields omitted by add. Without defaults, every field starts at zero. Default none.

defaults
: { ...
import lighting
lighting
.
const WHITE_SPOT: {
readonly intensity: number;
readonly color: v3f;
readonly range: number;
} & {
readonly aim: v3f;
readonly cone: v2f;
}

Holds WHITE with an aim straight down and a full cone, for a table of spot lights.

WHITE_SPOT
},
});
const
const light: lighting.Lighting
light
=
import lighting
lighting
.
function create<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
}>(root: TgpuRoot, options?: ({
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
} & lighting.Options) | undefined): lighting.Lighting

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
} & lighting.TablePoints

Enables point lights from a table or a function. Default none.

points
: {
table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> & lighting.LightTable

Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE. Flush and destroy it yourself. Default none, lights from light or spot.

table
:
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
} });
const
const lamp: table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamp
=
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.add(values?: table.Values<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> | undefined): table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>

Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is full, or when a value fails to write, which leaves the slot free.

add
({
position?: ArrayLike<number> | InferInput<Vec3f> | undefined
position
: [0, 7, 3],
aim?: ArrayLike<number> | InferInput<Vec3f> | undefined

Points the cone's axis away from the light. It can have any length.

aim
: [0, -1, -0.4], // any length
cone?: ArrayLike<number> | InferInput<Vec2f> | undefined

Holds the cone's scale and offset from lighting.cone(inner, outer). The default [0, 1] lights every direction.

cone
:
import lighting
lighting
.
const cone: (inner: number, outer: number) => v2f

Returns a cone's scale and offset for a spot light's cone, from its inner and outer half-angles in radians. Light falls from full at inner to none at outer, as glTF's spot lights do. It runs on the CPU and in shaders.

cone
(0.18, 0.24), // inner and outer half-angles in radians
color?: ArrayLike<number> | InferInput<Vec3f> | undefined

Sets the light colour in linear colour space.

color
: [1, 0.92, 0.8],
intensity?: number | undefined

Multiplies color.

intensity
: 60,
range?: number | undefined

Sets the distance in world units where light intensity reaches zero.

range
: 16,
});
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.fields: table.Fields<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>

Provides one handle per field. Keep a handle outside a loop instead of reading fields.x inside it.

fields
.
aim: table.HostField<Vec3f, table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>

Points the cone's axis away from the light. It can have any length.

aim
.
function set(id: table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>, x: number, y: number, z: number): void
set
(
const lamp: table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamp
, 0.2, -1, -0.4);
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.add(values?: table.Values<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> | undefined): table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>

Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is full, or when a value fails to write, which leaves the slot free.

add
({
position?: ArrayLike<number> | InferInput<Vec3f> | undefined
position
: [4, 1, 0],
intensity?: number | undefined

Multiplies color.

intensity
: 2 }); // the default cone: a point light
  • The cone Light is full inside the inner half-angle and falls to none at the outer one, as in glTF. lighting.cone(inner, outer) stores glTF’s scale and offset, and runs on the CPU and in shaders.
  • The white spot lighting.WHITE_SPOT aims straight down with the cone [0, 1], which lights every direction.
  • Cost The loop reads a light’s aim and cone only once its range test passes.
  • Moving spots In a table of lighting.MovingSpotLight, only the position is in the device part, for kernels to write.
  • A light function points.spot takes a function that returns a lighting.Spot, a Light with aim and cone, beside count or candidates.
  • The beam shading.beam(toLight, aim, cone) gives the share of a spot light along toLight, a unit direction from the point towards the light.

light.settings is a lighting.Settings uniform containing sun, sky and fog values. patch uploads supplied fields. A moving sun can update once per frame, and the shadow follows a new sunDirection at its next record:

const
const direction: [number, number, number]
direction
: [number, number, number] = [
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

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

Returns the cosine of a number.

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

cos
(
const t: 0.6
t
),
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

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

Returns the sine of a number.

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

sin
(
const t: 0.6
t
), 0.3];
const light: lighting.LightingOf<{
readonly shadow: {};
}>
light
.
Lighting.settings: TgpuUniform<WgslStruct<{
sunDirection: Vec3f;
sunIntensity: F32;
sunColor: Vec3f;
skyIntensity: F32;
skyTop: Vec3f;
fogDensity: F32;
skyBottom: Vec3f;
fogFalloff: F32;
fogColor: Vec3f;
skyReflection: F32;
fogStart: F32;
}>>

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.

settings
.
TgpuBufferBindingBase<WgslStruct<{ sunDirection: Vec3f; sunIntensity: F32; sunColor: Vec3f; skyIntensity: F32; skyTop: Vec3f; fogDensity: F32; skyBottom: Vec3f; fogFalloff: F32; fogColor: Vec3f; skyReflection: F32; fogStart: F32; }>>.patch(data: {
sunDirection?: InferInput<Vec3f> | undefined;
sunIntensity?: number | undefined;
sunColor?: InferInput<Vec3f> | undefined;
skyIntensity?: number | undefined;
skyTop?: InferInput<Vec3f> | undefined;
fogDensity?: number | undefined;
skyBottom?: InferInput<Vec3f> | undefined;
fogFalloff?: number | undefined;
fogColor?: InferInput<Vec3f> | undefined;
skyReflection?: number | undefined;
fogStart?: number | undefined;
} | undefined): void
patch
({
sunDirection?: InferInput<Vec3f> | undefined

Points towards the sun. It can have any length; shading normalizes it.

sunDirection
:
const direction: [number, number, number]
direction
,
sunColor?: InferInput<Vec3f> | undefined

Sets the sun colour in linear colour space.

sunColor
: [1, 0.7, 0.45],
fogDensity?: number | undefined

Sets fog density per world unit at y = 0.

fogDensity
: 0.04,
fogFalloff?: number | undefined

Sets how fog density falls with height. Density falls by a factor of e every 1 / fogFalloff world units. A value of 0 gives uniform fog.

fogFalloff
: 0.3,
});

Its fields, with their values in lighting.defaults:

Field Default Sets
sunDirection [0.4, 1, 0.3] The direction towards the sun, of any length.
sunColor [1, 1, 1] The sun’s linear colour.
sunIntensity 1 A factor on sunColor.
skyTop [0.2, 0.26, 0.36] The linear colour of the sky from directly above.
skyBottom [0.06, 0.05, 0.045] The linear colour of the ground from directly below.
skyIntensity 1 A factor on skyTop and skyBottom.
skyReflection 1 A factor on sky reflections, over skyIntensity.
fogColor [0.55, 0.62, 0.7] The fog’s linear colour.
fogDensity 0 Fog per world unit at y = 0.
fogFalloff 0 How fog density falls with height.
fogStart 0 The distance from the eye, in world units, where fog begins.
  • Slider values Shaders normalize the direction and multiply colours by their intensities. Pass slider values directly.
  • Zero direction A zero direction turns the sun off and leaves the shadow where it was.
  • Time of day environment.sunAt(hour, latitude, declination) gives the sun’s direction at an hour of the day, and environment.sunColor(direction) its colour through the air.
  • Fog height fogDensity falls by a factor of e per 1 / fogFalloff units of height. A falloff of 0 gives uniform fog. Negative falloff is treated as 0.
  • Fog start fogStart keeps a near island clear while the far sea hazes.
  • Sky reflection skyReflection above 1 brightens glass and clear-plastic rims without changing matte surfaces.
  • Fixed options points, shadow, pointShadow and shading are fixed at creation.
import
import { shading } from '@typegpu/kit'
GPU functions
pointAtsettingstowardsSunfalloffbeambeamOfand 21 more
facts
readscameraslighting

shade calls five functions, which the shading options replace:

Slot Called Type Its arguments Default
shading.reflect For the sun and each point light shading.ReflectHook material, point, direction, radiance shading.pbr
shading.ambient Once, for the light from elsewhere shading.AmbientHook material, point shading.hemisphere
shading.fog Last, for the air before the eye shading.FogHook point shading.heightFog
shading.sunShadow Once, for how much sun reaches shading.SunShadowHook point shading.sunShadowed
shading.attenuation For each point light in range shading.AttenuationHook point, toLight, distance, range, slot shading.reaching
  • reflect and ambient return linear d.v3f colours. direction is a unit vector toward the light. radiance is colour times intensity and attenuation, with the shadow also applied to the sun.
  • fog returns a shading.Air: added, the light the air between the eye and the point adds, and through, the share of the point’s light it lets through, per channel. shade returns color * through + added. Water that swallows red faster than blue lets less red through.
  • sunShadow returns 0 for shadow and 1 for full sunlight. Values above 1 can represent focused light. See your own sun shadow.
  • attenuation returns the share of a light’s intensity reaching the point. The loop reads the light’s colour and calls reflect only where it is above 0. reaching multiplies shading.falloff(distance, range), shading.beamOf(toLight, slot) and, where that is above 0, shading.lampShadowed(point, toLight, distance, slot). Use slot to read data of your own, such as a flicker per light or a cookie texture.
const
const toon: shading.ReflectHook
toon
:
import shading
shading
.
type ReflectHook = (material: shading.Material, point: shading.Point, direction: d.v3f, radiance: d.v3f) => d.v3f

Computes reflection from one light direction, as pbr and lambert do.

ReflectHook
= (
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
,
direction: d.v3f
direction
,
radiance: d.v3f
radiance
) => {
'use gpu';
const
const lit: number
lit
=
import std
std
.
function step(edge: number, x: number): number (+1 overload)
export step
step
(0.3,
import std
std
.
dot<d.v3f>(lhs: d.v3f, rhs: d.v3f): number
export dot
dot
(
point: {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}
point
.
normal: d.v3f

Holds a unit surface normal.

normal
,
direction: d.v3f
direction
));
return
material: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
material
.
color: d.v3f

Sets the diffuse colour of a dielectric or the reflection colour of a metal, in linear colour space.

color
*
radiance: d.v3f
radiance
*
const lit: number
lit
;
};
const
const horizon: shading.FogHook
horizon
:
import shading
shading
.
type FogHook = (point: shading.Point) => shading.Air

Returns the air between the eye and the point, as heightFog does.

FogHook
= (
point: {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}
point
) => {
'use gpu';
const
const away: number
away
=
import std
std
.
function saturate(value: number): number (+1 overload)
export saturate
saturate
(
point: {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}
point
.
view: d.v3f

Holds a unit direction from the point towards the eye.

view
.
v3f.y: number
y
* -4 + 0.5);
const
const air: d.v3f
air
=
import std
std
.
mix<d.v3f>(e1: d.v3f, e2: d.v3f, e3: number): d.v3f (+2 overloads)
export mix
mix
(
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0.9, 0.6, 0.4),
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0.4, 0.55, 0.8),
const away: number
away
);
const
const hidden: number
hidden
=
import shading
shading
.
const haze: (point: shading.Point) => number

Returns how much of the view fog hides between the camera and the point, from 0 to 1, from the lighting's fogDensity, fogFalloff and fogStart. Density falls by a factor of e every 1 / fogFalloff world units above y = 0, and the fog begins fogStart world units from the eye. A custom fog adds a colour of its own by it and lets 1 - haze through.

haze
(
point: {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}
point
);
return
import shading
shading
.
const Air: d.WgslStruct
(props?: {
added: d.v3f;
through: d.v3f;
} | undefined) => {
added: d.v3f;
through: d.v3f;
}

This schema holds what the air between the eye and a point does to the point's light: added is the light the air adds, and through the share of the point's light it lets through, per channel. A colour c seen through it is c * through + added.

Air
({
added: d.v3f
added
:
const air: d.v3f
air
*
const hidden: number
hidden
,
through: d.v3f
through
:
import d
d
.
const vec3f: d.Vec3f
(xyz: number) => d.v3f (+5 overloads)
vec3f
(1 -
const hidden: number
hidden
) });
};
const
const light: lighting.Lighting
light
=
import lighting
lighting
.
function create<{
readonly shading: {
readonly reflect: shading.ReflectHook;
readonly fog: shading.FogHook;
};
readonly settings: {
readonly fogDensity: 0.02;
readonly fogFalloff: 0.2;
};
}>(root: TgpuRoot, options?: ({
readonly shading: {
readonly reflect: shading.ReflectHook;
readonly fog: shading.FogHook;
};
readonly settings: {
readonly fogDensity: 0.02;
readonly fogFalloff: 0.2;
};
} & lighting.Options) | undefined): lighting.Lighting

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
shading: {
readonly reflect: shading.ReflectHook;
readonly fog: shading.FogHook;
} & lighting.Shading

Sets the functions that shading.shade calls. Default pbr, hemisphere, heightFog, sunShadowed and reaching.

shading
: {
reflect: shading.ReflectHook

Computes how a surface reflects the sun and each point light. Default shading.pbr.

reflect
:
const toon: shading.ReflectHook
toon
,
fog: shading.FogHook

Gives the light the air adds between the eye and a point, and the share of the point's light it lets through. Default shading.heightFog.

fog
:
const horizon: shading.FogHook
horizon
},
settings: {
readonly fogDensity: 0.02;
readonly fogFalloff: 0.2;
} & (Partial<d.InferInput<d.WgslStruct<{
sunDirection: d.Vec3f;
sunIntensity: d.F32;
sunColor: d.Vec3f;
skyIntensity: d.F32;
skyTop: d.Vec3f;
fogDensity: d.F32;
skyBottom: d.Vec3f;
fogFalloff: d.F32;
fogColor: d.Vec3f;
skyReflection: d.F32;
fogStart: d.F32;
}>>> | undefined)

Sets initial sun, sky and fog values over defaults. Default defaults, which has no fog.

settings
: {
fogDensity: 0.02
fogDensity
: 0.02,
fogFalloff: 0.2
fogFalloff
: 0.2 },
});
  • Haze shading.haze(point) is how much the lighting’s height fog hides the point, from 0 to 1. heightFog adds fogColor by it and lets 1 - haze through; add a colour of your own, as above.
  • Settings shading.settings() reads sun, sky and fog values from light.settings. Changing a value needs no new pipeline.
  • Matte shading shading.lambert omits highlights for cheaper shading on phones and flat-shaded art. It tints all reflection with the surface colour, including metals.
  • Ambient light shading.surrounded(material, point, irradiance, reflection) combines diffuse and reflected light for an ambient hook of your own. It applies the material’s occlusion to the reflected light only. See lightmaps.
  • Reflection direction shading.reflectionOf(point, roughness) returns the direction to sample reflected light along.
  • Ambient terms shading.reflectance and shading.specularOcclusion are the terms surrounded uses.
  • Parts of shade shading.unfogged, direct, sun and towardsSun are the parts of shade, for shaders that combine them differently.

Every pipeline built from light.inject() binds the resources its hooks read. A hook passed to lighting.create reaches every lit renderer. A fog that reads a ground paint texture and its uniforms then adds those to every figure and prop pipeline too. Each stage has 8 storage and 12 uniform buffers to share, so give a hook that only some renderers need to those renderers alone:

const ground = terrain.renderer().pipe((cfg) => cfg.with(shading.fog, paintedFog));

Renderer pipe runs after the lighting, so replaces the lighting’s. Fill your own pipelines the same way, root.pipe(light.inject()).with(shading.reflect, shading.lambert). Pipelines lists what each pipeline binds.

Glass that hides only a tenth of its background can still show full-strength highlights and sky reflections. Use shading.shadeClear(material, point, opacity) for this behavior. It returns premultiplied colour for pipelines.blend.over:

const
const pane: (world: d.v3f, normal: d.v3f) => d.v4f
pane
= (
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
,
normal: d.v3f
normal
:
import d
d
.
export v3f

Interface representing its WGSL vector type counterpart: vec3f or vec3. A vector with 3 elements of type f32

v3f
) => {
'use gpu';
const
const glass: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
glass
=
import materials
materials
.
const glossy: (color: d.v3f, roughness: number) => {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}

Creates a dielectric with specular highlights, such as paint, plastic or wet stone.

glossy
(
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0.8, 0.9, 1), 0.05);
return
import shading
shading
.
const shadeClear: (material: shading.Material, point: shading.Point, opacity: number) => d.v4f

Shades a clear surface such as glass or clear plastic. The result is premultiplied for pipelines.blend.over. opacity scales diffuse light, emission and the light the fog adds. Reflections, including highlights and sky light, contribute at full strength. A metal has only reflected light, so opacity scales only its fog. Every channel stays at or below 65 504.

shadeClear
(
const glass: {
color: d.v3f;
roughness: number;
emission: d.v3f;
metallic: number;
occlusion: number;
}
glass
,
import shading
shading
.
const pointAt: (position: d.v3f, normal: d.v3f) => {
position: d.v3f;
normal: d.v3f;
view: d.v3f;
uv: d.v2f;
uv1: d.v2f;
}

Creates a point at position with surface normal normal, viewed from the kit camera.

pointAt
(
world: d.v3f
world
,
normal: d.v3f
normal
), 0.1);
};
  • opacity scales the diffuse light, the emission and the light the fog adds; the reflected light is added whole. w is opacity.
  • A metal reflects all it shows, so opacity only fades its fog.
  • An instances renderer with blend: 'clear' shades through it.

One shadow map, read with one, four or nine comparisons

Try Set 256 texels and compare one, four or nine shadow comparisons. The map spans 9 units around a 0.3-unit-wide pillar; extra comparisons soften its stepped shadow.

Without shadows, a floating block can appear to rest on the floor. A lighting with a shadow group creates light.shadow, which records depth from the sun. Add each caster to it as you add to the scene, and record it each frame before the passes that shade:

const
const light: lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [-0.6, 1, -0.7];
};
readonly shadow: {
readonly extent: 9;
};
}>
light
=
import lighting
lighting
.
function create<{
readonly settings: {
readonly sunDirection: [-0.6, 1, -0.7];
};
readonly shadow: {
readonly extent: 9;
};
}>(root: TgpuRoot, options?: ({
readonly settings: {
readonly sunDirection: [-0.6, 1, -0.7];
};
readonly shadow: {
readonly extent: 9;
};
} & lighting.Options) | undefined): lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [-0.6, 1, -0.7];
};
readonly shadow: {
readonly extent: 9;
};
}>

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
settings: {
readonly sunDirection: [-0.6, 1, -0.7];
} & (Partial<InferInput<WgslStruct<{
sunDirection: Vec3f;
sunIntensity: F32;
sunColor: Vec3f;
skyIntensity: F32;
skyTop: Vec3f;
fogDensity: F32;
skyBottom: Vec3f;
fogFalloff: F32;
fogColor: Vec3f;
skyReflection: F32;
fogStart: F32;
}>>> | undefined)

Sets initial sun, sky and fog values over defaults. Default defaults, which has no fog.

settings
: {
sunDirection: [-0.6, 1, -0.7]
sunDirection
: [-0.6, 1, -0.7] },
shadow: {
readonly extent: 9;
} & lighting.FixedShadowOptions

Enables and configures the shadow from the sun. Default none.

shadow
: {
extent: 9

Sets the width of the square covered by the map in world units. The square is centred on the point passed to follow. Change it with setExtent. A shadow with an eye takes none. Default 20.

extent
: 9 },
});
const
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
=
import passes
passes
.
function create<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>, {
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>(root: TgpuRoot, screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>>, writes: {
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}, options?: passes.TargetOptions<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>> | undefined): passes.Description<...> (+1 overload)

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

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

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

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

create
(
const root: TgpuRoot
root
,
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>>
screen
, {
hdr: typeof passes.color
hdr
:
import passes
passes
.
const color: typeof passes.color

Marks the target that receives each renderer's colour.

color
,
depth: typeof passes.depth
depth
:
import passes
passes
.
const depth: typeof passes.depth

Marks the depth target.

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

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

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

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

inject
())
.
Description<{ readonly hdr: typeof color; readonly depth: typeof depth; }>.beneath(fill: Inject): passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>

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().

beneath
(
const light: lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [-0.6, 1, -0.7];
};
readonly shadow: {
readonly extent: 9;
};
}>
light
.
Lighting.inject(): Inject

Fills the shading hooks and resources for pipelines created from the configuration you pipe it into.

inject
());
const
const renderer: instances.Renderer
renderer
=
const things: instances.Instances<Plain>
things
.
Instances<Plain>.renderer(options?: instances.RendererOptions): instances.Renderer

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
();
const
const drawn: passes.Drawn
drawn
=
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Into<{ readonly hdr: typeof color; 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 (+1 overload)

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

add
(
const renderer: instances.Renderer
renderer
);
const
const cast: passes.Drawn
cast
=
const light: lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [-0.6, 1, -0.7];
};
readonly shadow: {
readonly extent: 9;
};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
ShadowPasses.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 (+1 overload)

Builds a caster's depth pipeline with the shadow's bias and returns its draw methods.

add
(
const renderer: instances.Renderer
renderer
);
import frames
frames
.
function animate(loop: Pick<frames.Frames, "run"> & Partial<Pick<frames.Frames, "seconds">>, options?: frames.AnimateOptions): frames.Animation
export animate

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

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

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

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

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

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

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const things: instances.Instances<Plain>
things
.
Instances<Plain>.flush(target?: frames.Frame | TgpuCommandEncoder): void

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
();
const light: lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [-0.6, 1, -0.7];
};
readonly shadow: {
readonly extent: 9;
};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
SunShadow.record(frame: frames.Frame | TgpuCommandEncoder, casters: passes.Drawn | readonly passes.Drawn[], options?: lighting.ShadowRecordOptions): void

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: frames.Frame
frame
,
const cast: passes.Drawn
cast
);
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Description<{ readonly hdr: typeof color; readonly depth: typeof depth; }>.record(frame: frames.Frame | TgpuCommandEncoder, drawn: passes.Drawn | readonly passes.Drawn[], options?: passes.BeginOptions<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}> | undefined): void

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

record
(
frame: frames.Frame
frame
,
const drawn: passes.Drawn
drawn
);
}),
);
  • Casters light.shadow.add(renderer) builds depth pipelines with bias against self-shadowing. cast.destroy() removes the caster and frees its per-view resources.
  • Compiling await light.initAsync() while loading compiles every caster added to its shadows. Include the lighting in the list for pipelines.compile to compile it with the scene’s other pipelines.
  • Coverage The map covers a square extent world units wide, centred on center. Outside it, surfaces are lit. Wider coverage spreads each over more ground: Blockfall covers its well with 2048 texels across 16 units, about 1/128 of a block per texel.
  • Direction The shadow follows sunDirection. A direction written to light.settings turns it at its next record. Call aim(direction) to cast from elsewhere.
  • The type light.shadow exists in the type only when the options give a shadow. A function of your own that takes such a lighting types it lighting.Shadowed, or lighting.PointShadowed for lamp shadows.
  • Timing Time the pass with a profiler as record(frame, casters, { timestampWrites: shadow.writes() }). A frame that draws no cascade writes the timer from an empty compute pass.
  • Memory A layer of the map takes size² × 2 bytes in depth16unorm and size² × 4 in the other formats.
stampede4 096 horses in a golden valley. Spook them and the panic spreads.
Click a horse to ride beside it. Its legs cast sharp shadows from the nearest cascade while the trees on the far slopes cast theirs from the last.

One square sharp enough for a horse’s legs covers a few dozen metres. Give the shadow an eye and it splits the view into cascades, each a layer of one map. The nearest covers the first metres in front of the camera, and each later one covers more ground with the same texels. record fits them to the camera each frame:

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

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

@returns ― a camera you update every frame

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

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

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

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

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

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

distance
: 12 });
const
const light: lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [0.6, 0.35, 0.3];
};
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly far: 120;
};
}>
light
=
import lighting
lighting
.
function create<{
readonly settings: {
readonly sunDirection: [0.6, 0.35, 0.3];
};
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly far: 120;
};
}>(root: TgpuRoot, options?: ({
readonly settings: {
readonly sunDirection: [0.6, 0.35, 0.3];
};
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly far: 120;
};
} & lighting.Options) | undefined): lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [0.6, 0.35, 0.3];
};
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly far: 120;
};
}>

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
settings: {
readonly sunDirection: [0.6, 0.35, 0.3];
} & (Partial<InferInput<WgslStruct<{
sunDirection: Vec3f;
sunIntensity: F32;
sunColor: Vec3f;
skyIntensity: F32;
skyTop: Vec3f;
fogDensity: F32;
skyBottom: Vec3f;
fogFalloff: F32;
fogColor: Vec3f;
skyReflection: F32;
fogStart: F32;
}>>> | undefined)

Sets initial sun, sky and fog values over defaults. Default defaults, which has no fog.

settings
: {
sunDirection: [0.6, 0.35, 0.3]
sunDirection
: [0.6, 0.35, 0.3] },
shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly far: 120;
} & 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
:
const view: cameras.OrbitCamera
view
,
cascades: 3

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
: 3,
far: 120

Sets how far from the eye the cascades reach, in world units. Change it with setFar. Needs an eye. Default 50.

far
: 120 },
});
const
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
=
import passes
passes
.
function create<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>, {
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>(root: TgpuRoot, screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>>, writes: {
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}, options?: passes.TargetOptions<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>> | undefined): passes.Description<...> (+1 overload)

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

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

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

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

create
(
const root: TgpuRoot
root
,
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>>
screen
, {
hdr: typeof passes.color
hdr
:
import passes
passes
.
const color: typeof passes.color

Marks the target that receives each renderer's colour.

color
,
depth: typeof passes.depth
depth
:
import passes
passes
.
const depth: typeof passes.depth

Marks the depth target.

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

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

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

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

inject
())
.
Description<{ readonly hdr: typeof color; readonly depth: typeof depth; }>.beneath(fill: Inject): passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>

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().

beneath
(
const light: lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [0.6, 0.35, 0.3];
};
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly far: 120;
};
}>
light
.
Lighting.inject(): Inject

Fills the shading hooks and resources for pipelines created from the configuration you pipe it into.

inject
());
const
const renderer: instances.Renderer
renderer
=
const things: instances.Instances<Plain>
things
.
Instances<Plain>.renderer(options?: instances.RendererOptions): instances.Renderer

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
();
const
const drawn: passes.Drawn
drawn
=
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Into<{ readonly hdr: typeof color; 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 (+1 overload)

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

add
(
const renderer: instances.Renderer
renderer
);
const
const cast: passes.Drawn
cast
=
const light: lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [0.6, 0.35, 0.3];
};
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly far: 120;
};
}>
light
.
shadow: lighting.Cascades | (lighting.Shadow & lighting.Cascades)

Provides the sun shadow when enabled in the options.

shadow
.
ShadowPasses.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 (+1 overload)

Builds a caster's depth pipeline with the shadow's bias and returns its draw methods.

add
(
const renderer: instances.Renderer
renderer
);
import frames
frames
.
function animate(loop: Pick<frames.Frames, "run"> & Partial<Pick<frames.Frames, "seconds">>, options?: frames.AnimateOptions): frames.Animation
export animate

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

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

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

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

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

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

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

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

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

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

dt
);
const things: instances.Instances<Plain>
things
.
Instances<Plain>.flush(target?: frames.Frame | TgpuCommandEncoder): void

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
();
const light: lighting.LightingOf<{
readonly settings: {
readonly sunDirection: [0.6, 0.35, 0.3];
};
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly far: 120;
};
}>
light
.
shadow: lighting.Cascades | (lighting.Shadow & lighting.Cascades)

Provides the sun shadow when enabled in the options.

shadow
.
SunShadow.record(frame: frames.Frame | TgpuCommandEncoder, casters: passes.Drawn | readonly passes.Drawn[], options?: lighting.ShadowRecordOptions): void

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: frames.Frame
frame
,
const cast: passes.Drawn
cast
); // a depth pass per cascade
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Description<{ readonly hdr: typeof color; readonly depth: typeof depth; }>.record(frame: frames.Frame | TgpuCommandEncoder, drawn: passes.Drawn | readonly passes.Drawn[], options?: passes.BeginOptions<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}> | undefined): void

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

record
(
frame: frames.Frame
frame
,
const drawn: passes.Drawn
drawn
);
}),
);
  • eye takes a camera with a CPU view: cameras.orbit, cameras.flat or cameras.custom. Update it before record.
  • The split after cascade k lies at far × (k / cascades)², 11% and 44% of far for three. splits: [0.08, 0.3] places them as fractions of far instead.
  • record fits a sphere around each slice of the view and snaps its centre to whole texels. The sphere keeps its size as the camera turns, so shadow edges hold still.
  • reach is how far each cascade reaches towards the sun beyond its slice. A caster farther towards the sun casts nothing.
  • cascades, far and splits need an eye, and extent and center work only without one. Type checking refuses the other combinations, and create throws for them. cascades: 1 fits one map to the view.

A view cut into shadow cascades, seen from a sun overhead

Try Drag the point away from the camera. It takes the first square that holds it, so its texels grow at each edge it leaves. Every square is one layer of the map, ruled here 16 cells across.

Casters draw once per cascade through the pipelines a single map builds. An instances renderer with cull: true culls every cascade in one pair of . Shading picks the first cascade whose square holds the point and switches cascades without a blend, unless a hook of your own blends them. A finished look for model scenes sizes two cascades for a scene of glTF models.

record clears and draws every cascade each frame. Casters that hold still under a still sun draw the same depth again. Pass redraw to choose the cascades that draw this frame. The others keep the layer they drew last:

// Set when a caster moves, from your own game state
let
let stirred: boolean
stirred
= true;
import frames
frames
.
function create(root: TgpuRoot, record: Recorder): frames.Frames

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

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

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

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

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 16;
};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
SunShadow.record(frame: frames.Frame | TgpuCommandEncoder, casters: Drawn | readonly Drawn[], options?: lighting.ShadowRecordOptions): void

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: frames.Frame
frame
,
const cast: Drawn
cast
, {
ShadowPrepareOptions.redraw?: ((cascade: number) => boolean) | undefined

Chooses which cascades draw their layer this frame, by index from the nearest. A cascade it skips keeps the layer it drew last, so still casters under a still sun can skip. A cascade still draws on the first record and when its place changes, as a fitted shadow's does when the eye moves, after aim, follow, setExtent, setFar and resize, and after a frame with enabled false, so () => false draws casters that never move once. A layer counts as drawn once its frame submits, so a cascade recorded into an encoder alone draws on every record until resize. Default every cascade.

@cpu

redraw
: () =>
let stirred: boolean
stirred
});
let stirred: boolean
stirred
= false;
});

With a culling renderer, give redraw to prepare before renderer.cull instead, as for lamps, so culling skips the cascades that keep their layer.

A cascade draws the first time the shadow is recorded and whenever its placement changes, even if redraw would skip it. Moving the fitted eye, turning the sun or calling aim, follow, setExtent or setFar can change that placement. All cascades draw again after resize replaces the map and when the shadow comes back on. A skipped cascade shows casters where they stood when it last drew. A layer counts as drawn once its frame submits. If a frame throws before its submit, the layer draws again. A cascade recorded into an encoder alone draws on every record until resize replaces the map, since that encoder may submit after any later frame.

Casters that never move, such as terrain or a reef, need no state of their own. A redraw that always answers false draws the shadow once and again only when its place changes:

const
const still: {
redraw: () => boolean;
}
still
= {
redraw: () => boolean
redraw
: () => false };
import frames
frames
.
function create(root: TgpuRoot, record: Recorder): frames.Frames

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

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

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

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

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const light: lighting.LightingOf<{
readonly shadow: {
readonly extent: 16;
};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
SunShadow.record(frame: frames.Frame | TgpuCommandEncoder, casters: Drawn | readonly Drawn[], options?: lighting.ShadowRecordOptions): void

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: frames.Frame
frame
,
const cast: Drawn
cast
,
const still: {
redraw: () => boolean;
}
still
);
});

record places the cascades with the shadow’s fit, a function on the CPU. The default, lighting.fitSlices, is the sphere around each slice described above. A fit of your own writes a cube for each cascade in the sun’s light space, whose axes are right, up and sun. It returns whether it placed them. Each cascade also reaches reach beyond its cube towards the sun.

The fit below widens each cube and snaps it to a coarse grid. Each cube then holds still while the view moves inside it. With redraw: () => false, a cascade then draws only when the view crosses a line of its grid:

const
const held: lighting.CascadeFit
held
:
import lighting
lighting
.
type CascadeFit = (input: lighting.CascadeFitInput, places: lighting.CascadePlace[]) => boolean
export CascadeFit

Places each cascade, writing places[k] for cascade k, and returns whether it placed them. When it returns false, as when the eye has no view yet, every point is sunlit until it places them. lighting.fitSlices is the default.

CascadeFit
= (
input: lighting.CascadeFitInput
input
,
places: lighting.CascadePlace[]
places
) => {
if (!
import lighting
lighting
.
function fitSlices(input: lighting.CascadeFitInput, places: lighting.CascadePlace[]): boolean
export fitSlices

Fits a sphere around each cascade's slice of the eye's view and snaps its centre to whole texels across the sun's rays. The sphere keeps its size as the eye turns, so shadow edges hold still. This is a fitted shadow's default fit; a fit of your own can call it and move what it placed.

@param ― input the eye, the sun's light space and the shadow's settings

@param ― places the places it writes, one per cascade

@returns ― whether it placed them, false while the eye has no view

fitSlices
(
input: lighting.CascadeFitInput
input
,
places: lighting.CascadePlace[]
places
)) return false;
for (const
const place: lighting.CascadePlace
place
of
places: lighting.CascadePlace[]
places
) {
const place: lighting.CascadePlace
place
.
CascadePlace.radius: number

Sets the distance from the cube's centre to each face, above 0, in world units.

radius
*= 1.3;
// Whole texels, a tenth of the layer apart, so the slice stays inside the cube
const
const step: number
step
= ((
const place: lighting.CascadePlace
place
.
CascadePlace.radius: number

Sets the distance from the cube's centre to each face, above 0, in world units.

radius
* 2) /
input: lighting.CascadeFitInput
input
.
CascadeFitInput.size: number

Gives the width and height of each layer of the map in texels.

size
) *
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.floor(x: number): number

Returns the greatest integer less than or equal to its numeric argument.

@param ― x A numeric expression.

floor
(
input: lighting.CascadeFitInput
input
.
CascadeFitInput.size: number

Gives the width and height of each layer of the map in texels.

size
/ 10);
const place: lighting.CascadePlace
place
.
CascadePlace.x: number

Sets the cube's centre along right, in world units.

x
=
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.round(x: number): number

Returns a supplied numeric expression rounded to the nearest integer.

@param ― x The value to be rounded to the nearest integer.

round
(
const place: lighting.CascadePlace
place
.
CascadePlace.x: number

Sets the cube's centre along right, in world units.

x
/
const step: number
step
) *
const step: number
step
;
const place: lighting.CascadePlace
place
.
CascadePlace.y: number

Sets the cube's centre along up, in world units.

y
=
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.round(x: number): number

Returns a supplied numeric expression rounded to the nearest integer.

@param ― x The value to be rounded to the nearest integer.

round
(
const place: lighting.CascadePlace
place
.
CascadePlace.y: number

Sets the cube's centre along up, in world units.

y
/
const step: number
step
) *
const step: number
step
;
const place: lighting.CascadePlace
place
.
CascadePlace.z: number

Sets the cube's centre along sun, in world units.

z
=
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.round(x: number): number

Returns a supplied numeric expression rounded to the nearest integer.

@param ― x The value to be rounded to the nearest integer.

round
(
const place: lighting.CascadePlace
place
.
CascadePlace.z: number

Sets the cube's centre along sun, in world units.

z
/
const step: number
step
) *
const step: number
step
;
}
return true;
};
const
const light: lighting.LightingOf<{
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly fit: lighting.CascadeFit;
};
}>
light
=
import lighting
lighting
.
function create<{
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly fit: lighting.CascadeFit;
};
}>(root: TgpuRoot, options?: ({
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly fit: lighting.CascadeFit;
};
} & lighting.Options) | undefined): lighting.LightingOf<{
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly fit: lighting.CascadeFit;
};
}>

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
readonly fit: lighting.CascadeFit;
} & 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
:
const view: cameras.OrbitCamera
view
,
cascades: 3

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
: 3,
fit: lighting.CascadeFit

Places the cascades in the sun's light space whenever the shadow fits them: on each record, after aim and after setFar. Needs an eye. Default lighting.fitSlices, a sphere around each slice of the view, snapped to whole texels.

@cpu

fit
:
const held: lighting.CascadeFit
held
},
});
  • The fit runs on each record, after aim and after setFar, and writes into the same places each time.
  • Snap each centre across the sun to whole texels of its layer, as fitSlices does, or shadow edges crawl as the cascade moves.
  • A fit that returns false lights every point, as a shadow does before its eye has a view.

Add a custom caster as a drawing to light.shadow. Supply a Vertex with a clip-space position, an at function producing it and a draw function. The shadow fills the kit’s cameras.current with the sun’s view, so scene vertex functions cast without changes:

const
const statue: meshes.Geometry<d.WgslStruct<{
position: d.Vec3f;
normal: d.Vec3f;
uv: d.Vec2f;
}>>
statue
=
import meshes
meshes
.
unindexed<d.WgslStruct<{
position: d.Vec3f;
normal: d.Vec3f;
uv: d.Vec2f;
}>>(g: meshes.Geometry<d.WgslStruct<{
position: d.Vec3f;
normal: d.Vec3f;
uv: d.Vec2f;
}>>): meshes.Geometry<d.WgslStruct<{
position: d.Vec3f;
normal: d.Vec3f;
uv: d.Vec2f;
}>>
export unindexed
unindexed
(
import meshes
meshes
.
function box({ width, height, depth, widthSegments, heightSegments, depthSegments, }?: meshes.BoxOptions): meshes.IndexedGeometry
box
());
const
const Corner: 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.

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

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

struct
({
position: d.Vec4f
position
:
import d
d
.
const vec4f: d.Vec4f
vec4f
});
const
const cast: Drawn
cast
=
const light: lighting.LightingOf<{
readonly shadow: {};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
ShadowPasses.add<d.WgslStruct<{
position: d.Vec4f;
}>, unknown>(drawing: Drawing<d.WgslStruct<{
position: d.Vec4f;
}>, unknown>): Drawn (+1 overload)

Builds a caster's depth pipeline with the shadow's bias and returns its draw methods.

add
({
Shaders<WgslStruct<{ position: Vec4f; }>, unknown>.Vertex: d.WgslStruct<{
position: d.Vec4f;
}>

Defines a vertex with its position in clip space and data carried to pixels.

Vertex
:
const Corner: d.WgslStruct<{
position: d.Vec4f;
}>
Corner
,
Shaders<WgslStruct<{ position: Vec4f; }>, unknown>.at: (vertexIndex: number, instanceIndex: number) => {
position: d.v4f;
}

Computes the vertex for a vertex and instance index, as a 'use gpu' function.

at
: (
vertexIndex: number
vertexIndex
: number,
_instanceIndex: number
_instanceIndex
: number) => {
'use gpu';
const
const world: d.v3f
world
=
const statue: meshes.Geometry<d.WgslStruct<{
position: d.Vec3f;
normal: d.Vec3f;
uv: d.Vec2f;
}>>
statue
.
Geometry<WgslStruct<{ position: Vec3f; normal: Vec3f; uv: Vec2f; }>>.vertexAt(this: void, i: number): {
position: d.v3f;
normal: d.v3f;
uv: d.v2f;
}
vertexAt
(
vertexIndex: number
vertexIndex
).
position: d.v3f
position
+
import d
d
.
const vec3f: d.Vec3f
(x: number, y: number, z: number) => d.v3f (+5 overloads)
vec3f
(0, 1, 0);
return
const Corner: d.WgslStruct
(props?: {
position: d.v4f;
} | undefined) => {
position: d.v4f;
}
Corner
({
position: d.v4f
position
:
import cameras
cameras
.
const toClip: (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
(
const world: d.v3f
world
) });
},
Drawing<WgslStruct<{ position: Vec4f; }>, unknown>.draw(pass: TgpuRenderCommands): void

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.

draw
: (
pass: TgpuRenderCommands
pass
) =>
pass: TgpuRenderCommands
pass
.
TgpuRenderCommands.draw(vertexCount: number, instanceCount?: number, firstVertex?: number, firstInstance?: number): void
draw
(
const statue: meshes.Geometry<d.WgslStruct<{
position: d.Vec3f;
normal: d.Vec3f;
uv: d.Vec2f;
}>>
statue
.
Geometry<V extends d.AnyWgslData = WgslStruct<{ position: Vec3f; normal: Vec3f; uv: Vec2f; }>>.vertexCount: number
vertexCount
),
});
const light: lighting.LightingOf<{
readonly shadow: {};
}>
light
.
shadow: lighting.Shadow | (lighting.Cascades & lighting.Shadow)

Provides the sun shadow when enabled in the options.

shadow
.
SunShadow.record(frame: Frame | TgpuCommandEncoder, casters: Drawn | readonly Drawn[], options?: lighting.ShadowRecordOptions): void

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
(
const frame: Frame
frame
,
const cast: Drawn
cast
); // each frame
  • Depth only Depth-only drawings need neither pixelOf nor color, and build no fragment stage. With pixelOf and depthOf, a drawing can supply another point’s depth, as impostors do.
  • Cutouts A drawing with cutout, such as a sprite whose texture is clear around its figure, casts the figure’s shadow. The shadow pass runs cutout alone, so the same drawing goes into the shadow map even when its pixelOf reads the lighting.
  • Masked instances Instances cut out by masked meshes or by their kind’s coverage cast through it the same way, at their own depth.
  • Indices and fills Supply an index buffer as indices for drawIndexed and fill shader dependencies with inject().

shade takes the share of sunlight at a point from the sunShadow hook. The default, shading.sunShadowed, moves the point lift texels along its normal and compares it with the map. It makes 1, 4 or 9 comparisons, as filter sets, and returns their mean, from 0 in shadow to 1 in light. A hook of your own can change that share. The fishtank multiplies shading.sunShadowed(point) by its caustics. The hook below blends each cascade into the next near the edge of its square. At the last cascade’s edge it blends the shadow into sunlight, so the shadow fades out instead of ending at a line:

const
const blended: shading.SunShadowHook
blended
:
import shading
shading
.
type SunShadowHook = (point: shading.Point) => number

Returns the share of sunlight that reaches a point, as sunShadowed does. A value of 0 means full shadow and 1 means full light. Values above 1 can model focused light.

SunShadowHook
= (
point: {
position: v3f;
normal: v3f;
view: v3f;
uv: v2f;
uv1: v2f;
}
point
) => {
'use gpu';
const
const at: {
index: number;
edge: number;
}
at
=
import shading
shading
.
const cascadeOf: (point: shading.Point) => {
index: number;
edge: number;
}

Returns the first cascade of the sun's shadow whose square holds the point, inset by the filter's half width and the shadow's lift, and how near its edge the point lies. Index -1 means no cascade holds it, or the shadow is off.

cascadeOf
(
point: {
position: v3f;
normal: v3f;
view: v3f;
uv: v2f;
uv1: v2f;
}
point
); // index -1 outside every cascade
const
const lit: number
lit
=
import shading
shading
.
const cascadeShadowed: (point: shading.Point, index: number) => number

Returns the share of sunlight that passes the filter in cascade index of the sun's shadow. A grid of depth comparisons gives 0 in full shadow and 1 in full light. For a point outside the cascade's square or depth, an index without a cascade, or while the shadow is off, this returns 1.

cascadeShadowed
(
point: {
position: v3f;
normal: v3f;
view: v3f;
uv: v2f;
uv1: v2f;
}
point
,
const at: {
index: number;
edge: number;
}
at
.
index: number
index
);
if (
const at: {
index: number;
edge: number;
}
at
.
edge: number

Rises from 0 to 1 over the outer 10% of the cascade's square.

edge
<= 0) return
const lit: number
lit
;
return
import std
std
.
function mix(e1: number, e2: number, e3: number): number (+2 overloads)
export mix
mix
(
const lit: number
lit
,
import shading
shading
.
const cascadeShadowed: (point: shading.Point, index: number) => number

Returns the share of sunlight that passes the filter in cascade index of the sun's shadow. A grid of depth comparisons gives 0 in full shadow and 1 in full light. For a point outside the cascade's square or depth, an index without a cascade, or while the shadow is off, this returns 1.

cascadeShadowed
(
point: {
position: v3f;
normal: v3f;
view: v3f;
uv: v2f;
uv1: v2f;
}
point
,
const at: {
index: number;
edge: number;
}
at
.
index: number
index
+ 1),
const at: {
index: number;
edge: number;
}
at
.
edge: number

Rises from 0 to 1 over the outer 10% of the cascade's square.

edge
);
};
const
const light: lighting.LightingOf<{
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
};
readonly shading: {
readonly sunShadow: shading.SunShadowHook;
};
}>
light
=
import lighting
lighting
.
function create<{
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
};
readonly shading: {
readonly sunShadow: shading.SunShadowHook;
};
}>(root: TgpuRoot, options?: ({
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
};
readonly shading: {
readonly sunShadow: shading.SunShadowHook;
};
} & lighting.Options) | undefined): lighting.LightingOf<{
readonly shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
};
readonly shading: {
readonly sunShadow: shading.SunShadowHook;
};
}>

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
shadow: {
readonly eye: cameras.OrbitCamera;
readonly cascades: 3;
} & 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
:
const view: cameras.OrbitCamera
view
,
cascades: 3

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
: 3 },
shading: {
readonly sunShadow: shading.SunShadowHook;
} & lighting.Shading

Sets the functions that shading.shade calls. Default pbr, hemisphere, heightFog, sunShadowed and reaching.

shading
: {
sunShadow: shading.SunShadowHook

Returns the share of sunlight that reaches a point. A value of 0 means full shadow and 1 means full light. Values above 1 can model focused light, such as light through moving water. Default shading.sunShadowed, which reads the shadow map.

sunShadow
:
const blended: shading.SunShadowHook
blended
},
});
  • cascadeOf(point) returns the first cascade that holds the point within its depth range and within its square inset by the filter’s half width and lift. Its edge rises from 0 to 1 over the outer 10% of the inset square.
  • cascadeShadowed(point, index) filters cascade index. It returns 1 for a point outside that cascade and for an index outside the cascades, so the last cascade blends into sunlight.
  • shading.sunShare(point) returns what the hook gives, for shaders that don’t call shade. The domino run’s dust brightens in sunlight with it.

The shadow group’s enabled callback turns the shadow on and off each frame, as for other pass descriptions. A quality menu can change its value without a second lighting:

const
const menu: {
shadows: boolean;
}
menu
= {
shadows: boolean
shadows
: true };
const
const light: lighting.LightingOf<{
readonly shadow: {
readonly enabled: () => boolean;
};
}>
light
=
import lighting
lighting
.
function create<{
readonly shadow: {
readonly enabled: () => boolean;
};
}>(root: TgpuRoot, options?: ({
readonly shadow: {
readonly enabled: () => boolean;
};
} & lighting.Options) | undefined): lighting.LightingOf<{
readonly shadow: {
readonly enabled: () => boolean;
};
}>

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
shadow: {
readonly enabled: () => boolean;
} & (lighting.ShadowOptions | undefined)

Enables and configures the shadow from the sun. Default none.

shadow
: {
enabled: () => boolean
enabled
: () =>
const menu: {
shadows: boolean;
}
menu
.
shadows: boolean
shadows
} });
  • While it is off, record records no pass, culling lists stay empty and shading.sunShadowed returns 1 without sampling the map.
  • The map and pipelines stay allocated, so shadows draw on the first frame after it turns on.

resize(size) replaces the map between frames:

  • Give light.shadow.part to the lit as shared: { shadow: light.shadow.part }, which puts it in a shared layout. Create that description before any other pipeline that shades.
  • When a pass of your own also reads the map, share it once with bindings.share and give the result to the description.
  • The next frame then makes one and no pipelines. The shadow’s own passes don’t read the map, so they need no group.
  • Without a shared layout, shading pipelines bind the map as fixed resources, and resize throws before it changes anything.
night-marketA potion stall on a rainy night, lit by a lantern, a fire and two lamps.
Turn shadows off to let the lamps shine through the table onto the cobbles beneath it. The seller's lamp throws the potions' shadows along the table. Raise the wind to swing the lantern under the string of lights; its shadows swing with it.
import
import { pointShadow } from '@typegpu/kit'
call
pointShadow.define(options?) → PointShadowDefinition

Give lighting.create a pointShadow.define to get light.pointShadow. It gives a shadow each to up to count lights of the lighting’s table. The lighting makes, compiles and destroys it with its own resources. A lighting without one leaves the point-shadow code out of your bundle. cast picks the lights:

import {
import lighting
lighting
,
import pointShadow
pointShadow
,
import table
table
} from '@typegpu/kit';
const
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
=
import table
table
.
function create<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>(root: TgpuRoot, def: table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>, options: table.Options<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>): table.Table<...> (+1 overload)

Allocates GPU buffers and a CPU copy of host rows. Throws unless capacity is an integer in [1, 2^20].

@param ― def the definition its shaders were written against, from table.define

@returns ― a table you destroy

create
(
const root: TgpuRoot
root
,
import lighting
lighting
.
const SpotLight: table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>
SpotLight
, {
Options<T extends AnyTableDef>.capacity: number

Sets the table capacity for its lifetime. Must be an integer in [1, 2^20], with slots from 0 to capacity - 1. A row id uses enough bits for the slot and the rest for its generation. The generation has 29 bits at 8 rows and 12 bits at 2^20 rows.

capacity
: 16,
Options<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.defaults?: table.Values<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> | undefined

Sets values for fields omitted by add. Without defaults, every field starts at zero. Default none.

defaults
: { ...
import lighting
lighting
.
const WHITE_SPOT: {
readonly intensity: number;
readonly color: v3f;
readonly range: number;
} & {
readonly aim: v3f;
readonly cone: v2f;
}

Holds WHITE with an aim straight down and a full cone, for a table of spot lights.

WHITE_SPOT
},
});
const
const light: lighting.LightingOf<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
}>
light
=
import lighting
lighting
.
function create<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
}>(root: TgpuRoot, options?: ({
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
} & lighting.Options) | undefined): lighting.LightingOf<...>

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

@returns ― lighting you destroy

create
(
const root: TgpuRoot
root
, {
points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
} & lighting.TablePoints

Enables point lights from a table or a function. Default none.

points
: {
table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> & lighting.LightTable

Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or MovingSpotLight. Its fields start at zero, so give it defaults such as lighting.WHITE. Flush and destroy it yourself. Default none, lights from light or spot.

table
:
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
},
pointShadow: pointShadow.PointShadowDefinition

Gives up to count point or spot lights a shadow each, as pointShadow.define describes them, which light.pointShadow.cast assigns. Needs points.table of lights the CPU places, not a moving one. Default none.

pointShadow
:
import pointShadow
pointShadow
.
function define(options?: pointShadow.PointShadowOptions): pointShadow.PointShadowDefinition

Describes point and spot shadows for lighting.create, which gives up to count lights of its points.table a shadow each as light.pointShadow. The lighting checks count and size when it makes them.

@param ― options the shadows' count, layer size, filter and depth format

@returns ― a definition to give lighting.create as pointShadow

define
({
PointShadowOptions.count?: number | undefined

Sets how many lights can cast a shadow at once, each with six layers of the map. Shading compares each in-range light with every shadow. Default 1.

count
: 2 }),
});
const
const fire: table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
fire
=
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.add(values?: table.Values<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> | undefined): table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>

Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is full, or when a value fails to write, which leaves the slot free.

add
({
position?: ArrayLike<number> | InferInput<Vec3f> | undefined
position
: [0, 0.8, 0],
color?: ArrayLike<number> | InferInput<Vec3f> | undefined

Sets the light colour in linear colour space.

color
: [1, 0.45, 0.15],
intensity?: number | undefined

Multiplies color.

intensity
: 8,
range?: number | undefined

Sets the distance in world units where light intensity reaches zero.

range
: 14 });
const
const sign: table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
sign
=
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.add(values?: table.Values<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>> | undefined): table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>

Adds a row in the lowest free slot. Uses defaults for omitted fields. Throws when the table is full, or when a value fails to write, which leaves the slot free.

add
({
position?: ArrayLike<number> | InferInput<Vec3f> | undefined
position
: [3, 4, 1],
aim?: ArrayLike<number> | InferInput<Vec3f> | undefined

Points the cone's axis away from the light. It can have any length.

aim
: [0, -1, 0.3],
cone?: ArrayLike<number> | InferInput<Vec2f> | undefined

Holds the cone's scale and offset from lighting.cone(inner, outer). The default [0, 1] lights every direction.

cone
:
import lighting
lighting
.
const cone: (inner: number, outer: number) => v2f

Returns a cone's scale and offset for a spot light's cone, from its inner and outer half-angles in radians. Light falls from full at inner to none at outer, as glTF's spot lights do. It runs on the CPU and in shaders.

cone
(0.3, 0.45),
intensity?: number | undefined

Multiplies color.

intensity
: 30,
range?: number | undefined

Sets the distance in world units where light intensity reaches zero.

range
: 10,
});
const light: lighting.LightingOf<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
}>
light
.
pointShadow: pointShadow.PointShadow

Provides the point and spot lights' shadows when enabled in the options.

pointShadow
.
PointShadow.cast(lights: readonly table.RowId[]): void

Gives a shadow to each light in lights, ids in the lighting's table, at most count. A light that already casts keeps its shadow, a light left out frees its own, and a new one takes a free shadow, so casting the same lights again writes nothing. A spot whose outer half-angle is at most 60° draws one layer along its aim, and a wider spot or a point light draws six faces. A light of no range or with a cone of no width draws nothing and shadows nothing. Throws for more lights than count.

cast
([
const fire: table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
fire
,
const sign: table.RowId<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
sign
]); // six faces for the fire, one layer for the sign
const
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
=
import passes
passes
.
function create<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>, {
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>(root: TgpuRoot, screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>>, writes: {
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}, options?: passes.TargetOptions<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>> | undefined): passes.Description<...> (+1 overload)

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

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

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

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

create
(
const root: TgpuRoot
root
,
const screen: targets.Targets<Specs<{
readonly hdr: {
readonly format: "rgba16float";
};
readonly depth: {
readonly format: "depth24plus";
};
}>>
screen
, {
hdr: typeof passes.color
hdr
:
import passes
passes
.
const color: typeof passes.color

Marks the target that receives each renderer's colour.

color
,
depth: typeof passes.depth
depth
:
import passes
passes
.
const depth: typeof passes.depth

Marks the depth target.

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

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

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

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

inject
())
.
Description<{ readonly hdr: typeof color; readonly depth: typeof depth; }>.beneath(fill: Inject): passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>

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().

beneath
(
const light: lighting.LightingOf<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
}>
light
.
Lighting.inject(): Inject

Fills the shading hooks and resources for pipelines created from the configuration you pipe it into.

inject
());
const
const renderer: instances.Renderer
renderer
=
const things: instances.Instances<Plain>
things
.
Instances<Plain>.renderer(options?: instances.RendererOptions): instances.Renderer

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
();
const
const drawn: passes.Drawn
drawn
=
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Into<{ readonly hdr: typeof color; 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 (+1 overload)

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

add
(
const renderer: instances.Renderer
renderer
);
const
const casters: passes.Drawn
casters
=
const light: lighting.LightingOf<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
}>
light
.
pointShadow: pointShadow.PointShadow

Provides the point and spot lights' shadows when enabled in the options.

pointShadow
.
ShadowPasses.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 (+1 overload)

Builds a caster's depth pipeline with the shadow's bias and returns its draw methods.

add
(
const renderer: instances.Renderer
renderer
);
import frames
frames
.
function animate(loop: Pick<frames.Frames, "run"> & Partial<Pick<frames.Frames, "seconds">>, options?: frames.AnimateOptions): frames.Animation
export animate

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

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

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

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

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

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

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const things: instances.Instances<Plain>
things
.
Instances<Plain>.flush(target?: frames.Frame | TgpuCommandEncoder): void

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
();
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.flush(target?: frames.Frame | TgpuCommandEncoder): void

Uploads changes since the last flush with queue.writeBuffer. Writes reach the queue before the next submit. Call once per frame before passes that read the table. A HistoryTable takes the frame or its encoder and throws without one.

flush
();
const light: lighting.LightingOf<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
}>
light
.
pointShadow: pointShadow.PointShadow

Provides the point and spot lights' shadows when enabled in the options.

pointShadow
.
PointShadow.record(frame: frames.Frame | TgpuCommandEncoder, casters: passes.Drawn | readonly passes.Drawn[], options?: pointShadow.PointShadowRecordOptions): void

Places each shadow at its light from the table's CPU rows, then clears and draws the layers of each shadowed light that redraw picks with the casters built by add, a depth pass per layer. Call this while recording each frame, before drawing shaded surfaces. A removed light frees its shadow. A frame that draws no layer writes a timer's timestamps from an empty compute pass.

record
(
frame: frames.Frame
frame
,
const casters: passes.Drawn
casters
); // seven depth passes
const scene: passes.Description<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}>
scene
.
Description<{ readonly hdr: typeof color; readonly depth: typeof depth; }>.record(frame: frames.Frame | TgpuCommandEncoder, drawn: passes.Drawn | readonly passes.Drawn[], options?: passes.BeginOptions<{
readonly hdr: typeof passes.color;
readonly depth: typeof passes.depth;
}> | undefined): void

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

record
(
frame: frames.Frame
frame
,
const drawn: passes.Drawn
drawn
);
}),
);
  • Layers Each shadow holds six layers of one texture_depth_2d_array.
  • Casting cast(lights) gives a shadow to each light in the list, at most count. A light that already casts keeps its shadow, a light left out frees its own, and a new one takes a free shadow. Casting the same lights again writes nothing, so you can cast from the lamps nearest the eye every frame.
  • Views A spot whose outer half-angle is at most 60° draws one layer, a perspective view along its aim. A wider spot or a point light draws six faces. Each face covers 90° plus the filter’s half width, so the filter at a face’s edge stays inside that face.
  • Placement record places each shadow at its light’s in the table, so a light moved on the CPU needs no other call. A removed light frees its shadow.
  • Near and far Near is 2% of the light’s range and far is range.
  • Shared options filter, format, bias, enabled and resize work as the sun’s do. lift moves the shaded point along its normal by that many texels at its distance from the light. Give the lit description shared: { pointShadow: light.pointShadow.part } to resize without new pipelines.
  • Memory A layer takes size² × 2 bytes in depth16unorm and size² × 4 in the other formats.

The default attenuation, shading.reaching, multiplies in shading.lampShadowed(point, toLight, distance, slot), which a hook of your own can call too. For each light in range, shading compares its slot with each of the count shadows. A shadowed light picks a face from the direction to the point, takes one matrix product and makes the filter’s comparisons.

Each layer is a depth pass that draws every caster, so seven layers cost seven passes each frame. A lamp that holds still over casters that hold still draws the same layers again. Pass redraw to choose the lights that draw this frame. The others keep the layers they drew last:

// Lamps with a caster that moved within their range this frame, from your own game state
const
const stirred: Set<unknown>
stirred
= new
var Set: SetConstructor
new <unknown>(iterable?: Iterable<unknown> | null | undefined) => Set<unknown> (+1 overload)
Set
<unknown>();
import frames
frames
.
function create(root: TgpuRoot, record: Recorder): frames.Frames

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

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

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

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

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.flush(target?: frames.Frame | TgpuCommandEncoder): void

Uploads changes since the last flush with queue.writeBuffer. Writes reach the queue before the next submit. Call once per frame before passes that read the table. A HistoryTable takes the frame or its encoder and throws without one.

flush
();
const light: lighting.LightingOf<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
}>
light
.
pointShadow: pointShadow.PointShadow

Provides the point and spot lights' shadows when enabled in the options.

pointShadow
.
PointShadow.record(frame: frames.Frame | TgpuCommandEncoder, casters: Drawn | readonly Drawn[], options?: pointShadow.PointShadowRecordOptions): void

Places each shadow at its light from the table's CPU rows, then clears and draws the layers of each shadowed light that redraw picks with the casters built by add, a depth pass per layer. Call this while recording each frame, before drawing shaded surfaces. A removed light frees its shadow. A frame that draws no layer writes a timer's timestamps from an empty compute pass.

record
(
frame: frames.Frame
frame
,
const casters: Drawn
casters
, {
PointShadowPrepareOptions.redraw?: ((light: table.RowId) => boolean) | undefined

Chooses which cast lights draw their layers this frame. A light it skips keeps the layers it drew last, so a still light over still casters can skip until something it sees moves. A light still draws when it gains a shadow, when its row moves, turns or changes range, after resize and after a frame with enabled false. Layers count as drawn once their frame submits, so a light recorded into an encoder alone draws on every record until resize. Default every light.

@cpu

redraw
: (
lamp: table.RowId
lamp
) =>
const stirred: Set<unknown>
stirred
.
Set<unknown>.has(value: unknown): boolean

@returns ― a boolean indicating whether an element with the specified value exists in the Set or not.

has
(
lamp: table.RowId
lamp
) });
const stirred: Set<unknown>
stirred
.
Set<unknown>.clear(): void

Removes all elements from the Set.

clear
();
});
  • A light draws even if redraw would skip it when it gains a shadow, moves or changes range, and when a narrow spot turns. It also draws after resize replaces the map and when the shadows come back on.
  • Like the sun’s, its layers count as drawn once their frame submits. A light of no range or with a cone of no width draws no layer.
  • A light whose flicker jitters its position draws every frame; flicker its intensity alone to keep its layers.
  • A frame that draws no layer writes a timer passed in timestampWrites from an empty compute pass, so a profiler timer can stay on record.

A culling renderer culls every layer of a shadow in renderer.cull, before record picks the lights that draw. Give redraw to prepare before culling instead. cull then culls only the layers that draw, one for a narrow spot, and record draws those:

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

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

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

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

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

create
(
const root: TgpuRoot
root
, (
frame: frames.Frame
frame
) => {
const things: instances.Instances<Plain>
things
.
Instances<Plain>.flush(target?: frames.Frame | TgpuCommandEncoder): void

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
();
const lamps: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>
lamps
.
Table<TableDef<"SpotLight", { aim: Vec3f; cone: Vec2f; position: Vec3f; range: F32; color: Vec3f; intensity: F32; }, {}>>.flush(target?: frames.Frame | TgpuCommandEncoder): void

Uploads changes since the last flush with queue.writeBuffer. Writes reach the queue before the next submit. Call once per frame before passes that read the table. A HistoryTable takes the frame or its encoder and throws without one.

flush
();
const light: lighting.LightingOf<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
}>
light
.
pointShadow: pointShadow.PointShadow

Provides the point and spot lights' shadows when enabled in the options.

pointShadow
.
PointShadow.prepare(options?: pointShadow.PointShadowPrepareOptions): void

Chooses the layers that draw this frame before renderer.cull, which then culls only those: the layers of each light redraw picks, and of a narrow spot only its one. The next record draws exactly these and ignores its own redraw. Call it after cast, in the frame that records: a change before that record, such as cast or resize, drops the choice. Without it, culling covers every layer.

prepare
({
PointShadowPrepareOptions.redraw?: ((light: table.RowId) => boolean) | undefined

Chooses which cast lights draw their layers this frame. A light it skips keeps the layers it drew last, so a still light over still casters can skip until something it sees moves. A light still draws when it gains a shadow, when its row moves, turns or changes range, after resize and after a frame with enabled false. Layers count as drawn once their frame submits, so a light recorded into an encoder alone draws on every record until resize. Default every light.

@cpu

redraw
: (
lamp: table.RowId
lamp
) =>
const stirred: Set<unknown>
stirred
.
Set<unknown>.has(value: unknown): boolean

@returns ― a boolean indicating whether an element with the specified value exists in the Set or not.

has
(
lamp: table.RowId
lamp
) });
const
const culling: TgpuComputePass
culling
=
frame: frames.Frame
frame
.
Frame.encoder: TgpuCommandEncoder

Records commands for submission after the recorder returns. submit() replaces this encoder. Read it at each call instead of keeping it, and let the frame submit it.

encoder
.
TgpuCommandEncoder.beginComputePass(descriptor?: TgpuComputePassDescriptor): TgpuComputePass

Begins recording a compute pass

beginComputePass
();
const renderer: instances.Renderer
renderer
.
Renderer.cull(pass: TgpuComputePass): void

Records visible-instance lists for each enabled description that contains this renderer, for the layers it reports active, such as those a shadow's prepare picked. Call this after flush() and any kernels that move instances, before drawing. Throws unless the renderer has cull: true.

cull
(
const culling: TgpuComputePass
culling
);
const culling: TgpuComputePass
culling
.
TgpuComputePass.end(): void

Completes the recording of this compute pass

end
();
const light: lighting.LightingOf<{
readonly points: {
readonly table: table.Table<table.TableDef<"SpotLight", {
aim: Vec3f;
cone: Vec2f;
position: Vec3f;
range: F32;
color: Vec3f;
intensity: F32;
}, {}>>;
};
readonly pointShadow: pointShadow.PointShadowDefinition;
}>
light
.
pointShadow: pointShadow.PointShadow

Provides the point and spot lights' shadows when enabled in the options.

pointShadow
.
PointShadow.record(frame: frames.Frame | TgpuCommandEncoder, casters: Drawn | readonly Drawn[], options?: pointShadow.PointShadowRecordOptions): void

Places each shadow at its light from the table's CPU rows, then clears and draws the layers of each shadowed light that redraw picks with the casters built by add, a depth pass per layer. Call this while recording each frame, before drawing shaded surfaces. A removed light frees its shadow. A frame that draws no layer writes a timer's timestamps from an empty compute pass.

record
(
frame: frames.Frame
frame
,
const casters: Drawn
casters
);
const stirred: Set<unknown>
stirred
.
Set<unknown>.clear(): void

Removes all elements from the Set.

clear
();
});
  • Call prepare after cast and after moving lights, in the frame that records. That record ignores a redraw of its own.
  • A change between prepare and record, such as cast, aim or resize, drops the choice. record then picks again, and those layers draw again the next frame.
  • The sun’s shadow takes the same prepare, with its cascades’ redraw.
  • Without prepare, culling covers every layer of an enabled shadow.

Call light.destroy() when nothing draws with its resources. It frees the shadow maps and their drawing resources. A table of lights is yours to destroy.

  • Culling Without candidates, every shaded pixel visits each light slot. There is no tile or cluster culling.
  • Clear coat shadeClear is exact for dielectrics and metals. It approximates intermediate metallic values.
  • One lighting A pipeline reads one lighting, the one piped last. Two lightings in one frame, such as a lit room seen through a window, need two sets of pipelines.
  • Depth precision A fixed map’s depth spans twice reach. At an extent of 20, a depth16unorm step is about 0.001 world units. A cascade’s depth spans its sphere’s width plus reach.
  • Cascade reach Cascades fit the camera’s view, not the casters. A caster beyond reach towards the sun casts nothing, and nothing beyond far is shadowed.
  • Fixed filter The filter is fixed at creation. A menu offering different filters needs a separate lighting for each.
  • Shadow casters Only lights placed on the CPU cast. lighting.create throws for pointShadow without points.table, or with a table of lighting.MovingPointLight or MovingSpotLight.
  • Layer cost Each layer that draws draws all its casters: six passes for a point light and one for a narrow spot.
  • Shadow count count is at most 42 at WebGPU’s minimum of 256 layers, and at most 157 in a uniform binding of 64 KiB. Shading compares every in-range light with every shadow, so its cost grows with count.
hookA hook is a placeholder that each pipeline fills with its own choice, such as the camera it draws through.Members and placeholders →
rendererA renderer draws one sort of thing, such as instances or particles, by handing a pass description a drawing.Every renderer is a drawing →
linear lightLinear light is colour as amounts of light, the form in which lighting adds up correctly, before the final pass encodes it for the screen.Words →
instanceAn instance is one copy of a mesh with its own position, rotation, scale and material, kept as a row of a table.Instances →
tableA table is a buffer of rows with named fields, some written by the CPU and the others by kernels.Rows →
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 →
flushA flush uploads the rows the CPU changed since the last one.Rows →
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 →
slotA slot is a row's place in its buffers, which a new row can take once the first is removed.Row ids →
storage bufferA storage buffer is GPU memory that shaders read by index and kernels can write, which is where the kit keeps rows.Words →
bindingA binding is one buffer, texture or sampler in a bind group, which a shader reads by its place there.Words →
fillA fill is the resource a pipeline binds for an accessor its shaders read.Members and placeholders →
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 →
texelA texel is one cell of a texture, as a pixel is one cell of the screen.Words →
dispatchA dispatch runs a kernel once over a number of threads, inside a compute pass.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 →
bind groupA bind group is a set of buffers, textures and samplers that a pipeline reads, and a pipeline has room for four.Words →
rowA row is one object's values in a buffer, such as one enemy, one particle or one light.Objects are rows in buffers →

Reference

kit.lighting

moduleHow to read this card

Creates lighting with a sun, sky and fog.

Callsborrows, never destroystakesreturns

lighting.create(root, { points?, shadow?, pointShadow?, … }?) → Lighting

root
the root
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
shadow?
the sun's shadow, with a depth pass per cascade
pointShadow?
shadows from pointShadow.define that cast gives to lights of points.table, with a depth pass per face
Lighting
lighting you destroy
takes

Options

5 fields
settings?

Partial<Settings>

Sets initial sun, sky and fog values over defaults.Default defaults, which has no fog.

shading?

Shading

Sets the functions that shading.shade calls.Default pbr, hemisphere, heightFog, sunShadowed and reaching.

points?

PointsOptions

Enables point lights from a table or a function.Default none.

shadow?

ShadowOptions

Enables and configures the shadow from the sun.Default none.

pointShadow?

PointShadowDefinition

Gives up to count point or spot lights a shadow each, as pointShadow.define describes them, which light.pointShadow.cast assigns.Default none.

takes

PointsOptions

points · 5 fields
table?

LightTable

Supplies a table of lighting.PointLight, MovingPointLight, SpotLight or MovingSpotLight.Default none, lights from light or spot.

candidates?

Candidates

Limits the loop to lights that may reach each shaded point, as grid.Candidates name them.Default every live slot.

light?

(slot: number) => Light'use gpu'

Returns the light at a slot.Default none, lights from table or spot.

spot?

(slot: number) => Spot'use gpu'

Returns the spot light at a slot, whose cone comes from lighting.cone.Default none, lights from table or light.

count?

number

Sets how many slots, from 0, every lit point visits.Default none, the slots candidates names.

takes

ShadowOptions

shadow · 14 fields
extent?

number

Sets the width of the square covered by the map in world units.Default 20.

center?

Vec3

Centres the square here at first.Default the origin.

eye?

CpuView

Fits the map to this camera's view, in cascades layers that reach far from the eye.Default none, a fixed map.

cascades?

1 | 2 | 3 | 4

Splits the view into 1 to 4 cascades, each a layer of the map drawn in a pass of its own.Default 1.

far?

number

Sets how far from the eye the cascades reach, in world units.Default 50.

splits?

number[]

Places the splits between cascades as fractions of far, cascades - 1 rising values between 0 and 1.Default (k / cascades)² after cascade k, 0.11 and 0.44 for three.

fit?

CascadeFit

Places the cascades in the sun's light space whenever the shadow fits them: on each record, after aim and after setFar.Default lighting.fitSlices, a sphere around each slice of the view, snapped to whole texels.

size?

number

Sets the width and height of each layer of the map in texels.Default 2048.

reach?

number

Sets how far the map reaches towards the sun in world units: from the point it follows, or beyond each cascade with an eye.Default twice the extent, or far with an eye.

filter?

1 | 4 | 9

Sets the number of comparisons per shaded point to 1, 4 or 9.Default 4.

format?

'depth16unorm' | 'depth24plus' | 'depth32float'

Sets the depth format of the map.Default 'depth16unorm'.

bias?

{ constant?: number; slope?: number }

Offsets depth written by caster pipelines to prevent self-shadowing.Default { constant: 2, slope: 2 }.

lift?

number

Moves a shaded point along its normal before comparison, in texels.Default 1.

enabled?

() => boolean

Controls whether record draws the shadow in the current frame.Default always.

returns

Lighting

8 members
settings

TgpuUniform<Settings>

Holds the sun, sky and fog values from defaults and the settings option.

shadow?

Shadow | Cascades

Provides the sun shadow when enabled in the options.

shadow.record(frame, casters, options?)

Clears the map in a depth pass per cascade that redraw picks and draws the casters built by add.

pointShadow?

PointShadow

Provides the point and spot lights' shadows when enabled in the options.

pointShadow.record(frame, casters, options?)

Places each shadow at its light from the table's CPU rows, then clears and draws the layers of each shadowed light that redraw picks with the casters built by add, a depth pass per layer.

inject()

Fills the shading hooks and resources for pipelines created from the configuration you pipe it into.

initAsync()

Compiles the pipelines of its shadows.

destroy()

Destroys the shadows' maps and the casters added to them.

takes

ShadowRecordOptions

shadow.record · 3 fields
clear?

boolean | (keyof W & string)[]

Selects targets to clear.Default true.

timestampWrites?

TimestampWrites | undefined

Supplies a timer's writes for the passes.Default none.

redraw?

(cascade: number) => boolean

Chooses which cascades draw their layer this frame, by index from the nearest.Default every cascade.

lighting.fitSlices(input, places)

input
the eye, the sun's light space and the shadow's settings
places
the places it writes, one per cascade

In a frame

records

shadow.record and pointShadow.record with what was added to them, before the passes that shade.

Holds

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.

lifecycle

initAsync()destroy()[Symbol.dispose]

binds
  • 1 uniform

    shading.shade, the sun, sky and fog.

  • 2 storage · 1 uniform

    shading.shade with a table of point lights.

  • 3 storage · 1 uniform

    shading.shade with a table of lights whose positions are on the device, the table's two parts.

  • 1 uniform

    shading.shade with points.light or points.spot, plus what the function binds.

  • none

    shading.shade with points.candidates, plus what their functions bind, 2 storage for a neighbour grid's range and slot.

  • 1 uniform

    shading.shade with a shadow, the sun's light space and cascades, beside the depth array and its comparison sampler.

  • 1 uniform

    shading.shade with pointShadow, each shadow's light, layers and views, beside their depth array and the comparison sampler.

Connects to

injects
  • hook

    The shading hooks its options name: reflect, ambient, fog, sunShadow and attenuation.

  • definition

    The sun, sky and fog, the shadows and the point lights, which shading reads.

Exports

GPU functions
cone
schemas
Light Spot Settings Span
constants
defaults WHITE
helpers
PointLight MovingPointLight SpotLight MovingSpotLight WHITE_SPOT
types
CascadeFit CascadeFitInput CascadePlace Cascades FittedShadowOptions FixedShadowOptions Shadow ShadowMapOptions ShadowPrepareOptions SunShadow Shading LightTable TablePoints LightPoints SpotPoints PointLights MovingPointLights SpotLights MovingSpotLights LightingOf Shadowed PointShadowed
schema

Light

4 fields
position

d.vec3f

range

d.f32

Sets the distance in world units where light intensity reaches zero.

color

d.vec3f

Sets the light colour in linear colour space.

intensity

d.f32

Multiplies color.

schema

Spot

6 fields
aim

d.vec3f

Points the cone's axis away from the light.

cone

d.vec2f

Holds the cone's scale and offset from lighting.cone(inner, outer).

position

d.vec3f

range

d.f32

Sets the distance in world units where light intensity reaches zero.

color

d.vec3f

Sets the light colour in linear colour space.

intensity

d.f32

Multiplies color.

schema

Settings

11 fields
sunDirection

d.vec3f

Points towards the sun.

sunIntensity

d.f32

Multiplies sunColor.

sunColor

d.vec3f

Sets the sun colour in linear colour space.

skyIntensity

d.f32

Multiplies skyTop and skyBottom.

skyTop

d.vec3f

Sets the linear sky colour from directly above.

fogDensity

d.f32

Sets fog density per world unit at y = 0.

skyBottom

d.vec3f

Sets the linear ground colour from directly below.

fogFalloff

d.f32

Sets how fog density falls with height.

fogColor

d.vec3f

Sets the fog colour in linear colour space.

skyReflection

d.f32

Scales sky reflections in addition to skyIntensity.

fogStart

d.f32

Sets the distance from the eye in world units where fog begins.

schema

Span

2 fields
first

d.u32

count

d.u32

used byAfterimageBlockfallCenserClassroomCloisterDomino runFireworksFish tankForestHex isleKineticNight marketQuiver treesRobot armSkeletonsSPH sculptSpiderStampedeSurvey model

kit.shading

shaderHow to read this card

These 'use gpu' functions shade surfaces with the lighting injected into their pipeline, and read its shadows.

Connects to

reads
  • cameras

    Its inject() fills them in the calling pipeline.

  • lighting

    Its inject() fills them in the calling pipeline.

Exports

GPU functions
pointAt settings towardsSun falloff beam beamOf pbr lambert reflectance specularOcclusion reflectionOf surrounded hemisphere haze heightFog cascadeOf cascadeShadowed sunShadowed lampShadowed reaching sunShare sun direct unfogged shade shadeClear incoming
accessors
reflect ambient fog sunShadow attenuation
schemas
Material Point Air CascadeAt
types
ReflectHook AmbientHook FogHook SunShadowHook AttenuationHook
schema

Material

5 fields
color

d.vec3f

Sets the diffuse colour of a dielectric or the reflection colour of a metal, in linear colour space.

roughness

d.f32

Sets roughness from 0 for a mirror to 1 for chalk.

emission

d.vec3f

Sets the emitted light in linear colour space.

metallic

d.f32

Sets metallic content from 0 for a dielectric to 1 for a metal.

occlusion

d.f32

Sets the share of ambient light that reaches the surface, from 0 in a crevice to 1 in the open, such as glTF's occlusion texture.

schema

Point

5 fields
position

d.vec3f

normal

d.vec3f

Holds a unit surface normal.

view

d.vec3f

Holds a unit direction from the point towards the eye.

uv

d.vec2f

Holds texture coordinates at the point.

uv1

d.vec2f

Holds the second uv set at the point, a mesh's uvs1, or zero.

schema

Air

2 fields
added

d.vec3f

through

d.vec3f

schema

CascadeAt

2 fields
index

d.i32

edge

d.f32

Rises from 0 to 1 over the outer 10% of the cascade's square.

used byAfterimageBlockfallCenserClassroomCloisterDomino runFireworksFish tankForestHex isleKineticNight marketQuiver treesRobot armSkeletonsSolar systemSPH sculptSpiderStampedeSurvey model

kit.materials

shaderHow to read this card

These 'use gpu' functions create materials for shading.shade, with colours or mesh textures.

Connects to

reads
  • meshPool

    Its inject() fills them in the calling pipeline.

Exports

GPU functions
matte glossy metal glow uvOf textured antialiased masked mappedNormal

used byAfterimageBlockfallCenserDomino runFireworksFish tankForestKineticNight marketQuiver treesRobot armSkeletonsSolar systemSPH sculptSpiderStampedeSurvey model

kit.pointShadow

cpuHow to read this card

Point and spot shadows for a lighting: define describes them, and lighting.create makes them for the lights of its table as light.pointShadow, compiles them in initAsync, fills their shading and destroys them.

Callstakesreturns

pointShadow.define(options?) → PointShadowDefinition

options?
the shadows' count, layer size, filter and depth format
PointShadowDefinition
a definition to give lighting.create as pointShadow
takes

PointShadowOptions

7 fields
count?

number

Sets how many lights can cast a shadow at once, each with six layers of the map.Default 1.

size?

number

Sets the width and height of each layer in texels, above twice the filter's reach: 2 for filter 1, 3 for 4 and 4 for 9.Default 512.

filter?

1 | 4 | 9

Sets the number of comparisons per shaded point to 1, 4 or 9.Default 4.

format?

'depth16unorm' | 'depth24plus' | 'depth32float'

Sets the depth format of the map.Default 'depth16unorm'.

bias?

{ constant?: number; slope?: number }

Offsets depth written by caster pipelines to prevent self-shadowing.Default { constant: 2, slope: 2 }.

lift?

number

Moves a shaded point along its normal before comparison, in texels at its distance from the light.Default 1.

enabled?

() => boolean

Controls whether record draws the shadows in the current frame.Default always.

Exports

types
PointShadowPrepareOptions PointShadowRecordOptions PointShadow PointShadowDefinition

used byBlockfallCloisterNight marketRobot arm