diff options
Diffstat (limited to 'src/abi.zig')
| -rw-r--r-- | src/abi.zig | 133 |
1 files changed, 127 insertions, 6 deletions
diff --git a/src/abi.zig b/src/abi.zig index ca1333e..03e2978 100644 --- a/src/abi.zig +++ b/src/abi.zig @@ -39,12 +39,38 @@ pub const Color = extern struct { 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 @@ -97,6 +123,17 @@ pub const Event = extern struct { 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); } @@ -104,6 +141,9 @@ pub const Event = extern struct { 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, @@ -115,14 +155,25 @@ pub const Stream = struct { /// 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, - /// Nanoseconds since the previous frame. + /// 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. @@ -137,6 +188,10 @@ pub const Input = struct { /// 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`. @@ -164,6 +219,21 @@ pub const Input = struct { } 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 }; @@ -225,8 +295,49 @@ pub const Voice = struct { 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 }, + /// 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, @@ -556,20 +667,30 @@ pub const Context = struct { }; /// One leaf of a reflected layout. Nested structs are flattened into dotted -/// paths; arrays stay whole. Hosts migrate state across layout changes, and +/// 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, - reserved: [3]u8 = @splat(0), + /// 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 { @@ -635,7 +756,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, gpu.Dispatch, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| { + 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; |
