//! svgview: shows one SVG from a list, fitted to its own canvas size, with //! either renderer. The differential tests drive it headless: set `index` //! and `backend` from the console, screenshot, compare with resvg. //! //! The list is `$SVGVIEW_LIST` (default `svgview.txt`): one `path width //! height` per line. const std = @import("std"); const sk = @import("sketch"); const vector = @import("vector"); pub const name = "svgview"; pub const width = 512; pub const height = 512; pub const State = struct { index: u32 = 0, backend: vector.Backend = .gpu, }; pub const Session = struct { gpu: ?vector.Renderer(.gpu) = null, cpu: ?vector.Renderer(.cpu) = null, }; const Entry = struct { path: []const u8, w: u32, h: u32 }; fn entry(host: sk.Host, index: u32) ?Entry { const list = host.readFile(host.env("SVGVIEW_LIST") orelse "svgview.txt"); var lines = std.mem.tokenizeScalar(u8, list, '\n'); var i: u32 = 0; while (lines.next()) |line| : (i += 1) { if (i != index) continue; var words = std.mem.tokenizeScalar(u8, line, ' '); const path = words.next() orelse return null; const w = std.fmt.parseInt(u32, words.next() orelse return null, 10) catch return null; const h = std.fmt.parseInt(u32, words.next() orelse return null, 10) catch return null; return .{ .path = path, .w = w, .h = h }; } return null; } pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { const e = entry(f.host, s.index) orelse { f.clear(0x400000); f.text(8, 8, 2, "no such entry", 0xffffff); return; }; f.canvas(e.w, e.h); show(s, ss, f, e) catch |err| { f.clear(0x400000); f.print(8, 8, 2, 0xffffff, "{s}: {t}", .{ e.path, err }); }; } fn show(s: *const State, ss: *Session, f: *sk.Frame, e: Entry) !void { const d = try vector.svg.parse(f.scratch, f.host.readFile(e.path)); // As resvg -w does: scale to the width, from the top-left corner (the // height is rounded, so fitting both would drift by a fraction). const s_ = @as(f32, @floatFromInt(e.w)) / d.view.w; const place = vector.geom.Affine.scale(s_, s_).mul(.translate(-d.view.x, -d.view.y)); switch (s.backend) { .gpu => try render(&ss.gpu, f, d, place, e), .cpu => try render(&ss.cpu, f, d, place, e), } } fn render(slot: anytype, f: *sk.Frame, d: vector.Drawing, place: vector.geom.Affine, e: Entry) !void { if (slot.*) |*r| if (r.width() != e.w or r.height() != e.h) { r.deinit(f.host); slot.* = null; }; if (slot.* == null) slot.* = try .init(f.session, f.host, e.w, e.h); const r = &slot.*.?; // resvg's `--background '#808080'`. r.begin(f, .{ 128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1 }); try r.draw(d, place, 1); r.present(f, sk.Rect{ .w = @floatFromInt(e.w), .h = @floatFromInt(e.h) }); }