summaryrefslogtreecommitdiff
path: root/src/host/Glyphs.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 04:02:44 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commit1f9fa4fc66c68e66e7653498f04d17052833d6c3 (patch)
tree177d92af30f09207a2c9164a9b425c7178d5845d /src/host/Glyphs.zig
parent1229dae433b0036547b1e28e76af645b1b57d7a0 (diff)
downloadsketchbook-1f9fa4fc66c68e66e7653498f04d17052833d6c3.tar.gz
sketchbook-1f9fa4fc66c68e66e7653498f04d17052833d6c3.zip
text: FreeType and HarfBuzz in the build, Pango, Cairo and glib out, glyphs from one atlas
build.zig.zon gains the freetype and harfbuzz packages pardes pins (lazy: a gpu-only embedder brings its own), and build.zig compiles them, with the flags pardes's window uses, together with pardes's vendor/font.c (unchanged) and a new vendor/text.c into one static library, sketchbook-text, which the host links. vendor/text.c replaces the Pango shim: the ten bundled faces by #embed, opened on first use by FreeType (font.c) and by HarfBuzz's own OpenType functions over the same bytes; sk_text_shape shapes a run left to right at a pixel size, each advance rounded to a whole pixel, with the line box font.c's cell metrics give; a codepoint the face lacks comes from one fallback face (ponytail: no fontconfig, no bidi); sk_text_font takes a sketch's own font from bytes. src/host/Glyphs.zig is the renderer: a text command is shaped at its canvas size, each glyph rastered by font.c's ui_font_raster at its device size and kept, trimmed to its ink (Atlas.inkBounds), in shelves of one 2048x2048 atlas, white premultiplied by coverage, cleared and refilled when full. Consecutive text commands are one SDL_RenderGeometry call; upright text lands on whole device pixels, NEAREST; textScaled (and a glyph past 512 device pixels) is unsnapped, LINEAR. The SDL debug font fallback off Linux goes: the faces are built in everywhere. Host.textSize measures with the same call. test/fonts.c (a Pango specimen outside the build) goes. Measured: a cold Debug build of the host 39.8 s before, 43.7 s after; the Debug host 117.7 MB (35.6 MB stripped) before, 159.5 MB (46.8 MB) after, with 6 shared libraries where it loaded 41 (pango, cairo, glib, fontconfig, the system freetype and harfbuzz and theirs). A frame of 4500 glyphs, half changing every frame (ReleaseFast, headless): 27.5 M instructions and 2.80 ms of CPU before, 5.33 M and 0.40 ms after; all static: 6.44 M and 0.47 ms before, 5.28 M and 0.42 ms after. zig build test: 192/192 steps, 146/146 tests; test/text.script's pinned pixels hold. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src/host/Glyphs.zig')
-rw-r--r--src/host/Glyphs.zig225
1 files changed, 225 insertions, 0 deletions
diff --git a/src/host/Glyphs.zig b/src/host/Glyphs.zig
new file mode 100644
index 0000000..8de40cf
--- /dev/null
+++ b/src/host/Glyphs.zig
@@ -0,0 +1,225 @@
+//! The host's text. A `Command.text` is shaped by vendor/text.c at its
+//! canvas size (what `textRun` measured), and each glyph is rasterized by
+//! pardes's font.c at the size it lands on the device, kept in one
+//! 2048x2048 coverage atlas: shelves of trimmed ink boxes, cleared and
+//! refilled when full (pardes's policy: no eviction). The texture holds
+//! white premultiplied by coverage, so a vertex colour is the ink and the
+//! coverage is mixed once, with no gamma. The glyphs of consecutive text
+//! commands are one geometry call (`flush`, which the Painter calls before
+//! anything else it draws). Upright text lands on whole device pixels and
+//! samples NEAREST; `textScaled` (and a glyph past 512 device pixels,
+//! rastered at 512) is placed unsnapped and samples LINEAR.
+const Glyphs = @This();
+const std = @import("std");
+const abi = @import("abi");
+const c = @import("c");
+const Atlas = @import("font_atlas");
+
+const side = Atlas.atlas_w;
+/// The largest raster, in device pixels: a bigger glyph is this one, stretched.
+const max_px = 512;
+
+/// A glyph of a face at a device size, in 64ths of a pixel.
+const Key = packed struct(u64) { face: u8, glyph: u32, px: u24 };
+/// Its ink box in the atlas, and where that box sits from the pen's origin
+/// on the baseline (device pixels, y down). Empty: nothing to draw.
+const Slot = struct { u: u16 = 0, v: u16 = 0, w: u16 = 0, h: u16 = 0, dx: i16 = 0, dy: i16 = 0 };
+
+gpa: std.mem.Allocator,
+/// Coverage, a byte a texel: `texture`'s contents to come.
+stage: []u8 = &.{},
+texture: ?*c.SDL_Texture = null,
+slots: std.AutoHashMapUnmanaged(Key, Slot) = .empty,
+/// The shelf being filled: its top, its height so far, and the pen in it.
+shelf: struct { x: u32 = 0, y: u32 = 0, h: u32 = 0 } = .{},
+/// What the stage changed since the last upload: x0, y0, x1, y1.
+dirty: [4]u32 = .{ 0, 0, side, side },
+/// A glyph's raster before it is trimmed, and the shaped glyphs of a run.
+raster: std.ArrayList(u8) = .empty,
+shaped: std.ArrayList(c.SkGlyph) = .empty,
+/// The pending geometry: six vertices a glyph, in logical units.
+batch: std.ArrayList(c.SDL_Vertex) = .empty,
+linear: bool = false,
+
+pub fn deinit(g: *Glyphs) void {
+ if (g.texture) |t| c.SDL_DestroyTexture(t);
+ g.gpa.free(g.stage);
+ g.slots.deinit(g.gpa);
+ g.raster.deinit(g.gpa);
+ g.shaped.deinit(g.gpa);
+ g.batch.deinit(g.gpa);
+ g.* = .{ .gpa = g.gpa };
+}
+
+/// The canvas size `scale` is, in pixels: scale 1 is 13.
+pub fn pixels(scale: f32) f32 {
+ return 13 * scale;
+}
+
+/// One `Command.text` into the batch.
+pub fn draw(g: *Glyphs, renderer: *c.SDL_Renderer, t: @FieldType(abi.Command, "text")) void {
+ const raster = if (t.raster > 0) t.raster else t.scale;
+ if (t.bytes.len == 0 or t.color.a == 0 or !(t.scale > 0) or !std.math.isFinite(t.scale) or !std.math.isFinite(raster)) return;
+ if (g.texture == null and !g.start(renderer)) return;
+ // Shaped at the size it was measured at; `k` stretches that layout to
+ // the size drawn (textScaled), `dpi` to the device.
+ var advance: i32 = 0;
+ var ascent: i32 = 0;
+ var height: i32 = 0;
+ const face: c_int = @backingInt(t.face);
+ var n: usize = 0;
+ while (true) {
+ n = @intCast(c.sk_text_shape(face, pixels(raster), t.bytes.ptr, t.bytes.len, g.shaped.items.ptr, @intCast(g.shaped.items.len), &advance, &ascent, &height));
+ if (n <= g.shaped.items.len) break;
+ g.shaped.resize(g.gpa, n) catch return;
+ }
+ const k = t.scale / raster;
+ const dpi = density(renderer);
+ const wanted = pixels(t.scale) * dpi;
+ const px = @min(wanted, max_px);
+ const stretch = wanted / px;
+ const snapped = k == 1 and stretch == 1;
+ if (g.linear != !snapped) {
+ g.flush(renderer);
+ g.linear = !snapped;
+ }
+ const ink: c.SDL_FColor = .{
+ .r = @as(f32, @floatFromInt(t.color.r)) * @as(f32, @floatFromInt(t.color.a)) / (255 * 255),
+ .g = @as(f32, @floatFromInt(t.color.g)) * @as(f32, @floatFromInt(t.color.a)) / (255 * 255),
+ .b = @as(f32, @floatFromInt(t.color.b)) * @as(f32, @floatFromInt(t.color.a)) / (255 * 255),
+ .a = @as(f32, @floatFromInt(t.color.a)) / 255,
+ };
+ const unit = k * dpi; // device pixels a layout pixel
+ const origin: [2]f32 = .{ t.x * dpi, (t.y + @as(f32, @floatFromInt(ascent)) * k) * dpi };
+ for (g.shaped.items[0..n]) |glyph| {
+ const key: Key = .{ .face = glyph.face, .glyph = glyph.glyph, .px = @intFromFloat(@round(px * 64)) };
+ const slot = g.slotFor(renderer, key) orelse continue;
+ if (slot.w == 0) continue;
+ var at: [2]f32 = .{ origin[0] + @as(f32, @floatFromInt(glyph.x)) * unit, origin[1] + @as(f32, @floatFromInt(glyph.y)) * unit };
+ if (snapped) at = .{ @round(origin[0]) + @round(@as(f32, @floatFromInt(glyph.x)) * unit), @round(origin[1]) + @round(@as(f32, @floatFromInt(glyph.y)) * unit) };
+ const x0 = (at[0] + @as(f32, @floatFromInt(slot.dx)) * stretch) / dpi;
+ const y0 = (at[1] + @as(f32, @floatFromInt(slot.dy)) * stretch) / dpi;
+ const x1 = x0 + @as(f32, @floatFromInt(slot.w)) * stretch / dpi;
+ const y1 = y0 + @as(f32, @floatFromInt(slot.h)) * stretch / dpi;
+ const s: f32 = 1.0 / @as(f32, side);
+ const s0 = @as(f32, @floatFromInt(slot.u)) * s;
+ const t0 = @as(f32, @floatFromInt(slot.v)) * s;
+ const s1 = @as(f32, @floatFromInt(slot.u + slot.w)) * s;
+ const t1 = @as(f32, @floatFromInt(slot.v + slot.h)) * s;
+ const quad = g.batch.addManyAsArray(g.gpa, 6) catch return;
+ const tl: c.SDL_Vertex = .{ .position = .{ .x = x0, .y = y0 }, .color = ink, .tex_coord = .{ .x = s0, .y = t0 } };
+ const tr: c.SDL_Vertex = .{ .position = .{ .x = x1, .y = y0 }, .color = ink, .tex_coord = .{ .x = s1, .y = t0 } };
+ const bl: c.SDL_Vertex = .{ .position = .{ .x = x0, .y = y1 }, .color = ink, .tex_coord = .{ .x = s0, .y = t1 } };
+ const br: c.SDL_Vertex = .{ .position = .{ .x = x1, .y = y1 }, .color = ink, .tex_coord = .{ .x = s1, .y = t1 } };
+ quad.* = .{ tl, tr, bl, tr, br, bl };
+ }
+}
+
+/// Draws the batch: the stage's new rows uploaded, then one geometry call.
+pub fn flush(g: *Glyphs, renderer: *c.SDL_Renderer) void {
+ if (g.batch.items.len == 0) return;
+ defer g.batch.clearRetainingCapacity();
+ const texture = g.texture orelse return;
+ g.upload();
+ _ = c.SDL_SetTextureScaleMode(texture, if (g.linear) c.SDL_SCALEMODE_LINEAR else c.SDL_SCALEMODE_NEAREST);
+ _ = c.SDL_RenderGeometry(renderer, texture, g.batch.items.ptr, @intCast(g.batch.items.len), null, 0);
+}
+
+fn start(g: *Glyphs, renderer: *c.SDL_Renderer) bool {
+ g.stage = g.gpa.alloc(u8, side * side) catch return false;
+ @memset(g.stage, 0);
+ const texture = c.SDL_CreateTexture(renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_STATIC, side, side) orelse {
+ g.gpa.free(g.stage);
+ g.stage = &.{};
+ return false;
+ };
+ _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND_PREMULTIPLIED);
+ g.texture = texture;
+ g.dirty = .{ 0, 0, side, side };
+ return true;
+}
+
+/// The stage's changed rectangle into the texture, coverage as white
+/// premultiplied (r = g = b = a), 64 rows at a time.
+fn upload(g: *Glyphs) void {
+ const d = g.dirty;
+ if (d[2] <= d[0] or d[3] <= d[1]) return;
+ const w = d[2] - d[0];
+ const band = 64;
+ g.raster.resize(g.gpa, w * band * 4) catch return;
+ var top = d[1];
+ while (top < d[3]) : (top += band) {
+ const h = @min(band, d[3] - top);
+ for (0..h) |y| for (0..w) |x| @memset(g.raster.items[(y * w + x) * 4 ..][0..4], g.stage[(top + y) * side + d[0] + x]);
+ const rect: c.SDL_Rect = .{ .x = @intCast(d[0]), .y = @intCast(top), .w = @intCast(w), .h = @intCast(h) };
+ _ = c.SDL_UpdateTexture(g.texture, &rect, g.raster.items.ptr, @intCast(w * 4));
+ }
+ g.dirty = .{ side, side, 0, 0 };
+}
+
+/// `key`'s slot, rasterized on first use; when the atlas is full, what is
+/// pending is drawn and the atlas starts over. Null if it cannot hold it.
+fn slotFor(g: *Glyphs, renderer: *c.SDL_Renderer, key: Key) ?Slot {
+ if (g.slots.get(key)) |s| return s;
+ return g.rasterize(key) orelse {
+ g.flush(renderer);
+ g.slots.clearRetainingCapacity();
+ @memset(g.stage, 0);
+ g.shelf = .{};
+ g.dirty = .{ 0, 0, side, side };
+ return g.rasterize(key);
+ };
+}
+
+/// font.c's raster of `key`, its advance centred on the pen as pardes
+/// centres a cell's, a margin of half its size around it; then trimmed to
+/// its ink and shelved. Null when the atlas has no room.
+fn rasterize(g: *Glyphs, key: Key) ?Slot {
+ const px = @as(f32, @floatFromInt(key.px)) / 64;
+ const font = c.sk_text_ui(key.face) orelse return null;
+ var cell_w: c_int = 0;
+ var height: c_int = 0;
+ var ascent: c_int = 0;
+ c.ui_font_cell_metrics(font, px, &cell_w, &height, &ascent);
+ const advance = @max(0, c.sk_text_advance(key.face, px, key.glyph));
+ const pad: c_int = @intFromFloat(@ceil(px / 2) + 2);
+ const w: usize = @intCast(advance + 2 * pad);
+ const h: usize = @intCast(height + 2 * pad);
+ g.raster.resize(g.gpa, w * h) catch return null;
+ const blank = c.ui_font_raster(font, px, key.glyph, 0, g.raster.items.ptr, @intCast(w), @intCast(w), @intCast(h), pad, advance, ascent + pad) == 0;
+ const box = if (blank) null else Atlas.inkBounds(g.raster.items, w, w, h);
+ const b = box orelse {
+ g.slots.put(g.gpa, key, .{}) catch {};
+ return .{};
+ };
+ const bw: u32 = @intCast(b.max_x - b.min_x + 1);
+ const bh: u32 = @intCast(b.max_y - b.min_y + 1);
+ // A new shelf when this one is full; a gap of a texel around each box,
+ // so LINEAR sampling at its edge reads nothing of a neighbour.
+ if (g.shelf.x + bw + 1 > side) g.shelf = .{ .y = g.shelf.y + g.shelf.h };
+ if (g.shelf.y + bh + 1 > side or bw + 1 > side) return null;
+ const slot: Slot = .{ .u = @intCast(g.shelf.x), .v = @intCast(g.shelf.y), .w = @intCast(bw), .h = @intCast(bh), .dx = @intCast(@as(i64, @intCast(b.min_x)) - pad), .dy = @intCast(@as(i64, @intCast(b.min_y)) - pad - ascent) };
+ g.slots.put(g.gpa, key, slot) catch return null;
+ for (0..bh) |y| @memcpy(g.stage[(slot.v + y) * side + slot.u ..][0..bw], g.raster.items[(b.min_y + y) * w + b.min_x ..][0..bw]);
+ g.dirty = .{ @min(g.dirty[0], slot.u), @min(g.dirty[1], slot.v), @max(g.dirty[2], slot.u + bw), @max(g.dirty[3], slot.v + bh) };
+ g.shelf.x += bw + 1;
+ g.shelf.h = @max(g.shelf.h, bh + 1);
+ return slot;
+}
+
+/// Device pixels a canvas unit: the render scale (a supersampled target's
+/// 4) times the window's logical presentation, if it is drawing there.
+fn density(renderer: *c.SDL_Renderer) f32 {
+ var sx: f32 = 1;
+ var sy: f32 = 1;
+ _ = c.SDL_GetRenderScale(renderer, &sx, &sy);
+ var w: c_int = 0;
+ var h: c_int = 0;
+ var mode: c.SDL_RendererLogicalPresentation = undefined;
+ var rect: c.SDL_FRect = undefined;
+ if (c.SDL_GetRenderLogicalPresentation(renderer, &w, &h, &mode) and mode != c.SDL_LOGICAL_PRESENTATION_DISABLED and w > 0 and h > 0 and c.SDL_GetRenderLogicalPresentationRect(renderer, &rect)) {
+ sx *= rect.w / @as(f32, @floatFromInt(w));
+ sy *= rect.h / @as(f32, @floatFromInt(h));
+ }
+ return @max(0.25, @max(sx, sy));
+}