summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 05:38:26 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commitd3742ddf2b3a85eb3935cb35e958fa27f1293a6b (patch)
treeb47dce7b82e72673432f6c8746517386c67ab742 /src
parentb65048ac19f9f47b6faa21d1a9f3d06ba3ff1a95 (diff)
parent81c4157b6731ee64a7bf9194c5df0818e2977f5d (diff)
downloadpardes-d3742ddf2b3a85eb3935cb35e958fa27f1293a6b.tar.gz
pardes-d3742ddf2b3a85eb3935cb35e958fa27f1293a6b.zip
integration: the GPU move whole, with the terminal a module of its own, the plumber and the diff work
A merge of pardes-next (uoqyunnw) and gpu-s4b (zxswllzu). One conflict, build.zig: core-test's root is the core without a terminal AND the Cells and Atlas tests join the unit suite; gui.zig merged by itself and is formatted (two role casts spelled as zig fmt spells them, two blank lines). Gated against a baseline recorded from pardes-next with the gate's test hooks and the renderer still in gui.zig (.scratch/sketch/gpu/mbase): frame corpus 77/77 identical in Debug and in ReleaseFast, the gated window -0.032% instructions (threshold 0.5%), unit-test on gui 1583/1591 with no failure the baseline has not, every GPU counter 0; on tui core-test 810/949 (139 skipped), shell-test 989/992, behaviour-test 269/273 (the four addon ABI tests the base fails). Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src')
-rw-r--r--src/gui/font.c471
-rw-r--r--src/gui/font.h98
-rw-r--r--src/gui/gui.zig1656
3 files changed, 334 insertions, 1891 deletions
diff --git a/src/gui/font.c b/src/gui/font.c
deleted file mode 100644
index aebe26e6..00000000
--- a/src/gui/font.c
+++ /dev/null
@@ -1,471 +0,0 @@
-// FreeType and HarfBuzz wrapper for gui.zig. The policy intentionally follows
-// Ghostty's FreeType backend: native hinting enabled, the auto-hinter available
-// as a fallback, and the light target for shape-preserving grayscale text.
-// HarfBuzz only picks glyphs (liga, calt); the grid, not the font's advances,
-// places them.
-#include "font.h"
-#include <freetype-zig.h>
-#include <freetype/ftbitmap.h>
-#include <freetype/ftmodapi.h>
-#include <hb-ft.h>
-#include <hb-ot.h>
-#include <hb.h>
-
-#include <string.h>
-
-struct UIFont {
- // FreeType allocates through ui_malloc and friends: the library holds a
- // pointer to this for its lifetime, which the UIFont outlives.
- struct FT_MemoryRec_ memory;
- FT_Library library;
- FT_Face face;
- FT_F26Dot6 size;
- // The charmap's answer for ASCII, which is most of every screen: a word the
- // renderer has not seen before looks up each of its cells.
- uint32_t ascii[128];
- // HarfBuzz state, made by the first ui_font_substitutes question (most
- // fallback faces are never asked).
- hb_font_t *hb;
- hb_buffer_t *buffer;
- FT_F26Dot6 hb_size;
- // Every glyph a lookup of a ligature feature could replace. Nothing else
- // can change a glyph, so a cell outside it is its nominal glyph without
- // shaping: every cell, in a font without ligatures.
- hb_set_t *substitutes;
- // ui_font_shape's per-cell scratch, grown to the longest run seen
- uint32_t *own;
- uint8_t *state;
- int32_t scratch;
-};
-
-static FT_F26Dot6 size_26_6(float px) {
- if (px < 1.0f)
- px = 1.0f;
- return (FT_F26Dot6)(px * 64.0f + 0.5f);
-}
-
-static int set_size(UIFont *f, float px) {
- const FT_F26Dot6 size = size_26_6(px);
- if (f->size == size)
- return 1;
- if (FT_Set_Char_Size(f->face, 0, size, 72, 72) != 0)
- return 0;
- f->size = size;
- return 1;
-}
-
-static int ceil_26_6(FT_Pos value) { return (int)((value + 63) >> 6); }
-
-static FT_Int32 load_flags(void) {
- // Hinting is on because FT_LOAD_NO_HINTING is absent. Likewise, leaving
- // FT_LOAD_NO_AUTOHINT absent lets FreeType fall back to its auto-hinter
- // when the face has no native instructions. This is Ghostty's default.
- return FT_LOAD_DEFAULT | FT_LOAD_TARGET_LIGHT;
-}
-
-static void *ft_alloc(FT_Memory memory, long size) {
- (void)memory;
- return ui_malloc((size_t)size);
-}
-
-static void ft_free(FT_Memory memory, void *block) {
- (void)memory;
- ui_free(block);
-}
-
-static void *ft_realloc(FT_Memory memory, long cur_size, long new_size,
- void *block) {
- (void)memory;
- (void)cur_size;
- return ui_realloc(block, (size_t)new_size);
-}
-
-UIFont *ui_font_new(const uint8_t *data, int32_t len) {
- if (!data || len <= 0)
- return NULL;
-
- UIFont *f = (UIFont *)ui_calloc(1, sizeof(UIFont));
- if (!f)
- return NULL;
- // FT_Init_FreeType is exactly FT_New_Library over FT_New_Memory's malloc
- // manager, then the default modules and properties: the same, over ours.
- f->memory = (struct FT_MemoryRec_){NULL, ft_alloc, ft_free, ft_realloc};
- if (FT_New_Library(&f->memory, &f->library) != 0) {
- ui_free(f);
- return NULL;
- }
- FT_Add_Default_Modules(f->library);
- FT_Set_Default_Properties(f->library);
- if (FT_New_Memory_Face(f->library, data, (FT_Long)len, 0, &f->face) != 0) {
- FT_Done_Library(f->library);
- ui_free(f);
- return NULL;
- }
- // Some symbol fonts do not expose a Unicode charmap. FreeType already
- // selects a usable default for those, so failure here is non-fatal.
- (void)FT_Select_Charmap(f->face, FT_ENCODING_UNICODE);
- for (uint32_t cp = 0; cp < 128; cp++)
- f->ascii[cp] = FT_Get_Char_Index(f->face, cp);
- return f;
-}
-
-// HarfBuzz reads this same face (and its charmap) through FreeType, so shaping
-// and rasterizing agree on glyph ids. None of these calls returns NULL: a
-// failure is an inert empty object, and shaping then yields nominal glyphs.
-static void start_harfbuzz(UIFont *f) {
- f->hb = hb_ft_font_create_referenced(f->face);
- f->buffer = hb_buffer_create();
- f->substitutes = hb_set_create();
- static const hb_tag_t features[] = {
- HB_TAG('l', 'i', 'g', 'a'), HB_TAG('c', 'a', 'l', 't'),
- HB_TAG('c', 'l', 'i', 'g'), HB_TAG('r', 'l', 'i', 'g'),
- HB_TAG('r', 'c', 'l', 't'), HB_TAG_NONE};
- hb_face_t *face = hb_font_get_face(f->hb);
- hb_set_t *lookups = hb_set_create();
- hb_ot_layout_collect_lookups(face, HB_OT_TAG_GSUB, NULL, NULL, features,
- lookups);
- hb_codepoint_t lookup = HB_SET_VALUE_INVALID;
- while (hb_set_next(lookups, &lookup))
- hb_ot_layout_lookup_collect_glyphs(face, HB_OT_TAG_GSUB, lookup, NULL,
- f->substitutes, NULL, NULL);
- hb_set_destroy(lookups);
-}
-
-const char *ui_font_name(UIFont *f) {
- if (!f || !f->face)
- return NULL;
- const char *postscript = FT_Get_Postscript_Name(f->face);
- if (postscript && postscript[0])
- return postscript;
- if (f->face->family_name && f->face->family_name[0])
- return f->face->family_name;
- return NULL;
-}
-
-uint32_t ui_font_glyph(UIFont *f, int32_t cp) {
- if (!f || cp < 0)
- return 0;
- if (cp < 128)
- return f->ascii[cp];
- return FT_Get_Char_Index(f->face, (FT_ULong)(uint32_t)cp);
-}
-
-void ui_font_free(UIFont *f) {
- if (!f)
- return;
- // The HarfBuzz font holds a reference on the face: release it first. (All
- // three accept NULL, a face that never shaped.)
- hb_set_destroy(f->substitutes);
- hb_buffer_destroy(f->buffer);
- hb_font_destroy(f->hb);
- if (f->face)
- FT_Done_Face(f->face);
- if (f->library)
- FT_Done_Library(f->library);
- ui_free(f->own);
- ui_free(f->state);
- ui_free(f);
-}
-
-void ui_font_prime(UIFont *f) {
- if (!f)
- return;
- hb_font_destroy(hb_ft_font_create_referenced(f->face));
- hb_buffer_t *buffer = hb_buffer_create();
- hb_buffer_add_utf8(buffer, "a", 1, 0, 1);
- hb_buffer_guess_segment_properties(buffer);
- hb_buffer_destroy(buffer);
-}
-
-void ui_font_cell_metrics(UIFont *f, float px, int32_t *cell_w, int32_t *cell_h,
- int32_t *ascent) {
- if (!f || !cell_w || !cell_h || !ascent || !set_size(f, px)) {
- if (cell_w)
- *cell_w = 1;
- if (cell_h)
- *cell_h = 1;
- if (ascent)
- *ascent = 1;
- return;
- }
-
- const FT_Size_Metrics metrics = f->face->size->metrics;
- const int asc = ceil_26_6(metrics.ascender);
- const int desc = ceil_26_6(-metrics.descender);
- int height = ceil_26_6(metrics.height);
- if (height < asc + desc)
- height = asc + desc;
-
- int width = ceil_26_6(metrics.max_advance);
- const FT_UInt m = FT_Get_Char_Index(f->face, 'M');
- if (FT_Load_Glyph(f->face, m, load_flags()) == 0) {
- const int advance = ceil_26_6(f->face->glyph->advance.x);
- if (advance > 0)
- width = advance;
- }
-
- *cell_w = width > 0 ? width : 1;
- *cell_h = height > 0 ? height : 1;
- *ascent = asc > 0 ? asc : 1;
-}
-
-static int raster(UIFont *f, float px, uint32_t glyph_index, int bold,
- uint8_t *out, int32_t stride, int32_t width, int32_t height,
- int32_t cell_x, int32_t cell_w, int32_t ascent,
- int centered) {
- if (!f || !out || stride < width || width <= 0 || height <= 0)
- return 0;
- for (int y = 0; y < height; y++)
- memset(out + (size_t)y * (size_t)stride, 0, (size_t)width);
- if (!set_size(f, px))
- return 0;
-
- if (FT_Load_Glyph(f->face, glyph_index, load_flags()) != 0)
- return 0;
- if (bold) {
- // Synthetic bold thickens the hinted outline before it is rendered, so
- // the wider stems are rasterized as one shape and keep hinted edges; the
- // advance is untouched, as the cell grid requires. Strength is Ghostty's
- // heuristic: 1/32 of the line height in 26.6, rounded up (one pixel at a
- // 32 px line). A bitmap strike has no outline: widen it by one whole pixel,
- // the classic overstrike, which keeps its pixels sharp.
- FT_GlyphSlot slot = f->face->glyph;
- if (slot->format == FT_GLYPH_FORMAT_OUTLINE) {
- const FT_Pos height = f->face->size->metrics.height;
- FT_Outline_Embolden(&slot->outline, (height + 31) / 32);
- } else if (slot->format == FT_GLYPH_FORMAT_BITMAP &&
- FT_GlyphSlot_Own_Bitmap(slot) == 0) {
- FT_Bitmap_Embolden(f->library, &slot->bitmap, 64, 0);
- }
- }
- if (FT_Render_Glyph(f->face->glyph, FT_RENDER_MODE_NORMAL) != 0)
- return 0;
-
- const FT_GlyphSlot glyph = f->face->glyph;
- const FT_Bitmap *bitmap = &glyph->bitmap;
- if (!bitmap->buffer || bitmap->width == 0 || bitmap->rows == 0)
- return 0;
-
- const int advance = ceil_26_6(glyph->advance.x);
- // Fallbacks may be proportional. Center their advance in the primary face's
- // fixed cell, exactly as Ghostty centers a narrower fallback face.
- const int gx = centered
- ? (width - (int)bitmap->width) / 2
- : cell_x + glyph->bitmap_left + (cell_w - advance) / 2;
- const int gy =
- centered ? (height - (int)bitmap->rows) / 2 : ascent - glyph->bitmap_top;
- const int pitch = bitmap->pitch;
- const int row_bytes = pitch < 0 ? -pitch : pitch;
-
- for (unsigned int y = 0; y < bitmap->rows; y++) {
- const int dy = gy + (int)y;
- if (dy < 0 || dy >= height)
- continue;
- const unsigned int source_y = pitch < 0 ? bitmap->rows - 1 - y : y;
- const uint8_t *src = bitmap->buffer + (size_t)source_y * (size_t)row_bytes;
-
- for (unsigned int x = 0; x < bitmap->width; x++) {
- const int dx = gx + (int)x;
- if (dx < 0 || dx >= width)
- continue;
-
- uint8_t coverage;
- if (bitmap->pixel_mode == FT_PIXEL_MODE_MONO) {
- coverage = (src[x >> 3] & (0x80u >> (x & 7))) ? 255 : 0;
- } else if (bitmap->pixel_mode == FT_PIXEL_MODE_GRAY) {
- coverage = src[x];
- if (bitmap->num_grays > 1 && bitmap->num_grays != 256)
- coverage = (uint8_t)((unsigned int)coverage * 255u /
- (bitmap->num_grays - 1u));
- } else {
- continue;
- }
- out[(size_t)dy * (size_t)stride + (size_t)dx] = coverage;
- }
- }
- return 1;
-}
-
-int ui_font_raster(UIFont *f, float px, uint32_t glyph, int bold, uint8_t *out,
- int32_t stride, int32_t width, int32_t height,
- int32_t cell_x, int32_t cell_w, int32_t ascent) {
- return raster(f, px, glyph, bold, out, stride, width, height, cell_x, cell_w,
- ascent, 0);
-}
-
-int ui_font_raster_centered(UIFont *f, float px, uint32_t glyph, int bold,
- uint8_t *out, int32_t stride, int32_t width,
- int32_t height) {
- return raster(f, px, glyph, bold, out, stride, width, height, 0, width, 0, 1);
-}
-
-// The horizontal ink of `glyph` placed as ui_font_raster places it in a cell
-// `cell` wide (26.6), relative to the cell's left edge. 0 when it has no ink.
-static int ink(UIFont *f, uint32_t glyph, FT_Pos cell, FT_Pos *left,
- FT_Pos *right) {
- if (FT_Load_Glyph(f->face, glyph, load_flags()) != 0)
- return 0;
- const FT_GlyphSlot slot = f->face->glyph;
- if (slot->metrics.width <= 0 || slot->metrics.height <= 0)
- return 0;
- const FT_Pos origin =
- (FT_Pos)(((int)(cell >> 6) - ceil_26_6(slot->advance.x)) / 2) * 64;
- *left = origin + slot->metrics.horiBearingX;
- *right = *left + slot->metrics.width;
- return 1;
-}
-
-// ui_font_shape's per-cell marks: no glyph of its own, keep the nominal glyph,
-// drawn as a slice of another cell's glyph.
-#define NONE UINT32_MAX
-#define PLAIN 1
-#define CLAIMED 2
-
-int ui_font_substitutes(UIFont *f, uint32_t glyph) {
- if (!f)
- return 0;
- if (!f->hb)
- start_harfbuzz(f);
- return hb_set_has(f->substitutes, glyph);
-}
-
-// The GSUB features shaping leaves on are the ligature ones; the others
-// HarfBuzz would apply (glyph composition, local forms, fractions around
-// U+2044, ...) are off, so a cell is either its nominal glyph, as the renderer
-// always drew it, or part of a ligature. Positioning is untouched: the grid
-// ignores advances and keeps nominal glyphs where marks would move.
-static const hb_feature_t shaping_features[] = {
- {HB_TAG('c', 'c', 'm', 'p'), 0, 0, (unsigned int)-1},
- {HB_TAG('l', 'o', 'c', 'l'), 0, 0, (unsigned int)-1},
- {HB_TAG('r', 'v', 'r', 'n'), 0, 0, (unsigned int)-1},
- {HB_TAG('l', 't', 'r', 'a'), 0, 0, (unsigned int)-1},
- {HB_TAG('l', 't', 'r', 'm'), 0, 0, (unsigned int)-1},
- {HB_TAG('r', 'a', 'n', 'd'), 0, 0, (unsigned int)-1},
- {HB_TAG('f', 'r', 'a', 'c'), 0, 0, (unsigned int)-1},
- {HB_TAG('n', 'u', 'm', 'r'), 0, 0, (unsigned int)-1},
- {HB_TAG('d', 'n', 'o', 'm'), 0, 0, (unsigned int)-1},
-};
-
-void ui_font_shape(UIFont *f, float px, int32_t cell_w, const uint32_t *cps,
- int32_t n, UIShapedCell *out) {
- if (!f || !cps || !out || n <= 0)
- return;
- for (int32_t i = 0; i < n; i++)
- out[i] = (UIShapedCell){ui_font_glyph(f, (int32_t)cps[i]), 0, 1, 0};
- if (!f->hb)
- start_harfbuzz(f);
- int substitutable = 0;
- for (int32_t i = 0; i < n && !substitutable; i++)
- substitutable = hb_set_has(f->substitutes, out[i].glyph);
- if (!substitutable || cell_w <= 0 || !set_size(f, px))
- return;
- if (n > f->scratch) {
- uint32_t *own = (uint32_t *)ui_realloc(f->own, (size_t)n * sizeof *own);
- if (!own)
- return;
- f->own = own;
- uint8_t *state = (uint8_t *)ui_realloc(f->state, (size_t)n);
- if (!state)
- return;
- f->state = state;
- f->scratch = n;
- }
- // hb-ft reads the FreeType size when told; positions are only consulted
- // for being nonzero, but a zero scale would hide exactly that.
- if (f->hb_size != f->size) {
- hb_ft_font_changed(f->hb);
- f->hb_size = f->size;
- }
- hb_buffer_clear_contents(f->buffer);
- // One codepoint per cell, so a cluster value IS a cell index.
- hb_buffer_add_codepoints(f->buffer, cps, n, 0, n);
- hb_buffer_set_direction(f->buffer, HB_DIRECTION_LTR);
- hb_buffer_guess_segment_properties(f->buffer);
- hb_shape(f->hb, f->buffer, shaping_features,
- sizeof shaping_features / sizeof shaping_features[0]);
- unsigned int count = 0;
- const hb_glyph_info_t *info = hb_buffer_get_glyph_infos(f->buffer, &count);
- const hb_glyph_position_t *pos =
- hb_buffer_get_glyph_positions(f->buffer, &count);
-
- // Each cell's own glyph is the one HarfBuzz left in its cluster. A cell a
- // ligature merged into an earlier cluster has NONE. A cluster the grid
- // cannot place (several glyphs, a positioned mark) is PLAIN, and so are the
- // cells merged into it: they keep their nominal glyphs.
- uint32_t *own = f->own;
- uint8_t *state = f->state;
- for (int32_t i = 0; i < n; i++) {
- own[i] = NONE;
- state[i] = 0;
- }
- for (unsigned int k = 0; k < count; k++) {
- const uint32_t cluster = info[k].cluster;
- if (cluster >= (uint32_t)n)
- continue;
- if (own[cluster] != NONE || pos[k].x_offset != 0 || pos[k].y_offset != 0)
- state[cluster] = PLAIN;
- else
- own[cluster] = info[k].codepoint;
- }
- for (int32_t i = 1; i < n; i++)
- if (own[i] == NONE && (state[i - 1] & PLAIN))
- state[i] = PLAIN;
-
- // A substituted glyph (or one whose cluster swallowed cells) may reach over
- // its neighbours: it claims those that draw nothing of their own, nearest
- // first, and each draws its slice of the one strip. Ink past a cell edge by
- // half a pixel or less is noise.
- const FT_Pos cell = (FT_Pos)cell_w * 64;
- for (int32_t i = 0; i < n; i++) {
- if ((state[i] & (PLAIN | CLAIMED)) || own[i] == NONE)
- continue;
- int32_t merged = 0;
- while (i + 1 + merged < n && own[i + 1 + merged] == NONE &&
- !(state[i + 1 + merged] & PLAIN))
- merged++;
- if (own[i] == out[i].glyph && merged == 0)
- continue;
- FT_Pos left = 0, right = 0;
- if (!ink(f, own[i], cell, &left, &right))
- continue; // a spacer: claimed, never claiming
- int32_t want_left =
- left < -32 ? (int32_t)((-left - 32 + cell - 1) / cell) : 0;
- int32_t want_right = right > cell + 32
- ? (int32_t)((right - cell - 32 + cell - 1) / cell)
- : 0;
- if (want_right < merged)
- want_right = merged;
- int32_t lead = 0, trail = 0;
- while (lead < want_left && 1 + lead + trail < UI_MAX_SPAN) {
- const int32_t j = i - lead - 1;
- FT_Pos l, r;
- if (j < 0 || (state[j] & (PLAIN | CLAIMED)) ||
- (own[j] != NONE &&
- (own[j] == out[j].glyph || ink(f, own[j], cell, &l, &r))))
- break;
- lead++;
- }
- while (trail < want_right && 1 + lead + trail < UI_MAX_SPAN) {
- const int32_t j = i + trail + 1;
- FT_Pos l, r;
- if (j >= n || (state[j] & (PLAIN | CLAIMED)) ||
- (own[j] != NONE &&
- (own[j] == out[j].glyph || ink(f, own[j], cell, &l, &r))))
- break;
- trail++;
- }
- for (int32_t j = i - lead; j <= i + trail; j++) {
- out[j] =
- (UIShapedCell){own[i], (uint8_t)lead, (uint8_t)(1 + lead + trail),
- (uint8_t)(j - (i - lead))};
- state[j] |= CLAIMED;
- }
- }
- // The rest draw their own glyph; a merged cell nothing claimed draws blank.
- const uint32_t space = f->ascii[' '];
- for (int32_t i = 0; i < n; i++) {
- if (state[i] & (PLAIN | CLAIMED))
- continue;
- out[i].glyph = own[i] == NONE ? space : own[i];
- }
-}
diff --git a/src/gui/font.h b/src/gui/font.h
deleted file mode 100644
index db964fb0..00000000
--- a/src/gui/font.h
+++ /dev/null
@@ -1,98 +0,0 @@
-// Tiny C shim over FreeType and HarfBuzz, so gui.zig only imports the stable
-// renderer API. The implementation owns FreeType's library and face objects
-// and HarfBuzz's font and buffer, and keeps the caller's font bytes borrowed
-// for the face lifetime.
-#ifndef UI_FONT_H
-#define UI_FONT_H
-#include <stddef.h>
-#include <stdint.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct UIFont UIFont;
-
-// Every allocation FreeType, HarfBuzz and this shim make: C's malloc, calloc,
-// realloc and free, implemented by gui.zig over a Zig allocator. HarfBuzz is
-// compiled to call them (hb_malloc_impl and friends); FreeType gets them as
-// each library's memory manager.
-void *ui_malloc(size_t size);
-void *ui_calloc(size_t count, size_t size);
-void *ui_realloc(void *block, size_t size);
-void ui_free(void *block);
-
-// Parse the first face in an in-memory font. `data` must stay alive for the
-// lifetime of the font. Returns NULL on failure.
-UIFont *ui_font_new(const uint8_t *data, int32_t len);
-
-// The face FreeType actually accepted. Prefer its PostScript name (the same
-// identity the macOS shell reports); fall back to the family name when the
-// font has no PostScript table. Borrowed for the UIFont lifetime.
-const char *ui_font_name(UIFont *f);
-
-// The glyph the selected Unicode charmap maps `cp` to. Glyph zero is the
-// face's .notdef box: the codepoint is missing, which is what fallback choice
-// asks.
-uint32_t ui_font_glyph(UIFont *f, int32_t cp);
-
-// `px` is the pixel height. Metrics and rasterization both configure FreeType
-// at that size, so hinted advances, baseline and bitmaps stay in step.
-void ui_font_cell_metrics(UIFont *f, float px, int32_t *cell_w, int32_t *cell_h,
- int32_t *ascent);
-
-// What one grid cell draws: `slice` of the glyph `glyph` rasterized across
-// `span` cells with its own cell `lead` cells from the left. A plain cell is
-// its own glyph, lead 0, span 1, slice 0.
-typedef struct {
- uint32_t glyph;
- uint8_t lead;
- uint8_t span;
- uint8_t slice;
-} UIShapedCell;
-
-// The longest glyph strip a ligature may claim, in cells.
-#define UI_MAX_SPAN 8
-
-// Whether a lookup of the font's ligature features (liga, calt, clig, rlig,
-// rclt) could replace `glyph`. When it cannot, shaping leaves the glyph alone
-// and its cell needs no shaping at all.
-int ui_font_substitutes(UIFont *f, uint32_t glyph);
-
-// One cell per codepoint of `cps`, all in this face, shaped by HarfBuzz with
-// the font's ligature features (a run with no glyph ui_font_substitutes
-// reports comes back nominal without it). A substituted glyph whose ink
-// reaches over neighbouring cells that draw nothing of their own (a
-// ligature's spacers, or the cells a merged cluster swallowed) claims them as
-// a strip. Otherwise, and for anything the grid cannot place (several glyphs
-// in one cell, positioned marks), each cell is its nominal glyph.
-void ui_font_shape(UIFont *f, float px, int32_t cell_w, const uint32_t *cps,
- int32_t n, UIShapedCell *out);
-
-// Rasterize `glyph` into `out` as a hinted grayscale mask of `width` x
-// `height` (`stride` bytes per row). The glyph's advance is centered in the
-// `cell_w` pixels that start at `cell_x`, and its baseline is `ascent` pixels
-// from the top; ink outside the mask is clipped. `bold` emboldens the outline
-// before rendering (synthetic bold, same advance). Returns 1 when the glyph
-// produced coverage, 0 for blank/error.
-int ui_font_raster(UIFont *f, float px, uint32_t glyph, int bold, uint8_t *out,
- int32_t stride, int32_t width, int32_t height,
- int32_t cell_x, int32_t cell_w, int32_t ascent);
-
-// Center bitmap ink bounds, independent of advance and baseline bearings.
-int ui_font_raster_centered(UIFont *f, float px, uint32_t glyph, int bold,
- uint8_t *out, int32_t stride, int32_t width,
- int32_t height);
-
-void ui_font_free(UIFont *f);
-
-// HarfBuzz makes a few process-wide objects on first use and keeps them for
-// the life of the process (the default Unicode functions, the locale's
-// language, hb-ft's font functions). Making them here, with `f`'s face, lets
-// the caller hand them an allocator that does not count them as leaks.
-void ui_font_prime(UIFont *f);
-
-#ifdef __cplusplus
-}
-#endif
-#endif
diff --git a/src/gui/gui.zig b/src/gui/gui.zig
index d4603bec..aa6fc92b 100644
--- a/src/gui/gui.zig
+++ b/src/gui/gui.zig
@@ -1,4 +1,7 @@
const SketchGpu = @import("sketch_gpu");
+const Cells = @import("gpu_cells"); // sketchbook's src/gpu/Cells.zig
+const Atlas = @import("font_atlas"); // sketchbook's src/font/Atlas.zig
+const Present = @import("gpu_present"); // sketchbook's src/gpu/Present.zig
const GpuScene = @import("gpu_scene");
const filesystem = @import("../fs.zig");
const std = @import("std");
@@ -38,13 +41,6 @@ const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ"))
const log = std.log.scoped(.gui);
const font_ttf = @embedFile("AdwaitaMono-Regular.ttf");
-const vert_spv = @embedFile("ui.vert.spv");
-const frag_spv = @embedFile("ui.frag.spv");
-const decor_frag_spv = @embedFile("decor.frag.spv");
-const overlay_vert_spv = @embedFile("overlay.vert.spv");
-const overlay_frag_spv = @embedFile("overlay.frag.spv");
-const image_vert_spv = @embedFile("image.vert.spv");
-const image_frag_spv = @embedFile("image.frag.spv");
const bg_default = [3]u8{ 18, 18, 18 };
const fg_default = [3]u8{ 204, 204, 204 };
@@ -85,66 +81,11 @@ const p9_arrow_mask = blk: {
break :blk m;
};
-const atlas_w: u32 = 2048;
-const atlas_h: u32 = 2048;
-const Slot = struct { u: u32, v: u32 };
-/// An atlas entry is a glyph of a face (0 the primary font, i the fallback
-/// i - 1) at a role's size, drawn `span` cells wide with its own cell `lead`
-/// cells in: a ligature is one strip whose cells sample their own slices.
-/// Packed, so the atlas map hashes one word instead of walking fields.
-const GlyphKey = packed struct(u64) {
- face: u8,
- glyph: u32,
- role: pardes.FontRole,
- decoration: GlyphDecoration = .{},
- centered: bool = false,
- lead: u4 = 0,
- span: u4 = 1,
- /// A light box-drawing rule (`ruleArms`), drawn edge to edge rather
- /// than from the font; `glyph` is its codepoint.
- rule: bool = false,
- _: u1 = 0,
-};
-
-/// The light box-drawing rules drawn by hand, as Ghostty and kitty draw
-/// them: a logical pixel thick through the cell's middle, out to its edges,
-/// so a markdown table's `|` (Tables.zig) joins the rows above and below it
-/// and its delimiter row is one line across, at any line height a font's
-/// own glyph would leave gaps in. The arms each one has: left, right, up, down.
-fn ruleArms(cp: u32) ?[4]bool {
- return switch (cp) {
- 0x2500 => .{ true, true, false, false }, // ─
- 0x2502 => .{ false, false, true, true }, // │
- 0x250c => .{ false, true, false, true }, // ┌
- 0x2510 => .{ true, false, false, true }, // ┐
- 0x2514 => .{ false, true, true, false }, // └
- 0x2518 => .{ true, false, true, false }, // ┘
- 0x251c => .{ false, true, true, true }, // ├
- 0x2524 => .{ true, false, true, true }, // ┤
- 0x252c => .{ true, true, false, true }, // ┬
- 0x2534 => .{ true, true, true, false }, // ┴
- 0x253c => .{ true, true, true, true }, // ┼
- else => null,
- };
-}
-
-fn drawRule(out: [*]u8, stride: usize, width: usize, height: usize, arms: [4]bool) void {
- if (width == 0 or height == 0) return;
- const t: usize = @min(@max(1, @as(usize, @intFromFloat(dp(1)))), @min(width, height));
- const mx = (width - t) / 2;
- const my = (height - t) / 2;
- for (0..height) |y| @memset(out[y * stride ..][0..width], 0);
- if (arms[0] or arms[1]) for (0..t) |k| {
- const from: usize = if (arms[0]) 0 else mx;
- const to: usize = if (arms[1]) width else mx + t;
- @memset(out[(my + k) * stride + from ..][0 .. to - from], 255);
- };
- if (arms[2] or arms[3]) {
- const from: usize = if (arms[2]) 0 else my;
- const to: usize = if (arms[3]) height else my + t;
- for (from..to) |y| @memset(out[y * stride + mx ..][0..t], 255);
- }
-}
+const atlas_w = Atlas.atlas_w;
+const atlas_h = Atlas.atlas_h;
+const Slot = Atlas.Slot;
+const GlyphKey = Atlas.Key;
+const ruleArms = Atlas.ruleArms;
const GlyphDecoration = packed struct(u5) {
bold: bool = false,
@@ -161,6 +102,19 @@ const GlyphDecoration = packed struct(u5) {
}
};
+// The atlas's Key holds a GlyphDecoration and a FontRole as its own
+// Decoration and Role (@bitCast, @enumFromInt): the same bits, so the same
+// slots.
+comptime {
+ std.debug.assert(@bitSizeOf(GlyphDecoration) == @bitSizeOf(Atlas.Decoration));
+ for (.{ .{ @FieldType(pardes.CellStyle, "ul"), Atlas.Underline }, .{ pardes.FontRole, Atlas.Role } }) |pair| {
+ const ours = @typeInfo(pair[0]).@"enum";
+ const its = @typeInfo(pair[1]).@"enum";
+ std.debug.assert(ours.tag_type == its.tag_type and ours.field_names.len == its.field_names.len);
+ for (ours.field_names, its.field_names, ours.field_values, its.field_values) |a, b, x, y| std.debug.assert(std.mem.eql(u8, a, b) and x == y);
+ }
+}
+
const TaglineRaster = struct {
px: f32,
width: u32,
@@ -168,12 +122,12 @@ const TaglineRaster = struct {
height: u32,
};
-fn taglineRaster(font: *c.UIFont, body_px: f32, body_cell_w: u32, body_cell_h: u32, percent: u8) TaglineRaster {
+fn taglineRaster(atlas: *const Atlas, body_px: f32, body_cell_w: u32, body_cell_h: u32, percent: u8) TaglineRaster {
const px = body_px * @as(f32, @floatFromInt(percent)) / 100.0;
var own_w: c_int = 1;
var own_h: c_int = 1;
var own_ascent: c_int = 1;
- c.ui_font_cell_metrics(font, px, &own_w, &own_h, &own_ascent);
+ atlas.cellMetrics(px, &own_w, &own_h, &own_ascent);
const fixed_w: c_int = @intCast(body_cell_w);
const fixed_h: c_int = @intCast(body_cell_h);
const band_h = std.math.clamp(own_h, 1, fixed_h);
@@ -207,10 +161,9 @@ var sdl_allocator: std.mem.Allocator = undefined;
const sdl_heap = c_heap.Heap(&sdl_allocator);
const max_fallback_fonts = 1 + fonts.fallback_names.len;
-const LoadedFallback = struct {
- face: *c.UIFont,
- bytes: []u8 = &.{},
-};
+comptime {
+ std.debug.assert(max_fallback_fonts <= Atlas.max_fallbacks);
+}
const max_touch_points: usize = 16;
const touch_scroll_tick: f32 = 0.02;
@@ -223,69 +176,13 @@ const font_px_step: f32 = 2.0;
const font_px_min: f32 = 8.0;
const font_px_max: f32 = 72.0;
-const InkBounds = struct { min_x: usize, min_y: usize, max_x: usize, max_y: usize };
-
-fn inkBounds(bitmap: []const u8, stride: usize, w: usize, h: usize) ?InkBounds {
- var bounds: ?InkBounds = null;
- for (0..h) |y| for (0..w) |x| {
- if (bitmap[y * stride + x] == 0) continue;
- if (bounds) |*b| {
- b.min_x = @min(b.min_x, x);
- b.min_y = @min(b.min_y, y);
- b.max_x = @max(b.max_x, x);
- b.max_y = @max(b.max_y, y);
- } else bounds = .{ .min_x = x, .min_y = y, .max_x = x, .max_y = y };
- };
- return bounds;
-}
+const CellInstance = Cells.CellInstance;
+const OverlayVertex = Cells.OverlayVertex;
+const ImageInstance = Cells.ImageInstance;
+const opaque_bg_bit = Cells.opaque_bg_bit;
-const CellInstance = extern struct {
- x0: f32,
- y0: f32,
- x1: f32,
- y1: f32,
- u0: f32,
- v0: f32,
- u1: f32,
- v1: f32,
- fr: f32,
- fg: f32,
- fb: f32,
- br: f32,
- bg: f32,
- bb: f32,
- /// The flags (the high bits, ui.vert.glsl).
- effect: u32 = 0,
- /// A clip rectangle in target pixels; x1 < x0 is none (ui.vert.glsl).
- clip_x0: f32 = 0,
- clip_y0: f32 = 0,
- clip_x1: f32 = -1,
- clip_y1: f32 = -1,
-};
-
-const OverlayVertex = extern struct {
- x: f32,
- y: f32,
- r: f32,
- g: f32,
- b: f32,
- a: f32,
-};
const OverlayColor = struct { r: f32, g: f32, b: f32, a: f32 };
-const ImageInstance = extern struct {
- x0: f32,
- y0: f32,
- x1: f32,
- y1: f32,
- u0: f32,
- v0: f32,
- u1: f32,
- v1: f32,
-};
-
-const opaque_bg_bit: u32 = 0x2000_0000;
-
const PreparedImage = struct {
premultiplied: bool = false,
place: pardes.Placement,
@@ -523,29 +420,15 @@ const Gui = struct {
addon_hash: [pardes.MAX_PANES]u64 = @splat(0),
addon_serial: [pardes.MAX_PANES]u32 = @splat(0),
addon_failed: [pardes.MAX_PANES]u64 = @splat(0),
- addon_pipeline: ?*c.SDL_GPUGraphicsPipeline = null,
window: *c.SDL_Window,
- device: *c.SDL_GPUDevice,
- swapchain_format: c.SDL_GPUTextureFormat,
- pipeline: *c.SDL_GPUGraphicsPipeline,
- decor_pipeline: *c.SDL_GPUGraphicsPipeline,
- overlay_pipeline: *c.SDL_GPUGraphicsPipeline,
- image_pipeline: *c.SDL_GPUGraphicsPipeline,
- atlas_tex: *c.SDL_GPUTexture,
- atlas_sampler: *c.SDL_GPUSampler,
- linear_sampler: *c.SDL_GPUSampler,
- atlas_xfer: *c.SDL_GPUTransferBuffer,
- vbuf: ?*c.SDL_GPUBuffer = null,
- vxfer: ?*c.SDL_GPUTransferBuffer = null,
- vbuf_cells: u32 = 0,
- overlay_vbuf: *c.SDL_GPUBuffer,
- overlay_vxfer: *c.SDL_GPUTransferBuffer,
+ /// The device, the window's claim or soft presenter, the frame's target
+ /// and the capture's read back (runNative owns it).
+ present: *Present,
+ /// The pipelines, the atlas's texture, the pictures' textures and the
+ /// buffers the frame is drawn from, on present's device (runNative owns
+ /// it).
+ cells: *Cells,
overlay_vertices: []OverlayVertex,
- image_vbuf: ?*c.SDL_GPUBuffer = null,
- image_vxfer: ?*c.SDL_GPUTransferBuffer = null,
- image_capacity: u32 = 0,
- /// The textures of the placements shown, by key.
- native_images: std.AutoHashMapUnmanaged(u64, *c.SDL_GPUTexture) = .empty,
prepared_images: std.ArrayListUnmanaged(PreparedImage) = .empty,
/// The glyph art of the placements whose panes ask for it (Petscii
/// on), and the frame copy it is drawn into.
@@ -556,15 +439,13 @@ const Gui = struct {
/// renderFrame's decor instances, group by group (buildDecor).
decor: std.ArrayListUnmanaged(CellInstance) = .empty,
- font: *c.UIFont,
- font_bytes: []u8 = &.{},
+ /// The faces and the glyphs drawn from them.
+ atlas: Atlas,
font_name: [255]u8 = @splat(0),
font_name_len: u8 = 0,
/// A replica client's: the session's font request it last followed
/// (syncReplicaFont), as a hash of the request.
remote_font_request: ?u64 = null,
- fallbacks: [max_fallback_fonts]?LoadedFallback = @splat(null),
- fallback_count: usize = 0,
px: f32,
tagline_px: f32,
tagline_percent: u8,
@@ -575,15 +456,6 @@ const Gui = struct {
ascent: i32,
tagline_baseline: i32,
- atlas_stage: []u8,
- glyphs: std.AutoHashMap(GlyphKey, Slot),
- pen_x: u32 = 0,
- pen_y: u32 = 0,
- /// The atlas rows drawn into since the last upload, [top, bottom): the
- /// whole atlas at first, since the texture starts undefined.
- atlas_dirty_top: u32 = 0,
- atlas_dirty_bottom: u32 = atlas_h,
- space_slot: Slot = .{ .u = 0, .v = 0 },
words: Words = .{},
touch: Touch = .{},
@@ -655,7 +527,6 @@ const Gui = struct {
/// null attached, where the session's tag is another process's.
hit_core: ?*pardes.Pardes = null,
- capture: bool = false,
/// Pixels the capture holds past the grid (PARDES_TEST_PAD).
capture_pad: u32 = 0,
capture_dir: []const u8 = "",
@@ -663,27 +534,15 @@ const Gui = struct {
/// frame series to look at.
capture_series: bool = false,
captured: u32 = 0,
- capture_tex: ?*c.SDL_GPUTexture = null,
- capture_tex_w: u32 = 0,
- capture_tex_h: u32 = 0,
- capture_xfer: ?*c.SDL_GPUTransferBuffer = null,
- capture_xfer_size: u32 = 0,
- soft_present: bool = false,
- surface_opacity: bool = false,
applied_window_opacity: u8 = 100,
- soft_renderer: ?*c.SDL_Renderer = null,
- soft_texture: ?*c.SDL_Texture = null,
/// What a window is opened again with (reopenWindow): the flags (not
- /// hidden), the present mode, its size when it was closed.
+ /// hidden), its size when it was closed (present keeps its present mode).
win_flags: c.SDL_WindowFlags = 0,
- present_mode: c.SDL_GPUPresentMode = c.SDL_GPU_PRESENTMODE_VSYNC,
window_w: c_int = 1120,
window_h: c_int = 720,
/// The window runNative destroys at the end: the one open then, if any.
window_slot: ?*?*c.SDL_Window = null,
- soft_tex_w: u32 = 0,
- soft_tex_h: u32 = 0,
gamepad: ?*c.SDL_Gamepad = null,
pad_x: f32 = 0,
@@ -695,15 +554,13 @@ const Gui = struct {
/// What a window held of its own let go (closeWindow lets the window go).
fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void {
- if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture);
- if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer);
g.glide.deinit(gpa);
gpa.free(g.scroll_edge);
g.prepared_images.deinit(gpa);
}
fn setGuiFontName(g: *Gui, fallback: []const u8) void {
- const name = if (c.ui_font_name(g.font)) |name_z| std.mem.span(name_z) else fallback;
+ const name = if (g.atlas.fontName()) |name_z| std.mem.span(name_z) else fallback;
const len = @min(name.len, g.font_name.len);
@memcpy(g.font_name[0..len], name[0..len]);
g.font_name_len = @intCast(len);
@@ -741,14 +598,7 @@ fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator)
return false;
};
const bytes = filesystem.readFile(gpa, face.path) catch return false;
- const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse {
- gpa.free(bytes);
- return false;
- };
- c.ui_font_free(g.font);
- if (g.font_bytes.len != 0) gpa.free(g.font_bytes);
- g.font = font;
- g.font_bytes = bytes; // FreeType borrows them for the face lifetime
+ if (!g.atlas.setFont(gpa, bytes)) return false;
if (f.requested_size_hundredths != 0)
g.px = @as(f32, @floatFromInt(f.requested_size_hundredths)) / 100;
setGuiFontName(g, face.name);
@@ -757,52 +607,17 @@ fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator)
}
fn loadFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void {
- if (c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len))) |face| {
- g.fallbacks[0] = .{ .face = face };
- g.fallback_count = 1;
- }
+ _ = g.atlas.addFallback(gpa, font_ttf, false);
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
for (fonts.fallbacks(arena_state.allocator())) |candidate| {
- if (g.fallback_count == g.fallbacks.len) break;
+ if (g.atlas.fallback_count == max_fallback_fonts) break;
const bytes = filesystem.readFile(gpa, candidate.path) catch continue;
- const len = std.math.cast(c_int, bytes.len) orelse {
- gpa.free(bytes);
- continue;
- };
- const face = c.ui_font_new(bytes.ptr, len) orelse {
- gpa.free(bytes);
- continue;
- };
- g.fallbacks[g.fallback_count] = .{ .face = face, .bytes = bytes };
- g.fallback_count += 1;
+ _ = g.atlas.addFallback(gpa, bytes, true);
}
}
-fn deinitFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void {
- for (g.fallbacks[0..g.fallback_count]) |loaded| {
- const fallback = loaded.?;
- c.ui_font_free(fallback.face);
- if (fallback.bytes.len != 0) gpa.free(fallback.bytes);
- }
-}
-
-const FaceGlyph = struct { face: u8, glyph: u32 };
-
-/// The face and glyph that draw `cp`, the face as a GlyphKey face: 0 is the
-/// primary font and i the fallback i - 1. A codepoint no face has draws the
-/// primary's .notdef.
-fn glyphForCodepoint(g: *const Gui, cp: u32) FaceGlyph {
- const primary = c.ui_font_glyph(g.font, @intCast(cp));
- if (primary != 0) return .{ .face = 0, .glyph = primary };
- for (g.fallbacks[0..g.fallback_count], 1..) |loaded, face| {
- const glyph = c.ui_font_glyph(loaded.?.face, @intCast(cp));
- if (glyph != 0) return .{ .face = @intCast(face), .glyph = glyph };
- }
- return .{ .face = 0, .glyph = 0 };
-}
-
const CellLayout = struct { w: f32, h: f32, x_off: f32, y_off: f32 };
const MouseCell = struct { col: u16, row: u16, body_hit: ?pardes.Mouse.BodyHit = null, tag_hit: ?pardes.TagHit = null, rule_above: bool = false };
@@ -856,16 +671,7 @@ fn fixedCellLayout(g: *const Gui) CellLayout {
return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 };
}
-/// What one group draws, in this order: its cells, its images, then its
-/// decor.
-const Group = struct {
- cell_start: u32 = 0,
- cell_count: u32 = 0,
- image_start: u32 = 0,
- image_count: u32 = 0,
- decor_start: u32 = 0,
- decor_count: u32 = 0,
-};
+const Group = Cells.Group;
/// The frame's draw groups, bottom to top: the page and the panes, the
/// notices floating over them, the debug box the core paints over those,
@@ -1066,49 +872,18 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
if (arrow_cursor) |cur| {
_ = c.SDL_SetCursor(cur);
} else log.err("SDL_CreateCursor: {s}", .{c.SDL_GetError()});
- const device = c.SDL_CreateGPUDevice(c.SDL_GPU_SHADERFORMAT_SPIRV, true, null) orelse {
- log.err("SDL_CreateGPUDevice: {s}", .{c.SDL_GetError()});
- return error.SdlInit;
- };
- defer c.SDL_DestroyGPUDevice(device);
- var soft_present = false;
- var soft_renderer: ?*c.SDL_Renderer = null;
- if (surface_opacity or !c.SDL_ClaimWindowForGPUDevice(device, window)) {
- if (surface_opacity)
- log.info("transparent window: the GPU API will not claim one, presenting through SDL_Renderer", .{})
- else
- log.warn("ClaimWindowForGPUDevice: {s}; presenting in software", .{c.SDL_GetError()});
- soft_renderer = c.SDL_CreateRenderer(window, null) orelse {
- log.err("SDL_CreateRenderer: {s}", .{c.SDL_GetError()});
- return error.SdlInit;
- };
- soft_present = true;
- }
- const present_mode: c.SDL_GPUPresentMode = blk: {
- if (soft_present) break :blk c.SDL_GPU_PRESENTMODE_VSYNC;
- for ([_]c.SDL_GPUPresentMode{ c.SDL_GPU_PRESENTMODE_IMMEDIATE, c.SDL_GPU_PRESENTMODE_MAILBOX, c.SDL_GPU_PRESENTMODE_VSYNC }) |mode| {
- if (c.SDL_WindowSupportsGPUPresentMode(device, window, mode)) break :blk mode;
- }
- break :blk c.SDL_GPU_PRESENTMODE_VSYNC;
- };
- if (!test_mode) _ = c.SDL_SetGPUAllowedFramesInFlight(device, 1);
- if (!soft_present) {
- _ = c.SDL_SetGPUSwapchainParameters(device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, present_mode);
- }
- const swapchain_format = if (soft_present)
- softTargetFormat(device)
- else
- c.SDL_GetGPUSwapchainTextureFormat(device, window);
+ var presenter = try Present.init(window, test_mode, surface_opacity);
+ defer presenter.deinit();
font_allocator = gpa;
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)) orelse {
- log.err("ui_font_new failed", .{});
- return error.FontInit;
+ var atlas = Atlas.init(gpa, font_ttf) catch |err| {
+ log.err("the font atlas: {t}", .{err});
+ return err;
};
// HarfBuzz's process-wide objects are made once and never freed: made
// from the default heap, they stay out of a Debug build's leak report.
font_allocator = std.heap.smp_allocator;
- c.ui_font_prime(font);
+ atlas.prime();
font_allocator = gpa;
// A harness forcing a density (PARDES_TEST_SCALE) draws the text as a
// person on that display would size it, so its chrome is seen at the
@@ -1117,10 +892,10 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
var cw: c_int = 10;
var chh: c_int = 20;
var asc: c_int = 16;
- c.ui_font_cell_metrics(font, px, &cw, &chh, &asc);
+ atlas.cellMetrics(px, &cw, &chh, &asc);
const cell_w: u32 = @intCast(@max(cw, 1));
const cell_h: u32 = @intCast(@max(chh, 1));
- const tagline = taglineRaster(font, px, cell_w, cell_h, config.gui_tagline_font_percent);
+ const tagline = taglineRaster(&atlas, px, cell_w, cell_h, config.gui_tagline_font_percent);
if (test_mode) {
const cols = envU16(env, "PARDES_TEST_COLS") orelse 80;
const rows = envU16(env, "PARDES_TEST_ROWS") orelse 24;
@@ -1130,38 +905,11 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
_ = c.SDL_SyncWindow(window);
}
- const atlas_tex = texture2d(device, c.SDL_GPU_TEXTUREFORMAT_R8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, atlas_w, atlas_h) orelse return error.GpuCreate;
-
- var samp_info = std.mem.zeroes(c.SDL_GPUSamplerCreateInfo);
- samp_info.min_filter = c.SDL_GPU_FILTER_NEAREST;
- samp_info.mag_filter = c.SDL_GPU_FILTER_NEAREST;
- samp_info.mipmap_mode = c.SDL_GPU_FILTER_NEAREST;
- samp_info.address_mode_u = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
- samp_info.address_mode_v = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
- samp_info.address_mode_w = c.SDL_GPU_SAMPLERADDRESSMODE_CLAMP_TO_EDGE;
- const atlas_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate;
- samp_info.min_filter = c.SDL_GPU_FILTER_LINEAR;
- samp_info.mag_filter = c.SDL_GPU_FILTER_LINEAR;
- samp_info.mipmap_mode = c.SDL_GPU_FILTER_LINEAR;
- const linear_sampler = c.SDL_CreateGPUSampler(device, &samp_info) orelse return error.GpuCreate;
-
- var ax_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = atlas_w * atlas_h, .props = 0 };
- const atlas_xfer = c.SDL_CreateGPUTransferBuffer(device, &ax_info) orelse return error.GpuCreate;
-
- const pipeline = try makePipeline(device, swapchain_format, vert_spv, frag_spv, 1, 1, cell_input, std.mem.zeroes(c.SDL_GPUColorTargetBlendState));
- const decor_pipeline = try makePipeline(device, swapchain_format, vert_spv, decor_frag_spv, 0, 1, cell_input, backgroundLayerBlend());
- const overlay_pipeline = try makePipeline(device, swapchain_format, overlay_vert_spv, overlay_frag_spv, 0, 1, overlay_input, backgroundLayerBlend());
- const image_pipeline = try makePipeline(device, swapchain_format, image_vert_spv, image_frag_spv, 1, 1, image_input, backgroundLayerBlend());
+ var cells = try Cells.init(presenter.device, presenter.swapchain_format, max_overlay_vertices);
+ // The pipelines, textures and buffers it holds, whatever they were
+ // regrown to, before the device (presenter's defer).
+ defer cells.deinit(gpa);
- const overlay_buffer_size: u32 = @intCast(max_overlay_vertices * @sizeOf(OverlayVertex));
- var ovb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = overlay_buffer_size, .props = 0 };
- const overlay_vbuf = c.SDL_CreateGPUBuffer(device, &ovb_info) orelse return error.GpuCreate;
- var ovx_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = overlay_buffer_size, .props = 0 };
- const overlay_vxfer = c.SDL_CreateGPUTransferBuffer(device, &ovx_info) orelse return error.GpuCreate;
-
- const atlas_stage = try gpa.alloc(u8, atlas_w * atlas_h);
- defer gpa.free(atlas_stage);
- @memset(atlas_stage, 0);
const overlay_vertices = try gpa.alloc(OverlayVertex, max_overlay_vertices);
defer gpa.free(overlay_vertices);
@@ -1170,20 +918,10 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
.arrow_cursor = arrow_cursor,
.link_cursor = link_cursor,
.box_cursor = box_cursor,
- .device = device,
- .swapchain_format = swapchain_format,
- .pipeline = pipeline,
- .decor_pipeline = decor_pipeline,
- .overlay_pipeline = overlay_pipeline,
- .image_pipeline = image_pipeline,
- .atlas_tex = atlas_tex,
- .atlas_sampler = atlas_sampler,
- .linear_sampler = linear_sampler,
- .atlas_xfer = atlas_xfer,
- .overlay_vbuf = overlay_vbuf,
- .overlay_vxfer = overlay_vxfer,
+ .present = &presenter,
+ .cells = &cells,
.overlay_vertices = overlay_vertices,
- .font = font,
+ .atlas = atlas,
.px = px,
.tagline_px = tagline.px,
.tagline_percent = config.gui_tagline_font_percent,
@@ -1193,62 +931,29 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
.cell_h = cell_h,
.ascent = asc,
.tagline_baseline = tagline.baseline,
- .atlas_stage = atlas_stage,
- .glyphs = std.AutoHashMap(GlyphKey, Slot).init(gpa),
- .capture = test_mode,
.capture_pad = if (test_mode) envU16(env, "PARDES_TEST_PAD") orelse 0 else 0,
.capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null,
.capture_dir = capture_dir orelse "",
- .soft_present = soft_present,
.demo = if (env.get("PARDES_FRAMES_DEMO")) |path| try pardes.FrameStats.readScript(init.arena.allocator(), init.io, path) else &.{},
.demo_next = if (env.get("PARDES_FRAMES_DEMO") != null) 0 else null,
- .surface_opacity = surface_opacity,
- .soft_renderer = soft_renderer,
.win_flags = reopen_flags,
- .present_mode = present_mode,
.window_w = want_w,
.window_h = want_h,
.window_slot = &window_slot,
};
- // The pipelines, textures and buffers the Gui holds, whatever they were
- // regrown to; the image ones are released below.
- defer {
- c.SDL_ReleaseGPUGraphicsPipeline(device, g.pipeline);
- c.SDL_ReleaseGPUGraphicsPipeline(device, g.decor_pipeline);
- c.SDL_ReleaseGPUGraphicsPipeline(device, g.overlay_pipeline);
- c.SDL_ReleaseGPUTexture(device, g.atlas_tex);
- c.SDL_ReleaseGPUSampler(device, g.atlas_sampler);
- c.SDL_ReleaseGPUSampler(device, g.linear_sampler);
- c.SDL_ReleaseGPUTransferBuffer(device, g.atlas_xfer);
- c.SDL_ReleaseGPUBuffer(device, g.overlay_vbuf);
- c.SDL_ReleaseGPUTransferBuffer(device, g.overlay_vxfer);
- if (g.vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer);
- if (g.vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
- if (g.image_vbuf) |buffer| c.SDL_ReleaseGPUBuffer(device, buffer);
- if (g.image_vxfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
- if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(device, texture);
- if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(device, transfer);
- if (g.gamepad) |pad| c.SDL_CloseGamepad(pad);
- }
+ defer if (g.gamepad) |pad| c.SDL_CloseGamepad(pad);
setGuiFontName(&g, "Adwaita Mono");
loadFallbackFonts(&g, gpa);
- defer deinitFallbackFonts(&g, gpa);
- defer g.glyphs.deinit();
+ defer g.atlas.deinit(gpa);
defer g.words.deinit(gpa);
defer {
if (g.addon_gpu) |*gpu| gpu.deinit();
- if (g.addon_pipeline) |pipeline_| c.SDL_ReleaseGPUGraphicsPipeline(device, pipeline_);
- clearNativeImages(&g);
- g.native_images.deinit(gpa);
g.prepared_images.deinit(gpa);
g.art.deinit(gpa);
if (g.art_arena) |*arena| arena.deinit();
g.cover.deinit(gpa);
g.decor.deinit(gpa);
}
- defer c.SDL_ReleaseGPUGraphicsPipeline(device, image_pipeline);
- defer if (g.font_bytes.len != 0) gpa.free(g.font_bytes); // set by Font, if it ran
- defer c.ui_font_free(g.font);
defer gpa.free(g.scroll_edge); // grown on demand by stepScroll
defer g.glide.deinit(gpa);
resetGlyphAtlas(&g);
@@ -1266,14 +971,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di
fn closeWindow(g: *Gui) void {
_ = c.SDL_GetWindowSize(g.window, &g.window_w, &g.window_h);
_ = c.SDL_StopTextInput(g.window);
- if (g.soft_renderer) |renderer| {
- if (g.soft_texture) |texture| c.SDL_DestroyTexture(texture);
- g.soft_texture = null;
- g.soft_tex_w = 0;
- g.soft_tex_h = 0;
- c.SDL_DestroyRenderer(renderer);
- g.soft_renderer = null;
- } else c.SDL_ReleaseWindowFromGPUDevice(g.device, g.window);
+ g.present.detach(g.window);
c.SDL_DestroyWindow(g.window);
if (g.window_slot) |slot| if (slot.* == g.window) {
slot.* = null;
@@ -1285,17 +983,9 @@ fn closeWindow(g: *Gui) void {
fn reopenWindow(g: *Gui) bool {
const window = c.SDL_CreateWindow("pardes", g.window_w, g.window_h, g.win_flags) orelse return false;
if (comptime builtin.os.tag == .macos) c.ui_macos_trackpad_attach(window);
- if (g.soft_present) {
- g.soft_renderer = c.SDL_CreateRenderer(window, null) orelse {
- c.SDL_DestroyWindow(window);
- return false;
- };
- } else {
- if (!c.SDL_ClaimWindowForGPUDevice(g.device, window)) {
- c.SDL_DestroyWindow(window);
- return false;
- }
- _ = c.SDL_SetGPUSwapchainParameters(g.device, window, c.SDL_GPU_SWAPCHAINCOMPOSITION_SDR, g.present_mode);
+ if (!g.present.attach(window)) {
+ c.SDL_DestroyWindow(window);
+ return false;
}
g.window = window;
if (g.window_slot) |slot| slot.* = window;
@@ -1303,7 +993,7 @@ fn reopenWindow(g: *Gui) bool {
// ponytail: another view's window asks the hit test of whichever
// window's share the Gui holds then (the workspace tag sits in the same
// place in every view); a test per window if one moves it.
- if (!g.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g);
+ if (!g.present.capture) _ = c.SDL_SetWindowHitTest(window, hitTest, g);
_ = c.SDL_StartTextInput(window);
return true;
}
@@ -1469,7 +1159,7 @@ fn localSession(
// One view, the window's (host_io.restoreCore).
shell.gview = 0;
shell.stopPtys();
- clearNativeImages(g);
+ g.cells.clearImages();
g.prepared_images.clearRetainingCapacity();
nc.view().frontend.native_images = true;
nc.view().frontend.native_image_patches = true;
@@ -3292,16 +2982,11 @@ fn pollFrame(ctx: ?*anyopaque) void {
core.rejectFont();
break :blk;
};
- const nf = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse {
+ if (!g.atlas.setFont(s.gpa, bytes)) {
log.err("ui_font_new failed: {s}", .{path});
- s.gpa.free(bytes);
core.rejectFont();
break :blk;
- };
- c.ui_font_free(g.font);
- if (g.font_bytes.len != 0) s.gpa.free(g.font_bytes);
- g.font = nf;
- g.font_bytes = bytes; // FreeType borrows them for the face lifetime
+ }
if (core.settings.font.requested_size_hundredths != 0)
g.px = @as(f32, @floatFromInt(core.settings.font.requested_size_hundredths)) / 100;
setGuiFontName(g, core.settings.font.requested_name.get());
@@ -3325,7 +3010,8 @@ fn pollFrame(ctx: ?*anyopaque) void {
var frame_capture_dir: ?[]const u8 = null;
var frame_capture_count: u32 = 0;
-fn captureSeries(dir: []const u8, pixels: []const u8, w: u32, h: u32) void {
+fn captureSeries(pixels: []const u8, w: u32, h: u32) void {
+ const dir = frame_capture_dir orelse return;
var path_buf: [4096]u8 = undefined;
const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{d:0>6}.bgra", .{ dir, frame_capture_count }, 0) catch return;
const fd = libc.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
@@ -3482,7 +3168,7 @@ fn syncWindowOpacity(g: *Gui, core: *pardes.Pardes) void {
if (!core.settings.window_opacity_pending) return;
// Offscreen captures also support per-pixel alpha. Never approximate this
// with SDL_SetWindowOpacity: that would make foreground text translucent.
- finishWindowOpacity(core, &g.applied_window_opacity, if (g.surface_opacity or g.capture or core.settings.window_opacity == 100)
+ finishWindowOpacity(core, &g.applied_window_opacity, if (g.present.surface_opacity or g.present.capture or core.settings.window_opacity == 100)
null
else
"background transparency requires a native Wayland or alpha-capable SDL window");
@@ -4200,17 +3886,6 @@ fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect
return .{ .x = x0, .y = y0, .w = x1 - x0, .h = y1 - y0 };
}
-fn releaseNativeImage(g: *Gui, key: u64) void {
- if (g.native_images.fetchRemove(key)) |removed|
- c.SDL_ReleaseGPUTexture(g.device, removed.value);
-}
-
-fn clearNativeImages(g: *Gui) void {
- var iterator = g.native_images.valueIterator();
- while (iterator.next()) |texture| c.SDL_ReleaseGPUTexture(g.device, texture.*);
- g.native_images.clearRetainingCapacity();
-}
-
/// A placement the window shows as a texture: pixels, not glyph art.
fn texturePlacement(place: pardes.Placement) bool {
return !place.art.glyph and validImageBytes(place) != null;
@@ -4249,72 +3924,13 @@ fn uploadNativeTexture(
place: pardes.Placement,
) !void {
const byte_len = validImageBytes(place) orelse return error.BadImage;
- const key = place.key;
- if (g.native_images.contains(key)) return;
const r = place.raster;
- const row = r.stride;
- if (place.dirty) |dirty| dirty: {
- // The core changed only these rows since a picture we still hold:
- // write them into that texture rather than sending the whole page.
- if (dirty.y + dirty.h > r.h) break :dirty;
- const texture = g.native_images.get(dirty.from) orelse break :dirty;
- try uploadTextureRows(g, cmd, texture, r.bytes()[dirty.y * row ..][0 .. dirty.h * row], r.w, dirty.y, dirty.h);
- try g.native_images.put(gpa, key, texture);
- _ = g.native_images.remove(dirty.from);
- return;
- }
-
- const texture = texture2d(g.device, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREUSAGE_SAMPLER, r.w, r.h) orelse return error.GpuCreate;
- errdefer c.SDL_ReleaseGPUTexture(g.device, texture);
- try uploadTextureRows(g, cmd, texture, r.bytes()[0..byte_len], r.w, 0, r.h);
- try g.native_images.put(gpa, key, texture);
-}
-
-/// Copy `rows` rows of RGBA, `width` pixels each, into `texture` at row `y`.
-fn uploadTextureRows(
- g: *Gui,
- cmd: *c.SDL_GPUCommandBuffer,
- texture: *c.SDL_GPUTexture,
- rgba: []const u8,
- width: usize,
- y: usize,
- rows: usize,
-) !void {
- var xf_info = c.SDL_GPUTransferBufferCreateInfo{
- .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD,
- .size = @intCast(rgba.len),
- .props = 0,
- };
- const transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate;
- defer c.SDL_ReleaseGPUTransferBuffer(g.device, transfer);
- const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, transfer, false) orelse return error.GpuMap);
- @memcpy(mapped[0..rgba.len], rgba);
- c.SDL_UnmapGPUTransferBuffer(g.device, transfer);
-
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTextureTransferInfo{
- .transfer_buffer = transfer,
- .offset = 0,
- .pixels_per_row = @intCast(width),
- .rows_per_layer = @intCast(rows),
- };
- const dst = c.SDL_GPUTextureRegion{
- .texture = texture,
- .mip_level = 0,
- .layer = 0,
- .x = 0,
- .y = @intCast(y),
- .z = 0,
- .w = @intCast(width),
- .h = @intCast(rows),
- .d = 1,
- };
- c.SDL_UploadToGPUTexture(copy, &src, &dst, false);
- c.SDL_EndGPUCopyPass(copy);
+ const dirty: ?Cells.Dirty = if (place.dirty) |d| .{ .from = d.from, .y = d.y, .h = d.h } else null;
+ try g.cells.image(gpa, cmd, place.key, r.bytes()[0..byte_len], r.w, r.h, r.stride, dirty);
}
fn appendPreparedImage(g: *Gui, gpa: std.mem.Allocator, place: pardes.Placement) void {
- const texture = g.native_images.get(place.key) orelse return;
+ const texture = g.cells.native_images.get(place.key) orelse return;
if (nativePlaceGeometry(g, place) == null) return;
g.prepared_images.append(gpa, .{ .place = place, .texture = texture }) catch {};
}
@@ -4373,14 +3989,14 @@ fn prepareNativeImages(
while (true) {
var stale: [pardes.MAX_PANES]u64 = undefined;
var stale_len: usize = 0;
- var iterator = g.native_images.iterator();
+ var iterator = g.cells.native_images.iterator();
while (iterator.next()) |entry| {
if (surfaceHasNativeKey(surface, entry.key_ptr.*)) continue;
stale[stale_len] = entry.key_ptr.*;
stale_len += 1;
if (stale_len == stale.len) break;
}
- for (stale[0..stale_len]) |key| releaseNativeImage(g, key);
+ for (stale[0..stale_len]) |key| g.cells.releaseImage(key);
if (stale_len < stale.len) break;
}
@@ -4394,25 +4010,18 @@ fn prepareNativeImages(
const capacity = std.math.cast(u32, g.prepared_images.items.len) orelse return false;
if (capacity == 0) return true;
- growInstances(g, &g.image_vbuf, &g.image_vxfer, &g.image_capacity, capacity, @sizeOf(ImageInstance)) catch return false;
-
- const ptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.image_vxfer.?, false) orelse return false);
- const instances: [*]ImageInstance = @ptrCast(@alignCast(ptr));
+ const instances = g.cells.mapImages(gpa, capacity) orelse return false;
const win_w: f32 = @floatFromInt(sw);
const win_h: f32 = @floatFromInt(sh);
var idx: u32 = 0;
for (g.prepared_images.items) |prepared| {
+ // Drawn in this order, instance by instance (Cells.drawImages).
+ g.cells.images.appendAssumeCapacity(.{ .premultiplied = prepared.premultiplied, .texture = prepared.texture, .clip = imageScissor(g, prepared.place) });
if (!emitPreparedImage(g, surface, &instances[idx], prepared, win_w, win_h)) continue;
idx += 1;
}
- c.SDL_UnmapGPUTransferBuffer(g.device, g.image_vxfer.?);
std.debug.assert(idx == capacity);
-
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.image_vxfer.?, .offset = 0 };
- const dst = c.SDL_GPUBufferRegion{ .buffer = g.image_vbuf.?, .offset = 0, .size = idx * @sizeOf(ImageInstance) };
- c.SDL_UploadToGPUBuffer(copy, &src, &dst, false);
- c.SDL_EndGPUCopyPass(copy);
+ g.cells.uploadImages(cmd, idx);
return true;
}
@@ -4425,35 +4034,6 @@ fn imageScissor(g: *const Gui, place: pardes.Placement) c.SDL_Rect {
};
}
-fn drawNativeImagesGpu(
- g: *Gui,
- rp: ?*c.SDL_GPURenderPass,
- batch: Group,
- whole: c.SDL_Rect,
-) void {
- const pass = rp orelse return;
- c.SDL_BindGPUGraphicsPipeline(pass, g.image_pipeline);
- var idx = batch.image_start;
- const end = batch.image_start + batch.image_count;
- for (g.prepared_images.items[batch.image_start..end]) |prepared| {
- c.SDL_BindGPUGraphicsPipeline(pass, if (prepared.premultiplied) g.addon_pipeline.? else g.image_pipeline);
- const clip = imageScissor(g, prepared.place);
- if (clip.w > 0 and clip.h > 0) {
- c.SDL_SetGPUScissor(pass, &clip);
- const sampler = c.SDL_GPUTextureSamplerBinding{ .texture = prepared.texture, .sampler = g.linear_sampler };
- c.SDL_BindGPUFragmentSamplers(pass, 0, &sampler, 1);
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.image_vbuf.?, .offset = idx * @sizeOf(ImageInstance) };
- c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1);
- c.SDL_DrawGPUPrimitives(pass, 6, 1, 0, 0);
- }
- idx += 1;
- }
- std.debug.assert(idx == batch.image_start + batch.image_count);
- // Back to the whole target: what draws after a picture may run on past
- // the grid, as a rule and a band do.
- c.SDL_SetGPUScissor(pass, &whole);
-}
-
fn renderFrame(
g: *Gui,
gpa: std.mem.Allocator,
@@ -4475,14 +4055,14 @@ fn renderFrame(
if (cursor) |value| _ = c.SDL_SetCursor(value);
}
g.words.memo = .{}; // positional, and this frame's cells are new
- const cmd = c.SDL_AcquireGPUCommandBuffer(g.device) orelse return false;
+ const cmd = g.cells.begin() orelse return false;
var command_consumed = false;
defer if (!command_consumed) {
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
+ Cells.submit(cmd);
};
- const frame_target = try acquireTarget(g, cmd, @as(u32, surface.cols) * g.cell_w + g.capture_pad, @as(u32, surface.rows) * g.cell_h + g.capture_pad) orelse {
+ const frame_target = try g.present.acquireTarget(cmd, g.window, @as(u32, surface.cols) * g.cell_w + g.capture_pad, @as(u32, surface.rows) * g.cell_h + g.capture_pad) orelse {
command_consumed = true;
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
+ Cells.submit(cmd);
return false;
};
const target = frame_target.texture;
@@ -4523,7 +4103,7 @@ fn renderFrame(
core.frames.caret = caretRow(g, surface, now) orelse 0;
const cursors_shown = !quad_mode;
var overlay_count = buildOverlay(g, core.settings.pet, core.settings.jump_trail, surface, now, sw, sh);
- if (overlay_count != 0 and !uploadOverlayGpu(g, cmd, overlay_count))
+ if (overlay_count != 0 and !g.cells.uploadOverlay(cmd, g.overlay_vertices[0..overlay_count]))
overlay_count = 0;
if (!prepareNativeImages(g, gpa, cmd, surface, &groups, sw, sh)) {
g.prepared_images.clearRetainingCapacity();
@@ -4542,16 +4122,12 @@ fn renderFrame(
const page = chrome.page orelse bg_default;
const background_opacity = backgroundOpacity(g.applied_window_opacity);
- var color_target = std.mem.zeroes(c.SDL_GPUColorTargetInfo);
- color_target.texture = target;
- color_target.clear_color = .{
+ const clear: c.SDL_FColor = .{
.r = @as(f32, @floatFromInt(page[0])) / 255.0 * background_opacity,
.g = @as(f32, @floatFromInt(page[1])) / 255.0 * background_opacity,
.b = @as(f32, @floatFromInt(page[2])) / 255.0 * background_opacity,
.a = background_opacity,
};
- color_target.load_op = c.SDL_GPU_LOADOP_CLEAR;
- color_target.store_op = c.SDL_GPU_STOREOP_STORE;
var shifted: u32 = 0;
var row: u16 = 0;
@@ -4590,14 +4166,11 @@ fn renderFrame(
// The shifted rows of a scroll: its body, a glide's rows past it, and
// a body layer's rows past the grid's.
const capacity = std.math.add(u32, cell_total, 3 * cells + decor_len) catch return error.GpuCapacity;
- try growInstances(g, &g.vbuf, &g.vxfer, &g.vbuf_cells, capacity, @sizeOf(CellInstance));
-
- const vptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.vxfer.?, false) orelse {
+ const instances = try g.cells.mapCells(capacity) orelse {
command_consumed = true;
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
+ Cells.submit(cmd);
return false;
- });
- const instances: [*]CellInstance = @ptrCast(@alignCast(vptr));
+ };
const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else cells;
const cursor_bar = if (surface.cursor) |cu| cu.bar else false;
row = 0;
@@ -4648,98 +4221,36 @@ fn renderFrame(
const held: u16 = if (scrolling) |id| if (core.panes[id]) |pane| pane.context_rows else 0 else 0;
shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page, held);
@memcpy(instances[cell_total + shifted ..][0..decor_len], g.decor.items);
- c.SDL_UnmapGPUTransferBuffer(g.device, g.vxfer.?);
-
- if (g.atlas_dirty_top < g.atlas_dirty_bottom) uploadAtlas(g, cmd);
-
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.vxfer.?, .offset = 0 };
- const dst = c.SDL_GPUBufferRegion{ .buffer = g.vbuf.?, .offset = 0, .size = (cell_total + shifted + decor_len) * @sizeOf(CellInstance) };
- c.SDL_UploadToGPUBuffer(copy, &src, &dst, false);
- c.SDL_EndGPUCopyPass(copy);
+ g.cells.uploadCells(cmd, cell_total + shifted + decor_len, &g.atlas);
}
build_zone.end();
building = false;
if (frame_probe) |probe| probe.zone(.gui_build, probe_build);
- const rp = c.SDL_BeginGPURenderPass(cmd, &color_target, 1, null);
- pushLayerOpacity(cmd, rp, background_opacity);
- const whole = c.SDL_Rect{ .x = 0, .y = 0, .w = @intCast(sw), .h = @intCast(sh) };
- const decor_base = cell_total + shifted;
- for (groups.items[0..groups.len], 0..) |group, index| {
- const has_shifted = index == 0 and shifted != 0;
- if ((group.cell_count != 0 or has_shifted) and g.vbuf != null) {
- c.SDL_BindGPUGraphicsPipeline(rp, g.pipeline);
- const samp_binding = c.SDL_GPUTextureSamplerBinding{ .texture = g.atlas_tex, .sampler = g.atlas_sampler };
- c.SDL_BindGPUFragmentSamplers(rp, 0, &samp_binding, 1);
- if (group.cell_count != 0) {
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.vbuf.?, .offset = group.cell_start * @sizeOf(CellInstance) };
- c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1);
- c.SDL_DrawGPUPrimitives(rp, 6, group.cell_count, 0, 0);
- }
- if (has_shifted) {
- const clip = scrollScissor(g, layout, sw, sh);
- c.SDL_SetGPUScissor(rp, &clip);
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.vbuf.?, .offset = cell_total * @sizeOf(CellInstance) };
- c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1);
- c.SDL_DrawGPUPrimitives(rp, 6, shifted, 0, 0);
- c.SDL_SetGPUScissor(rp, &whole);
- }
- }
- if (group.image_count != 0) drawNativeImagesGpu(g, rp, group, whole);
- if (group.decor_count != 0 and g.vbuf != null) {
- c.SDL_BindGPUGraphicsPipeline(rp, g.decor_pipeline);
- // Ink keeps its colour at any WindowOpacity.
- pushLayerOpacity(cmd, rp, if (index == groups.ink) 1 else background_opacity);
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.vbuf.?, .offset = (decor_base + group.decor_start) * @sizeOf(CellInstance) };
- c.SDL_BindGPUVertexBuffers(rp, 0, &binding, 1);
- c.SDL_DrawGPUPrimitives(rp, 6, group.decor_count, 0, 0);
- }
- }
- drawOverlayGpu(g, cmd, rp, overlay_count);
- c.SDL_EndGPURenderPass(rp);
+ // Drawn only over a scroll's shifted rows (scrollScissor asks a scroll).
+ const scroll_clip = if (shifted != 0) scrollScissor(g, layout, sw, sh) else std.mem.zeroes(c.SDL_Rect);
+ g.cells.record(cmd, target, sw, sh, clear, background_opacity, groups.items[0..groups.len], groups.ink, cell_total, shifted, scroll_clip, overlay_count);
command_consumed = true;
return finishFrame(g, gpa, cmd, frame_target);
}
-const Target = struct { texture: *c.SDL_GPUTexture, w: u32, h: u32 };
-
-/// What this frame draws into: the capture texture in test mode (the grid's
-/// size plus PARDES_TEST_PAD) or with a soft presenter, else the swapchain's
-/// image; null when there is none to be had this time.
-fn acquireTarget(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, capture_w: u32, capture_h: u32) !?Target {
- if (g.capture) {
- if (capture_w == 0 or capture_h == 0) return null;
- try ensureCaptureTexture(g, capture_w, capture_h);
- return .{ .texture = g.capture_tex.?, .w = capture_w, .h = capture_h };
- }
- if (g.soft_present) {
- var pw: c_int = 0;
- var ph: c_int = 0;
- if (!c.SDL_GetWindowSizeInPixels(g.window, &pw, &ph) or pw <= 0 or ph <= 0) return null;
- try ensureCaptureTexture(g, @intCast(pw), @intCast(ph));
- return .{ .texture = g.capture_tex.?, .w = @intCast(pw), .h = @intCast(ph) };
- }
- var swap_tex: ?*c.SDL_GPUTexture = null;
- var sw: u32 = 0;
- var sh: u32 = 0;
- if (!c.SDL_AcquireGPUSwapchainTexture(cmd, g.window, &swap_tex, &sw, &sh)) return null;
- // A busy swapchain skips the frame.
- return .{ .texture = swap_tex orelse return null, .w = sw, .h = sh };
-}
-
/// Submits the frame: captured, handed to the soft presenter, or presented.
-fn finishFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: Target) !bool {
- if (g.capture) {
+fn finishFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: Present.Target) !bool {
+ if (g.present.capture) {
try captureFrame(g, gpa, cmd, target.texture, target.w, target.h);
return true;
}
- if (g.soft_present) {
- try softPresentFrame(g, cmd, target.texture, target.w, target.h);
- return true;
- }
- return c.SDL_SubmitGPUCommandBuffer(cmd);
+ var took: Present.Timings = .{};
+ const presented = try g.present.finishFrame(cmd, target, &captureSeries, &took);
+ // A soft present's wait for the GPU, its upload of the frame and its flip.
+ if (g.present.soft_present) if (frame_probe) |probe| {
+ const now = monoNs();
+ probe.zone(.gui_wait, now -| took.wait_ns);
+ probe.zone(.gui_upload, now -| took.upload_ns);
+ probe.zone(.gui_flip, now -| took.flip_ns);
+ };
+ return presented;
}
const ResolvedCell = struct {
@@ -5016,9 +4527,9 @@ fn emitSurfaceCell(
if (grip) {
// A grip is one glyph centered across the gutter, not text: it is
// looked up by its codepoint's glyph, never shaped.
- const drawn = glyphForCodepoint(g, cellCodepoint(glyph));
- const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = GlyphDecoration.fromCell(glyph), .centered = true });
- const slot = cached orelse g.space_slot;
+ const drawn = g.atlas.glyphForCodepoint(cellCodepoint(glyph));
+ const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = @bitCast(GlyphDecoration.fromCell(glyph)), .centered = true });
+ const slot = cached orelse g.atlas.space_slot;
const b = button.?;
const center = (b[0] + b[2]) / 2 - @as(f32, @floatFromInt(col - offset)) * body_layout.w;
const shift: f32 = if (cached != null) @as(f32, @floatFromInt(@as(u32, offset) * g.cell_w)) + @as(f32, @floatFromInt(config.GUTTER * g.cell_w)) / 2 - center else 0;
@@ -5053,10 +4564,10 @@ fn emitSurfaceCell(
// Over it, only its own glyph; the band round it and the ring
// are decor (gripDecor).
if (here.pane_grip and !grip) {
- instances[next.*].u0 = @as(f32, @floatFromInt(g.space_slot.u)) / atlas_w;
+ instances[next.*].u0 = @as(f32, @floatFromInt(g.atlas.space_slot.u)) / atlas_w;
instances[next.*].u1 = instances[next.*].u0 + @as(f32, @floatFromInt(g.cell_w)) / atlas_w;
- instances[next.*].v0 = @as(f32, @floatFromInt(g.space_slot.v)) / atlas_h;
- instances[next.*].v1 = @as(f32, @floatFromInt(g.space_slot.v + g.tagline_height)) / atlas_h;
+ instances[next.*].v0 = @as(f32, @floatFromInt(g.atlas.space_slot.v)) / atlas_h;
+ instances[next.*].v1 = @as(f32, @floatFromInt(g.atlas.space_slot.v + g.tagline_height)) / atlas_h;
}
// Its ground is the fill again.
instances[next.*].br = base.br;
@@ -5150,11 +4661,11 @@ fn refitFont(g: *Gui, core: ?*pardes.Pardes) void {
var cw: c_int = 10;
var chh: c_int = 20;
var asc: c_int = 16;
- c.ui_font_cell_metrics(g.font, g.px, &cw, &chh, &asc);
+ g.atlas.cellMetrics(g.px, &cw, &chh, &asc);
g.cell_w = @intCast(@max(cw, 1));
g.cell_h = @intCast(@max(chh, 1));
g.ascent = @intCast(@max(asc, 1));
- const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, g.tagline_percent);
+ const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, g.tagline_percent);
g.tagline_px = tagline.px;
g.tagline_width = tagline.width;
g.tagline_baseline = tagline.baseline;
@@ -5172,14 +4683,8 @@ fn refitFont(g: *Gui, core: ?*pardes.Pardes) void {
// The first cell of the cleared atlas stays blank: the space slot.
fn resetGlyphAtlas(g: *Gui) void {
- g.glyphs.clearRetainingCapacity();
+ g.atlas.reset(g.cell_w);
g.words.clear();
- @memset(g.atlas_stage, 0);
- g.space_slot = .{ .u = 0, .v = 0 };
- g.pen_x = g.cell_w;
- g.pen_y = 0;
- g.atlas_dirty_top = 0;
- g.atlas_dirty_bottom = atlas_h;
}
fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void {
@@ -5192,7 +4697,7 @@ fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void {
fn fitTaglineFont(g: *Gui, percent: u8) bool {
if (percent == g.tagline_percent) return false;
g.tagline_percent = percent;
- const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, percent);
+ const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, percent);
g.tagline_px = tagline.px;
g.tagline_width = tagline.width;
g.tagline_baseline = tagline.baseline;
@@ -5289,19 +4794,18 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role:
return words.slots.items[memo.slots + at - memo.start];
var here = wordCell(&line[at]);
// An underlined or struck-out space is a glyph of its own: it draws its line.
- if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.space_slot;
+ if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.atlas.space_slot;
if (ruleArms(here.cp) != null)
- return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = role, .rule = true }) orelse g.space_slot;
- const gpa = g.glyphs.allocator;
+ return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = @fromBackingInt(@intCast(@backingInt(role))), .rule = true }) orelse g.atlas.space_slot;
+ const gpa = g.atlas.glyphs.allocator;
const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration };
- const known = words.cells.getOrPut(gpa, cell_key) catch return g.space_slot;
+ const known = words.cells.getOrPut(gpa, cell_key) catch return g.atlas.space_slot;
if (!known.found_existing) {
- const drawn = glyphForCodepoint(g, here.cp);
- const font = if (drawn.face == 0) g.font else g.fallbacks[drawn.face - 1].?.face;
- known.value_ptr.* = if (role == .body and c.ui_font_substitutes(font, drawn.glyph) != 0)
+ const drawn = g.atlas.glyphForCodepoint(here.cp);
+ known.value_ptr.* = if (role == .body and g.atlas.substitutes(drawn.face, drawn.glyph))
Words.shape_slot
else
- cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = role, .decoration = here.decoration }) orelse g.space_slot;
+ cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = @fromBackingInt(@intCast(@backingInt(role))), .decoration = @bitCast(here.decoration) }) orelse g.atlas.space_slot;
}
const plain = known.value_ptr.*;
if (!std.meta.eql(plain, Words.shape_slot)) return plain;
@@ -5319,7 +4823,7 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role:
const text_start = words.text.items.len;
var end = start;
while (true) {
- words.text.append(gpa, here.cp) catch return g.space_slot;
+ words.text.append(gpa, here.cp) catch return g.atlas.space_slot;
end += 1;
if (end == line.len) break;
const next = wordCell(&line[end]);
@@ -5349,27 +4853,26 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role:
const n = text.len;
words.slots.ensureUnusedCapacity(gpa, n) catch {
words.text.shrinkRetainingCapacity(text_start);
- return g.space_slot;
+ return g.atlas.space_slot;
};
words.shaped.resize(gpa, n) catch {
words.text.shrinkRetainingCapacity(text_start);
- return g.space_slot;
+ return g.atlas.space_slot;
};
const shaped = words.shaped.items;
var run_start: usize = 0;
- var face = glyphForCodepoint(g, text[0]).face;
+ var face = g.atlas.glyphForCodepoint(text[0]).face;
while (run_start < n) {
var run_end = run_start + 1;
var next_face = face;
while (run_end < n) : (run_end += 1) {
- next_face = glyphForCodepoint(g, text[run_end]).face;
+ next_face = g.atlas.glyphForCodepoint(text[run_end]).face;
if (next_face != face) break;
}
- const run_font = if (face == 0) g.font else g.fallbacks[face - 1].?.face;
- c.ui_font_shape(run_font, g.px, @intCast(g.cell_w), text[run_start..].ptr, @intCast(run_end - run_start), shaped[run_start..].ptr);
+ g.atlas.shape(face, g.px, g.cell_w, text[run_start..run_end], shaped[run_start..]);
for (shaped[run_start..run_end]) |cell| {
- const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = decoration, .lead = @intCast(cell.lead), .span = @intCast(cell.span) };
- const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.space_slot;
+ const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = @bitCast(decoration), .lead = @intCast(cell.lead), .span = @intCast(cell.span) };
+ const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.atlas.space_slot;
words.slots.appendAssumeCapacity(slot);
}
run_start = run_end;
@@ -5386,20 +4889,10 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role:
fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gui {
return .{
.window = undefined,
- .device = undefined,
- .swapchain_format = undefined,
- .pipeline = undefined,
- .decor_pipeline = undefined,
- .overlay_pipeline = undefined,
- .image_pipeline = undefined,
- .atlas_tex = undefined,
- .atlas_sampler = undefined,
- .linear_sampler = undefined,
- .atlas_xfer = undefined,
- .overlay_vbuf = undefined,
- .overlay_vxfer = undefined,
+ .present = undefined,
+ .cells = undefined,
.overlay_vertices = &.{},
- .font = undefined,
+ .atlas = .{ .font = undefined, .atlas_stage = &.{}, .glyphs = undefined },
.px = 0,
.tagline_px = 0,
.tagline_percent = 0,
@@ -5409,377 +4902,26 @@ fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gu
.cell_h = cell_h,
.ascent = 0,
.tagline_baseline = 0,
- .atlas_stage = &.{},
- .glyphs = undefined,
};
}
-/// The atlas slot of `key`, rasterized on first use. A strip is `span` cells
-/// wide (a grip glyph GUTTER cells, centered); a cell samples its slice of it.
+/// The atlas slot of `key` (Atlas.cachedGlyph), rasterized on first use at
+/// the window's sizes, a grip glyph GUTTER cells wide, its rules and
+/// decorations a logical pixel thick (dp): a raster is the frame probe's.
/// Null when the atlas is full.
fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot {
- if (g.glyphs.get(key)) |s| return s;
- const slot_w = g.cell_w * @as(u32, if (key.centered) config.GUTTER else key.span);
- if (g.pen_x + slot_w > atlas_w) {
- g.pen_x = 0;
- g.pen_y += g.cell_h;
- }
- if (g.pen_y + g.cell_h > atlas_h) return null; // atlas full: fall back
+ if (g.atlas.glyphs.get(key)) |s| return s;
const probe_raster = monoNs();
- defer if (frame_probe) |probe| {
+ const body: Atlas.Size = .{ .px = g.px, .cell_w = g.cell_w, .height = g.cell_h, .baseline = g.ascent };
+ const tagline: Atlas.Size = .{ .px = g.tagline_px, .cell_w = g.tagline_width, .height = g.tagline_height, .baseline = g.tagline_baseline };
+ const s = g.atlas.cachedGlyph(key, body, tagline, config.GUTTER, @intFromFloat(dp(1))) orelse return null;
+ if (frame_probe) |probe| {
probe.zone(.gui_raster, probe_raster);
probe.rastered +|= 1;
- };
- const s = Slot{ .u = g.pen_x, .v = g.pen_y };
- const out = g.atlas_stage.ptr + @as(usize, s.v) * atlas_w + s.u;
- const face = if (key.face == 0) g.font else g.fallbacks[key.face - 1].?.face;
- const px = if (key.role == .tagline) g.tagline_px else g.px;
- const baseline = if (key.role == .tagline) g.tagline_baseline else g.ascent;
- const cell_w = if (key.role == .tagline) g.tagline_width else g.cell_w;
- const raster_w = if (key.centered) slot_w else cell_w * key.span;
- const raster_h = if (key.role == .tagline) g.tagline_height else g.cell_h;
- const bold = @intFromBool(key.decoration.bold);
- if (key.rule) {
- drawRule(out, atlas_w, raster_w, raster_h, ruleArms(key.glyph).?);
- } else if (key.centered) {
- _ = c.ui_font_raster_centered(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h));
- } else {
- _ = c.ui_font_raster(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h), @intCast(cell_w * key.lead), @intCast(cell_w), baseline);
}
- decorateLine(out, atlas_w, raster_w, raster_h, baseline, key.decoration);
- if (key.centered) centerGlyphInk(out, raster_w, raster_h);
- g.atlas_dirty_top = @min(g.atlas_dirty_top, s.v);
- g.atlas_dirty_bottom = @max(g.atlas_dirty_bottom, s.v + raster_h);
- g.glyphs.put(key, s) catch return null;
- g.pen_x += slot_w;
return s;
}
-// Run once when a grip glyph enters the atlas, after decorations. Copy only
-// visible ink so bearings, empty bitmap margins and bold all share one center.
-fn centerGlyphInk(out: [*]u8, width: usize, height: usize) void {
- const b = inkBounds(out[0 .. (height - 1) * atlas_w + width], atlas_w, width, height) orelse return;
- const w = b.max_x - b.min_x + 1;
- const h = b.max_y - b.min_y + 1;
- const left = (width - w) / 2;
- const top = (height - h) / 2;
- var scratch: [atlas_w]u8 = undefined;
- for (0..h) |step| {
- const row = if (top > b.min_y) h - 1 - step else step;
- const source = (b.min_y + row) * atlas_w + b.min_x;
- const target = (top + row) * atlas_w;
- @memcpy(scratch[0..w], out[source..][0..w]);
- @memset(out[target..][0..width], 0);
- @memcpy(out[target + left ..][0..w], scratch[0..w]);
- }
- for (0..height) |row| {
- if (row < top or row >= top + h) @memset(out[row * atlas_w ..][0..width], 0);
- }
-}
-
-// Underline and strikethrough stay inside the existing atlas slot, so text
-// advance, caret and selection geometry are identical to the regular glyph.
-// The cached mask keeps this work out of steady-state rendering and also
-// decorates terminal spaces. Bold is not drawn here: the rasterizer emboldens
-// the outline.
-fn decorateLine(out: [*]u8, stride: usize, width: usize, height: usize, baseline: i32, decoration: GlyphDecoration) void {
- if (width == 0 or height == 0) return;
- // A line is a logical pixel thick, its dots and waves as long: the same
- // weight at any density (dp).
- const t: usize = @intFromFloat(dp(1));
- if (decoration.underline != .off) {
- const base: usize = @intCast(@max(0, baseline));
- const row = @min(base + 1, height -| t);
- for (0..width) |x| {
- const top = switch (decoration.underline) {
- .off => unreachable,
- .single => row,
- .double => {
- const upper = @min(base + 1, height -| 3 * t);
- for (0..t) |k| {
- out[@min(upper + k, height - 1) * stride + x] = 255;
- out[@min(upper + 2 * t + k, height - 1) * stride + x] = 255;
- }
- continue;
- },
- .curly => row -| @as(usize, if (x % (4 * t) < 2 * t) t else 0),
- .dotted => if (x % (3 * t) < t) row else continue,
- .dashed => if (x % (6 * t) < 4 * t) row else continue,
- };
- for (0..t) |k| out[@min(top + k, height - 1) * stride + x] = 255;
- }
- }
- if (decoration.strikethrough) {
- const row = @min(height -| t, @as(usize, @intCast(@max(0, baseline))) * 2 / 3);
- for (0..t) |k| @memset(out[@min(row + k, height - 1) * stride ..][0..width], 255);
- }
-}
-
-/// Uploads only the atlas rows drawn into since the last upload. Glyphs fill
-/// the atlas pen-style, a band of rows at a time, so new glyphs are a band a
-/// cell or two tall, not the whole 4 MB texture. The band sits at the same
-/// offset in the transfer buffer as in the stage, and the texture keeps the
-/// rows outside it.
-fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void {
- const top = g.atlas_dirty_top;
- const rows = g.atlas_dirty_bottom - top;
- const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.atlas_xfer, false) orelse return;
- const dst: [*]u8 = @ptrCast(ptr);
- @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], g.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]);
- c.SDL_UnmapGPUTransferBuffer(g.device, g.atlas_xfer);
-
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = g.atlas_xfer, .offset = top * atlas_w, .pixels_per_row = atlas_w, .rows_per_layer = rows };
- const dstregion = c.SDL_GPUTextureRegion{ .texture = g.atlas_tex, .mip_level = 0, .layer = 0, .x = 0, .y = top, .z = 0, .w = atlas_w, .h = rows, .d = 1 };
- c.SDL_UploadToGPUTexture(copy, &src, &dstregion, false);
- c.SDL_EndGPUCopyPass(copy);
- g.atlas_dirty_top = atlas_h;
- g.atlas_dirty_bottom = 0;
-}
-
-/// A vertex buffer and its upload buffer holding at least `needed`
-/// elements of `stride` bytes: those there when they do, else twice as
-/// many again until they would (the old ones let go).
-fn growInstances(g: *Gui, buffer: *?*c.SDL_GPUBuffer, transfer: *?*c.SDL_GPUTransferBuffer, capacity: *u32, needed: u32, stride: u32) !void {
- if (needed <= capacity.* and buffer.* != null and transfer.* != null) return;
- var grown = @max(@as(u32, 1), capacity.*);
- while (grown < needed) grown = std.math.mul(u32, grown, 2) catch return error.GpuCapacity;
- const size = std.math.mul(u32, grown, stride) catch return error.GpuCapacity;
- var vb_info = c.SDL_GPUBufferCreateInfo{ .usage = c.SDL_GPU_BUFFERUSAGE_VERTEX, .size = size, .props = 0 };
- const next_buffer = c.SDL_CreateGPUBuffer(g.device, &vb_info) orelse return error.GpuCreate;
- errdefer c.SDL_ReleaseGPUBuffer(g.device, next_buffer);
- var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = size, .props = 0 };
- const next_transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate;
- if (buffer.*) |old| c.SDL_ReleaseGPUBuffer(g.device, old);
- if (transfer.*) |old| c.SDL_ReleaseGPUTransferBuffer(g.device, old);
- buffer.* = next_buffer;
- transfer.* = next_transfer;
- capacity.* = grown;
-}
-
-/// One vertex buffer of a pipeline: `pitch` bytes an element, read per
-/// vertex or per instance through `attrs`.
-const VertexInput = struct { pitch: u32, rate: c.SDL_GPUVertexInputRate, attrs: []const c.SDL_GPUVertexAttribute };
-
-/// The cells' and the decor's instances (ui.vert.glsl).
-const cell_input: VertexInput = .{ .pitch = @sizeOf(CellInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{
- .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "x0") },
- .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "u0") },
- .{ .location = 2, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "fr") },
- .{ .location = 3, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT3, .offset = @offsetOf(CellInstance, "br") },
- .{ .location = 4, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_UINT, .offset = @offsetOf(CellInstance, "effect") },
- .{ .location = 5, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(CellInstance, "clip_x0") },
-} };
-
-const overlay_input: VertexInput = .{ .pitch = @sizeOf(OverlayVertex), .rate = c.SDL_GPU_VERTEXINPUTRATE_VERTEX, .attrs = &.{
- .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2, .offset = @offsetOf(OverlayVertex, "x") },
- .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(OverlayVertex, "r") },
-} };
-
-const image_input: VertexInput = .{ .pitch = @sizeOf(ImageInstance), .rate = c.SDL_GPU_VERTEXINPUTRATE_INSTANCE, .attrs = &.{
- .{ .location = 0, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "x0") },
- .{ .location = 1, .buffer_slot = 0, .format = c.SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4, .offset = @offsetOf(ImageInstance, "u0") },
-} };
-
-/// A pipeline drawing triangles into `color_format`: `vert`, and `frag`
-/// with its samplers and uniform buffers, over one vertex buffer of
-/// `input` (none: the post chain's triangle over the whole frame).
-pub fn makePipeline(
- device: *c.SDL_GPUDevice,
- color_format: c.SDL_GPUTextureFormat,
- vert: []const u8,
- frag: []const u8,
- samplers: u32,
- uniforms: u32,
- input: ?VertexInput,
- blend: c.SDL_GPUColorTargetBlendState,
-) !*c.SDL_GPUGraphicsPipeline {
- const vs = try makeShader(device, vert, c.SDL_GPU_SHADERSTAGE_VERTEX, 0, 0);
- defer c.SDL_ReleaseGPUShader(device, vs);
- const fs = try makeShader(device, frag, c.SDL_GPU_SHADERSTAGE_FRAGMENT, samplers, uniforms);
- defer c.SDL_ReleaseGPUShader(device, fs);
- var col_desc = c.SDL_GPUColorTargetDescription{ .format = color_format, .blend_state = blend };
- var vbuf_desc: c.SDL_GPUVertexBufferDescription = undefined;
- var info = std.mem.zeroes(c.SDL_GPUGraphicsPipelineCreateInfo);
- info.vertex_shader = vs;
- info.fragment_shader = fs;
- info.primitive_type = c.SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
- if (input) |in| {
- vbuf_desc = .{ .slot = 0, .pitch = in.pitch, .input_rate = in.rate, .instance_step_rate = 0 };
- info.vertex_input_state = .{
- .vertex_buffer_descriptions = &vbuf_desc,
- .num_vertex_buffers = 1,
- .vertex_attributes = in.attrs.ptr,
- .num_vertex_attributes = @intCast(in.attrs.len),
- };
- }
- info.rasterizer_state.fill_mode = c.SDL_GPU_FILLMODE_FILL;
- info.rasterizer_state.cull_mode = c.SDL_GPU_CULLMODE_NONE;
- info.multisample_state.sample_count = c.SDL_GPU_SAMPLECOUNT_1;
- info.target_info = .{ .color_target_descriptions = &col_desc, .num_color_targets = 1 };
- return c.SDL_CreateGPUGraphicsPipeline(device, &info) orelse error.GpuCreate;
-}
-
-fn backgroundLayerBlend() c.SDL_GPUColorTargetBlendState {
- var blend = std.mem.zeroes(c.SDL_GPUColorTargetBlendState);
- blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_SRC_ALPHA;
- blend.dst_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
- blend.color_blend_op = c.SDL_GPU_BLENDOP_ADD;
- blend.src_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR;
- blend.dst_alpha_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
- blend.alpha_blend_op = c.SDL_GPU_BLENDOP_ADD;
- blend.enable_blend = true;
- return blend;
-}
-
-fn makeShader(device: *c.SDL_GPUDevice, code: []const u8, stage: c.SDL_GPUShaderStage, n_samplers: u32, n_uniform_buffers: u32) !*c.SDL_GPUShader {
- var info = std.mem.zeroes(c.SDL_GPUShaderCreateInfo);
- info.code = code.ptr;
- info.code_size = code.len;
- info.entrypoint = "main";
- info.format = c.SDL_GPU_SHADERFORMAT_SPIRV;
- info.stage = stage;
- info.num_samplers = n_samplers;
- info.num_uniform_buffers = n_uniform_buffers;
- return c.SDL_CreateGPUShader(device, &info) orelse error.GpuCreate;
-}
-
-/// A 2D texture of one level, one layer and one sample.
-pub fn texture2d(device: *c.SDL_GPUDevice, format: c.SDL_GPUTextureFormat, usage: c.SDL_GPUTextureUsageFlags, width: u32, height: u32) ?*c.SDL_GPUTexture {
- var info = std.mem.zeroes(c.SDL_GPUTextureCreateInfo);
- info.type = c.SDL_GPU_TEXTURETYPE_2D;
- info.format = format;
- info.usage = usage;
- info.width = width;
- info.height = height;
- info.layer_count_or_depth = 1;
- info.num_levels = 1;
- info.sample_count = c.SDL_GPU_SAMPLECOUNT_1;
- return c.SDL_CreateGPUTexture(device, &info);
-}
-
-fn ensureCaptureTexture(g: *Gui, width: u32, height: u32) !void {
- if (g.capture_tex != null and g.capture_tex_w == width and g.capture_tex_h == height) return;
- const next = texture2d(g.device, g.swapchain_format, c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET, width, height) orelse return error.GpuCreate;
- if (g.capture_tex) |texture| c.SDL_ReleaseGPUTexture(g.device, texture);
- g.capture_tex = next;
- g.capture_tex_w = width;
- g.capture_tex_h = height;
-}
-
-fn softTargetFormat(device: *c.SDL_GPUDevice) c.SDL_GPUTextureFormat {
- const candidates = [_]c.SDL_GPUTextureFormat{
- c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM,
- c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM,
- };
- for (candidates) |format| {
- if (c.SDL_GPUTextureSupportsFormat(
- device,
- format,
- c.SDL_GPU_TEXTURETYPE_2D,
- c.SDL_GPU_TEXTUREUSAGE_COLOR_TARGET | c.SDL_GPU_TEXTUREUSAGE_SAMPLER,
- )) return format;
- }
- return c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM;
-}
-
-fn softPixelFormat(format: c.SDL_GPUTextureFormat) ?c.SDL_PixelFormat {
- return switch (format) {
- c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM,
- c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB,
- => c.SDL_PIXELFORMAT_ARGB8888,
- c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM,
- c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB,
- => c.SDL_PIXELFORMAT_ABGR8888,
- else => null,
- };
-}
-
-fn ensureSoftTexture(g: *Gui, width: u32, height: u32) !*c.SDL_Texture {
- if (g.soft_texture) |texture| {
- if (g.soft_tex_w == width and g.soft_tex_h == height) return texture;
- c.SDL_DestroyTexture(texture);
- g.soft_texture = null;
- }
- const renderer = g.soft_renderer orelse return error.GpuCreate;
- const pixel_format = softPixelFormat(g.swapchain_format) orelse return error.UnsupportedCaptureFormat;
- const next = c.SDL_CreateTexture(
- renderer,
- pixel_format,
- c.SDL_TEXTUREACCESS_STREAMING,
- @intCast(width),
- @intCast(height),
- ) orelse return error.GpuCreate;
- _ = c.SDL_SetTextureScaleMode(next, c.SDL_SCALEMODE_NEAREST);
- _ = c.SDL_SetTextureBlendMode(next, c.SDL_BLENDMODE_NONE);
- g.soft_texture = next;
- g.soft_tex_w = width;
- g.soft_tex_h = height;
- return next;
-}
-
-/// The frame in `target`, `size` bytes, copied down into `capture_xfer`
-/// (grown to it first) by `cmd`, which the caller submits and waits for.
-/// With no buffer to be had the command buffer is submitted as it is.
-fn downloadTarget(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32, size: u32) !*c.SDL_GPUTransferBuffer {
- if (g.capture_xfer == null or g.capture_xfer_size < size) {
- var info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_DOWNLOAD, .size = size, .props = 0 };
- const next = c.SDL_CreateGPUTransferBuffer(g.device, &info) orelse {
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
- return error.GpuCreate;
- };
- if (g.capture_xfer) |transfer| c.SDL_ReleaseGPUTransferBuffer(g.device, transfer);
- g.capture_xfer = next;
- g.capture_xfer_size = size;
- }
- const xfer = g.capture_xfer.?;
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src = c.SDL_GPUTextureRegion{ .texture = target, .mip_level = 0, .layer = 0, .x = 0, .y = 0, .z = 0, .w = sw, .h = sh, .d = 1 };
- const dst = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = xfer, .offset = 0, .pixels_per_row = sw, .rows_per_layer = sh };
- c.SDL_DownloadFromGPUTexture(copy, &src, &dst);
- c.SDL_EndGPUCopyPass(copy);
- return xfer;
-}
-
-fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void {
- const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format);
- const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1);
- if (size == 0 or bpp != 4) {
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
- return error.UnsupportedCaptureFormat;
- }
- const xfer = try downloadTarget(g, cmd, target, sw, sh, size);
-
- const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit;
- defer c.SDL_ReleaseGPUFence(g.device, fence);
- var fences = [_]*c.SDL_GPUFence{fence};
- const probe_wait = monoNs();
- if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit;
- if (frame_probe) |probe| probe.zone(.gui_wait, probe_wait);
-
- const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap;
- defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer);
-
- const texture = try ensureSoftTexture(g, sw, sh);
- const renderer = g.soft_renderer orelse return error.GpuCreate;
- const probe_upload = monoNs();
- defer if (frame_probe) |probe| probe.zone(.gui_upload, probe_upload);
- if (!c.SDL_UpdateTexture(texture, null, mapped, @intCast(sw * bpp))) return error.GpuMap;
- // PARDES_FRAMES_CAPTURE: every presented frame's pixels as they went
- // out, and when, for a recording at the frames' own times. One write a
- // frame; nothing else.
- if (frame_capture_dir) |dir| captureSeries(dir, @as([*]const u8, @ptrCast(mapped))[0..size], sw, sh);
- // The cell shader already produced premultiplied backgrounds with opaque
- // foreground ink. Copy that alpha unchanged; never modulate the full frame.
- _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE);
- _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.surface_opacity) 0 else 255);
- _ = c.SDL_RenderClear(renderer);
- _ = c.SDL_RenderTexture(renderer, texture, null, null);
- const probe_flip = monoNs();
- _ = c.SDL_RenderPresent(renderer);
- if (frame_probe) |probe| probe.zone(.gui_flip, probe_flip);
-}
-
fn backgroundOpacity(percent: u8) f32 {
std.debug.assert(percent <= 100);
return @as(f32, @floatFromInt(percent)) / 100;
@@ -5808,27 +4950,14 @@ fn latencyNote(comptime fmt: []const u8, args: anytype) void {
/// Writes the frame to latest.ppm in the capture directory, and in a
/// series to frame-<n>.ppm too.
fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTexture, sw: u32, sh: u32) !void {
- const size = c.SDL_CalculateGPUTextureFormatSize(g.swapchain_format, sw, sh, 1);
- if (size == 0) {
- _ = c.SDL_SubmitGPUCommandBuffer(cmd);
- return error.UnsupportedCaptureFormat;
- }
- const xfer = try downloadTarget(g, cmd, target, sw, sh, size);
+ const frame = try g.present.readFrame(cmd, target, sw, sh);
+ defer g.present.releaseFrame(frame);
+ latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, frame.fence_ns, frame.submit_ns });
- const submit_ns = monoNs();
- const fence = c.SDL_SubmitGPUCommandBufferAndAcquireFence(cmd) orelse return error.GpuSubmit;
- defer c.SDL_ReleaseGPUFence(g.device, fence);
- var fences = [_]*c.SDL_GPUFence{fence};
- if (!c.SDL_WaitForGPUFences(g.device, true, &fences, 1)) return error.GpuSubmit;
- latencyNote("F {d} {d} {d}\n", .{ frame_started_ns, monoNs(), submit_ns });
-
- const mapped = c.SDL_MapGPUTransferBuffer(g.device, xfer, false) orelse return error.GpuMap;
- defer c.SDL_UnmapGPUTransferBuffer(g.device, xfer);
- const pixels: [*]const u8 = @ptrCast(mapped);
- try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, "latest");
+ try writeCapturePpm(g, gpa, frame.pixels, sw, sh, "latest", false);
var name: [24]u8 = undefined;
// unreachable below: "frame-" and a u32 fit 24
- if (g.capture_series) try writeCapturePpm(g, gpa, pixels[0..size], sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable);
+ if (g.capture_series) try writeCapturePpm(g, gpa, frame.pixels, sw, sh, std.fmt.bufPrint(&name, "frame-{d:0>5}", .{g.captured}) catch unreachable, true);
g.captured +%= 1;
}
@@ -5858,41 +4987,44 @@ fn writeTestStatus(g: *const Gui, core: *const pardes.Pardes, presented: bool) v
_ = libc.rename(tmp_path, final_path);
}
-fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8) !void {
+/// `<name>.ppm`, RGB; with `alpha`, `<name>.pam` (P7 RGB_ALPHA) instead: a
+/// series keeps the alpha a blend writes, which the window's transparency
+/// shows and an RGB capture cannot.
+fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, name: []const u8, alpha: bool) !void {
// A latency trace times frames, and an 8 MB file write per frame would
// stall the loop it is timing.
if (g.capture_dir.len == 0 or latency_fd >= 0) return;
- const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format);
- if (bpp != 4) return error.UnsupportedCaptureFormat;
- const bgr = switch (g.swapchain_format) {
- c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM_SRGB => false,
- c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM, c.SDL_GPU_TEXTUREFORMAT_B8G8R8A8_UNORM_SRGB => true,
- else => return error.UnsupportedCaptureFormat,
- };
+ const bgr = try g.present.bgr();
var tmp_buf: [4096]u8 = undefined;
var final_buf: [4096]u8 = undefined;
- const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.ppm.tmp", .{ g.capture_dir, name }, 0) catch return error.CapturePathTooLong;
- const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.ppm", .{ g.capture_dir, name }, 0) catch return error.CapturePathTooLong;
+ const ext = if (alpha) "pam" else "ppm";
+ const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/{s}.{s}.tmp", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong;
+ const final_path = std.fmt.bufPrintSentinel(&final_buf, "{s}/{s}.{s}", .{ g.capture_dir, name, ext }, 0) catch return error.CapturePathTooLong;
const fd = libc.open(tmp_path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o644));
if (fd < 0) return error.CaptureWriteFailed;
defer _ = libc.close(fd);
- var header: [64]u8 = undefined;
- const hdr = std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch unreachable; // two u32s fit 64
+ var header: [96]u8 = undefined;
+ const hdr = if (alpha)
+ std.fmt.bufPrint(&header, "P7\nWIDTH {d}\nHEIGHT {d}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", .{ width, height }) catch unreachable // two u32s fit 96
+ else
+ std.fmt.bufPrint(&header, "P6\n{d} {d}\n255\n", .{ width, height }) catch unreachable; // two u32s fit 96
_ = host_io.writeFd(fd, hdr);
- const row_rgb = try gpa.alloc(u8, @as(usize, width) * 3);
+ const depth: usize = if (alpha) 4 else 3;
+ const row_rgb = try gpa.alloc(u8, @as(usize, width) * depth);
defer gpa.free(row_rgb);
for (0..height) |row| {
const src = pixels[row * width * 4 ..][0 .. @as(usize, width) * 4];
for (0..width) |x| {
const si = x * 4;
- const di = x * 3;
+ const di = x * depth;
row_rgb[di + 0] = src[si + if (bgr) @as(usize, 2) else 0];
row_rgb[di + 1] = src[si + 1];
row_rgb[di + 2] = src[si + if (bgr) @as(usize, 0) else 2];
+ if (alpha) row_rgb[di + 3] = src[si + 3];
}
_ = host_io.writeFd(fd, row_rgb);
}
@@ -6727,40 +5859,6 @@ fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, now_ns: u64, build
builder.addTri(px[0][0], px[0][1], px[2][0], px[2][1], px[3][0], px[3][1], color);
}
-fn uploadOverlayGpu(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, vertex_count: u32) bool {
- const byte_len: u32 = vertex_count * @sizeOf(OverlayVertex);
- const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.overlay_vxfer, false) orelse return false;
- const dst: [*]u8 = @ptrCast(ptr);
- const src: [*]const u8 = @ptrCast(g.overlay_vertices.ptr);
- @memcpy(dst[0..byte_len], src[0..byte_len]);
- c.SDL_UnmapGPUTransferBuffer(g.device, g.overlay_vxfer);
- const copy = c.SDL_BeginGPUCopyPass(cmd);
- const src_loc = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.overlay_vxfer, .offset = 0 };
- const dst_region = c.SDL_GPUBufferRegion{ .buffer = g.overlay_vbuf, .offset = 0, .size = byte_len };
- c.SDL_UploadToGPUBuffer(copy, &src_loc, &dst_region, false);
- c.SDL_EndGPUCopyPass(copy);
- return true;
-}
-
-fn pushLayerOpacity(cmd: *c.SDL_GPUCommandBuffer, pass: ?*c.SDL_GPURenderPass, opacity: f32) void {
- const uniforms = [4]f32{ opacity, 0, 0, 0 };
- c.SDL_PushGPUFragmentUniformData(cmd, 0, &uniforms, @sizeOf(@TypeOf(uniforms)));
- // The source alpha is geometric/image coverage, not window opacity. Its
- // alpha contribution is multiplied by this constant separately, so a
- // rail repainted over a gutter still has alpha p, not p + p*(1-p).
- c.SDL_SetGPUBlendConstants(pass, .{ .r = opacity, .g = opacity, .b = opacity, .a = opacity });
-}
-
-fn drawOverlayGpu(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, rp: ?*c.SDL_GPURenderPass, vertex_count: u32) void {
- if (vertex_count == 0) return;
- const pass = rp orelse return;
- c.SDL_BindGPUGraphicsPipeline(pass, g.overlay_pipeline);
- const binding = c.SDL_GPUBufferBinding{ .buffer = g.overlay_vbuf, .offset = 0 };
- c.SDL_BindGPUVertexBuffers(pass, 0, &binding, 1);
- pushLayerOpacity(cmd, pass, backgroundOpacity(g.applied_window_opacity));
- c.SDL_DrawGPUPrimitives(pass, vertex_count, 1, 0, 0);
-}
-
const OverlayBuilder = struct {
vertices: []OverlayVertex,
len: usize = 0,
@@ -6835,25 +5933,24 @@ fn expectCoverIsScan(cover: []const Cover, cols: u16, rows: u16, body_layers: []
};
}
-/// A Gui that can shape and rasterize `font` at `px`, and nothing else. From
-/// here on the fonts allocate from std.testing.allocator (the caller puts
-/// font_allocator back), so the test counts what they leak.
-fn textTestGui(font: *c.UIFont, px: f32) !Gui {
- c.ui_font_prime(font);
+/// A Gui that can shape and rasterize the face in `bytes` at `px`, and
+/// nothing else. From here on the fonts allocate from std.testing.allocator
+/// (the caller puts font_allocator back), so the test counts what they leak.
+fn textTestGui(bytes: []const u8, px: f32) !Gui {
+ var atlas = try Atlas.init(std.testing.allocator, bytes);
+ atlas.prime();
font_allocator = std.testing.allocator;
var cw: c_int = 0;
var ch: c_int = 0;
var ascent: c_int = 0;
- c.ui_font_cell_metrics(font, px, &cw, &ch, &ascent);
- const tag = taglineRaster(font, px, @intCast(cw), @intCast(ch), 82);
+ atlas.cellMetrics(px, &cw, &ch, &ascent);
+ const tag = taglineRaster(&atlas, px, @intCast(cw), @intCast(ch), 82);
var g = testGui(@intCast(cw), @intCast(ch), tag.width, tag.height);
- g.font = font;
+ g.atlas = atlas;
g.px = px;
g.ascent = ascent;
g.tagline_px = tag.px;
g.tagline_baseline = tag.baseline;
- g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h);
- g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator);
resetGlyphAtlas(&g);
return g;
}
@@ -6865,7 +5962,7 @@ fn textTestLine(comptime text: []const u8) [text.len]pardes.Cell {
}
fn glyphKeyAt(g: *Gui, slot: Slot) !GlyphKey {
- var it = g.glyphs.iterator();
+ var it = g.atlas.glyphs.iterator();
while (it.next()) |entry| if (std.meta.eql(entry.value_ptr.*, slot)) return entry.key_ptr.*;
return error.NoGlyph;
}
@@ -6927,37 +6024,39 @@ fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: par
test "FreeType and HarfBuzz allocate from the gui allocator and give it all back" {
// HarfBuzz's process-wide objects come from the default heap, as in runNative.
- const primer = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- c.ui_font_prime(primer);
- c.ui_font_free(primer);
+ var primer = try Atlas.init(std.testing.allocator, font_ttf);
+ primer.prime();
+ primer.deinit(std.testing.allocator);
font_allocator = std.testing.allocator;
defer font_allocator = std.heap.smp_allocator;
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
- var mask: [64 * 64]u8 = undefined;
- try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, 27, c.ui_font_glyph(font, 'g'), 1, &mask, 64, 32, 48, 0, 32, 30));
- try std.testing.expectEqual(@as(c_int, 0), c.ui_font_substitutes(font, c.ui_font_glyph(font, '-')));
+ var atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer atlas.deinit(std.testing.allocator);
+ atlas.reset(32);
+ const size: Atlas.Size = .{ .px = 27, .cell_w = 32, .height = 48, .baseline = 30 };
+ const g_slot = atlas.cachedGlyph(.{ .face = 0, .glyph = atlas.glyphForCodepoint('g').glyph, .role = .body, .decoration = .{ .bold = true } }, size, size, config.GUTTER, 1).?;
+ try std.testing.expect(Atlas.inkBounds(atlas.atlas_stage[@as(usize, g_slot.v) * atlas_w + g_slot.u ..], atlas_w, 32, 48) != null);
+ try std.testing.expect(!atlas.substitutes(0, atlas.glyphForCodepoint('-').glyph));
// A font with ligatures runs the whole HarfBuzz pass.
const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf");
defer std.testing.allocator.free(bytes);
- const maple = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit;
- defer c.ui_font_free(maple);
+ var maple = try Atlas.init(std.testing.allocator, bytes);
+ defer maple.deinit(std.testing.allocator);
var cell_w: c_int = 0;
var cell_h: c_int = 0;
var ascent: c_int = 0;
- c.ui_font_cell_metrics(maple, 27, &cell_w, &cell_h, &ascent);
+ maple.cellMetrics(27, &cell_w, &cell_h, &ascent);
const text = [_]u32{ 'a', '-', '>', 'b', '=', '=' };
var shaped: [text.len]c.UIShapedCell = undefined;
- c.ui_font_shape(maple, 27, cell_w, &text, text.len, &shaped);
+ maple.shape(0, 27, @intCast(cell_w), &text, &shaped);
try std.testing.expectEqual(@as(u8, 2), shaped[1].span);
try std.testing.expectEqual(@as(u8, 2), shaped[4].span);
}
test "every font size step moves the cell, and the ends are reachable exactly" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
+ var atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer atlas.deinit(std.testing.allocator);
var px = font_px_min + font_px_step;
while (px <= font_px_max) : (px += 1.0) {
var cw: c_int = 0;
@@ -6965,95 +6064,33 @@ test "every font size step moves the cell, and the ends are reachable exactly" {
var asc: c_int = 0;
var pw: c_int = 0;
var ph: c_int = 0;
- c.ui_font_cell_metrics(font, px, &cw, &ch, &asc);
- c.ui_font_cell_metrics(font, px - font_px_step, &pw, &ph, &asc);
+ atlas.cellMetrics(px, &cw, &ch, &asc);
+ atlas.cellMetrics(px - font_px_step, &pw, &ph, &asc);
try std.testing.expect(cw > pw and ch > ph);
}
try std.testing.expectEqual(font_px_max, std.math.clamp(font_px_max + font_px_step, font_px_min, font_px_max));
try std.testing.expectEqual(font_px_min, std.math.clamp(font_px_min - font_px_step, font_px_min, font_px_max));
}
-test "FreeType atlas raster is grayscale, bounded, and clears blank cells" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
- const h = c.ui_font_glyph(font, 'H');
- try std.testing.expect(h != 0);
- try std.testing.expectEqual(@as(u32, 0), c.ui_font_glyph(font, 0x10ffff));
-
- const size: f32 = 13.0;
- var cell_w: c_int = 0;
- var cell_h: c_int = 0;
- var ascent: c_int = 0;
- c.ui_font_cell_metrics(font, size, &cell_w, &cell_h, &ascent);
- try std.testing.expect(cell_w > 0 and cell_w <= 128);
- try std.testing.expect(cell_h > 0 and cell_h <= 128);
-
- const stride: c_int = 128;
- var bitmap: [128 * 128]u8 = @splat(0xaa);
- try std.testing.expectEqual(
- @as(c_int, 1),
- c.ui_font_raster(font, size, h, 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent),
- );
-
- var ink: usize = 0;
- var soft: usize = 0;
- var regular_coverage: usize = 0;
- for (0..@intCast(cell_h)) |y| {
- for (0..@intCast(cell_w)) |x| {
- const coverage = bitmap[y * @as(usize, @intCast(stride)) + x];
- if (coverage > 0) ink += 1;
- if (coverage > 0 and coverage < 255) soft += 1;
- regular_coverage += coverage;
- }
- }
- try std.testing.expect(ink > 0);
- try std.testing.expect(soft > 0);
- // Synthetic bold thickens the outline inside the same cell.
- try std.testing.expectEqual(
- @as(c_int, 1),
- c.ui_font_raster(font, size, h, 1, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent),
- );
- var bold_coverage: usize = 0;
- for (0..@intCast(cell_h)) |y| {
- for (0..@intCast(cell_w)) |x| bold_coverage += bitmap[y * @as(usize, @intCast(stride)) + x];
- for (bitmap[y * @as(usize, @intCast(stride)) + @as(usize, @intCast(cell_w)) ..][0..@intCast(stride - cell_w)]) |guard|
- try std.testing.expectEqual(@as(u8, 0xaa), guard);
- }
- try std.testing.expect(bold_coverage > regular_coverage);
-
- try std.testing.expectEqual(
- @as(c_int, 0),
- c.ui_font_raster(font, size, c.ui_font_glyph(font, ' '), 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent),
- );
- for (0..@intCast(cell_h)) |y|
- for (0..@intCast(cell_w)) |x|
- try std.testing.expectEqual(
- @as(u8, 0),
- bitmap[y * @as(usize, @intCast(stride)) + x],
- );
-}
-
test "tagline glyph shrinks into its own cell and stays vertically centered" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
-
const body_px: f32 = 27.0;
- var cell_w: c_int = 1;
- var cell_h: c_int = 1;
- var body_ascent: c_int = 1;
- c.ui_font_cell_metrics(font, body_px, &cell_w, &cell_h, &body_ascent);
- const tag = taglineRaster(font, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent);
+ var g = try textTestGui(font_ttf, body_px);
+ defer font_allocator = std.heap.smp_allocator;
+ defer g.atlas.deinit(std.testing.allocator);
+ defer g.words.deinit(std.testing.allocator);
+ _ = fitTaglineFont(&g, config.gui_tagline_font_percent);
+ const cell_w: c_int = @intCast(g.cell_w);
+ const cell_h: c_int = @intCast(g.cell_h);
+ const tag = taglineRaster(&g.atlas, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent);
try std.testing.expect(tag.px < body_px);
try std.testing.expect(tag.width < @as(u32, @intCast(cell_w)));
- const stride: c_int = 128;
- var body: [128 * 128]u8 = @splat(0);
- var tagline: [128 * 128]u8 = @splat(0);
- const h = c.ui_font_glyph(font, 'H');
- try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, body_px, h, 0, &body, stride, cell_w, cell_h, 0, cell_w, body_ascent));
- try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, tag.px, h, 0, &tagline, stride, @intCast(tag.width), @intCast(tag.height), 0, @intCast(tag.width), tag.baseline));
- const b = inkBounds(&body, @intCast(stride), @intCast(cell_w), @intCast(cell_h)).?;
- const t = inkBounds(&tagline, @intCast(stride), @intCast(tag.width), @intCast(tag.height)).?;
+ // Each at its role's size, as a frame draws it.
+ const h = g.atlas.glyphForCodepoint('H').glyph;
+ const body = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .body }).?;
+ const tagline = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .tagline }).?;
+ const b = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, body.v) * atlas_w + body.u ..], atlas_w, @intCast(cell_w), @intCast(cell_h)).?;
+ const t = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, tagline.v) * atlas_w + tagline.u ..], atlas_w, @intCast(tag.width), @intCast(tag.height)).?;
try std.testing.expect(t.max_x - t.min_x < b.max_x - b.min_x);
try std.testing.expect(t.max_y - t.min_y < b.max_y - b.min_y);
const body_center_x: isize = @intCast(b.min_x + b.max_x);
@@ -7069,15 +6106,15 @@ test "tagline glyph shrinks into its own cell and stays vertically centered" {
}
test "tagline percentage changes measured band height without body metrics" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
+ var atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer atlas.deinit(std.testing.allocator);
var cell_w: c_int = 1;
var cell_h: c_int = 1;
var ascent: c_int = 1;
- c.ui_font_cell_metrics(font, 27.0, &cell_w, &cell_h, &ascent);
- const small = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 40);
- const configured = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 82);
- const full = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 100);
+ atlas.cellMetrics(27.0, &cell_w, &cell_h, &ascent);
+ const small = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 40);
+ const configured = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 82);
+ const full = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 100);
try std.testing.expect(small.width < configured.width);
try std.testing.expect(configured.width <= full.width);
try std.testing.expectEqual(@as(u32, @intCast(cell_w)), full.width);
@@ -7097,16 +6134,9 @@ test "installed Nerd Symbols fallback covers Yazi directory icons" {
const bytes = try filesystem.readFile(std.testing.allocator, candidate.path);
defer std.testing.allocator.free(bytes);
- const face = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit;
- defer c.ui_font_free(face);
- try std.testing.expect(c.ui_font_glyph(face, 0xe5ff) != 0);
-}
-
-test "the shader instance ABI: the flags after the colours, the clip after them" {
- try std.testing.expectEqual(@as(usize, 76), @sizeOf(CellInstance));
- try std.testing.expectEqual(@as(usize, 56), @offsetOf(CellInstance, "effect"));
- try std.testing.expectEqual(@as(usize, 60), @offsetOf(CellInstance, "clip_x0"));
- try std.testing.expectEqual(@as(usize, 32), @sizeOf(ImageInstance));
+ var atlas = try Atlas.init(std.testing.allocator, bytes);
+ defer atlas.deinit(std.testing.allocator);
+ try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0);
}
test "GUI PTY reader delivers a real shell tail before EOF and joins on close" {
@@ -8084,7 +7114,7 @@ test "concealed terminal text emits no ink on its ground" {
var cell: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } };
cell.text[0] = 'X';
const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default);
- try std.testing.expectEqualDeep(g.space_slot, resolved.slot);
+ try std.testing.expectEqualDeep(g.atlas.space_slot, resolved.slot);
try std.testing.expectEqual(bg_default, resolved.bg);
}
@@ -8326,12 +7356,9 @@ test "insert cursor overlays without replacing the character beneath it" {
test "a ligature draws across its cells, one slice each, and comes apart under the cursor" {
const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf");
defer std.testing.allocator.free(bytes);
- const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit;
- defer c.ui_font_free(font);
- var g = try textTestGui(font, 27);
+ var g = try textTestGui(bytes, 27);
defer font_allocator = std.heap.smp_allocator;
- defer std.testing.allocator.free(g.atlas_stage);
- defer g.glyphs.deinit();
+ defer g.atlas.deinit(std.testing.allocator);
defer g.words.deinit(std.testing.allocator);
const line = textTestLine("a->b");
@@ -8341,7 +7368,7 @@ test "a ligature draws across its cells, one slice each, and comes apart under t
try std.testing.expectEqual(slots[1].v, slots[2].v);
try std.testing.expectEqual(slots[1].u + g.cell_w, slots[2].u);
var strips: usize = 0;
- var it = g.glyphs.iterator();
+ var it = g.atlas.glyphs.iterator();
while (it.next()) |entry| if (entry.key_ptr.span == 2) {
strips += 1;
try std.testing.expectEqual(@as(u4, 1), entry.key_ptr.lead);
@@ -8349,7 +7376,7 @@ test "a ligature draws across its cells, one slice each, and comes apart under t
};
try std.testing.expectEqual(@as(usize, 1), strips);
// The arrow runs through the seam: both halves carry ink at it.
- const seam = g.atlas_stage[@as(usize, slots[2].v) * atlas_w ..];
+ const seam = g.atlas.atlas_stage[@as(usize, slots[2].v) * atlas_w ..];
var left_ink: usize = 0;
var right_ink: usize = 0;
for (0..g.cell_h) |y| {
@@ -8358,8 +7385,8 @@ test "a ligature draws across its cells, one slice each, and comes apart under t
}
try std.testing.expect(left_ink > 0 and right_ink > 0);
// `a` and `b` are their plain glyphs.
- try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'a'), .role = .body }).?, slots[0]);
- try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'b'), .role = .body }).?, slots[3]);
+ try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('a').glyph, .role = .body }).?, slots[0]);
+ try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('b').glyph, .role = .body }).?, slots[3]);
// A second line with the same word reuses the shaped slots.
const again = textTestLine("a->b");
@@ -8368,83 +7395,78 @@ test "a ligature draws across its cells, one slice each, and comes apart under t
try std.testing.expectEqual(text_len, g.words.text.items.len);
// The cursor on either half shows plain `-` and `>`.
- const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '-'), .role = .body }).?;
- const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '>'), .role = .body }).?;
+ const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('-').glyph, .role = .body }).?;
+ const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('>').glyph, .role = .body }).?;
for ([_]usize{ 1, 2 }) |cursor| {
try std.testing.expectEqual(plain_minus, cellSlot(&g, &line, 1, cursor, .body));
try std.testing.expectEqual(plain_greater, cellSlot(&g, &line, 2, cursor, .body));
}
// A tagline is never shaped.
- try std.testing.expectEqual(c.ui_font_glyph(font, '-'), (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph);
+ try std.testing.expectEqual(g.atlas.glyphForCodepoint('-').glyph, (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph);
}
test "a font without ligatures draws every cell as its own glyph, exactly as before shaping" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
- var g = try textTestGui(font, 18);
+ var g = try textTestGui(font_ttf, 18);
defer font_allocator = std.heap.smp_allocator;
- defer std.testing.allocator.free(g.atlas_stage);
- defer g.glyphs.deinit();
+ defer g.atlas.deinit(std.testing.allocator);
defer g.words.deinit(std.testing.allocator);
+ // Each glyph as it is drawn unshaped, in an atlas of its own.
+ var plain = try textTestGui(font_ttf, 18);
+ defer plain.atlas.deinit(std.testing.allocator);
+ defer plain.words.deinit(std.testing.allocator);
const text = "a->b != c => d <= e |> www == :: 0x1F";
var line = textTestLine(text);
line[3].style.bold = true; // a style change inside a word
- var expected: [64 * 64]u8 = undefined;
for (line, 0..) |cell, i| {
if (text[i] == ' ') continue;
const slot = cellSlot(&g, &line, i, null, .body);
const key = try glyphKeyAt(&g, slot);
- try std.testing.expectEqual(c.ui_font_glyph(font, text[i]), key.glyph);
+ try std.testing.expectEqual(g.atlas.glyphForCodepoint(text[i]).glyph, key.glyph);
try std.testing.expectEqual(@as(u4, 1), key.span);
- _ = c.ui_font_raster(font, 18, key.glyph, @intFromBool(cell.style.bold), &expected, 64, @intCast(g.cell_w), @intCast(g.cell_h), 0, @intCast(g.cell_w), g.ascent);
+ const expected = cachedGlyph(&plain, .{ .face = 0, .glyph = key.glyph, .role = .body, .decoration = .{ .bold = cell.style.bold } }).?;
for (0..g.cell_h) |y|
- try std.testing.expectEqualSlices(u8, expected[y * 64 ..][0..g.cell_w], g.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]);
+ try std.testing.expectEqualSlices(u8, plain.atlas.atlas_stage[(expected.v + y) * atlas_w + expected.u ..][0..g.cell_w], g.atlas.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]);
}
}
test "pane indicator cached ink centers bearings styles and sizes" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
var g = testGui(10, 20, 6, 12);
- g.font = font;
- g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h);
- defer std.testing.allocator.free(g.atlas_stage);
- g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator);
- defer g.glyphs.deinit();
+ g.atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer g.atlas.deinit(std.testing.allocator);
for ([_]f32{ 13, 27, 40 }) |px| {
g.px = px;
var cw: c_int = 0;
var ch: c_int = 0;
- c.ui_font_cell_metrics(font, px, &cw, &ch, &g.ascent);
+ g.atlas.cellMetrics(px, &cw, &ch, &g.ascent);
g.cell_w = @intCast(cw);
g.cell_h = @intCast(ch);
for ([_]u8{ 40, 82, 100 }) |percent| {
- const tag = taglineRaster(font, px, g.cell_w, g.cell_h, percent);
+ const tag = taglineRaster(&g.atlas, px, g.cell_w, g.cell_h, percent);
g.tagline_width = tag.width;
g.tagline_height = tag.height;
g.tagline_px = tag.px;
g.tagline_baseline = tag.baseline;
resetGlyphAtlas(&g);
- try std.testing.expectEqual(@as(usize, 0), g.glyphs.count());
+ try std.testing.expectEqual(@as(usize, 0), g.atlas.glyphs.count());
for ([_]u32{ '^', '$', 'j' }) |cp| for ([_]bool{ false, true }) |bold| {
- const key: GlyphKey = .{ .face = 0, .glyph = c.ui_font_glyph(font, @intCast(cp)), .role = .tagline, .decoration = .{ .bold = bold }, .centered = true };
+ const key: GlyphKey = .{ .face = 0, .glyph = g.atlas.glyphForCodepoint(cp).glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true };
const slot = cachedGlyph(&g, key).?;
- const bounds = inkBounds(g.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?;
+ const bounds = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?;
const center_x: isize = @intCast(bounds.min_x + bounds.max_x);
const center_y: isize = @intCast(bounds.min_y + bounds.max_y);
try std.testing.expect(@abs(center_x - @as(isize, @intCast(g.cell_w * config.GUTTER - 1))) <= 1);
try std.testing.expect(@abs(center_y - @as(isize, @intCast(tag.height - 1))) <= 1);
- const count = g.glyphs.count();
- const pen = g.pen_x;
+ const count = g.atlas.glyphs.count();
+ const pen = g.atlas.pen_x;
try std.testing.expectEqualDeep(slot, cachedGlyph(&g, key).?);
- try std.testing.expectEqual(count, g.glyphs.count());
- try std.testing.expectEqual(pen, g.pen_x);
+ try std.testing.expectEqual(count, g.atlas.glyphs.count());
+ try std.testing.expectEqual(pen, g.atlas.pen_x);
};
}
}
resetGlyphAtlas(&g);
- g.pen_y = atlas_h;
- try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '^'), .role = .tagline, .centered = true }));
+ g.atlas.pen_y = atlas_h;
+ try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('^').glyph, .role = .tagline, .centered = true }));
}
test "pane indicator halves are safe on an exhausted atlas" {
@@ -8461,15 +7483,12 @@ test "pane indicator halves are safe on an exhausted atlas" {
coverFrame(&cover, 6, 2, &.{}, &.{}, &grip);
const chrome: pardes.Chrome = .{};
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
var g = testGui(10, 20, 8, 16);
- g.font = font;
+ g.atlas = try Atlas.init(std.testing.allocator, font_ttf);
+ defer g.atlas.deinit(std.testing.allocator);
g.px = 20;
g.tagline_px = 16;
- g.pen_y = atlas_h;
- g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator);
- defer g.glyphs.deinit();
+ g.atlas.pen_y = atlas_h;
defer g.words.deinit(std.testing.allocator);
var instances: [4]CellInstance = undefined;
var next: u32 = 0;
@@ -8480,94 +7499,13 @@ test "pane indicator halves are safe on an exhausted atlas" {
try std.testing.expectEqual(@as(u32, 4), next);
}
-test "a box-drawing rule reaches its cell's edges, and only its arms do" {
- const stride = 12;
- const width = 9;
- const height = 15;
- var mask: [stride * height]u8 = @splat(0xa5);
- drawRule(&mask, stride, width, height, ruleArms(0x253c).?);
- // ┼: ink on all four edges, none in the corners, nothing past the slot.
- try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]);
- try std.testing.expectEqual(@as(u8, 255), mask[(height - 1) * stride + width / 2]);
- try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride]);
- try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride + width - 1]);
- try std.testing.expectEqual(@as(u8, 0), mask[0]);
- for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard);
- drawRule(&mask, stride, width, height, ruleArms(0x2502).?);
- try std.testing.expectEqual(@as(u8, 0), mask[(height / 2) * stride]);
- try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]);
- try std.testing.expect(ruleArms('|') == null);
-}
-
-test "glyph decorations render spaces and stay inside their atlas slot" {
- const stride = 9;
- const width = 5;
- const height = 7;
- for ([_]GlyphDecoration{
- .{ .underline = .single },
- .{ .underline = .double },
- .{ .underline = .curly },
- .{ .underline = .dotted },
- .{ .underline = .dashed },
- .{ .strikethrough = true },
- }) |decoration| {
- var mask: [stride * (height + 1)]u8 = @splat(0xa5);
- for (0..height) |y| @memset(mask[y * stride ..][0..width], 0);
- decorateLine(&mask, stride, width, height, 5, decoration);
- try std.testing.expect(inkBounds(&mask, stride, width, height) != null);
- for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard|
- try std.testing.expectEqual(@as(u8, 0xa5), guard);
- for (mask[stride * height ..]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard);
- }
+test "a concealed cell's underline draws nothing of its own" {
const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } };
try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank());
}
-test "the atlas's dirty rows hold every row a new glyph draws into, and a reset dirties them all" {
- const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?;
- defer c.ui_font_free(font);
- var g = try textTestGui(font, 18);
- defer font_allocator = std.heap.smp_allocator;
- defer std.testing.allocator.free(g.atlas_stage);
- defer g.glyphs.deinit();
- defer g.words.deinit(std.testing.allocator);
- // The texture as uploadAtlas leaves it, which starts undefined.
- const texture = try std.testing.allocator.alloc(u8, atlas_w * atlas_h);
- defer std.testing.allocator.free(texture);
- @memset(texture, 0xa5);
- var glyph: u32 = 0;
- for (0..40) |frame| {
- if (frame == 30) resetGlyphAtlas(&g); // a font change
- // Plain glyphs, strips, taglines, grip glyphs and decorations.
- for (0..25) |_| {
- glyph += 1;
- const span: u4 = @intCast(1 + glyph % 3);
- _ = cachedGlyph(&g, .{
- .face = 0,
- .glyph = glyph,
- .role = if (glyph % 4 == 0) .tagline else .body,
- .decoration = .{ .bold = glyph % 2 == 0, .underline = if (glyph % 5 == 0) .curly else .off, .strikethrough = glyph % 11 == 0 },
- .centered = glyph % 13 == 0,
- .lead = @intCast(glyph % span),
- .span = span,
- }) orelse return error.AtlasFull;
- }
- for (0..atlas_h) |row| {
- const stage = g.atlas_stage[row * atlas_w ..][0..atlas_w];
- const uploaded = texture[row * atlas_w ..][0..atlas_w];
- if (row >= g.atlas_dirty_top and row < g.atlas_dirty_bottom)
- @memcpy(uploaded, stage)
- else
- try std.testing.expect(std.mem.eql(u8, stage, uploaded));
- }
- g.atlas_dirty_top = atlas_h;
- g.atlas_dirty_bottom = 0;
- }
- try std.testing.expect(g.pen_y >= 2 * g.cell_h);
-}
-
test "overlapping background layers keep one uniform opacity" {
- const blend = backgroundLayerBlend();
+ const blend = Cells.backgroundLayerBlend();
try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR), blend.src_alpha_blendfactor);
try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA), blend.dst_alpha_blendfactor);
for ([_]f32{ 0, 0.25, 0.7, 1 }) |opacity| {
@@ -9160,7 +8098,7 @@ fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer
};
const hash = std.hash.Wyhash.hash(frame.serial, frame.bytes);
if (g.addon_failed[id] == hash) continue;
- if (g.addon_gpu == null) g.addon_gpu = .init(gpa, g.device);
+ if (g.addon_gpu == null) g.addon_gpu = .init(gpa, g.cells.device);
const gpu = &g.addon_gpu.?;
const target: GpuScene.abi.Image = @fromBackingInt(@intCast(id + 1));
if (g.addon_hash[id] != hash or g.addon_serial[id] != frame.serial) {
@@ -9188,11 +8126,7 @@ fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer
g.addon_serial[id] = frame.serial;
}
const out = gpu.output(target) orelse continue;
- if (g.addon_pipeline == null) {
- var blend = backgroundLayerBlend();
- blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE;
- g.addon_pipeline = makePipeline(g.device, g.swapchain_format, image_vert_spv, image_frag_spv, 1, 1, image_input, blend) catch continue;
- }
+ g.cells.makeAddonPipeline() catch continue;
g.prepared_images.append(gpa, .{
.premultiplied = true,
.texture = out.texture,
@@ -9201,3 +8135,81 @@ fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer
}
if (g.addon_gpu) |*gpu| gpu.endFrame();
}
+
+test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes to the recorded stage and slots" {
+ // The glyph atlas the frames sample, byte for byte and on any machine:
+ // FreeType and HarfBuzz are the build's, the faces the repo's (the
+ // embedded Adwaita Mono, assets/MapleMono-NF for ligatures and Nerd
+ // icons). CJK has no face of the repo's and no fallback of pardes's
+ // list: the frame corpus draws its .notdef. Recorded before the GPU
+ // move (.scratch/sketch/briefs/gpu-s0.md); a change here is a change
+ // to every frame.
+ const want = [2][2]u64{ .{ 0xa03053f14e2c5472, 0x9029886b638b07d5 }, .{ 0xcbaa53a0103aaff5, 0x7563d69768f7d867 } };
+ const maple = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf");
+ defer std.testing.allocator.free(maple);
+ defer display_scale = 1;
+ var got: [2][2]u64 = undefined;
+ for ([_]f32{ 27, 54 }, [_]f32{ 1, 2 }, &got) |px, scale, *hashes| {
+ display_scale = scale;
+ var stage_hash = std.hash.Wyhash.init(0);
+ var slots_hash = std.hash.Wyhash.init(0);
+ // 0: Adwaita Mono, Maple its fallback; 1: Maple, whose ligatures shape.
+ for ([_][]const u8{ font_ttf, maple }) |primary| {
+ var g = try textTestGui(primary, px);
+ defer font_allocator = std.heap.smp_allocator;
+ defer g.atlas.deinit(std.testing.allocator);
+ defer g.words.deinit(std.testing.allocator);
+ try std.testing.expect(g.atlas.addFallback(std.testing.allocator, maple, false));
+ try std.testing.expect(fitTaglineFont(&g, 80));
+ const decorations = [_]Atlas.Decoration{
+ .{},
+ .{ .bold = true },
+ .{ .underline = .single },
+ .{ .underline = .double },
+ .{ .underline = .curly },
+ .{ .underline = .dotted },
+ .{ .underline = .dashed },
+ .{ .strikethrough = true },
+ };
+ for (0x21..0x7f) |cp| {
+ const drawn = g.atlas.glyphForCodepoint(@intCast(cp));
+ for (decorations) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body, .decoration = decoration }) orelse return error.AtlasFull;
+ for (decorations[0..2]) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = decoration }) orelse return error.AtlasFull;
+ }
+ const space = g.atlas.glyphForCodepoint(' ');
+ _ = cachedGlyph(&g, .{ .face = space.face, .glyph = space.glyph, .role = .body, .decoration = .{ .underline = .single } }) orelse return error.AtlasFull;
+ for ([_]u32{ 0x2500, 0x2502, 0x250c, 0x2510, 0x2514, 0x2518, 0x251c, 0x2524, 0x252c, 0x2534, 0x253c }) |cp| for ([_]Atlas.Role{ .body, .tagline }) |role| {
+ _ = cachedGlyph(&g, .{ .face = 0, .glyph = cp, .role = role, .rule = true }) orelse return error.AtlasFull;
+ };
+ for ([_]u32{ '$', '^', 'j' }) |cp| for ([_]bool{ false, true }) |bold| {
+ const drawn = g.atlas.glyphForCodepoint(cp);
+ _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }) orelse return error.AtlasFull;
+ };
+ // Nerd icons (Yazi's folder, a file, powerline's arrow): Maple's,
+ // the primary's or the fallback's.
+ for ([_]u32{ 0xe5ff, 0xf07b, 0xe0b0 }) |cp| {
+ const drawn = g.atlas.glyphForCodepoint(cp);
+ try std.testing.expect(drawn.glyph != 0);
+ _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body }) orelse return error.AtlasFull;
+ }
+ // Ligature strips, shaped by the words' cache as a frame shapes them.
+ const line = textTestLine("a->b => != <= >= == === !== |> <| :: ++ -- www office");
+ for (0..line.len) |i| _ = cellSlot(&g, &line, i, null, .body);
+ stage_hash.update(g.atlas.atlas_stage);
+ const Entry = struct { key: u64, u: u32, v: u32 };
+ var entries: std.ArrayList(Entry) = .empty;
+ defer entries.deinit(std.testing.allocator);
+ var it = g.atlas.glyphs.iterator();
+ while (it.next()) |e| try entries.append(std.testing.allocator, .{ .key = @bitCast(e.key_ptr.*), .u = e.value_ptr.u, .v = e.value_ptr.v });
+ std.mem.sort(Entry, entries.items, {}, struct {
+ fn less(_: void, x: Entry, y: Entry) bool {
+ return x.key < y.key;
+ }
+ }.less);
+ for (entries.items) |e| slots_hash.update(std.mem.asBytes(&e));
+ }
+ hashes.* = .{ stage_hash.final(), slots_hash.final() };
+ }
+ if (!std.meta.eql(want, got)) std.debug.print("atlas hashes: .{{ .{{ 0x{x}, 0x{x} }}, .{{ 0x{x}, 0x{x} }} }}\n", .{ got[0][0], got[0][1], got[1][0], got[1][1] });
+ try std.testing.expectEqual(want, got);
+}