From 30a603341e3b23da6e5ab5995b060c8e4ec52242 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 00:01:02 -0300 Subject: test: the GPU move's gates, sharper: a window the harness starts runs under PARDES_TEST_WRAP when it names a command (perf stat, a script), given the window's argv, its binary made absolute; a test window's series keeps its frames as PAM (P7 RGB_ALPHA), so the corpus sees the alpha a blend writes (latest.ppm and every other capture stay RGB); the corpus adds a translucent addon picture, test/veil.zig (zig build veil: a GPU pass that clears to half alpha and draws nothing), for the addon pipeline's colour factor, which the snake's opaque picture never showed; the snake's window ends with its pane gone and at rest, so it ends having drawn as many frames every run --- build.zig | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'build.zig') diff --git a/build.zig b/build.zig index 0e67b61e..7e3c812d 100644 --- a/build.zig +++ b/build.zig @@ -447,6 +447,7 @@ pub fn build(b: *std.Build) void { const addon_mod = b.createModule(.{ .root_source_file = b.path("src/kinds/addon.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "pardes_addon", .module = kind_mod }} }); const snake_shader_step = b.step("snake-shader", "build the optional GPU snake addon into zig-out/lib"); var snake_shader_lib: ?*std.Build.Step.Compile = null; + const veil_step = b.step("veil", "build the frame corpus's translucent GPU test addon (test/veil.zig) into zig-out/lib"); if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { const files = b.addWriteFiles(); for ([_][]const u8{ "vert", "frag", "post.frag" }) |stage| { @@ -461,6 +462,9 @@ pub fn build(b: *std.Build) void { snake_shader_lib = lib; snake_shader_step.dependOn(&b.addInstallArtifact(lib, .{}).step); snake_shader_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step); + // The frame corpus's translucent addon (test/veil.zig), into lib/ beside the snake. + const veil = b.addLibrary(.{ .name = "veil", .linkage = .dynamic, .root_module = b.createModule(.{ .root_source_file = b.path("test/veil.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "addon", .module = addon_mod }, .{ .name = "gpu_scene", .module = sb.module("gpu_scene") } } }) }); + veil_step.dependOn(&b.addInstallArtifact(veil, .{}).step); } // The PDF addon (addons/pdf/pdf.zig over MuPDF through pdf_bridge.c), built // and installed as the image addon is: compiled only for a step that -- cgit v1.3 From e8662178dba9d779cbfaa290154ae78c61402d30 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 02:04:50 -0300 Subject: gui: the renderer's shaders, instance ABI and GPU resource helpers are sketchbook's (src/gpu/), moved as they were, the first step of the GPU move: the seven GLSL shaders and their prebuilt SPIR-V leave shaders/ (crt.ci.metal stays), and CellInstance, OverlayVertex, ImageInstance, opaque_bg_bit, the vertex inputs, makePipeline, backgroundLayerBlend, makeShader, texture2d and growInstances (the device for the Gui) leave gui.zig for sketchbook's src/gpu/Cells.zig, built from the sketchbook checkout over gui.zig's own `c` as the Executor is (module gpu_cells; its instance-ABI test with it, run by unit-test); the embedded SPIR-V comes from sketchbook's GLSL through glslc, or its prebuilt copies with -Dprebuilt-shaders, under the same @embedFile names, byte for byte the same; the `shaders` refresh step is sketchbook's now; building.typ says so --- build.zig | 29 +++--- docs/typ/building.typ | 2 +- shaders/decor.frag.glsl | 26 ----- shaders/image.frag.glsl | 17 ---- shaders/image.vert.glsl | 33 ------- shaders/overlay.frag.glsl | 17 ---- shaders/overlay.vert.glsl | 11 --- shaders/prebuilt/decor.frag.spv | Bin 2176 -> 0 bytes shaders/prebuilt/image.frag.spv | Bin 1344 -> 0 bytes shaders/prebuilt/image.vert.spv | Bin 3152 -> 0 bytes shaders/prebuilt/overlay.frag.spv | Bin 1008 -> 0 bytes shaders/prebuilt/overlay.vert.spv | Bin 1040 -> 0 bytes shaders/prebuilt/ui.frag.spv | Bin 3184 -> 0 bytes shaders/prebuilt/ui.vert.spv | Bin 3848 -> 0 bytes shaders/ui.frag.glsl | 39 -------- shaders/ui.vert.glsl | 53 ---------- src/gui/gui.zig | 199 ++++---------------------------------- 17 files changed, 33 insertions(+), 393 deletions(-) delete mode 100644 shaders/decor.frag.glsl delete mode 100644 shaders/image.frag.glsl delete mode 100644 shaders/image.vert.glsl delete mode 100644 shaders/overlay.frag.glsl delete mode 100644 shaders/overlay.vert.glsl delete mode 100644 shaders/prebuilt/decor.frag.spv delete mode 100644 shaders/prebuilt/image.frag.spv delete mode 100644 shaders/prebuilt/image.vert.spv delete mode 100644 shaders/prebuilt/overlay.frag.spv delete mode 100644 shaders/prebuilt/overlay.vert.spv delete mode 100644 shaders/prebuilt/ui.frag.spv delete mode 100644 shaders/prebuilt/ui.vert.spv delete mode 100644 shaders/ui.frag.glsl delete mode 100644 shaders/ui.vert.glsl (limited to 'build.zig') diff --git a/build.zig b/build.zig index 7e3c812d..12b7b35c 100644 --- a/build.zig +++ b/build.zig @@ -161,18 +161,12 @@ pub fn build(b: *std.Build) void { const tracy = b.option([]const u8, "tracy", "enable Tracy profiling; supply the path to a Tracy source checkout"); const macos_sdk = b.option([]const u8, "macos-sdk", "the macOS SDK a gui built for macOS from another system takes SDL's headers and frameworks from"); const macos_identity = b.option([]const u8, "macos-identity", "codesigning identity for pardes.app (default: ad-hoc)") orelse "-"; - const prebuilt_shaders = b.option(bool, "prebuilt-shaders", "embed the committed shaders/prebuilt/*.spv instead of running glslc (default: on for a bare `zig build`, off when -Dplatform names a shell)") orelse also_gui; + const prebuilt_shaders = b.option(bool, "prebuilt-shaders", "embed sketchbook's committed src/gpu/shaders/prebuilt/*.spv instead of running glslc over its GLSL (default: on for a bare `zig build`, off when -Dplatform names a shell)") orelse also_gui; const mupdf_check = b.step("mupdf-check", "the pdf addon's check: MuPDF compiles, links, renders and searches docs/design.pdf, and its script runs"); const pdf_pointer_bench_step = b.step("pdf-pointer-bench", "time PDF hover and selection gestures and prove their pixels (-Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] [--cell WxH])"); const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])"); - const shaders_step = b.step("shaders", "refresh the committed shaders/prebuilt/*.spv (glslc)"); - const update_shaders = b.addUpdateSourceFiles(); - for (gui_shaders) |name| { - update_shaders.addCopyFileToSource(compileGlsl(b, name), b.fmt("shaders/prebuilt/{s}.spv", .{name})); - } - shaders_step.dependOn(&update_shaders.step); // build-time IO: slurps the grammars' highlights.scm queries, and reads // vendor/themes to find the theme sources @@ -899,6 +893,8 @@ pub fn build(b: *std.Build) void { const gui_shell_mods: [2]?*std.Build.Module = .{ gui_shell_mod, if (platform == .gui) static_mod else null }; // SDL's headers, for the macOS trackpad adapter's test after the loop. var sdl_include: ?std.Build.LazyPath = null; + // sketchbook's Cells.zig's own tests (the instance ABI), for unit-test. + var cells_test: ?*std.Build.Step.Compile = null; for (gui_shell_mods) |gui_shell_entry| if (gui_shell_entry) |gm| { // SDL's build asks a cross build for macOS for the SDK's paths. const sdk: ?std.Build.LazyPath = if (macos_sdk) |p| .{ .cwd_relative = p } else null; @@ -927,6 +923,10 @@ pub fn build(b: *std.Build) void { if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { const gpu = b.createModule(.{ .root_source_file = sb.path("src/gpu/Executor.zig"), .imports = &.{ .{ .name = "abi", .module = sb.module("abi") }, .{ .name = "c", .module = gui_c_mod } } }); gm.addImport("sketch_gpu", gpu); + // pardes's renderer, moved to sketchbook (src/gpu/), compiled + // against pardes's SDL; its tests run with unit-test. + gm.addImport("gpu_cells", b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} })); + if (cells_test == null) cells_test = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "c", .module = gui_c_mod }} }), .filters = test_filters }); gm.addImport("gpu_scene", sb.module("gpu_scene")); } sdl_include = dep.path("include"); @@ -993,11 +993,11 @@ pub fn build(b: *std.Build) void { gm.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ .root_source_file = b.path("assets/AdwaitaMono-Regular.ttf"), }); - for (gui_shaders) |name| gm.addAnonymousImport(b.fmt("{s}.spv", .{name}), .{ + if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| for (gui_shaders) |name| gm.addAnonymousImport(b.fmt("{s}.spv", .{name}), .{ .root_source_file = if (prebuilt_shaders) - b.path(b.fmt("shaders/prebuilt/{s}.spv", .{name})) + sb.path(b.fmt("src/gpu/shaders/prebuilt/{s}.spv", .{name})) else - compileGlsl(b, name), + compileGlsl(b, sb.path(b.fmt("src/gpu/shaders/{s}.glsl", .{name})), name), }); }; if (target.result.os.tag == .macos) if (sdl_include) |include| { @@ -1588,6 +1588,7 @@ pub fn build(b: *std.Build) void { // The perf and fs bench programs' own tests: they compile no editor. _ = units.add(b, perf_tests, null); _ = units.add(b, fs_bench_test, null); + if (cells_test) |t| _ = units.add(b, t, null); const core_test = b.addTest(.{ .root_module = core_module, .filters = test_filters }); const run_core_test = b.addRunArtifact(core_test); run_core_test.has_side_effects = true; @@ -2032,12 +2033,12 @@ fn reindexed(b: *std.Build, archive: std.Build.LazyPath, index: usize) std.Build return run.addOutputFileArg(b.fmt("{d}.a", .{index})); } -/// glslc shaders/.glsl -fshader-stage= -o .spv, -/// returned as a LazyPath for @embedFile. The stage is the name's own suffix. -fn compileGlsl(b: *std.Build, name: []const u8) std.Build.LazyPath { +/// glslc -fshader-stage= -o .spv, returned as +/// a LazyPath for @embedFile. The stage is the name's own suffix. +fn compileGlsl(b: *std.Build, glsl: std.Build.LazyPath, name: []const u8) std.Build.LazyPath { const stage = if (std.mem.endsWith(u8, name, ".vert")) "vertex" else "fragment"; const cmd = b.addSystemCommand(&.{ "glslc", b.fmt("-fshader-stage={s}", .{stage}) }); - cmd.addFileArg(b.path(b.fmt("shaders/{s}.glsl", .{name}))); + cmd.addFileArg(glsl); cmd.addArg("-o"); return cmd.addOutputFileArg(b.fmt("{s}.spv", .{name})); } diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 6bf7dfce..cf80bd3a 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -65,7 +65,7 @@ must share with its session; `pardes --help` lists every flag. [`-Dtheme-animation`], [bool, `true`], [`-Dworkspace-tag`], [bool: draw the workspace tag row; on except for macOS, whose menu bar carries it], [`-Dmacos-sdk`], [path: the macOS SDK SDL's headers and frameworks come from, for a gui built for macOS elsewhere], - [`-Dprebuilt-shaders`], [bool: embed the committed SPIR-V; on for a bare `zig build`, off with `-Dplatform`; `zig build shaders` refreshes it with glslc], + [`-Dprebuilt-shaders`], [bool: embed the committed SPIR-V; on for a bare `zig build`, off with `-Dplatform`; the shaders are sketchbook's (`src/gpu/shaders/`), and its `zig build shaders` refreshes the SPIR-V with glslc], [`-Dtracy`], [path to a Tracy checkout; off], [`-Dmacos-identity`], [codesigning identity for `pardes.app`; `-` (ad hoc)], [`-Dtest-filter`], [run only tests whose name contains it; a filter that matches nothing fails], diff --git a/shaders/decor.frag.glsl b/shaders/decor.frag.glsl deleted file mode 100644 index 71bb12e3..00000000 --- a/shaders/decor.frag.glsl +++ /dev/null @@ -1,26 +0,0 @@ -#version 450 - -// Decor, drawn by ui.vert.glsl like a cell, and blended as the overlay -// pipeline blends (backgroundLayerBlend). Ink (a cursor) is drawn with the -// opacity uniform at 1. -// -// A hard-edged fill (a rule, a rail, a grip mark, a bar cursor): its colour -// rides in the cell's ground (a_bg), its coverage in a_fg.r, so the result -// is the overlay pipeline's exactly. - -layout(std140, set = 3, binding = 0) uniform UiUniforms { - float background_opacity; -} u_ui; - -layout(location = 1) in vec3 v_fg; -layout(location = 2) in vec3 v_bg; -layout(location = 5) flat in vec4 v_clip; - -layout(location = 0) out vec4 o_col; - -void main() { - if (v_clip.z >= v_clip.x && (gl_FragCoord.x < v_clip.x || gl_FragCoord.x >= v_clip.z || - gl_FragCoord.y < v_clip.y || gl_FragCoord.y >= v_clip.w)) discard; - float opacity = clamp(u_ui.background_opacity, 0.0, 1.0); - o_col = vec4(v_bg * opacity, v_fg.r); -} diff --git a/shaders/image.frag.glsl b/shaders/image.frag.glsl deleted file mode 100644 index 38a95da6..00000000 --- a/shaders/image.frag.glsl +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 - -layout(set = 2, binding = 0) uniform sampler2D u_image; -layout(std140, set = 3, binding = 0) uniform UiUniforms { - float background_opacity; -} u_ui; - -layout(location = 0) in vec2 v_uv; -layout(location = 0) out vec4 o_col; - -void main() { - vec4 source = texture(u_image, v_uv); - // Keep source coverage for destination subtraction; the pipeline scales - // source alpha by the same opacity through its alpha blend constant. - source.rgb *= clamp(u_ui.background_opacity, 0.0, 1.0); - o_col = source; -} diff --git a/shaders/image.vert.glsl b/shaders/image.vert.glsl deleted file mode 100644 index ace55a53..00000000 --- a/shaders/image.vert.glsl +++ /dev/null @@ -1,33 +0,0 @@ -#version 450 - -// One instance per Surface image attachment. The CPU has already converted -// the pane's cell rectangle and the aspect-preserving contain fit to NDC. -layout(location = 0) in vec4 a_rect; // x0, y0, x1, y1 -layout(location = 1) in vec4 a_uv_rect; // u0, v0, u1, v1 - -layout(location = 0) out vec2 v_uv; - -void main() { - vec2 pos; - int corner = gl_VertexIndex % 6; - if (corner == 0) { - pos = vec2(a_rect.x, a_rect.y); - v_uv = vec2(a_uv_rect.x, a_uv_rect.y); - } else if (corner == 1) { - pos = vec2(a_rect.z, a_rect.y); - v_uv = vec2(a_uv_rect.z, a_uv_rect.y); - } else if (corner == 2) { - pos = vec2(a_rect.z, a_rect.w); - v_uv = vec2(a_uv_rect.z, a_uv_rect.w); - } else if (corner == 3) { - pos = vec2(a_rect.x, a_rect.y); - v_uv = vec2(a_uv_rect.x, a_uv_rect.y); - } else if (corner == 4) { - pos = vec2(a_rect.z, a_rect.w); - v_uv = vec2(a_uv_rect.z, a_uv_rect.w); - } else { - pos = vec2(a_rect.x, a_rect.w); - v_uv = vec2(a_uv_rect.x, a_uv_rect.w); - } - gl_Position = vec4(pos, 0.0, 1.0); -} diff --git a/shaders/overlay.frag.glsl b/shaders/overlay.frag.glsl deleted file mode 100644 index b5ac8d5a..00000000 --- a/shaders/overlay.frag.glsl +++ /dev/null @@ -1,17 +0,0 @@ -#version 450 - -layout(std140, set = 3, binding = 0) uniform UiUniforms { - float background_opacity; -} u_ui; - -layout(location = 0) in vec4 v_color; - -layout(location = 0) out vec4 o_col; - -void main() { - // Preserve shape coverage for destination subtraction. The pipeline uses - // the matching opacity blend constant for source alpha, so graphics laid - // over a background with the same opacity do not accumulate opaque seams. - // Text/cursor draw groups bind opacity 1 instead. - o_col = vec4(v_color.rgb * clamp(u_ui.background_opacity, 0.0, 1.0), v_color.a); -} diff --git a/shaders/overlay.vert.glsl b/shaders/overlay.vert.glsl deleted file mode 100644 index 5f6be593..00000000 --- a/shaders/overlay.vert.glsl +++ /dev/null @@ -1,11 +0,0 @@ -#version 450 - -layout(location = 0) in vec2 a_pos; -layout(location = 1) in vec4 a_color; - -layout(location = 0) out vec4 v_color; - -void main() { - v_color = a_color; - gl_Position = vec4(a_pos, 0.0, 1.0); -} diff --git a/shaders/prebuilt/decor.frag.spv b/shaders/prebuilt/decor.frag.spv deleted file mode 100644 index 0d5af9d2..00000000 Binary files a/shaders/prebuilt/decor.frag.spv and /dev/null differ diff --git a/shaders/prebuilt/image.frag.spv b/shaders/prebuilt/image.frag.spv deleted file mode 100644 index d663ed80..00000000 Binary files a/shaders/prebuilt/image.frag.spv and /dev/null differ diff --git a/shaders/prebuilt/image.vert.spv b/shaders/prebuilt/image.vert.spv deleted file mode 100644 index 1105bae2..00000000 Binary files a/shaders/prebuilt/image.vert.spv and /dev/null differ diff --git a/shaders/prebuilt/overlay.frag.spv b/shaders/prebuilt/overlay.frag.spv deleted file mode 100644 index e296e99e..00000000 Binary files a/shaders/prebuilt/overlay.frag.spv and /dev/null differ diff --git a/shaders/prebuilt/overlay.vert.spv b/shaders/prebuilt/overlay.vert.spv deleted file mode 100644 index a518c576..00000000 Binary files a/shaders/prebuilt/overlay.vert.spv and /dev/null differ diff --git a/shaders/prebuilt/ui.frag.spv b/shaders/prebuilt/ui.frag.spv deleted file mode 100644 index 91022fe2..00000000 Binary files a/shaders/prebuilt/ui.frag.spv and /dev/null differ diff --git a/shaders/prebuilt/ui.vert.spv b/shaders/prebuilt/ui.vert.spv deleted file mode 100644 index ad132bf9..00000000 Binary files a/shaders/prebuilt/ui.vert.spv and /dev/null differ diff --git a/shaders/ui.frag.glsl b/shaders/ui.frag.glsl deleted file mode 100644 index 7f70629a..00000000 --- a/shaders/ui.frag.glsl +++ /dev/null @@ -1,39 +0,0 @@ -#version 450 - -// Sample the glyph atlas (R = coverage 0..1) and mix the cell's bg up to its fg -// by that coverage. Output is PREMULTIPLIED: an opaque cell is unchanged. -// WindowOpacity changes only the ground's coverage, never the glyph's ink. - -layout(set = 2, binding = 0) uniform sampler2D u_atlas; -layout(std140, set = 3, binding = 0) uniform UiUniforms { - float background_opacity; -} u_ui; - -layout(location = 0) in vec2 v_uv; -layout(location = 1) in vec3 v_fg; -layout(location = 2) in vec3 v_bg; -layout(location = 4) flat in uint v_effect; -layout(location = 5) flat in vec4 v_clip; - -layout(location = 0) out vec4 o_col; - -void main() { - if (v_clip.z >= v_clip.x && (gl_FragCoord.x < v_clip.x || gl_FragCoord.x >= v_clip.z || - gl_FragCoord.y < v_clip.y || gl_FragCoord.y >= v_clip.w)) discard; - float a = texture(u_atlas, v_uv).r; - // A block cursor is foreground chrome even though its fill occupies the - // cell background: keep it visible at WindowOpacity 0. Otherwise the - // ground's coverage is the setting's. The flag is shared with - // ui.vert.glsl and src/gui/gui.zig. - float bgA = (v_effect & 0x20000000u) != 0u ? 1.0 : clamp(u_ui.background_opacity, 0.0, 1.0); - - // Ink over ground, both premultiplied: v_fg*a + (v_bg*bgA)*(1-a), which is - // mix() with the ground already premultiplied. At bgA = 1 that is exactly - // the mix(v_bg, v_fg, a) at alpha 1 this shader always wrote. - vec4 under = vec4(v_bg * bgA, bgA); - vec4 cell = vec4(mix(under.rgb, v_fg, a), mix(under.a, 1.0, a)); - - // FreeType's hinted grayscale bitmap is already the intended coverage. - // Preserve it exactly; weight-changing gamma hacks blur small stems. - o_col = cell; -} diff --git a/shaders/ui.vert.glsl b/shaders/ui.vert.glsl deleted file mode 100644 index e3532e68..00000000 --- a/shaders/ui.vert.glsl +++ /dev/null @@ -1,53 +0,0 @@ -#version 450 - -// Terminal cell renderer. The CPU uploads one instance per visible cell; this -// shader expands each instance into a two-triangle quad with gl_VertexIndex. -// The fragment shader mixes fg/bg by the atlas's alpha (a glyph mask in the R -// channel), so background fills and glyph foregrounds draw in a single pass. - -layout(location = 0) in vec4 a_rect; // x0, y0, x1, y1 -layout(location = 1) in vec4 a_uv_rect; // u0, v0, u1, v1 -layout(location = 2) in vec3 a_fg; -layout(location = 3) in vec3 a_bg; -// Flags, the high bits: an opaque block-cursor fill (ui.frag.glsl). -layout(location = 4) in uint a_effect; -// A clip rectangle in target pixels (x0, y0, x1, y1): the fragment shader -// drops what lies outside it. x1 < x0 is none. -layout(location = 5) in vec4 a_clip; - -layout(location = 0) out vec2 v_uv; -layout(location = 1) out vec3 v_fg; -layout(location = 2) out vec3 v_bg; -layout(location = 4) flat out uint v_effect; -layout(location = 5) flat out vec4 v_clip; - -void main() { - vec2 pos; - vec2 uv; - int corner = gl_VertexIndex % 6; - if (corner == 0) { - pos = vec2(a_rect.x, a_rect.y); - uv = vec2(a_uv_rect.x, a_uv_rect.y); - } else if (corner == 1) { - pos = vec2(a_rect.z, a_rect.y); - uv = vec2(a_uv_rect.z, a_uv_rect.y); - } else if (corner == 2) { - pos = vec2(a_rect.z, a_rect.w); - uv = vec2(a_uv_rect.z, a_uv_rect.w); - } else if (corner == 3) { - pos = vec2(a_rect.x, a_rect.y); - uv = vec2(a_uv_rect.x, a_uv_rect.y); - } else if (corner == 4) { - pos = vec2(a_rect.z, a_rect.w); - uv = vec2(a_uv_rect.z, a_uv_rect.w); - } else { - pos = vec2(a_rect.x, a_rect.w); - uv = vec2(a_uv_rect.x, a_uv_rect.w); - } - v_uv = uv; - v_fg = a_fg; - v_bg = a_bg; - v_effect = a_effect; - v_clip = a_clip; - gl_Position = vec4(pos, 0.0, 1.0); -} diff --git a/src/gui/gui.zig b/src/gui/gui.zig index cc43d8b6..d0d46f44 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1,4 +1,5 @@ const SketchGpu = @import("sketch_gpu"); +const Cells = @import("gpu_cells"); // sketchbook's src/gpu/Cells.zig const GpuScene = @import("gpu_scene"); const filesystem = @import("../fs.zig"); const std = @import("std"); @@ -240,52 +241,13 @@ fn inkBounds(bitmap: []const u8, stride: usize, w: usize, h: usize) ?InkBounds { return bounds; } -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 CellInstance = Cells.CellInstance; +const OverlayVertex = Cells.OverlayVertex; +const ImageInstance = Cells.ImageInstance; +const opaque_bg_bit = Cells.opaque_bg_bit; -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, @@ -1131,7 +1093,7 @@ 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; + const atlas_tex = Cells.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; @@ -1149,10 +1111,10 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di 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()); + const pipeline = try Cells.makePipeline(device, swapchain_format, vert_spv, frag_spv, 1, 1, Cells.cell_input, std.mem.zeroes(c.SDL_GPUColorTargetBlendState)); + const decor_pipeline = try Cells.makePipeline(device, swapchain_format, vert_spv, decor_frag_spv, 0, 1, Cells.cell_input, Cells.backgroundLayerBlend()); + const overlay_pipeline = try Cells.makePipeline(device, swapchain_format, overlay_vert_spv, overlay_frag_spv, 0, 1, Cells.overlay_input, Cells.backgroundLayerBlend()); + const image_pipeline = try Cells.makePipeline(device, swapchain_format, image_vert_spv, image_frag_spv, 1, 1, Cells.image_input, Cells.backgroundLayerBlend()); 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 }; @@ -4264,7 +4226,7 @@ fn uploadNativeTexture( 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; + const texture = Cells.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); @@ -4394,7 +4356,7 @@ 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; + Cells.growInstances(g.device, &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)); @@ -4590,7 +4552,7 @@ 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)); + try Cells.growInstances(g.device, &g.vbuf, &g.vxfer, &g.vbuf_cells, capacity, @sizeOf(CellInstance)); const vptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.vxfer.?, false) orelse { command_consumed = true; @@ -5542,130 +5504,9 @@ fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void { 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; + const next = Cells.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; @@ -7116,12 +6957,6 @@ test "installed Nerd Symbols fallback covers Yazi directory icons" { 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)); -} test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { const gpa = std.testing.allocator; @@ -8581,7 +8416,7 @@ test "the atlas's dirty rows hold every row a new glyph draws into, and a reset } 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| { @@ -9203,9 +9038,9 @@ fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer } const out = gpu.output(target) orelse continue; if (g.addon_pipeline == null) { - var blend = backgroundLayerBlend(); + var blend = Cells.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.addon_pipeline = Cells.makePipeline(g.device, g.swapchain_format, image_vert_spv, image_frag_spv, 1, 1, Cells.image_input, blend) catch continue; } g.prepared_images.append(gpa, .{ .premultiplied = true, -- cgit v1.3 From 1d4015b1b9740a894bea288dadb11d212eceff73 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 03:00:00 -0300 Subject: gui: the font shim and the glyph atlas are sketchbook's (vendor/font.{c,h}, src/font/Atlas.zig), moved as they were, the second step of the GPU move: font.c and font.h leave src/gui/ byte for byte, and the atlas leaves gui.zig, its faces (the primary, its bytes, the fallbacks), its stage, slots, pen and dirty rows, GlyphKey (Atlas.Key, the same bits: a FontRole and a GlyphDecoration go in as its Role and Decoration, checked at compile time), ruleArms, drawRule, inkBounds, glyphForCodepoint, cachedGlyph, centerGlyphInk and decorateLine; gui.zig holds an Atlas and asks it for what it asked the shim (a face, a fallback, the name, the cell, a substitution, a run shaped), so it calls no ui_font_ function; cachedGlyph stays as the window's: it hands the atlas the body's and the tagline's sizes, GUTTER and dp(1) on every miss (a window reopened on another display draws its rules at that display's dp(1) without a reset, as before) and keeps the frame probe's raster zone; the Atlas module is built from the sketchbook checkout over gui.zig's own `c` as Cells is, font.c compiled from there against pardes's FreeType and HarfBuzz; its tests (the raster, the box rules, the decorations, the dirty rows) are Atlas.zig's and run with unit-test, the tests of pardes's use of it (shaping, taglines, grips, the allocator, the atlas's bytes, whose hashes are unchanged) stay here over the Atlas --- build.zig | 25 +- src/gui/font.c | 471 ------------------------------------ src/gui/font.h | 98 -------- src/gui/gui.zig | 737 ++++++++++++++------------------------------------------ 4 files changed, 203 insertions(+), 1128 deletions(-) delete mode 100644 src/gui/font.c delete mode 100644 src/gui/font.h (limited to 'build.zig') diff --git a/build.zig b/build.zig index 12b7b35c..c2a0c8ac 100644 --- a/build.zig +++ b/build.zig @@ -895,7 +895,11 @@ pub fn build(b: *std.Build) void { var sdl_include: ?std.Build.LazyPath = null; // sketchbook's Cells.zig's own tests (the instance ABI), for unit-test. var cells_test: ?*std.Build.Step.Compile = null; + // sketchbook's Atlas.zig's own tests, for unit-test. + var atlas_test: ?*std.Build.Step.Compile = null; for (gui_shell_mods) |gui_shell_entry| if (gui_shell_entry) |gm| { + // This shell's `c`, for the Atlas's tests below. + var font_c: ?*std.Build.Module = null; // SDL's build asks a cross build for macOS for the SDK's paths. const sdk: ?std.Build.LazyPath = if (macos_sdk) |p| .{ .cwd_relative = p } else null; const sdl_dep = b.lazyDependency("sdl", .{ .target = target, .optimize = optimize, .sanitize_c = .off, .preferred_linkage = .static, .system_include_path = if (sdk) |p| p.path(b, "usr/include") else null, .system_framework_path = if (sdk) |p| p.path(b, "System/Library/Frameworks") else null, .library_path = if (sdk) |p| p.path(b, "usr/lib") else null }); @@ -919,6 +923,7 @@ pub fn build(b: *std.Build) void { gui_c.addIncludePath(dep.path("include")); gui_c.addIncludePath(b.path("src/gui")); const gui_c_mod = gui_c.createModule(); + font_c = gui_c_mod; gm.addImport("gui_c", gui_c_mod); if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { const gpu = b.createModule(.{ .root_source_file = sb.path("src/gpu/Executor.zig"), .imports = &.{ .{ .name = "abi", .module = sb.module("abi") }, .{ .name = "c", .module = gui_c_mod } } }); @@ -927,6 +932,11 @@ pub fn build(b: *std.Build) void { // against pardes's SDL; its tests run with unit-test. gm.addImport("gpu_cells", b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} })); if (cells_test == null) cells_test = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "c", .module = gui_c_mod }} }), .filters = test_filters }); + // The glyph atlas (src/font/Atlas.zig) over the font shim + // (vendor/font.{c,h}), compiled below against pardes's + // FreeType and HarfBuzz. + gm.addImport("font_atlas", b.createModule(.{ .root_source_file = sb.path("src/font/Atlas.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} })); + gui_c.addIncludePath(sb.path("vendor")); gm.addImport("gpu_scene", sb.module("gpu_scene")); } sdl_include = dep.path("include"); @@ -983,11 +993,21 @@ pub fn build(b: *std.Build) void { }); gm.linkLibrary(harfbuzz); gm.addIncludePath(upstream.path("src")); + // The Atlas's own tests, over the same FreeType, HarfBuzz and + // shim, the embedded face theirs to draw. + if (atlas_test == null) if (font_c) |fc| if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { + const atlas_mod = b.createModule(.{ .root_source_file = sb.path("src/font/Atlas.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "c", .module = fc }} }); + atlas_mod.linkLibrary(ft); + atlas_mod.linkLibrary(harfbuzz); + atlas_mod.addIncludePath(upstream.path("src")); + atlas_mod.addCSourceFile(.{ .file = sb.path("vendor/font.c") }); + atlas_mod.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ .root_source_file = b.path("assets/AdwaitaMono-Regular.ttf") }); + atlas_test = b.addTest(.{ .root_module = atlas_mod, .filters = test_filters }); + }; } if (target.result.os.tag.isDarwin()) gm.addRPath(.{ .cwd_relative = "/usr/local/lib" }); - gm.addIncludePath(b.path("src/gui")); - gm.addCSourceFile(.{ .file = b.path("src/gui/font.c") }); + if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| gm.addCSourceFile(.{ .file = sb.path("vendor/font.c") }); // the embedded UI font: provided as a build import since assets/ lives // outside the src/ module root (@embedFile can't escape it) gm.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ @@ -1589,6 +1609,7 @@ pub fn build(b: *std.Build) void { _ = units.add(b, perf_tests, null); _ = units.add(b, fs_bench_test, null); if (cells_test) |t| _ = units.add(b, t, null); + if (atlas_test) |t| _ = units.add(b, t, null); const core_test = b.addTest(.{ .root_module = core_module, .filters = test_filters }); const run_core_test = b.addRunArtifact(core_test); run_core_test.has_side_effects = true; 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 -#include -#include -#include -#include -#include - -#include - -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 -#include - -#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 d0d46f44..14194122 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1,5 +1,6 @@ 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 GpuScene = @import("gpu_scene"); const filesystem = @import("../fs.zig"); const std = @import("std"); @@ -87,66 +88,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, @@ -163,6 +109,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, @@ -170,12 +129,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); @@ -209,10 +168,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; @@ -225,22 +183,6 @@ 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; @@ -519,15 +461,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, @@ -538,15 +478,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 = .{}, @@ -666,7 +597,7 @@ fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void { } 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); @@ -704,14 +635,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); @@ -720,50 +644,15 @@ 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; - } -} - -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 }; + _ = g.atlas.addFallback(gpa, bytes, true); } - return .{ .face = 0, .glyph = 0 }; } const CellLayout = struct { w: f32, h: f32, x_off: f32, y_off: f32 }; @@ -1064,14 +953,14 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di c.SDL_GetGPUSwapchainTextureFormat(device, window); 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 @@ -1080,10 +969,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; @@ -1122,9 +1011,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di 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); @@ -1146,7 +1032,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di .overlay_vbuf = overlay_vbuf, .overlay_vxfer = overlay_vxfer, .overlay_vertices = overlay_vertices, - .font = font, + .atlas = atlas, .px = px, .tagline_px = tagline.px, .tagline_percent = config.gui_tagline_font_percent, @@ -1156,8 +1042,6 @@ 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, @@ -1195,8 +1079,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di } 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(); @@ -1210,8 +1093,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di 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); @@ -3254,16 +3135,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()); @@ -4612,7 +4488,7 @@ fn renderFrame( @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); + if (g.atlas.atlas_dirty_top < g.atlas.atlas_dirty_bottom) uploadAtlas(g, cmd); const copy = c.SDL_BeginGPUCopyPass(cmd); const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.vxfer.?, .offset = 0 }; @@ -4978,9 +4854,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; @@ -5015,10 +4891,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; @@ -5117,11 +4993,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; @@ -5139,14 +5015,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 { @@ -5159,7 +5029,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; @@ -5256,19 +5126,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 = @enumFromInt(@intFromEnum(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 = @enumFromInt(@intFromEnum(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; @@ -5286,7 +5155,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]); @@ -5316,27 +5185,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; @@ -5366,7 +5234,7 @@ fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gu .overlay_vbuf = undefined, .overlay_vxfer = undefined, .overlay_vertices = &.{}, - .font = undefined, + .atlas = .{ .font = undefined, .atlas_stage = &.{}, .glyphs = undefined }, .px = 0, .tagline_px = 0, .tagline_percent = 0, @@ -5376,110 +5244,24 @@ 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); } + return s; } /// Uploads only the atlas rows drawn into since the last upload. Glyphs fill @@ -5488,11 +5270,11 @@ fn decorateLine(out: [*]u8, stride: usize, width: usize, height: usize, baseline /// 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 top = g.atlas.atlas_dirty_top; + const rows = g.atlas.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]); + @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], g.atlas.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]); c.SDL_UnmapGPUTransferBuffer(g.device, g.atlas_xfer); const copy = c.SDL_BeginGPUCopyPass(cmd); @@ -5500,8 +5282,8 @@ fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void { 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; + g.atlas.atlas_dirty_top = atlas_h; + g.atlas.atlas_dirty_bottom = 0; } fn ensureCaptureTexture(g: *Gui, width: u32, height: u32) !void { @@ -6690,25 +6472,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; } @@ -6720,7 +6501,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; } @@ -6782,37 +6563,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; @@ -6820,95 +6603,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); @@ -6924,15 +6645,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); @@ -6952,9 +6673,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); + var atlas = try Atlas.init(std.testing.allocator, bytes); + defer atlas.deinit(std.testing.allocator); + try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0); } @@ -7933,7 +7654,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); } @@ -8175,12 +7896,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"); @@ -8190,7 +7908,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); @@ -8198,7 +7916,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| { @@ -8207,8 +7925,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"); @@ -8217,83 +7935,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" { @@ -8310,15 +8023,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; @@ -8329,92 +8039,11 @@ 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 = Cells.backgroundLayerBlend(); try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR), blend.src_alpha_blendfactor); @@ -9070,19 +8699,13 @@ test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes 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| { - const font = c.ui_font_new(primary.ptr, @intCast(primary.len)) orelse return error.FontInit; - defer c.ui_font_free(font); - const fallback = c.ui_font_new(maple.ptr, @intCast(maple.len)) orelse return error.FontInit; - defer c.ui_font_free(fallback); - var g = try textTestGui(font, px); + var g = try textTestGui(primary, px); 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); - g.fallbacks[0] = .{ .face = fallback }; - g.fallback_count = 1; + try std.testing.expect(g.atlas.addFallback(std.testing.allocator, maple, false)); try std.testing.expect(fitTaglineFont(&g, 80)); - const decorations = [_]GlyphDecoration{ + const decorations = [_]Atlas.Decoration{ .{}, .{ .bold = true }, .{ .underline = .single }, @@ -9093,34 +8716,34 @@ test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes .{ .strikethrough = true }, }; for (0x21..0x7f) |cp| { - const drawn = glyphForCodepoint(&g, @intCast(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 = glyphForCodepoint(&g, ' '); + 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 ([_]pardes.FontRole{ .body, .tagline }) |role| { + 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 = glyphForCodepoint(&g, cp); + 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 = glyphForCodepoint(&g, 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_stage); + 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.glyphs.iterator(); + 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 { -- cgit v1.3 From 2d0cb01f1e060c9cf182df491a077cd10d4bfb11 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 03:50:16 -0300 Subject: gui: presentation is sketchbook's (src/gpu/Present.zig), moved as it was, the third step of the GPU move: the device, the window's claim or the soft presenter (a transparent Wayland window, or a claim refused), the present mode, frames in flight and the swapchain's format (runNative), the window's release and claim again (closeWindow, reopenWindow: Present.detach and attach, the window passed in), the frame's target (acquireTarget), the soft present (its renderer, texture and formats, the read back into the capture transfer buffer, the flip), the capture texture and its read back leave gui.zig; Present.init logs what runNative logged, under the gui scope; the Gui holds a pointer to runNative's Present (`present`, its device still `device`), which releases the capture's texture and transfer buffer before the device at the end (they were released in the Gui's defer, beside the gamepad); gui.zig keeps what it writes: captureFrame takes the frame Present.readFrame maps (its submit and fence times for the latency trace, as measured before) and writes latest and the series as before, writeCapturePpm asks Present.bgr for the byte order, and PARDES_FRAMES_CAPTURE is the soft present's frame tap (captureSeries, which reads its directory itself); a soft present's wait, upload and flip come back as Present.Timings and go to the frame probe's zones; releaseWindowParts, which nothing calls, loses the capture's two lines; frame corpus unchanged (77 frames) --- build.zig | 4 +- src/gui/gui.zig | 305 ++++++++------------------------------------------------ 2 files changed, 44 insertions(+), 265 deletions(-) (limited to 'build.zig') diff --git a/build.zig b/build.zig index c2a0c8ac..6d2ddeaf 100644 --- a/build.zig +++ b/build.zig @@ -930,7 +930,9 @@ pub fn build(b: *std.Build) void { gm.addImport("sketch_gpu", gpu); // pardes's renderer, moved to sketchbook (src/gpu/), compiled // against pardes's SDL; its tests run with unit-test. - gm.addImport("gpu_cells", b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} })); + const cells_mod = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} }); + gm.addImport("gpu_cells", cells_mod); + gm.addImport("gpu_present", b.createModule(.{ .root_source_file = sb.path("src/gpu/Present.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "gpu_cells", .module = cells_mod } } })); if (cells_test == null) cells_test = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "c", .module = gui_c_mod }} }), .filters = test_filters }); // The glyph atlas (src/font/Atlas.zig) over the font shim // (vendor/font.{c,h}), compiled below against pardes's diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 14194122..c7fa898b 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1,6 +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"); @@ -430,8 +431,11 @@ const Gui = struct { addon_failed: [pardes.MAX_PANES]u64 = @splat(0), addon_pipeline: ?*c.SDL_GPUGraphicsPipeline = null, window: *c.SDL_Window, + /// The device, the window's claim or soft presenter, the frame's target + /// and the capture's read back (runNative owns it). + present: *Present, + /// present's device, which everything else is made on. device: *c.SDL_GPUDevice, - swapchain_format: c.SDL_GPUTextureFormat, pipeline: *c.SDL_GPUGraphicsPipeline, decor_pipeline: *c.SDL_GPUGraphicsPipeline, overlay_pipeline: *c.SDL_GPUGraphicsPipeline, @@ -549,7 +553,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 = "", @@ -557,27 +560,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, @@ -589,8 +580,6 @@ 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); @@ -918,39 +907,10 @@ 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(); + const device = presenter.device; + const swapchain_format = presenter.swapchain_format; font_allocator = gpa; var atlas = Atlas.init(gpa, font_ttf) catch |err| { @@ -1019,8 +979,8 @@ 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, + .present = &presenter, .device = device, - .swapchain_format = swapchain_format, .pipeline = pipeline, .decor_pipeline = decor_pipeline, .overlay_pipeline = overlay_pipeline, @@ -1042,17 +1002,12 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di .cell_h = cell_h, .ascent = asc, .tagline_baseline = tagline.baseline, - .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, @@ -1073,8 +1028,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di 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); } setGuiFontName(&g, "Adwaita Mono"); @@ -1110,14 +1063,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; @@ -1129,17 +1075,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; @@ -1147,7 +1085,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; } @@ -3163,7 +3101,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)); @@ -3320,7 +3259,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"); @@ -4318,7 +4257,7 @@ fn renderFrame( defer if (!command_consumed) { _ = c.SDL_SubmitGPUCommandBuffer(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); return false; @@ -4541,43 +4480,22 @@ fn renderFrame( 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 { @@ -5221,8 +5139,8 @@ 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, + .present = undefined, .device = undefined, - .swapchain_format = undefined, .pipeline = undefined, .decor_pipeline = undefined, .overlay_pipeline = undefined, @@ -5286,128 +5204,6 @@ fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void { g.atlas.atlas_dirty_bottom = 0; } -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 = Cells.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; @@ -5436,27 +5232,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-.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", false); + 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, true); + 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; } @@ -5493,13 +5276,7 @@ fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u // 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; @@ -8669,7 +8446,7 @@ fn prepareAddonGpu(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer if (g.addon_pipeline == null) { var blend = Cells.backgroundLayerBlend(); blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; - g.addon_pipeline = Cells.makePipeline(g.device, g.swapchain_format, image_vert_spv, image_frag_spv, 1, 1, Cells.image_input, blend) catch continue; + g.addon_pipeline = Cells.makePipeline(g.device, g.present.swapchain_format, image_vert_spv, image_frag_spv, 1, 1, Cells.image_input, blend) catch continue; } g.prepared_images.append(gpa, .{ .premultiplied = true, -- cgit v1.3 From 49f659e24c5ace2568555a0a37772bc56a0be393 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 04:36:56 -0300 Subject: gui: the renderer's resources, pictures, overlay and atlas upload are sketchbook's (src/gpu/Cells.zig), moved as they were, the fourth step of the GPU move, its first half: the atlas's texture, sampler and upload buffer, the pictures' sampler, the four pipelines, the overlay's buffers and their release (runNative: Cells.init and deinit, on Present's device, before the device goes), the cells' and the pictures' instance buffers, the pictures' textures by key (releaseNativeImage, clearNativeImages, uploadNativeTexture's upload and uploadTextureRows: Cells.image, which takes the RGBA, its size and stride and the dirty rows, still the whole picture or only the rows that changed into the texture held), the pictures' instance upload (Cells.mapImages and uploadImages around gui.zig's emitPreparedImage) and their draws (drawNativeImagesGpu: Cells.drawImages, each picture's clip, imageScissor's, kept beside its texture as the frame's instances are written), the addon pipeline (made on first use as before: Cells.makeAddonPipeline), uploadAtlas (over the Atlas's dirty rows), uploadOverlayGpu, pushLayerOpacity and drawOverlayGpu leave gui.zig; the seven SPIR-V embeds go with the pipelines (build.zig gives the `.spv` imports to the Cells module, sketchbook's GLSL through glslc or its prebuilt copies, as before); the Gui holds a pointer to runNative's Cells (`cells`) and no longer the device; an addon's texture is still handed over borrowed and premultiplied; renderFrame's command buffer, cell upload and render pass stay for the second half; frame corpus unchanged (77 frames) --- build.zig | 29 ++--- src/gui/gui.zig | 343 +++++++------------------------------------------------- 2 files changed, 59 insertions(+), 313 deletions(-) (limited to 'build.zig') diff --git a/build.zig b/build.zig index 6d2ddeaf..25f1d8b9 100644 --- a/build.zig +++ b/build.zig @@ -928,16 +928,25 @@ pub fn build(b: *std.Build) void { if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| { const gpu = b.createModule(.{ .root_source_file = sb.path("src/gpu/Executor.zig"), .imports = &.{ .{ .name = "abi", .module = sb.module("abi") }, .{ .name = "c", .module = gui_c_mod } } }); gm.addImport("sketch_gpu", gpu); - // pardes's renderer, moved to sketchbook (src/gpu/), compiled - // against pardes's SDL; its tests run with unit-test. - const cells_mod = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} }); - gm.addImport("gpu_cells", cells_mod); - gm.addImport("gpu_present", b.createModule(.{ .root_source_file = sb.path("src/gpu/Present.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "gpu_cells", .module = cells_mod } } })); - if (cells_test == null) cells_test = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "c", .module = gui_c_mod }} }), .filters = test_filters }); // The glyph atlas (src/font/Atlas.zig) over the font shim // (vendor/font.{c,h}), compiled below against pardes's // FreeType and HarfBuzz. - gm.addImport("font_atlas", b.createModule(.{ .root_source_file = sb.path("src/font/Atlas.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} })); + const atlas_mod = b.createModule(.{ .root_source_file = sb.path("src/font/Atlas.zig"), .imports = &.{.{ .name = "c", .module = gui_c_mod }} }); + gm.addImport("font_atlas", atlas_mod); + // pardes's renderer, moved to sketchbook (src/gpu/), compiled + // against pardes's SDL; its tests run with unit-test. Its + // SPIR-V is sketchbook's GLSL through glslc, or the prebuilt + // copies with -Dprebuilt-shaders. + const cells_mod = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "font_atlas", .module = atlas_mod } } }); + for (gui_shaders) |name| cells_mod.addAnonymousImport(b.fmt("{s}.spv", .{name}), .{ + .root_source_file = if (prebuilt_shaders) + sb.path(b.fmt("src/gpu/shaders/prebuilt/{s}.spv", .{name})) + else + compileGlsl(b, sb.path(b.fmt("src/gpu/shaders/{s}.glsl", .{name})), name), + }); + gm.addImport("gpu_cells", cells_mod); + gm.addImport("gpu_present", b.createModule(.{ .root_source_file = sb.path("src/gpu/Present.zig"), .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "gpu_cells", .module = cells_mod } } })); + if (cells_test == null) cells_test = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = sb.path("src/gpu/Cells.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "c", .module = gui_c_mod }, .{ .name = "font_atlas", .module = atlas_mod } } }), .filters = test_filters }); gui_c.addIncludePath(sb.path("vendor")); gm.addImport("gpu_scene", sb.module("gpu_scene")); } @@ -1015,12 +1024,6 @@ pub fn build(b: *std.Build) void { gm.addAnonymousImport("AdwaitaMono-Regular.ttf", .{ .root_source_file = b.path("assets/AdwaitaMono-Regular.ttf"), }); - if (b.lazyDependency("sketchbook", .{ .@"gpu-only" = true })) |sb| for (gui_shaders) |name| gm.addAnonymousImport(b.fmt("{s}.spv", .{name}), .{ - .root_source_file = if (prebuilt_shaders) - sb.path(b.fmt("src/gpu/shaders/prebuilt/{s}.spv", .{name})) - else - compileGlsl(b, sb.path(b.fmt("src/gpu/shaders/{s}.glsl", .{name})), name), - }); }; if (target.result.os.tag == .macos) if (sdl_include) |include| { const adapter_test = b.addSystemCommand(&.{ "xcrun", "clang", "-fobjc-arc", "-O1", "-framework", "Cocoa", "-I" }); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index c7fa898b..3dfafd68 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -42,13 +42,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 }; @@ -429,32 +422,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, /// The device, the window's claim or soft presenter, the frame's target /// and the capture's read back (runNative owns it). present: *Present, - /// present's device, which everything else is made on. - device: *c.SDL_GPUDevice, - 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 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. @@ -909,8 +885,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di } else log.err("SDL_CreateCursor: {s}", .{c.SDL_GetError()}); var presenter = try Present.init(window, test_mode, surface_opacity); defer presenter.deinit(); - const device = presenter.device; - const swapchain_format = presenter.swapchain_format; font_allocator = gpa; var atlas = Atlas.init(gpa, font_ttf) catch |err| { @@ -942,34 +916,10 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di _ = c.SDL_SyncWindow(window); } - const atlas_tex = Cells.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 Cells.makePipeline(device, swapchain_format, vert_spv, frag_spv, 1, 1, Cells.cell_input, std.mem.zeroes(c.SDL_GPUColorTargetBlendState)); - const decor_pipeline = try Cells.makePipeline(device, swapchain_format, vert_spv, decor_frag_spv, 0, 1, Cells.cell_input, Cells.backgroundLayerBlend()); - const overlay_pipeline = try Cells.makePipeline(device, swapchain_format, overlay_vert_spv, overlay_frag_spv, 0, 1, Cells.overlay_input, Cells.backgroundLayerBlend()); - const image_pipeline = try Cells.makePipeline(device, swapchain_format, image_vert_spv, image_frag_spv, 1, 1, Cells.image_input, Cells.backgroundLayerBlend()); - - 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; + 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_vertices = try gpa.alloc(OverlayVertex, max_overlay_vertices); defer gpa.free(overlay_vertices); @@ -980,17 +930,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di .link_cursor = link_cursor, .box_cursor = box_cursor, .present = &presenter, - .device = device, - .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, + .cells = &cells, .overlay_vertices = overlay_vertices, .atlas = atlas, .px = px, @@ -1012,40 +952,19 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di .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.gamepad) |pad| c.SDL_CloseGamepad(pad); - } + defer if (g.gamepad) |pad| c.SDL_CloseGamepad(pad); setGuiFontName(&g, "Adwaita Mono"); loadFallbackFonts(&g, gpa); 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 gpa.free(g.scroll_edge); // grown on demand by stepScroll defer g.glide.deinit(gpa); resetGlyphAtlas(&g); @@ -1251,7 +1170,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; @@ -3977,17 +3896,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; @@ -4026,72 +3934,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 = Cells.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 {}; } @@ -4150,14 +3999,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; } @@ -4171,25 +4020,18 @@ fn prepareNativeImages( const capacity = std.math.cast(u32, g.prepared_images.items.len) orelse return false; if (capacity == 0) return true; - Cells.growInstances(g.device, &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; } @@ -4202,35 +4044,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, @@ -4252,7 +4065,7 @@ 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 = c.SDL_AcquireGPUCommandBuffer(g.cells.device) orelse return false; var command_consumed = false; defer if (!command_consumed) { _ = c.SDL_SubmitGPUCommandBuffer(cmd); @@ -4300,7 +4113,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(); @@ -4367,9 +4180,9 @@ 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 Cells.growInstances(g.device, &g.vbuf, &g.vxfer, &g.vbuf_cells, capacity, @sizeOf(CellInstance)); + try Cells.growInstances(g.cells.device, &g.cells.vbuf, &g.cells.vxfer, &g.cells.vbuf_cells, capacity, @sizeOf(CellInstance)); - const vptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, g.vxfer.?, false) orelse { + const vptr: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.cells.device, g.cells.vxfer.?, false) orelse { command_consumed = true; _ = c.SDL_SubmitGPUCommandBuffer(cmd); return false; @@ -4425,13 +4238,13 @@ 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.?); + c.SDL_UnmapGPUTransferBuffer(g.cells.device, g.cells.vxfer.?); - if (g.atlas.atlas_dirty_top < g.atlas.atlas_dirty_bottom) uploadAtlas(g, cmd); + if (g.atlas.atlas_dirty_top < g.atlas.atlas_dirty_bottom) g.cells.uploadAtlas(cmd, &g.atlas); 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) }; + const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.cells.vxfer.?, .offset = 0 }; + const dst = c.SDL_GPUBufferRegion{ .buffer = g.cells.vbuf.?, .offset = 0, .size = (cell_total + shifted + decor_len) * @sizeOf(CellInstance) }; c.SDL_UploadToGPUBuffer(copy, &src, &dst, false); c.SDL_EndGPUCopyPass(copy); } @@ -4440,40 +4253,40 @@ fn renderFrame( 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); + Cells.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 }; + if ((group.cell_count != 0 or has_shifted) and g.cells.vbuf != null) { + c.SDL_BindGPUGraphicsPipeline(rp, g.cells.pipeline); + const samp_binding = c.SDL_GPUTextureSamplerBinding{ .texture = g.cells.atlas_tex, .sampler = g.cells.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) }; + const binding = c.SDL_GPUBufferBinding{ .buffer = g.cells.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) }; + const binding = c.SDL_GPUBufferBinding{ .buffer = g.cells.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); + if (group.image_count != 0) g.cells.drawImages(rp, group.image_start, group.image_count, whole); + if (group.decor_count != 0 and g.cells.vbuf != null) { + c.SDL_BindGPUGraphicsPipeline(rp, g.cells.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) }; + Cells.pushLayerOpacity(cmd, rp, if (index == groups.ink) 1 else background_opacity); + const binding = c.SDL_GPUBufferBinding{ .buffer = g.cells.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); + g.cells.drawOverlay(cmd, rp, overlay_count, backgroundOpacity(g.applied_window_opacity)); c.SDL_EndGPURenderPass(rp); command_consumed = true; @@ -5140,17 +4953,7 @@ fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gu return .{ .window = undefined, .present = undefined, - .device = 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, + .cells = undefined, .overlay_vertices = &.{}, .atlas = .{ .font = undefined, .atlas_stage = &.{}, .glyphs = undefined }, .px = 0, @@ -5182,28 +4985,6 @@ fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { return s; } -/// 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.atlas_dirty_top; - const rows = g.atlas.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.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.atlas_dirty_top = atlas_h; - g.atlas.atlas_dirty_bottom = 0; -} - fn backgroundOpacity(percent: u8) f32 { std.debug.assert(percent <= 100); return @as(f32, @floatFromInt(percent)) / 100; @@ -6141,40 +5922,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, @@ -8415,7 +8162,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) { @@ -8443,11 +8190,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 = Cells.backgroundLayerBlend(); - blend.src_color_blendfactor = c.SDL_GPU_BLENDFACTOR_ONE; - g.addon_pipeline = Cells.makePipeline(g.device, g.present.swapchain_format, image_vert_spv, image_frag_spv, 1, 1, Cells.image_input, blend) catch continue; - } + g.cells.makeAddonPipeline() catch continue; g.prepared_images.append(gpa, .{ .premultiplied = true, .texture = out.texture, -- cgit v1.3