summaryrefslogtreecommitdiff
path: root/src/host/Host.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/Host.zig')
-rw-r--r--src/host/Host.zig214
1 files changed, 121 insertions, 93 deletions
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 3a2a25f..3485d79 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -27,15 +27,17 @@ pub const Options = struct {
library: ?[]const u8 = null,
/// Local 9P control socket, opt-in.
ninep: ?[]const u8 = null,
- /// State file; the sessions database goes next to it, `<name>.xitdb`
- /// for `<name>.state`. Empty: `$XDG_DATA_HOME/<name>/<name>.state`
+ /// The save, a sessions database: `<stem>.xitdb`, for a path
+ /// `<stem>.xitdb`, `<stem>.state` (where a state file from before is
+ /// imported from) or `<stem>`. Empty: `$XDG_DATA_HOME/<name>/<name>.xitdb`
/// (`~/.local/share` without it), for a shipped game.
state: []const u8 = "",
/// Playing a script: from fresh state, sessions go to memory only.
script: bool = false,
/// Offscreen video, silent audio, no vsync: for scripts and CI.
headless: bool = false,
- /// Forget the state file's contents: scripts start from a known place.
+ /// Start from State's defaults, not the save's present: scripts start
+ /// from a known place.
fresh: bool = false,
/// Time every GPU command alone and print the times at exit.
profile_gpu: bool = false,
@@ -70,7 +72,7 @@ images: gfx.Images,
/// Plays the 2D commands: targets, blend, antialiased shapes.
painter: gfx.Painter,
audio: sound.Audio,
-state: memory.StateFile,
+state: memory.State,
session: memory.Session,
/// A failed resource setup disables app callbacks while keeping host controls alive.
session_ready: bool = false,
@@ -91,8 +93,11 @@ reloads: usize = 0,
/// file's inode, size and modification time): sessions' stretches carry it,
/// and `play` warns on a mismatch.
build: u64 = 0,
-/// The state file's path when the host chose it (`Options.state`), `gpa`'s.
+/// The save's path when the host chose it (`Options.state`), `gpa`'s.
state_path: []const u8 = "",
+/// `Options.state` without `.xitdb` or `.state`: the save is
+/// `<stem>.xitdb`, the sketch's own files `<stem>.<name>`.
+stem: []const u8 = "",
/// Copies of the sketch's info strings, replaced on every load.
info_arena: std.heap.ArenaAllocator,
name: []const u8 = "",
@@ -176,15 +181,13 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
var data_buf: [std.fs.max_path_bytes]u8 = undefined;
const state_path = if (given.state.len > 0) "" else blk: {
const data = environ.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{environ.get("HOME") orelse "."});
- const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.state", .{ data, info.name, info.name });
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}/{s}.xitdb", .{ data, info.name, info.name });
errdefer gpa.free(path);
try std.Io.Dir.cwd().createDirPath(io, std.fs.path.dirname(path).?);
break :blk path;
};
errdefer gpa.free(state_path);
if (state_path.len > 0) options.state = state_path;
- var state = try memory.StateFile.open(gpa, options.state);
- errdefer state.close();
self.* = .{
.gpa = gpa,
@@ -197,13 +200,14 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
.images = .{ .gpa = gpa, .renderer = renderer.? },
.painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null },
.audio = .{ .gpa = gpa },
- .state = state,
+ .state = .init(gpa),
.session = .init(gpa),
.timeline = undefined,
.sessions = .{ .gpa = gpa, .io = io },
.sketch = sketch,
.library = library,
.state_path = state_path,
+ .stem = stemOf(options.state),
.info_arena = .init(gpa),
.frame_arena = .init(gpa),
.input = .{ .exporting = options.export_to != null },
@@ -224,10 +228,8 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std
self.build = fileId(io, options.library orelse "/proc/self/exe");
try self.adopt(sketch);
self.openSessions(info.record);
- // Before --fresh: it never touches the history.
- if (importSnapshots(&self.state, &self.sessions)) |n| {
- if (n > 0) self.print("{d} snapshots of {s} are marks now", .{ n, options.state });
- } else |err| self.print("snapshots of {s} kept in it: {t}", .{ options.state, err });
+ // Before --fresh, which never touches the save.
+ self.openPresent();
if (options.fresh) self.resetState();
if (!options.headless and options.export_to == null) {
self.presentation = Presentation.init(gpa, self.window) catch null;
@@ -258,14 +260,19 @@ pub fn deinit(self: *Host) void {
self.files.deinit(self.gpa);
for (self.retired.items) |bytes| std.posix.munmap(bytes);
self.retired.deinit(self.gpa);
+ // A scripted run from fresh state, or an export, leaves no files.
+ const private = (self.options.script or self.options.export_to != null) and self.options.fresh;
var written = self.written.keyIterator();
- while (written.next()) |path| self.gpa.free(path.ptr[0 .. path.len + 1]);
+ while (written.next()) |path| {
+ if (private) std.Io.Dir.cwd().deleteFile(self.io, path.*) catch {};
+ self.gpa.free(path.ptr[0 .. path.len + 1]);
+ }
self.written.deinit(self.gpa);
self.timeline.deinit();
self.session.deinit(self.gpa);
self.made.images.deinit(self.gpa);
self.made.buffers.deinit(self.gpa);
- self.state.close();
+ self.state.deinit(self.gpa);
self.pending.deinit(self.gpa);
self.frame_arena.deinit();
self.info_arena.deinit();
@@ -330,7 +337,7 @@ test "timing clock drives ordinary ticks without moving input or replay time" {
}
pub fn live(self: *Host) []u8 {
- return self.state.slot(0);
+ return self.state.live();
}
/// One frame: reload if a build replaced the library, feed input through
@@ -696,7 +703,7 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void {
const replay = self.console.execute(self, line, now) catch |err| {
// The sketch has printed its own error already.
if (err == error.NotRecording) {
- self.console.log("Not recording (a release build: .record = true collects): no marks or clips.");
+ self.console.log("Not recording (an export): no marks or clips.");
} else if (err != error.CommandFailed) self.console.print("{t}. Type help for usage.", .{err});
if (self.timeline.restored) self.jumped = true;
try self.restoredInput(now);
@@ -738,7 +745,6 @@ pub fn resetState(self: *Host) void {
self.sketch.defaults(.state, bytes.ptr);
const ctx = self.context();
self.sketch.init(&ctx, bytes.ptr);
- self.state.markUsed(0, true);
}
/// Loads the watched library again.
@@ -757,14 +763,14 @@ pub fn load(self: *Host, path: []const u8) !void {
self.library = library;
self.reloads += 1;
self.build = fileId(self.io, path);
- self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() }) catch |err| self.print("session: {t}", .{err});
+ self.sessions.stretch(.{ .build = self.build, .source = self.source, .layout = self.state.header }) catch |err| self.print("session: {t}", .{err});
self.print("reload {d}: {s}", .{ self.reloads, path });
}
fn adopt(self: *Host, sketch: abi.Sketch) !void {
const info = sketch.info();
if (info.abi != abi.hash) return error.AbiMismatch;
- const adoption = try self.state.adopt(self.gpa, info.state, sketch.defaults);
+ const migrated = try self.state.adopt(self.gpa, info.state, sketch.defaults);
const session_reset = try self.session.adopt(self.gpa, info.session, sketch.defaults);
if (session_reset) self.releaseMade();
_ = self.info_arena.reset(.retain_capacity);
@@ -777,12 +783,7 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void {
self.sketch = sketch;
self.timeline.defaults = sketch.defaults;
self.reloaded = true;
- switch (adoption) {
- .unchanged => {},
- .created => {},
- .migrated => |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset }),
- }
- if (!self.state.used(0)) self.resetState();
+ if (migrated) |m| self.print("state layout changed: kept {d} fields, reset {d} to defaults", .{ m.kept, m.reset });
if (session_reset) {
const ctx = self.context();
self.session_ready = self.sketch.setup(&ctx);
@@ -932,42 +933,86 @@ fn consoleKey(e: abi.Event) ?Console.Key {
};
}
-/// Starts this run's session (Sessions.zig): in a file beside the state
-/// file when the build records, in memory for a script from fresh state,
-/// nowhere for an export. A database that cannot be opened is said, and
-/// the run goes on unrecorded.
+/// Opens the save (Sessions.zig) and starts this run's session in it: a
+/// file, `<stem>.xitdb`; in memory for a script from fresh state; nowhere
+/// for an export. A save that cannot be opened is said, and the run goes
+/// on unsaved.
fn openSessions(self: *Host, record: bool) void {
const o = self.options;
- const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else if (record) .file else .off;
+ const mode: Sessions.Mode = if (o.export_to != null) .off else if (o.script and o.fresh) .memory else .file;
var buf: [std.fs.max_path_bytes]u8 = undefined;
- const stem = if (std.mem.endsWith(u8, o.state, ".state")) o.state[0 .. o.state.len - ".state".len] else o.state;
- const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{stem}) catch "sketch.xitdb";
- const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.layoutBytes() };
+ const path = std.fmt.bufPrint(&buf, "{s}.xitdb", .{self.stem}) catch "sketch.xitdb";
+ const first: Sessions.Stretch = .{ .build = self.build, .source = self.source, .layout = self.state.header };
self.sessions = Sessions.open(self.gpa, self.io, mode, path, first, wallClock(self.io)) catch |err| blk: {
- self.print("not recording: {s}: {t}", .{ path, err });
+ self.print("not saved: {s}: {t}", .{ path, err });
break :blk .{ .gpa = self.gpa, .io = self.io };
};
- if (o.headless) return;
- switch (self.sessions.mode()) {
- .file => self.print("recording to {s}", .{path}),
- .memory => {},
- .off => if (o.export_to == null) self.print("not recording (release build: .record = true collects)", .{}),
- }
+ if (o.headless or self.sessions.mode() != .file) return;
+ self.print("{s} to {s}", .{ if (record) "recording" else "saving", path });
+}
+
+/// The State this run starts from: the save's present, its newest keyframe
+/// and the frames logged after it, replayed; in a new save, a state file
+/// from before (`<stem>.state`), imported once and left as it was; else
+/// `init`'s.
+fn openPresent(self: *Host) void {
+ var events: std.ArrayList(abi.Event) = .empty;
+ defer events.deinit(self.gpa);
+ const found = self.sessions.present(&events) catch |err| blk: {
+ self.print("the save's present did not read ({t}): starting from defaults", .{err});
+ break :blk null;
+ };
+ const key = found orelse {
+ if (self.sessions.session != 0 or self.sessions.mode() != .file) return self.resetState();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const old = std.fmt.bufPrint(&buf, "{s}.state", .{self.stem}) catch return self.resetState();
+ const n = importOld(self.gpa, old, &self.state, &self.sessions, self.sketch.defaults) catch |err| {
+ if (err != error.FileNotFound) self.print("{s} not imported ({t}): kept as it was", .{ old, err });
+ return self.resetState();
+ };
+ return self.print("{s} imported: its State, and {d} snapshots as marks; the file is kept as it was", .{ old, n });
+ };
+ defer key.free(self.gpa);
+ self.timeline.restore(key) catch |err| {
+ self.print("the save's present did not restore ({t}): starting from defaults", .{err});
+ return self.resetState();
+ };
+ self.timeline.restored = false;
+ var frames: usize = 0;
+ for (events.items) |e| frames += @intFromBool(e.kind == .tick);
+ if (frames == 0) return;
+ if (key.build != self.build) return self.print("{d} frames played after the save's last keyframe not replayed: another build", .{frames});
+ // As they were fed: `started` only for a run's first frame.
+ self.started = key.frame == 0;
+ self.update(events.items);
+ self.started = true;
}
-/// Snapshots of a state file from before sessions become marks "1".."7",
-/// then the file holds live state only. While nothing records, they stay.
-fn importSnapshots(state: *memory.StateFile, sessions: *Sessions) !usize {
- if (state.slots == 1 or sessions.mode() == .off) return 0;
+/// A state file from before (`path`) into a new save: its live State into
+/// `state`, its snapshots (slots 1..7) marks "1".."7", in `state`'s layout;
+/// the file is left as it was. Returns the number of marks.
+fn importOld(gpa: std.mem.Allocator, path: []const u8, state: *memory.State, sessions: *Sessions, defaults: *const fn (abi.Memory, [*]u8) callconv(.c) void) !usize {
+ const old = try memory.OldState.open(path);
+ defer old.close();
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const scratch = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), state.layout.size);
var n: usize = 0;
- for (1..state.slots) |i| if (state.used(i)) {
- _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, state.slot(i));
+ for (1..old.slots) |i| if (old.slot(i)) |image| {
+ _ = try memory.restore(arena.allocator(), old.layoutBytes(), image, state.layout, scratch, defaults);
+ _ = try sessions.mark(&.{'0' + @as(u8, @intCast(i))}, .import, scratch);
n += 1;
};
- try state.dropSnapshots();
+ _ = try memory.restore(arena.allocator(), old.layoutBytes(), old.slot(0) orelse return error.CorruptStateFile, state.layout, state.live(), defaults);
return n;
}
+/// `path` without `.xitdb` or `.state`.
+pub fn stemOf(path: []const u8) []const u8 {
+ for ([_][]const u8{ ".xitdb", ".state" }) |suffix| if (std.mem.endsWith(u8, path, suffix)) return path[0 .. path.len - suffix.len];
+ return path;
+}
+
fn wallClock(io: std.Io) u64 {
return @intCast(@max(0, std.Io.Timestamp.now(io, .real).nanoseconds));
}
@@ -1093,7 +1138,11 @@ fn apiAppendFile(ctx: *anyopaque, name_ptr: [*]const u8, name_len: usize, bytes:
return "";
}
var buf: [std.fs.max_path_bytes]u8 = undefined;
- const path = std.mem.print(&buf, "{s}.{s}", .{ self.options.state, name }) catch return "";
+ const o = self.options;
+ const private = (o.script or o.export_to != null) and o.fresh;
+ // A scripted run from fresh state, or an export, writes files of its own
+ // (two runs of one build step may share a directory), gone at exit.
+ const path = (if (private) std.mem.print(&buf, "{s}.{d}.{s}", .{ self.stem, std.os.linux.getpid(), name }) else std.mem.print(&buf, "{s}.{s}", .{ self.stem, name })) catch return "";
if (replace) {
// A new file: a mapping of the old one stays valid.
std.Io.Dir.cwd().deleteFile(self.io, path) catch {};
@@ -1194,22 +1243,11 @@ test "session setup runs for restored state and layout reset, not same-layout re
Fixture.init_calls = 0;
Fixture.fail_setup = false;
const a = std.testing.allocator;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var state_buf: [std.fs.max_path_bytes]u8 = undefined;
- const state_path = try std.mem.print(&state_buf, ".zig-cache/tmp/{s}/setup.state", .{&tmp.sub_path});
- {
- var state = try memory.StateFile.open(a, state_path);
- defer state.close();
- _ = try state.adopt(a, Fixture.description.state, Fixture.defaults);
- @as(*Fixture.State, @ptrCast(state.slot(0).ptr)).value = 77;
- state.markUsed(0, true);
- }
- // Exercise adoption with real persisted memory, without opening SDL devices.
+ // Exercise adoption without opening SDL devices.
var host: Host = undefined;
host.gpa = a;
- host.state = try memory.StateFile.open(a, state_path);
- defer host.state.close();
+ host.state = .init(a);
+ defer host.state.deinit(a);
host.session = .init(a);
defer host.session.deinit(a);
host.info_arena = .init(a);
@@ -1224,7 +1262,8 @@ test "session setup runs for restored state and layout reset, not same-layout re
host.input = .{};
host.commands = .empty;
try host.adopt(Fixture.sketch);
- try std.testing.expectEqual(@as(u32, 77), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value);
+ // Defaults: the present or `init` comes after (openPresent).
+ try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.State, @ptrCast(@alignCast(host.live().ptr))).value);
try std.testing.expectEqual(@as(usize, 0), Fixture.init_calls);
try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls);
const session_ptr = host.session.bytes.ptr;
@@ -1265,7 +1304,7 @@ test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload
try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data"));
}
-test "a state file's snapshots from before sessions become marks, and the file one slot" {
+test "a state file from before imports into a new save: its State live, its snapshots marks, the file as it was" {
const State = extern struct { v: u32 = 0 };
const D = struct {
fn f(_: abi.Memory, p: [*]u8) callconv(.c) void {
@@ -1278,32 +1317,24 @@ test "a state file's snapshots from before sessions become marks, and the file o
defer tmp.cleanup();
var buf: [std.fs.max_path_bytes]u8 = undefined;
const path = try std.mem.print(&buf, ".zig-cache/tmp/{s}/old.state", .{&tmp.sub_path});
- // An eight-slot SKETCH02 file, slots 0, 1 and 3 used: built from a new
- // one-slot file's header.
- {
- var file = try memory.StateFile.open(gpa, path);
- defer file.close();
- _ = try file.adopt(gpa, abi.layout.of(State, .state), D.f);
- }
- const one = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited);
- defer gpa.free(one);
+ var state: memory.State = .init(gpa);
+ defer state.deinit(gpa);
+ _ = try state.adopt(gpa, abi.layout.of(State, .state), D.f);
+ // An eight-slot SKETCH02 file, slots 0, 1 and 3 used, its header State's.
const stride = memory.page;
const old = try gpa.alloc(u8, memory.header_len + memory.old_slot_count * stride);
defer gpa.free(old);
@memset(old, 0);
- @memcpy(old[0..memory.header_len], one[0..memory.header_len]);
+ @memcpy(old[0..state.header.len], state.header);
const h: *memory.Header = @ptrCast(@alignCast(old.ptr));
h.magic = memory.file_magic_v2;
h.used = 0b1011;
for ([_][2]u32{ .{ 0, 5 }, .{ 1, 11 }, .{ 3, 33 } }) |slot| std.mem.writeInt(u32, old[memory.header_len + slot[0] * stride ..][0..4], slot[1], .little);
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = old });
- var state = try memory.StateFile.open(gpa, path);
- defer state.close();
- try std.testing.expectEqual(memory.old_slot_count, state.slots);
- var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.layoutBytes() }, 0);
+ var sessions = try Sessions.open(gpa, io, .memory, "", .{ .build = 1, .source = "", .layout = state.header }, 0);
defer sessions.deinit();
- try std.testing.expectEqual(@as(usize, 2), try importSnapshots(&state, &sessions));
+ try std.testing.expectEqual(@as(usize, 2), try importOld(gpa, path, &state, &sessions, D.f));
for ([_][2]u32{ .{ '1', 11 }, .{ '3', 33 } }) |want| {
const m = (try sessions.findMark(&.{@intCast(want[0])})).?;
const key = try sessions.load(m.session, m.key);
@@ -1312,17 +1343,13 @@ test "a state file's snapshots from before sessions become marks, and the file o
try std.testing.expectEqual(want[1], std.mem.readInt(u32, key.state[0..4], .little));
}
try std.testing.expectEqual(@as(?Sessions.Entry, null), try sessions.findMark("2"));
- // One slot now, live state kept, and it reopens so.
- try std.testing.expectEqual(@as(usize, 1), state.slots);
- try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.slot(0)[0..4], .little));
- var again = try memory.StateFile.open(gpa, path);
- defer again.close();
- try std.testing.expectEqualStrings(&memory.file_magic, &again.header().magic);
- try std.testing.expectEqual(@as(usize, 1), again.slots);
- try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, again.slot(0)[0..4], .little));
+ try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, state.live()[0..4], .little));
+ const after = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .unlimited);
+ defer gpa.free(after);
+ try std.testing.expectEqualSlices(u8, old, after);
}
-test "appendFile appends to a file beside the state and names it for readFile" {
+test "appendFile appends to a file beside the save and names it for readFile" {
const io = std.testing.io;
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
@@ -1332,7 +1359,8 @@ test "appendFile appends to a file beside the state and names it for readFile" {
host.io = io;
host.written = .empty;
host.files = .empty;
- host.options = .{ .state = try std.mem.print(&buf, ".zig-cache/tmp/{s}/t.state", .{&tmp.sub_path}) };
+ host.options = .{};
+ host.stem = try std.mem.print(&buf, ".zig-cache/tmp/{s}/t", .{&tmp.sub_path});
defer {
var written = host.written.keyIterator();
while (written.next()) |path| host.gpa.free(path.ptr[0 .. path.len + 1]);
@@ -1340,14 +1368,14 @@ test "appendFile appends to a file beside the state and names it for readFile" {
}
const name = "take-1.f32";
const path = std.mem.span(apiAppendFile(&host, name, name.len, "ab", 2, false));
- try std.testing.expect(std.mem.endsWith(u8, path, "/t.state.take-1.f32"));
+ try std.testing.expect(std.mem.endsWith(u8, path, "/t.take-1.f32"));
try std.testing.expectEqual(path.ptr, apiAppendFile(&host, name, name.len, "cd", 2, false));
- const bytes = try tmp.dir.readFileAlloc(io, "t.state.take-1.f32", host.gpa, .unlimited);
+ const bytes = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited);
defer host.gpa.free(bytes);
try std.testing.expectEqualStrings("abcd", bytes);
// writeFile: a new file, its old bytes gone.
_ = apiAppendFile(&host, name, name.len, "e", 1, true);
- const again = try tmp.dir.readFileAlloc(io, "t.state.take-1.f32", host.gpa, .unlimited);
+ const again = try tmp.dir.readFileAlloc(io, "t.take-1.f32", host.gpa, .unlimited);
defer host.gpa.free(again);
try std.testing.expectEqualStrings("e", again);
}