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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
|
//! Types shared by a host and the sketches it loads.
//!
//! Host and sketch are built by the same `zig build`, with the same compiler
//! and standard library, so ordinary Zig types cross the boundary: slices,
//! tagged unions, `std.mem.Allocator`. Two rules keep reloads safe:
//! - whatever outlives a call lives in host memory (host code is never
//! unloaded, so host allocators and function pointers stay valid);
//! - `hash` covers the layout of every type here, and a host refuses a sketch
//! built against different definitions instead of misreading its memory.
//!
//! Only `Event` and the reflected `Layout` are `extern`: they are written to disk.
const std = @import("std");
pub const layout = @import("layout.zig");
pub const Key = @import("keys.zig").Key;
/// Bytes read back from a GPU buffer (see `Command.download`).
pub const Download = struct { key: u32, bytes: []const u8 };
pub const Rect = extern struct {
x: f32 = 0,
y: f32 = 0,
w: f32 = 0,
h: f32 = 0,
pub fn contains(r: Rect, x: f32, y: f32) bool {
return x >= r.x and y >= r.y and x < r.x + r.w and y < r.y + r.h;
}
pub fn inset(r: Rect, d: f32) Rect {
return .{ .x = r.x + d, .y = r.y + d, .w = r.w - 2 * d, .h = r.h - 2 * d };
}
};
pub const Color = extern struct {
r: u8,
g: u8,
b: u8,
a: u8 = 0xff,
pub const white: Color = .{ .r = 255, .g = 255, .b = 255 };
pub const black: Color = .{ .r = 0, .g = 0, .b = 0 };
/// `v` in all three channels, opaque: `.gray(127)`.
pub fn gray(v: u8) Color {
return .{ .r = v, .g = v, .b = v };
}
pub fn hex(rgb: u24) Color {
return .{ .r = @truncate(rgb >> 16), .g = @truncate(rgb >> 8), .b = @truncate(rgb) };
}
pub fn alpha(c: Color, a: u8) Color {
return .{ .r = c.r, .g = c.g, .b = c.b, .a = a };
}
/// `c` with alpha `a` in 0..1, saturating: below 0 (a spent
/// lifespan) is transparent, above 1 opaque, NaN transparent.
pub fn alphaFloat(c: Color, a: f32) Color {
const clamped: f32 = if (a > 0) @min(a, 1) else 0;
return c.alpha(@intFromFloat(@round(clamped * 255)));
}
};
/// How 2D drawing combines with what is already there (`Command.blend`).
/// Both are fixed-function on both hosts and match: `alpha` is source
/// over (canvas `source-over`, SDL `BLEND`), `add` adds the colour times
/// its alpha, and the alphas (canvas `lighter`; natively a custom SDL
/// blend mode, since SDL's `ADD` would keep the destination's alpha in a
/// transparent target).
pub const BlendMode = enum(u8) { alpha, add };
/// Where an image's corners land (`Command.image.corners`): any affine
/// placement, rotated, sheared or mirrored. The fourth corner follows.
pub const Corners = struct {
top_left: [2]f32,
top_right: [2]f32,
bottom_left: [2]f32,
};
/// One input event. Recordings are arrays of these on disk, so the layout is
/// frozen: 24 bytes, no padding, no pointers.
pub const Event = extern struct {
/// Nanoseconds. Live: host clock. Replay: time since the recording began.
time: u64 = 0,
/// Canvas coordinates for pointer events; `tick` stores dt seconds in `x`.
x: f32 = 0,
y: f32 = 0,
kind: Kind,
flags: u8 = 0,
/// Mouse button (1 left, 2 middle, 3 right) or USB HID scancode.
code: u16 = 0,
/// Unicode codepoint for `text`, key modifiers, or `@bitCast` wheel delta.
value: u32 = 0,
pub const Kind = enum(u8) {
/// Once per frame, after that frame's other events.
tick,
mouse_move,
mouse_down,
mouse_up,
wheel,
key_down,
key_up,
text,
/// Focus loss, or the console took the pointer: drop armed gestures.
cancel,
/// Horizontal wheel delta; appended to preserve recorded event values.
wheel_horizontal,
_,
};
/// `flags` bit for a held key's auto-repeat.
pub const repeat: u8 = 1;
/// For mouse and wheel events: the modifier keys held as it happened,
/// as `Key.Mod` bits. Read this rather than `Input.held`, which is the
/// state after the frame's events, and misses modifiers that come with
/// no key events at all (a trackpad's pinch is ctrl+wheel).
pub fn modifiers(e: Event) u32 {
return e.flags >> 4;
}
/// `flags` for an event with `mods` (`Key.Mod` bits) held.
pub fn withModifiers(mods: u32) u8 {
return @intCast((mods & 0xf) << 4);
}
pub fn wheel(e: Event) f32 {
return @bitCast(e.value);
}
/// A frame's tick, `dt` nanoseconds after the previous one.
pub fn tick(time: u64, dt: u64) Event {
return .{ .kind = .tick, .time = time, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) };
}
/// A tick's `dt` in nanoseconds, from the seconds it records: what
/// `Input.dt` is, live and replayed alike (nanoseconds do not survive
/// the trip through f32, so live time must come through it too).
pub fn tickDt(e: Event) u64 {
return @intFromFloat(@round(@max(0, @as(f64, e.x)) * std.time.ns_per_s));
}
comptime {
std.debug.assert(@sizeOf(Event) == 24);
}
};
pub const Mode = enum { live, recording, playing, paused };
/// Mouse buttons by `Event.code`.
pub const MouseButton = enum(u16) { left = 1, middle = 2, right = 3, _ };
/// A host audio stream, as last observed by the host.
pub const Stream = struct {
key: u32,
/// Samples waiting to be played.
queued: u32 = 0,
/// Samples pushed since the stream was last cleared.
pushed: u64 = 0,
};
/// Everything a sketch learns about the world for one call.
pub const Input = struct {
/// In `update`, the frame's tick time (`Event.time`: since the
/// recording began while recording or replaying); in `draw`, the host
/// clock, or the playback position.
now: u64 = 0,
/// In `update`, the frame's tick `dt` (`Event.tickDt`), the same live
/// and replayed; in `draw`, likewise for the frame just updated.
dt: u64 = 0,
frame: u64 = 0,
events: []const Event = &.{},
mode: Mode = .live,
/// First frame after new code, or a new layout, was loaded.
reloaded: bool = false,
/// In `draw`: State did not come here by `update` from what the last
/// `draw` saw. Set on the first frame, after a seek, step, snapshot
/// load, `set`, `reset`, a recording's play or record start, a sketch
/// command, and every reload (with `reloaded`). Pictures accumulated
/// in Session (a trail in an offscreen image) are stale then: redraw
/// them from State. `update` never sees it: it is not input.
jumped: bool = false,
/// First update since the program started (never after a hot reload):
/// the place to stop what should not resume from saved state, like a
/// song that was playing when the program quit.
started: bool = false,
/// The console is open and owns the keyboard.
console: bool = false,
/// The host is exporting frames (`--export`): nobody watches or clicks,
/// so a player runs through once, without its controls, and quits.
exporting: bool = false,
/// The canvas.
width: f32 = 0,
height: f32 = 0,
/// The room the host has for the canvas, in the canvas's units at 1:1:
/// the window's size (CSS pixels on the web). A sketch that sets its
/// canvas to it fills any window, a phone's included, at its own scale.
window_width: f32 = 0,
window_height: f32 = 0,
/// Pointer, buttons and keys follow the events fed, one frame at a time.
/// Restoring a snapshot (play, seek, step, load) clears them, and a
/// recording begins with events that restore them, so a replay starts
/// from the input its recording started from.
mouse_x: f32 = 0,
mouse_y: f32 = 0,
/// Held mouse buttons, bit `button - 1`.
buttons: u32 = 0,
/// Held keys by USB HID scancode, maintained from the events fed so far.
keys: std.StaticBitSet(256) = .empty,
streams: []const Stream = &.{},
sample_rate: u32 = 48_000,
/// Mono samples at `sample_rate` recorded since the previous frame, while
/// `draw` declares `Command.microphone`. Only `draw` sees them: they come
/// from a device, not from events, so they do not replay.
microphone: []const f32 = &.{},
/// Finished `Command.download`s, oldest first. Like the microphone,
/// only `draw` sees them, and they do not replay.
downloads: []const Download = &.{},
/// `key` is any enum whose values are HID scancodes, like `sketch.Key`.
pub fn held(in: *const Input, key: anytype) bool {
return in.keys.isSet(@backingInt(key));
}
/// Went down this frame; auto-repeats excluded.
pub fn pressed(in: *const Input, key: anytype) bool {
for (in.events) |e| {
if (e.kind == .key_down and e.code == @backingInt(key) and e.flags & Event.repeat == 0) return true;
}
return false;
}
/// Held after this frame's events (`buttons` bit `button - 1`).
pub fn mouseHeld(in: *const Input, button: MouseButton) bool {
return in.buttons & (@as(u32, 1) << @intCast(@min(@backingInt(button) -| 1, 31))) != 0;
}
/// The first press of `button` this frame, with its position (`e.x`,
/// `e.y`), or null. A sketch that needs every press reads `events`.
pub fn mousePressed(in: *const Input, button: MouseButton) ?Event {
for (in.events) |e| if (e.kind == .mouse_down and e.code == @backingInt(button)) return e;
return null;
}
/// The first release of `button` this frame, or null.
pub fn mouseReleased(in: *const Input, button: MouseButton) ?Event {
for (in.events) |e| if (e.kind == .mouse_up and e.code == @backingInt(button)) return e;
return null;
}
pub fn stream(in: *const Input, key: u32) Stream {
for (in.streams) |s| if (s.key == key) return s;
return .{ .key = key };
}
/// Follows mouse, button and key state through one fed event.
pub fn track(in: *Input, e: Event) void {
switch (e.kind) {
.mouse_move, .wheel, .wheel_horizontal => {
in.mouse_x = e.x;
in.mouse_y = e.y;
},
.mouse_down, .mouse_up => {
in.mouse_x = e.x;
in.mouse_y = e.y;
const bit = @as(u32, 1) << @intCast(@min(e.code -| 1, 31));
if (e.kind == .mouse_down) in.buttons |= bit else in.buttons &= ~bit;
},
.key_down => in.keys.set(@min(e.code, 255)),
.key_up => in.keys.unset(@min(e.code, 255)),
.cancel => {
in.buttons = 0;
in.keys = .empty;
},
else => {},
}
}
pub fn seconds(in: *const Input) f64 {
return @as(f64, @floatFromInt(in.now)) / std.time.ns_per_s;
}
};
pub const Image = enum(u32) { none = 0, _ };
pub const Audio = enum(u32) { none = 0, _ };
/// GPU memory made by `Host.newBuffer`, filled by `Command.upload` or by
/// compute shaders, and read by any shader. Contents stay on the GPU.
pub const Buffer = enum(u32) { none = 0, _ };
pub const Cursor = enum { hidden, arrow, pointer };
/// Voices are reconciled, not triggered: `draw` declares every voice that
/// should sound this frame, keyed by a number of its choosing. A new key, or
/// a new serial for a key, starts the sound from its beginning; an undeclared
/// key stops. A finished one-shot stays silent while its key and serial are
/// still declared, so replaying or scrubbing state never re-fires sounds.
pub const Voice = struct {
key: u32,
audio: Audio,
serial: u32 = 0,
loop: bool = false,
volume: f32 = 1,
/// Linear fade at both ends, in samples.
fade: u32 = 0,
};
/// Slices must stay alive until the host consumes the frame, right after
/// `draw` returns. `sketch.Frame` copies the small ones (text, GPU
/// descriptions, uniforms) into scratch memory itself; bulk data (vertices,
/// samples, pixels, uploads) must already live in scratch, session or store
/// memory, or be a literal.
pub const Command = union(enum) {
clear: Color,
rect: struct { dst: Rect, color: Color },
/// Filled regions in one color, described twice over the same
/// `points` (canvas coordinates). As subpaths, `points[ends[i - 1] ..
/// ends[i]]` (from 0 for the first), which the web fills nonzero, one
/// fill per positively wound subpath (clockwise on screen) together
/// with the negatively wound ones after it, its holes. And as
/// triangles, `indices` into `points` three at a time, which native
/// draws with SDL_RenderGeometry. Each such group of subpaths and its
/// triangles must cover the same region, the triangles without
/// overlapping each other, or translucent colors blend twice natively
/// where the web blends once; separate groups that overlap blend
/// twice on both. `sketch.draw` makes shapes that keep this contract.
///
/// `colors`, when not empty, gives each subpath its own colour
/// (`colors[i]` for subpath `i`, `color` past the end), so shapes of
/// many colours go in one command: the web fills each group in its
/// first subpath's colour, native gives each point its subpath's
/// colour, so a group (an outline and its holes) and the triangles
/// between them must share one.
///
/// Antialiased on both hosts: the web's canvas does it per shape;
/// native takes 4x4 samples a pixel (a GPU renderer; without one,
/// aliased), on the canvas through a layer that a run of consecutive
/// shapes shares, in a target throughout (see `target`).
shape: struct { color: Color, points: []const [2]f32, ends: []const u32, indices: []const u32, colors: []const Color = &.{} },
/// `src` empty: the whole image. `tint` multiplies it: colour per
/// channel, alpha as a whole. `corners`, when set, places the image
/// (any affine: `sketch.Frame.imageAt` centres and turns it) and `dst`
/// is unused. Native samples nearest; the web antialiases the edges of
/// a turned image.
image: struct { image: Image, dst: Rect, src: Rect = .{}, tint: Color = .white, corners: ?Corners = null },
/// Where the 2D commands after it draw: an image made by
/// `Host.newImage` (an offscreen target, kept between frames), or
/// `.none` for the canvas. Each frame starts on the canvas. Switching
/// clears the clip. Images start transparent. Natively a target is
/// supersampled whole (4x4) and holds premultiplied colour, so it
/// shows the same picture however its commands were split across
/// frames, and draws as a canvas would.
/// A target is a Session cache, never truth: redraw it when
/// `Input.jumped`.
target: Image,
/// The blend for the 2D commands after it (`rect`, `shape`, `image`;
/// `text` and `clear` ignore it). Each frame starts with `alpha`.
blend: BlendMode,
/// Fixed 8px cells, `scale` times larger.
text: struct { x: f32, y: f32, scale: f32, color: Color, bytes: []const u8 },
clip: ?Rect,
/// Logical canvas size; the host scales the window to fit.
canvas: struct { w: u32, h: u32 },
cursor: Cursor,
voice: Voice,
/// Mono samples at `Input.sample_rate` for stream `key`.
audio: struct { key: u32, samples: []const f32, clear: bool = false },
/// RGBA8 rows of `w * 4` bytes into an image made by `Host.newImage`.
pixels: struct { image: Image, w: u32, h: u32, rgba: []const u8, premultiplied: bool = false },
/// Renders a GPU pass into an image made by `Host.newImage`, when
/// `Host.gpu` says the host can.
gpu: gpu.Pass,
/// Bytes into a buffer made by `Host.newBuffer`, at `offset`.
upload: struct { buffer: Buffer, offset: u32 = 0, bytes: []const u8 },
/// Runs a compute shader over buffers (see `abi.gpu`).
compute: gpu.Dispatch,
/// Keeps the default recording device open while declared, like a
/// voice; what it hears arrives in `Input.microphone`.
microphone,
/// Asks the user for a file. The answer arrives later as the console
/// line `<command> <path>`, so it reaches the sketch's `command` (and
/// the console log) like anything typed. `pattern` filters by extension:
/// "wav;flac;ogg", or empty for any file.
open_file: struct { command: []const u8, pattern: []const u8 = "" },
/// Copies `size` bytes of a buffer from `offset` back to the CPU. They
/// arrive in `Input.downloads` under `key` once the GPU has got there,
/// usually a frame or two later; the frame does not wait.
download: struct { buffer: Buffer, offset: u32 = 0, size: u32, key: u32 = 0 },
/// Runs a console line after this frame, as if typed: the way `draw`,
/// which cannot write State, hands it something only it learns.
run: []const u8,
quit,
};
/// GPU work described as data. A sketch declares its pipelines and draws;
/// the host builds the real objects, caches them by the hash of their
/// description (so an edited shader simply becomes a new pipeline after a
/// reload), and runs the pass. Sketches never touch a graphics API.
///
/// Shaders are SPIR-V for native hosts and WGSL for the web host; the
/// build makes both from GLSL (`addShaders` in build.zig), and a sketch
/// passes whichever its build gave it. Resources follow SDL_GPU's SPIR-V
/// convention, which the WGSL keeps: vertex uniforms in set 1, fragment
/// uniforms in set 3, binding = slot. Uniform bytes must follow std140.
pub const gpu = struct {
pub const Shader = struct {
/// SPIR-V, or WGSL on the web.
code: []const u8,
uniform_buffers: u32 = 0,
/// Read-only storage buffers: set 0 in a vertex shader, set 2 in a
/// fragment shader.
storage_buffers: u32 = 0,
};
/// A compute shader. SDL_GPU's SPIR-V sets: read-only buffers in set 0,
/// read-write buffers in set 1, uniforms in set 2.
pub const Kernel = struct {
/// SPIR-V, or WGSL on the web.
code: []const u8,
readonly_buffers: u32 = 0,
readwrite_buffers: u32 = 0,
uniform_buffers: u32 = 0,
/// The shader's `local_size`.
threads: [3]u32 = .{ 64, 1, 1 },
};
/// One run of a kernel, in a compute pass of its own: everything it
/// writes is visible to the commands after it.
pub const Dispatch = struct {
/// Names it in GPU timings (`--profile-gpu`).
label: []const u8 = "",
kernel: Kernel,
readonly: []const Buffer = &.{},
readwrite: []const Buffer = &.{},
/// Uniform slot 0, std140.
uniforms: []const u8 = &.{},
groups: [3]u32 = .{ 1, 1, 1 },
};
pub const Format = enum { float, float2, float3, float4, ubyte4_norm };
pub const Attribute = struct { location: u32, format: Format, offset: u32 };
pub const Blend = enum {
/// Overwrite.
none,
/// Source over, premultiplied colors.
premultiplied,
additive,
};
pub const Compare = enum { never, less, equal, less_or_equal, greater, not_equal, greater_or_equal, always };
pub const StencilOp = enum { keep, zero, replace, increment_and_clamp, decrement_and_clamp, invert, increment_and_wrap, decrement_and_wrap };
pub const StencilFace = struct {
compare: Compare = .always,
pass: StencilOp = .keep,
fail: StencilOp = .keep,
};
pub const Pipeline = struct {
vertex: Shader,
fragment: Shader,
/// Bytes per vertex.
stride: u32,
attributes: []const Attribute,
primitive: enum { triangle_list, triangle_strip, line_list, line_strip } = .triangle_list,
blend: Blend = .premultiplied,
write_color: bool = true,
/// Stencil test and update, per triangle facing. Needs a pass with
/// a stencil buffer.
stencil: ?struct { front: StencilFace, back: StencilFace } = null,
};
pub const Draw = struct {
/// Index into `Pass.pipelines`.
pipeline: u32,
/// Empty for a pipeline without attributes, whose vertex shader
/// makes its own vertices from `gl_VertexIndex`.
vertices: []const u8 = &.{},
vertex_count: u32,
stencil_reference: u8 = 0,
/// Uniform slot 0 of each stage.
vertex_uniforms: []const u8 = &.{},
fragment_uniforms: []const u8 = &.{},
/// Read-only storage buffers of each stage, binding = index.
vertex_storage: []const Buffer = &.{},
fragment_storage: []const Buffer = &.{},
scissor: ?Rect = null,
};
// Layouts from types: Zig knows every offset at comptime, so vertex
// formats and uniform layouts come from plain structs, never by hand.
/// Vertex attributes for `V`: one per field, locations in field order,
/// formats from the field types (`f32`, `[2..4]f32` or vectors, `[4]u8`
/// normalized).
pub fn attributes(comptime V: type) []const Attribute {
return comptime blk: {
if (@typeInfo(V).@"struct".layout != .@"extern") @compileError(@typeName(V) ++ " must be extern to be a vertex");
const s = @typeInfo(V).@"struct";
var out: [s.field_names.len]Attribute = undefined;
for (s.field_names, s.field_types, 0..) |name, F, i| out[i] = .{ .location = i, .offset = @offsetOf(V, name), .format = formatOf(F) };
const frozen = out;
break :blk &frozen;
};
}
fn formatOf(comptime T: type) Format {
if (T == f32) return .float;
if (T == [4]u8 or T == @Vector(4, u8)) return .ubyte4_norm;
const len, const child = switch (@typeInfo(T)) {
.array => |a| .{ a.len, a.child },
.vector => |v| .{ v.len, v.child },
else => @compileError("no vertex format for " ++ @typeName(T)),
};
if (child != f32) @compileError("no vertex format for " ++ @typeName(T));
return switch (len) {
2 => .float2,
3 => .float3,
4 => .float4,
else => @compileError("no vertex format for " ++ @typeName(T)),
};
}
/// A pipeline drawing vertices of type `V`: stride and attributes filled in.
pub fn pipeline(comptime V: type, p: struct {
vertex: Shader,
fragment: Shader,
primitive: @FieldType(Pipeline, "primitive") = .triangle_list,
blend: Blend = .premultiplied,
write_color: bool = true,
stencil: @FieldType(Pipeline, "stencil") = null,
}) Pipeline {
return .{
.vertex = p.vertex,
.fragment = p.fragment,
.stride = @sizeOf(V),
.attributes = attributes(V),
.primitive = p.primitive,
.blend = p.blend,
.write_color = p.write_color,
.stencil = p.stencil,
};
}
/// Fails to compile unless `U` lays out as the std140 uniform block
/// GLSL would declare for it (see `glsl.zig`).
pub const assertStd140 = @import("glsl.zig").assertStd140;
/// `value`'s bytes, checked against std140, copied into `arena` so they
/// outlive the caller until the frame is consumed.
pub fn uniform(arena: std.mem.Allocator, value: anytype) []const u8 {
comptime assertStd140(@TypeOf(value));
const copy = arena.create(@TypeOf(value)) catch return &.{};
copy.* = value;
return std.mem.asBytes(copy);
}
pub const Pass = struct {
/// Names it in GPU timings (`--profile-gpu`).
label: []const u8 = "",
/// The target; its size is the image's.
image: Image,
width: u32,
height: u32,
/// 1, 2, 4 or 8. More than one renders multisampled and resolves.
samples: u8 = 1,
stencil: bool = false,
/// Premultiplied; null keeps the image's previous contents.
clear: ?[4]f32 = .{ 0, 0, 0, 0 },
pipelines: []const Pipeline,
draws: []const Draw,
};
};
/// Host services. Handles and loaded data outlive reloads.
pub const Host = struct {
ctx: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
log: *const fn (*anyopaque, []const u8) void,
/// Cached by path. A missing file still gets a handle: it draws as a
/// placeholder, and starts working when the file appears.
loadImage: *const fn (*anyopaque, []const u8) Image,
/// PNG bytes in memory. Not cached.
decodeImage: *const fn (*anyopaque, []const u8) Image,
/// A blank image for `Command.pixels`.
newImage: *const fn (*anyopaque, u32, u32) Image,
/// Releases an image; its handle draws nothing afterwards.
freeImage: *const fn (*anyopaque, Image) void,
/// Whether `Command.gpu` and `Command.compute` run here: the host
/// has a GPU device.
gpu: *const fn (*anyopaque) bool,
/// A GPU buffer of `size` bytes, zeroed; `.none` without a GPU.
newBuffer: *const fn (*anyopaque, u32) Buffer,
freeBuffer: *const fn (*anyopaque, Buffer) void,
/// Zero while unknown.
imageSize: *const fn (*anyopaque, Image) [2]u32,
/// What `Command.text` gives the bytes at a scale: the width they
/// advance and the height of their line, in canvas units.
textSize: *const fn (*anyopaque, f32, []const u8) [2]f32,
/// `.none` if the file does not load.
loadSound: *const fn (*anyopaque, []const u8) Audio,
/// WAV, FLAC or Ogg Vorbis bytes in memory. Not cached. `.none` if
/// they do not decode.
decodeSound: *const fn (*anyopaque, []const u8) Audio,
/// A loaded sound's samples: mono, at `Input.sample_rate`, alive as
/// long as the host. Empty for `.none`.
samples: *const fn (*anyopaque, Audio) []const f32,
/// The whole file, mapped for the life of the host; empty if missing.
readFile: *const fn (*anyopaque, []const u8) []const u8,
env: *const fn (*anyopaque, []const u8) ?[]const u8,
/// A monotonic clock in nanoseconds, for measuring, not for state:
/// `update` must use `Input` time to stay replayable.
clock: *const fn (*anyopaque) u64,
};
pub fn log(h: Host, message: []const u8) void {
h.vtable.log(h.ctx, message);
}
pub fn print(h: Host, comptime fmt: []const u8, args: anytype) void {
var buf: [512]u8 = undefined;
h.log(std.mem.print(&buf, fmt, args) catch "(message too long)");
}
pub fn loadImage(h: Host, path: []const u8) Image {
return h.vtable.loadImage(h.ctx, path);
}
pub fn decodeImage(h: Host, png: []const u8) Image {
return h.vtable.decodeImage(h.ctx, png);
}
pub fn newImage(h: Host, w: u32, height: u32) Image {
return h.vtable.newImage(h.ctx, w, height);
}
pub fn freeImage(h: Host, image: Image) void {
h.vtable.freeImage(h.ctx, image);
}
pub fn gpu(h: Host) bool {
return h.vtable.gpu(h.ctx);
}
pub fn newBuffer(h: Host, size: u32) Buffer {
return h.vtable.newBuffer(h.ctx, size);
}
pub fn freeBuffer(h: Host, buffer: Buffer) void {
h.vtable.freeBuffer(h.ctx, buffer);
}
pub fn imageSize(h: Host, image: Image) [2]u32 {
return h.vtable.imageSize(h.ctx, image);
}
/// The size `f.text(x, y, scale, bytes, ...)` covers from `x, y`: width
/// and line height in canvas units, for laying text out (in `draw`:
/// `update` gets no host). Native text is shaped and hinted at the size
/// it is drawn, so a width is not a multiple of the scale: measure at
/// the scale drawn.
pub fn textSize(h: Host, scale: f32, bytes: []const u8) [2]f32 {
return h.vtable.textSize(h.ctx, scale, bytes);
}
pub fn loadSound(h: Host, path: []const u8) Audio {
return h.vtable.loadSound(h.ctx, path);
}
pub fn decodeSound(h: Host, wav: []const u8) Audio {
return h.vtable.decodeSound(h.ctx, wav);
}
pub fn samples(h: Host, audio: Audio) []const f32 {
return h.vtable.samples(h.ctx, audio);
}
pub fn readFile(h: Host, path: []const u8) []const u8 {
return h.vtable.readFile(h.ctx, path);
}
pub fn env(h: Host, name: []const u8) ?[]const u8 {
return h.vtable.env(h.ctx, name);
}
pub fn clock(h: Host) u64 {
return h.vtable.clock(h.ctx);
}
};
/// What the host passes to every call: services, input, and memory by
/// lifetime, shortest first.
pub const Context = struct {
host: Host,
input: *const Input,
/// Frame lifetime: all of it is released after the host consumes the
/// frame.
scratch: std.mem.Allocator,
/// This process: survives reloads; frees one allocation at a time, and
/// releases the rest when Session's layout changes.
session: std.mem.Allocator,
/// On disk, next to the state file: survives reloads and restarts, at
/// the same addresses, so Store may point into it.
store: std.mem.Allocator,
/// The sketch's `Session` and `Store` values.
session_root: [*]u8,
store_root: [*]u8,
/// Filled by `draw`, using `scratch`.
commands: *std.ArrayList(Command),
};
/// One leaf of a reflected layout. Nested structs are flattened into dotted
/// paths, and arrays and vectors into element leaves (`boids[].pos[]`, one
/// leaf for all elements, see `dims`). Hosts migrate state across layout changes, and
/// inspect or edit it by name, from these. Stored in the state file header.
pub const Field = extern struct {
path: [*:0]const u8,
offset: u32,
size: u32,
kind: Kind,
/// How many `[]` the path has: one per array or vector it sits in.
rank: u8 = 0,
reserved: [2]u8 = @splat(0),
/// Structural hash of the field's type: equal hashes copy byte for byte.
hash: u64,
/// Enums: "name=value" pairs separated by commas. Empty otherwise.
tags: [*:0]const u8 = "",
/// `rank` entries, outermost first: element count and byte stride of
/// each `[]` in `path`. `offset` is element 0's.
dims: [*]const Dim = &[_]Dim{},
/// `array` is a whole array or vector, kept for copying it in one piece
/// when its type is unchanged; its elements follow as leaves of their
/// own (`list[]`, `list[].x`).
pub const Kind = enum(u8) { int, uint, float, bool, @"enum", array, bytes, _ };
pub const Dim = extern struct { count: u32, stride: u32 };
};
pub const Layout = struct {
size: usize = 0,
alignment: usize = 1,
hash: u64 = 0,
fields: []const Field = &.{},
};
/// Returned by `sketch_info`. The host copies what it keeps, since a
/// sketch's read-only data disappears with the library.
pub const Info = struct {
/// The sketch's `abi.hash`: a host refuses one that differs from its own.
abi: u64,
name: []const u8,
width: u32,
height: u32,
state: Layout,
session: Layout,
store: Layout,
/// Console completions offered by the sketch.
commands: []const []const u8 = &.{},
};
/// Which memory `sketch_defaults` fills.
pub const Memory = enum(u8) { state, session, store };
/// The entry points of a sketch, exported from libraries under these names.
/// What became of a console line offered to a sketch.
pub const Outcome = enum(u8) {
/// Not one of its commands.
unknown,
done,
/// It returned an error, already printed to the console.
failed,
};
pub const Sketch = struct {
info: *const fn () callconv(.c) *const Info,
/// Declared default values, and nothing else.
defaults: *const fn (Memory, [*]u8) callconv(.c) void,
/// Setup for brand new state, after its defaults.
init: *const fn (*const Context, [*]u8) callconv(.c) void,
/// Deterministic: new state from state and input, nothing else.
update: *const fn (*const Context, [*]u8) callconv(.c) void,
/// Presentation: reads state, may change session and store, appends
/// commands.
draw: *const fn (*const Context, [*]const u8) callconv(.c) void,
/// A console line the host did not understand.
command: *const fn (*const Context, [*]u8, *const []const u8) callconv(.c) Outcome,
pub const symbols = .{
.info = "sketch_info",
.defaults = "sketch_defaults",
.init = "sketch_init",
.update = "sketch_update",
.draw = "sketch_draw",
.command = "sketch_command",
};
};
/// Layout hash of everything above. Changes whenever a shared type does.
pub const hash: u64 = blk: {
@setEvalBranchQuota(1_000_000);
var h: u64 = 0;
for (.{ Rect, Color, BlendMode, Corners, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, gpu.Dispatch, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| {
h = std.hash.Wyhash.hash(h, @typeName(T) ++ layout.signature(T));
}
break :blk h;
};
test "vertex attributes and std140 checks come from the types" {
const Vertex = extern struct { position: [2]f32, color: [4]u8, uv: [2]f32 };
const attrs = gpu.attributes(Vertex);
try std.testing.expectEqual(@as(usize, 3), attrs.len);
try std.testing.expectEqual(gpu.Format.ubyte4_norm, attrs[1].format);
try std.testing.expectEqual(@as(u32, 12), attrs[2].offset);
const Block = extern struct { color: [4]f32, size: [2]f32, pad: [2]f32, stops: [4][4]f32 };
comptime gpu.assertStd140(Block);
const p = gpu.pipeline(Vertex, .{ .vertex = .{ .code = "" }, .fragment = .{ .code = "" } });
try std.testing.expectEqual(@as(u32, 20), p.stride);
}
test {
_ = layout;
_ = @import("keys.zig");
}
|