diff options
Diffstat (limited to 'src/host/Host.zig')
| -rw-r--r-- | src/host/Host.zig | 120 |
1 files changed, 99 insertions, 21 deletions
diff --git a/src/host/Host.zig b/src/host/Host.zig index 7ebe54a..de19b99 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -6,8 +6,9 @@ const std = @import("std"); const c = @import("c"); const abi = @import("abi"); const memory = @import("memory.zig"); -const Timeline = @import("timeline.zig").Timeline; -const mapRecordings = @import("timeline.zig").mapRecordings; +const playback = @import("timeline.zig"); +const Timeline = playback.Timeline; +const mapRecordings = playback.mapRecordings; const gfx = @import("gfx.zig"); const sound = @import("audio.zig"); const Gpu = @import("gpu.zig"); @@ -44,6 +45,8 @@ passes: ?Gpu = null, offscreen: ?*c.SDL_Texture = null, pointer_cursor: ?*c.SDL_Cursor = null, images: gfx.Images, +/// Plays the 2D commands: targets, blend, antialiased shapes. +painter: gfx.Painter, audio: sound.Audio, state: memory.StateFile, session: memory.Session, @@ -58,6 +61,9 @@ sketch: abi.Sketch, library: ?Library = null, watch: ?Watch = null, reloads: usize = 0, +/// Identifies the running build of the sketch (a hash of its library or +/// executable file): recordings carry it, and `play` warns on a mismatch. +build: u64 = 0, /// Copies of the sketch's info strings, replaced on every load. info_arena: std.heap.ArenaAllocator, name: []const u8 = "", @@ -73,6 +79,9 @@ canvas: [2]u32 = .{ 0, 0 }, cursor: abi.Cursor = .arrow, quit: bool = false, reloaded: bool = true, +/// For `Input.jumped`: state changed other than by `update` since the +/// last `draw` (a seek, a load, a `set`...). The first frame is one. +jumped: bool = true, started: bool = true, last_now: u64 = 0, /// Saved after the next frame is drawn (scripts). @@ -115,8 +124,10 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std std.log.warn("no GPU renderer ({s}); drawing without one", .{c.SDL_GetError()}); renderer = c.SDL_CreateRenderer(window, null) orelse return sdlError("SDL_CreateRenderer"); } - errdefer c.SDL_DestroyRenderer(renderer); + // Deferred in reverse: the renderer goes first, then the device it + // draws through (the other order crashed in SDL_DestroyRenderer). errdefer if (gpu) |device| c.SDL_DestroyGPUDevice(device); + errdefer c.SDL_DestroyRenderer(renderer); if (!options.headless) _ = c.SDL_SetRenderVSync(renderer, 1); // Colors carry alpha: fills blend, as they do on the web. _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND); @@ -142,6 +153,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std .renderer = renderer.?, .gpu = gpu, .images = .{ .gpa = gpa, .renderer = renderer.? }, + .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null }, .audio = .{ .gpa = gpa }, .state = state, .session = .init(gpa), @@ -154,6 +166,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std .frame_arena = .init(gpa), }; self.timeline = .{ .bank = .{ .state = &self.state, .inputs = recordings } }; + self.painter.images = &self.images; if (gpu) |device| self.passes = .init(gpa, device); if (options.profile_gpu) if (self.passes) |*g| { g.profile = .init(gpa); @@ -164,6 +177,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std }; self.setCanvas(info.width, info.height); _ = c.SDL_StartTextInput(self.window); + self.build = fileHash(options.library orelse "/proc/self/exe"); try self.adopt(sketch); if (options.fresh) { self.state.header().used = 0; @@ -177,6 +191,7 @@ pub fn deinit(self: *Host) void { if (self.watch) |w| w.deinit(); self.audio.deinit(); if (self.passes) |*g| g.deinit(&self.images); + self.painter.deinit(); self.images.deinit(); if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor); if (self.offscreen) |texture| c.SDL_DestroyTexture(texture); @@ -229,10 +244,10 @@ pub fn frame(self: *Host, now: u64) !void { .playing => self.update(h.tick(now)), .paused => {}, .live, .recording => { - try self.pending.append(self.gpa, .{ .kind = .tick, .time = now, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) }); - for (self.pending.items) |e| h.capture(e) catch |err| self.print("Recording stopped: {t}", .{err}); - self.input.now = now; - self.input.dt = dt; + // One frame: what was routed since the last one, then its tick. + // Recorded first, so `update` sees the times a replay will. + try self.pending.append(self.gpa, abi.Event.tick(now, dt)); + h.capture(self.pending.items) catch |err| self.print("Recording stopped: {t}", .{err}); self.update(self.pending.items); }, } @@ -240,26 +255,60 @@ pub fn frame(self: *Host, now: u64) !void { try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position); } -/// Feeds events to the sketch's deterministic `update`. +/// Feeds whole frames to the sketch's deterministic `update`, one call per +/// frame (events up to and including a tick), live or replayed alike. pub fn update(self: *Host, events: []const abi.Event) void { - // Input follows the events actually fed, live or replayed. - for (events) |e| self.input.track(e); - 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); + var frames = playback.frames(events); + while (frames.next()) |one| { + // Input follows the events actually fed, frame by frame. + for (one) |e| self.input.track(e); + const tick = one[one.len - 1]; + self.input.now = tick.time; + self.input.dt = tick.tickDt(); + self.input.events = one; + 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 = &.{}; } +/// After live state was restored from a snapshot: the pointer, buttons and +/// keys tracked so far belong to other bytes, so they start over. A new +/// recording then begins with events that bring back what is held now, so +/// its replay starts from the same input (they are fed and recorded as the +/// first frame's first events). +fn restoredInput(self: *Host, now: u64) !void { + const h = &self.timeline; + if (!h.restored) return; + h.restored = false; + const was = self.input; + self.input.mouse_x = 0; + self.input.mouse_y = 0; + self.input.buttons = 0; + self.input.keys = .empty; + if (h.mode != .recording or h.bank.recording(h.selected).count != 0) return; + var seed: std.ArrayList(abi.Event) = .empty; + defer seed.deinit(self.gpa); + if (was.mouse_x != 0 or was.mouse_y != 0) try seed.append(self.gpa, .{ .kind = .mouse_move, .time = now, .x = was.mouse_x, .y = was.mouse_y }); + for (0..32) |bit| if (was.buttons & (@as(u32, 1) << @intCast(bit)) != 0) { + try seed.append(self.gpa, .{ .kind = .mouse_down, .time = now, .x = was.mouse_x, .y = was.mouse_y, .code = @intCast(bit + 1) }); + }; + var keys = was.keys.iterator(.{}); + while (keys.next()) |key| try seed.append(self.gpa, .{ .kind = .key_down, .time = now, .code = @intCast(key) }); + try self.pending.insertSlice(self.gpa, 0, seed.items); +} + fn draw(self: *Host, now: u64) !void { const arena = self.frame_arena.allocator(); self.input.now = now; self.input.mode = self.timeline.mode; self.input.reloaded = self.reloaded; + self.input.jumped = self.jumped or self.reloaded; self.reloaded = false; + self.jumped = false; self.input.console = self.console.visible; self.input.width = @floatFromInt(self.canvas[0]); self.input.height = @floatFromInt(self.canvas[1]); @@ -286,9 +335,14 @@ fn draw(self: *Host, now: u64) !void { _ = c.SDL_SetRenderDrawColor(self.renderer, 0, 0, 0, 255); _ = c.SDL_RenderClear(self.renderer); self.audio.beginFrame(); + self.painter.begin(self.offscreen, self.canvas, arena); var lines: std.ArrayList([]const u8) = .empty; for (self.commands.items) |command| switch (command) { - .canvas => |size| self.setCanvas(size.w, size.h), + .canvas => |size| { + self.painter.end(); + self.setCanvas(size.w, size.h); + self.painter.begin(self.offscreen, self.canvas, arena); + }, .cursor => |kind| self.cursor = kind, .voice => |voice| self.audio.declare(voice), .audio => |a| self.audio.push(a.key, a.samples, a.clear), @@ -300,11 +354,11 @@ fn draw(self: *Host, now: u64) !void { .download => |d| if (self.passes) |*g| g.download(d) catch |err| self.print("gpu download: {t} ({s})", .{ err, c.SDL_GetError() }), .open_file => |o| self.openFile(o.command, o.pattern), .run => |line| try lines.append(arena, line), - else => gfx.draw(self.renderer, &self.images, command), + else => self.painter.draw(command), }; + self.painter.end(); self.audio.endFrame(); for (lines.items) |line| self.runLine(line, now) catch {}; - _ = c.SDL_SetRenderClipRect(self.renderer, null); var extra: std.ArrayList(abi.Command) = .empty; if (self.console.overlay_memory) try overlay.drawMemory(&extra, arena, self.state.layout, self.live(), self.input.width); @@ -313,7 +367,8 @@ fn draw(self: *Host, now: u64) !void { try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.canvas); } if (self.console.visible) try self.console.draw(self, &extra, arena); - for (extra.items) |command| gfx.draw(self.renderer, &self.images, command); + for (extra.items) |command| self.painter.draw(command); + self.painter.end(); self.applyCursor(); if (self.screenshot) |path| { @@ -432,11 +487,25 @@ 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.CommandFailed) self.console.print("{t}. Type help for usage.", .{err}); + if (self.timeline.restored) self.jumped = true; + try self.restoredInput(now); return err; }; + if (self.timeline.restored or movesState(line)) self.jumped = true; + try self.restoredInput(now); if (self.timeline.mode == .paused) self.update(replay); } +/// Whether a console line that succeeded may have changed State other than +/// through `update` (restoring a snapshot is caught apart from this). +fn movesState(line: []const u8) bool { + var words = std.mem.tokenizeAny(u8, line, " \t"); + const verb = words.next() orelse return false; + const still = [_][]const u8{ "help", "overlay", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" }; + for (still) |w| if (std.mem.eql(u8, verb, w)) return false; + return true; +} + /// Offers a line to the sketch. pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome { self.input.now = now; @@ -467,6 +536,7 @@ pub fn load(self: *Host, path: []const u8) !void { if (self.library) |*old| old.close(); self.library = library; self.reloads += 1; + self.build = fileHash(path); self.print("reload {d}: {s}", .{ self.reloads, path }); } @@ -636,6 +706,14 @@ fn consoleKey(e: abi.Event) ?Console.Key { }; } +/// A hash of a file's bytes; 0 when it cannot be read. +fn fileHash(path: []const u8) u64 { + const bytes = memory.mapReadOnly(path); + if (bytes.len == 0) return 0; + defer std.posix.munmap(bytes); + return std.hash.Wyhash.hash(0, bytes) | 1; +} + fn scratchDir(environ: *const std.process.Environ.Map) []const u8 { return environ.get("XDG_RUNTIME_DIR") orelse "/tmp"; } |
