#shader Region
Purpose
A #shader region holds the programs a GPU runs: vertex, pixel,
compute, task and mesh shaders, written in tape. The compiler checks them with
the rest of the module, and the standard library’s shader compiler turns
each one into SPIR-V (for Vulkan), GLSL (for OpenGL) and the Metal
Shading Language (for Metal) while the program compiles. You never write
SPIR-V, GLSL or Metal yourself. In tape code, each shader’s name is a
gpu.Shader constant that the gpu module makes
pipelines from.
#code
import gpu from "gpu";
pub struct Particle { pos: gpu.Vec2; vel: gpu.Vec2; }
pub struct Step { dt: f32; count: u32; }
pub struct View { scale: gpu.Vec2; tint: gpu.Vec4; }
fn pipelines(dev: *gpu.Device) -> void or gpu.GpuError {
let step = dev.compute_pipeline(&advance) or return; // advance is a gpu.Shader
let dots = dev.render_pipeline(&dot_vs, &dot_ps, gpu.RenderOptions {
primitive: gpu.Primitive.TriangleStrip;
}) or return;
let s_particles = step.slot("ps"); // slots by parameter name
let s_instances = dots.slot("p");
}
#shader
import gpu from "gpu";
compute(64) fn advance(ps: []Particle, u: uniform Step) {
let i = gpu.global_id().x;
if (i >= u.count) { return; }
var p = ps[i];
p.pos = p.pos + p.vel * u.dt;
ps[i] = p;
}
pub struct DotOut { position: gpu.Vec4; tint: gpu.Vec4; }
vertex fn dot_vs(corner: gpu.Vec2, p: instance Particle, u: uniform View) -> DotOut {
let at = p.pos + corner * 0.01;
return DotOut { position: gpu.vec4(at.x * u.scale.x, at.y * u.scale.y, 0.0, 1.0);
tint: u.tint; };
}
pixel fn dot_ps(v: DotOut, u: uniform View) -> gpu.Vec4 {
return v.tint;
}The region needs import gpu from "gpu"; (in the region or in #code:
one import serves both). A shader written wrong is a compile error at
its line, from tape check, tape run and tape build alike, on every
platform: the SPIR-V, the GLSL and the Metal text are all made wherever you
compile.
Stages
A stage is a function with a stage word before fn:
| Declaration | Runs | Returns |
|---|---|---|
vertex fn name(params) -> Out | once per vertex | a struct with a field position: gpu.Vec4 (clip space) |
pixel fn name(v: Out, params) -> gpu.Vec4 | once per covered pixel | the pixel’s colour, premultiplied |
pixel fn name(v: Out, params) -> Targets | the same | one value per colour target: a struct of gpu.Vec4s (gpu.UVec4s for integer targets) |
pixel fn name(v: Out, params) | the same | nothing: a depth-only pass (a shadow map) |
compute(x) fn name(params) | once per invocation | nothing |
task(x) fn name(params) -> gpu.UVec3 | once per invocation of a mesh pipeline’s task workgroups | the mesh workgroups to launch |
mesh(x) fn name(params) | once per invocation of its mesh workgroups | nothing: it writes vertices and triangles |
-
compute(x),compute(x, y)andcompute(x, y, z)give the workgroup size: constant integers, each 1 to 1024.compute fnwithout it is an error.task(...)andmesh(...)take theirs the same way (Mesh and task stages). -
A vertex shader’s output struct passes its other fields on to the pixel shader, interpolated across the triangle (integer fields are passed flat, not interpolated).
-
@centroidon such a field keeps it in range at the edge of a triangle under multisampling. A thin triangle can cover a sample while the pixel’s centre lies outside it; a plain field is still evaluated at the centre, so it is extrapolated, and a colour can come out huge. A@centroidfield is evaluated at a point the triangle covers:tapestruct Out { position: gpu.Vec4; @centroid colour: gpu.Vec4; uv: gpu.Vec2; }It is per field and never automatic because it has a cost: neighbouring pixels are no longer evaluated evenly spaced, so
ddx,ddyandfwidthof that field are less accurate, and a texture sampled with it chooses its mip level less well. Mark what must not leave its range (a colour, a weight) and leave auva mipmapped texture reads unmarked. It means nothing without multisampling. A mesh stage’s vertex struct takes it the same way. On an integer field orposition, or on a struct’s field the stage names as something else than its vertex output (a vertex input, a uniform, a colour target’s), it is a compile error. -
A pixel shader’s first parameter is that same struct, interpolated. The render pipeline checks that the vertex shader’s output and the pixel shader’s input are the same struct.
-
A pixel shader writing several targets at once (a G-buffer) returns a struct of up to 8 fields, each a
gpu.Vec4or, for an integer target (R32u), agpu.UVec4: fieldiis colour targetiof the pass, and the pipeline names their formats (RenderOptions.formats). One integer target alone is a-> gpu.UVec4stage.
Clip space is the same on every backend: x and y from -1 to 1 with y up, z from 0 to 1.
Parameters
A stage’s parameters are where its data comes from. Their types say what each one is:
| Parameter | Is | The program binds |
|---|---|---|
vals: []T | a storage buffer, read and written | a buffer with gpu.STORAGE |
vals: []const T | a storage buffer, read only | the same |
ctr: *T | a storage buffer holding one struct (counters, a header) | the same |
atlas: gpu.Texture2D | a texture of floats | a texture and a gpu.Sampler |
ids: gpu.UTexture2D | a texture of unsigned integers (R32u) | the same |
depth: gpu.DepthTexture2D | a depth texture (Depth32f), read as f32 | the same |
layers: gpu.Texture2DArray | a 2D array texture of floats | an array texture and a sampler |
vol: gpu.Texture3D | a 3D texture of floats | a 3D texture and a sampler |
img: gpu.ImageRgba16f (ImageRgba8, ImageR32u, …) | a storage image of that format, read and written by texel (compute and pixel stages) | a texture made with storage: true, of that format |
u: uniform T | the stage’s constants for one draw or dispatch: a struct, at most one per stage | a value of T |
corner: T (vertex) | the vertex’s attributes: a scalar, a vector or a struct of them | a buffer with gpu.VERTEX |
p: instance T (vertex) | the same, one per instance | a buffer with gpu.VERTEX, drawn instanced |
v: Out (pixel, first) | the vertex shader’s output (the mesh shader’s vertex in a mesh pipeline) | nothing: the pipeline joins the stages |
p: payload *T (task), p: payload *const T (mesh) | the payload a task workgroup writes for the mesh workgroups it launches | nothing |
verts: vertices *[N]V, tris: primitives *[M]gpu.UVec3 (mesh) | the mesh workgroup’s vertices (at most N) and triangles (at most M) | nothing |
One buffer can be storage for one shader and a vertex stream for another:
a compute shader writes the particles, and the render pass draws the same
buffer as instances, with no copy (make it gpu.STORAGE | gpu.VERTEX).
A pixel stage takes @early_depth, which runs the depth test before the stage
instead of after it. A stage that writes to storage otherwise runs for hidden
pixels too, so a list of fragments or a count would hold ones the test then
rejects:
@early_depth pixel fn layer_ps(v: Out, nodes: []Node, count: []u32) {
let i = gpu.atomic_add(&count[0], 1);
nodes[i] = Node { depth: gpu.frag_coord().z; };
}On any other stage it is a compile error. A pixel the stage then discards has already written its depth: the test was over before the stage ran.
Slots and uniforms
The program never counts bindings. It looks each one up by the
parameter’s name once, next to the pipeline, and keeps the gpu.Slot.
The uniforms are a struct of your own: gpu.gen_uniforms(T) makes a
setter for it, uniforms_T(&pass, &u), called in a pass before the
draw or dispatch.
#code
import gpu from "gpu";
pub struct Particle { pos: gpu.Vec2; vel: gpu.Vec2; }
pub struct Step { dt: f32; count: u32; }
@tape { gpu.gen_uniforms(Step); } // makes uniforms_Step(pass, u)
fn step_all(dev: *gpu.Device, particles: *const gpu.Buffer, n: u32) -> void or gpu.GpuError {
let step = dev.compute_pipeline(&advance) or return;
let s_ps = step.slot("ps"); // the parameter's name
var u = Step { dt: 0.016; count: n; };
var cp = dev.compute();
cp.pipeline(&step);
uniforms_Step(&cp, &u);
cp.storage(s_ps, particles, 0);
cp.dispatch_for(n as i64); // n invocations, in groups of 64
cp.end();
}
#shader
import gpu from "gpu";
compute(64) fn advance(ps: []Particle, u: uniform Step) {
let i = gpu.global_id().x;
if (i >= u.count) { return; }
ps[i].pos = ps[i].pos + ps[i].vel * u.dt;
}- A render pipeline joins its vertex and pixel stages by name: a
parameter of the same name in both stages is one binding (and must be
the same kind of resource in both), and
uniformparameters in both stages are the pipeline’s one uniform struct, set once for both. slotwith a name the pipeline lacks traps, naming it.uniforms_Tpasses the struct’s bytes and its name; the pass traps if the pipeline’s uniform struct is another one or has another size.- A dispatch or draw with a slot or the uniforms never set traps, naming what is missing.
Sharing declarations with #code
The region’s structs, enums, consts and helper functions are the
module’s, like those of #code, and a struct or a const declared in
#code is usable in a shader (a const’s value is written into the
shader). The particle struct the compute shader writes is the
one the program fills on the CPU:
#code
import gpu from "gpu";
import io from "io";
fn main() -> i32 {
io.println("{cell_of(gpu.vec2(3.5, 2.0), 10)} of {CELLS}"); // 23 of 100
return 0;
}
#shader
import gpu from "gpu";
const CELLS: u32 = 100;
fn cell_of(p: gpu.Vec2, width: u32) -> u32 {
return (p.y as u32) * width + (p.x as u32);
}
compute(16, 16) fn mark(cells: []u32) {
let id = gpu.global_id();
let c = cell_of(gpu.vec2(id.x as f32, id.y as f32), 16);
if (c < CELLS) { cells[c] = 1; }
}A helper is ordinary tape, so #code can call it on the CPU. A stage
function can’t be called: in #code its name is the gpu.Shader value
(cannot call a value of type 'gpu.Shader').
A helper can take a buffer or texture as a parameter of its own; what it is given must be one of the stage’s resource parameters (or of the calling helper’s):
#shader
import gpu from "gpu";
fn at(din: []const u32, x: u32, y: u32, width: u32) -> u32 {
return din[y * width + x];
}
compute(64) fn copy_row(din: []const u32, dout: []u32) {
let i = gpu.global_id().x;
dout[i] = at(din, i, 0, 64);
}What a shader can use
Inside #shader the language is tape’s, cut down to what a GPU runs.
Types: bool, i32, u32, f32; gpu’s vectors and Mat4;
structs and fixed arrays ([4]u32) of these; enums, which are their
integers on the GPU. Not i64, u64 or f64 (GPUs lack them),
string, optionals, slices other than parameters, or pointers other
than a *T parameter and the & of an atomic.
Statements: let, var, assignment (=, +=, …), if/else,
while, for (i in a..b), break, continue, return, and in a
compute stage shared name: [N]T; (workgroup memory, below). Not
match, defer, or, fire, or for over anything but a range.
Calls: the region’s helpers and gpu’s functions: the vectors’
methods and operators, the math, and the intrinsics below. A helper may
not call itself, directly or through another. A function of #code or
of another module is not a shader function and is an error at the call.
The region holds imports, structs, enums, consts and functions, and nothing else:
- no
varorletat the top level: a shader reads only its parameters, consts and literals; - no components,
threads,@tapeblocks or@link; - no methods,
extern fnor@tape fn(vector maths isgpu’s methods, which shaders call); - no
unionortagged.
Vectors and matrices
| Type | Lanes |
|---|---|
gpu.Vec2, gpu.Vec3, gpu.Vec4 | f32 |
gpu.IVec2, gpu.IVec3, gpu.IVec4 | i32 |
gpu.UVec2, gpu.UVec3, gpu.UVec4 | u32 |
gpu.Mat4 | four Vec4 columns, c0 to c3 |
They are plain structs (v.x, v.y, …) that work on the CPU as well:
math3d’s, which gpu names as its own
(gpu.Vec3 is math3d.Vec3). A shader may write either module’s names;
the GPU forms are the ones below, and the rest of math3d (inverses,
quaternions, …) is CPU code.
- Made with
gpu.vec2(x, y)…gpu.uvec4(...), and one value in every lane withgpu.splat2(v),splat3,splat4,isplat2…usplat4. + - * /between two vectors of one type, and with the lane type on either side (v * 2.0,2.0 * v); unary-on float and signed vectors;%on integer vectors;==compares the whole value.Vec3andVec4have.xy,Vec4.xyz(and the same on the integer vectors).- Float vector methods:
length,normalize,dot,distance,abs,floor,ceil,round,fract,sign,min,max,clamp,mix,step,smoothstep,reflect,cross(Vec3), andto_iandto_uto the integer vectors.ddx,ddyandfwidthtoo, in a pixel stage, the vector forms ofgpu.ddxand its kin. Integer vectors havemin,max,clamp,abs(signed),to_f, andto_uorto_i. Mat4 * Vec4,Mat4 * Mat4,gpu.mat4_identity()andgpu.mat4_ortho(left, right, bottom, top).
A u32’s bits: gpu.clz(v) and gpu.ctz(v) (leading and trailing zeros, each 32 for
0), gpu.popcount(v), gpu.bit_reverse(v); an f32’s: gpu.float_bits(f) -> u32,
gpu.bits_float(u) -> f32. They work on the CPU as well.
Scalar maths on f32: gpu.asin, acos, gpu.floor, ceil, round (a half away from
zero, as on the CPU), fract, sin, cos,
tan, atan2, sqrt, inverse_sqrt, pow, exp, log, abs,
sign, min, max, clamp, mix, step, smoothstep, fmod
(GLSL’s mod). On integers: gpu.min_i, max_i, clamp_i, abs_i,
min_u, max_u, clamp_u. Tape has no overloading by parameter type,
so the integer forms have their own names.
Intrinsics
| Call | Stage | Gives |
|---|---|---|
gpu.global_id() -> UVec3 | compute, task, mesh | the invocation’s position in the whole dispatch |
gpu.local_id() -> UVec3 | compute, task, mesh | its position in its workgroup |
gpu.group_id() -> UVec3 | compute, task, mesh | its workgroup’s position (a mesh workgroup’s among those its task workgroup launched) |
gpu.set_mesh_counts(vertices: u32, triangles: u32) | mesh | how many vertices and triangles the workgroup writes |
gpu.vertex_index() -> u32 | vertex | the vertex’s number |
gpu.instance_index() -> u32 | vertex | the instance’s number |
gpu.frag_coord() -> Vec4 | pixel | the pixel’s position in the target |
gpu.primitive_id() -> u32 | pixel | which primitive of its draw this pixel is of (Info.primitive_id), from 0 in each draw and each instance |
gpu.discard() | pixel | drops the pixel: no colour, no depth, and what the stage writes to storage after it has no effect |
gpu.sample(t, uv: Vec2) -> Vec4 | any | the texture at uv, through its sampler |
gpu.load(t, at: IVec2) -> Vec4 | any | one texel, no filtering |
gpu.load_u(t, at: IVec2) -> UVec4 | any | one texel of a UTexture2D |
gpu.size(t) -> IVec2 | any | the texture’s width and height |
gpu.sample_depth(t, uv: Vec2) -> f32 | any | a DepthTexture2D at uv, through its sampler |
gpu.load_depth(t, at: IVec2) -> f32 | any | one depth texel, no filtering |
gpu.sample_level(t, uv: Vec2, lod: f32) -> Vec4 | any | the texture at a mip level (fractions blend levels, with a MipFilter.Linear sampler) |
gpu.sample_grad(t, uv: Vec2, dx: Vec2, dy: Vec2) -> Vec4 | any | the texture at uv, the level from how uv changes across a pixel, as given (fine for anisotropic footprints your own code works out) |
gpu.ddx(v: f32) -> f32, gpu.ddy(v), gpu.fwidth(v) | pixel | how v changes to the next pixel right, to the next row down, and the sum of the sizes |
gpu.sample_table(t, i: u32, uv: Vec2) -> Vec4 | any | texture i of a Texture2DTable at uv; i may differ per invocation and must be below the table’s length |
gpu.sample_table_level(t, i, uv, lod: f32), gpu.sample_table_grad(t, i, uv, dx, dy) | any | the same at a level, by gradients |
gpu.load_table(t, i, at: IVec2) -> Vec4, gpu.size_table(t, i) -> IVec2 | any | one texel of texture i, its size |
gpu.load_level(t, at: IVec2, level: i32) -> Vec4 | any | one texel of a level |
gpu.sample_array(t, uv: Vec2, layer: i32) -> Vec4 | any | a Texture2DArray’s layer at uv |
gpu.sample_array_level(t, uv, layer: i32, lod: f32) -> Vec4 | any | the same, at a mip level |
gpu.load_array(t, at: IVec2, layer: i32, level: i32) -> Vec4 | any | one texel of a layer’s level |
gpu.sample_3d(t, uvw: Vec3) -> Vec4 | any | a Texture3D at uvw (0..1 each way) |
gpu.sample_3d_level(t, uvw: Vec3, lod: f32) -> Vec4 | any | the same, at a mip level |
gpu.load_3d(t, at: IVec3, level: i32) -> Vec4 | any | one texel of a level |
In a vertex or compute stage a texture is sampled at level 0 (sample,
sample_array, sample_3d, sample_depth): only a pixel stage picks
the level from how fast uv changes across the screen. sample_level
names it anywhere.
| gpu.atomic_add(p, v), atomic_min, atomic_max, atomic_exchange | any | the old value; p is &buf[i] or &ctr.field of a u32 |
| atomic_add_i, atomic_min_i, atomic_max_i, atomic_exchange_i | any | the same on i32 |
| gpu.atomic_compare_exchange(p, expected, value), atomic_compare_exchange_i | any | value goes in only if *p is expected; the old value either way: it won if that is expected |
Texture coordinate (0, 0) is the first texel of row 0, and row 0 is the top of the texture, on every backend.
A gpu.Texture2DTable parameter is a stage’s many textures by index, one to a stage
(pass.texture_table, gpu):
pixel fn resolve_ps(v: Out, mats: gpu.Texture2DTable, ids: gpu.UTexture2D) -> gpu.Vec4 {
let c = gpu.frag_coord();
let m = gpu.load_u(ids, gpu.ivec2(c.x as i32, c.y as i32)).x;
return gpu.sample_table(mats, m, v.uv);
}ddy counts rows down the target, on every backend: gpu.ddy(gpu.frag_coord().y)
is 1, and a coordinate that rises with clip space’s y has a negative ddy.
gpu.primitive_id() is what a visibility buffer stores. It counts from 0 in each
draw and each instance whatever the first_index, so a program adds its own base
from a uniform. A device without it refuses the pipeline by name, and so does a
mesh pipeline, whose stage has no way to set it.
pixel fn visibility_ps(v: Out, u: uniform Draw) -> gpu.UVec4 {
return gpu.uvec4(u.base + gpu.primitive_id(), 0, 0, 0);
}gpu.discard() is the alpha test: a card of foliage writes depth only where it
has a leaf. It is a pixel stage’s: a call from any other stage, or from a helper
another stage calls, is a compile error at the call. It doesn’t return from the
stage as far as the source goes, so the stage still ends with its return.
pixel fn leaf_ps(v: Out, atlas: gpu.Texture2D) -> gpu.Vec4 {
let c = gpu.sample(atlas, v.uv);
if (c.w < 0.5) { gpu.discard(); }
return c;
}#shader
import gpu from "gpu";
struct Counters { alive: u32; died: u32; }
compute(256) fn census(hp: []const f32, ctr: *Counters, bins: []u32) {
let i = gpu.global_id().x;
if (hp[i] > 0.0) { gpu.atomic_add(&ctr.alive, 1); } else { gpu.atomic_add(&ctr.died, 1); }
gpu.atomic_add(&bins[i % 16], 1);
}Layout
A struct that crosses to the GPU (a storage element, a vertex input, the
uniforms) has the compiler’s layout there too, the same offsets as on
the CPU, so the program writes it with bytes.gen_of(T)’s of_T and
reads it back as it is. gpu’s vectors are aligned the way the GPU
aligns them (Vec2 to 8 bytes, Vec4 to 16) to make that hold.
Vec3,IVec3andUVec3don’t cross: GLSL and Metal give them different sizes. Use the 4-lane vector. In locals they are fine.booldoesn’t cross either: use au32.- A vertex struct is read at the CPU’s offsets, so a
@packedone is fine. A storage or uniform struct whose fields the GPU would place differently (aVec4at byte 8) is an error naming the field.
Workgroup memory and subgroups
A compute stage’s invocations run in workgroups (its compute(x, y, z)
size), and a workgroup’s invocations share memory the stage declares in
its body:
#shader
import gpu from "gpu";
// each workgroup's 256 values summed: written to shared memory, the
// barrier, then read by the first invocation
compute(256) fn reduce(vals: []const f32, sums: []f32) {
shared part: [256]f32;
let l = gpu.local_id().x;
part[l] = vals[gpu.global_id().x];
gpu.barrier();
if (l == 0) {
var s: f32 = 0.0;
for (i in 0..256) { s = s + part[i]; }
sums[gpu.group_id().x] = s;
}
}shared name: [N]T;declares a fixed-size array of the workgroup, in the stage function itself (not in a helper, never at the top of the region). It has no initializer and starts unset.gpu.barrier()(in a compute, task or mesh stage) waits until every invocation of the workgroup has reached it; what they wrote to shared memory before it is then visible to all. Every invocation must reach it: not inside anifsome of them skip.
A workgroup runs in subgroups (a SIMD group, a wave: 32 invocations on most GPUs), whose invocations exchange values without memory:
| Call | Gives |
|---|---|
gpu.subgroup_size(), gpu.subgroup_lane(), gpu.subgroup_id() | the subgroup’s size, this invocation’s lane in it, the subgroup’s index in the workgroup (u32) |
gpu.subgroup_add(v), subgroup_min(v), subgroup_max(v) | over the subgroup’s invocations (u32; _f forms for f32) |
gpu.subgroup_exclusive_add(v), subgroup_inclusive_add(v) | the sum over the lanes before this one, or up to it: a prefix sum (_f too) |
gpu.subgroup_any(b), subgroup_all(b) | whether any, or every, invocation’s b holds |
gpu.subgroup_ballot(b) -> UVec4 | a bit per lane where b holds (lanes 0 to 31 in x, 32 to 63 in y) |
gpu.subgroup_broadcast(v, lane), subgroup_broadcast_first(v) | v of that lane, or of the first active lane (_f too) |
They are a compute stage’s. Metal has them from Metal 3, Apple7 and Mac2
GPUs on (an older Intel Mac has subgroup_size, subgroup_lane and
subgroup_id only); on OpenGL they
need the GL_KHR_shader_subgroup extension (most current drivers):
dev.info().subgroups and subgroup_size say whether the device has
them, and a pipeline using one where it doesn’t is
GpuError.Unsupported, naming the operations. Never assume a size:
read gpu.subgroup_size() in the stage: on some GPUs each stage has its
own, whatever dev.info().subgroup_size says.
#shader
import gpu from "gpu";
// compaction: where each kept element goes, from a subgroup's prefix sum
// and the totals of the subgroups before it, in workgroup memory
compute(256) fn place(keep: []const u32, at: []u32) {
shared totals: [64]u32;
let i = gpu.global_id().x;
let before = gpu.subgroup_exclusive_add(keep[i]);
totals[gpu.subgroup_id()] = gpu.subgroup_add(keep[i]);
gpu.barrier();
var base: u32 = 0;
for (s in 0..gpu.subgroup_id()) { base = base + totals[s]; }
at[i] = base + before;
}Mesh and task stages
A mesh pipeline makes its triangles in workgroups instead of reading vertex buffers: a mesh stage writes a small mesh (a meshlet) per workgroup, and an optional task stage before it decides how many mesh workgroups to launch, and passes them a payload. Culling meshlets on the GPU, terrain and generated geometry are what it is for.
#shader
import gpu from "gpu";
pub struct Tiles { base: u32; count: u32; }
pub struct MV { position: gpu.Vec4; colour: gpu.Vec4; }
// each task workgroup launches two mesh workgroups, and says which tiles
task(2) fn tiles_ts(t: payload *Tiles) -> gpu.UVec3 {
if (gpu.local_id().x == 0) {
t.base = gpu.group_id().x * 2;
t.count = 2;
}
gpu.barrier();
return gpu.uvec3(t.count, 1, 1);
}
// each mesh workgroup writes one quad: four vertices, two triangles
mesh(4) fn tiles_ms(cols: []const gpu.Vec4, t: payload *const Tiles,
verts: vertices *[4]MV, tris: primitives *[2]gpu.UVec3) {
let q = t.base + gpu.group_id().x;
gpu.set_mesh_counts(4, 2);
let i = gpu.local_id().x;
let x = (q % 2) as f32 - 1.0 + (i % 2) as f32;
let y = (q / 2) as f32 - 1.0 + (i / 2) as f32;
verts[i] = MV { position: gpu.vec4(x, y, 0.0, 1.0); colour: cols[q]; };
if (i == 0) { tris[0] = gpu.uvec3(0, 1, 2); }
if (i == 1) { tris[1] = gpu.uvec3(2, 1, 3); }
}
pixel fn tile_ps(v: MV) -> gpu.Vec4 { return v.colour; }- A task stage returns the mesh workgroups to launch, the same
gpu.UVec3from every invocation. It writes its payload, a struct, through itspayload *Tparameter; the mesh stage reads the same struct throughpayload *const T. - A mesh stage has one
vertices *[N]Vand oneprimitives *[M]gpu.UVec3parameter: N and M are the most it writes (constants).Vis a vertex output struct, withposition: gpu.Vec4, and is what the pixel stage takes. It callsgpu.set_mesh_counts(vertices, triangles)before writing, and writes whole vertices and triangles (verts[i] = MV { ... },tris[i] = gpu.uvec3(a, b, c)); it doesn’t read them back. Triangles only. - The program makes the pipeline with
dev.mesh_pipeline(&tiles_ts, &tiles_ms, &tile_ps, opts)(ornullfor no task stage) and draws it withpass.draw_mesh_tasks(x, y, z)ordraw_mesh_tasks_indirect(gpu). - Mesh shaders are Vulkan’s (
VK_EXT_mesh_shader) and Metal’s (Metal 3 GPUs); OpenGL 4.3 has none.dev.info().mesh_shaderssays whether the device has them, andmax_mesh_vertices,max_mesh_primitivesandmax_task_payloadhow much room a workgroup has. A mesh pipeline where they are missing, or a stage asking more, isGpuError.Unsupported, naming what and the backend.
Indirect arguments
A compute stage can write the arguments of the draws and dispatches that
follow it (gpu’s indirect work): gpu.DrawArgs,
gpu.DrawIndexedArgs and gpu.DispatchArgs are plain structs a stage
writes as storage.
#shader
import gpu from "gpu";
pub struct Counter { n: u32; }
compute(64) fn keep_visible(radius: []const f32, draws: []gpu.DrawArgs, count: *Counter) {
let i = gpu.global_id().x;
if (radius[i] <= 0.0) { return; }
let at = gpu.atomic_add(&count.n, 1);
draws[at] = gpu.DrawArgs { vertices: 36; instances: 1; first_vertex: 0; first_instance: i; };
}Storage images
A storage image’s type names its format, and its reads and writes are its methods:
| Call | Gives |
|---|---|
img.load(at: IVec2) -> Vec4 | the texel (UVec4 for ImageR32u, ImageRg32u) |
img.store(at: IVec2, v: Vec4) | writes it (UVec4 for the integer ones) |
img.size() -> IVec2 | the bound level’s width and height |
img.atomic_add(at, v: u32) -> u32, atomic_min, atomic_max, atomic_exchange | on ImageR32u only: the old value |
img.atomic_compare_exchange(at, expected: u32, value: u32) -> u32 | on ImageR32u, as gpu.atomic_compare_exchange |
the same on gpu.Image3dR32f, gpu.ImageArrayR32u, … | at an IVec3: z the slice or the layer; size() an IVec3 |
img.atomic_min_u64(at, v: UVec2), atomic_max_u64 | on ImageRg32u only: the texel as a u64 (below) |
#shader
import gpu from "gpu";
compute(8, 8) fn splat(heat: gpu.ImageR32u, colour: gpu.ImageRgba8) {
let g = gpu.global_id();
let at = gpu.ivec2(g.x as i32, g.y as i32);
let n = heat.atomic_add(gpu.ivec2(at.x / 4, at.y / 4), 1);
colour.store(at, gpu.vec4(n as f32 / 16.0, 0.0, 0.0, 1.0));
}An invocation sees its own stores; the next pass sees every one.
64-bit atomics
A depth and an id packed into one 64-bit value, kept per pixel by an
atomic max or min, is a visibility buffer. A shader has no u64: the
value is a gpu.UVec2, x its low 32 bits and y its high (the bytes of
a little-endian u64), in a []gpu.UVec2 storage buffer or an
ImageRg32u:
#shader
import gpu from "gpu";
compute(64) fn nearest(depths: []const u32, ids: []const u32, best: []gpu.UVec2) {
let i = gpu.global_id().x;
// the smallest depth wins: depth in the high half, the id in the low
gpu.atomic_min_u64(&best[i % 16], gpu.uvec2(ids[i], depths[i]));
}| Call | Does |
|---|---|
gpu.atomic_min_u64(&buf[i], v: UVec2), atomic_max_u64 | on a []gpu.UVec2 storage buffer’s element, compared as u64s; no old value |
img.atomic_min_u64(at: IVec2, v: UVec2), atomic_max_u64 | on an ImageRg32u’s texel |
They are Vulkan’s (shaderBufferInt64Atomics; for images
VK_EXT_shader_image_atomic_int64) and Metal’s on Apple9 GPUs (M3 and
later); OpenGL 4.3 has none. dev.info().atomics_u64 and
image_atomics_u64 say whether the device has them, and a pipeline
using them where it doesn’t is GpuError.Unsupported, naming them and
the backend. In a stage that uses an image’s 64-bit atomics, every
ImageRg32u is a 64-bit image: its load and store still give and take
the halves as x and y.
Ray queries
A stage can trace a ray through a scene of triangles the program built
(gpu: Blas, Tlas): a parameter of
type gpu.Tlas is the scene.
#shader
import gpu from "gpu";
pixel fn shade(v: Out, scene: gpu.Tlas, u: uniform Light) -> gpu.Vec4 {
let p = gpu.vec3(v.world.x, v.world.y, v.world.z);
let lit = !gpu.ray_any(scene, p, gpu.vec3(u.dir.x, u.dir.y, u.dir.z), 0.001, 1000.0);
if (lit) { return v.colour; }
return v.colour * 0.3;
}| Call | Gives |
|---|---|
gpu.ray_query(scene, origin: Vec3, dir: Vec3, tmin: f32, tmax: f32) -> gpu.Hit | the closest triangle hit between tmin and tmax along dir |
gpu.ray_any(scene, origin, dir, tmin, tmax) -> bool | whether anything is hit there, stopping at the first (shadows) |
gpu.ray_query_mask(scene, origin, dir, tmin, tmax, mask: u32), gpu.ray_any_mask(...) | the same, testing only instances with a bit of mask in Instance.mask |
gpu.ray_begin(scene, origin, dir, tmin, tmax, mask: u32) -> gpu.RayQuery | a ray whose shader decides each non-opaque triangle (below) |
pub struct Hit {
hit: bool; // false: nothing between tmin and tmax (the rest is 0)
t: f32; // the hit's distance along dir, in dir's lengths
instance: u32; // its instance's id (gpu.Instance.id)
primitive: u32; // the triangle's index in its Blas
bary: Vec2; // its barycentrics: the weights of the triangle's second and third vertices
}Both faces are hit. ray_query and ray_any treat every triangle as opaque. A Blas
made opaque: false holds triangles the shader decides, for foliage and the like,
through a loop: tape’s shaders have no callbacks.
let q = gpu.ray_begin(scene, origin, dir, 0.001, 1000.0, 255);
while (q.proceed()) { // true: a non-opaque triangle in the ray's way
let c = q.candidate(); // a gpu.Hit
if (gpu.sample_table_level(leaves, c.instance, uv_at(c), 0.0).w > 0.5) { q.commit(); }
}
let h = q.committed(); // the closest opaque or committed; h.hit false if noneA gpu.RayQuery is a local of the function that began it: let q = gpu.ray_begin(...),
never passed to a helper. Opaque triangles commit themselves and never reach the loop.
Ray queries are in
every stage on Vulkan (VK_KHR_ray_query); on Metal in compute, vertex
and pixel stages (supportsRaytracing, supportsRaytracingFromRender);
OpenGL 4.3 has none. dev.info().ray_queries (and ray_queries_render
for the stages that draw) say so beforehand, and a pipeline using them
where the device can’t is GpuError.Unsupported.
Errors
Every error is at a line of the shader and stops the compile:
| Written | Error |
|---|---|
var g: u32 = 0; at the top of the region | a #shader region has no variables: a shader reads its parameters, consts and literals |
fn Particle.speed(self) -> f32 | a #shader region's functions are shaders and their helpers: no extern fn, @tape fn or method here |
tagged Shape { ... } | a #shader region holds structs, enums, consts and functions: a GPU has no unions or tagged unions |
compute fn f(...) | compute needs its workgroup size: compute(256) fn, compute(16, 16) fn |
let x: f64 = 1.0; | a f64 is not on GPUs |
let s = "hi"; | a string is not on GPUs |
a vertex result with no position | Out: a vertex shader's result has a field position: gpu.Vec4 |
@centroid k: u32; in the vertex output | Out.k: @centroid on a u32: an integer varying is flat, never interpolated |
@centroid position: gpu.Vec4; | Out.position: @centroid is for what the pixel stage reads; position says where the vertex is, and is not interpolated |
@centroid on a vertex input’s field | In.at: @centroid marks a field of the stage's vertex output, and here that is Out |
vertex struct Q { ... } | a stage word goes before a fn: vertex fn, pixel fn, compute(x) fn“ |
a pixel stage returning an f32 | pixel fn ps: a pixel stage returns its colour, a gpu.Vec4 (not f32; a gpu.UVec4 for an integer target, a struct of them for several targets, nothing for a depth-only pass) |
| a pixel stage without the vertex output first | pixel fn ps: a pixel fn's first parameter is the vertex shader's output struct, interpolated: pixel fn ps(v: Out, …)“ |
| a compute stage with a result | compute fn k: a compute stage returns nothing: it writes its results to storage buffers |
two uniform parameters | 'b': a stage has one uniform struct; put its values in the first one's fields |
u: uniform u32 | 'u': a uniform is a struct (u: uniform Params): a u32 is one of its fields |
instance on a pixel or compute parameter | 'z': instance is a vertex stage's: a stream advancing once per instance |
uniform or instance on a helper’s parameter | 'u': uniform is a stage's parameter (a helper takes values) |
one: *u32 | 'one': a pointer parameter is one struct in a storage buffer; a *u32 has no binding of its own |
let f = helper; | a shader has no function values: call the function |
| helpers calling each other in a circle | fn a calls itself (through the functions it calls): a GPU has no call stack, so a shader can't recurse; use a loop |
pos: gpu.Vec3 in a storage struct | gpu.Vec3 does not cross to the GPU: std430 gives it 12 bytes, MSL 16; use the 4-lane vector |
a call to a #code function | host is not a shader function: a shader calls gpu's intrinsics and the helpers of its region |
match | a shader can't use match: if/else is what the GPU runs |
for (x in buffer) | a shader's foris over a range:for (i in 0..n), then index the buffer |
defer | a GPU has no unwinding; write the work where it belongs |
shared t: [4]u32; in a helper or another stage | 't': shared memory is a compute stage's, declared in the stage function (a helper takes values) |
shared t: u32; | 't': shared memory is a fixed-size array (shared t: [256]u32;) |
gpu.barrier() outside a compute, task or mesh stage | gpu.barrier is a compute, task or mesh stage's |
| a task stage returning nothing | task fn t: a task stage returns the mesh workgroups it launches, a gpu.UVec3 (the same in every invocation), not void |
| a mesh stage without its outputs | mesh fn m: a mesh stage has one verticesand oneprimitives parameter (v: vertices *[64]MeshV, t: primitives *[126]gpu.UVec3) |
payload on a compute or vertex parameter | 'p': payload is a task stage's (written) or a mesh stage's (read) |
verts[i].colour = c;, or reading verts[i], in a mesh stage | a mesh stage writes its vertices and triangles whole (verts[i] = …), and never reads them |
When a pipeline is made, a resource two stages share by name must be the
same kind and type in both ("data" is a f32 in one stage and a u32 in the other: one resource, one type), and so must the uniform struct: the
program stops there, naming it.
What a stage compiles to
The gpu.Shader a stage’s name stands for is a struct of four strings:
glsl (GLSL 4.30), msl (Metal Shading Language), layout, a JSON
description of its bindings, vertex streams and uniforms that gpu
reads when it makes a pipeline, and spirv, the SPIR-V 1.5 module as
base64 text. All of them are made on every platform, and the backend
takes its own. Print one to see what a shader became:
#code
import gpu from "gpu";
import io from "io";
pub struct Params { add: u32; count: u32; }
fn main() -> i32 {
io.println(add_one.glsl);
return 0;
}
#shader
import gpu from "gpu";
compute(64) fn add_one(vals: []u32, u: uniform Params) {
let i = gpu.global_id().x;
if (i >= u.count) { return; }
vals[i] = vals[i] + u.add;
}The texts carry #line directives with the shader’s tape lines, so a
driver’s message points at your source.
Last modified: