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/noc/notes/research-love-raylib.md | |
| parent | 82fca5c9f29124f37f6dcd08e73e6999ce44a69d (diff) | |
| download | sketchbook-6933f99ddb2d7103515d26838496309a807bba26.tar.gz sketchbook-6933f99ddb2d7103515d26838496309a807bba26.zip | |
Move standalone sketches into sketchbook examples
Diffstat (limited to 'examples/noc/notes/research-love-raylib.md')
| -rw-r--r-- | examples/noc/notes/research-love-raylib.md | 477 |
1 files changed, 477 insertions, 0 deletions
diff --git a/examples/noc/notes/research-love-raylib.md b/examples/noc/notes/research-love-raylib.md new file mode 100644 index 0000000..90cab7f --- /dev/null +++ b/examples/noc/notes/research-love-raylib.md @@ -0,0 +1,477 @@ +# LÖVE and raylib, read for sketchbook + +What would make sketchbook as quick to iterate in as LÖVE or raylib while +keeping it explicit, low level, free of hidden globals and fixed on its +invariants (plain-data State, deterministic replayed `update`, `draw` +emits commands as data, every command runs on both hosts, GPU work as data). + +Sources: `~/05-genizah/love/src` (paths below are relative to it), +`~/05-genizah/raylib/src`, and sketchbook at +`lib/sketchbook` (`SB/` below). noc's own workarounds are in +`sketches/noc/src/helpers_{a,b}.zig`. + +**The one-paragraph verdict.** Both libraries hide a lot of state: +the current color, a matrix stack, the bound canvas, the blend mode, the +shader, the global RNG. Their real *implementations* are what sketchbook +should take. Every batched shape is transformed on the CPU and turned into +triangles on the CPU, and a batch is just "flush when texture/mode changes". +That fits command-as-data well: put the transform and tessellation in the +sketch library, as a **value** you copy instead of push/pop, and add **one** +cheap geometry command (`shape`: triangles in one color) plus a few +small state commands (`blend`, `target`) and GPU-pass fields (`instances`, +`textures`). Leave out every API that is a setter on hidden state, and every +API keyed by strings. + +--- + +## 1. Relevant APIs and how they are built + +| Area | LÖVE | raylib | How it works | sketchbook today | +| --- | --- | --- | --- | --- | +| Transform stack | `push/pop/translate/rotate/scale/shear/applyTransform` (`modules/graphics/Graphics.cpp:2795-2899`, stack `Graphics.h:1097`) | `rlPushMatrix/rlPopMatrix` (`rlgl.h:1207-1238`, fixed depth 32 at `rlgl.h:228`) | A `std::vector<Matrix4>` / a 32-deep array. **Both apply it on the CPU per vertex at batch time**: LÖVE `t.transformXY(...)` in `polygon` (`Graphics.cpp:2742`) and `Polyline::draw` (`Polyline.cpp:~430`); raylib `rlVertex3f` multiplies when `transformRequired` (`rlgl.h:1495-1503`). The GPU sees only an ortho projection. | None. noc keeps an `Affine` in its `Style` (`helpers_a.zig:150`); `vector.geom.Affine` exists (`SB/src/vector/geom.zig:36`). | +| Pixel scale for tessellation | `pixelScaleStack` updated by `scale` (`Graphics.cpp:2868`), used by `calculateEllipsePoints` (`:2456-2460`) and `polyline` (`:2468`) | none (radius only) | Segment count grows with the size on screen, so a zoomed circle stays round. | — | +| Batching | `requestBatchedDraw` (`Graphics.cpp:1986-2121`): flush if primitive, vertex format, texture or shader type differ (`:1995-2001`) or the buffer is full; `flushBatchedDraws` `:2123` | `rlDrawCall{mode, vertexCount, textureId}` (`rlgl.h:407`); new draw call on mode change (`rlBegin`, `rlgl.h:1452`) or texture change (`rlSetTexture`, `:1638`); flush when full (`rlCheckRenderBatchLimit`, `:3205`); upload with `glBufferSubData` (`:2975`) | Append to a CPU array; on any state change, close the run. | Every command is drawn by itself. SDL_Renderer queues internally. The GPU pass uploads all draws' vertices in one copy (`SB/src/host/gpu.zig:192-200`). | +| Streaming vertex memory | `StreamBuffer` map/unmap/markUsed/nextFrame (`StreamBuffer.h:62-66`; GL ring split by frame, `opengl/StreamBuffer.cpp:41,144-152`) | one CPU array per batch, re-uploaded | A frame-partitioned ring, so the CPU never writes what the GPU still reads. | The **scratch arena** already does this on the CPU side. Web rings in `host.js:91-107`. | +| Circles / arcs | `circle/ellipse/arc` → polygon of `calculateEllipsePoints` points (`Graphics.cpp:2561-2690`) | `DrawCircleSector` (`rshapes.c:1646`), segments from an error bound `th = acos(2(1-e/r)^2-1)`, `e = 0.5px` (`rshapes.c:62-65, 1668`) | CPU tessellation into a fan/quads. raylib's error bound is the better rule. | Only through `vector` (Bézier ellipse → stencil+cover on GPU, or CPU coverage). | +| Filled polygon | `polygon(fill)` = **triangle fan** (`Graphics.cpp:2694-2711`) | `DrawTriangleFan` (`rshapes.c:541`) | A fan is only right for convex polygons; LÖVE documents "convex only". | `vector` handles any polygon with nonzero/even-odd fill (stencil). | +| Thick lines | `Polyline::render` (`Polyline.cpp:36`): a triangle strip with joins per vertex. Miter by Cramer's rule (`:173-222`), a zero-size quad where the direction reverses (`:196-210`), bevel `:243`, none `:110`. **No miter limit.** | `DrawLineEx` = a 4-vertex strip (`rshapes.c:183`); `DrawSplineLinear` miter, no limit (`rshapes.c:3735`); `DrawLineV` = GL lines (`:205`) | A strip of non-overlapping quads, except at sharp inner turns. | `vector.Polygons.stroke` (`SB/src/vector/Polygons.zig:181-330`): quads plus join and cap polygons that **overlap** and rely on nonzero union; has a miter limit. | +| Line anti-aliasing | `LINE_SMOOTH` "overdraw": shrink by 0.3 px (`Polyline.cpp:47-48`), then an extra strip whose outer vertices have alpha 0 (`render_overdraw :308`, `fill_color_array :472-488`) | none (relies on MSAA hint) | A fringe of per-vertex alpha: cheap AA with no MSAA. | GPU path: 8× MSAA. SDL_Renderer: none. Canvas2D: always AA. | +| Shapes + sprites in one batch | default texture | `SetShapesTexture` = the font's white pixel (`rshapes.c:93`) | Shapes sample a white texel, so shapes and text share one draw call. | n/a | +| Offscreen targets | `setCanvas` → `setRenderTargets` (`Graphics.cpp:1054`) | `BeginTextureMode` (`rcore.c:1001`): flush, bind FBO, reset ortho to the target's size | Global "current target" + flush. | GPU passes always render **into an Image**; 2D commands can draw only to the screen. | +| Blend modes | `setBlendMode` (`Graphics.cpp:1619`); table of premultiplied factors for alpha/add/subtract/multiply/lighten/darken/screen/replace (`renderstate.cpp:31-58`) | `BeginBlendMode` (`rcore.c:1066`), `rlSetBlendMode` (`rlgl.h:2118`), enum `rlgl.h:497-502` | Global state; a change flushes. | `gpu.Blend` = none/premultiplied/additive (`SB/src/abi.zig:314-320`); 2D: always alpha. | +| Shader authoring | User writes `vec4 effect(color, tex, uv, px)`; LÖVE wraps it in a prelude (`Shader.cpp:310-313`, built in `createShaderStageCode :586`) | Default attribute and uniform names (`rlgl.h:1003-1021`: `vertexPosition`, `mvp`, `colDiffuse`, `texture0`) | A convention plus a generated prelude. | GLSL → SPIR-V/WGSL at build time; layouts from Zig structs (`addShaders`). No samplers (`SB/src/host/gpu.zig:525`). | +| Uniforms | `Shader:send(name, …)` → `getUniformInfo(name)` (`Shader.cpp:794`) | `GetShaderLocation(name)` → `SetShaderValue(loc, ptr, type)` (`rcore.c:1346-1370`) | String lookup through reflection; types checked at run time. | std140 bytes from a Zig struct, checked at **compile time** (`SB/src/abi.zig:416-427`). Already better. | +| Shader live reload | (LÖVE: reload the game) | `examples/shaders/shaders_hot_reloading.c:43-94`: poll the file's mtime, `LoadShader`, look up the locations again | Runtime compile from source. | A shader change is a rebuild, then a hot reload; pipelines are cached by content hash (`SB/src/host/gpu.zig:536+`, `host.js:190`). State is kept. | +| SpriteBatch / Mesh | `SpriteBatch::add` writes 4 transformed verts on the CPU (`SpriteBatch.cpp:88-121`), a dirty range; `Mesh` with a user vertex format (`Mesh.cpp:48`) | — | Retained GPU objects. | `gpu.Draw{vertices}` from session memory is already the "mesh as data" form. | +| RNG | `RandomGenerator`: xorshift64* (`math/RandomGenerator.cpp:67-74`), Box-Muller **caches the second normal** (`:76-91`), wang-hashed seed (`:93-109`), `getState/setState` as a hex string that **drops the cached normal** (`:116-145`) | `GetRandomValue` over a **static global** xoshiro128** (`external/rprand.h:152`, `rcore.c:1701-1723`) | LÖVE: an object with serializable state (but lossy); raylib: a hidden global. | noc keeps `std.Random.DefaultPrng` in State (`random_walk.zig`). Works, but there is no `normal`, no stateless form for `draw`. | +| Noise | `love.math.noise` = simplex (`math/MathModule.h:132-147`, remapped to 0..1), a fixed `perm[512]` (`libraries/noise1234/simplexnoise1234.cpp:62`) | (none in core) | A pure function of the coordinates; no seed, no state. | noc ported Processing's noise (`helpers_a.zig:46-125`). | +| Main loop / time | `love.run` (`modules/love/callbacks.lua:168-205`): `dt = timer.step()` → `update(dt)` → `origin()` → `draw()` → sleep 1 ms | `SetTargetFPS` + `EndDrawing` waits, then `PollInputEvents` (`rcore.c:880-920, 1576`); `GetFrameTime` (`:1634`) | Variable dt in both. | Variable dt as recorded `tick` events (`SB/src/host/Host.zig:225-235`), which makes replay exact. noc rebuilt a 60 Hz accumulator (`helpers_a.zig:17-27`). | +| Input | callbacks `keypressed/...` dispatched from `love.handlers` (`callbacks.lua:30-32`) + `isDown` polling | polling: `IsKeyPressed` = `previous==0 && current==1` (`rcore.c:3882-3888`, arrays `:332`) | Callbacks, or a diff of key state between frames (which **loses a press and release that both fall in one frame**). | Events in `in.events`; `pressed` scans them (`SB/src/abi.zig:160-166`). Already the better model. | +| Camera2D | — | `Camera2D{offset,target,rotation,zoom}`; `GetCameraMatrix2D` (`rcore.c:1473-1497`); `BeginMode2D` flushes and loads the matrix (`:925`) | A matrix pushed into the global stack. | `sk.Camera{x,y,zoom}` with `toScreen/toWorld/zoomAt` (`SB/src/sketch/camera.zig`); no rotation, nothing to draw through it. | + +Host facts that set the cost of each proposal: + +- Native 2D is an **SDL_Renderer on the SDL_GPU device** + (`SB/src/host/Host.zig:111`). SDL3 has `SDL_RenderGeometry` + (`SDL_render.h:2464`; `SDL_Vertex` uses float color, `:89-94`), + `SDL_RenderTextureAffine` (`:2337`), `SDL_SetRenderTarget` with + `SDL_TEXTUREACCESS_TARGET` (`:1512`, `:105`), and `SDL_BLENDMODE_ADD`/`MUL` + (`SDL_blendmode.h:57-60`). +- Web 2D is **Canvas2D** (`SB/web/host.js:441-485`): native paths, always + anti-aliased, `globalCompositeOperation`, `transform()`, and offscreen + canvases (`newImage` already makes one with its own 2D context, + `host.js:427-431`). It has **no triangle primitive and no per-vertex + color**. One path filled once has no seams; separate fills of adjacent + triangles show conflation seams. +- Parity gap found while reading: the web host drops the image tint's RGB + (`SB/src/sketch/web.zig:30` passes only `tint.a`). + +--- + +## 2. Proposals + +Ranked by how much iteration speed they buy per unit of invariant risk. +"Lives in" uses **lib** (`src/sketch`, compiled into every app, reloaded), +**abi** (new data in `abi.Command`/`abi.gpu`, bumps `abi.hash`) and +**host** (both `src/host` and `web/host.js` + `src/sketch/web.zig`). + +### P1. `sk.Pen`: transform and style as a value; CPU tessellation (lib) + +LÖVE's and raylib's real design, without the hidden stack. A `Pen` is a small +struct holding `*Frame`, an `Affine`, and the style. "push/pop" is **copying +the value**: Zig scoping balances it, so a pop can never be missing and there +is no depth limit (rlgl's 32, `rlgl.h:228`). Nothing global; a fresh Pen per +`draw` replaces LÖVE's implicit `origin()` every frame (`callbacks.lua:196`). +The Pen holds a pointer, so trying to keep one in State is already a compile +error (`SB/src/layout.zig:85`). + +```zig +pub const Pen = struct { + f: *Frame, + xf: Affine = .identity, // vector.geom.Affine, moved to sketch.geom + fill: ?Color = .white, + stroke: ?Color = null, + width: f32 = 1, + join: enum { miter, bevel, round } = .miter, + cap: enum { butt, square, round } = .butt, + miter_limit: f32 = 4, + /// Max distance from the true curve, in canvas pixels (raylib's 0.5). + tolerance: f32 = 0.5, + + pub fn init(f: *Frame) Pen; + pub fn translated(p: Pen, v: anytype) Pen; // returns a copy: "push" + pub fn rotated(p: Pen, radians: f32) Pen; + pub fn scaled(p: Pen, s: anytype) Pen; + pub fn through(p: Pen, cam: Camera) Pen; // camera as one more transform + + pub fn rect(p: Pen, r: anytype) void; // axis-aligned + no stroke → `fill` cmd + pub fn roundRect(p: Pen, r: anytype, radius: f32) void; + pub fn circle(p: Pen, c: anytype, radius: f32) void; + pub fn ellipse(p: Pen, c: anytype, rx: f32, ry: f32) void; + pub fn arc(p: Pen, c: anytype, radius: f32, a0: f32, a1: f32, mode: enum { open, chord, pie }) void; + pub fn line(p: Pen, a: anytype, b: anytype) void; + pub fn polyline(p: Pen, pts: []const Vec, closed: bool) void; + pub fn polygon(p: Pen, pts: []const Vec) void; // fill + stroke + pub fn image(p: Pen, img: Image, dst: anytype, o: anytype) void; // P7 when rotated + pub fn print(p: Pen, at: anytype, comptime fmt: []const u8, args: anytype) void; // translate+scale only +}; +``` + +```zig +pub fn draw(s: *const State, f: *sk.Frame) void { + f.clear(0x101010); + const p: sk.Pen = .init(f); + p.circle(s.ball, 12); + { + var ship = p.through(s.camera).translated(s.ship.pos).rotated(s.ship.angle); + ship.fill = null; + ship.stroke = .white; + ship.width = 2; + ship.polygon(&.{ .{ 10, 0 }, .{ -6, 6 }, .{ -6, -6 } }); + } // "pop" +} +``` + +How it is built (taken from the references): +- Transform on the CPU while emitting, as `transformXY` (`Graphics.cpp:2742`) + and `rlVertex3f` (`rlgl.h:1502`) do. The hosts never see a matrix. +- Segment count from raylib's error bound (`rshapes.c:1668`) with `r` + multiplied by `xf.scaleFactor()`. That is LÖVE's `pixelScaleStack` idea, + derived from the value instead of tracked separately. +- Strokes: LÖVE's strip (`Polyline.cpp:173-222`, including the reversal quad + at `:196`) with the **miter limit from `vector.Polygons`** (bevel past it; + both LÖVE and raylib spike). Round joins and caps go in as fans that only + cover the outer wedge, not whole circles, so the strip stays free of + overlaps (see P2 for why that matters). +- Fill: a fan when convex, ear clipping when concave (LÖVE's plain fan, + `Graphics.cpp:2710`, is wrong for concave shapes). Self-intersecting + shapes and shapes with holes go to `vector` (stencil-then-cover), which + stays the quality path (SVG, exact coverage, 8× MSAA). +- Output: one `shape` command per shape (P2), triangles in `f.scratch`. + +Cost: lib-only CPU work. A circle at r=50 is about 30 triangles; 5k shapes +a frame is well under 1 ms of tessellation. Invariants: none touched, since +it is draw-side only and memory is scratch. It replaces noc's +`Pen`+`show()` pattern (`helpers_a.zig:165-195`), which today renders a +full-canvas 8× MSAA stencil pass every frame just to get a circle, and +needs WebGPU on the web. + +### P2. `Command.shape`: one region of triangles in one color (abi + host) + +The single new geometry command. It is what both hosts can do cheaply *and +equally*: + +```zig +/// One filled region in one color: triangles in canvas pixels, already +/// transformed. Triangles of one shape must not overlap: the web paints +/// the region once (one nonzero path), native paints each triangle. +shape: struct { + color: Color, + /// 3 points per triangle. + triangles: []const [2]f32, + /// Anti-aliasing for hosts whose triangles have hard edges: a triangle + /// list whose vertices carry alpha 0 (outer) or 1 (inner). Hosts that + /// smooth edges themselves (Canvas2D) skip it. + fringe: []const extern struct { x: f32, y: f32, alpha: f32 } = &.{}, +}, +``` + +- **Native**: convert to `SDL_Vertex` in the host's frame arena (float color, + `SDL_render.h:89`) and call `SDL_RenderGeometry` once for the body and once + for the fringe. SDL queues it like the rest. About 1 µs per call plus the + copy. Merging consecutive commands of the same color into one call is a + host-local optimization, LÖVE's flush-on-state-change rule + (`Graphics.cpp:1995`). +- **Web**: `fillStyle = color; beginPath(); moveTo/lineTo/lineTo/closePath` + per triangle, read from a `Float32Array` view of wasm memory; one + `fill('nonzero')`. One fill per shape gives no seams and keeps the + semantics of separate shapes: two overlapping translucent circles double + up on both hosts. The fringe is skipped because Canvas2D already + antialiases. About 50–100 ns a triangle in JS. +- The fringe is LÖVE's overdraw (`Polyline.cpp:47, 472-488`): the Pen shrinks + the shape by 0.3 px and adds a 1 px alpha ramp. It makes native edges look + close to Canvas2D's without MSAA on SDL_Renderer. The Pen can skip it when + `p.aa == false` (pixel art). +- Why not per-vertex colors or textured triangles: Canvas2D can do neither + cheaply (affine-textured triangles take `clip` + `setTransform` + + `drawImage` per triangle). Gradients, per-vertex colors and big meshes + belong in GPU passes, which both hosts already run. +- Why not `circle`/`polyline` commands: each host would need its own + tessellator or path code, the results would differ (Canvas2D's joins vs + ours), and the native host would grow. Tessellation stays in the + reloadable library, so a fix to it hot-reloads. +- Watch: in one path, triangles of **opposite winding that overlap cancel** + under nonzero. The no-overlap rule covers it; the Pen keeps all triangles + wound one way anyway, as `vector`'s tests already check + (`Polygons.zig:~371`). + +Invariant touched: host parity. Both hosts execute it; the only intended +difference is the edge AA and the documented overlap rule. + +### P3. Fixed steps and input helpers on `Input` (lib + abi methods, no new data) + +LÖVE and raylib both feed variable dt to `update` (`callbacks.lua:190-193`, +`rcore.c:1634`). Sketchbook *records* dt, so replay is exact, but physics +still depends on the frame rate across machines (and `pendulum` / +`flocking` care). Lift noc's `steps60` (`helpers_a.zig:17-27`) into the +library as plain data: + +```zig +pub const Clock = struct { + /// Seconds not yet stepped. f64: tick dt is f32 seconds. + owed: f64 = 0, + steps: u64 = 0, + + /// Whole steps of `1/hz` that this update's ticks pay for, at most + /// `max` (the rest is dropped, so a stall does not spiral). + pub fn advance(c: *Clock, in: *const Input, hz: f64, max: u32) u32; + /// How far into the next step we are, 0..1, for `draw` to interpolate. + pub fn alpha(c: Clock, hz: f64) f32; +}; + +pub fn update(s: *State, in: *const sk.Input) void { + for (0..s.clock.advance(in, 60, 8)) |_| step(s); +} +``` + +Input sugar over the event list (all pure functions of `in.events`, so they +replay): +`released(key)`, `clicked(button)` / `unclicked(button)`, `wheel() f32` (sum, +with `.horizontal`), `typed()` (an iterator over text codepoints), +`elapsed() f32` (sum of tick dt in this update). Keep the event-list model: +raylib's state diff (`rcore.c:3888`) misses a key that goes down and up in +one frame; scanning events does not. Do **not** add callbacks +(`love.handlers`): the event list *is* the data form of callbacks. + +Cost: none on hosts. Invariants: strengthens determinism; `Clock` lives in +State and migrates field by field. + +### P4. `sk.Rng` and `sk.noise`: randomness as plain data (lib) + +```zig +/// xoshiro128** (or PCG32): integer-only, so native and wasm agree bit for bit. +pub const Rng = extern struct { + s: [4]u32, + pub fn init(seed: u64) Rng; // splitmix, never all-zero (LÖVE `:99-106`) + pub fn float(r: *Rng) f32; // [0,1) + pub fn range(r: *Rng, lo: anytype, hi: @TypeOf(lo)) @TypeOf(lo); + pub fn chance(r: *Rng, p: f32) bool; + pub fn normal(r: *Rng, mean: f32, sd: f32) f32; // Box-Muller, both values used per call, NO cached spare + pub fn pick(r: *Rng, comptime T: type, items: []const T) T; + pub fn fork(r: *Rng, key: u32) Rng; // an independent stream per entity +}; +/// Stateless, for `draw` (which cannot advance State): a pure hash. +pub fn hash(seed: u32, i: u32) u32; +pub fn hashFloat(seed: u32, i: u32) f32; + +pub const noise = struct { + pub fn simplex2(x: f32, y: f32) f32; // -1..1 + pub fn simplex3(x: f32, y: f32, z: f32) f32; + pub fn fbm2(x: f32, y: f32, o: struct { octaves: u4 = 4, gain: f32 = 0.5, lacunarity: f32 = 2 }) f32; +}; +``` + +- State stays plain data: `rng.s` is a `[4]u32` field, so it is saved, + snapshotted, migrated and visible to `get`/`set`. The trap to avoid is + LÖVE's: `getState` drops the cached second normal + (`RandomGenerator.cpp:135`), so restoring a state changes the next + `randomNormal`. Either cache nothing, or make the spare a State field. + Never keep a hidden global (raylib's `rprand_state`, `rprand.h:152`). +- Noise is a pure function with a comptime table (LÖVE's `perm[512]`, + `simplexnoise1234.cpp:62`), safe in both `update` and `draw`. Better + still: hash-based gradient noise with no table, with the same code in + `sketchbook/noise.glsl`, so a flow field computed on the CPU matches the + one a shader draws. +- Determinism caution: keep transcendentals (`@sin`, `@log` in `normal`) + out of paths that must replay *across* hosts. On one host they replay + exactly; native libm and wasm's builtins may differ in the last bit. + +Cost: none on hosts. Invariants: none touched; this is what the invariants +want. + +### P5. Blend modes: `Command.blend` for 2D and a larger `gpu.Blend` (abi + host) + +```zig +/// Until the next `blend` or the end of the frame. Starts as `.alpha`. +blend: enum { alpha, add, multiply }, +``` + +| mode | SDL (per draw/texture) | Canvas2D `globalCompositeOperation` | +| --- | --- | --- | +| alpha | `SDL_BLENDMODE_BLEND` | `source-over` | +| add | `SDL_BLENDMODE_ADD` (`srcRGB*srcA + dst`) | `lighter` (same formula) | +| multiply | `SDL_BLENDMODE_MUL` (`src*dst + dst*(1-srcA)`) | `multiply` (same, on an opaque backdrop) | + +Those three match exactly. `screen` and `subtract` do not match on +SDL_Renderer without custom modes, and Canvas2D's `copy` clears outside the +shape, so leave all three out of 2D. It is a state command like `clip`. The +Pen tracks the current mode and emits one only on a change. + +For GPU passes, extend `gpu.Blend` (`SB/src/abi.zig:314-320`) with LÖVE's +premultiplied table (`renderstate.cpp:31-58`): `subtract`, `multiply`, +`screen`, `lighten`(max), `darken`(min). Both SDL_GPU (`gpu.zig:562-571`) +and WebGPU (`host.js:195-199`) take any factor or op, so this only adds +table rows. + +Cost: trivial on both hosts. Invariants: none. + +### P6. Offscreen 2D: `Command.target` + `Host.newTarget` + `Input.jumped` (abi + host) + +LÖVE's Canvas and raylib's RenderTexture: draw 2D commands into an image, +then show it with `image`. + +```zig +/// 2D commands that follow draw into `image` (made by `Host.newTarget`), or +/// the screen for `.none`. `clear` and `clip` apply to the target. +target: Image, +// Host: newTarget(w, h) Image +// Input: jumped: bool // State was replaced, not stepped (seek, snapshot load, `set`, replay start, migration) +``` + +- Native: `SDL_CreateTexture(..., SDL_TEXTUREACCESS_TARGET, ...)` and + `SDL_SetRenderTarget`. `clear` then clears the target. Logical + presentation applies only to the window. +- Web: `newImage` already makes an offscreen canvas with its own context + (`host.js:427-431`). `target` swaps the module's `ctx` and resets the fit + transform. Cheap. +- Do not let a 2D target also be a GPU-pass image: on the web those are + WebGPU textures behind a "shown" canvas (`host.js:159-188`). It is a + separate constructor for that reason. +- **The invariant**: a target's pixels are a *Session cache derived from + State*, never truth. After a seek they are stale, so add `Input.jumped`, + and `draw` rebuilds: `if (in.jumped or ss.drawn > s.steps) redrawAll()`. + This turns noc's `random_walk` from re-uploading 640×360×4 bytes of + `pixels` every frame (`random_walk.zig`, `draw`) into drawing only the new + dots into a target. The bitset in State stays the truth, so seeks still + show the right trail. + +Cost: cheap on both hosts. Invariants: Session (a new handle kind); replay +coverage (handled by `jumped`). + +### P7. Rotated and scaled images: `image.xf`, and fix web tint (abi + host) + +```zig +image: struct { image: Image, dst: Rect, src: Rect = .{}, tint: Color = .white, + /// Maps the unit square (0,0)-(1,1) onto the canvas; null: `dst`. + xf: ?[6]f32 = null }, +``` + +Native: `SDL_RenderTextureAffine(origin, right, down)` (`SDL_render.h:2337`), +three points straight from the affine. Web: `save(); transform(a,b,c,d,e,f); +drawImage(src, 0,0,1,1); restore()`. The Pen fills in `xf` only when its +transform is not a translate-plus-scale. This covers LÖVE's +`draw(img, x, y, r, sx, sy, ox, oy)` without textured triangles. While in +there: the web drops the tint's RGB (`web.zig:30`). Either implement it (a +cached tinted copy per (image, tint)) or document alpha-only. Silent +divergence is the worst option. + +Cost: one call each. Invariants: host parity (fixes one). + +### P8. Textures in GPU passes: `Shader.samplers`, `Draw.textures` (abi + host) + +This is the biggest gap against LÖVE's canvas-plus-shader workflow +(`effect(color, tex, uv, px)`, `Shader.cpp:310-313`) and raylib's +postprocessing example. Today a GPU pass cannot sample anything +(`num_samplers = 0`, `SB/src/host/gpu.zig:525`), so there is no +post-processing, no sprite atlas on the GPU, and no ping-pong. + +```zig +pub const Shader = struct { code: []const u8, uniform_buffers: u32 = 0, storage_buffers: u32 = 0, + samplers: u32 = 0 }; // fragment: set 2 after storage, SDL_GPU convention +pub const Sampler = enum { nearest, linear, nearest_repeat, linear_repeat }; +pub const Draw = struct { ..., textures: []const struct { image: Image, sampler: Sampler = .linear } = &.{} }; +``` + +Native: images that are GPU-pass targets already have an `SDL_GPUTexture`. +Loaded PNGs come from the GPU renderer, so their GPU texture is a property +of the SDL_Texture (`SDL_PROP_TEXTURE_GPU_TEXTURE_POINTER`). Bind with +`SDL_BindGPUFragmentSamplers` and a small sampler cache. Web: pass images are +`GPUTexture`s already; `<img>`/canvas images get +`copyExternalImageToTexture` once, cached per image, again after `pixels`. +Sampling the image a pass renders into is an error on both hosts. + +Pair it with a shipped include, `sketchbook/effect.glsl`: a full-screen +triangle vertex shader and a std140 `Frame { vec2 resolution; vec2 mouse; +float time; }` block, written out from a Zig struct like the other layouts. +That gives raylib's hot-reload example's three uniforms +(`shaders_hot_reloading.c:50-52`) and LÖVE's `effect` convention with no +string lookups. + +Cost: moderate host work (sampler cache, texture lookup); runtime cost is +one bind per draw. Invariants: GPU-as-data kept, since an `Image` handle is +data. + +### P9. Instanced draws: `Draw.instances` (abi + host) + +```zig +pub const Draw = struct { ..., instances: u32 = 1 }; +``` + +Native `SDL_DrawGPUPrimitives(rp, count, instances, 0, 0)` (now hard-coded +1 at `gpu.zig:256`); web `pass.draw(count, instances)` (`host.js:258`). +With `vertex_storage` holding per-particle data from State (uploaded) or +from a compute pass, `gl_InstanceIndex` draws 50k SDF circles in one draw. +This is the data-form answer to `SpriteBatch`/`ParticleSystem`: no retained +batch object, just a buffer and a count. The lib can ship +`sk.gpu.circles(f, image, buffer, count)` built on it. + +Cost: one-line change per host. Invariants: none. + +### P10. Plain-data helpers that noc had to write (lib) + +- `sk.Bounded(T, capacity)`: a fixed-capacity list for State (noc's + `helpers_b.List`). Pointer-free, migrates as `items` + `len`. Since + `std.BoundedArray` was removed, every sketch writes this. +- `sk.v2` over `@Vector(2, f32)`: `len`, `dist`, `norm`, `setLen`, `limit`, + `heading`, `fromAngle`, `rotate`, `perp`, `lerp`. raymath's functions + (`raymath.h:447-470`) return by value, which suits Zig; skip the + `Vector2` struct and use the SIMD vector, which `shape.zig` already + duck-types. +- `sk.Camera` gains `rotation` and `affine() Affine`, so `pen.through(cam)` is + the whole of raylib's `BeginMode2D` (`rcore.c:925, 1473-1497`) with no + global matrix and no flush. Keep `x, y, zoom` field names so saved + cameras migrate. +- `sk.map(v, a0, a1, b0, b1)`, `sk.hsv(h, s, v)` for color. + +Cost: none. Invariants: none. + +### Smaller notes + +- **Batch at the source, not in the hosts.** The command list is already + LÖVE's batch. The only batching worth having is native coalescing of + consecutive `shape`s of one color and blend, plus one GPU submit per + frame (README "Known limits"). Don't add a sketch-side "current batch". +- **Shader live reload**: already have it (build, then hot reload, then the + content-hash pipeline cache) with state intact, which raylib's example + (`shaders_hot_reloading.c:79-94`) cannot do. Make the shader build fast + instead (shader-only rebuild under `--watch`). Do not add a runtime GLSL + compiler to the host: the web would also need naga at run time. +- **`love.graphics.points`/1-px lines**: route through `shape` (1-px quads). + `gpu` `line_list` stays for GPU passes only. WebGPU lines are always 1 + device pixel wide. + +--- + +## 3. What not to copy + +| Don't copy | Where | Why, for sketchbook | +| --- | --- | --- | +| Setters on hidden render state: `setColor`, `setLineWidth`, `setBlendMode`, `setCanvas`, `setShader`, `BeginMode2D/BlendMode/TextureMode/ShaderMode` | `Graphics.cpp:1619`, `rcore.c:925-1079` | Global mutable state, so every helper has to save and restore it. Begin/End pairs leak on an early return. The Pen value (P1) does the same job with scoping and no stack. | +| A matrix stack with push/pop | `Graphics.cpp:2795-2858`, `rlgl.h:1207-1238` (32 deep, overflow is a log message) | Unbalanced pops, a depth limit. A copied `Affine` cannot get out of balance. | +| A transform command sent to the hosts | (rlgl's modelview is per-batch state) | Both references transform on the CPU anyway (`Graphics.cpp:2742`, `rlgl.h:1502`). Sending matrices would make Canvas2D and SDL disagree on stroke widths and text, and would make every host command transform-aware. | +| Host-side `circle`/`polyline`/`arc` commands | `rshapes.c` whole | Two tessellators (native) or native paths (web) that differ in joins, AA and segment counts. Tessellation in the reloadable library is fixed once and reloads live. | +| GL lines for thin lines | `DrawLineV` `rshapes.c:205`, `DrawLineStrip` | Width and AA depend on the driver; WebGPU is fixed at 1 px. Use quads. | +| Fan fill for arbitrary polygons | `Graphics.cpp:2710`, `DrawTriangleFan` | Wrong for concave input. Ear-clip, or use `vector`. | +| Miter joins without a limit | `Polyline.cpp:212-216`, `rshapes.c:3735+` | Spikes on sharp angles. `vector` already has `miter_limit`. | +| Strokes built from overlapping pieces then drawn as triangles | (`vector.Polygons.stroke` is right for stencil, wrong for P2) | Native alpha would double where pieces overlap; the web would not. Strip tessellation instead. | +| Global RNG / `love.math.random` / `GetRandomValue` | `rprand.h:152`, `rcore.c:1711` | Hidden state outside State is not snapshotted, so replays diverge. | +| Serializing RNG state without all of it | `RandomGenerator.cpp:116-145` | The cached Box-Muller value is lost, so a restore changes the stream. All RNG state must be State fields. | +| String-keyed uniforms (`send`, `GetShaderLocation`) | `Shader.cpp:794`, `rcore.c:1346` | Runtime lookups and silent misses. A Zig struct with `assertStd140` at comptime is strictly better. | +| Runtime shader loading from files | `LoadShader` `rcore.c:1217`; hot-reload example | Needs glslc/naga in the host. The build plus hot reload does it already. | +| Retained GPU objects (`SpriteBatch`, `Mesh`, `ParticleSystem`) | `SpriteBatch.cpp:88-121`, `Mesh.cpp:48` | Mutable objects with dirty ranges. Their data form (vertices in session memory, `upload`, `instances`) already fits; particles live in State as arrays. | +| Callbacks for input | `callbacks.lua:30-32` | Order-dependent side effects. The event list is the same information as data, and replays. | +| Previous/current key arrays | `rcore.c:332, 3882-3888` | Misses a press and release that fall in one frame. Scan events. | +| Variable dt into the simulation | `callbacks.lua:190-193`, `rcore.c:1634` | Replays fine, but behavior depends on the machine's frame rate. Use `Clock` (P3). | +| Depth-sorting hack, `RL_QUADS` alignment padding | `rlgl.h:1490`, `:1452-1480` | GL 1.1 baggage. The command list is already in painter's order. | +| White-pixel shapes texture | `rshapes.c:93` | Exists to keep shapes and sprites in one textured batch. With `shape` as its own command (and GPU passes for heavy cases) it buys nothing. | +| Canvas contents as truth | LÖVE "draw once, never clear" idiom | Pixels are not State, so seeks would lie. Targets are Session caches rebuilt on `in.jumped` (P6). | |
