diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 21:28:20 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-16 21:28:20 -0300 |
| commit | 6933f99ddb2d7103515d26838496309a807bba26 (patch) | |
| tree | 991c2fe7d4a57957222876e190fa4d16a0fb889c /examples/shaders | |
| parent | 82fca5c9f29124f37f6dcd08e73e6999ce44a69d (diff) | |
| download | sketchbook-6933f99ddb2d7103515d26838496309a807bba26.tar.gz sketchbook-6933f99ddb2d7103515d26838496309a807bba26.zip | |
Move standalone sketches into sketchbook examples
Diffstat (limited to 'examples/shaders')
22 files changed, 678 insertions, 0 deletions
diff --git a/examples/shaders/README.md b/examples/shaders/README.md new file mode 100644 index 0000000..98b5bc0 --- /dev/null +++ b/examples/shaders/README.md @@ -0,0 +1,81 @@ +# shaders + +Five Book of Shaders examples, each written twice, in Zig (`shaders/zig`) +and in GLSL (`shaders/glsl`), drawn by one sketch: left/right or a click +change example, `l` the language. `zig build e2e` screenshots every pair +into `.zig-cache/e2e/`, and checks a hot reload (`test/reload.script`, +`addReloadCheck` in `build.zig`): one edit to a Zig shader, one to a GLSL +shader and one to the sketch's Zig code, State kept, each edit visible. +`zig build run` with `zig build lib --watch` beside it is the live loop. + +| example | Book of Shaders | Zig vs GLSL pixels | +| --- | --- | --- | +| expo | 05/expo.frag | equal (±1/255) | +| hsb_wheel | 06/hsb-colorwheel.frag | equal (±1/255) | +| polar | 07/polar.frag | equal (±1/255) | +| truchet | 10/2d-random-truchet.frag | identical | +| clouds | 13/clouds.frag | animated; differs only by the time between shots | + +## Zig shaders in 0.17: viable, with four sharp edges + +Zig compiles a fragment or vertex shader to Vulkan SPIR-V with its own +backend: `export fn main() callconv(.{ .spirv_fragment = .{} })`, stage I/O +and resources as `@extern` pointers in the `.input`, `.output`, `.uniform`, +`.storage_buffer` and `.push_constant` address spaces, with +`.decoration = .{ .location }` or `.{ .descriptor = .{ .set, .binding } }`, +and builtins in `std.spirv` (`frag_coord`, `vertex_index`, `position_out`, +barriers, image sampling). `@sin`, `@floor`, `@sqrt`, `@exp2`, `@mod` and the +like become GLSL.std.450 instructions. The output passes `spirv-val`, runs +on SDL_GPU, matches glslc's pixels, compiles as fast as glslc does, and, +after one fix-up, translates to WGSL through naga like the GLSL shaders. + +`sb.addZigShaders` (sketchbook's build.zig, prototyped here) returns the +same `Shaders` (SPIR-V module and WGSL twin) as `addShaders`, so a sketch +cannot tell which language a shader came from. + +The edges, and what this project does about each: + +1. **Target `spirv32-vulkan`, self-hosted backend.** `spirv64` declares + `PhysicalStorageBufferAddresses`, which naga refuses. Without + `use_llvm = false`, `-O ReleaseFast` goes through LLVM and writes an + empty file with no error. +2. **Zig puts `Aligned N` on every `OpLoad`/`OpStore`.** Vulkan accepts + it; naga's SPIR-V reader fails with "invalid operand count 6 for Load", + and `spirv-opt` keeps the operands. sketchbook's `tools/spirv_strip.zig` + (~30 lines) drops them before anything else reads the module. +3. **Not all of `std.math` is shader code.** `std.math.atan2` indexes const + tables through generic pointers, which logical addressing forbids + (compile error). `gl.zig` calls GLSL.std.450 `Atan2` through inline SPIR-V + assembly instead: four lines. Expect the same for anything table-driven. +4. **Shared uniform structs need a vec2 that changes with the target.** + Native `extern struct`s cannot hold `@Vector`s, and in a uniform block + a `[2]f32` gets array stride 4, which naga and WebGPU reject (std140 + wants 16). Native Vulkan happened to render it. `uniforms.zig` + uses `pub const vec2 = if (builtin.cpu.arch.isSpirV()) @Vector(2, f32) + else [2]f32;` so one struct serves the sketch, the Zig shaders and the + generated GLSL, and `abi.gpu.uniform` still checks std140 on the CPU + side. + +Ergonomics: Zig does not broadcast scalars (`v * 2.0` is a compile +error, `@splat` needs a result type), so GLSL's `vec3(y)` and `3.0 - 2.0 * +f` become `gl.v3(y)` and `gl.v2(3) - gl.v2(2) * f`. Swizzles become +indexing (`st[1]`, `.{ fc[0], fc[1] }`). The Zig ports are the same length +as the GLSL ones (9/13/7/17/41 lines vs 11/14/8/18/37) but noisier. In +exchange you get real functions and types, `comptime`, `for (0..5)`, +modules shared with the CPU side (the same `Uniforms`, the same noise +function could run on both), and one toolchain: no glslc, and no +`#include` or `#define` preamble. + +The SPIR-V is 2–4× larger than glslc's (names and debug strings), which +costs nothing at this scale. + +## Not verified + +- The web build: `zig build web` produces the page, and naga validates + every WGSL twin, but headless Chrome here only offers SwiftShader, which + loses its device before the first frame. Open `zig build serve` in a + real browser to check. +- Compute shaders and storage buffers in Zig (`@SpirvType(.{ .runtime_array + = T })` exists; not tried here), and textures and samplers. Reloading a + Zig shader edit is checked (`test/reload.script`, through `load`); the + file watcher path (`zig build lib --watch`) only by hand. diff --git a/examples/shaders/build.zig b/examples/shaders/build.zig new file mode 100644 index 0000000..3a20bbf --- /dev/null +++ b/examples/shaders/build.zig @@ -0,0 +1,41 @@ +const std = @import("std"); +const sketchbook = @import("sketchbook"); + +/// The Book of Shaders examples, each written twice: `shaders/zig/<name>.zig` +/// and `shaders/glsl/<name>.frag`. +const examples = [_][]const u8{ "expo", "hsb_wheel", "polar", "truchet", "clouds" }; + +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize }); + + const uniforms = b.createModule(.{ .root_source_file = b.path("src/uniforms.zig") }); + var glsl_sources: std.ArrayList(std.Build.LazyPath) = .empty; + var zig_sources: std.ArrayList(std.Build.LazyPath) = .empty; + glsl_sources.append(b.graph.arena, b.path("shaders/glsl/fullscreen.vert")) catch @panic("OOM"); + zig_sources.append(b.graph.arena, b.path("shaders/zig/fullscreen.zig")) catch @panic("OOM"); + for (examples) |name| { + glsl_sources.append(b.graph.arena, b.path(b.fmt("shaders/glsl/{s}.frag", .{name}))) catch @panic("OOM"); + zig_sources.append(b.graph.arena, b.path(b.fmt("shaders/zig/{s}.zig", .{name}))) catch @panic("OOM"); + } + const glsl = sb.addShaders(.{ .layouts = .{ .module = uniforms, .types = &.{"Uniforms"} }, .sources = glsl_sources.items }); + const gl = b.createModule(.{ .root_source_file = b.path("shaders/zig/gl.zig"), .imports = &.{.{ .name = "uniforms", .module = uniforms }} }); + const zig = sb.addZigShaders(.{ .sources = zig_sources.items, .imports = &.{.{ .name = "gl", .module = gl }} }); + + const app = sb.app(.{ .name = "shaders", .root_source_file = b.path("src/main.zig"), .imports = &.{ + .{ .name = "uniforms", .module = uniforms }, + .{ .name = "glsl_shaders", .module = glsl.module }, + .{ .name = "zig_shaders", .module = zig.module }, + } }); + const steps = app.addSteps(.{ .web = .{}, .scripts = &.{ b.path("test/shaders.script"), b.path("test/timeline.script") } }); + + // Hot reload keeps State through an edit of each kind: a Zig shader, a + // GLSL shader, and the sketch's own Zig code. + const reload = app.addReloadCheck(.{ .script = b.path("test/reload.script"), .edits = &.{ + .{ .file = "shaders/zig/expo.zig", .old = ".{ 0, 1, 0 }", .new = ".{ 1, 0, 0 }" }, + .{ .file = "shaders/glsl/expo.frag", .old = "vec3(0.0, 1.0, 0.0)", .new = "vec3(1.0, 0.0, 0.0)" }, + .{ .file = "src/main.zig", .old = "0xff8040", .new = "0x40c0ff" }, + } }); + steps.e2e.dependOn(&reload.run.step); +} diff --git a/examples/shaders/build.zig.zon b/examples/shaders/build.zig.zon new file mode 100644 index 0000000..783fb87 --- /dev/null +++ b/examples/shaders/build.zig.zon @@ -0,0 +1,10 @@ +.{ + .name = .shaders, + .version = "0.1.0", + .dependencies = .{ + .sketchbook = .{ .path = "../.." }, + }, + .minimum_zig_version = "0.17.0", + .paths = .{""}, + .fingerprint = 0x2e44946f333b7e9f, +} diff --git a/examples/shaders/shaders/glsl/clouds.frag b/examples/shaders/shaders/glsl/clouds.frag new file mode 100644 index 0000000..35c3c04 --- /dev/null +++ b/examples/shaders/shaders/glsl/clouds.frag @@ -0,0 +1,37 @@ +#version 450 +#include "gl.glsl" +float random(in vec2 st) { + return fract(sin(dot(st, vec2(12.9898, 78.233))) * 43758.5453123); +} +float noise(in vec2 st) { + vec2 i = floor(st); + vec2 f = fract(st); + float a = random(i); + float b = random(i + vec2(1.0, 0.0)); + float c = random(i + vec2(0.0, 1.0)); + float d = random(i + vec2(1.0, 1.0)); + vec2 u = f * f * (3.0 - 2.0 * f); + return mix(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.x * u.y; +} +float fbm(in vec2 st) { + float v = 0.0; + float a = 0.5; + mat2 rot = mat2(cos(0.5), sin(0.5), -sin(0.5), cos(0.5)); + for (int i = 0; i < 5; ++i) { + v += a * noise(st); + st = rot * st * 2.0 + vec2(100.0); + a *= 0.5; + } + return v; +} +void main() { + vec2 st = FRAG_COORD / u_resolution * 3.0; + vec2 q = vec2(fbm(st), fbm(st + vec2(1.0))); + vec2 r = vec2(fbm(st + q + vec2(1.7, 9.2) + 0.15 * u_time), + fbm(st + q + vec2(8.3, 2.8) + 0.126 * u_time)); + float f = fbm(st + r); + vec3 color = mix(vec3(0.101961, 0.619608, 0.666667), vec3(0.666667, 0.666667, 0.498039), clamp(f * f * 4.0, 0.0, 1.0)); + color = mix(color, vec3(0, 0, 0.164706), clamp(length(q), 0.0, 1.0)); + color = mix(color, vec3(0.666667, 1, 1), clamp(length(r.x), 0.0, 1.0)); + out_color = vec4((f * f * f + 0.6 * f * f + 0.5 * f) * color, 1.0); +} diff --git a/examples/shaders/shaders/glsl/expo.frag b/examples/shaders/shaders/glsl/expo.frag new file mode 100644 index 0000000..3c216fd --- /dev/null +++ b/examples/shaders/shaders/glsl/expo.frag @@ -0,0 +1,11 @@ +#version 450 +#include "gl.glsl" +float plot(vec2 st, float pct) { + return smoothstep(pct - 0.02, pct, st.y) - smoothstep(pct, pct + 0.02, st.y); +} +void main() { + vec2 st = FRAG_COORD / u_resolution; + float y = pow(st.x, 5.0); + float pct = plot(st, y); + out_color = vec4((1.0 - pct) * vec3(y) + pct * vec3(0.0, 1.0, 0.0), 1.0); +} diff --git a/examples/shaders/shaders/glsl/fullscreen.vert b/examples/shaders/shaders/glsl/fullscreen.vert new file mode 100644 index 0000000..d6fb0f0 --- /dev/null +++ b/examples/shaders/shaders/glsl/fullscreen.vert @@ -0,0 +1,5 @@ +#version 450 +void main() { + vec2 p = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2); + gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0); +} diff --git a/examples/shaders/shaders/glsl/gl.glsl b/examples/shaders/shaders/glsl/gl.glsl new file mode 100644 index 0000000..06a45e0 --- /dev/null +++ b/examples/shaders/shaders/glsl/gl.glsl @@ -0,0 +1,8 @@ +// The Book of Shaders' preamble, for Vulkan GLSL. +#include "Uniforms.glsl" +layout(location = 0) out vec4 out_color; +#define u_resolution u.resolution +#define u_mouse u.mouse +#define u_time u.time +// GL's y-up gl_FragCoord. +#define FRAG_COORD vec2(gl_FragCoord.x, u_resolution.y - gl_FragCoord.y) diff --git a/examples/shaders/shaders/glsl/hsb_wheel.frag b/examples/shaders/shaders/glsl/hsb_wheel.frag new file mode 100644 index 0000000..b10c2de --- /dev/null +++ b/examples/shaders/shaders/glsl/hsb_wheel.frag @@ -0,0 +1,14 @@ +#version 450 +#include "gl.glsl" +#define TWO_PI 6.28318530718 +vec3 hsb2rgb(in vec3 c) { + vec3 rgb = clamp(abs(mod(c.x * 6.0 + vec3(0.0, 4.0, 2.0), 6.0) - 3.0) - 1.0, 0.0, 1.0); + rgb = rgb * rgb * (3.0 - 2.0 * rgb); + return c.z * mix(vec3(1.0), rgb, c.y); +} +void main() { + vec2 to_center = vec2(0.5) - FRAG_COORD / u_resolution; + float angle = atan(to_center.y, to_center.x); + float radius = length(to_center) * 2.0; + out_color = vec4(hsb2rgb(vec3(angle / TWO_PI + 0.5, radius, 1.0)), 1.0); +} diff --git a/examples/shaders/shaders/glsl/polar.frag b/examples/shaders/shaders/glsl/polar.frag new file mode 100644 index 0000000..af06c7a --- /dev/null +++ b/examples/shaders/shaders/glsl/polar.frag @@ -0,0 +1,8 @@ +#version 450 +#include "gl.glsl" +void main() { + vec2 pos = vec2(0.5) - FRAG_COORD / u_resolution; + float r = length(pos) * 2.0; + float f = cos(atan(pos.y, pos.x) * 3.0); + out_color = vec4(vec3(1.0 - smoothstep(f, f + 0.02, r)), 1.0); +} diff --git a/examples/shaders/shaders/glsl/truchet.frag b/examples/shaders/shaders/glsl/truchet.frag new file mode 100644 index 0000000..d5dc702 --- /dev/null +++ b/examples/shaders/shaders/glsl/truchet.frag @@ -0,0 +1,18 @@ +#version 450 +#include "gl.glsl" +float random(in vec2 st) { + return fract(sin(dot(st, vec2(12.9898, 78.233))) * 43758.5453123); +} +vec2 truchet(in vec2 st, in float index) { + index = fract((index - 0.5) * 2.0); + if (index > 0.75) st = vec2(1.0) - st; + else if (index > 0.5) st = vec2(1.0 - st.x, st.y); + else if (index > 0.25) st = 1.0 - vec2(1.0 - st.x, st.y); + return st; +} +void main() { + vec2 st = FRAG_COORD / u_resolution * 10.0; + vec2 tile = truchet(fract(st), random(floor(st))); + float c = smoothstep(tile.x - 0.3, tile.x, tile.y) - smoothstep(tile.x, tile.x + 0.3, tile.y); + out_color = vec4(vec3(c), 1.0); +} diff --git a/examples/shaders/shaders/zig/clouds.zig b/examples/shaders/shaders/zig/clouds.zig new file mode 100644 index 0000000..0924a0d --- /dev/null +++ b/examples/shaders/shaders/zig/clouds.zig @@ -0,0 +1,47 @@ +//! The Book of Shaders 13/clouds.frag: domain-warped fbm. +const gl = @import("gl"); + +fn random(st: gl.V2) f32 { + return gl.fract(@sin(gl.dot(st, .{ 12.9898, 78.233 })) * 43758.5453123); +} + +fn noise(st: gl.V2) f32 { + const i = @floor(st); + const f = gl.fract(st); + const a = random(i); + const b = random(i + gl.V2{ 1, 0 }); + const c = random(i + gl.V2{ 0, 1 }); + const d = random(i + gl.V2{ 1, 1 }); + const u = f * f * (gl.v2(3) - gl.v2(2) * f); + return gl.mix(a, b, u[0]) + (c - a) * u[1] * (1 - u[0]) + (d - b) * u[0] * u[1]; +} + +fn fbm(start: gl.V2) f32 { + const cs = @cos(@as(f32, 0.5)); + const sn = @sin(@as(f32, 0.5)); + var st = start; + var v: f32 = 0; + var a: f32 = 0.5; + for (0..5) |_| { + v += a * noise(st); + // GLSL's mat2(c, s, -s, c) * st, column-major. + st = gl.V2{ cs * st[0] - sn * st[1], sn * st[0] + cs * st[1] } * gl.v2(2) + gl.v2(100); + a *= 0.5; + } + return v; +} + +export fn main() callconv(gl.fragment) void { + const t = gl.u.time; + const st = gl.st() * gl.v2(3); + const q: gl.V2 = .{ fbm(st), fbm(st + gl.v2(1)) }; + const r: gl.V2 = .{ + fbm(st + q + gl.V2{ 1.7, 9.2 } + gl.v2(0.15 * t)), + fbm(st + q + gl.V2{ 8.3, 2.8 } + gl.v2(0.126 * t)), + }; + const f = fbm(st + r); + var c = gl.mix(gl.V3{ 0.101961, 0.619608, 0.666667 }, gl.V3{ 0.666667, 0.666667, 0.498039 }, gl.clamp(f * f * 4, 0, 1)); + c = gl.mix(c, gl.V3{ 0, 0, 0.164706 }, gl.clamp(gl.length(q), 0, 1)); + c = gl.mix(c, gl.V3{ 0.666667, 1, 1 }, gl.clamp(@abs(r[0]), 0, 1)); + gl.color(gl.v3(f * f * f + 0.6 * f * f + 0.5 * f) * c); +} diff --git a/examples/shaders/shaders/zig/expo.zig b/examples/shaders/shaders/zig/expo.zig new file mode 100644 index 0000000..716e2a9 --- /dev/null +++ b/examples/shaders/shaders/zig/expo.zig @@ -0,0 +1,12 @@ +//! The Book of Shaders 05/expo.frag: y = x^5, with its plot. +const gl = @import("gl"); + +fn plot(st: gl.V2, pct: f32) f32 { + return gl.smoothstep(pct - 0.02, pct, st[1]) - gl.smoothstep(pct, pct + 0.02, st[1]); +} + +export fn main() callconv(gl.fragment) void { + const st = gl.st(); + const y = gl.pow(st[0], 5); + gl.color(gl.mix(gl.v3(y), .{ 0, 1, 0 }, plot(st, y))); +} diff --git a/examples/shaders/shaders/zig/fullscreen.zig b/examples/shaders/shaders/zig/fullscreen.zig new file mode 100644 index 0000000..0e0092e --- /dev/null +++ b/examples/shaders/shaders/zig/fullscreen.zig @@ -0,0 +1,9 @@ +//! One triangle over the whole target, from the vertex index alone. +const std = @import("std"); + +export fn main() callconv(.spirv_vertex) void { + const i = std.spirv.vertex_index; + const x: f32 = @floatFromInt((i << 1) & 2); + const y: f32 = @floatFromInt(i & 2); + std.spirv.position_out.* = .{ x * 2 - 1, y * 2 - 1, 0, 1 }; +} diff --git a/examples/shaders/shaders/zig/gl.zig b/examples/shaders/shaders/zig/gl.zig new file mode 100644 index 0000000..f33d5cb --- /dev/null +++ b/examples/shaders/shaders/zig/gl.zig @@ -0,0 +1,73 @@ +//! The GLSL vocabulary the Book of Shaders leans on, for fragment shaders +//! written in Zig: the stage's inputs and outputs, and the builtins Zig +//! does not have under GLSL's names. +const std = @import("std"); +pub const Uniforms = @import("uniforms").Uniforms; + +pub const V2 = @Vector(2, f32); +pub const V3 = @Vector(3, f32); +pub const V4 = @Vector(4, f32); + +pub const fragment: std.builtin.CallingConvention = .{ .spirv_fragment = .{} }; + +/// Fragment uniform slot 0: SDL_GPU's set 3, binding 0. +pub const u = @extern(*addrspace(.uniform) const Uniforms, .{ .name = "u", .decoration = .{ .descriptor = .{ .set = 3, .binding = 0 } } }); +pub const out = @extern(*addrspace(.output) V4, .{ .name = "color", .decoration = .{ .location = 0 } }); + +/// `gl_FragCoord.xy / u_resolution`, y up as in GL (Vulkan and WebGPU put +/// the origin at the top). +pub fn st() V2 { + const fc = std.spirv.frag_coord; + const xy = V2{ fc[0], fc[1] } / u.resolution; + return .{ xy[0], 1 - xy[1] }; +} + +pub fn color(c: V3) void { + out.* = .{ c[0], c[1], c[2], 1 }; +} + +/// GLSL's `vec2(x)`: Zig does not broadcast a scalar into a vector. +pub fn v2(x: f32) V2 { + return @splat(x); +} +pub fn v3(x: f32) V3 { + return @splat(x); +} + +pub fn fract(x: anytype) @TypeOf(x) { + return x - @floor(x); +} +pub fn dot(a: anytype, b: @TypeOf(a)) f32 { + return @reduce(.Add, a * b); +} +pub fn length(a: anytype) f32 { + return @sqrt(dot(a, a)); +} +pub fn mix(a: anytype, b: @TypeOf(a), t: f32) @TypeOf(a) { + const T = @TypeOf(a); + return if (T == f32) a + (b - a) * t else a + (b - a) * @as(T, @splat(t)); +} +pub fn clamp(x: anytype, lo: f32, hi: f32) @TypeOf(x) { + const T = @TypeOf(x); + return if (T == f32) @min(@max(x, lo), hi) else @min(@max(x, @as(T, @splat(lo))), @as(T, @splat(hi))); +} +pub fn smoothstep(e0: f32, e1: f32, x: f32) f32 { + const t = clamp((x - e0) / (e1 - e0), 0, 1); + return t * t * (3 - 2 * t); +} +pub fn pow(x: f32, y: f32) f32 { + return @exp2(y * @log2(x)); +} +/// GLSL's `atan(y, x)`. `std.math.atan2` indexes constant tables through +/// generic pointers, which Vulkan's logical addressing forbids, so this is +/// the GLSL.std.450 instruction itself. +pub fn atan2(y: f32, x: f32) f32 { + return asm ( + \\%glsl = OpExtInstImport "GLSL.std.450" + \\%ret = OpExtInst %f32 %glsl 25 %y %x + : [ret] "" (-> f32), + : [f32] "t" (f32), + [y] "" (y), + [x] "" (x), + ); +} diff --git a/examples/shaders/shaders/zig/hsb_wheel.zig b/examples/shaders/shaders/zig/hsb_wheel.zig new file mode 100644 index 0000000..71c7110 --- /dev/null +++ b/examples/shaders/shaders/zig/hsb_wheel.zig @@ -0,0 +1,16 @@ +//! The Book of Shaders 06/hsb-colorwheel.frag. +const std = @import("std"); +const gl = @import("gl"); + +fn hsb2rgb(c: gl.V3) gl.V3 { + var rgb = gl.clamp(@abs(@mod(gl.v3(c[0] * 6) + gl.V3{ 0, 4, 2 }, gl.v3(6)) - gl.v3(3)) - gl.v3(1), 0, 1); + rgb = rgb * rgb * (gl.v3(3) - gl.v3(2) * rgb); + return gl.v3(c[2]) * gl.mix(gl.v3(1), rgb, c[1]); +} + +export fn main() callconv(gl.fragment) void { + const to_center = gl.v2(0.5) - gl.st(); + const angle = gl.atan2(to_center[1], to_center[0]); + const radius = gl.length(to_center) * 2; + gl.color(hsb2rgb(.{ angle / std.math.tau + 0.5, radius, 1 })); +} diff --git a/examples/shaders/shaders/zig/polar.zig b/examples/shaders/shaders/zig/polar.zig new file mode 100644 index 0000000..85df26e --- /dev/null +++ b/examples/shaders/shaders/zig/polar.zig @@ -0,0 +1,9 @@ +//! The Book of Shaders 07/polar.frag: a three-petal flower in polar terms. +const gl = @import("gl"); + +export fn main() callconv(gl.fragment) void { + const pos = gl.v2(0.5) - gl.st(); + const r = gl.length(pos) * 2; + const f = @cos(gl.atan2(pos[1], pos[0]) * 3); + gl.color(gl.v3(1 - gl.smoothstep(f, f + 0.02, r))); +} diff --git a/examples/shaders/shaders/zig/truchet.zig b/examples/shaders/shaders/zig/truchet.zig new file mode 100644 index 0000000..fc74304 --- /dev/null +++ b/examples/shaders/shaders/zig/truchet.zig @@ -0,0 +1,21 @@ +//! The Book of Shaders 10/2d-random-truchet.frag. +const gl = @import("gl"); + +fn random(st: gl.V2) f32 { + return gl.fract(@sin(gl.dot(st, .{ 12.9898, 78.233 })) * 43758.5453123); +} + +fn truchet(st: gl.V2, index: f32) gl.V2 { + const i = gl.fract((index - 0.5) * 2); + if (i > 0.75) return gl.v2(1) - st; + if (i > 0.5) return .{ 1 - st[0], st[1] }; + if (i > 0.25) return gl.v2(1) - gl.V2{ 1 - st[0], st[1] }; + return st; +} + +export fn main() callconv(gl.fragment) void { + const st = gl.st() * gl.v2(10); + const tile = truchet(gl.fract(st), random(@floor(st))); + const c = gl.smoothstep(tile[0] - 0.3, tile[0], tile[1]) - gl.smoothstep(tile[0], tile[0] + 0.3, tile[1]); + gl.color(gl.v3(c)); +} diff --git a/examples/shaders/src/main.zig b/examples/shaders/src/main.zig new file mode 100644 index 0000000..bcbe160 --- /dev/null +++ b/examples/shaders/src/main.zig @@ -0,0 +1,92 @@ +//! The Book of Shaders, a few examples, each in Zig and in GLSL: left and +//! right (or a click) change example, `l` the language. The pictures should +//! match. +const std = @import("std"); +const sk = @import("sketch"); +const gpu = sk.abi.gpu; +const Uniforms = @import("uniforms").Uniforms; +const zig = @import("zig_shaders"); +const glsl = @import("glsl_shaders"); + +pub const name = "shaders"; +pub const width = 600; +pub const height = 600; + +const examples = .{ "expo", "hsb_wheel", "polar", "truchet", "clouds" }; + +pub const Language = enum { zig, glsl }; + +pub const State = struct { + example: u8 = 0, + language: Language = .zig, + /// Seconds, from recorded ticks: replays see the same time. + time: f32 = 0, +}; + +pub const Session = struct { + image: sk.Image = .none, + size: [2]u32 = .{ 0, 0 }, +}; + +pub fn update(s: *State, in: *const sk.Input) void { + const n: u8 = examples.len; + for (in.events) |e| switch (e.kind) { + .tick => s.time += e.x, + .mouse_down => s.example = (s.example + 1) % n, + else => {}, + }; + if (in.pressed(sk.Key.right)) s.example = (s.example + 1) % n; + if (in.pressed(sk.Key.left)) s.example = (s.example + n - 1) % n; + if (in.pressed(sk.Key.l)) s.language = if (s.language == .zig) .glsl else .zig; +} + +pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { + const in = f.in; + if (!f.host.gpu()) { + f.clear(0x000000); + f.text(8, 8, 2, "no GPU here", 0xffffff); + return; + } + const size: [2]u32 = .{ @intFromFloat(in.width), @intFromFloat(in.height) }; + if (ss.image == .none or !std.meta.eql(ss.size, size)) { + if (ss.image != .none) f.host.freeImage(ss.image); + ss.image = f.host.newImage(size[0], size[1]); + ss.size = size; + } + const uniforms: Uniforms = .{ + .resolution = .{ in.width, in.height }, + .mouse = .{ in.mouse_x, in.height - in.mouse_y }, + .time = s.time, + }; + f.gpu(.{ + .label = "book of shaders", + .image = ss.image, + .width = size[0], + .height = size[1], + .pipelines = &.{pipelines[@intFromEnum(s.language)][s.example]}, + .draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, uniforms) }}, + }); + f.image(ss.image, .{ .x = 0, .y = 0, .w = in.width, .h = in.height }, .{}); + f.print(8, 8, 2, 0xff8040, "{s} in {t}", .{ names[s.example], s.language }); +} + +const names: [examples.len][]const u8 = examples; + +const pipelines = blk: { + var p: [2][examples.len]gpu.Pipeline = undefined; + for (examples, 0..) |example, i| { + p[@intFromEnum(Language.zig)][i] = pipeline(zig.fullscreen, @field(zig, example)); + p[@intFromEnum(Language.glsl)][i] = pipeline(glsl.fullscreen_vert, @field(glsl, example ++ "_frag")); + } + break :blk p; +}; + +fn pipeline(vertex: []const u8, fragment: []const u8) gpu.Pipeline { + return .{ + .vertex = .{ .code = vertex }, + .fragment = .{ .code = fragment, .uniform_buffers = 1 }, + .stride = 0, + .attributes = &.{}, + .blend = .none, + }; +} diff --git a/examples/shaders/src/uniforms.zig b/examples/shaders/src/uniforms.zig new file mode 100644 index 0000000..5810e46 --- /dev/null +++ b/examples/shaders/src/uniforms.zig @@ -0,0 +1,21 @@ +//! What every fragment shader here reads: the one definition, imported by +//! the sketch, by the Zig shaders, and written out as GLSL for the others. +const builtin = @import("builtin"); + +/// GLSL's vec2. On the GPU a vector, which SPIR-V lays out as vec2 (an +/// array in a uniform block gets a 16-byte stride under std140); on the +/// CPU an array, since extern structs cannot hold vectors there. +pub const vec2 = if (builtin.cpu.arch.isSpirV()) @Vector(2, f32) else [2]f32; + +pub const Uniforms = extern struct { + /// Pixels. + resolution: vec2, + /// Pixels, y up as in GL. + mouse: vec2, + /// Seconds. + time: f32, + pad0: f32 = 0, + pad1: vec2 = .{ 0, 0 }, + + pub const glsl = .{ .uniform = .{ .set = 3, .instance = "u" } }; +}; diff --git a/examples/shaders/test/reload.script b/examples/shaders/test/reload.script new file mode 100644 index 0000000..ba0063a --- /dev/null +++ b/examples/shaders/test/reload.script @@ -0,0 +1,31 @@ +# Live reload with State kept: the second build ({v2}) changes the plot +# colour of expo in the Zig shader and in the GLSL one, and the label +# colour in the sketch's Zig code (see addReloadCheck in build.zig). +frames 10 +key right +key left +expect example 0 +expect language zig +screenshot .zig-cache/e2e/reload-zig-before.png +key l +expect language glsl +frames 2 +screenshot .zig-cache/e2e/reload-glsl-before.png +key l +key right +expect example 1 +frames 2 +load {v2} +expect example 1 +expect language zig +key left +frames 2 +screenshot .zig-cache/e2e/reload-zig-after.png +key l +expect language glsl +frames 2 +screenshot .zig-cache/e2e/reload-glsl-after.png +# The plot (the shaders) and the label (the Zig code) both changed. +expect-different-screenshot .zig-cache/e2e/reload-zig-before.png .zig-cache/e2e/reload-zig-after.png 0 40 600 560 +expect-different-screenshot .zig-cache/e2e/reload-glsl-before.png .zig-cache/e2e/reload-glsl-after.png 0 40 600 560 +expect-different-screenshot .zig-cache/e2e/reload-zig-before.png .zig-cache/e2e/reload-zig-after.png 0 0 300 30 diff --git a/examples/shaders/test/shaders.script b/examples/shaders/test/shaders.script new file mode 100644 index 0000000..a67e0db --- /dev/null +++ b/examples/shaders/test/shaders.script @@ -0,0 +1,43 @@ +# Each example in Zig, then in GLSL: the screenshots of a pair should match. +frames 30 +screenshot .zig-cache/e2e/expo-zig.png +key l +expect language glsl +frames 2 +screenshot .zig-cache/e2e/expo-glsl.png +key l +key right +frames 2 +screenshot .zig-cache/e2e/hsb_wheel-zig.png +key l +expect language glsl +frames 2 +screenshot .zig-cache/e2e/hsb_wheel-glsl.png +key l +key right +frames 2 +screenshot .zig-cache/e2e/polar-zig.png +key l +expect language glsl +frames 2 +screenshot .zig-cache/e2e/polar-glsl.png +key l +key right +frames 2 +screenshot .zig-cache/e2e/truchet-zig.png +key l +expect language glsl +frames 2 +screenshot .zig-cache/e2e/truchet-glsl.png +key l +key right +frames 2 +screenshot .zig-cache/e2e/clouds-zig.png +key l +expect language glsl +frames 2 +screenshot .zig-cache/e2e/clouds-glsl.png +key l +key right +frames 2 +expect example 0 diff --git a/examples/shaders/test/timeline.script b/examples/shaders/test/timeline.script new file mode 100644 index 0000000..0041d73 --- /dev/null +++ b/examples/shaders/test/timeline.script @@ -0,0 +1,71 @@ +# Timeline check (design.md "Acceptance: timeline"), from +# noc/test/accel_to_mouse.timeline.script. State is the example index, the +# language and the time, summed from recorded ticks: a replay must land on +# the same example, language and time to the bit, and draw the same picture. + +# 1. Record: keys and a click change example and language while time runs. +frames 10 +console snapshot 1 +console record 0 +frames 20 +key right +frames 15 +key l +frames 10 +down 300 300 +up 300 300 +frames 20 +key right +key right +frames 10 +key l +key left +frames 25 +expect example 3 +expect language zig +console save 2 + +# 2. Played to the end, exactly. +console play 0 +frames 150 +expect-snapshot 2 +screenshot .zig-cache/e2e/shaders-played.png +# 5. Paused: `draw` must not move State (time included). +frames 30 +expect-snapshot 2 + +# 3. Sought to the end, and to the middle and played on. +console seek end +expect-snapshot 2 +screenshot .zig-cache/e2e/shaders-sought.png +# 7. What a seek shows equals what playing showed. +expect-same-screenshot .zig-cache/e2e/shaders-played.png .zig-cache/e2e/shaders-sought.png +console seek 1000 +console pause +frames 10 +console pause +frames 30 +console pause +frames 150 +expect-snapshot 2 + +# 4. Stepped from the start, then back and forth. +console seek start +console step 100000 +expect-snapshot 2 +console step -25 +console step 25 +expect-snapshot 2 +screenshot .zig-cache/e2e/shaders-stepped.png +expect-same-screenshot .zig-cache/e2e/shaders-played.png .zig-cache/e2e/shaders-stepped.png + +# 6. Live input (a click, a key), then the same replay. +console stop +down 100 100 +up 100 100 +key l +frames 10 +console play 0 +frames 150 +expect-snapshot 2 +console stop |
