summaryrefslogtreecommitdiff
path: root/examples/noc/notes/impl-draw-layer.md
blob: 7505d496ebf64fc41c78b0dee55c94a99b718956 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# Iteration 1, drawing half: as shipped (draw-layer)

This is design.md sections B, C and D8/D10, built in `lib/sketchbook`.
It is a new layer on top of the existing one. `abi.Command`, `f.emit`,
GPU passes and the existing Frame methods are unchanged. The only new
host primitive is `Command.shape`. Everything else is sketch-library
code with no state of its own.

## API

```zig
// ---- L0: abi ----
Command.shape: struct { color: Color, points: []const [2]f32, ends: []const u32, indices: []const u32 }
pub fn Color.gray(v: u8) Color                                  // `.fill = .gray(127)`

// ---- sk.math (src/math/: one module; `vector.geom` is the same module) ----
pub const Vec = @Vector(2, f32);
vec, dot, cross, length, splat, mix, perp, normalize           // as before, from vector/geom.zig
pub fn scale(a: Vec, k: f32) Vec
pub fn distance(a: Vec, b: Vec) f32
pub fn withLength(a: Vec, len: f32) Vec                         // setMag; zero stays zero
pub fn clampLength(a: Vec, max: f32) Vec                        // limit
pub fn angle(a: Vec) f32                                        // heading
pub fn unit(radians: f32) Vec                                   // fromAngle
pub const Affine = struct { a, b, c, d, e, f: f32, identity, translate, scale, rotate, skew, mul, apply,
    applyVector, determinant, scaleFactor, invert,
    pub fn place(at: Vec, radians: f32) Affine,                 // translate · rotate
    pub fn maxScale(m: Affine) f32 };                           // for segment counts
Rect, Bounds, Cubic, line, quad, eval, split, flattenCount, roughLength, arc   // vector's, unchanged
pub fn noise(seed: u32, x: f32, y: f32, z: f32) f32             // 0..1, 4 octaves, falloff 0.5, no table

// ---- sk.draw L1 (src/sketch/draw.zig) ----
pub const tolerance: f32 = 0.25;     // canvas px a flattened circle may stray, after the transform
pub const miter_limit: f32 = 4;      // half-widths; bevel beyond
pub const Error = std.mem.Allocator.Error;
pub const Tessellation = struct {
    points: std.ArrayList([2]f32) = .empty,
    ends: std.ArrayList(u32) = .empty,
    indices: std.ArrayList(u32) = .empty,
    pub const empty: Tessellation;
    pub fn deinit(t: *Tessellation, gpa: Allocator) void;
    pub fn clearRetainingCapacity(t: *Tessellation) void;
    pub fn triangles(t: *const Tessellation, gpa: Allocator) Error![][2]f32;   // flat, for a GPU pass
    // the append API the shapes are made of
    pub fn appendPoint(t: *Tessellation, gpa: Allocator, p: Vec) Error!u32;
    pub fn endSubpath(t: *Tessellation, gpa: Allocator) Error!void;
    pub fn appendTriangle(t: *Tessellation, gpa: Allocator, a: u32, b: u32, c: u32) Error!void; // auto-wound, zero-area dropped
    // shapes
    pub fn fillCircle(t, gpa, center: Vec, radius: f32, xf: Affine) Error!void;
    pub fn strokeCircle(t, gpa, center: Vec, radius: f32, width: f32, xf: Affine) Error!void;
    pub fn fillPolygon(t, gpa, points: []const Vec, xf: Affine) Error!void;            // simple; concave ok
    pub fn strokePolygon(t, gpa, points: []const Vec, width: f32, xf: Affine) Error!void;
    pub fn strokePolyline(t, gpa, points: []const Vec, width: f32, xf: Affine) Error!void; // butt ends
    pub fn strokeLine(t, gpa, a: Vec, b: Vec, width: f32, xf: Affine) Error!void;      // round ends
};
pub fn circleSegments(radius: f32, xf: Affine) u32;
pub fn Frame.shape(f: *Frame, t: *const draw.Tessellation, color: Color) void;          // on sk.Frame

// ---- sk.draw L2 ----
pub const Pen = struct {
    fill: ?Color = null, stroke: ?Color = null, width: f32 = 1, xf: Affine = .identity,
    pub fn transformed(p: Pen, m: Affine) Pen;                  // xf = p.xf · m (push)
};
pub fn circle(f: *Frame, center: Vec, radius: f32, pen: Pen) void;   // fill, then stroke on the edge
pub fn line(f: *Frame, a: Vec, b: Vec, pen: Pen) void;               // stroke colour, round ends
pub fn polygon(f: *Frame, points: []const Vec, pen: Pen) void;       // fill, then stroke

// ---- root ----
pub const Clock = struct {
    hz: f32 = 60, owed: f64 = 0, count: u64 = 0,
    pub const max_steps = 8;
    pub fn steps(c: *Clock, in: *const Input) u32;              // sums `tick` events
    pub fn tick(c: *Clock, dt: f32) u32;                        // per-event form
};
pub fn List(comptime T: type, comptime capacity: u32) type;     // buffer, len; capacity, slice,
    // constSlice, count, appendBounded (error.OutOfMemory), orderedRemove, swapRemove, clear
```

