diff options
| author | Gabriel Schneider <[email protected]> | 2026-09-25 21:47:58 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-09-25 21:48:16 -0300 |
| commit | 9c33714591a2147f7e5879e77212ca9886d0c967 (patch) | |
| tree | d250be9d9bc365d7894d49455c0f6376966b58be /README.md | |
| download | sketchbook-9c33714591a2147f7e5879e77212ca9886d0c967.tar.gz sketchbook-9c33714591a2147f7e5879e77212ca9886d0c967.zip | |
Put the game first: lib/sketchbook, sketches/vecanim
The root is the game. The platform library moves to lib/sketchbook (with
serve_web.py, which serves any sketch's web build, as a tool of it), and
vecanim to sketches/vecanim, still its own package on the same library.
Diffstat (limited to 'README.md')
| -rw-r--r-- | README.md | 160 |
1 files changed, 160 insertions, 0 deletions
diff --git a/README.md b/README.md new file mode 100644 index 0000000..6531fcd --- /dev/null +++ b/README.md @@ -0,0 +1,160 @@ +# sketchbook + +A small Zig 0.16 platform for sketching games and toys, in the spirit of +Processing and pygame: write plain data and two functions, save, and the +running program picks up the new code with its state intact. + +```zig +const sk = @import("sketch"); + +pub const State = struct { x: f32 = 480, y: f32 = 300, hue: f32 = 0 }; + +pub fn update(s: *State, in: *const sk.Input) void { + if (in.pressed(sk.Key.space)) s.hue += 30; + s.x += (in.mouse_x - s.x) * 0.1; + s.y += (in.mouse_y - s.y) * 0.1; +} + +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(0x202020); + f.fill(.{ .x = s.x - 10, .y = s.y - 10, .w = 20, .h = 20 }, 0xff8040); + f.print(8, 8, 2, 0xffffff, "hue {d}", .{s.hue}); +} +``` + +## An app + +An app is an ordinary module. Every declaration is optional: + +| Declaration | Meaning | +| --- | --- | +| `name`, `width`, `height` | Window title and initial canvas | +| `State` | Persistent state: saved to a file, snapshotted, replayed. No pointers (compile error). | +| `Session` | Survives reloads, never saved: caches, loaded handles, audio buffers. May point into host memory. | +| `init(state, host)` | Setup for brand-new state, after the declared defaults | +| `update(state, input)` | **Deterministic**: the host replays recorded input through it | +| `draw(state, session, frame)` | Pictures and sound, as commands; may change only `Session` | +| `command(state, session, console, line) !bool` | Console lines the host does not know | +| `commands` | Console completions | + +`update` sees `input.events`: pointer, wheel, key, text, `cancel` (focus loss, +console) and one `tick` per frame carrying `dt`. Recorded ticks make +time-driven sketches replay exactly. + +`draw` gets a `Frame`: `clear`, `fill`, `image`, `text`, `print`, `clip`, +`canvas`, `cursor`, `voice`, `audio`, `pixels`, `quit`, plus `f.arena` (frame +lifetime), `f.gpa` (session lifetime) and `f.host` (`loadImage`, +`decodeImage`, `newImage`, `loadSound`, `decodeSound`, `readFile`, `env`, +`log`). + +Geometry and colors are duck-typed. Anything with `x`/`y` is a point, anything +that also has `w`/`h` (or `width`/`height`) is a rect, in any number type, and +`@Vector`s or arrays work too. Colors are `r`/`g`/`b`[/`a`] or `0xRRGGBB`. The +helpers return the caller's own type: + +- `sk.shape`: `isPoint`/`isRect`/`isColor`, `contains`, `inset`, `offset` +- `sk.Camera`: `toScreen`, `toWorld`, `pan`, `zoomAt` +- `sk.tween`: `lerp` over any plain data, `lerpFields(a, b, t, .{ .x, .zoom })`, `toward(a, .{ .x = 100 }, t)`, and `ease` + +**Vector graphics**, in the `vector` module (import `sb.modules.vector`): +SVG parsing (the static subset Typst emits, and more) into cubic Bézier +data; flattening, stroking, dashing, trimming, clipping and morphing as +geometry; and `vector.Renderer(.gpu)` or `vector.Renderer(.cpu)`. The CPU +backend computes exact coverage and runs anywhere, wasm included. The GPU +backend describes stencil-then-cover passes (8× MSAA, gradients in a +shader). Both are tested against resvg (see `sketches/vecanim` in the game repository). + +**GPU work is data.** A sketch describes pipelines (SPIR-V, vertex layout, +blend, stencil) and passes (`f.gpu(.{ .image, .pipelines, .draws, ... })`); +the host runs them with SDL_GPU. It caches shaders and pipelines by content +hash, so an edited shader is just a new pipeline after a reload. No sketch +touches a graphics API, and another host (Vulkan, WebGPU) would be another +translation of the same data. `abi.gpu.pipeline(Vertex, ...)` derives the +vertex layout from a struct, and `abi.gpu.uniform` checks std140 at +compile time. + +Sound is declarative. `f.voice(.{ .key, .audio, .serial, .loop, .volume })` +declares a voice that should be sounding. A new key or serial starts it, and +an undeclared key stops it. A finished one-shot stays finished while it is +still declared, so replays and seeks never re-fire sounds. `f.audio(key, +samples, .{})` streams PCM, and `input.stream(key)` reports what the host has +queued and played. + +## The host + +- **Hot reload.** It watches the library file and loads each new build through + a private copy. +- **State file.** `<name>.state` holds the live state plus 7 snapshot slots, + shared via `MAP_SHARED`. Its header carries the reflected layout, so a + layout change migrates every slot field by field, with enums matched by tag + name, and `sketchbook-probe` can print any sketch's state. +- **Time travel.** Recordings, replay, seek and step work on any sketch, + because they only need state bytes and events. +- **Console and overlays.** `get`/`set <field path>`, snapshots, recordings and + the memory and scope overlays come from the host; unknown lines go to the + sketch. +- **Scripts** (`--headless --fresh --script file`) drive the same routing and + frames as a player: `click`, `key`, `type`, `console`, `expect field value`, + `expect-audio`, `screenshot`, `load`, `await-reload`. +- **GPU.** The host's 2D renderer runs on an SDL GPU device, which also + runs sketches' GPU passes. Without a GPU it falls back to any renderer. +- **Memory.** SDL allocations go through a leak-checking allocator; a leak + fails the exit. + +## Build API + +```zig +const sketchbook = @import("sketchbook"); + +pub fn build(b: *std.Build) void { + const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize }); + const app = sb.app(.{ .name = "demo", .root_source_file = b.path("src/main.zig") }); + _ = app.addSteps(.{ .scripts = &.{b.path("test/play.script")} }); +} +``` + +`addSteps` installs the executable and adds `run`, `lib`, `web`, `probe`, +`e2e` and `test`. Every piece is also available on its own and returns plain +`std.Build` objects: + +| Call | Returns | +| --- | --- | +| `app.addLibrary()` | the hot-reloadable shared library | +| `app.addExecutable()` | host and sketch linked into one binary | +| `app.addWeb(.{ .assets = ... })` | the wasm module and a ready-to-serve directory | +| `app.addRun(lib, .{})` | the generic host running the installed library | +| `app.addScript(exe, file, .{})` | a headless, fresh-state scripted run | +| `app.addProbe(state)` | the probe on a state file | +| `app.addTest(.{})` | tests with the app importable as `app` | + +Shaders, in the same style: + +```zig +const layouts = sb.addGlslLayouts(.{ .module = my_layouts, .types = &.{ "Vertex", "Paint" } }); +const shaders = sb.addSpirvModule(&.{ + .{ .name = "fill_vert", .spirv = sb.addGlslc(.{ .source = b.path("fill.vert"), .include_dirs = &.{layouts.dir} }).spirv }, +}); +``` + +`addGlslLayouts` writes `<Name>.glsl` declarations generated from Zig +structs (tagged with `pub const glsl = .vertex` or +`.{ .uniform = .{ .set, .instance } }`), so the Zig struct is the one +definition. `addGlslc` compiles one file. `addSpirvModule` embeds the +results, aligned for Vulkan. + +`sb.modules`, `sb.host_exe` and `sb.probe_exe` are exposed for anything else. +Add `.sketchbook = .{ .path = "..." }` to your `build.zig.zon`. + +## The boundary + +Host and sketch are built by the same `zig build`, so ordinary Zig types cross +it (slices, tagged unions, `std.mem.Allocator`). `abi.hash`, a comptime hash +of every shared type's layout, guards against the one real hazard: a host +refuses a library built against different definitions. Everything that outlives +a call lives in host memory, since host code is never unloaded. Only the +recorded `Event` and the reflected `Layout` are `extern`, because they are +written to disk. + +`zig build test` in this directory runs the unit tests and a headless reload +through `dlopen`, where a counter sketch changes its layout mid-run and keeps +its values. |
