diff options
Diffstat (limited to 'src/abi.zig')
| -rw-r--r-- | src/abi.zig | 181 |
1 files changed, 151 insertions, 30 deletions
diff --git a/src/abi.zig b/src/abi.zig index 4782599..ca1333e 100644 --- a/src/abi.zig +++ b/src/abi.zig @@ -13,6 +13,9 @@ 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, @@ -71,11 +74,25 @@ pub const Event = extern struct { 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); } @@ -112,25 +129,38 @@ pub const Input = struct { started: bool = false, /// The console is open and owns the keyboard. console: 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, 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(), + 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(@intFromEnum(key)); + 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 == @intFromEnum(key) and e.flags & Event.repeat == 0) return true; + if (e.kind == .key_down and e.code == @backingInt(key) and e.flags & Event.repeat == 0) return true; } return false; } @@ -141,7 +171,7 @@ pub const Input = struct { /// Follows mouse, button and key state through one fed event. pub fn track(in: *Input, e: Event) void { switch (e.kind) { - .mouse_move, .wheel => { + .mouse_move, .wheel, .wheel_horizontal => { in.mouse_x = e.x; in.mouse_y = e.y; }, @@ -155,7 +185,7 @@ pub const Input = struct { .key_up => in.keys.unset(@min(e.code, 255)), .cancel => { in.buttons = 0; - in.keys = .initEmpty(); + in.keys = .empty; }, else => {}, } @@ -167,6 +197,9 @@ pub const Input = struct { 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 @@ -185,7 +218,10 @@ pub const Voice = struct { }; /// Slices must stay alive until the host consumes the frame, right after -/// `draw` returns: literals, the frame arena and session memory all qualify. +/// `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 }, @@ -205,6 +241,25 @@ pub const Command = union(enum) { /// 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, }; @@ -213,13 +268,44 @@ pub const Command = union(enum) { /// 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. +/// 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 { - spirv: []const u8, + /// 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 }; @@ -258,12 +344,17 @@ pub const gpu = struct { pub const Draw = struct { /// Index into `Pass.pipelines`. pipeline: u32, - vertices: []const u8, + /// 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, }; @@ -276,9 +367,9 @@ pub const gpu = struct { 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 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; }; @@ -336,6 +427,8 @@ pub const gpu = struct { } 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, @@ -366,14 +459,22 @@ pub const Host = struct { 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. + /// 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, /// `.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. + /// 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, @@ -387,7 +488,7 @@ pub const Host = struct { } 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)"); + 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); @@ -404,6 +505,12 @@ pub const Host = struct { 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); } @@ -413,6 +520,9 @@ pub const Host = struct { 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); } @@ -424,15 +534,24 @@ pub const Host = struct { } }; -/// What the host passes to every call. +/// 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: 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`. + /// 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), }; @@ -470,12 +589,13 @@ pub const Info = struct { 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 }; +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. @@ -495,10 +615,11 @@ pub const Sketch = struct { 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, + /// 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", @@ -514,7 +635,7 @@ pub const Sketch = struct { 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| { + for (.{ Rect, Color, 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; @@ -528,7 +649,7 @@ test "vertex attributes and std140 checks come from the types" { 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 = "" } }); + const p = gpu.pipeline(Vertex, .{ .vertex = .{ .code = "" }, .fragment = .{ .code = "" } }); try std.testing.expectEqual(@as(u32, 20), p.stride); } |
