summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md13
-rw-r--r--build.zig12
-rw-r--r--src/abi.zig18
-rw-r--r--src/host/Console.zig8
-rw-r--r--src/host/Host.zig19
-rw-r--r--src/host/audio.zig11
-rw-r--r--src/host/script.zig6
-rw-r--r--src/sketch/root.zig9
-rw-r--r--src/sketch/web.zig23
9 files changed, 90 insertions, 29 deletions
diff --git a/README.md b/README.md
index 6531fcd..62e5ab1 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,9 @@ An app is an ordinary module. Every declaration is optional:
`update` sees `input.events`: pointer, wheel, key, text, `cancel` (focus loss,
console) and one `tick` per frame carrying `dt`. Recorded ticks make
-time-driven sketches replay exactly.
+time-driven sketches replay exactly. `input.started` is true on the first update after
+the program starts, never after a reload: state is saved, so this is where
+to stop what should not resume on its own.
`draw` gets a `Frame`: `clear`, `fill`, `image`, `text`, `print`, `clip`,
`canvas`, `cursor`, `voice`, `audio`, `pixels`, `quit`, plus `f.arena` (frame
@@ -95,7 +97,10 @@ queued and played.
sketch.
- **Scripts** (`--headless --fresh --script file`) drive the same routing and
frames as a player: `click`, `key`, `type`, `console`, `expect field value`,
- `expect-audio`, `screenshot`, `load`, `await-reload`.
+ `expect-audio`, `screenshot`, `load`, `reload`, `await-reload`. A failed
+ `expect`, or a console line that errors (a sketch command returning an
+ error included), fails the script. Headless always means offscreen, even
+ with `SDL_VIDEO_DRIVER` set, and GPU work still runs, into a texture.
- **GPU.** The host's 2D renderer runs on an SDL GPU device, which also
runs sketches' GPU passes. Without a GPU it falls back to any renderer.
- **Memory.** SDL allocations go through a leak-checking allocator; a leak
@@ -121,9 +126,9 @@ pub fn build(b: *std.Build) void {
| --- | --- |
| `app.addLibrary()` | the hot-reloadable shared library |
| `app.addExecutable()` | host and sketch linked into one binary |
-| `app.addWeb(.{ .assets = ... })` | the wasm module and a ready-to-serve directory |
+| `app.addWeb(.{ .assets = ... })` | the wasm module and a ready-to-serve directory; tests can read its state by path with `sk_field` (numbers) and `sk_tag` (enum tag names) |
| `app.addRun(lib, .{})` | the generic host running the installed library |
-| `app.addScript(exe, file, .{})` | a headless, fresh-state scripted run |
+| `app.addScript(exe_or_lib, file, .{})` | a headless, fresh-state scripted run, of the executable or of the library through the host (so the script can `reload` it) |
| `app.addProbe(state)` | the probe on a state file |
| `app.addTest(.{})` | tests with the app importable as `app` |
diff --git a/build.zig b/build.zig
index 9fc9049..8de7f01 100644
--- a/build.zig
+++ b/build.zig
@@ -406,16 +406,20 @@ pub const App = struct {
cwd: ?Build.LazyPath = null,
};
- /// Plays a script headless against `exe` (from `addExecutable`), with a
- /// throwaway state file. Fails when an expectation does.
- pub fn addScript(app: App, exe: *Build.Step.Compile, script: Build.LazyPath, options: ScriptOptions) *Build.Step.Run {
+ /// Plays a script headless, with a throwaway state file, against
+ /// `artifact`: the executable (`addExecutable`), or the hot-reloadable
+ /// library (`addLibrary`) through the generic host, which scripts can
+ /// `reload`. Fails when an expectation or a console line does.
+ pub fn addScript(app: App, artifact: *Build.Step.Compile, script: Build.LazyPath, options: ScriptOptions) *Build.Step.Run {
const b = app.sb.b;
- const run = b.addRunArtifact(exe);
+ const library = artifact.isDynamicLibrary();
+ const run = b.addRunArtifact(if (library) app.sb.host_exe else artifact);
run.addArgs(&.{ "--headless", "--fresh", "--script" });
run.addFileArg(script);
run.addArg("--state");
_ = run.addOutputFileArg(b.fmt("{s}.state", .{app.name}));
for (options.defines) |pair| run.addArgs(&.{ "--define", b.fmt("{s}={s}", .{ pair[0], pair[1] }) });
+ if (library) run.addArtifactArg(artifact);
run.setCwd(options.cwd orelse b.path("."));
run.expectExitCode(0);
run.has_side_effects = true;
diff --git a/src/abi.zig b/src/abi.zig
index 3e23c47..4782599 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -106,6 +106,10 @@ pub const Input = struct {
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,
@@ -366,8 +370,9 @@ pub const Host = struct {
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.
+ /// 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,
@@ -473,6 +478,15 @@ pub const Info = struct {
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.
@@ -484,7 +498,7 @@ pub const Sketch = struct {
/// 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) bool,
+ command: *const fn (*const Context, [*]u8, [*]u8, *const []const u8) callconv(.c) Outcome,
pub const symbols = .{
.info = "sketch_info",
diff --git a/src/host/Console.zig b/src/host/Console.zig
index d9aa469..e6be2f0 100644
--- a/src/host/Console.zig
+++ b/src/host/Console.zig
@@ -135,7 +135,7 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
if (eq(command, "help")) {
self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N | seek start|end|<ms>");
self.log("diff [N] | reset | get <field> | set <field> <value> | overlay memory|sound | quit");
- if (!host.forward(self, line, now)) self.log("Backtick hides the console. Tab completes.");
+ if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes.");
return &.{};
}
if (eq(command, "overlay")) {
@@ -210,7 +210,11 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const
} else {
// Sketch commands edit state outside the recorded input.
h.stop(now);
- if (!host.forward(self, line, now)) return error.UnknownCommand;
+ switch (host.forward(self, line, now)) {
+ .unknown => return error.UnknownCommand,
+ .failed => return error.CommandFailed,
+ .done => {},
+ }
}
return &.{};
}
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 81a5dc8..92d1b55 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -67,6 +67,7 @@ canvas: [2]u32 = .{ 0, 0 },
cursor: abi.Cursor = .arrow,
quit: bool = false,
reloaded: bool = true,
+started: bool = true,
last_now: u64 = 0,
/// Saved after the next frame is drawn (scripts).
screenshot: ?[:0]const u8 = null,
@@ -223,6 +224,8 @@ pub fn update(self: *Host, events: []const abi.Event) void {
if (events.len > 0 and self.timeline.mode != .live and self.timeline.mode != .recording) self.input.now = events[events.len - 1].time;
self.input.events = events;
self.input.mode = self.timeline.mode;
+ self.input.started = self.started;
+ self.started = false;
const ctx = self.context();
self.sketch.update(&ctx, self.live().ptr);
self.input.events = &.{};
@@ -307,7 +310,7 @@ pub fn route(self: *Host, e: abi.Event) !void {
},
.key_down => {
const key = consoleKey(e) orelse return;
- if (self.console.edit(key, self.completions)) |line| self.runLine(line, e.time);
+ if (self.console.edit(key, self.completions)) |line| self.runLine(line, e.time) catch {};
return;
},
.key_up => return,
@@ -319,17 +322,19 @@ pub fn route(self: *Host, e: abi.Event) !void {
try self.pending.append(self.gpa, e);
}
-/// Runs a console line now, replaying whatever a seek asks for.
-pub fn runLine(self: *Host, line: []const u8, now: u64) void {
+/// Runs a console line now, replaying whatever a seek asks for. An error is
+/// printed to the console, and returned for scripts to fail on.
+pub fn runLine(self: *Host, line: []const u8, now: u64) !void {
const replay = self.console.execute(self, line, now) catch |err| {
- self.console.print("{t}. Type help for usage.", .{err});
- return;
+ // The sketch has printed its own error already.
+ if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
+ return err;
};
if (self.timeline.mode == .paused) self.update(replay);
}
-/// Offers a line to the sketch; false if it did not take it.
-pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) bool {
+/// Offers a line to the sketch.
+pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome {
self.input.now = now;
const ctx = self.context();
return self.sketch.command(&ctx, self.live().ptr, self.session.bytes.ptr, &line);
diff --git a/src/host/audio.zig b/src/host/audio.zig
index fc8dcfb..87332b1 100644
--- a/src/host/audio.zig
+++ b/src/host/audio.zig
@@ -55,19 +55,22 @@ pub const Audio = struct {
return out;
}
+ /// `.none` when the file is missing or unreadable, remembered so the
+ /// warning prints once.
pub fn load(self: *Audio, path: []const u8) abi.Audio {
if (self.paths.get(path)) |audio| return audio;
- const audio = self.add(decodeFile(self.gpa, path) catch |err| blk: {
+ const audio: abi.Audio = if (decodeFile(self.gpa, path)) |samples| self.add(samples) else |err| blk: {
std.log.warn("sound {s}: {t}", .{ path, err });
- break :blk &.{};
- });
+ break :blk .none;
+ };
const key = self.gpa.dupe(u8, path) catch return audio;
self.paths.put(self.gpa, key, audio) catch self.gpa.free(key);
return audio;
}
+ /// `.none` when `wav` does not decode.
pub fn decode(self: *Audio, wav: []const u8) abi.Audio {
- return self.add(decodeWav(self.gpa, wav) catch &.{});
+ return self.add(decodeWav(self.gpa, wav) catch return .none);
}
fn add(self: *Audio, samples: []f32) abi.Audio {
diff --git a/src/host/script.zig b/src/host/script.zig
index 4563a47..ec716e9 100644
--- a/src/host/script.zig
+++ b/src/host/script.zig
@@ -73,7 +73,11 @@ fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []cons
} else if (eq(u8, command, "type")) {
for (rest) |byte| try host.route(.{ .kind = .text, .time = now.*, .value = byte });
} else if (eq(u8, command, "console")) {
- host.runLine(rest, now.*);
+ // A failing console line fails the script, like a failed expect.
+ host.runLine(rest, now.*) catch |err| {
+ std.debug.print(" console {s}: {t}\n", .{ rest, err });
+ return err;
+ };
} else if (eq(u8, command, "frames")) {
const count = try std.fmt.parseInt(usize, rest, 10);
for (0..count) |_| try advance(host, now);
diff --git a/src/sketch/root.zig b/src/sketch/root.zig
index 316a886..0567839 100644
--- a/src/sketch/root.zig
+++ b/src/sketch/root.zig
@@ -193,16 +193,17 @@ pub fn Glue(comptime App: type) type {
else => App.draw(current, session(ss), &f),
}
}
- pub fn command(ctx: *const abi.Context, s: [*]u8, ss: [*]u8, line: *const []const u8) callconv(.c) bool {
- if (!@hasDecl(App, "command")) return false;
+ pub fn command(ctx: *const abi.Context, s: [*]u8, ss: [*]u8, line: *const []const u8) callconv(.c) abi.Outcome {
+ if (!@hasDecl(App, "command")) return .unknown;
var c: Console = .{ .host = ctx.host, .in = ctx.input };
- return switch (comptime arity(App.command)) {
+ const taken = switch (comptime arity(App.command)) {
3 => App.command(state(s), &c, line.*),
else => App.command(state(s), session(ss), &c, line.*),
} catch |err| {
c.print("{t}. Type help for usage.", .{err});
- return true;
+ return .failed;
};
+ return if (taken) .done else .unknown;
}
};
}
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index 7246c0d..e91a0ad 100644
--- a/src/sketch/web.zig
+++ b/src/sketch/web.zig
@@ -23,7 +23,8 @@ const js = struct {
};
/// Exports `App` for `web/host.js`: `sk_init`, `sk_event`, `sk_frame`, and
-/// `sk_field` for tests to read state by path.
+/// for tests to read state by path, `sk_field` (a number) and `sk_tag` (an
+/// enum's tag name).
pub fn exportWeb(comptime App: type) void {
const D = Driver(App);
@export(&D.init, .{ .name = "sk_init" });
@@ -31,6 +32,7 @@ pub fn exportWeb(comptime App: type) void {
@export(&D.frame, .{ .name = "sk_frame" });
@export(&D.buffer, .{ .name = "sk_buffer" });
@export(&D.field, .{ .name = "sk_field" });
+ @export(&D.tag, .{ .name = "sk_tag" });
}
fn Driver(comptime App: type) type {
@@ -96,6 +98,7 @@ fn Driver(comptime App: type) type {
input.dt = dt;
input.frame += 1;
input.events = events[0..event_count];
+ input.started = input.frame == 1;
const ctx = context();
G.update(&ctx, std.mem.asBytes(&state));
input.events = &.{};
@@ -131,6 +134,24 @@ fn Driver(comptime App: type) type {
/// The state field at the path written into `sk_buffer`, as a number
/// (enums by value); NaN when there is no such scalar field.
+ /// Writes the tag name of the enum field at the path in `buffer` over
+ /// it, and returns its length; -1 when there is no such enum field.
+ fn tag(len: usize) callconv(.c) i32 {
+ const name = path[0..@min(len, path.len)];
+ for (G.description.state.fields) |f| {
+ if (f.kind != .@"enum" or !std.mem.eql(u8, std.mem.span(f.path), name)) continue;
+ const value: u64 = @intFromFloat(field(len));
+ var pairs = std.mem.tokenizeScalar(u8, std.mem.span(f.tags), ',');
+ while (pairs.next()) |pair| {
+ const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue;
+ if ((std.fmt.parseInt(u64, pair[eq + 1 ..], 10) catch continue) != value) continue;
+ @memcpy(path[0..eq], pair[0..eq]);
+ return @intCast(eq);
+ }
+ }
+ return -1;
+ }
+
fn field(len: usize) callconv(.c) f64 {
const name = path[0..@min(len, path.len)];
const bytes = std.mem.asBytes(&state);