From e77b01d4b5504cea08a3f88cf8502897d868a1d3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 16 Nov 2026 18:04:21 -0300 Subject: Add glTF scene rendering, resource setup and 9P controls --- src/host/Host.zig | 177 +++++++++++++- src/host/control.zig | 368 ++++++++++++++++++++++++++++ src/host/gfx.zig | 9 +- src/host/gpu.zig | 669 --------------------------------------------------- src/host/root.zig | 5 + 5 files changed, 548 insertions(+), 680 deletions(-) create mode 100644 src/host/control.zig delete mode 100644 src/host/gpu.zig (limited to 'src/host') diff --git a/src/host/Host.zig b/src/host/Host.zig index 008d143..02a88c7 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -12,15 +12,18 @@ const Timeline = playback.Timeline; const mapRecordings = playback.mapRecordings; const gfx = @import("gfx.zig"); const sound = @import("audio.zig"); -const Gpu = @import("gpu.zig"); +const Gpu = @import("gpu"); const overlay = @import("overlay.zig"); const Console = @import("Console.zig"); +const Control = @import("control.zig").Control; const Library = @import("library.zig").Library; const Watch = @import("library.zig").Watch; pub const Options = struct { /// A hot-reloaded sketch library. Unused when a sketch is linked in. library: ?[]const u8 = null, + /// Local 9P control socket, opt-in. + ninep: ?[]const u8 = null, /// State file; recordings go next to it with an `.inputs` suffix. state: []const u8 = "sketch.state", /// Offscreen video, silent audio, no vsync: for scripts and CI. @@ -59,6 +62,8 @@ painter: gfx.Painter, audio: sound.Audio, state: memory.StateFile, session: memory.Session, +/// A failed resource setup disables app callbacks while keeping host controls alive. +session_ready: bool = false, store: memory.StoreFile, /// Images and buffers the sketch made (`newImage`, `decodeImage`, /// `newBuffer`): Session holds their handles, so they go when it resets. @@ -98,6 +103,7 @@ screenshot: ?[:0]const u8 = null, /// Frames exported so far (`Options.export_to`). exported: u64 = 0, dialog: Dialog = .{}, +control: ?*Control = null, pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, options: Options, linked: ?abi.Sketch) !void { if (options.headless) { @@ -200,12 +206,13 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std } pub fn deinit(self: *Host) void { + if (self.control) |control| control.deinit(); self.dialog.deinit(); 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.passes) |*g| g.deinit(); if (self.pointer_cursor) |cursor| c.SDL_DestroyCursor(cursor); if (self.offscreen) |texture| c.SDL_DestroyTexture(texture); c.SDL_DestroyRenderer(self.renderer); @@ -233,7 +240,9 @@ pub fn deinit(self: *Host) void { /// The interactive loop. An export runs it on a clock of its own, frame k /// at k/fps seconds (from 1 s, as scripts do), whatever the wall clock says. pub fn run(self: *Host) !void { + if (self.options.ninep) |path| self.control = try Control.init(self.gpa, path); 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); } @@ -278,6 +287,7 @@ pub fn frame(self: *Host, now: u64) !void { /// 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 { + if (!self.session_ready) return; var frames = playback.frames(events); while (frames.next()) |one| { // Input follows the events actually fed, frame by frame. @@ -353,7 +363,7 @@ fn draw(self: *Host, now: u64) !void { self.input.downloads = if (self.passes) |*g| try g.collect(arena) else &.{}; self.input.frame += 1; const ctx = self.context(); - self.sketch.draw(&ctx, self.live().ptr); + if (self.session_ready) self.sketch.draw(&ctx, self.live().ptr); _ = c.SDL_SetRenderTarget(self.renderer, self.offscreen); _ = c.SDL_SetRenderClipRect(self.renderer, null); @@ -375,7 +385,7 @@ fn draw(self: *Host, now: u64) !void { .voice => |voice| self.audio.declare(voice), .audio => |a| self.audio.push(a.key, a.samples, a.clear), .quit => self.quit = true, - .gpu => |pass| if (self.passes) |*g| g.run(&self.images, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), + .gpu => |pass| if (self.passes) |*g| self.runGpu(g, pass) catch |err| self.print("gpu pass: {t} ({s})", .{ err, c.SDL_GetError() }), .upload => |u| if (self.passes) |*g| g.write(u.buffer, u.offset, u.bytes) catch |err| self.print("gpu upload: {t} ({s})", .{ err, c.SDL_GetError() }), .compute => |d| if (self.passes) |*g| g.compute(d) catch |err| self.print("gpu compute: {t} ({s})", .{ err, c.SDL_GetError() }), .microphone => self.audio.listen(), @@ -400,13 +410,14 @@ fn draw(self: *Host, now: u64) !void { self.painter.end(); self.applyCursor(); - if (self.screenshot != null or self.options.export_to != null) { + if (self.screenshot != null or self.options.export_to != null or (self.control != null and self.control.?.capture_pending)) { const surface = c.SDL_RenderReadPixels(self.renderer, null) orelse return sdlError("SDL_RenderReadPixels"); defer c.SDL_DestroySurface(surface); if (self.screenshot) |path| { self.screenshot = null; if (!c.SDL_SavePNG(surface, path.ptr)) return sdlError("SDL_SavePNG"); } + if (self.control) |control| if (control.capture_pending) control.capture(surface); if (self.options.export_to) |to| try self.exportFrame(surface, to); } if (!self.options.headless) if (self.offscreen) |canvas| { @@ -573,6 +584,10 @@ fn movesState(line: []const u8) bool { /// Offers a line to the sketch. pub fn forward(self: *Host, _: *Console, line: []const u8, now: u64) abi.Outcome { + if (!self.session_ready) { + self.print("session setup failed; restart after fixing the resource error", .{}); + return .failed; + } self.input.now = now; const ctx = self.context(); return self.sketch.command(&ctx, self.live().ptr, &line); @@ -626,6 +641,11 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void { .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 (session_reset) { + const ctx = self.context(); + self.session_ready = self.sketch.setup(&ctx); + if (!self.session_ready) self.console.visible = true; + } if (session_reset and self.reloads > 0) self.print("session layout changed: session reset", .{}); switch (stored) { .unchanged, .created => {}, @@ -636,7 +656,8 @@ fn adopt(self: *Host, sketch: abi.Sketch) !void { /// Frees what the old Session made: its handles are gone with it. fn releaseMade(self: *Host) void { for (self.made.images.items) |image| { - if (self.passes) |*g| g.forget(&self.images, image); + self.images.unwrap(image); + if (self.passes) |*g| g.forget(image); self.images.free(image); } if (self.passes) |*g| for (self.made.buffers.items) |buffer| g.freeBuffer(buffer); @@ -800,6 +821,7 @@ const api: abi.Host.VTable = .{ .gpu = apiGpu, .newBuffer = apiNewBuffer, .freeBuffer = apiFreeBuffer, + .writeBuffer = apiWriteBuffer, .imageSize = apiImageSize, .textSize = apiTextSize, .loadSound = apiLoadSound, @@ -830,7 +852,8 @@ fn apiNewImage(ctx: *anyopaque, w: u32, h: u32) abi.Image { fn apiFreeImage(ctx: *anyopaque, image: abi.Image) void { const self = hostOf(ctx); forget(&self.made.images, image); - if (self.passes) |*g| g.forget(&self.images, image); + self.images.unwrap(image); + if (self.passes) |*g| g.forget(image); self.images.free(image); } fn apiGpu(ctx: *anyopaque) bool { @@ -838,12 +861,17 @@ fn apiGpu(ctx: *anyopaque) bool { } fn apiNewBuffer(ctx: *anyopaque, size: u32) abi.Buffer { const self = hostOf(ctx); - const g = &(self.passes orelse return .none); + const g = if (self.passes) |*passes| passes else return .none; return self.remember(.buffers, g.newBuffer(size) catch |err| blk: { self.print("gpu buffer: {t} ({s})", .{ err, c.SDL_GetError() }); break :blk .none; }); } +fn apiWriteBuffer(ctx: *anyopaque, buffer: abi.Buffer, offset: u32, bytes: []const u8) !void { + const self = hostOf(ctx); + const gpu = if (self.passes) |*passes| passes else return error.GpuUnavailable; + try gpu.write(buffer, offset, bytes); +} fn apiFreeBuffer(ctx: *anyopaque, buffer: abi.Buffer) void { const self = hostOf(ctx); forget(&self.made.buffers, buffer); @@ -879,3 +907,136 @@ fn apiClock(_: *anyopaque) u64 { fn apiEnv(ctx: *anyopaque, name: []const u8) ?[]const u8 { return hostOf(ctx).environ.get(name); } + +fn runGpu(self: *Host, g: *Gpu, pass: abi.gpu.Pass) !void { + const before = g.output(pass.image); + const changed = if (before) |t| t.width != pass.width or t.height != pass.height else true; + if (changed) self.images.unwrap(pass.image); + try g.run(pass); + if (g.output(pass.image)) |t| try self.images.wrap(pass.image, t.texture, t.width, t.height); +} + +test "session setup runs for restored state and layout reset, not same-layout reload or state reset" { + const Fixture = struct { + const State = extern struct { value: u32 = 1 }; + const Session1 = extern struct { ready: u32 = 0 }; + const Session2 = extern struct { ready: u32 = 0, extra: u32 = 0 }; + const Store = struct {}; + var setup_calls: usize = 0; + var init_calls: usize = 0; + var fail_setup = false; + const description: abi.Info = .{ .abi = abi.hash, .name = "setup-test", .width = 1, .height = 1, .state = abi.layout.of(State, .state), .session = abi.layout.of(Session1, .session), .store = abi.layout.of(Store, .store) }; + const changed: abi.Info = blk: { + var value = description; + value.session = abi.layout.of(Session2, .session); + break :blk value; + }; + fn info() callconv(.c) *const abi.Info { + return &description; + } + fn info2() callconv(.c) *const abi.Info { + return &changed; + } + fn defaults(kind: abi.Memory, ptr: [*]u8) callconv(.c) void { + switch (kind) { + .state => @as(*State, @ptrCast(@alignCast(ptr))).* = .{}, + .session => @as(*Session1, @ptrCast(@alignCast(ptr))).* = .{}, + .store => {}, + } + } + fn defaults2(kind: abi.Memory, ptr: [*]u8) callconv(.c) void { + if (kind == .session) @as(*Session2, @ptrCast(@alignCast(ptr))).* = .{} else defaults(kind, ptr); + } + fn init(_: *const abi.Context, _: [*]u8) callconv(.c) void { + init_calls += 1; + } + fn setup(ctx: *const abi.Context) callconv(.c) bool { + setup_calls += 1; + @as(*u32, @ptrCast(@alignCast(ctx.session_root))).* += 1; + return !fail_setup; + } + fn update(_: *const abi.Context, _: [*]u8) callconv(.c) void {} + fn draw(_: *const abi.Context, _: [*]const u8) callconv(.c) void {} + fn command(_: *const abi.Context, _: [*]u8, _: *const []const u8) callconv(.c) abi.Outcome { + return .unknown; + } + const sketch: abi.Sketch = .{ .info = info, .defaults = defaults, .init = @This().init, .setup = setup, .update = @This().update, .draw = @This().draw, .command = command }; + }; + Fixture.setup_calls = 0; + 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; + var store_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}); + const store_path = try std.mem.print(&store_buf, ".zig-cache/tmp/{s}/setup.store", .{&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. + var host: Host = undefined; + host.gpa = a; + host.state = try memory.StateFile.open(a, state_path); + defer host.state.close(); + host.store = try memory.StoreFile.open(a, store_path, false); + defer host.store.close(); + host.session = .init(a); + defer host.session.deinit(a); + host.info_arena = .init(a); + defer host.info_arena.deinit(); + host.frame_arena = .init(a); + defer host.frame_arena.deinit(); + host.options = .{ .headless = true }; + host.console = .{}; + host.reloads = 0; + host.made = .{}; + host.passes = null; + 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); + 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; + try host.adopt(Fixture.sketch); + try std.testing.expectEqual(session_ptr, host.session.bytes.ptr); + try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); + host.resetState(); + try std.testing.expectEqual(@as(usize, 1), Fixture.init_calls); + try std.testing.expectEqual(@as(usize, 1), Fixture.setup_calls); + var changed = Fixture.sketch; + changed.info = Fixture.info2; + changed.defaults = Fixture.defaults2; + try host.adopt(changed); + try std.testing.expectEqual(@as(usize, 2), Fixture.setup_calls); + try std.testing.expectEqual(@as(u32, 1), @as(*Fixture.Session2, @ptrCast(host.session.bytes.ptr)).ready); + try std.testing.expect(host.session_ready); + Fixture.fail_setup = true; + defer Fixture.fail_setup = false; + try host.adopt(Fixture.sketch); + try std.testing.expect(!host.session_ready); + try std.testing.expect(host.console.visible); + try std.testing.expectEqual(abi.Outcome.failed, host.forward(&host.console, "anything", 0)); + try host.adopt(Fixture.sketch); + try std.testing.expect(!host.session_ready); // A compatible reload cannot bless partial resources. + try std.testing.expectEqual(@as(usize, 3), Fixture.setup_calls); +} + +test "setup writeBuffer propagates unavailable, unknown and out-of-bounds upload errors" { + const a = std.testing.allocator; + var host: Host = undefined; + host.passes = null; + const client: abi.Host = .{ .ctx = &host, .vtable = &api }; + try std.testing.expectError(error.GpuUnavailable, client.writeBuffer(.none, 0, "data")); + host.passes = .{ .gpa = a, .device = undefined, .stencil_format = undefined }; + defer host.passes.?.buffers.deinit(a); + try std.testing.expectError(error.UnknownBuffer, client.writeBuffer(.none, 0, "data")); + try host.passes.?.buffers.append(a, .{ .buffer = undefined, .size = 4 }); + try std.testing.expectError(error.UploadOutOfBounds, client.writeBuffer(@fromBackingInt(@intCast(1)), 2, "data")); +} diff --git a/src/host/control.zig b/src/host/control.zig new file mode 100644 index 0000000..58b41b3 --- /dev/null +++ b/src/host/control.zig @@ -0,0 +1,368 @@ +//! Local 9P controls, serviced on the frame thread: no SDL or state races. +const std = @import("std"); +const c9 = @import("cloud9"); +const c = @import("c"); +const Host = @import("Host.zig"); +const fs = c9.fs; +const transport = c9.transport; +const Backend = struct { + pub const Req = fs.Req; + pub const Reply = fs.Reply; +}; +const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4 }); +const msize = 16384; +const names = [_][]const u8{ "/", "ctl", "status", "log", "screen.png", "profile", "profile-trace" }; + +const Connection = struct { + fd: c_int = -1, + server: Server = undefined, + input: [msize]u8 = undefined, + output: [msize * 2]u8 = undefined, + incoming: [msize]u8 = undefined, + used: usize = 0, + snapshots: [32]?[]u8 = @splat(null), + + fn close(self: *Connection, a: std.mem.Allocator) void { + if (self.fd < 0) return; + transport.close(self.fd); + for (&self.snapshots) |*snapshot| if (snapshot.*) |bytes| { + a.free(bytes); + snapshot.* = null; + }; + self.fd = -1; + } +}; + +pub const Control = struct { + allocator: std.mem.Allocator, + path: [:0]u8, + listener: c_int, + connections: [4]Connection = @splat(.{}), + png: []u8 = &.{}, + capture_pending: bool = false, + generation: u64 = 0, + capture_error: ?anyerror = null, + + pub fn init(a: std.mem.Allocator, path: []const u8) !*Control { + const self = try a.create(Control); + errdefer a.destroy(self); + const z = try a.dupeSentinel(u8, path, 0); + errdefer a.free(z); + // Refuse an existing path; never unlink another process's socket. + const fd = try transport.listenFd(.{ .unix = z }, 4); + errdefer { + transport.close(fd); + _ = std.c.unlink(z); + } + if (std.c.chmod(z, 0o600) != 0) return error.SocketPermissions; + self.* = .{ .allocator = a, .path = z, .listener = fd }; + return self; + } + + pub fn deinit(self: *Control) void { + for (&self.connections) |*conn| conn.close(self.allocator); + transport.close(self.listener); + _ = std.c.unlink(self.path); + self.allocator.free(self.path); + self.allocator.free(self.png); + self.allocator.destroy(self); + } + + pub fn poll(self: *Control, host: *Host) void { + if (transport.acceptFd(self.listener, false) catch null) |fd| { + var accepted = false; + for (&self.connections) |*conn| if (conn.fd < 0) { + conn.fd = fd; + conn.used = 0; + conn.server = .init(.{ .in = &conn.input, .out = &conn.output, .root = 1 }); + accepted = true; + break; + }; + if (!accepted) transport.close(fd); + } + for (&self.connections) |*conn| { + if (conn.fd < 0) continue; + self.service(host, conn) catch conn.close(self.allocator); + } + } + + fn service(self: *Control, host: *Host, conn: *Connection) !void { + // Bound work per frame, including clients which continually write. + for (0..32) |_| { + var progressed = false; + if (conn.used != 0) { + const consumed = conn.server.push(conn.incoming[0..conn.used]); + std.mem.copyForwards(u8, &conn.incoming, conn.incoming[consumed..conn.used]); + conn.used -= consumed; + progressed = consumed != 0; + } + while (conn.server.next()) |req| self.answer(host, conn, req); + if (conn.server.protocol.dead) return error.Closed; + if (conn.server.output().len > 0) { + if (try transport.write(conn.fd, conn.server.output())) |n| { + if (n == 0) return error.Closed; + conn.server.wrote(n); + progressed = true; + } + } + if (conn.used < conn.incoming.len) { + if (try transport.read(conn.fd, conn.incoming[conn.used..])) |n| { + if (n == 0) return error.Closed; + conn.used += n; + progressed = true; + } + } + if (!progressed) break; + } + } + + fn answer(self: *Control, host: *Host, conn: *Connection, req: fs.Req) void { + var reply: fs.Reply = .{ .tag = req.tag }; + var buffer: [msize]u8 = undefined; + const bytes = self.respond(host, conn, req, &reply, &buffer) catch |err| blk: { + reply = .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = @errorName(err) }; + break :blk &.{}; + }; + conn.server.reply(&reply, bytes); + } + + fn respond(self: *Control, host: *Host, conn: *Connection, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 { + if (req.node < 1 or req.node > names.len) return error.UnknownFile; + switch (req.op) { + .lookup => { + if (req.node != 1) return error.NotDirectory; + for (names[1..], 2..) |name, node| if (std.mem.eql(u8, name, req.data)) { + reply.attr = self.attr(node); + return &.{}; + }; + return error.UnknownFile; + }, + .getattr => reply.attr = self.attr(req.node), + .open => { + if (req.node == 5 or req.node == 7) { + if (req.node == 5) { + if (self.capture_pending) return error.CapturePending; + if (self.capture_error) |err| return err; + if (self.png.len == 0) return error.CaptureScreenshotFirst; + } + for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) { + slot.* = if (req.node == 5) try self.allocator.dupe(u8, self.png) else try self.trace(host); + reply.handle = @intCast(handle); + return &.{}; + }; + return error.TooManySnapshots; + } + }, + .release => if (req.opened and req.handle > 0 and req.handle <= conn.snapshots.len) { + const slot = &conn.snapshots[req.handle - 1]; + if (slot.*) |bytes| self.allocator.free(bytes); + slot.* = null; + }, + .readdir => { + if (req.node != 1) return error.NotDirectory; + var used: usize = 0; + for (names[1..], 0..) |name, index| { + if (index < req.off) continue; + std.mem.writeInt(u64, buffer[used..][0..8], index + 2, .little); + buffer[used + 8] = 0; + buffer[used + 9] = @intCast(name.len); + @memcpy(buffer[used + 10 ..][0..name.len], name); + used += 10 + name.len; + } + return buffer[0..used]; + }, + .read => { + var writer: std.Io.Writer = .fixed(buffer); + const bytes: []const u8 = switch (req.node) { + 2 => "Write one console command per line. screenshot captures the next frame.\n", + 3 => blk: { + try writer.print("name {s}\nsize {d} {d}\nmode {t}\ngpu {s}\nscreenshot_pending {}\nscreenshot_generation {d}\nscreenshot_error {s}\n", .{ host.name, host.canvas[0], host.canvas[1], host.timeline.mode, if (host.gpu != null) "yes" else "no", self.capture_pending, self.generation, if (self.capture_error) |err| @errorName(err) else "none" }); + break :blk writer.buffered(); + }, + 4 => blk: { + for (host.console.lines) |line| { + try writer.writeAll(line.bytes[0..line.len]); + try writer.writeByte('\n'); + } + break :blk writer.buffered(); + }, + 5, 7 => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle, + 6 => blk: { + const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled; + const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled; + try writer.print("# CPU wall milliseconds including GPU submission and fence wait; not hardware timestamps\n# frames {d}\nlabel\tcount\tmean_ms\tworst_ms\tp95_ms\tp99_ms\n", .{gpu.frame - profile.start_frame}); + var entries = profile.entries.iterator(); + while (entries.next()) |entry| { + const value = entry.value_ptr; + const percentiles = value.percentiles(); + const count: f64 = @floatFromInt(@max(value.count, 1)); + try writer.print("{s}\t{d}\t{d:.6}\t{d:.6}\t{d:.6}\t{d:.6}\n", .{ entry.key_ptr.*, value.count, @as(f64, @floatFromInt(value.total)) / count / std.time.ns_per_ms, @as(f64, @floatFromInt(value.worst)) / std.time.ns_per_ms, @as(f64, @floatFromInt(percentiles[0])) / std.time.ns_per_ms, @as(f64, @floatFromInt(percentiles[1])) / std.time.ns_per_ms }); + } + break :blk writer.buffered(); + }, + else => return error.NotFile, + }; + return window(bytes, req.off, req.size); + }, + .write => { + if (req.node != 2) return error.ReadOnly; + if (req.data.len > 4096 or std.mem.indexOfScalar(u8, req.data, 0) != null) return error.InvalidCommand; + var lines = std.mem.tokenizeScalar(u8, req.data, '\n'); + while (lines.next()) |raw| { + const line = std.mem.trim(u8, raw, " \t\r"); + if (std.mem.eql(u8, line, "screenshot")) { + self.capture_pending = true; + self.capture_error = null; + } else if (std.mem.eql(u8, line, "profile-reset")) { + const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled; + const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled; + for (profile.entries.values()) |*entry| entry.* = .{}; + profile.start_frame = gpu.frame; + } else try host.runLine(line, c.SDL_GetTicksNS()); + } + reply.written = @intCast(req.data.len); + }, + .setattr => { + if (req.node != 2 or !req.truncate) return error.ReadOnly; + reply.attr = self.attr(req.node); + }, + } + return &.{}; + } + + fn trace(self: *Control, host: *Host) ![]u8 { + const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled; + const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled; + const buffer = try self.allocator.alloc(u8, 256 << 10); + defer self.allocator.free(buffer); + var writer: std.Io.Writer = .fixed(buffer); + try writer.writeAll("label,sample,ns\n"); + var entries = profile.entries.iterator(); + while (entries.next()) |entry| { + const value = entry.value_ptr; + for (0..value.retained()) |i| { + try writer.writeByte('"'); + for (entry.key_ptr.*) |ch| { + if (ch == '"') try writer.writeByte('"'); + try writer.writeByte(ch); + } + try writer.print("\",{d},{d}\n", .{ value.count - value.retained() + i + 1, value.sample(i) }); + } + } + return self.allocator.dupe(u8, writer.buffered()); + } + + fn attr(self: *Control, node: u64) fs.Attr { + return .{ .name = names[@intCast(node - 1)], .node = node, .dir = node == 1, .mode = if (node == 1) 0o700 else if (node == 2) 0o600 else 0o400, .size = if (node == 5) self.png.len else 0, .version = if (node == 5) @truncate(self.generation) else 0 }; + } + + pub fn capture(self: *Control, surface: *c.SDL_Surface) void { + self.capture_pending = false; + self.save(surface) catch |err| { + self.capture_error = err; + }; + } + + fn save(self: *Control, surface: *c.SDL_Surface) !void { + const stream = c.SDL_IOFromDynamicMem() orelse return error.CaptureStream; + defer _ = c.SDL_CloseIO(stream); + if (!c.SDL_SavePNG_IO(surface, stream, false)) return error.EncodePng; + const size = c.SDL_GetIOSize(stream); + if (size <= 0) return error.EncodePng; + const pointer = c.SDL_GetPointerProperty(c.SDL_GetIOProperties(stream), c.SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER, null) orelse return error.EncodePng; + const png = try self.allocator.dupe(u8, @as([*]const u8, @ptrCast(pointer))[0..@intCast(size)]); + self.allocator.free(self.png); + self.png = png; + self.generation += 1; + } +}; + +fn window(bytes: []const u8, offset: u64, count: u32) []const u8 { + if (offset >= bytes.len) return &.{}; + const start: usize = @intCast(offset); + return bytes[start..][0..@min(count, bytes.len - start)]; +} + +test "9P reads respect offsets, counts and EOF" { + try std.testing.expectEqualStrings("cd", window("abcdef", 2, 2)); + try std.testing.expectEqualStrings("ef", window("abcdef", 4, 200)); + try std.testing.expectEqualStrings("", window("abcdef", std.math.maxInt(u64), 10)); +} + +test "control writes validate and screenshot opens pin an immutable snapshot" { + const a = std.testing.allocator; + var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 }; + var host: Host = undefined; // These backend operations do not access the host. + var conn: Connection = .{}; + var reply: fs.Reply = .{ .tag = 1 }; + var buf: [256]u8 = undefined; + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .setattr, .node = 2, .truncate = true }, &reply, &buf); + try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 3, .data = "screenshot" }, &reply, &buf)); + try std.testing.expectError(error.InvalidCommand, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "screenshot\x00" }, &reply, &buf)); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "screenshot\n" }, &reply, &buf); + try std.testing.expect(control.capture_pending); + try std.testing.expectError(error.CapturePending, control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 5 }, &reply, &buf)); + control.capture_pending = false; + control.png = try a.dupe(u8, "first image"); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 5 }, &reply, &buf); + const handle = reply.handle; + a.free(control.png); + control.png = try a.dupe(u8, "second image"); + defer a.free(control.png); + const bytes = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 5, .handle = handle, .size = 100 }, &reply, &buf); + try std.testing.expectEqualStrings("first image", bytes); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 5, .handle = handle, .opened = true }, &reply, &buf); + try std.testing.expect(conn.snapshots[handle - 1] == null); +} + +test "control writes reset profiling counters while retaining labels" { + const a = std.testing.allocator; + var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 }; + var host: Host = undefined; + host.passes = null; + var conn: Connection = .{}; + var reply: fs.Reply = .{ .tag = 1 }; + var buf: [512]u8 = undefined; + const reset: fs.Req = .{ .tag = 1, .op = .write, .node = 2, .data = "profile-reset\n" }; + try std.testing.expectError(error.ProfilingDisabled, control.respond(&host, &conn, reset, &reply, &buf)); + host.passes = @as(@import("gpu"), undefined); + const gpu = &host.passes.?; + gpu.profile = .init(a); + defer gpu.profile.?.deinit(); + const profile = &gpu.profile.?; + try profile.entries.put(profile.arena.allocator(), "scene", .{}); + profile.entries.values()[0].add(400_000); + profile.entries.values()[0].add(600_000); + gpu.frame = 420; + const read: fs.Req = .{ .tag = 1, .op = .read, .node = 6, .size = buf.len }; + const before = try control.respond(&host, &conn, read, &reply, &buf); + try std.testing.expect(std.mem.indexOf(u8, before, "scene\t2\t0.500000\t0.600000") != null); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 7 }, &reply, &buf); + const trace_handle = reply.handle; + _ = try control.respond(&host, &conn, reset, &reply, &buf); + const trace = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 7, .handle = trace_handle, .size = 100 }, &reply, &buf); + try std.testing.expectEqualStrings("label,sample,ns\n\"scene\",1,400000\n\"scene\",2,600000\n", trace); + _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 7, .handle = trace_handle, .opened = true }, &reply, &buf); + try std.testing.expect(conn.snapshots[trace_handle - 1] == null); + try std.testing.expectEqual(@as(usize, 1), profile.entries.count()); + try std.testing.expectEqual(@as(u64, 0), profile.entries.values()[0].total); + try std.testing.expectEqual(@as(u64, 420), profile.start_frame); + const after = try control.respond(&host, &conn, read, &reply, &buf); + try std.testing.expect(std.mem.indexOf(u8, after, "# frames 0") != null); + try std.testing.expect(std.mem.indexOf(u8, after, "scene\t0\t0.000000\t0.000000") != null); +} + +test "control writes profiling ring retains latest samples and nearest rank percentiles" { + var entry: @import("gpu").Profile.Entry = .{}; + for (1..4100) |ns| entry.add(ns); + try std.testing.expectEqual(@as(u64, 4099), entry.count); + try std.testing.expectEqual(@as(usize, 2048), entry.retained()); + try std.testing.expectEqual(@as(u64, 2052), entry.sample(0)); + try std.testing.expectEqual(@as(u64, 4099), entry.sample(2047)); + try std.testing.expectEqual([2]u64{ 3997, 4079 }, entry.percentiles()); + entry = .{}; + try std.testing.expectEqual(@as(usize, 0), entry.retained()); + try std.testing.expectEqual([2]u64{ 0, 0 }, entry.percentiles()); + entry.add(20); + try std.testing.expectEqual([2]u64{ 20, 20 }, entry.percentiles()); +} diff --git a/src/host/gfx.zig b/src/host/gfx.zig index a7ebd05..fef58c3 100644 --- a/src/host/gfx.zig +++ b/src/host/gfx.zig @@ -12,6 +12,7 @@ pub const Images = struct { const Entry = struct { texture: ?*c.SDL_Texture = null, + gpu_texture: ?*anyopaque = null, w: u32 = 0, h: u32 = 0, /// Holds premultiplied colour: a target drawn into, a GPU pass's @@ -79,6 +80,7 @@ pub const Images = struct { /// Makes `image` show a GPU render target (GPU renderer only). pub fn wrap(self: *Images, image: abi.Image, gpu_texture: *anyopaque, w: u32, h: u32) !void { const entry = self.get(image) orelse return error.UnknownImage; + if (entry.gpu_texture == gpu_texture) return; const props = c.SDL_CreateProperties(); defer c.SDL_DestroyProperties(props); _ = c.SDL_SetPointerProperty(props, c.SDL_PROP_TEXTURE_CREATE_GPU_TEXTURE_POINTER, gpu_texture); @@ -89,7 +91,7 @@ pub const Images = struct { // Rendered output: smooth scaling, and already premultiplied. _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_LINEAR); entry.release(); - entry.* = .{ .texture = texture, .w = w, .h = h, .premultiplied = true, .smooth = true }; + entry.* = .{ .texture = texture, .w = w, .h = h, .premultiplied = true, .smooth = true, .gpu_texture = gpu_texture }; } /// Stops showing a wrapped render target, before the target goes away. @@ -97,6 +99,7 @@ pub const Images = struct { const entry = self.get(image) orelse return; if (entry.texture) |t| c.SDL_DestroyTexture(t); entry.texture = null; + entry.gpu_texture = null; } pub fn free(self: *Images, image: abi.Image) void { @@ -591,7 +594,7 @@ fn fcolor(color: abi.Color) c.SDL_FColor { /// Native shaped text on Linux, using a 13px monospace face at scale 1. /// Other targets retain SDL's built-in 8x8 fallback. Coordinates are line-box tops. pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []const u8, color: abi.Color, face: abi.Face, raster: f32) void { - if (@import("builtin").os.tag == .linux and c.sk_text_draw_scaled(renderer, @intFromEnum(face), x, y, scale, raster, bytes.ptr, bytes.len, color.r, color.g, color.b, color.a)) return; + if (@import("builtin").os.tag == .linux and c.sk_text_draw_scaled(renderer, @backingInt(face), x, y, scale, raster, bytes.ptr, bytes.len, color.r, color.g, color.b, color.a)) return; var buf: [1024]u8 = undefined; const len = @min(std.mem.indexOfScalar(u8, bytes, 0) orelse bytes.len, buf.len - 1); @memcpy(buf[0..len], bytes[0..len]); @@ -623,7 +626,7 @@ pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: [] /// its line, in canvas units (`Host.textSize`). pub fn textSize(renderer: *c.SDL_Renderer, scale: f32, bytes: []const u8, face: abi.Face) [2]f32 { var size: [2]f32 = .{ 0, 0 }; - if (@import("builtin").os.tag == .linux and c.sk_text_measure_face(renderer, @intFromEnum(face), scale, bytes.ptr, bytes.len, &size[0], &size[1])) return size; + if (@import("builtin").os.tag == .linux and c.sk_text_measure_face(renderer, @backingInt(face), scale, bytes.ptr, bytes.len, &size[0], &size[1])) return size; // The debug font's 8 px cells. const s = @max(scale, 1); return .{ @as(f32, @floatFromInt(bytes.len)) * 8 * s, 8 * s }; diff --git a/src/host/gpu.zig b/src/host/gpu.zig deleted file mode 100644 index 94b2e39..0000000 --- a/src/host/gpu.zig +++ /dev/null @@ -1,669 +0,0 @@ -//! Runs `abi.gpu` passes and dispatches with SDL_GPU: the translation from -//! GPU work as data to a real API. Shaders and pipelines are built on first -//! use and cached by the hash of their description; entries a sketch stops -//! using (an edited shader, after a reload) are released after a while. -const Gpu = @This(); -const std = @import("std"); -const c = @import("c"); -const abi = @import("abi"); -const gfx = @import("gfx.zig"); - -pub const color_format = c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM; -/// Frames an unused shader or pipeline survives. -const keep_frames = 300; - -gpa: std.mem.Allocator, -device: *c.SDL_GPUDevice, -stencil_format: c.SDL_GPUTextureFormat, -shaders: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUShader)) = .empty, -pipelines: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUGraphicsPipeline)) = .empty, -kernels: std.AutoHashMapUnmanaged(u64, Cached(c.SDL_GPUComputePipeline)) = .empty, -/// Storage buffers by handle: `Buffer` n is `buffers[n - 1]`, null once freed. -buffers: std.ArrayList(?Storage) = .empty, -/// Uploads to storage buffers go through this, in chunks of its size. -staging: ?*c.SDL_GPUTransferBuffer = null, -/// Render targets per image: the resolved texture the renderer shows, and -/// multisampled and stencil attachments as passes ask for them. -targets: std.AutoHashMapUnmanaged(abi.Image, Target) = .empty, -vertices: ?*c.SDL_GPUBuffer = null, -vertex_capacity: u32 = 0, -upload: ?*c.SDL_GPUTransferBuffer = null, -upload_capacity: u32 = 0, -frame: u64 = 0, -/// Set by `--profile-gpu`: every command is timed alone (see `Profile`). -profile: ?Profile = null, -/// Downloads in flight, oldest first, and transfer buffers to reuse. -downloads: std.ArrayList(Download) = .empty, -spare: std.ArrayList(Transfer) = .empty, - -const Transfer = struct { buffer: *c.SDL_GPUTransferBuffer, size: u32 }; -const Download = struct { key: u32, size: u32, transfer: Transfer, fence: *c.SDL_GPUFence }; - -/// GPU time per labelled command. Each command starts on an idle GPU and is -/// waited for, so its time is its own: the total of a frame is what the -/// GPU spends on it, though the waiting makes the frame itself slower. -pub const Profile = struct { - entries: std.StringArrayHashMapUnmanaged(Entry) = .empty, - arena: std.heap.ArenaAllocator, - - const Entry = struct { count: u64 = 0, total: u64 = 0, worst: u64 = 0 }; - - pub fn init(gpa: std.mem.Allocator) Profile { - return .{ .arena = .init(gpa) }; - } - - pub fn deinit(p: *Profile) void { - p.arena.deinit(); - } - - fn add(p: *Profile, label: []const u8, ns: u64) void { - const a = p.arena.allocator(); - const entry = p.entries.getOrPut(a, label) catch return; - if (!entry.found_existing) { - entry.key_ptr.* = a.dupe(u8, label) catch "?"; - entry.value_ptr.* = .{}; - } - entry.value_ptr.count += 1; - entry.value_ptr.total += ns; - entry.value_ptr.worst = @max(entry.value_ptr.worst, ns); - } - - pub fn report(p: *Profile, frames: u64) void { - std.debug.print("gpu time over {d} frames (ms)\n{s: <24} {s: >7} {s: >9} {s: >9} {s: >11}\n", .{ frames, "command", "count", "mean", "worst", "per frame" }); - var sum: u64 = 0; - var it = p.entries.iterator(); - while (it.next()) |e| { - const v = e.value_ptr.*; - sum += v.total; - std.debug.print("{s: <24} {d: >7} {d: >9.3} {d: >9.3} {d: >11.3}\n", .{ e.key_ptr.*, v.count, ms(v.total) / @as(f64, @floatFromInt(v.count)), ms(v.worst), ms(v.total) / @as(f64, @floatFromInt(@max(frames, 1))) }); - } - std.debug.print("{s: <24} {s: >7} {s: >9} {s: >9} {d: >11.3}\n", .{ "all", "", "", "", ms(sum) / @as(f64, @floatFromInt(@max(frames, 1))) }); - } - - fn ms(ns: u64) f64 { - return @as(f64, @floatFromInt(ns)) / std.time.ns_per_ms; - } -}; - -/// Submits `cmd`; when profiling, waits for it and books its time from -/// `start` (taken on an idle GPU, before recording) under `label`. -fn submit(g: *Gpu, cmd: *c.SDL_GPUCommandBuffer, label: []const u8, start: u64) !void { - const p = &(g.profile orelse { - if (!c.SDL_SubmitGPUCommandBuffer(cmd)) return error.GpuSubmit; - return; - }); - const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; - defer c.SDL_ReleaseGPUFence(g.device, fence); - _ = c.SDL_WaitForGPUFences(g.device, true, &fence, 1); - p.add(label, c.SDL_GetTicksNS() - start); -} - -/// When profiling: waits for the GPU to be idle, then the time to start from. -fn startTiming(g: *Gpu) u64 { - if (g.profile != null) _ = c.SDL_WaitForGPUIdle(g.device); - return c.SDL_GetTicksNS(); -} - -/// The most bytes one buffer upload stages at a time. -const staging_size = 4 << 20; - -fn Cached(comptime T: type) type { - return struct { object: *T, used: u64 }; -} - -const Storage = struct { buffer: *c.SDL_GPUBuffer, size: u32 }; - -const Target = struct { - width: u32, - height: u32, - texture: *c.SDL_GPUTexture, - samples: u8 = 1, - msaa: ?*c.SDL_GPUTexture = null, - /// Not rendered into yet: undefined natively, so the first pass that - /// would load clears to zero (WebGPU's starting contents). - fresh: bool = true, - msaa_fresh: bool = true, - stencil_samples: u8 = 0, - stencil: ?*c.SDL_GPUTexture = null, -}; - -pub fn init(gpa: std.mem.Allocator, device: *c.SDL_GPUDevice) Gpu { - const d24 = c.SDL_GPUTextureSupportsFormat(device, c.SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT, c.SDL_GPU_TEXTURETYPE_2D, c.SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET); - return .{ - .gpa = gpa, - .device = device, - .stencil_format = if (d24) c.SDL_GPU_TEXTUREFORMAT_D24_UNORM_S8_UINT else c.SDL_GPU_TEXTUREFORMAT_D32_FLOAT_S8_UINT, - }; -} - -pub fn deinit(g: *Gpu, images: *gfx.Images) void { - if (g.profile) |*p| { - p.report(g.frame); - p.deinit(); - } - var shaders = g.shaders.valueIterator(); - while (shaders.next()) |s| c.SDL_ReleaseGPUShader(g.device, s.object); - var pipelines = g.pipelines.valueIterator(); - while (pipelines.next()) |p| c.SDL_ReleaseGPUGraphicsPipeline(g.device, p.object); - var kernels = g.kernels.valueIterator(); - while (kernels.next()) |k| c.SDL_ReleaseGPUComputePipeline(g.device, k.object); - for (g.buffers.items) |entry| if (entry) |b| c.SDL_ReleaseGPUBuffer(g.device, b.buffer); - for (g.downloads.items) |d| { - _ = c.SDL_WaitForGPUFences(g.device, true, &d.fence, 1); - c.SDL_ReleaseGPUFence(g.device, d.fence); - c.SDL_ReleaseGPUTransferBuffer(g.device, d.transfer.buffer); - } - for (g.spare.items) |t| c.SDL_ReleaseGPUTransferBuffer(g.device, t.buffer); - g.downloads.deinit(g.gpa); - g.spare.deinit(g.gpa); - if (g.staging) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); - var targets = g.targets.iterator(); - while (targets.next()) |entry| g.releaseTarget(images, entry.key_ptr.*, entry.value_ptr.*); - if (g.vertices) |b| c.SDL_ReleaseGPUBuffer(g.device, b); - if (g.upload) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); - g.shaders.deinit(g.gpa); - g.pipelines.deinit(g.gpa); - g.kernels.deinit(g.gpa); - g.buffers.deinit(g.gpa); - g.targets.deinit(g.gpa); -} - -/// Releases what nothing has used for a while. -pub fn endFrame(g: *Gpu) void { - g.frame += 1; - inline for (.{ &g.pipelines, &g.shaders, &g.kernels }) |map| { - var it = map.iterator(); - while (it.next()) |entry| { - if (g.frame - entry.value_ptr.used < keep_frames) continue; - switch (@TypeOf(map)) { - @TypeOf(&g.pipelines) => c.SDL_ReleaseGPUGraphicsPipeline(g.device, entry.value_ptr.object), - @TypeOf(&g.kernels) => c.SDL_ReleaseGPUComputePipeline(g.device, entry.value_ptr.object), - else => c.SDL_ReleaseGPUShader(g.device, entry.value_ptr.object), - } - map.removeByPtr(entry.key_ptr); - // The iterator is invalid after a removal: the rest waits a frame. - break; - } - } -} - -pub fn run(g: *Gpu, images: *gfx.Images, pass: abi.gpu.Pass) !void { - if (pass.width == 0 or pass.height == 0 or pass.draws.len == 0 and pass.clear == null) return; - const samples = g.supportedSamples(pass.samples); - const t = try g.renderTarget(images, pass.image, pass.width, pass.height, samples, pass.stencil); - // Each pipeline is looked up on first use in the pass, not per draw: - // the lookup hashes the shaders' code. Outer null: not looked up yet; - // inner null: it failed (warned once). - const built = try g.gpa.alloc(??*c.SDL_GPUGraphicsPipeline, pass.pipelines.len); - defer g.gpa.free(built); - @memset(built, null); - - const start = g.startTiming(); - // Every draw's vertices go up in one copy. - var total: u32 = 0; - for (pass.draws) |d| total += @intCast(std.mem.alignForward(usize, d.vertices.len, 4)); - const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; - if (total > 0) { - try g.reserve(total); - const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.upload, true) orelse return error.GpuMap); - var offset: usize = 0; - for (pass.draws) |d| { - @memcpy(mapped[offset..][0..d.vertices.len], d.vertices); - offset += std.mem.alignForward(usize, d.vertices.len, 4); - } - c.SDL_UnmapGPUTransferBuffer(g.device, g.upload); - const copy = c.SDL_BeginGPUCopyPass(cmd); - c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = g.upload, .offset = 0 }, &.{ .buffer = g.vertices, .offset = 0, .size = total }, true); - c.SDL_EndGPUCopyPass(copy); - } - - const clear = pass.clear orelse .{ 0, 0, 0, 0 }; - var color: c.SDL_GPUColorTargetInfo = std.mem.zeroes(c.SDL_GPUColorTargetInfo); - color.clear_color = .{ .r = clear[0], .g = clear[1], .b = clear[2], .a = clear[3] }; - // `clear = null` keeps what the attachment holds, as on the web: a - // multisampled pass loads its multisampled attachment, which every - // pass therefore stores as well as resolves. A new attachment is - // cleared to zero instead, since Vulkan starts it undefined where - // WebGPU starts it zeroed. - const fresh = if (samples > 1) &t.msaa_fresh else &t.fresh; - color.load_op = if (pass.clear != null or fresh.*) c.SDL_GPU_LOADOP_CLEAR else c.SDL_GPU_LOADOP_LOAD; - fresh.* = false; - if (samples > 1) { - color.texture = t.msaa; - color.store_op = c.SDL_GPU_STOREOP_RESOLVE_AND_STORE; - color.resolve_texture = t.texture; - } else { - color.texture = t.texture; - color.store_op = c.SDL_GPU_STOREOP_STORE; - } - t.fresh = false; - var depth: c.SDL_GPUDepthStencilTargetInfo = std.mem.zeroes(c.SDL_GPUDepthStencilTargetInfo); - if (pass.stencil) { - depth.texture = t.stencil; - depth.load_op = c.SDL_GPU_LOADOP_DONT_CARE; - depth.store_op = c.SDL_GPU_STOREOP_DONT_CARE; - depth.stencil_load_op = c.SDL_GPU_LOADOP_CLEAR; - depth.stencil_store_op = c.SDL_GPU_STOREOP_DONT_CARE; - depth.clear_stencil = 0; - } - const rp = c.SDL_BeginGPURenderPass(cmd, &color, 1, if (pass.stencil) &depth else null) orelse return error.GpuRenderPass; - var bound: ?*c.SDL_GPUGraphicsPipeline = null; - // State already set in this pass, so draws that repeat it skip the call. - var vertex_uniforms: ?[]const u8 = null; - var stencil_reference: ?u8 = null; - var scissor: ?c.SDL_Rect = null; - var vertex_base: ?u32 = null; - var offset: u32 = 0; - for (pass.draws) |d| { - defer offset += @intCast(std.mem.alignForward(usize, d.vertices.len, 4)); - if (d.pipeline >= pass.pipelines.len or d.vertex_count == 0) continue; - const slot = &built[d.pipeline]; - if (slot.* == null) slot.* = g.pipeline(pass.pipelines[d.pipeline], samples, pass.stencil) catch |err| blk: { - std.log.warn("gpu pipeline {d}: {t} ({s})", .{ d.pipeline, err, c.SDL_GetError() }); - break :blk @as(?*c.SDL_GPUGraphicsPipeline, null); - }; - const chosen = slot.*.? orelse continue; - if (bound != chosen) { - c.SDL_BindGPUGraphicsPipeline(rp, chosen); - bound = chosen; - } - // Vertices at a multiple of the stride are reached from one binding - // at 0 by the draw's first vertex; others get a binding of their own. - var first: u32 = 0; - if (d.vertices.len > 0) { - const stride = pass.pipelines[d.pipeline].stride; - const base = if (stride > 0 and offset % stride == 0) 0 else offset; - if (base == 0 and stride > 0) first = offset / stride; - if (vertex_base != base) { - c.SDL_BindGPUVertexBuffers(rp, 0, &.{ .buffer = g.vertices, .offset = base }, 1); - vertex_base = base; - } - } - var bound_storage: [8]*c.SDL_GPUBuffer = undefined; - if (d.vertex_storage.len > 0) c.SDL_BindGPUVertexStorageBuffers(rp, 0, &bound_storage, g.resolve(d.vertex_storage, &bound_storage) catch continue); - if (d.fragment_storage.len > 0) c.SDL_BindGPUFragmentStorageBuffers(rp, 0, &bound_storage, g.resolve(d.fragment_storage, &bound_storage) catch continue); - // Pushed uniforms stay for later draws: the same bytes (sketches - // share one slice for a pass's viewport) need no second push. - if (d.vertex_uniforms.len > 0) if (vertex_uniforms == null or vertex_uniforms.?.ptr != d.vertex_uniforms.ptr or vertex_uniforms.?.len != d.vertex_uniforms.len) { - c.SDL_PushGPUVertexUniformData(cmd, 0, d.vertex_uniforms.ptr, @intCast(d.vertex_uniforms.len)); - vertex_uniforms = d.vertex_uniforms; - }; - if (d.fragment_uniforms.len > 0) c.SDL_PushGPUFragmentUniformData(cmd, 0, d.fragment_uniforms.ptr, @intCast(d.fragment_uniforms.len)); - if (pass.stencil and stencil_reference != d.stencil_reference) { - c.SDL_SetGPUStencilReference(rp, d.stencil_reference); - stencil_reference = d.stencil_reference; - } - const full: abi.Rect = .{ .w = @floatFromInt(pass.width), .h = @floatFromInt(pass.height) }; - const s = d.scissor orelse full; - const rect: c.SDL_Rect = .{ .x = @intFromFloat(@max(s.x, 0)), .y = @intFromFloat(@max(s.y, 0)), .w = @intFromFloat(@max(s.w, 0)), .h = @intFromFloat(@max(s.h, 0)) }; - if (scissor == null or !std.meta.eql(scissor.?, rect)) { - c.SDL_SetGPUScissor(rp, &rect); - scissor = rect; - } - c.SDL_DrawGPUPrimitives(rp, d.vertex_count, 1, first, 0); - } - c.SDL_EndGPURenderPass(rp); - try g.submit(cmd, if (pass.label.len > 0) pass.label else "pass", start); -} - -/// Runs one dispatch in a compute pass of its own. -pub fn compute(g: *Gpu, d: abi.gpu.Dispatch) !void { - if (d.groups[0] == 0 or d.groups[1] == 0 or d.groups[2] == 0) return; - const built = try g.kernel(d.kernel); - const start = g.startTiming(); - var readonly: [8]*c.SDL_GPUBuffer = undefined; - const readonly_count = try g.resolve(d.readonly, &readonly); - var readwrite: [8]*c.SDL_GPUBuffer = undefined; - const readwrite_count = try g.resolve(d.readwrite, &readwrite); - var bindings: [8]c.SDL_GPUStorageBufferReadWriteBinding = undefined; - for (readwrite[0..readwrite_count], bindings[0..readwrite_count]) |b, *binding| binding.* = std.mem.zeroInit(c.SDL_GPUStorageBufferReadWriteBinding, .{ .buffer = b }); - const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; - const pass = c.SDL_BeginGPUComputePass(cmd, null, 0, &bindings, readwrite_count) orelse { - _ = c.SDL_CancelGPUCommandBuffer(cmd); - return error.GpuComputePass; - }; - c.SDL_BindGPUComputePipeline(pass, built); - if (readonly_count > 0) c.SDL_BindGPUComputeStorageBuffers(pass, 0, &readonly, readonly_count); - if (d.uniforms.len > 0) c.SDL_PushGPUComputeUniformData(cmd, 0, d.uniforms.ptr, @intCast(d.uniforms.len)); - c.SDL_DispatchGPUCompute(pass, d.groups[0], d.groups[1], d.groups[2]); - c.SDL_EndGPUComputePass(pass); - try g.submit(cmd, if (d.label.len > 0) d.label else "compute", start); -} - -/// A zeroed storage buffer, readable by every stage and writable by compute. -pub fn newBuffer(g: *Gpu, size: u32) !abi.Buffer { - if (size == 0) return error.EmptyBuffer; - const usage = c.SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ | c.SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_READ | c.SDL_GPU_BUFFERUSAGE_COMPUTE_STORAGE_WRITE; - const buffer = c.SDL_CreateGPUBuffer(g.device, &.{ .usage = usage, .size = size, .props = 0 }) orelse return error.GpuBuffer; - errdefer c.SDL_ReleaseGPUBuffer(g.device, buffer); - try g.buffers.append(g.gpa, .{ .buffer = buffer, .size = size }); - const handle: abi.Buffer = @fromBackingInt(@intCast(g.buffers.items.len)); - // Vulkan leaves new memory undefined; sketches get zeroes, copied from - // one zeroed staging block as many times as it takes. - const staging = try g.stagingBuffer(); - const block: u32 = @min(size, staging_size); - const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, staging, true) orelse return error.GpuMap); - @memset(mapped[0..block], 0); - c.SDL_UnmapGPUTransferBuffer(g.device, staging); - const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; - const copy = c.SDL_BeginGPUCopyPass(cmd); - var offset: u32 = 0; - while (offset < size) : (offset += block) { - c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = staging, .offset = 0 }, &.{ .buffer = buffer, .offset = offset, .size = @min(block, size - offset) }, false); - } - c.SDL_EndGPUCopyPass(copy); - if (!c.SDL_SubmitGPUCommandBuffer(cmd)) return error.GpuSubmit; - return handle; -} - -fn stagingBuffer(g: *Gpu) !*c.SDL_GPUTransferBuffer { - if (g.staging == null) g.staging = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = staging_size, .props = 0 }) orelse return error.GpuBuffer; - return g.staging.?; -} - -pub fn freeBuffer(g: *Gpu, handle: abi.Buffer) void { - const index = @backingInt(handle); - if (index == 0 or index > g.buffers.items.len) return; - const entry = &g.buffers.items[index - 1]; - if (entry.*) |b| c.SDL_ReleaseGPUBuffer(g.device, b.buffer); - entry.* = null; -} - -/// Copies `bytes` into a buffer at `offset`, through the staging buffer. -pub fn write(g: *Gpu, handle: abi.Buffer, offset: u32, bytes: []const u8) !void { - const target = g.storage(handle) orelse return error.UnknownBuffer; - if (@as(u64, offset) + bytes.len > target.size) return error.UploadOutOfBounds; - const staging = try g.stagingBuffer(); - var done: usize = 0; - while (done < bytes.len) { - const chunk = bytes[done..][0..@min(staging_size, bytes.len - done)]; - const start = g.startTiming(); - // Cycling: a chunk still in flight keeps its own memory. - const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, staging, true) orelse return error.GpuMap); - @memcpy(mapped[0..chunk.len], chunk); - c.SDL_UnmapGPUTransferBuffer(g.device, staging); - const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; - const copy = c.SDL_BeginGPUCopyPass(cmd); - c.SDL_UploadToGPUBuffer(copy, &.{ .transfer_buffer = staging, .offset = 0 }, &.{ .buffer = target.buffer, .offset = offset + @as(u32, @intCast(done)), .size = @intCast(chunk.len) }, false); - c.SDL_EndGPUCopyPass(copy); - try g.submit(cmd, "upload", start); - done += chunk.len; - } -} - -/// Starts copying `size` bytes of a buffer from `offset` back to the CPU; -/// `collect` hands them over once the GPU is done, a frame or more later. -pub fn download(g: *Gpu, d: @FieldType(abi.Command, "download")) !void { - const source = g.storage(d.buffer) orelse return error.UnknownBuffer; - if (d.size == 0 or @as(u64, d.offset) + d.size > source.size) return error.DownloadOutOfBounds; - const transfer = for (g.spare.items, 0..) |t, i| { - if (t.size >= d.size) break g.spare.swapRemove(i); - } else Transfer{ - .buffer = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = d.size, .props = 0 }) orelse return error.GpuBuffer, - .size = d.size, - }; - errdefer g.spare.append(g.gpa, transfer) catch c.SDL_ReleaseGPUTransferBuffer(g.device, transfer.buffer); - const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return error.GpuCommandBuffer; - const copy = c.SDL_BeginGPUCopyPass(cmd); - c.SDL_DownloadFromGPUBuffer(copy, &.{ .buffer = source.buffer, .offset = d.offset, .size = d.size }, &.{ .transfer_buffer = transfer.buffer, .offset = 0 }); - c.SDL_EndGPUCopyPass(copy); - const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit; - g.downloads.append(g.gpa, .{ .key = d.key, .size = d.size, .transfer = transfer, .fence = fence }) catch |err| { - _ = c.SDL_WaitForGPUFences(g.device, true, &fence, 1); - c.SDL_ReleaseGPUFence(g.device, fence); - return err; - }; -} - -/// The downloads the GPU has finished, copied into `arena`, in the order -/// they were asked for. -pub fn collect(g: *Gpu, arena: std.mem.Allocator) ![]const abi.Download { - var done: std.ArrayList(abi.Download) = .empty; - while (g.downloads.items.len > 0) { - const d = g.downloads.items[0]; - if (!c.SDL_QueryGPUFence(g.device, d.fence)) break; - _ = g.downloads.orderedRemove(0); - c.SDL_ReleaseGPUFence(g.device, d.fence); - defer g.spare.append(g.gpa, d.transfer) catch c.SDL_ReleaseGPUTransferBuffer(g.device, d.transfer.buffer); - const mapped: [*]const u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, d.transfer.buffer, false) orelse return error.GpuMap); - defer c.SDL_UnmapGPUTransferBuffer(g.device, d.transfer.buffer); - try done.append(arena, .{ .key = d.key, .bytes = try arena.dupe(u8, mapped[0..d.size]) }); - } - return done.items; -} - -fn storage(g: *Gpu, handle: abi.Buffer) ?Storage { - const index = @backingInt(handle); - if (index == 0 or index > g.buffers.items.len) return null; - return g.buffers.items[index - 1]; -} - -/// The SDL buffers behind `handles`, into `out`; returns how many. -fn resolve(g: *Gpu, handles: []const abi.Buffer, out: []*c.SDL_GPUBuffer) !u32 { - if (handles.len > out.len) return error.TooManyBuffers; - for (handles, out[0..handles.len]) |handle, *b| b.* = (g.storage(handle) orelse return error.UnknownBuffer).buffer; - return @intCast(handles.len); -} - -fn kernel(g: *Gpu, k: abi.gpu.Kernel) !*c.SDL_GPUComputePipeline { - var h = std.hash.Wyhash.init(0); - h.update(k.code); - inline for (.{ k.readonly_buffers, k.readwrite_buffers, k.uniform_buffers, k.threads[0], k.threads[1], k.threads[2] }) |v| h.update(std.mem.asBytes(&@as(u32, v))); - const key = h.final(); - const entry = try g.kernels.getOrPut(g.gpa, key); - if (!entry.found_existing) { - errdefer _ = g.kernels.remove(key); - var info: c.SDL_GPUComputePipelineCreateInfo = std.mem.zeroes(c.SDL_GPUComputePipelineCreateInfo); - info.code_size = k.code.len; - info.code = k.code.ptr; - info.entrypoint = "main"; - info.format = c.SDL_GPU_SHADERFORMAT_SPIRV; - info.num_readonly_storage_buffers = k.readonly_buffers; - info.num_readwrite_storage_buffers = k.readwrite_buffers; - info.num_uniform_buffers = k.uniform_buffers; - info.threadcount_x = k.threads[0]; - info.threadcount_y = k.threads[1]; - info.threadcount_z = k.threads[2]; - entry.value_ptr.object = c.SDL_CreateGPUComputePipeline(g.device, &info) orelse return error.GpuComputePipeline; - } - entry.value_ptr.used = g.frame; - return entry.value_ptr.object; -} - -fn supportedSamples(g: *Gpu, wanted: u8) u8 { - var s: u8 = if (wanted >= 8) 8 else if (wanted >= 4) 4 else if (wanted >= 2) 2 else 1; - while (s > 1 and !c.SDL_GPUTextureSupportsSampleCount(g.device, color_format, sampleCount(s))) s /= 2; - return s; -} - -fn sampleCount(s: u8) c.SDL_GPUSampleCount { - return switch (s) { - 8 => c.SDL_GPU_SAMPLECOUNT_8, - 4 => c.SDL_GPU_SAMPLECOUNT_4, - 2 => c.SDL_GPU_SAMPLECOUNT_2, - else => c.SDL_GPU_SAMPLECOUNT_1, - }; -} - -/// The image's render target, (re)created to fit the pass. -fn renderTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, w: u32, h: u32, samples: u8, stencil: bool) !*Target { - var entry = try g.targets.getOrPut(g.gpa, image); - if (entry.found_existing and (entry.value_ptr.width != w or entry.value_ptr.height != h)) { - g.releaseTarget(images, image, entry.value_ptr.*); - entry.found_existing = false; - } - if (!entry.found_existing) { - errdefer _ = g.targets.remove(image); - const resolved = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER, 1); - errdefer c.SDL_ReleaseGPUTexture(g.device, resolved); - try images.wrap(image, resolved, w, h); - entry.value_ptr.* = .{ .width = w, .height = h, .texture = resolved }; - } - const t = entry.value_ptr; - if (samples > 1 and (t.msaa == null or t.samples != samples)) { - if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m); - t.msaa = try g.texture(w, h, color_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, samples); - t.samples = samples; - t.msaa_fresh = true; - } - if (stencil and (t.stencil == null or t.stencil_samples != samples)) { - if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s); - t.stencil = try g.texture(w, h, g.stencil_format, c.SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET, samples); - t.stencil_samples = samples; - } - return t; -} - -fn releaseTarget(g: *Gpu, images: *gfx.Images, image: abi.Image, t: Target) void { - images.unwrap(image); - c.SDL_ReleaseGPUTexture(g.device, t.texture); - if (t.msaa) |m| c.SDL_ReleaseGPUTexture(g.device, m); - if (t.stencil) |s| c.SDL_ReleaseGPUTexture(g.device, s); -} - -/// Forgets an image's target, when the image itself is freed. -pub fn forget(g: *Gpu, images: *gfx.Images, image: abi.Image) void { - const t = g.targets.fetchRemove(image) orelse return; - g.releaseTarget(images, image, t.value); -} - -fn texture(g: *Gpu, w: u32, h: u32, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, samples: u8) !*c.SDL_GPUTexture { - var info: c.SDL_GPUTextureCreateInfo = std.mem.zeroes(c.SDL_GPUTextureCreateInfo); - info.type = c.SDL_GPU_TEXTURETYPE_2D; - info.format = format; - info.usage = usage; - info.width = w; - info.height = h; - info.layer_count_or_depth = 1; - info.num_levels = 1; - info.sample_count = sampleCount(samples); - return c.SDL_CreateGPUTexture(g.device, &info) orelse error.GpuTexture; -} - -fn reserve(g: *Gpu, bytes: u32) !void { - if (bytes > g.vertex_capacity) { - const capacity = @max(bytes, g.vertex_capacity * 2, 64 * 1024); - if (g.vertices) |b| c.SDL_ReleaseGPUBuffer(g.device, b); - g.vertices = c.SDL_CreateGPUBuffer(g.device, &.{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = capacity, .props = 0 }) orelse return error.GpuBuffer; - g.vertex_capacity = capacity; - } - if (bytes > g.upload_capacity) { - const capacity = @max(bytes, g.upload_capacity * 2, 64 * 1024); - if (g.upload) |b| c.SDL_ReleaseGPUTransferBuffer(g.device, b); - g.upload = c.SDL_CreateGPUTransferBuffer(g.device, &.{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = capacity, .props = 0 }) orelse return error.GpuBuffer; - g.upload_capacity = capacity; - } -} - -fn shader(g: *Gpu, s: abi.gpu.Shader, stage: c.SDL_GPUShaderStage) !struct { *c.SDL_GPUShader, u64 } { - var h = std.hash.Wyhash.init(stage); - h.update(s.code); - h.update(std.mem.asBytes(&s.uniform_buffers)); - h.update(std.mem.asBytes(&s.storage_buffers)); - const key = h.final(); - const entry = try g.shaders.getOrPut(g.gpa, key); - if (!entry.found_existing) { - errdefer _ = g.shaders.remove(key); - entry.value_ptr.object = c.SDL_CreateGPUShader(g.device, &.{ - .code_size = s.code.len, - .code = s.code.ptr, - .entrypoint = "main", - .format = c.SDL_GPU_SHADERFORMAT_SPIRV, - .stage = stage, - .num_samplers = 0, - .num_storage_textures = 0, - .num_storage_buffers = s.storage_buffers, - .num_uniform_buffers = s.uniform_buffers, - .props = 0, - }) orelse return error.GpuShader; - } - entry.value_ptr.used = g.frame; - return .{ entry.value_ptr.object, key }; -} - -fn pipeline(g: *Gpu, p: abi.gpu.Pipeline, samples: u8, stencil: bool) !*c.SDL_GPUGraphicsPipeline { - const vertex, const vertex_key = try g.shader(p.vertex, c.SDL_GPU_SHADERSTAGE_VERTEX); - const fragment, const fragment_key = try g.shader(p.fragment, c.SDL_GPU_SHADERSTAGE_FRAGMENT); - // Field by field: no padding bytes in the key. - var h = std.hash.Wyhash.init(vertex_key ^ (fragment_key *% 31)); - inline for (.{ p.stride, @backingInt(p.primitive), @backingInt(p.blend), @intFromBool(p.write_color), samples, @intFromBool(stencil) }) |v| h.update(std.mem.asBytes(&@as(u32, v))); - for (p.attributes) |a| inline for (.{ a.location, @backingInt(a.format), a.offset }) |v| h.update(std.mem.asBytes(&@as(u32, v))); - if (p.stencil) |st| inline for (.{ st.front, st.back }) |face| inline for (.{ @backingInt(face.compare), @backingInt(face.pass), @backingInt(face.fail) }) |v| h.update(std.mem.asBytes(&@as(u32, v))); - const key = h.final(); - const entry = try g.pipelines.getOrPut(g.gpa, key); - if (!entry.found_existing) { - errdefer _ = g.pipelines.remove(key); - var attributes: [16]c.SDL_GPUVertexAttribute = undefined; - const count = @min(p.attributes.len, attributes.len); - for (p.attributes[0..count], attributes[0..count]) |a, *out| out.* = .{ - .location = a.location, - .buffer_slot = 0, - .offset = a.offset, - .format = switch (a.format) { - .float => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT, - .float2 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, - .float3 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, - .float4 => c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, - .ubyte4_norm => c.SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM, - }, - }; - var blend: c.SDL_GPUColorTargetBlendState = std.mem.zeroes(c.SDL_GPUColorTargetBlendState); - blend.enable_blend = p.blend != .none; - blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD; - blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD; - blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; - blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; - const dst: c.SDL_GPUBlendFactor = if (p.blend == .additive) c.SDL_GPU_BLENDFACTOR_ONE else c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA; - blend.dst_color_blendfactor = dst; - blend.dst_alpha_blendfactor = dst; - blend.enable_color_write_mask = true; - blend.color_write_mask = if (p.write_color) c.SDL_GPU_COLORCOMPONENT_R | c.SDL_GPU_COLORCOMPONENT_G | c.SDL_GPU_COLORCOMPONENT_B | c.SDL_GPU_COLORCOMPONENT_A else 0; - const target_description: c.SDL_GPUColorTargetDescription = .{ .format = color_format, .blend_state = blend }; - var depth_stencil: c.SDL_GPUDepthStencilState = std.mem.zeroes(c.SDL_GPUDepthStencilState); - if (p.stencil) |st| { - depth_stencil.enable_stencil_test = true; - depth_stencil.compare_mask = 0xff; - depth_stencil.write_mask = 0xff; - depth_stencil.front_stencil_state = stencilFace(st.front); - depth_stencil.back_stencil_state = stencilFace(st.back); - } - var info: c.SDL_GPUGraphicsPipelineCreateInfo = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo); - info.vertex_shader = vertex; - info.fragment_shader = fragment; - info.vertex_input_state = .{ - .vertex_buffer_descriptions = &.{ .slot = 0, .pitch = p.stride, .input_rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .instance_step_rate = 0 }, - // No attributes: the vertex shader makes its own vertices. - .num_vertex_buffers = @intFromBool(count > 0), - .vertex_attributes = &attributes, - .num_vertex_attributes = @intCast(count), - }; - info.primitive_type = switch (p.primitive) { - .triangle_list => c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST, - .triangle_strip => c.SDL_GPU_PRIMITIVETYPE_TRIANGLESTRIP, - .line_list => c.SDL_GPU_PRIMITIVETYPE_LINELIST, - .line_strip => c.SDL_GPU_PRIMITIVETYPE_LINESTRIP, - }; - info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL; - info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE; - info.rasterizer_state.front_face = c.SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE; - info.multisample_state.sample_count = sampleCount(samples); - info.depth_stencil_state = depth_stencil; - info.target_info.color_target_descriptions = &target_description; - info.target_info.num_color_targets = 1; - info.target_info.depth_stencil_format = g.stencil_format; - info.target_info.has_depth_stencil_target = stencil; - entry.value_ptr.object = c.SDL_CreateGPUGraphicsPipeline(g.device, &info) orelse return error.GpuPipeline; - } - entry.value_ptr.used = g.frame; - return entry.value_ptr.object; -} - -fn stencilFace(face: abi.gpu.StencilFace) c.SDL_GPUStencilOpState { - // Both enums follow SDL's order, after its INVALID. - return .{ - .compare_op = @as(u32, @backingInt(face.compare)) + 1, - .pass_op = @as(u32, @backingInt(face.pass)) + 1, - .fail_op = @as(u32, @backingInt(face.fail)) + 1, - .depth_fail_op = c.SDL_GPU_STENCILOP_KEEP, - }; -} diff --git a/src/host/root.zig b/src/host/root.zig index d01a63f..c9cdde6 100644 --- a/src/host/root.zig +++ b/src/host/root.zig @@ -39,6 +39,8 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--state")) { options.state = args.next() orelse fatal("--state needs a file"); + } else if (std.mem.eql(u8, arg, "--9p")) { + options.ninep = args.next() orelse fatal("--9p needs a socket path"); } else if (std.mem.eql(u8, arg, "--fresh")) { options.fresh = true; } else if (std.mem.eql(u8, arg, "--headless")) { @@ -121,6 +123,7 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { const usage = \\usage: sketchbook [options] [LIBRARY] + \\ --9p SOCKET local 9P controls: ctl, status, log, screen.png \\ --state FILE persistent state (default: sketch.state) \\ --headless offscreen video, silent audio, no vsync \\ --script FILE play a script instead of reading devices @@ -191,9 +194,11 @@ const sdl_heap = struct { }; test { + _ = Host; _ = memory; _ = fields; _ = timeline; _ = @import("audio.zig"); _ = @import("Console.zig"); + _ = @import("control.zig"); } -- cgit v1.3