Build (`lib/sketchbook/build.zig`):

```zig
sketchbook.Options.script_optimize: ?OptimizeMode = null        // e2e/script executables; null = optimize
Sketchbook.addZigShaders(sb, .{ .sources, .imports }) Shaders   // moved from sketches/shaders
Sketchbook.ShaderOptions, Sketchbook.ZigShaderOptions           // named option types (recipes)
App.addScriptExecutable(app) *Compile                           // at script_optimize; addSteps' e2e uses it
App.addReloadCheck(app, .{ .script, .edits: []const Edit }) ReloadCheck   // Edit = { file, old, new }
// steps: `zig build test` (now also noise on wasm32 via node, shapes natively, examples),
//        `zig build test-web` (shapes in headless Chrome + 5000-circle timing)
```

Files: `src/math/{root,noise}.zig` (vector/geom.zig moved here),
`src/sketch/{draw,clock,list}.zig`, `src/host/gfx.zig` (shape), and
`src/host/gpu.zig` (MSAA load). Also `src/sketch/web.zig` and
`web/host.js` (shape, tint, a `sketch.frame(ms)` test hook), and
`tools/{spirv_strip.zig,reload_edit.zig,wasi_run.mjs,shapes_web.mjs}`.
The examples are `examples/pen.zig` (L2) and `examples/flock.zig`
(L1/L0 mixed with `f.fill`/`f.print`).

## Decisions

- **Native `shape`** is one `SDL_RenderGeometryRaw` call. It takes the
  points as they are, a single `SDL_FColor` with stride 0, and u32
  indices, so it allocates nothing and copies nothing. `gfx.draw` keeps
  its signature and Host.zig did not change for it. Clip and draw order
  come from the renderer, as for `rect`. The perf agent's notes had not
  appeared, so this follows the brief (SDL_RenderGeometry first).
- **Native shapes are aliased.** There is no AA fringe, because a fringe
  halves 1 px lines on the web (E7). Accepting this or adding host-side
  MSAA is still open question 1 for the owner.
- **Web fill: one path per shape, not one per command.** The web fills
  each positively wound subpath together with the negatively wound ones
  that follow it (its holes) as one nonzero path. Measured in headless
  Chrome, software Canvas2D: 5000 9-gons in one path take 200 ms, as 5000
  paths 9 ms, as 50 paths of 100 subpaths 17 ms. Skia degrades
  superlinearly with subpaths per path. So batching on the web meant one
  fill per shape anyway, and the side effect is better parity: native
  blends overlapping triangles of different shapes twice, and now so does
  the web. The only parity exception left is a stroke that overlaps
  itself.
- **Winding contract.** Each L1 call ends with `finish`: the subpath
  enclosing the most area is made positive (shoelace > 0, clockwise on a
  y-down screen), and if it was not, every subpath of that shape is
  reversed and the indices are remapped. This handles mirroring
  transforms and counterclockwise input. `appendTriangle` winds each
  triangle positively and drops zero-area ones. Holes (the inside of a
  ring, the inner loop of a polygon outline) are negative subpaths that
  follow their outline.
- **Concave fill is in.** Ear clipping is O(n²) on a scratch index array,
  with an O(n) convexity check first that falls back to a fan. That is
  cheap at sketch sizes (5000 circles still go through the fan). For a
  self-crossing polygon it falls back to clipping the rest without the
  ear test, so the native and web results may differ (documented).
