diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 20:31:59 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-16 20:31:59 -0300 |
| commit | 82fca5c9f29124f37f6dcd08e73e6999ce44a69d (patch) | |
| tree | b3d5487659aa933d47699e5e420fa6140b0b75f3 /src/host/Host.zig | |
| parent | e77b01d4b5504cea08a3f88cf8502897d868a1d3 (diff) | |
| download | sketchbook-82fca5c9f29124f37f6dcd08e73e6999ce44a69d.tar.gz sketchbook-82fca5c9f29124f37f6dcd08e73e6999ce44a69d.zip | |
Add display-paced frame timing and presentation feedback in Zig
Diffstat (limited to 'src/host/Host.zig')
| -rw-r--r-- | src/host/Host.zig | 81 |
1 files changed, 77 insertions, 4 deletions
diff --git a/src/host/Host.zig b/src/host/Host.zig index 02a88c7..745d9a1 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -15,6 +15,9 @@ const sound = @import("audio.zig"); const Gpu = @import("gpu"); const overlay = @import("overlay.zig"); const Console = @import("Console.zig"); +const Timing = @import("Timing.zig"); +const Presentation = @import("Presentation.zig"); +const timing_marker = @import("timing_marker.zig"); const Control = @import("control.zig").Control; const Library = @import("library.zig").Library; const Watch = @import("library.zig").Watch; @@ -32,6 +35,8 @@ pub const Options = struct { fresh: bool = false, /// Time every GPU command alone and print the times at exit. profile_gpu: bool = false, + /// Binary frame/time marker for external video measurements. + timing_marker: bool = false, /// Export every frame: PNGs `<dir>/000000.png`, ..., or for "-" raw RGBA /// rows on stdout. Frames run on a clock of their own (see `fps`). export_to: ?[]const u8 = null, @@ -52,6 +57,7 @@ renderer: *c.SDL_Renderer, /// Runs sketches' GPU passes, and the 2D renderer draws through it too. /// Null when the machine has no usable GPU driver. gpu: ?*c.SDL_GPUDevice, +presentation: ?*Presentation = null, passes: ?Gpu = null, /// GPU canvas, shared by native/headless drawing, backdrop filters and screenshots. offscreen: ?*c.SDL_Texture = null, @@ -71,6 +77,8 @@ made: struct { images: std.ArrayList(abi.Image) = .empty, buffers: std.ArrayList recordings: []align(memory.page) u8, timeline: Timeline, console: Console = .{}, +timing: Timing = .{}, +timing_atlas: overlay.TimingAtlas = .{}, sketch: abi.Sketch, library: ?Library = null, watch: ?Watch = null, @@ -98,6 +106,7 @@ reloaded: bool = true, jumped: bool = true, started: bool = true, last_now: u64 = 0, +last_frame_end: u64 = 0, /// Saved after the next frame is drawn (scripts). screenshot: ?[:0]const u8 = null, /// Frames exported so far (`Options.export_to`). @@ -203,6 +212,10 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std @memset(self.recordings, 0); self.resetState(); } + if (!options.headless and options.export_to == null) { + self.presentation = Presentation.init(gpa, self.window) catch null; + if (options.timing_marker) self.print("presentation tracing: {s}", .{if (self.presentation) |p| p.status else "disabled_or_allocation_failed"}); + } } pub fn deinit(self: *Host) void { @@ -215,6 +228,7 @@ pub fn deinit(self: *Host) void { if (self.passes) |*g| g.deinit(); if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor); if (self.offscreen) |texture| c.SDL_DestroyTexture(texture); + if (self.presentation) |p| p.deinit(self.gpa); c.SDL_DestroyRenderer(self.renderer); if (self.gpu) |device| c.SDL_DestroyGPUDevice(device); c.SDL_DestroyWindow(self.window); @@ -244,11 +258,54 @@ pub fn run(self: *Host) !void { while (!self.quit) { if (self.control) |control| control.poll(self); try self.poll(); - try self.frame(if (self.options.export_to == null) c.SDL_GetTicksNS() else std.time.ns_per_s + self.exported * std.time.ns_per_s / self.options.fps); + if (self.presentation) |p| p.poll(); + if (!self.options.headless and self.options.export_to == null and + c.SDL_GetWindowFlags(self.window) & (c.SDL_WINDOW_OCCLUDED | c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_HIDDEN) != 0 and + self.screenshot == null and !(self.control != null and self.control.?.capture_pending)) + { + // Occluded Wayland presentation can block for a second; keep controls alive and resume without a camera jump. + self.last_now = 0; + self.last_frame_end = 0; + _ = c.SDL_Delay(10); + continue; + } + // GPU fences do not limit presentation rate; follow the measured display clock. + const wait_ns = if (self.presentation) |p| p.waitNs() else 0; + if (wait_ns != 0) { + c.SDL_DelayPrecise(@min(wait_ns, std.time.ns_per_ms)); + continue; + } + const wall = c.SDL_GetTicksNS(); + const now = if (self.options.export_to != null) + std.time.ns_per_s + self.exported * std.time.ns_per_s / self.options.fps + else + frameTime(wall, if (self.presentation) |p| p.sampleNs(wall) else wall, self.last_now, self.timeline.mode, self.pending.items); + try self.frame(now); } self.timeline.stop(c.SDL_GetTicksNS()); } +// Live animation uses the display clock, but a tick must not predate its input. +fn frameTime(wall: u64, scheduled: u64, previous: u64, mode: abi.Mode, events: []const abi.Event) u64 { + if (mode != .live and mode != .recording) return wall; + var now = @max(scheduled, previous); + for (events) |event| now = @max(now, event.time); + return now; +} + +test "timing clock drives ordinary ticks without moving input or replay time" { + const expectEqual = std.testing.expectEqual; + try expectEqual(@as(u64, 100), frameTime(103, 100, 80, .live, &.{})); + try expectEqual(@as(u64, 120), frameTime(127, 120, 100, .recording, &.{})); + const events = [_]abi.Event{ .{ .kind = .key_down, .time = 102 }, .{ .kind = .key_up, .time = 101 } }; + try expectEqual(@as(u64, 102), frameTime(103, 100, 80, .live, &events)); + try expectEqual(@as(u64, 102), events[0].time); + try expectEqual(@as(u64, 101), events[1].time); + try expectEqual(@as(u64, 103), frameTime(103, 103, 80, .live, &.{})); // No feedback. + try expectEqual(@as(u64, 110), frameTime(103, 100, 110, .live, &.{})); // Clock reversal. + for ([_]abi.Mode{ .playing, .paused }) |mode| try expectEqual(@as(u64, 103), frameTime(103, 100, 110, mode, &events)); +} + pub fn live(self: *Host) []u8 { return self.state.slot(0); } @@ -256,6 +313,7 @@ pub fn live(self: *Host) []u8 { /// One frame: reload if a build replaced the library, feed input through /// `update`, then `draw` and present. pub fn frame(self: *Host, now: u64) !void { + const started = c.SDL_GetTicksNS(); const zone = tracy.zone(@src(), "frame"); tracy.frameMark(); defer zone.end(); @@ -281,7 +339,10 @@ pub fn frame(self: *Host, now: u64) !void { }, } self.pending.clearRetainingCapacity(); - try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position); + const work = try self.draw(if (h.mode == .live or h.mode == .recording) now else h.position, started); + const ended = c.SDL_GetTicksNS(); + self.timing.add(.{ .frame = ended - (if (self.last_frame_end == 0) started else self.last_frame_end), .work = work }); + self.last_frame_end = ended; } /// Feeds whole frames to the sketch's deterministic `update`, one call per @@ -331,7 +392,7 @@ fn restoredInput(self: *Host, now: u64) !void { try self.pending.insertSlice(self.gpa, 0, seed.items); } -fn draw(self: *Host, now: u64) !void { +fn draw(self: *Host, now: u64, started: u64) !u64 { const zone = tracy.zone(@src(), "Host.zig:draw"); defer zone.end(); const arena = self.frame_arena.allocator(); @@ -405,7 +466,14 @@ fn draw(self: *Host, now: u64) !void { const samples = self.audio.scope.snapshot(); try overlay.drawScope(&extra, arena, &samples, self.audio.scope.rate, self.canvas); } + if (self.timing.visible) { + if (self.timing_atlas.image == .none) self.timing_atlas = try overlay.TimingAtlas.init(&self.images, &self.painter); + for (extra.items) |command| self.painter.draw(command); + extra.clearRetainingCapacity(); + try overlay.drawTiming(&self.painter, &self.timing, self.canvas, self.timing_atlas); + } if (self.console.visible) try self.console.draw(self, &extra, arena); + if (self.options.timing_marker) try timing_marker.draw(&extra, arena, self.canvas, self.input.frame, self.input.now); for (extra.items) |command| self.painter.draw(command); self.painter.end(); self.applyCursor(); @@ -425,10 +493,15 @@ fn draw(self: *Host, now: u64) !void { _ = c.SDL_SetTextureBlendMode(canvas, c.SDL_BLENDMODE_NONE); _ = c.SDL_RenderTexture(self.renderer, canvas, null, null); }; + // Present otherwise encodes the deferred 2D commands after the work timestamp. + if (!c.SDL_FlushRenderer(self.renderer)) return sdlError("SDL_FlushRenderer"); + const work = c.SDL_GetTicksNS() - started; const present_zone = tracy.zone(@src(), "present"); + if (self.presentation) |p| p.request(self.input.frame, self.input.now); _ = c.SDL_RenderPresent(self.renderer); present_zone.end(); if (self.passes) |*g| g.endFrame(); + return work; } /// One exported frame: `<to>/<its number, six digits>.png`, or for "-" its @@ -577,7 +650,7 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void { 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" }; + const still = [_][]const u8{ "help", "overlay", "timing", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit" }; for (still) |w| if (std.mem.eql(u8, verb, w)) return false; return true; } |
