summaryrefslogtreecommitdiff
path: root/src/host/Glyphs.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/Glyphs.zig')
-rw-r--r--src/host/Glyphs.zig279
1 files changed, 279 insertions, 0 deletions
diff --git a/src/host/Glyphs.zig b/src/host/Glyphs.zig
new file mode 100644
index 0000000..b3fdbfb
--- /dev/null
+++ b/src/host/Glyphs.zig
@@ -0,0 +1,279 @@
+//! 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));
+}
+
+test "the atlas's glyphs are pardes's: the same coverage bytes and the same place" {
+ const gpa = std.testing.allocator;
+ var g: Glyphs = .{ .gpa = gpa };
+ g.stage = try gpa.alloc(u8, side * side);
+ @memset(g.stage, 0);
+ defer g.deinit();
+ var compared: usize = 0;
+ var clipped: usize = 0;
+ // Grid faces (every advance the cell's) and a proportional one, which
+ // pardes centres in its cell.
+ for ([_]abi.Face{ .mono, .mono_bold, .mono_italic, .code, .code_medium, .sans }) |face| for ([_]f32{ 13, 19.5, 26, 52 }) |px| {
+ // pardes's Atlas over the same face: its own stage, its cells.
+ var pardes: Atlas = .{ .font = c.sk_text_ui(@backingInt(face)).?, .atlas_stage = try gpa.alloc(u8, side * side), .glyphs = .init(gpa) };
+ defer {
+ gpa.free(pardes.atlas_stage);
+ pardes.glyphs.deinit();
+ }
+ var cell_w: c_int = 0;
+ var height: c_int = 0;
+ var ascent: c_int = 0;
+ pardes.cellMetrics(px, &cell_w, &height, &ascent);
+ const body: Atlas.Size = .{ .px = px, .cell_w = @intCast(cell_w), .height = @intCast(height), .baseline = ascent };
+ pardes.reset(body.cell_w);
+ for (0x21..0x7f) |cp| {
+ const glyph = c.ui_font_glyph(pardes.font, @intCast(cp));
+ const ours = g.rasterize(.{ .face = @backingInt(face), .glyph = glyph, .px = @intFromFloat(px * 64) }).?;
+ // pardes centres the advance in its cell: nothing for a grid
+ // face, whose advances are all the cell's.
+ const shift = @divTrunc(cell_w - c.sk_text_advance(@backingInt(face), px, glyph), 2);
+ const x = shift + ours.dx;
+ const y = ascent + ours.dy;
+ // Ink pardes's cell cuts off is not comparable: count it.
+ if (x < 0 or y < 0 or x + ours.w > cell_w or y + ours.h > height) {
+ clipped += 1;
+ continue;
+ }
+ const at = pardes.cachedGlyph(.{ .face = 0, .glyph = glyph, .role = .body }, body, body, 1, 1).?;
+ const cell = pardes.atlas_stage[at.v * side + at.u ..];
+ const theirs = Atlas.inkBounds(cell, side, body.cell_w, body.height).?;
+ try std.testing.expectEqual(theirs.max_x - theirs.min_x + 1, ours.w);
+ try std.testing.expectEqual(theirs.max_y - theirs.min_y + 1, ours.h);
+ try std.testing.expectEqual(@as(i64, @intCast(theirs.min_x)), x);
+ try std.testing.expectEqual(@as(i64, @intCast(theirs.min_y)), y);
+ for (0..ours.h) |row| try std.testing.expectEqualSlices(u8, cell[(theirs.min_y + row) * side + theirs.min_x ..][0..ours.w], g.stage[(ours.v + row) * side + ours.u ..][0..ours.w]);
+ compared += 1;
+ }
+ };
+ // 6 faces at 4 sizes, 94 printable ASCII glyphs each: 2256, a few of
+ // which reach out of pardes's cell (`_` under it, `|` over it).
+ std.debug.print("pardes's raster: {d} glyphs equal byte for byte, {d} clipped by its cell\n", .{ compared, clipped });
+ try std.testing.expectEqual(@as(usize, 2256), compared + clipped);
+ try std.testing.expect(compared > 1900);
+}