- **Strokes.** Each segment is a body quad. At a joint, the inner corners
  meet at the inner miter point, and both bodies are cut back to it
  ("clean") when that point is within half of each neighbouring segment
  (the whole segment at an open end). The gap is then the triangle (inner
  point, outer corner a, outer corner b), plus a miter-tip triangle up to
  4 half-widths, beyond which it is bevelled. Everything is disjoint, and
  the outline the web fills follows exactly these corners. When the inner
  point does not fit (short segments at an acute turn), the bodies are
  not cut. The outline then goes through the vertex on the inner side,
  as Skia's inner join does, so the web has no hole, but native overlaps
  there. This is the documented exception, tested with `.disjoint =
  false`: no holes, and the triangles and outline cover the same region.
  `strokePolyline` is not in critic-zig's list. It is the internal
  stroke with butt ends, exposed because the zig-zag case needs an open
  line, and it costs nothing.
- **Segment count** is ceil(π / acos(1 − 0.25 / R)), clamped to 8..1024,
  where R = radius × `Affine.maxScale` (the longer axis, not the mean,
  so non-uniform scales stay round).
- **Clock caps per tick, not per call.** Each tick owes at most 8 steps
  and drops the rest of its debt. With the cap per tick, N updates of one
  tick each equal one update of N ticks exactly, which is the property
  critic-core asked for. Per update it is still at most 8, since the host
  now feeds one tick per update. `tick(dt)` is the per-event form
  (porter-b's request).
- **List.** Every accessor clamps `len` to the capacity (agreed with
  core-host, who keeps `len` as is in migration). The default buffer is
  `@splat` of the element's default: `.{}` for structs whose fields all
  have defaults, zero for numbers and vectors, the first tag for enums,
  null for optionals, otherwise `undefined`. It never uses
  `std.mem.zeroes` (E9). Std names: `appendBounded` returns
  `error.OutOfMemory`.
- **Noise** is improved Perlin with the permutation table replaced by a
  lowbias32-style hash of (seed, x, y, z), and four octaves of falloff
  0.5 mapped to 0.5 ± 0.5·sum/0.9375. Coordinates are clamped to ±1e9,
  and NaN clamps too. Its golden bits are equal natively (Debug and
  ReleaseFast) and on wasm32-wasi in ReleaseSafe, as the web builds it.
  Only noise runs on wasm, because LLVM 21 cannot compile one of the
  Bézier tests (`arc`'s vector constants) for wasm32 in release modes
  ("Cannot select ConstantPool"). That is a compiler bug, not ours, and
  the web builds of vecanim, which call `arc`, are unaffected.
- **`Frame.shape`.** The method's name collides with the `sk.shape`
  module (the duck-typed helpers). Inside root.zig the module is now
  called `shapes`, and `sk.shape` stays public as before.
- **Web tint** goes through a per-image scratch canvas: a copy of the
  image, `multiply` with the tint colour, then `destination-in` with the
  image, drawn with the tint's alpha. It is not cached by tint. It equals
  SDL's colour mod for opaque pixels. For semi-transparent pixels canvas
  gives (1−α)·tint + α·src·tint, where SDL gives src·tint, so they differ
  slightly at soft edges.
- **MSAA load.** `clear = null` now loads natively as on the web. Every
  multisampled pass stores as well as resolves (`RESOLVE_AND_STORE`),
  because a later pass may load. The first pass into a new attachment
  (resolved or multisampled) clears to zero instead, since Vulkan starts
  undefined and WebGPU zeroed.
- **`script_optimize`.** The `host` module no longer has an optimize mode
  of its own, so it builds in its executable's mode. A script executable
  in ReleaseSafe recompiles only Zig code; SDL and the C pieces keep
  `optimize`. The default is `optimize`, so nothing changes until an app
  sets it. The game, noc and vecanim do not set it. Wiring a `b.option`
  is one line in their build.zig.
- **`addZigShaders`** is the prototype moved over unchanged, except that
  naga is found through sketchbook's lookup (PATH or cargo's directory)
  and its doc comment keeps the reasons for each step. The shaders sketch
  calls `sb.addZigShaders`.
- **`addReloadCheck`.** At configure time it walks the app's module
  graph: module roots, plus every shader set's sources and imports, which
  `addShaders`/`addZigShaders` now record as recipes in `Shared`. For
  each edited file it copies the outermost source directory holding it.
  The copy is a WriteFiles copy, so its path is content-hashed and the
  Run cache sees changes; `tools/reload_edit.zig` then applies the edits
  and fails unless `old` occurs exactly once. The graph is then rebuilt:
  a module whose root (or any import) moved into a copy is cloned, and a
  shader set with any source in a copy is made again from it. Unchanged
  modules are shared, so the `sketch` module is never duplicated. An
  edited file that no source directory holds fails at configure time. A
  generated path's display name is "generated", so shader names now come
  from `fileName()`, which takes the sub path.
- **Screenshot compare** is core-host's script commands
  (`expect-different-screenshot A B [x y w h]`, `expect-same-screenshot`,
  `expect-pixel`), not a separate build step.

## Tests

- `zig build test` in lib/sketchbook (all pass):
  - draw.zig: circles, rings, a mirrored ring, convex, concave, reversed
    and star polygons under three transforms each (identity, place,
    mirror), polygon outlines, lines, a dot, a 1 px line, the acute
    zig-zag at widths 2, 12 and 30 (and mirrored), straight runs with
    repeated points, a square outline, and empty input. Each shape is
    checked for indices in range, every triangle positive, no two
    triangles overlapping (on a 160×160 sample grid), triangles in the
    region exactly where the subpaths' winding is nonzero, and triangle
    area equal to subpath area. Fallback joins are checked for coverage
    only.
  - clock.zig: 600 random ticks plus a 2 s stall, fed one per call and
    all at once, give equal step counts and equal bytes, the stall is
    capped at 8, and `hz = 0` gives no steps.
  - list.zig: append, ordered and swap removal, full; a `len` of 10 in a
    capacity-4 list clamps; defaults for an enum without a 0 tag, f32,
    `@Vector`, and a struct without defaults.
  - math: the vector helpers, `place`, noise smoothness and range, and
    goldens. noise.zig also runs on wasm32-wasi ReleaseSafe under Node.
  - `test/shapes.zig` + `test/shapes.script`, natively headless: two
    translucent circles (127 alone, 63 in the overlap), the concave
    arrow, the zig-zag's joins, the ring and its hole, and the 1 px line
    (0 on its row, 255 on either side), checked with `expect-pixel`;
    then 5000 circles separate and batched.
  - `examples/pen.zig` and `examples/flock.zig` compile as libraries.
- `zig build test-web` in lib/sketchbook (passes) draws the same frame in
  headless Chrome. Of the pixels away from edges in either picture
  (150085 compared, 9915 next to edges), 0 differ by more than 3. The
  sampled points match exactly, and the 1 px line is 0,0,0 on its row on
  the web too. The median frame for 5000 circles, raster included, is
  about 12 ms as 5000 shapes and 8 ms batched, against a 16 ms assertion
  (`SHAPES_BUDGET_MS` overrides it). It is not part of `zig build test`,
  because it needs Chrome and is timing-sensitive under a parallel build.
- Reload checks, in `e2e`:
  - `sketches/shaders/test/reload.script`: edits to the Zig shader
    (expo's plot colour), the GLSL shader (the same) and the sketch's Zig
    code (label colour). State checks before and after `load {v2}`, and
    three `expect-different-screenshot` rects. Looked at: the plot is
    green before and red after, and the label orange before and blue
    after.
  - `sketches/noc/test/bouncing_ball_reload.script`: record, play, pause,
    screenshot, `load {v2}` (a darker ball), screenshot. The ball is in
    the same place and darker, `bounces` is kept, and play goes on.
  - The file-watcher path, checked once by hand on sketches/shaders
    (scratch script, not committed): the host ran headless with
    `await-reload 60`, a Zig shader edit was rebuilt with `zig build lib`,
    and the host reloaded it. The screenshots showed a green plot before
    and blue after. The edit was reverted and the library rebuilt.
- Still passing: the game `zig build test e2e -j1`, noc `e2e -j1`,
  shaders `e2e -j1`, vecanim `e2e -j1` and `web`. Default parallel e2e
  runs still sometimes fail with the known `LeakedSdlMemory` under many
  Vulkan devices (board, porter-a). This change neither causes nor fixes
  that.

## Deferred

- Native antialiasing for `shape` (open question 1): an MSAA SDL_GPU
  pipeline on the host, with no API change.
- Arcs, ellipses, rounded rects, round joins, cap options for polylines,
  dashes, and a `Path` builder. Not needed by any port.
- `Pen` variants (`polyline` in L2), image affines, blend modes.
- A self-overlapping stroke on native (it double-blends): fixing it needs
  a polygon union in the tessellator.
- Making `test-web` part of `test`. It needs Chrome, and its timing
  assertion is unreliable under a parallel build.
- Rewriting the noc ports onto the new layer is phase E. The examples
  show the shape: pen.zig is accel_to_mouse plus angular_forces, and
  flock.zig is critic-zig's flocking rewrite.