# Shaders


Some pictures are not made of shapes: a field of drifting smoke, a glowing body, a tunnel. For those you write a shader, a small program in SkSL (Skia's shading language, close to GLSL) that is run once for every pixel and returns that pixel's color. `fx` draws a shader into a rect like any other shape, and ships three finished ones.

> **Note:** On this page the shaders run on your GPU and cost next to nothing. A render draws them on the CPU, where they are the most expensive thing in the library. Read [drawing small](#drawing-small) before you fill a film with them.

## Your own shader

```odin
shader :: proc(sksl: cstring, r: Rect, uniforms: ..f32)
```

`shader` fills `r` with what the SkSL program returns. The numbers after the rect fill the program's uniforms in the order they are declared: a `float` takes one, a `float2` two, a `float3` three, a `float4` four. Uniforms you do not fill are 0. Declare float types only.

```glsl
uniform float t;       // seconds
uniform float4 rect;   // x, y, w, h of the rect being filled
uniform float3 color;  // r, g, b in 0..1

half4 main(float2 p) { // p: this pixel
	float2 u = (p - rect.xy - 0.5 * rect.zw) / rect.w; // centered; 1 = the rect's height
	float a = smoothstep(0.5, 0.2, length(u));
	return half4(half3(color) * a, a); // premultiplied
}
```

Three things to know:

- **Coordinates.** `p` is in the coordinates you are drawing in (stage px, unless a group has moved you), not relative to the rect. Nothing is passed for you, so the shaders in `fx` all take the rect as a `float4` and start by turning `p` into a centered position measured in rect heights, as above. Do the same and the picture keeps its proportions in any rect.
- **Time.** There is no clock in a shader. Pass `s.t` (or `s.lt`) as a uniform and compute everything from it, like the rest of a scene.
- **Color.** `main` returns premultiplied color: multiply the color by its alpha. Return alpha 1 for an opaque picture, less and whatever is below shows through. `unpack(color)` gives you a `Color` as four floats in 0..1 for the uniforms.

If the program does not compile, Skia's error is printed and nothing is drawn. SkSL is stricter than desktop GLSL in a few places: loops need a fixed count, and the types are spelled `float2`, `float3`, `half4`.

```odin
shade_custom :: proc(s: fx.Shot) {
	RINGS :: `
	uniform float t;
	uniform float4 rect;  // x, y, w, h of the rect being filled
	uniform float3 color;
	uniform float count;
	half4 main(float2 p) {
		// p is in stage px; u is centered on the rect, one unit = its height
		float2 u = (p - rect.xy - 0.5 * rect.zw) / rect.w;
		float d = length(u);
		float wave = 0.5 + 0.5 * sin(6.2831853 * (d * count - t));
		float a = wave * smoothstep(0.75, 0.1, d);
		return half4(half3(color) * a, a); // premultiplied: transparent where a is 0
	}`
	fx.backdrop(.Night)
	r := fx.stage()
	c := fx.unpack(fx.theme.na)
	// the floats fill the uniforms in the order they are declared
	fx.shader(RINGS, r, s.lt, r.x, r.y, r.w, r.h, c.r, c.g, c.b, knob("count", 6, 1, 24))
	fx.caption("fx.shader", {960, 540}, 200, fx.theme.nt, {0.5, 0.5})
}
```

A shader's picture is ordinary drawing. It can sit inside a group that fades or scales it, under text, or under a [post filter](/docs/post/): the fable film folds a `nebula` through `kaleido` for its title.

## Drawing small

```odin
shader_scaled :: proc(sksl: cstring, r: Rect, res: f32, uniforms: ..f32)
```

SkSL on the CPU is slow. One thread needs about 2 s for a single 1080p frame of warped noise or a raymarched body, a thousand times what a frame of text and shapes takes. But pictures like that are smooth, and a smooth picture does not need every pixel.

`shader_scaled` is `shader` drawn into a smaller image, `res` (0.05 to 1) of the rect's size in each direction, and scaled up to fill the rect. A third of the resolution is a ninth of the pixels: at a third or half, the same pictures cost 0.1 to 0.5 s a frame. The shader notices nothing, it still sees stage coordinates.

Use it for anything soft (noise, gradients, glows), and plain `shader` for anything with hard edges or fine lines, which scaling would blur. Drag `res` down to see where this picture starts to fall apart:

```odin
shade_scaled :: proc(s: fx.Shot) {
	SMOKE :: `
	uniform float t;
	uniform float4 rect;
	uniform float3 dark;
	uniform float3 light;
	` + fx.NOISE_SKSL + `
	half4 main(float2 p) {
		float2 u = (p - rect.xy) / rect.w * 3;
		float f = fbm(u + 2 * fbm(u * 0.8 + t * 0.12));
		return half4(half3(mix(dark, light, smoothstep(0.4, 0.9, f))), 1);
	}`
	res := knob("res", 0.25, 0.05, 1)
	r := fx.stage()
	a, b := fx.unpack(fx.theme.night), fx.unpack(fx.theme.na)
	if fx.group({o = fx.fade(s)}) {
		fx.shader_scaled(SMOKE, r, res, s.lt, r.x, r.y, r.w, r.h, a.r, a.g, a.b, b.r, b.g, b.b)
		fx.label(fmt.tprintf("drawn at %.0f × %.0f", 1920 * res, 1080 * res), {960, 540}, fx.mono(72, 500), fx.theme.nt, {0.5, 0.5})
	}
}
```

## Noise for your shaders

```odin
NOISE_SKSL :: `…` // float h12(float2 p); float vn(float2 p); float fbm(float2 p);
```

`NOISE_SKSL` is a piece of SkSL to put in front of your own `main` (constant strings join with `+`, as in the demo above). It defines three functions, all returning 0..1:

| Function | Returns |
| --- | --- |
| `h12(p)` | A hash: an unrelated value for every `p`. |
| `vn(p)` | Value noise: smooth, one bump per unit. |
| `fbm(p)` | Four layers of `vn` at rising frequency: clouds. |

Feeding `fbm` into its own input (`fbm(u + fbm(u))`) is what makes smoke out of clouds.

## Nebula

```odin
Nebula :: struct {
	deep, mid, hot: Color, // background, the filaments, their brightest cores
	scale:          f32, // size of the structures, 0 = 1 (bigger = larger clouds)
	detail:         f32, // 0..1 how wispy, 0 = 0.5
	level:          f32, // overall brightness, 0 = 1
	flow:           Vec2, // drift of the whole field, stage heights per second
	seed:           f32,
	res:            f32, // render resolution, 0 = 1/3
}

nebula :: proc(r: Rect, t: f32, n: Nebula)
```

Slow filaments of warped noise: a sky, a mind, a field to put things in. `deep` is the background and the picture is opaque. `mid` and `hot` are light added on top of it, so dim them (mix them toward black) for a background that stays behind its text. The field evolves slowly with `t` on its own; `flow` adds a drift of the whole thing, and `seed` gives you a different sky.

It is drawn through `shader_scaled` at a third of the resolution unless `res` says otherwise.

```odin
shade_nebula :: proc(s: fx.Shot) {
	if fx.group({o = fx.fade(s, 0.8, 0.8)}) {
		fx.nebula(fx.stage(), s.lt, {
			deep   = fx.theme.night,
			mid	= fx.theme.na,
			hot	= fx.theme.nt,
			scale  = knob("scale", 1, 0.3, 3),
			detail = knob("detail", 0.5, 0.05, 1),
			level  = knob("level", 1, 0.2, 2.5),
			flow   = {0.03, -0.01},
		})
		fx.caption("A field to put things in", {960, 540}, 120, fx.theme.nt, {0.5, 0.5})
	}
}
```

## Orb

```odin
Orb :: struct {
	radius:  f32, // of the body, in px
	morph:   f32, // 0 = a sphere … 1 = restless
	spin:    f32, // turns of its surface pattern, in radians
	a, b, c: Color, // the film's colors across the fresnel
	glow:    f32, // halo strength, 0 = 0.6
	res:     f32, // render resolution, 0 = 0.5
}

orb :: proc(r: Rect, t: f32, o: Orb)
```

A raymarched body with an iridescent skin and a halo, centered in `r`. Make `r` a square about three times the radius wide (more if the halo should reach further); around the body the picture is transparent, and the halo fades out before the rect's edge. `a` is the color you see where the surface faces you, `b` and `c` take over toward the rim. `morph` above 1 is allowed and wilder.

It is the costliest picture here, a full raymarch per pixel, and is drawn at half resolution by default. Keep its rect no bigger than it needs to be.

```odin
shade_orb :: proc(s: fx.Shot) {
	fx.backdrop(.Night)
	if fx.group({o = fx.fade(s)}) {
		// a square about three radii wide, the body in its middle
		fx.orb({420, 0, 1080, 1080}, s.lt, {
			radius = 330,
			morph  = knob("morph", 0.7, 0, 1.5),
			spin   = s.lt * 0.7,
			a	  = fx.theme.na,
			b	  = 0xff9a86ff,
			c	  = 0xff62e6d2,
			glow   = knob("glow", 0.6, 0.05, 2),
		})
	}
}
```

## Tunnel

```odin
tunnel :: proc(r: Rect, t: f32, color, accent: Color, speed: f32 = 1, twist: f32 = 0.15, ribs: f32 = 12, res: f32 = 0.5)
```

An endless tunnel of rings and ribs flying toward the viewer, opaque, on black. The lines are in `color`; `accent` lights up a flickering panel here and there and the glow at the far end. `speed` is in rings per second, `twist` in turns along the tunnel's length (0 is straight), `ribs` is how many lines run along it.

```odin
shade_tunnel :: proc(s: fx.Shot) {
	speed := knob("speed", 1, 0, 4)
	twist := knob("twist", 0.15, -1, 1)
	ribs := knob("ribs", 12, 3, 32)
	if fx.group({o = fx.fade(s)}) {
		fx.tunnel(fx.stage(), s.lt, fx.theme.na, fx.theme.nt, speed, twist, ribs)
	}
}
```

## Reference

| Procedure | Draws |
| --- | --- |
| `shader(sksl, r, uniforms…)` | An SkSL program into `r`, at full resolution. |
| `shader_scaled(sksl, r, res, uniforms…)` | The same at `res` of the resolution, scaled up. |
| `nebula(r, t, n)` | Filaments of warped noise, opaque. `n` is a `Nebula`. |
| `orb(r, t, o)` | A raymarched iridescent body with a halo, transparent around it. `o` is an `Orb`. |
| `tunnel(r, t, color, accent, speed, twist, ribs, res)` | A tunnel flying toward the viewer, on black. |
| `NOISE_SKSL` | SkSL source of `h12`, `vn` and `fbm`, to prepend to your own. |
| `NEBULA`, `ORB`, `TUNNEL` | The SkSL sources of the three pictures, to read or to start from. |
