//! The sketchbook host: runs a sketch linked in, or loaded from a library //! that it hot-reloads whenever a build replaces it. Its options are //! `flags`, which parse the command line and print `--help`. const std = @import("std"); const c = @import("c"); const abi = @import("abi"); pub const Host = @import("Host.zig"); pub const memory = @import("memory.zig"); pub const fields = @import("fields.zig"); pub const script = @import("script.zig"); pub const timeline = @import("timeline.zig"); /// Entry point for both the generic host (`linked == null`) and apps that /// link their sketch in. pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { const gpa = init.gpa; var options: Host.Options = .{}; var script_path: ?[]const u8 = null; var defines: std.ArrayList([2][]const u8) = .empty; defer defines.deinit(gpa); var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(gpa); var args = init.minimal.args.iterate(); _ = args.skip(); while (args.next()) |arg| { if (!std.mem.startsWith(u8, arg, "-")) { options.library = arg; continue; } const flag: Flag = if (std.mem.eql(u8, arg, "-h")) .help else (if (std.mem.startsWith(u8, arg, "--")) std.meta.stringToEnum(Flag, arg[2..]) else null) orelse fatal("{s} is no option (see --help)", .{arg}); const v = if (flags.get(flag).arg.len == 0) "" else args.next() orelse fatal("{s} needs {s}", .{ arg, flags.get(flag).arg }); switch (flag) { .@"9p" => options.ninep = v, .state => options.state = v, .headless => options.headless = true, .script => { script_path = v; options.script = true; }, .fresh => options.fresh = true, .@"timing-marker" => options.timing_marker = true, .@"profile-gpu" => options.profile_gpu = true, .console => try lines.append(gpa, v), .define => { const eq = std.mem.indexOfScalar(u8, v, '=') orelse fatal("{s} needs {s}", .{ arg, "NAME=VALUE" }); try defines.append(gpa, .{ v[0..eq], v[eq + 1 ..] }); }, .@"export" => { options.export_to = v; options.headless = true; options.fresh = true; }, .fps => options.fps = std.fmt.parseInt(u32, v, 10) catch 0, .frames => options.frames = std.fmt.parseInt(u64, v, 10) catch fatal("{s} needs {s}", .{ arg, "a number" }), .size => { const x = std.mem.indexOfScalar(u8, v, 'x') orelse 0; const w = std.fmt.parseInt(u32, v[0..x], 10) catch 0; const h = std.fmt.parseInt(u32, v[x + 1 ..], 10) catch 0; if (w == 0 or h == 0) fatal("{s} needs {s}", .{ arg, "WxH" }); options.size = .{ w, h }; }, .help => return std.debug.print("{s}", .{usage}), } if (options.fps == 0) fatal("{s} needs {s}", .{ arg, "a whole number of frames a second" }); } if (linked == null and options.library == null) fatal("no sketch library given (see --help)", .{}); if (options.export_to) |to| { if (script_path != null) fatal("--export plays no script: it runs the sketch on its own", .{}); if (!std.mem.eql(u8, to, "-")) { try std.Io.Dir.cwd().createDirPath(init.io, to); } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg", .{}); } if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.xitdb"; // A scripted run from fresh state, or an export, touches no save. if (!((script_path != null or options.export_to != null) and options.fresh)) sketchbookDir(init.io, options.state); sdl_heap.install(); { var host: Host = undefined; try host.init(gpa, init.io, init.environ_map, options, linked); defer host.deinit(); for (lines.items) |line| host.runLine(line, c.SDL_GetTicksNS()) catch {}; if (script_path) |path| { const source = try std.Io.Dir.cwd().readFileAlloc(init.io, path, gpa, .limited(1 << 20)); defer gpa.free(source); try script.run(&host, source, defines.items); } else try host.run(); } if (sdl_heap.leaked()) return error.LeakedSdlMemory; } /// The options: a row each, what parses the command line (the switch in /// `main` sets what each one means) and prints `--help`. const Flag = enum { @"9p", state, headless, script, fresh, @"timing-marker", @"profile-gpu", console, define, @"export", fps, frames, size, help }; const flags = std.enums.EnumArray(Flag, struct { arg: []const u8 = "", doc: []const u8 }).init(.{ .@"9p" = .{ .arg = "SOCKET", .doc = "local 9P controls: ctl, status, log, screen.png" }, .state = .{ .arg = "FILE", .doc = "the save, one file: FILE, or FILE.xitdb for a FILE.state (where a\nstate file from before is imported from, once); default:\n$XDG_DATA_HOME//.xitdb, sketch.xitdb for --script, --export" }, .headless = .{ .doc = "offscreen video, silent audio, no vsync" }, .script = .{ .arg = "FILE", .doc = "play a script instead of reading devices" }, .fresh = .{ .doc = "start from default state (the save's history is kept)" }, .@"timing-marker" = .{ .doc = "encode frame ID and draw sample time for video analysis" }, .@"profile-gpu" = .{ .doc = "time each GPU command alone, print the times at exit" }, .console = .{ .arg = "LINE", .doc = "run a console line once the sketch is loaded (repeatable)" }, .define = .{ .arg = "NAME=VALUE", .doc = "substitute {NAME} in the script" }, .@"export" = .{ .arg = "DIR|-", .doc = "headless, from fresh state: every frame as DIR/000000.png, ...\nor for - as raw RGBA on stdout, until the sketch quits" }, .fps = .{ .arg = "N", .doc = "export: frames a second (60); each tick is exactly 1/N s" }, .frames = .{ .arg = "N", .doc = "export: stop after N frames" }, .size = .{ .arg = "WxH", .doc = "the first canvas and, headless, the room for it" }, .help = .{ .doc = "this, also -h" }, }); /// `--help`: a line per flag, its doc's lines under one another. const usage = blk: { @setEvalBranchQuota(100_000); const pad: [23]u8 = @splat(' '); var text: []const u8 = "usage: sketchbook [options] [LIBRARY]\n"; for (std.enums.values(Flag)) |flag| { const f = flags.get(flag); const head = " --" ++ @tagName(flag) ++ (if (f.arg.len > 0) " " ++ f.arg else ""); text = text ++ head ++ pad[head.len..]; var lines = std.mem.splitScalar(u8, f.doc, '\n'); text = text ++ lines.first() ++ "\n"; while (lines.next()) |more| text = text ++ pad ++ more ++ "\n"; } break :blk text; }; /// A save in a directory named `.sketchbook` (`zig build run`'s): the /// directory is made, with a `.gitignore` of `*` (the save grows, and a jj /// snapshot would commit it), and the state file an older build kept beside /// it (`.state`) is moved in, once, to be imported. A file is never /// replaced: when both exist, nothing moves. fn sketchbookDir(io: std.Io, state: []const u8) void { const dir = std.fs.path.dirname(state) orelse return; if (!std.mem.eql(u8, std.fs.path.basename(dir), ".sketchbook")) return; const cwd = std.Io.Dir.cwd(); cwd.createDirPath(io, dir) catch return; var buf: [std.fs.max_path_bytes]u8 = undefined; const ignore = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{dir}) catch return; cwd.writeFile(io, .{ .sub_path = ignore, .data = "*\n", .flags = .{ .exclusive = true } }) catch {}; var from_buf: [std.fs.max_path_bytes]u8 = undefined; var to_buf: [std.fs.max_path_bytes]u8 = undefined; const parent = std.fs.path.dirname(dir) orelse "."; const stem = Host.stemOf(std.fs.path.basename(state)); const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}.state", .{ parent, stem }, 0) catch return; const to = std.fmt.bufPrintSentinel(&to_buf, "{s}/{s}.state", .{ dir, stem }, 0) catch return; switch (std.os.linux.errno(std.os.linux.renameat2(std.os.linux.AT.FDCWD, from.ptr, std.os.linux.AT.FDCWD, to.ptr, .{ .NOREPLACE = true }))) { .SUCCESS => std.debug.print("sketchbook: moved {s} to {s}\n", .{ from, to }), .EXIST => std.debug.print("sketchbook: {s} and {s} both exist: nothing moved, {s} is used\n", .{ from, to, to }), else => {}, } } fn fatal(comptime fmt: []const u8, args: anytype) noreturn { std.debug.print("sketchbook: " ++ fmt ++ "\n", args); std.process.exit(2); } /// SDL's allocations go through a leak-checking allocator of their own, so a /// session that leaks SDL memory fails loudly at exit. const sdl_heap = struct { var debug: std.heap.DebugAllocator(.{ .backing_allocator_zeroes = false }) = .{}; const alignment: std.mem.Alignment = .of(std.c.max_align_t); const header = alignment.forward(@sizeOf(usize)); fn install() void { _ = c.SDL_SetMemoryFunctions(malloc, calloc, realloc, free); } fn leaked() bool { return debug.deinit() == .leak; } fn block(size: usize) ?[*]u8 { const total = std.math.add(usize, header, size) catch return null; const base = debug.allocator().rawAlloc(total, alignment, @returnAddress()) orelse return null; @as(*usize, @ptrCast(@alignCast(base))).* = total; return base + header; } fn whole(mem: *anyopaque) []u8 { const base: [*]u8 = @as([*]u8, @ptrCast(mem)) - header; return base[0..@as(*const usize, @ptrCast(@alignCast(base))).*]; } fn malloc(size: usize) callconv(.c) ?*anyopaque { return block(size); } fn calloc(n: usize, size: usize) callconv(.c) ?*anyopaque { const bytes = std.math.mul(usize, n, size) catch return null; const mem = block(bytes) orelse return null; @memset(mem[0..bytes], 0); return mem; } fn realloc(maybe: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { const old = whole(maybe orelse return malloc(size)); const total = std.math.add(usize, header, size) catch return null; if (debug.allocator().rawRemap(old, alignment, total, @returnAddress())) |base| { @as(*usize, @ptrCast(@alignCast(base))).* = total; return base + header; } const new = block(size) orelse return null; @memcpy(new[0..@min(size, old.len - header)], old[header..][0..@min(size, old.len - header)]); debug.allocator().rawFree(old, alignment, @returnAddress()); return new; } fn free(maybe: ?*anyopaque) callconv(.c) void { debug.allocator().rawFree(whole(maybe orelse return), alignment, @returnAddress()); } }; test { _ = Host; _ = memory; _ = fields; _ = timeline; _ = @import("Sessions.zig"); _ = @import("audio.zig"); _ = @import("Console.zig"); _ = @import("control.zig"); _ = @import("timing_marker.zig"); }