Shaders
Status (2026-11-23): @vertex and @fragment shaders, closures written as shaders, and
compute kernels compile to WGSL and run through WebGPU, with the wgpu library (wgpu-native
and SDL3): example/wgpu, example/life, example/shooter, example/spheres. WGSL is the
only shader language.
A shader is ordinary som code that runs on the GPU: for each corner of a mesh (a vertex
shader), each pixel (a fragment shader) or each item of a buffer (a compute kernel). It's a
closure written where it's used, or a function marked @vertex, @fragment or
@compute. It's compiled for the GPU while compiling,
everything it calls with it, and it still runs (and can be tested) on the CPU.
What's where
- The language (
crates/compiler/shader, lowering, the compile-time pass):@fragment,@computeand@if GPU; compiling a function and what it calls to WGSL;each_uniform's body for each struct or closure;mem::size_of<T>(). It knows nothing of a window or a GPU API: what it makes is WGSL text and a way to walk the uniforms. som::gpu(std/gpu): what shaders are written with and what a host needs, on both sides.Fragment,Texture,Buffer<T>,Grid,Cells;gpu::shader(f)andgpu::kernel(f), a shader's WGSL (worked out while compiling);gpu::Shader<U>, the WGSL and aU's uniforms, given to a host asgpu::Uniforms.som::wgsl(std/wgsl): WGSL's built-in functions,extern "wgsl", only on the GPU. Std's math and vectors are@if GPUon them.wgpu(libs/wgpu, not std): a host. A window and its input (SDL3) and the GPU (wgpu-native), both imported from their headers;ShaderandKernelload the WGSL and pack the uniforms;Painterdraws flat shapes and text. It's a library that comes with som, found byuse wgpu;(see below), and opinionated: std has no native libraries to need. Any other host could be written againstsom::gputhe same way.
A closure: what it captures are its uniforms
use wgpu;
let mut gpu = wgpu::Gpu::open("demo", 800, 450);
let mut background = wgpu::Shader::empty();
while gpu.frame() {
let time = gpu.time();
background.fullscreen(&mut gpu, (frag) => vec4(frag.uv.x, 0.5 + 0.5 * time.sin(), 0.0, 1.0));
gpu.present();
}The closure is the shader; time, which it captures, is a uniform, set from each frame's
closure. There's no struct of uniforms to write and nothing to set by hand. One that's a
struct of the program's own is set field by field (camera.pos). Captures have to copy,
since each is a value for the GPU. A closure captures the parts of a variable it reads when
the variable itself doesn't copy, so g.camera and g.level.texture inside it capture
those two, not all of g. A part that doesn't copy is still lent, and an error says what to
capture instead, except a Buffer or Texture, which is bound the same either way.
Each closure written out is its own shader (its own type), compiled once. wgpu::Shader
loads it the first time it's drawn, which is why Shader::empty() is written before the loop
and the closure inside it. (frag) => needs no type: empty() is in an impl bounded by
U: fn(Fragment) -> Vec4. shader.draw(&mut gpu, x, y, width, height, closure) draws it over
part of the window instead (in pixels; gpu.scale is pixels to a point).
A @fragment function and a struct of uniforms
struct Stripes { pub time: f32, pub tint: Vec4, pub image: gpu::Texture }
@fragment
fn stripes(frag: Fragment, u: &Stripes) -> Vec4 {
let k = 0.6 + 0.4 * ((frag.uv.x + frag.uv.y) * 10.0 + u.time).sin();
vec4(u.image.sample(frag.uv).rgb * u.tint.rgb * k, 1.0)
}
let mut striped: wgpu::Shader<Stripes> = wgpu::Shader::fragment(stripes);
striped.fullscreen(&mut gpu, Stripes { time, tint, image });Every @fragment function is compiled for the GPU, used or not, so som check reports a
broken one. A fragment shader takes a Fragment (uv, from (0, 0) at the top left to (1, 1)
at the bottom right of what's drawn; color; position, in pixels), a & to a struct of
uniforms, or both, and gives the pixel's colour, which is blended over what's there by its
alpha.
gpu::Shader<U> and the uniforms
A gpu::Shader<U> is a shader's WGSL (wgsl, made while compiling: gpu::shader(f) costs
nothing when it runs) and the type of its uniforms, U: a struct, or the closure.
shader.each(&u, (i, name, value) => …) calls back with each uniform's index, its name and
its value as a gpu::Uniform (Float, Int, Uint, Bool, Vec2–Vec4, Texture,
Buffer, or Numbers for an array or an integer vector). It's gpu::each_uniform, whose
body the compiler writes for each U (crates/compiler/6-lower/src/uniforms.rs): a
struct's fields, going into the program's own structs among them, or a closure's captures;
each value made with Uniform::from(&field). No list, no loop.
A uniform is an f32, i32, u32, bool, a vector of 2 to 4 numbers, an array of numbers
or f32 vectors, an array of structs, a Texture, a Buffer, or a struct of the program's own
holding those. The fields have to be pub for now: each reads them from the standard
library.
An array of structs, spheres: [Sphere; 4], is WGSL's own array<Sphere, 4>: its items'
fields are numbers, vectors and matrices of them, or such structs (no bool, which a uniform
buffer can't hold). Each struct is declared aligned to 16 bytes, with an @size on its last
member making it a multiple of 16 long, as a uniform buffer needs; the host gives each item's
fields in order, Uniform::Pad before each item and after the last aligning it to 16. So
for sphere in s.spheres { … sphere.radius … } reads it as it's written, no packing into
Vec4s.
In WGSL every uniform but a texture or buffer is a member of one struct, SomUniforms (group
0, binding 0), in the order each gives them. The host packs them by WGSL's rules: each at
the next multiple of its alignment (4 for a number, 8 for a vec2, 16 for a vec3/vec4).
An array's items are 16 bytes apart, so [f32; N] and [Vec2; N] are declared as arrays of
vec4s, and the shader copies out the first of each. A bool is a u32. The sampler is
binding 1, and each texture and buffer the next, in order. The module has its own vertex
shader, vs_main, one triangle over the viewport, and fs_main, which calls the shader;
the host sets the viewport to where it's drawn.
The shader reads its uniforms where they are: its &U isn't passed, and u.lights[i] is
som_u.lights[i].xyz. A function given a & into the uniforms (halls(frag, &s),
ripple(&u.image, …)) gets a copy of its own reading them in place too, f_halls_u: WGSL
can't pass a pointer to the uniform buffer, and copying it into each call would put every
array among them in the function's own memory for each pixel.
Meshes: a @vertex shader and what it passes on
A vertex shader runs for each corner of a mesh. It takes a struct of the corner's numbers
and may take a & to a struct of uniforms; it gives a gpu::Vertex<S>: where the corner
lands, in clip space, and passed, an S of the program's own. The fragment shader drawn
with it takes that S, each field blended between the triangle's corners for the pixel:
struct Corner { pub pos: Vec3, pub normal: Vec3 }
struct Surface { pub world: Vec3, pub normal: Vec3 }
@vertex
fn place(c: Corner, s: &Scene) -> gpu::Vertex<Surface> {
let world = s.model * vec4(c.pos, 1.0);
gpu::Vertex { position: s.view_projection * world, passed: Surface { world: world.xyz, normal: … } }
}
@fragment
fn shade(surface: Surface, s: &Scene) -> Vec4 { … }
let ball: wgpu::Mesh<Corner> = gpu.mesh(corners.as_slice(), indices.as_slice());
let mut material = wgpu::Material::new(place, shade);
material.draw(&mut gpu, &ball, Scene { … });Material::new is bounded so that the S the vertex shader gives is the one the fragment
shader takes: a mismatch is a type error. Both take the same uniforms.
- The corner is a struct of numbers and vectors of them (
f32,i32,u32,Vec2…Vec4): each field is a vertex attribute,@location(i)in field order, read from the mesh's buffer as the CPU lays the struct out. The host finds each field's format by going through the struct with@for f in Tand a trait,wgpu::Attribute. - What's passed on is the same: numbers and vectors. Each field is
@location(i)ofSomVaryings, declared alike in both modules, since both are made fromS. Integers are taken from the first corner (@interpolate(flat)) rather than blended. - The two modules are compiled apart,
gpu::shader(place)andgpu::shader(shade): a vertex module withvs_main, and a fragment module withfs_maintakingSomVaryings. A fragment shader taking aFragmentinstead keeps its own vertex shader, over a rectangle. - Depth:
wgpukeeps a depth buffer the size of the window, cleared by the firstMaterialdrawn each frame, so nearer pixels hide those behind.
example/spheres lights a grid of spheres by Cook-Torrance (GGX, Smith, Schlick), from
smooth to rough, metal and not, all in som.
Compute kernels
A kernel is a closure given an index, (i) => …, run on the GPU once for each item of the
buffer it fills, giving that item. What it captures are its uniforms, as a shader's are, and
a gpu::Buffer<T> among them is read with get:
let input = gpu.upload(&numbers); // a gpu::Buffer<f32>
let mut output: gpu::Buffer<f32> = gpu.buffer(1000);
let mut double = wgpu::Kernel::empty();
double.fill(&mut gpu, &mut output, (i) => input.get(i) * 2.0 + 1.0);
gpu.read(&output, &mut back);gpu.fill(&mut output, (i) => …) does the same without a Kernel to hold: the Gpu keeps
each kernel it loads, found again by its source, and so gpu.update, gpu.each and
gpu.fullscreen for a fragment shader. A Kernel of your own is for timing it (time_ms).
Two buffers a kernel goes back and forth between, reading one and filling the other, are
swapped with mem::swap(&mut now, &mut next).
gpu.read waits for the GPU to finish everything it's been given. What's read every frame
is read without waiting instead: gpu.read_later(&buffer) starts a gpu::Reading, after the
work given so far, and gpu.take(&mut reading, &mut into) copies it out once the GPU's done,
saying whether it was. What's taken is a frame or so old, and later work doesn't change it.
if gpu.take(&mut reading, &mut back) {
// `back` as the buffer was when the reading started.
reading = gpu.read_later(&particles);
}A kernel can update a buffer instead, given the item as it is too, (i, item) => …, and
changing it in place: example/pathtracer adds each frame's light to its sums this
way. Each invocation only sees its own item, so they can all run at once. One that reads
other items of the buffer, like example/life's step reading a cell's neighbours, fills
another buffer instead.
For pixels or a board's cells there's gpu::Image<T>, gpu.image(W, H): width × height
items, row after row. fill and update of an image give the kernel each item's position, a
Vec2i column and row, instead of its index ((p) => …, (p, item) => …), and an image a
kernel or shader captures is read with get(p) or get(x, y), or at a fragment's uv with
sample(frag.uv), the nearest item, as a Texture is sampled. image.pixel(uv) is the pixel a
uv is in, and image.uv(p) where a pixel's middle is:
let mut now: gpu::Image<i32> = gpu.image(W, H);
step.fill(&mut gpu, &mut next, (p) => {
let left = now.get((p.x + W as i32 - 1) % W as i32, p.y);
…
});Which fill is meant is chosen by the buffer's type: a closure whose parameters aren't
written is checked once one is chosen, as that one wants. In WGSL the position is
vec2<i32>(i32(i % som_u.som_width), i32(i / som_u.som_width)), the width the host gives
after the uniforms; a captured image is a storage buffer and its own …_width uniform, and
get(x, y) reads item y * width + x. sample(uv) works out the image's height from its
buffer's length, arrayLength, and clamps to the edges.
Atomics: many runs changing the same place
A gpu::Atomic<T>, gpu.atomics(len), is len u32s, i32s or f32s that many runs of a kernel
change at once, each change whole, so none is lost to another made at the same moment, as it
would be in a Buffer: add, sub, min, max, and_bits, or_bits, xor_bits and
exchange, each giving the item as it was, and get and set. A kernel that only does this
gives nothing, and is run a number of times with each:
let counts: gpu::Atomic<u32> = gpu.atomics(256);
let mut tally = wgpu::Kernel::empty();
tally.each(&mut gpu, pixels.len, (i) => { counts.add(brightness(pixels.get(i)), 1); });
gpu.read(&counts.plain(), &mut histogram);
gpu.clear(&mut counts);gpu.clear takes a Buffer, an Atomic, or a struct of them (wgpu::Clear, by @fields),
and gpu.room(len) makes any of those, each part len long (wgpu::Room): so a struct of
named atomics is made and cleared in one go, let mut cells: Cells = gpu.room(MAX_CELLS);,
gpu.clear(&mut cells);.
In WGSL it's a var<storage, read_write> of array<atomic<T>>, and its methods WGSL's
atomicAdd(&a[i], v) and the rest. A kernel or a fragment shader can capture one; a vertex
shader can't, as WebGPU doesn't let it write. plain() is the same memory as a Buffer<T>,
for the host to read back and a shader to read as any buffer. A kernel run with each is told
how many times it runs by the last uniform, som_count, as it fills no buffer.
WGSL's atomics are whole numbers, so an Atomic<f32> holds its items' bits, atomic<u32>:
get, set and exchange are a bitcast either side, and add, sub, min and max a
loop of atomicCompareExchangeWeak in a function of their own, trying again while another
thread changed the item first. That's slower than a whole number's add where many change the
same item, about twice in example/nbody's busiest cells, but saves working in fixed point.
The _bits methods are only for whole numbers.
A struct of the program's own holding only Atomics, buffers, images and textures is lent as
they are, each field bound by itself, so related atomics can be named rather than packed into
one:
struct Cells {
pub light: gpu::Atomic<f32>,
pub shadow: gpu::Atomic<f32>,
}
fn splat(cells: &Cells, i: usize, light: f32) {
cells.light.add(i, light);
}
gpu.each(BODIES, (i) => splat(&cells, place(i), 0.5));Groups: shared memory and barriers
A kernel's threads run in groups of gpu::GROUP, 64. gpu::lane() is a thread's place in its
group and gpu::group() the group's. Memory a group shares, gpu::Shared<T, N>, is made in
the kernel with gpu::shared(), and read and set with get and set; gpu::barrier() waits
for every thread of the group to get there, and for what each set before it to be there for
all. So a group can fetch a tile of a buffer together, a thread an item, and then each read
all of it, rather than every thread reading every item from the buffer:
step.fill(&mut gpu, &mut next, (i) => {
let tile: gpu::Shared<Vec2, 64> = gpu::shared();
let mut pull = vec2(0.0, 0.0);
for t in 0..(BODIES / gpu::GROUP) {
tile.set(gpu::lane(), bodies.get(t * gpu::GROUP + gpu::lane()).pos);
gpu::barrier();
for j in 0..gpu::GROUP { pull = pull + pulled_by(me, tile.get(j)); }
gpu::barrier();
}
…
});Each gpu::shared() is a var<workgroup> array of its own; a function given a & to one is
bound to it, as to a captured buffer. A kernel that waits at a barrier runs for every thread
of each group, the last group's past the end too, so all reach it; only the items there are
are stored. (One run with each gets indexes up to the group's end: check them.)
WGSL needs every thread of a group to reach a barrier, the same number of times, and naga
doesn't check it. som does, while compiling (crates/compiler/shader/src/uniformity.rs): what
can differ between a group's threads varies (the item's index, lane(), what an Atomic or
Shared memory gives, a buffer's item at an index that varies, and what's worked out from
those or set where only some threads go), and a barrier, or a call to a function that waits at
one, where a branch whose condition varies decides whether it runs (before the paths join;
an early return too) is an error, at the barrier.
gpu::tiled(&items, start, (acc, j, item) => …) does that dance for any buffer: it goes
through every item in order, each tile fetched by the group together, folding what step
works out from start, and it handles a last tile that isn't full. Given a pick too,
gpu::tiled(&items, pick, start, step), the tile holds only what pick makes of each item, so
less is fetched and kept; example/nbody shares only each body's position and mass this way,
and it's faster than its hand-written tiles were (2.6 ms against 2.9 for 8192 bodies). Every
thread of the group has to call it, as it waits at barriers.
let mass = (b: Body) => Mass { at: b.pos, mass: b.mass };
let pull = gpu::tiled(&bodies, mass, vec2(0.0), (pull: Vec2, j: usize, other: Mass) => pull + pulled_by(me, other));kernel.time_ms(&mut gpu) is how long a recent run took on the GPU, in milliseconds, from
the GPU's own timestamps: the latest it's said, without waiting for it, so a frame or so
behind and cheap to show every frame. 0 where the GPU can't time its work, or before it's
said for any run. Only a Kernel of your own is timed, each run in a pass of its own.
A buffer doesn't copy, and what writes it takes it as &mut. A closure captures a buffer by
reference, so a kernel that reads the buffer it fills, which the GPU refuses (a buffer is
either read or written in one dispatch), is a borrow error:
k.fill(&mut gpu, &mut sums, (i) => sums.get(i) + 1.0) lends sums twice.
gpu::kernel(f) is its WGSL: cs_main, 64 threads to a group, storing what the closure gives
at i for each i below the buffer's length (or a function marked @compute, taking the
index, the item if it updates, and a & to a struct of uniforms). A shader can capture a buffer too: example/life
steps the Game of Life with kernels and draws it with a shader, all reading buffers that
never leave the GPU.
A buffer's items are laid out as the CPU has them, so the host copies an array of them in and
out as it is. In WGSL a buffer is an array<u32>, and each item is read and written word by
word by a function made for it (som_load_buf_cells, som_store_Particle), converting with
bitcast. An item is made of 4-byte numbers, f32, i32 and u32, and bools, in vectors,
arrays, structs, enums and optionals, each read from where C puts it (the compiler's one
layout, som_mir::layout, which compile-time code shares): a bool is a byte of a word,
read with extractBits and written with insertBits; an enum is its u32 tag and common
fields, then its variants' own fields sharing one place, of which a store writes only the
tag's; an optional is its bool, then its value. An item's size is a multiple of 4 bytes, so
no two share a word, which a thread writing a bool would race. (Not usize, 8 bytes on the
CPU and 4 on the GPU, nor f64.)
WGSL can't pass a pointer to a buffer to a function yet (naga doesn't take
unrestricted_pointer_parameters). A function can still take a & to a buffer, image or
Atomic the kernel or shader captures, neighbours(&cells, i): it isn't passed, but bound,
as a & into the uniforms is, and the function has a copy of its own for each that reads it
where it's declared.
mem::size_of<T>(), which the host needs to make a buffer, is the size the compile-time pass
lays T out at: as C does.
The wgpu library
use wgpu; finds it in libs/, beside the standard library: after a program's own folders,
use name; looks in each folder of $SOM_PATH (separated by :), then in libs/. A
library is a folder of .som files, as a program's own module is.
wgpu::Gpu::open(title, width, height) opens a window (brew install wgpu-native sdl3) and
the GPU. Each frame is gpu.frame() (false once it's closed, or Escape is pressed), drawing,
then gpu.present(). Also:
- Input:
gpu.pressed(wgpu::Key::R)(since the frame before),gpu.held(Key::W),gpu.mouse()(as auv),gpu.mouse_moved()(aftergpu.grab_mouse()),left_held,right_held. - Time:
gpu.time(),gpu.frame_time(),gpu.fps(). - Data:
gpu.load_texture(w, h, pixels),gpu.load_grid(&mut grid),gpu.buffer<T>(len),gpu.upload(&items),gpu.write(&buffer, &items),gpu.read(&buffer, &mut into),gpu.read_later(&buffer)andgpu.take(&mut reading, &mut into). wgpu::Painter::new(&mut gpu):rect,circle,text(a 5 by 7 font of its own, space to~) andtext_width, in points. It's a@fragmentfunction inlibs/wgpulike any other.
Seeing the WGSL
som build --emit wgsl writes every @fragment and @compute function as the GPU gets it, a
file each next to the output (main.stripes.wgsl); --emit wgsl=DIR puts them in DIR, and
--emit wgsl=- prints them. Every shader is compiled for the GPU while checking, used or not,
so som check and the editor report a broken one before anything asks for it.
Each shader's WGSL is then read and checked by naga, wgpu's own shader compiler
(crates/compiler/shader/src/validate.rs), so WGSL that wgpu would refuse when the program
runs is an error while compiling instead. That's a bug in the translator, and the error says
so, with naga's words and the line of WGSL.
tests/tests/wgsl.rs also fails a shader in tests/corpus/shaders that falls back to a jump
table. SOM_WGSL_EXTRA=$PWD/example/shooter checks one more program's (an absolute path).
Vectors
Vec2, Vec3 and Vec4 are Vector<N, f32>, made with vec2(x, y), vec3(xy, z),
vec4(rgb, a) and so on. They have + - * / (with another vector or an f32, on either side
of *), -v, .x .y .z .w and every swizzle of them, and dot, length,
normalized, mix, clamp, abs, min, max, floor, round; f32 has sin, cos,
pow, sqrt, fract, clamp, mix, smoothstep and more as methods. In a shader each is
WGSL's own; on the CPU, ordinary code.
- Swizzles: any two to four components in any order, repeated or not, are a new vector:
v.zyx,p.xxyy. They're the standard library's own props, written out once in the genericimpl<N, T> Vector<N, T>by nested@fors,@ident(p0, p1, p2)making each name and@if i0 < N && …keeping each to the vectors that have its components (std/data/vector.som), so an editor lists them; on the GPU each is WGSL's own.zyx. Reading only, for now. - Colours are
Color<N: usize = 3>, a distinct type made likeVector<N, f32>: a plainColoris red, green and blue, and aColor<4>how opaque it is too.ais only on aColor<4>, so lighting worked out in aColornever touches an alpha by mistake;c.with_alpha(0.5)gives one,c4.rgbleaves it out. Their swizzles go byrgb(anda): two letters aVec2, three aColor, four aColor<4>.rgb(…)makes aColor,rgba(…)aColor<4>. A plain vector has norgb: that's a colour's. - Tone mapping and gamma:
c.reinhard()andc.aces()ease light of any brightness into 0 to 1, andc.to_screen()gives it as the screen shows it (each channel to the power of 1 / 2.2):c.aces().to_screen().with_alpha(1.0). - Textures from data:
gpu.texture(width, height, &colours)of a slice ofColor<4>s, orgpu.texture(64, 64, (x, y) => …)giving each pixel's colour; each channel kept as a byte. - Where a pixel is:
frag.sizeis how many pixels across and down what's drawn is (worked out from howuvchanges between pixels,dpdx),frag.pixelthe pixel's place in pixels from the top left,frag.from_middlefrom the middle, andfrag.centeredfrom -1 to 1 up the height with the width kept square: a ray through it isvec3(frag.centered, -1.0), and noaspectuniform is needed. - A fragment shader gives a
Color<4>or aVec4(gpu::Pixel, which both are; on the GPU they're the samevec4<f32>), andfrag.color, the colour of what's drawn, is aColor<4>. The painter's colours (rect,text, …) areColor<4>s. - Made of parts:
vec4(rgb, 1.0),vec4(xy, zw),vec4(xy, z, w),vec4(x, yzw),vec3(x, yz),vec3(v)for three of one number. - With a number, each component:
light.min(1.0),v.max(0.0), andclampbetween two vectors as well as two numbers; on the GPU, the number spread to the vector's type. asbetween vectors:p.floor() as Vec2i,cell as Vec2.asthat isn't between numbers, pointers or C's text is the target'sFrom: the standard library's convert a vector's components as numbers convert, and any type can have its own.
Areas: a width × height of anything kept row after row
gpu::Area { width, height } is the shape of items kept row after row in something one long,
a Buffer, an Atomic, or a struct of them all read at the same index:
area.index(x, y) (or index(at: Vec2i)) is the index of a column and row, none off the
edge; area.around(p) the four items round a point, where item (x, y)'s middle is at
(x, y), each a Corner with its index (none off the edge) and its weight in blending
them. So a bilinear read is a loop:
let mut sum = vec3(0.0);
for corner in grid.area.around(at) {
let i = corner.index else continue;
sum = sum + vec3(cells.light.get(i), cells.tinted.get(i), cells.shadow.get(i)) * corner.weight;
}It's plain data, so a shader captures it as a uniform: the standard library's structs whose
fields are all pub (not the ones the language knows itself, like Texture) are gone into as
the program's own are.
Matrices
Matrix<C, R> (som::data) is C columns of R rows of f32s, as WGSL's matCxR<f32>:
Mat2, Mat3, Mat4, made with mat4(x, y, z, w) from its columns, Matrix::zero() or
Matrix::identity(). A matrix times a vector of C numbers is a vector of R; a
Matrix<K, R> times a Matrix<C, K> is a Matrix<C, R>. The sizes are in the type, so
multiplying ones that don't fit is a type error, saying what does:
error: cannot apply `*` to `Matrix<2, 4>` and `Matrix<4, 4>`
┆ `Matrix<2, 4>` has `*` with `Vector<2, f32>`, `Matrix<C, 2>` or `f32` on the rightAlso +, -, * f32, transposed (a Matrix<R, C>), at(column, row), and for Mat4
the transforms: translation, scaling, rotation_x/y/z, perspective (depth 0 to 1, as
WebGPU has it) and look_at. Points are vec4(p, 1.0) and directions vec4(d, 0.0).
As a uniform, a matrix is Uniform::Matrix: its columns, each 16 bytes after the one before
(an array<vec4<f32>, C>, each column cut to its R numbers in the shader). On the GPU its
operations are std's own code, translated like any other.
Textures
A gpu::Texture among the uniforms is a texture to sample: u.image.sample(uv) gives its
colour at uv (each from 0 to 1). It's bound on its own, used where it's named, since WGSL
can't put a texture in a struct; helpers take a &gpu::Texture. A struct of the program's own
among the uniforms can hold one, and reading it there reads the binding. A texture can't be
kept in a variable or put in another struct, and only the GPU samples one: on the CPU,
sample fails. A struct the uniforms hold twice can't have its texture read, which is said
where it's read.
Grids: the same data on both sides
gpu::Grid is a grid of numbers from 0 to 255, Grid::of(w, h, &cells), kept on the CPU and
loaded onto the GPU as grid.texture (gpu.load_grid(&mut grid), a pixel per cell, the
number its red). Both a Grid and a Texture are gpu::Cells, with cell(x, y) (0
outside), so code written for any M: gpu::Cells runs on both:
fn raycast<M: gpu::Cells>(map: &M, pos: Vec2, ray: Vec2) -> Hit { … map.cell(x, y) … }
raycast(&g.level, a, dir) // the game: line of sight, against its Grid
raycast(&u.map, u.camera.pos, ray) // the shader: the same function, on the textureOn the GPU, a texture's cell is textureLoad; on the CPU, only a Grid has cells to read.
example/shooter draws and collides with one level this way.
@if GPU: the GPU is a system
The GPU is treated like an OS in @if WINDOWS { … }. som::wgsl declares WGSL's built-in
functions (extern "wgsl" { … }), which exist only on the GPU, as som::c's exist only on
the OSes. Code picks with @if GPU:
pub fn sin(rads: f32) -> f32 {
@if GPU { return wgsl::sin(rads); } else { return c::sinf(rads); }
}What can run where is worked out over the call graph by the same check as for OSes
(driver/src/targets.rs): a @fragment function has to run on the GPU, so one that reaches
c::printf is reported with the chain, chatty → helper → println → c::printf, and calling
wgsl::floor from main is reported as not available on macos.
Unlike an OS @if, @if GPU isn't decided while loading, because a shader is compiled for
both in one build: for the GPU by gpu::shader, and for the CPU as an ordinary function.
Both branches are resolved and type-checked (Ast::gpu_ifs); lowering makes a GPU copy of
each function a shader reaches (Mir::gpu), taking the GPU's branch there and the other
branch in the CPU's copy. C codegen leaves the GPU copies out. On the GPU, an OS @if takes
the target's branch.
@if is a statement, so a function written this way returns from both branches.
What else can't be on the GPU
These are errors from the translator, reported where the shader reaches them and through which calls:
- Text, pointers, slices, raw memory (
List,string,Rc, …). - 64-bit numbers and 8/16-bit integers.
usizebecomesu32. - Failing (
@fail,assert), recursion, function values, and keeping a reference rather than passing it to a call.
How it's compiled (crates/compiler/shader)
gpu::shader and gpu::kernel are standard library functions the compile-time interpreter
recognises (Mir::wgsl): lowering records which shader each instance is for, because a
function passed by name holds no value. The driver compiles each with
som_shader::wgsl(mir, entry) and gives each instance a body returning the source.
The translation is MIR → WGSL, function by function:
| MIR | WGSL |
|---|---|
| struct / enum / optional / range | struct (an enum's tag is a u32; its members most aligned first, since its layout is the GPU's own) |
Vector<N, T>, [T; 2..4] |
WGSL's own vecN<T>; std's + - * / (of two vectors, or a vector and a number either way round), .x/.xy…, magnitude, normalized are WGSL's operators, swizzles, length and normalize; vec3(0.5) is vec3<f32>(0.5); dot, cross, mix, clamp, min, max, abs, pow, sqrt, floor, ceil, fract, exp, sin and cos are WGSL's functions, given vectors for a number where WGSL wants them |
[T; N] |
array<T, N> |
a @const |
a struct or array one: a WGSL const of the same name, declared once (const BALLS: array<Ball, 3> = …;), or a var<private> if it has padding before a packed vec3, which naga's Metal backend writes as a constant Metal refuses (validate::metal_breaks), and a variable only ever holding it read as it (BALLS[i], not a copy first); a number or vector one: its value, written where it's used. One @shader(f) needs while constants are still being worked out is worked out first |
&T param |
T (a copy: nothing changes it during the call) |
&mut T param |
ptr<function, T>, given &place and read through (*p) |
| local reference | the place it refers to, written out; indexes it reads are copied where it's made |
if, while, loop, for, match |
if/else and for (;;) with break/continue, laid out by dominators (structure.rs) |
what can't be laid out that way (a break out of two loops) |
switch on the next block, inside for (;;) |
Not yet
- A vertex shader written as a closure; a vertex shader without a fragment shader.
- Instancing, index buffers of
u16s, more than one vertex buffer, culling. - Pixel position and the facing in a fragment shader taking what's passed on.
Next
See TODO.md, "Shaders".