summaryrefslogtreecommitdiff
path: root/src/sketch/root.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/sketch/root.zig')
-rw-r--r--src/sketch/root.zig175
1 files changed, 147 insertions, 28 deletions
diff --git a/src/sketch/root.zig b/src/sketch/root.zig
index 52f05b2..490b2f9 100644
--- a/src/sketch/root.zig
+++ b/src/sketch/root.zig
@@ -7,18 +7,18 @@
//! pub const height = 600;
//! pub const State = struct { ... }; // saved, snapshotted, replayed: no pointers
//! pub const Session = struct { ... }; // this process: survives reloads
-//! pub const Store = struct { ... }; // on disk: survives restarts too
//! pub const commands = .{"hello"}; // console completions
//! pub fn init(state: *State, host: sk.Host) void
+//! pub fn setup(session: *Session, init: *sk.Init) !void
//! pub fn update(state: *State, in: *const sk.Input) void
-//! pub fn draw(state: *const State, session: *Session, store: *Store, f: *sk.Frame) void
-//! pub fn command(state: *State, store: *Store, c: *sk.Console, line: []const u8) !bool
+//! pub fn draw(state: *const State, session: *Session, f: *sk.Frame) void
+//! pub fn command(state: *State, session: *Session, c: *sk.Console, line: []const u8) !bool
//!
//! Functions take the parameters they name, by type, in any order: `draw`
-//! may ask for `*Session`, `*Store`, both or neither. `update` must be
+//! may ask for `*Session` or not. `update` must be
//! deterministic, so it gets `State` and `Input` only: the host replays
//! recorded input through it. `draw` presents state as pictures and sound,
-//! and changes only Session and Store. Geometry and colors are duck-typed:
+//! and changes only Session. Geometry and colors are duck-typed:
//! see `shape`.
const std = @import("std");
pub const abi = @import("abi");
@@ -40,7 +40,13 @@ pub const List = @import("list.zig").List;
/// Data computed in draw from a few State fields, kept in Session and rebuilt when they change (or after a reload).
pub const Derived = @import("derived.zig").Derived;
pub const web = @import("web.zig");
+/// Text measured and laid out anywhere (`update` too): `size`, `layout`,
+/// `font`, and the `Paragraph` `Frame.paragraph` draws.
+pub const text = @import("text.zig");
+/// sfxr's sound effects, rendered to samples for `host.newSound`.
+pub const sfxr = @import("sfxr.zig");
const request = @import("request.zig");
+const text_module = text;
pub const Request = request.Request;
pub const Handled = request.Handled;
@@ -59,6 +65,13 @@ pub const Voice = abi.Voice;
pub const BlendMode = abi.BlendMode;
pub const Face = abi.Face;
+/// Resource initialization, once per fresh Session (also when State is restored).
+/// No State, Input, scratch allocator, or drawing commands are available here.
+pub const Init = struct {
+ host: Host,
+ session: std.mem.Allocator,
+};
+
/// What `draw` receives: input, host services, memory by lifetime and the
/// command list. Commands may be built from anything: the methods copy what
/// they keep (text, GPU descriptions) into `scratch`, except bulk data
@@ -71,14 +84,12 @@ pub const Frame = struct {
scratch: std.mem.Allocator,
/// For Session: this process.
session: std.mem.Allocator,
- /// For Store: on disk, across restarts.
- store: std.mem.Allocator,
/// A library's own state for this frame (canim's table of places), in
/// `scratch`: null at each frame's start.
user: ?*anyopaque = null,
pub fn init(ctx: *const abi.Context) Frame {
- return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session, .store = ctx.store };
+ return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .scratch = ctx.scratch, .session = ctx.session };
}
pub fn emit(f: *Frame, command: abi.Command) void {
@@ -150,13 +161,23 @@ pub const Frame = struct {
pub fn blend(f: *Frame, mode: BlendMode) void {
f.emit(.{ .blend = mode });
}
+ /// Text from its top left corner, scale 1 a 13 px face; a `\n` starts
+ /// a line. `sk.text.size(.mono, scale, bytes)` is what it covers.
pub fn text(f: *Frame, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes) } });
+ f.textIn(.mono, x, y, scale, bytes, color);
}
- /// `text` in another face of the built-in family: bold or italic mono,
- /// or the sans (`host.textSizeIn` measures it).
+ /// `text` in another face: bold or italic mono, the sans, JetBrains
+ /// Mono NL, or a sketch's own (`sk.text.font`).
pub fn textIn(f: *Frame, face: Face, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face } });
+ if (std.mem.indexOfScalar(u8, bytes, '\n') != null) {
+ _ = f.paragraph(x, y, bytes, .{ .face = face, .scale = scale, .color = paint(color) });
+ } else f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face } });
+ }
+ /// A paragraph from its top left corner (`sk.text.Paragraph`: a width
+ /// to wrap at, alignment, spans, the glyphs revealed, a caret), drawn;
+ /// its `Layout` returned, as `sk.text.layout` gives it, from `x`, `y`.
+ pub fn paragraph(f: *Frame, x: f32, y: f32, bytes: []const u8, p: text_module.Paragraph) text_module.Layout {
+ return text_module.lay(f.keep(u8, bytes), p, x, y, f, &.{});
}
/// `textIn` laid out and rasterized at `raster` and drawn at `scale`,
/// its position not snapped to a pixel: for text under a moving
@@ -167,7 +188,7 @@ pub const Frame = struct {
f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face, .raster = raster } });
}
pub fn print(f: *Frame, x: f32, y: f32, scale: f32, color: anytype, comptime fmt: []const u8, args: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.format(fmt, args) } });
+ f.textIn(.mono, x, y, scale, f.format(fmt, args), color);
}
/// Formats into scratch memory.
pub fn format(f: *Frame, comptime fmt: []const u8, args: anytype) []const u8 {
@@ -201,9 +222,20 @@ pub const Frame = struct {
pub fn voice(f: *Frame, v: Voice) void {
f.emit(.{ .voice = v });
}
+ /// Scales every voice of `group` this frame (1 when not declared).
+ pub fn gain(f: *Frame, group: u3, value: f32) void {
+ f.emit(.{ .gain = .{ .group = group, .gain = value } });
+ }
pub fn audio(f: *Frame, key: u32, samples: []const f32, options: struct { clear: bool = false }) void {
f.emit(.{ .audio = .{ .key = key, .samples = samples, .clear = options.clear } });
}
+ /// Streams `count` samples a compute shader wrote to `buffer` (f32 from
+ /// `offset`) on stream `key`, as `audio` streams samples: a GPU synth's
+ /// output, heard without a readback of the sketch's own. Make
+ /// `in.lead -| in.stream(key).queued` of them a frame.
+ pub fn audioBuffer(f: *Frame, key: u32, buffer: abi.Buffer, options: struct { offset: u32 = 0, count: u32 }) void {
+ f.emit(.{ .audio_buffer = .{ .key = key, .buffer = buffer, .offset = options.offset, .count = options.count } });
+ }
pub fn pixels(f: *Frame, img: Image, w: u32, h: u32, rgba: []const u8, options: struct { premultiplied: bool = false }) void {
f.emit(.{ .pixels = .{ .image = img, .w = w, .h = h, .rgba = rgba, .premultiplied = options.premultiplied } });
}
@@ -223,6 +255,12 @@ pub const Frame = struct {
kept.draws = draws;
f.emit(.{ .gpu = kept });
}
+ /// Samples the source color and optionally depth into a distinct image.
+ pub fn postProcess(f: *Frame, source: Image, destination: Image, post: abi.gpu.PostProcess) void {
+ var kept = post;
+ kept.fragment_uniforms = f.keep(u8, post.fragment_uniforms);
+ f.emit(.{ .post_process = .{ .source = source, .target = destination, .effect = kept } });
+ }
/// `bytes` into a buffer made by `Host.newBuffer`.
pub fn upload(f: *Frame, buffer: abi.Buffer, offset: u32, bytes: []const u8) void {
f.emit(.{ .upload = .{ .buffer = buffer, .offset = offset, .bytes = bytes } });
@@ -270,12 +308,11 @@ fn paint(value: anytype) Color {
}
/// What `command` receives: somewhere to answer, the current input, and the
-/// allocators for Session and Store.
+/// allocator for Session.
pub const Console = struct {
host: Host,
in: *const Input,
session: std.mem.Allocator,
- store: std.mem.Allocator,
pub fn log(c: *Console, message: []const u8) void {
c.host.log(message);
@@ -285,29 +322,41 @@ pub const Console = struct {
}
};
+/// What the build knows of a sketch and passes to `sketch` and
+/// `exportSketch` (build.zig's generated roots fill it in).
+pub const Build = struct {
+ /// The repository revision the sketch was built from, "" when unknown.
+ source: []const u8 = "",
+ /// Keep history in the save (`abi.Info.record`).
+ record: bool = false,
+};
+
/// The entry points of `App`, for a host that links it statically.
-pub fn sketch(comptime App: type) abi.Sketch {
- const G = Glue(App);
- return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .update = G.update, .draw = G.draw, .command = G.command };
+pub fn sketch(comptime App: type, comptime made: Build) abi.Sketch {
+ const G = Glue(App, made);
+ return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .setup = G.setup, .update = G.update, .draw = G.draw, .command = G.command };
}
/// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library.
-pub fn exportSketch(comptime App: type) void {
- const G = Glue(App);
+pub fn exportSketch(comptime App: type, comptime made: Build) void {
+ const G = Glue(App, made);
const names = abi.Sketch.symbols;
@export(&G.info, .{ .name = names.info });
@export(&G.defaults, .{ .name = names.defaults });
@export(&G.init, .{ .name = names.init });
+ @export(&G.setup, .{ .name = names.setup });
@export(&G.update, .{ .name = names.update });
@export(&G.draw, .{ .name = names.draw });
@export(&G.command, .{ .name = names.command });
+ @export(&G.build, .{ .name = "sketch_build" });
}
-pub fn Glue(comptime App: type) type {
+pub fn Glue(comptime App: type, comptime made: Build) type {
return struct {
pub const State = if (@hasDecl(App, "State")) App.State else struct {};
pub const Session = if (@hasDecl(App, "Session")) App.Session else struct {};
- pub const Store = if (@hasDecl(App, "Store")) App.Store else struct {};
+
+ const build: [abi.build.len:0]u8 = abi.build.*;
pub const description: abi.Info = .{
.abi = abi.hash,
@@ -316,8 +365,10 @@ pub fn Glue(comptime App: type) type {
.height = if (@hasDecl(App, "height")) App.height else 600,
.state = abi.layout.of(State, .state),
.session = abi.layout.of(Session, .session),
- .store = abi.layout.of(Store, .store),
.commands = if (@hasDecl(App, "commands")) &App.commands else &.{},
+ .source = made.source ++ " " ++ abi.build,
+ .record = made.record,
+ .audio_pull = if (@hasDecl(App, "audio_pull")) App.audio_pull else 0,
};
/// What a call can offer, by type.
@@ -325,12 +376,14 @@ pub fn Glue(comptime App: type) type {
ctx: *const abi.Context,
state: [*]u8,
frame: ?*Frame = null,
+ resource_init: ?*Init = null,
console: ?*Console = null,
line: []const u8 = "",
};
/// Calls `func` with the arguments its parameter types ask for.
fn call(comptime func: anytype, comptime name: []const u8, offer: Offer) @typeInfo(@TypeOf(func)).@"fn".return_type.? {
+ text_module.host = offer.ctx.host;
const F = @TypeOf(func);
var args: std.meta.ArgsTuple(F) = undefined;
inline for (@typeInfo(F).@"fn".param_types, 0..) |P, i| {
@@ -340,8 +393,11 @@ pub fn Glue(comptime App: type) type {
return std.mem.eql(u8, name, n);
}
};
- if (comptime is.named("update") and (T == *Session or T == *Store))
+ if (comptime is.named("update") and T == *Session)
@compileError("update must be deterministic: it gets State and Input only, so a replay reproduces it");
+ if (comptime is.named("setup") and (T == *State or T == *const State or T == *const Input))
+ @compileError("setup initializes resources: it gets Session, Init and Host only");
+ if (comptime (T == *Init or T == *const Init) and !is.named("setup")) @compileError(name ++ " gets no Init: only setup does");
if (comptime is.named("draw") and T == *State) @compileError("draw only reads State: take *const State");
if (comptime T == *Frame and !is.named("draw")) @compileError(name ++ " gets no Frame: only draw does");
if (comptime T == *Console and !is.named("command")) @compileError(name ++ " gets no Console: only command does");
@@ -349,12 +405,12 @@ pub fn Glue(comptime App: type) type {
@ptrCast(@alignCast(offer.state))
else if (T == *Session or T == *const Session)
@ptrCast(@alignCast(offer.ctx.session_root))
- else if (T == *Store or T == *const Store)
- @ptrCast(@alignCast(offer.ctx.store_root))
else if (T == *const Input)
offer.ctx.input
else if (T == Host)
offer.ctx.host
+ else if (T == *Init or T == *const Init)
+ offer.resource_init.?
else if (T == *Frame)
offer.frame.?
else if (T == *Console)
@@ -374,12 +430,21 @@ pub fn Glue(comptime App: type) type {
switch (which) {
.state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{},
.session => @as(*Session, @ptrCast(@alignCast(ptr))).* = .{},
- .store => @as(*Store, @ptrCast(@alignCast(ptr))).* = .{},
}
}
pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void {
if (@hasDecl(App, "init")) call(App.init, "init", .{ .ctx = ctx, .state = s });
}
+ pub fn setup(ctx: *const abi.Context) callconv(.c) bool {
+ if (!@hasDecl(App, "setup")) return true;
+ var resource_init: Init = .{ .host = ctx.host, .session = ctx.session };
+ const result = call(App.setup, "setup", .{ .ctx = ctx, .state = undefined, .resource_init = &resource_init });
+ if (@typeInfo(@TypeOf(result)) == .error_union) result catch |err| {
+ ctx.host.print("session setup failed: {t}", .{err});
+ return false;
+ };
+ return true;
+ }
pub fn update(ctx: *const abi.Context, s: [*]u8) callconv(.c) void {
if (@hasDecl(App, "update")) call(App.update, "update", .{ .ctx = ctx, .state = s });
}
@@ -390,7 +455,7 @@ pub fn Glue(comptime App: type) type {
}
pub fn command(ctx: *const abi.Context, s: [*]u8, line: *const []const u8) callconv(.c) abi.Outcome {
if (!@hasDecl(App, "command")) return .unknown;
- var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session, .store = ctx.store };
+ var c: Console = .{ .host = ctx.host, .in = ctx.input, .session = ctx.session };
const taken = call(App.command, "command", .{ .ctx = ctx, .state = s, .console = &c, .line = line.* }) catch |err| {
c.print("{t}. Type help for usage.", .{err});
return .failed;
@@ -410,4 +475,58 @@ test {
_ = @import("clock.zig");
_ = @import("list.zig");
_ = @import("derived.zig");
+ _ = sfxr;
+ _ = text;
+}
+
+test "setup receives session resources without a Frame and reports errors" {
+ const App = struct {
+ pub const Session = struct { bytes: []u8 = &.{}, calls: u32 = 0 };
+ pub fn setup(session: *Session, resources: *Init) !void {
+ session.calls += 1;
+ session.bytes = try resources.session.dupe(u8, "ready");
+ return error.TestSetupFailure;
+ }
+ };
+ const Log = struct {
+ fn log(ctx: *anyopaque, message: []const u8) void {
+ const seen: *bool = @ptrCast(@alignCast(ctx));
+ seen.* = std.mem.eql(u8, message, "session setup failed: TestSetupFailure");
+ }
+ };
+ var seen = false;
+ var vtable: abi.Host.VTable = undefined;
+ vtable.log = Log.log;
+ var session: App.Session = .{};
+ var ctx: abi.Context = undefined;
+ ctx.host = .{ .ctx = &seen, .vtable = &vtable };
+ ctx.session_root = std.mem.asBytes(&session);
+ ctx.session = std.testing.allocator;
+ const app = sketch(App, .{});
+ try std.testing.expect(!app.setup(&ctx));
+ defer std.testing.allocator.free(session.bytes);
+ try std.testing.expectEqualStrings("ready", session.bytes);
+ try std.testing.expectEqual(@as(u32, 1), session.calls);
+ try std.testing.expect(seen);
+}
+
+test "postprocess preserves image handles and copies transient uniforms" {
+ var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena.deinit();
+ var commands: std.ArrayList(abi.Command) = .empty;
+ var ctx: abi.Context = undefined;
+ ctx.commands = &commands;
+ var frame: Frame = undefined;
+ frame.ctx = &ctx;
+ frame.scratch = arena.allocator();
+ var uniforms = [_]u8{ 1, 2, 3, 4 };
+ const source: Image = @fromBackingInt(@intCast(1));
+ const target: Image = @fromBackingInt(@intCast(2));
+ frame.postProcess(source, target, .{ .vertex = .{ .code = "vertex" }, .fragment = .{ .code = "fragment" }, .sample_depth = true, .fragment_uniforms = &uniforms });
+ uniforms[0] = 9;
+ const post = commands.items[0].post_process;
+ try std.testing.expectEqual(source, post.source);
+ try std.testing.expectEqual(target, post.target);
+ try std.testing.expect(post.effect.sample_depth);
+ try std.testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4 }, post.effect.fragment_uniforms);
}