summaryrefslogtreecommitdiff
path: root/src/abi.zig
blob: 478259999f4bfa497d94517918ddf9f288aec88b (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
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
//! 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;

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 };

    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 };
    }
};

/// 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,
        _,
    };
    /// `flags` bit for a held key's auto-repeat.
    pub const repeat: u8 = 1;

    pub fn wheel(e: Event) f32 {
        return @bitCast(e.value);
    }

    comptime {
        std.debug.assert(@sizeOf(Event) == 24);
    }
};

pub const Mode = enum { live, recording, playing, paused };

/// 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 {
    now: u64 = 0,
    /// Nanoseconds since the previous frame.
    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,
    /// 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,
    width: f32 = 0,
    height: f32 = 0,
    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) = .initEmpty(),
    streams: []const Stream = &.{},
    sample_rate: u32 = 48_000,

    /// `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(@intFromEnum(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 == @intFromEnum(key) and e.flags & Event.repeat == 0) return true;
        }
        return false;
    }
    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 => {
                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 = .initEmpty();
            },
            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, _ };
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: literals, the frame arena and session memory all qualify.
pub const Command = union(enum) {
    clear: Color,
    rect: struct { dst: Rect, color: Color },
    /// `src` empty: the whole image. `tint` multiplies it.
    image: struct { image: Image, dst: Rect, src: Rect = .{}, tint: Color = .white },
    /// 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,
    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. Resources follow SDL_GPU's SPIR-V convention:
/// 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 {
        spirv: []const u8,
        uniform_buffers: u32 = 0,
    };

    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,
        vertices: []const u8,
        vertex_count: u32,
        stencil_reference: u8 = 0,
        /// Uniform slot 0 of each stage.
        vertex_uniforms: []const u8 = &.{},
        fragment_uniforms: []const u8 = &.{},
        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 fields = @typeInfo(V).@"struct".fields;
            var out: [fields.len]Attribute = undefined;
            for (fields, 0..) |f, i| out[i] = .{ .location = i, .offset = @offsetOf(V, f.name), .format = formatOf(f.type) };
            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 {
        /// 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` runs here: the host has a GPU device.
        gpu: *const fn (*anyopaque) bool,
        /// Zero while unknown.
        imageSize: *const fn (*anyopaque, Image) [2]u32,
        /// `.none` if the file does not load.
        loadSound: *const fn (*anyopaque, []const u8) Audio,
        /// WAV bytes in memory. Not cached. `.none` if they do not decode.
        decodeSound: *const fn (*anyopaque, []const u8) Audio,
        /// 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.fmt.bufPrint(&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 imageSize(h: Host, image: Image) [2]u32 {
        return h.vtable.imageSize(h.ctx, image);
    }
    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 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.
pub const Context = struct {
    host: Host,
    input: *const Input,
    /// Frame lifetime: reset after the host consumes the frame.
    arena: std.mem.Allocator,
    /// Session lifetime: survives reloads, released when the session resets.
    gpa: std.mem.Allocator,
    /// Filled by `draw`, using `arena`.
    commands: *std.ArrayList(Command),
};

/// One leaf of a reflected layout. Nested structs are flattened into dotted
/// paths; arrays stay whole. 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,
    reserved: [3]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 = "",

    pub const Kind = enum(u8) { int, uint, float, bool, @"enum", array, bytes, _ };
};

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,
    /// Console completions offered by the sketch.
    commands: []const []const u8 = &.{},
};

/// Which memory `sketch_defaults` fills.
pub const Memory = enum(u8) { state, session };

/// 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, appends commands.
    draw: *const fn (*const Context, [*]const u8, [*]u8) callconv(.c) void,
    /// A console line the host did not understand; true when handled.
    command: *const fn (*const Context, [*]u8, [*]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, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, 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 = .{ .spirv = "" }, .fragment = .{ .spirv = "" } });
    try std.testing.expectEqual(@as(u32, 20), p.stride);
}

test {
    _ = layout;
    _ = @import("keys.zig");
}