From bcdf31227309969a9af3a07b6e945f50a95c2dbc Mon Sep 17 00:00:00 2001 From: Jeremy Collins Date: Sun, 29 Nov 2026 23:17:54 -0500 Subject: [PATCH] Add an OpenGL ES 3.0 backend that draws into a host framebuffer A host that already renders with OpenGL ES, such as a Qt Quick application with a QQuickFramebufferObject, had to share Vulkan images with its GL context to show a chart. `-Dgpu=gles` now builds the library with an OpenGL ES 3.0 backend. It draws the same prepared scene as the other backends, with the same vertex streams, blend state, draw order and batcher. The host attaches its current context with the new kind CHARTTABLE_NATIVE_GLES_CONTEXT and a charttable_gles_context, which carries the host's get_proc_address. The library loads every GL function through it and links no GL library. charttable_render_gles draws into a framebuffer the host names, at the size the host gives. charttable_render draws into the framebuffer bound for drawing. charttable creates no window, no EGL surface and no context, and it never swaps buffers. Every call that issues GL commands saves the state it changes and restores it before it returns. The backend needs no depth attachment. No pipeline of the Vulkan backend writes depth, so its depth test only refuses depth 1.0, which no range uses. makeScene runs on the build worker, where the host's context is not current. In this backend it copies the scene to CPU memory, and adoptScene makes the GL objects on the owner thread. With kind CHARTTABLE_NATIVE_NONE the backend opens libEGL at run time and makes a headless context of its own, for snapshots and for the tests. attach_surface now refuses a kind the backend does not know with CHARTTABLE_ERR_UNSUPPORTED, where it converted it with @enumFromInt. The shaders are GLSL ES 3.00 ports of shaders/vk, in shaders/gles. A CI job builds and tests the backend with Mesa through a headless EGL. --- .github/workflows/ci.yml | 28 +- DESIGN.md | 2 + README.md | 21 +- build.zig | 32 +- include/charttable.h | 57 +- shaders/gles/README.md | 28 + shaders/gles/fill.frag | 15 + shaders/gles/fill.vert | 45 ++ shaders/gles/pattern.frag | 23 + shaders/gles/pattern.vert | 34 + shaders/gles/prelude.glsl | 34 + shaders/gles/sdf.frag | 26 + shaders/gles/sprite.frag | 14 + shaders/gles/sprite.vert | 42 ++ src/capi.zig | 88 ++- src/gpu/gpu.zig | 11 +- src/gpu/gpu_gles.zig | 1500 +++++++++++++++++++++++++++++++++++++ 17 files changed, 1985 insertions(+), 15 deletions(-) create mode 100644 shaders/gles/README.md create mode 100644 shaders/gles/fill.frag create mode 100644 shaders/gles/fill.vert create mode 100644 shaders/gles/pattern.frag create mode 100644 shaders/gles/pattern.vert create mode 100644 shaders/gles/prelude.glsl create mode 100644 shaders/gles/sdf.frag create mode 100644 shaders/gles/sprite.frag create mode 100644 shaders/gles/sprite.vert create mode 100644 src/gpu/gpu_gles.zig diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7f4cff8..39a5a72 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,8 +11,10 @@ on: # charttable builds with Zig 0.16 into libcharttable.a, libcharttable.so and the # C header. Every consumer takes one of those three, so CI builds all of them. # -# Three jobs, because no single runner compiles the whole library: +# Four jobs, because no single runner compiles the whole library: # * build-test — the gate. Vulkan backend, system codecs, the full test suite. +# * gles — the OpenGL ES backend (-Dgpu=gles) and the full test suite, +# drawn with Mesa's software renderer through a headless EGL. # * macos — the only runner that compiles the Metal backend and the ObjC # shim, and the only one that builds the demo app. # * cross — every target a release ships, so a tag does not discover a @@ -48,6 +50,30 @@ jobs: - name: Build the shared library run: zig build shared + gles: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + # The backend links no GL library. Its tests open libEGL at run time and + # draw with Mesa's llvmpipe on the surfaceless platform, so the runner + # needs no display. + - name: Install EGL, Mesa and the codecs + run: | + sudo apt-get update + sudo apt-get install -y libegl1 libgles2 libegl-mesa0 libgl1-mesa-dri libwebp-dev libpng-dev + + - name: Install Zig + uses: mlugg/setup-zig@v2 + with: + version: 0.16.0 + + - name: Build and test + run: zig build install test -Dgpu=gles + + - name: Build the shared library + run: zig build shared -Dgpu=gles + macos: runs-on: macos-latest steps: diff --git a/DESIGN.md b/DESIGN.md index d05a840..21d5b6b 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -94,6 +94,8 @@ charttable/ gpu_metal.zig + metal_shim.m/.h gpu_vk.zig + c_vk.zig gpu_d3d12.zig + c_d3d12.zig + gpu_gles.zig OpenGL ES 3.0 (-Dgpu=gles): the host's + context and framebuffer, GL loaded by name gpu_sdl.zig + c_sdl.zig raster.zig raster sources/layers (rework of lookout raster.zig — spec "raster" type) diff --git a/README.md b/README.md index 1da973b..ce19d8b 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ --- -charttable is one Zig library behind a C ABI. It draws through Metal, Vulkan or Direct3D 12, so the same library serves macOS, iOS, Linux, Windows and Android. It does no networking. Tiles come from a local pmtiles archive, or from your code through a resource callback. +charttable is one Zig library behind a C ABI. It draws through Metal, Vulkan or Direct3D 12, so the same library serves macOS, iOS, Linux, Windows and Android. A build with `-Dgpu=gles` draws through OpenGL ES 3.0 instead, into a framebuffer of a context the host owns. It does no networking. Tiles come from a local pmtiles archive, or from your code through a resource callback. ## Install @@ -49,6 +49,21 @@ charttable_tick(ct, dt_ms); if (charttable_needs_redraw(ct)) charttable_render(ct); ``` +A host with its own OpenGL ES context, such as a Qt Quick `QQuickFramebufferObject`, attaches that context and draws into its framebuffer. charttable loads the GL functions through the host's loader, so the library links no GL library. It creates no window and no EGL surface, and it never swaps buffers. Each call restores the GL state it changed. + +```c +static void *get_proc(const char *name, void *user) { + return (void *)eglGetProcAddress(name); +} + +charttable_gles_context gl = { .get_proc_address = get_proc }; +charttable_attach_surface(ct, CHARTTABLE_NATIVE_GLES_CONTEXT, &gl, w_px, h_px); + +/* each frame, with the context current */ +charttable_gles_target t = { .framebuffer = fbo, .width = w_px, .height = h_px }; +charttable_render_gles(ct, &t); +``` + The API is one opaque handle and about forty functions. A mutex inside the handle serializes them, so every call is safe from any thread. The three functions that touch the surface must be called from the thread that owns it, because the platform requires that. ## What it renders @@ -64,7 +79,7 @@ A layer or property charttable does not support yet is skipped, and the reason g - **A tile is turned into triangles once.** After that, a pan, zoom or rotation draws the same geometry with a new matrix. A map sitting still uses no CPU. - **Restyling touches the paint stream only.** Geometry and evaluated paint sit in separate vertex streams. Changing a color, an opacity or a whole palette re-uploads the paint and leaves the geometry alone, so a day-to-night switch lands in one frame. - **Features appear at the zoom the style names.** Each vertex carries the zoom range it is visible in, so a feature fades in at 12.4 if the style says 12.4, not at 13. -- **One scene, three backends.** Metal, Vulkan and D3D12 draw from the same prepared scene, so a fix in the renderer reaches all three. +- **One scene, four backends.** Metal, Vulkan, D3D12 and OpenGL ES draw from the same prepared scene, so a fix in the renderer reaches all of them. ## Build @@ -76,7 +91,7 @@ zig build lib # libcharttable.a and the header, into zig-out zig build shared # the shared library, beside it ``` -Add `-Dcodec-source` to compile libwebp and libpng in rather than link the platform copies. A cross build needs it. `-Dgpu=vk` picks the Vulkan backend on Windows, where D3D12 is the default. `-Dversion` sets what `charttable_version()` reports and what the shared library stamps into its soname. A release passes the tag, and a source build reports `0.0.0-dev`. +Add `-Dcodec-source` to compile libwebp and libpng in rather than link the platform copies. A cross build needs it. `-Dgpu=vk` picks the Vulkan backend on Windows, where D3D12 is the default. `-Dgpu=gles` picks the OpenGL ES 3.0 backend on any target off Apple. Its tests draw with a headless context from libEGL, and skip when libEGL is absent. `-Dversion` sets what `charttable_version()` reports and what the shared library stamps into its soname. A release passes the tag, and a source build reports `0.0.0-dev`. ## Status diff --git a/build.zig b/build.zig index 286986d..4fa8323 100644 --- a/build.zig +++ b/build.zig @@ -16,11 +16,14 @@ pub fn build(b: *std.Build) void { // Windows can draw with either backend: D3D12 is the default there, and // the Vulkan backend has a win32 surface path for a host that would rather - // run on the loader. Everywhere else this option has nothing to choose. - const GpuBackend = enum { auto, vk, d3d12 }; - const gpu_choice = b.option(GpuBackend, "gpu", "Windows renderer backend: d3d12 (default) or vk") orelse .auto; - const use_d3d12 = windows and gpu_choice != .vk; - const use_vk = !apple and !use_d3d12; + // run on the loader. `gles` picks the OpenGL ES 3.0 backend on any target + // off Apple, for a host that draws with a GL context of its own. + const GpuBackend = enum { auto, vk, d3d12, gles }; + const gpu_choice = b.option(GpuBackend, "gpu", "Renderer backend: d3d12 (Windows default), vk (default off Apple and Windows), or gles") orelse .auto; + if (apple and gpu_choice == .gles) @panic("-Dgpu=gles: Apple targets draw with Metal"); + const use_gles = !apple and gpu_choice == .gles; + const use_d3d12 = windows and !use_gles and gpu_choice != .vk; + const use_vk = !apple and !use_d3d12 and !use_gles; // The library module every consumer imports (`@import("charttable")`). const mod = b.addModule("charttable", .{ @@ -78,6 +81,7 @@ pub fn build(b: *std.Build) void { ct_opts.addOption(bool, "libpng", use_libpng); // Which renderer src/gpu/gpu.zig selects on Windows. ct_opts.addOption(bool, "gpu_d3d12", use_d3d12); + ct_opts.addOption(bool, "gpu_gles", use_gles); // Where the vendored spec conformance fixtures live (absolute, so the // test binary finds them regardless of its own cwd). The harness skips // itself when the directory is absent. @@ -135,6 +139,24 @@ pub fn build(b: *std.Build) void { for (hlsl) |e| m.addAnonymousImport(e[0], .{ .root_source_file = b.path(e[1]) }); } + // The OpenGL ES backend (src/gpu/gpu_gles.zig). The GLSL ES rides in + // as source and the context compiles it at open. Every GL function + // comes from the host's loader, or from libEGL opened at run time for + // a snapshot, so the build links no GL library. + if (use_gles) { + const glsl = [_][2][]const u8{ + .{ "gles_prelude", "shaders/gles/prelude.glsl" }, + .{ "gles_fill_vert", "shaders/gles/fill.vert" }, + .{ "gles_fill_frag", "shaders/gles/fill.frag" }, + .{ "gles_pattern_vert", "shaders/gles/pattern.vert" }, + .{ "gles_pattern_frag", "shaders/gles/pattern.frag" }, + .{ "gles_sprite_vert", "shaders/gles/sprite.vert" }, + .{ "gles_sprite_frag", "shaders/gles/sprite.frag" }, + .{ "gles_sdf_frag", "shaders/gles/sdf.frag" }, + }; + for (glsl) |e| m.addAnonymousImport(e[0], .{ .root_source_file = b.path(e[1]) }); + } + if (use_vk) { const spv = [_][2][]const u8{ .{ "fill_vert_spv", "shaders/vk/fill.vert.spv" }, diff --git a/include/charttable.h b/include/charttable.h index 6df2a4d..cacfc55 100644 --- a/include/charttable.h +++ b/include/charttable.h @@ -3,7 +3,10 @@ * One opaque handle, one mutex behind it. Every function here is safe to call * from any thread and is serialized internally, with ONE exception that is a * platform rule rather than ours: charttable_attach_surface, _render and - * _snapshot_rgba must be called from the thread that owns the surface. + * _snapshot_rgba must be called from the thread that owns the surface. With + * an OpenGL ES context (CHARTTABLE_NATIVE_GLES_CONTEXT), _render_gles, + * _detach_surface and _close join them, and the context must be current on + * that thread for each call. * * Conventions: * - Sizes and positions are LOGICAL POINTS; the library scales by the @@ -70,13 +73,52 @@ typedef enum { CHARTTABLE_NATIVE_X11_WINDOW = 5, /* charttable_x11_window* (vk) */ CHARTTABLE_NATIVE_ANDROID_WINDOW = 7, /* ANativeWindow* (vk) */ CHARTTABLE_NATIVE_WAYLAND_SURFACE = 8, /* charttable_wayland_surface* (vk) */ - CHARTTABLE_NATIVE_D3D12_PANEL = 10 /* no handle (d3d12 backend): the + CHARTTABLE_NATIVE_D3D12_PANEL = 10, /* no handle (d3d12 backend): the * renderer makes a composition * swapchain and the host composes * it; fetch it with * charttable_d3d12_swapchain */ + CHARTTABLE_NATIVE_GLES_CONTEXT = 11 /* charttable_gles_context* (gles + * backend, -Dgpu=gles) */ } charttable_native_kind; +/* ---- OpenGL ES (a library built with -Dgpu=gles) ------------------------- + * + * charttable draws with the host's OpenGL ES 3.0 context. It creates no + * window, no EGLSurface and no context, and it never swaps buffers. It loads + * every GL function through get_proc_address, so the library links no GL + * library. Make the context current before attach, render, render_gles, + * snapshot, detach and close, on the thread that owns it. + * + * Each of those calls saves the GL state it changes and restores it before + * it returns: the framebuffer bindings, the viewport, the enables, the blend + * state, the color mask, the clear color, the program, the vertex array, the + * array, uniform and pixel buffer bindings, the texture and sampler of unit + * 0, and the pack and unpack parameters. charttable needs no depth or stencil + * attachment: it draws in paint order. + * + * In a library with this backend, kind CHARTTABLE_NATIVE_NONE opens libEGL at + * run time and makes a headless context of its own, for snapshots. */ + +/* Return the address of the GL function `name` (for example "glDrawArrays"), + * or NULL. eglGetProcAddress, or QOpenGLContext::getProcAddress, does this. */ +typedef void *(*charttable_gles_get_proc)(const char *name, void *user); + +/* `native` for CHARTTABLE_NATIVE_GLES_CONTEXT. charttable reads it only + * during charttable_attach_surface. */ +typedef struct { + charttable_gles_get_proc get_proc_address; + void *user; /* passed back to get_proc_address */ +} charttable_gles_context; + +/* A framebuffer of the host's context. 0 names the default framebuffer. + * width and height are pixels. */ +typedef struct { + uint32_t framebuffer; + uint32_t width; + uint32_t height; +} charttable_gles_target; + /* Create the render surface. `native` is a CAMetalLayer* when kind is * CHARTTABLE_NATIVE_METAL_LAYER, NULL for CHARTTABLE_NATIVE_D3D12_PANEL and * for offscreen-only rendering. */ @@ -261,9 +303,18 @@ int charttable_idle(charttable *); uint32_t charttable_pending_tiles(charttable *); /* Draw into the attached surface. Returns 1 if it drew, 0 if there was - * nothing to draw, negative on error. */ + * nothing to draw, negative on error. With CHARTTABLE_NATIVE_GLES_CONTEXT it + * draws into the framebuffer bound for drawing, at the size of the last + * charttable_resize times the pixel density. */ int charttable_render(charttable *); +/* OpenGL ES only. Clear `target` to the style's background and draw a frame + * into it. The size of the target becomes the size of the frame in pixels, so + * a resized framebuffer needs only a new target; call charttable_resize too, + * for the viewport in points. Returns 1 if it drew, CHARTTABLE_ERR_UNSUPPORTED + * on another backend or kind, other negative values on error. */ +int charttable_render_gles(charttable *, const charttable_gles_target *target); + /* Render offscreen and copy RGBA8 (top-down, w*h*4) into dst. */ int charttable_snapshot_rgba(charttable *, uint8_t *dst, size_t len); diff --git a/shaders/gles/README.md b/shaders/gles/README.md new file mode 100644 index 0000000..9878739 --- /dev/null +++ b/shaders/gles/README.md @@ -0,0 +1,28 @@ +# GLSL ES 3.00 shaders (OpenGL ES) + +charttable's scene contract (src/scene/types.zig) stated in GLSL ES 3.00, for +the backend that `-Dgpu=gles` selects. There is no build-time shader step: +gpu_gles.zig embeds these files and the host's context compiles them at open. +Every stage is compiled as two strings, `prelude.glsl` and then the stage, so +the uniform block and the per-draw uniforms are declared once. + +Each stage is a port of the file of the same name in `shaders/vk/`. Keep them +in step with those, and with `shaders/metal.metal`, the reference statement of +the contract. + +## Differences from the Vulkan shaders + +- The block `U` is `scene.Uniforms`, std140, at uniform buffer binding 0. The + backend writes it once per frame. +- The fields that change per draw are plain uniforms: `u_clip` + (`clip_rect`), `u_cell` (`cell_px`) and `u_halo` (`color`). +- `pattern.frag` counts `gl_FragCoord.y` from the top row with `u_fb_h`, the + target height. GL counts it from the bottom row, and the other backends + from the top. +- Every sampler reads texture unit 0. + +## The vertex layout + +The attribute locations are the ones in `shaders/vk/README.md`. The integer +attributes (`a_zwin`, `a_flags`, `a_pack`) use `glVertexAttribIPointer`, and +the paint streams are normalized `GL_UNSIGNED_BYTE` x4. diff --git a/shaders/gles/fill.frag b/shaders/gles/fill.frag new file mode 100644 index 0000000..21a7704 --- /dev/null +++ b/shaders/gles/fill.frag @@ -0,0 +1,15 @@ +// Flat color from stream B, clipped to the tile of the draw. A port of +// shaders/vk/fill.frag. prelude.glsl comes first. +in vec4 v_color; +in vec2 v_world; +layout(location = 0) out vec4 o_color; + +bool clipped(vec2 world) { + return world.x < u_clip.x || world.y < u_clip.y || + world.x > u_clip.z || world.y > u_clip.w; +} + +void main() { + if (clipped(v_world)) discard; + o_color = v_color; +} diff --git a/shaders/gles/fill.vert b/shaders/gles/fill.vert new file mode 100644 index 0000000..dc7ea97 --- /dev/null +++ b/shaders/gles/fill.vert @@ -0,0 +1,45 @@ +// charttable fill vertex shader (OpenGL ES 3.0): flat-color triangles, for +// area fills and line work. A port of shaders/vk/fill.vert. Keep the two in +// step. prelude.glsl comes first. +layout(location = 0) in vec2 a_pos; +layout(location = 1) in vec2 a_off; +layout(location = 2) in uint a_zwin; +layout(location = 3) in uint a_flags; +layout(location = 4) in float a_depth; +layout(location = 5) in vec4 a_color; +layout(location = 6) in vec4 a_color_hi; + +out vec4 v_color; +out vec2 v_world; + +vec2 world_of(vec2 p, vec2 off) { + vec2 back = vec2( off.x * u.rot_cos + off.y * u.rot_sin, + -off.x * u.rot_sin + off.y * u.rot_cos); + return p + back * u.size_scale * u.world_per_px; +} + +bool gate(uint zwin) { + float zmin = float(zwin & 0xFFFFu); + float zmax = float(zwin >> 16); + return zmin <= u.zoom && u.zoom <= zmax; +} + +vec2 screen_offset(vec2 off, uint flags) { + if ((flags & 1u) != 0u) { + off = vec2(off.x * u.rot_cos - off.y * u.rot_sin, + off.x * u.rot_sin + off.y * u.rot_cos); + } + return off; +} + +void main() { + vec4 clip = u.mvp * vec4(a_pos, 0.0, 1.0); + vec2 off = screen_offset(a_off, a_flags); + float wslope = (float((a_flags >> 8) & 0xFFu) - 128.0) * (1.0 / 32.0); + off *= exp2(wslope * u.zoom_t); + clip.xy += off * u.px_to_clip * u.size_scale * clip.w; + clip.z = a_depth * clip.w; + gl_Position = gate(a_zwin) ? clip : vec4(0.0, 0.0, 2.0, 1.0); // z=2 -> clipped + v_color = mix(a_color, a_color_hi, clamp(u.zoom_t, 0.0, 1.0)); + v_world = world_of(a_pos, off); +} diff --git a/shaders/gles/pattern.frag b/shaders/gles/pattern.frag new file mode 100644 index 0000000..bc5096e --- /dev/null +++ b/shaders/gles/pattern.frag @@ -0,0 +1,23 @@ +// Phase = (fragment - world origin) / cell, in framebuffer px, with y counted +// from the top row as the other backends count it. A port of +// shaders/vk/pattern.frag. prelude.glsl comes first. +uniform sampler2D cell; + +in vec2 v_anchor; +in vec2 v_world; +layout(location = 0) out vec4 o_color; + +bool clipped(vec2 world) { + return world.x < u_clip.x || world.y < u_clip.y || + world.x > u_clip.z || world.y > u_clip.w; +} + +void main() { + if (clipped(v_world)) discard; + vec2 frag = vec2(gl_FragCoord.x, u_fb_h - gl_FragCoord.y); + vec2 sz = max(u_cell, vec2(1.0)); + vec2 uv = fract((frag - v_anchor) / sz); + vec4 c = texture(cell, uv); + if (c.a < 0.02) discard; + o_color = c; +} diff --git a/shaders/gles/pattern.vert b/shaders/gles/pattern.vert new file mode 100644 index 0000000..7089bc2 --- /dev/null +++ b/shaders/gles/pattern.vert @@ -0,0 +1,34 @@ +// Area fills tiled from a pattern cell. A port of shaders/vk/pattern.vert. +// prelude.glsl comes first. +layout(location = 0) in vec2 a_pos; +layout(location = 1) in vec2 a_off; +layout(location = 2) in uint a_zwin; +layout(location = 3) in uint a_flags; +layout(location = 4) in float a_depth; + +out vec2 v_anchor; +out vec2 v_world; + +vec2 world_of(vec2 p, vec2 off) { + vec2 back = vec2( off.x * u.rot_cos + off.y * u.rot_sin, + -off.x * u.rot_sin + off.y * u.rot_cos); + return p + back * u.size_scale * u.world_per_px; +} + +void main() { + vec4 clip = u.mvp * vec4(a_pos, 0.0, 1.0); + vec2 off = a_off; + if ((a_flags & 1u) != 0u) { + off = vec2(off.x * u.rot_cos - off.y * u.rot_sin, + off.x * u.rot_sin + off.y * u.rot_cos); + } + clip.xy += off * u.px_to_clip * u.size_scale * clip.w; + clip.z = a_depth * clip.w; + + float zmin = float(a_zwin & 0xFFFFu); + float zmax = float(a_zwin >> 16); + bool vis = zmin <= u.zoom && u.zoom <= zmax; + gl_Position = vis ? clip : vec4(0.0, 0.0, 2.0, 1.0); + v_anchor = u.anchor_px; + v_world = world_of(a_pos, off); +} diff --git a/shaders/gles/prelude.glsl b/shaders/gles/prelude.glsl new file mode 100644 index 0000000..8e5db39 --- /dev/null +++ b/shaders/gles/prelude.glsl @@ -0,0 +1,34 @@ +#version 300 es +// charttable GLSL ES 3.00 prelude. The backend (src/gpu/gpu_gles.zig) passes +// this text ahead of every stage, so the block and the per-draw uniforms are +// declared once and the two stages of a program cannot disagree about them. +precision highp float; +precision highp int; +precision highp sampler2D; + +// scene.Uniforms, 144 bytes, std140 in this field order. The backend writes +// it once per frame. The per-draw fields (clip_rect, cell_px, color) are +// read from the plain uniforms below, so a draw sets three values and does +// not rewrite the block. +layout(std140) uniform U { + mat4 mvp; + vec2 px_to_clip; + float size_scale; + float zoom; // fractional zoom * 256 + float zoom_t; + float world_per_px; + float rot_sin; + float rot_cos; + vec4 color; + vec2 anchor_px; + vec2 cell_px; + vec4 clip_rect; +} u; + +uniform vec4 u_clip; // Uniforms.clip_rect of this draw +uniform vec2 u_cell; // Uniforms.cell_px of this draw +uniform vec4 u_halo; // Uniforms.color of this draw (the SDF halo) +// The target height in px. GL puts the origin of gl_FragCoord at the bottom +// row; the other backends put it at the top. The pattern phase flips y with +// this, so a pattern cell lands on the same pixels everywhere. +uniform float u_fb_h; diff --git a/shaders/gles/sdf.frag b/shaders/gles/sdf.frag new file mode 100644 index 0000000..d145b14 --- /dev/null +++ b/shaders/gles/sdf.frag @@ -0,0 +1,26 @@ +// SDF text with an optional halo in the color of the draw (u_halo). A port of +// shaders/vk/sdf.frag. prelude.glsl comes first. +uniform sampler2D atlas; + +in vec2 v_uv; +in vec4 v_color; +in float v_weight; +layout(location = 0) out vec4 o_color; + +const float SDF_EDGE = 191.0 / 255.0; + +void main() { + float d = texture(atlas, v_uv).r; + float w = fwidth(d); + float a = smoothstep(SDF_EDGE - w, SDF_EDGE + w, d); + if (v_weight > 0.0) { + float halo_a = smoothstep(SDF_EDGE - v_weight - w, SDF_EDGE - v_weight + w, d); + float cov = max(a, halo_a); + if (cov <= 0.0) discard; + vec3 col = mix(u_halo.rgb, v_color.rgb, a); + o_color = vec4(col, cov * v_color.a); + return; + } + if (a <= 0.0) discard; + o_color = vec4(v_color.rgb, v_color.a * a); +} diff --git a/shaders/gles/sprite.frag b/shaders/gles/sprite.frag new file mode 100644 index 0000000..69c3f37 --- /dev/null +++ b/shaders/gles/sprite.frag @@ -0,0 +1,14 @@ +// The atlas texel modulated by the paint stream. A port of +// shaders/vk/sprite.frag. prelude.glsl comes first. +uniform sampler2D atlas; + +in vec2 v_uv; +in vec4 v_color; +in float v_weight; +layout(location = 0) out vec4 o_color; + +void main() { + vec4 c = texture(atlas, v_uv) * v_color; + if (c.a < (1.0 / 255.0)) discard; + o_color = c; +} diff --git a/shaders/gles/sprite.vert b/shaders/gles/sprite.vert new file mode 100644 index 0000000..f9d92ff --- /dev/null +++ b/shaders/gles/sprite.vert @@ -0,0 +1,42 @@ +// Textured-quad vertex shader: sprite symbols, SDF text, and raster tiles. A +// port of shaders/vk/sprite.vert. prelude.glsl comes first. +layout(location = 0) in vec2 a_pos; +layout(location = 1) in vec2 a_off; +layout(location = 2) in vec2 a_uv; +layout(location = 3) in float a_weight; +layout(location = 4) in uint a_zwin; +layout(location = 5) in uint a_pack; +layout(location = 6) in float a_depth; +layout(location = 7) in vec4 a_color; +layout(location = 8) in vec4 a_color_hi; + +out vec2 v_uv; +out vec4 v_color; +out float v_weight; + +void main() { + uint flags = a_pack & 0xFFu; + bool flip = ((a_pack >> 8) & 0xFFu) != 0u; + float tangent = float((a_pack >> 16) & 0xFFu) / 256.0 * 6.2831853071795864; + + vec4 clip = u.mvp * vec4(a_pos, 0.0, 1.0); + + vec2 off = a_off; + if (flip && (cos(tangent) * u.rot_cos - sin(tangent) * u.rot_sin) < 0.0) { + off = -off; + } + if ((flags & 1u) != 0u) { + off = vec2(off.x * u.rot_cos - off.y * u.rot_sin, + off.x * u.rot_sin + off.y * u.rot_cos); + } + clip.xy += off * u.px_to_clip * u.size_scale * clip.w; + clip.z = a_depth * clip.w; + + float zmin = float(a_zwin & 0xFFFFu); + float zmax = float(a_zwin >> 16); + bool vis = zmin <= u.zoom && u.zoom <= zmax; + gl_Position = vis ? clip : vec4(0.0, 0.0, 2.0, 1.0); + v_uv = a_uv; + v_color = mix(a_color, a_color_hi, clamp(u.zoom_t, 0.0, 1.0)); + v_weight = a_weight; +} diff --git a/src/capi.zig b/src/capi.zig index 767a26d..efc7437 100644 --- a/src/capi.zig +++ b/src/capi.zig @@ -81,6 +81,14 @@ pub const NativeKind = enum(c_int) { android_window = 7, // ANativeWindow* (vk backend) wayland_surface = 8, // charttable_wayland_surface* (vk backend) d3d12_panel = 10, // no handle (d3d12 backend); see charttable_d3d12_swapchain + gles_context = 11, // charttable_gles_context* (gles backend) +}; + +/// `charttable_gles_target`: a framebuffer of the host's current GL context. +pub const GlesTarget = extern struct { + framebuffer: u32, + width: u32, + height: u32, }; pub const Options = extern struct { @@ -288,12 +296,15 @@ export fn charttable_attach_surface( const self = locked(h) orelse return ERR_HANDLE; defer self.mu.unlock(); if (w_px == 0 or h_px == 0) return ERR_ARG; + // A kind this backend does not know is refused here. @enumFromInt on it + // would be undefined behaviour. + const native_kind = std.enums.fromInt(gpu.NativeKind, kind) orelse return ERR_UNSUPPORTED; if (self.g) |*g| g.deinit(); self.g = gpu.Gpu.init(.{ .width = w_px, .height = h_px, .native_handle = native, - .native_kind = @enumFromInt(kind), + .native_kind = native_kind, }) catch { self.g = null; return ERR_SURFACE; @@ -991,6 +1002,32 @@ export fn charttable_render(h: ?*anyopaque) callconv(.c) c_int { return if (drew) 1 else 0; } +/// Draw a frame into a framebuffer of the host's OpenGL ES context, which +/// must be current on this thread. Only for a surface attached with kind +/// gles_context; every other backend and kind returns ERR_UNSUPPORTED. The +/// GL state the call changes is restored before it returns. +export fn charttable_render_gles(h: ?*anyopaque, target: ?*const GlesTarget) callconv(.c) c_int { + const self = locked(h) orelse return ERR_HANDLE; + defer self.mu.unlock(); + const t = target orelse return ERR_ARG; + if (t.width == 0 or t.height == 0) return ERR_ARG; + const g = if (self.g) |*g| g else return ERR_SURFACE; + if (comptime !@hasDecl(gpu.Gpu, "renderFramebuffer")) { + return ERR_UNSUPPORTED; + } else { + // A snapshot-only surface has its own context, not the host's. + if (g.egl != null) return ERR_UNSUPPORTED; + _ = self.m.update() catch return ERR_MEMORY; + collectMissing(self); + pumpResources(self); + syncAtlases(self); + _ = self.m.uploadIfChanged(g, &self.uploaded) catch return ERR_MEMORY; + const drew = g.renderFramebuffer(self.m.uniforms(), t.framebuffer, t.width, t.height); + if (drew) self.m.markDrawn(); + return if (drew) 1 else 0; + } +} + /// Render offscreen and copy RGBA8 (top-down, w*h*4) into `dst`. export fn charttable_snapshot_rgba(h: ?*anyopaque, dst: [*]u8, len: usize) callconv(.c) c_int { const self = locked(h) orelse return ERR_HANDLE; @@ -1291,6 +1328,55 @@ test "capi: a loaded sprite and glyph atlas actually reach the surface" { try testing.expect(dark > 500); } +test "capi: an OpenGL ES host context draws through charttable_render_gles" { + const h = charttable_open(&.{ .workers = 1 }) orelse return error.OpenFailed; + defer charttable_close(h); + try testing.expectEqual(OK, charttable_set_style_json(h, smoke_style.ptr, smoke_style.len)); + const target = GlesTarget{ .framebuffer = 0, .width = 64, .height = 32 }; + if (comptime !@import("ct_build").gpu_gles) { + // Every other backend refuses the kind and the call. + var dummy: u8 = 0; + try testing.expectEqual(ERR_UNSUPPORTED, charttable_attach_surface(h, @intFromEnum(NativeKind.gles_context), &dummy, 64, 32)); + try testing.expectEqual(ERR_SURFACE, charttable_render_gles(h, &target)); + } else { + const host = gpu.gles.TestHost.open(64, 32) catch return error.SkipZigTest; + defer host.close(); + var ctx = gpu.gles.GlesContext{ .get_proc_address = gpu.gles.TestHost.getProc, .user = host }; + try testing.expectEqual(OK, charttable_attach_surface(h, @intFromEnum(NativeKind.gles_context), &ctx, 64, 32)); + defer charttable_detach_surface(h); + try testing.expectEqual(OK, charttable_resize(h, 64, 32)); + try testing.expectEqual(ERR_ARG, charttable_render_gles(h, null)); + + var spins: usize = 0; + while (spins < 200 and charttable_idle(h) == 0) : (spins += 1) { + _ = charttable_tick(h, 16); + @import("util/lock.zig").sleepMs(1); + } + // The host left its own content in the framebuffer. + host.clearTo(0, 1, 0); + const bound = host.boundFramebuffer(); + const t = GlesTarget{ .framebuffer = host.fbo, .width = 64, .height = 32 }; + try testing.expectEqual(@as(c_int, 1), charttable_render_gles(h, &t)); + // charttable cleared it to the scene's background, and the binding + // the host had is the binding it gets back. + const bg = handle(h).?.g.?.clear; + const want = [4]u8{ + @intFromFloat(@round(bg.r * 255)), @intFromFloat(@round(bg.g * 255)), + @intFromFloat(@round(bg.b * 255)), @intFromFloat(@round(bg.a * 255)), + }; + try testing.expectEqual(want, host.pixel(10, 10)); + try testing.expectEqual(bound, host.boundFramebuffer()); + + // A snapshot on the host's context draws into a framebuffer of its + // own and leaves the host's alone. + host.clearTo(0, 1, 0); + var snap: [64 * 32 * 4]u8 = undefined; + try testing.expectEqual(OK, charttable_snapshot_rgba(h, &snap, snap.len)); + try testing.expectEqualSlices(u8, &want, snap[0..4]); + try testing.expectEqual([4]u8{ 0, 255, 0, 255 }, host.pixel(10, 10)); + } +} + test "capi: a bad style is refused and the old one stands" { const h = charttable_open(null) orelse return error.OpenFailed; defer charttable_close(h); diff --git a/src/gpu/gpu.zig b/src/gpu/gpu.zig index 22088bb..05079e7 100644 --- a/src/gpu/gpu.zig +++ b/src/gpu/gpu.zig @@ -5,13 +5,17 @@ //! * Windows -> gpu_d3d12.zig (Direct3D 12) //! * Linux / Android -> gpu_vk.zig (raw Vulkan) //! * freestanding / wasi -> gpu_none.zig (stub) +//! * `-Dgpu=gles`, off Apple -> gpu_gles.zig (OpenGL ES 3.0) //! The target OS decides, except on Windows, where `-Dgpu=vk` selects the -//! Vulkan backend instead (it carries a win32 surface path). All backends +//! Vulkan backend instead (it carries a win32 surface path), and wherever +//! `-Dgpu=gles` selects the OpenGL ES backend. All backends //! expose: Gpu (+ its Scene/SceneData), Uniforms, Options, NativeKind, Color. const builtin = @import("builtin"); const ct_build = @import("ct_build"); -const impl = if (builtin.os.tag == .windows and ct_build.gpu_d3d12) +const impl = if (ct_build.gpu_gles) + @import("gpu_gles.zig") +else if (builtin.os.tag == .windows and ct_build.gpu_d3d12) @import("gpu_d3d12.zig") else switch (builtin.os.tag) { .macos, .ios, .visionos => @import("gpu_metal.zig"), @@ -28,6 +32,9 @@ pub const NativeKind = impl.NativeKind; pub const Color = impl.Color; /// Whether the selected backend draws at all. False only for gpu_none.zig. pub const renders = impl.renders; +/// The OpenGL ES backend's own names (GlesContext, TestHost), in a build +/// with `-Dgpu=gles` only. +pub const gles = if (ct_build.gpu_gles) impl else void; test { _ = impl; diff --git a/src/gpu/gpu_gles.zig b/src/gpu/gpu_gles.zig new file mode 100644 index 0000000..05aca6e --- /dev/null +++ b/src/gpu/gpu_gles.zig @@ -0,0 +1,1500 @@ +//! OpenGL ES 3.0 backend: the pipelines, the scene's buffers, and a frame +//! rendered into a framebuffer of the host's GL context, or offscreen for a +//! snapshot. Selected by gpu.zig when the build passes `-Dgpu=gles`. It keeps +//! the scene contract of gpu_vk.zig: the same vertex streams, the same blend +//! state, the same draw order, and the same batcher. +//! +//! Two ways to get a context: +//! * NativeKind.gles_context: the host owns a context and makes it current +//! before each call that draws or uploads. charttable loads every entry +//! point through the host's `get_proc_address`, so the library links no +//! GL library. It creates no surface and never swaps buffers. +//! * NativeKind.none: a snapshot-only Gpu. The backend opens libEGL at run +//! time and makes its own headless context (surfaceless, or a 1x1 +//! pbuffer). This is the path the tests take. +//! +//! The GL state contract. Every call that issues GL commands saves the state +//! it changes and restores it before it returns. The list is `Saved` below: +//! the framebuffer bindings, the viewport, the enables, the blend state, the +//! color mask, the clear color, the program, the vertex array, the buffer +//! bindings, the texture and sampler of unit 0, and the pack and unpack +//! state. A host that shares its context with charttable gets that state +//! back. +//! +//! Differences from the Vulkan backend, and why: +//! * No depth buffer. In the Vulkan backend no pipeline writes depth, so the +//! depth test there only refuses depth 1.0, which no range uses. Without +//! it, the backend draws into any host framebuffer, with or without a +//! depth attachment. +//! * The frame's Uniforms go into one uniform buffer per frame. The three +//! fields that change per draw (clip_rect, cell_px, color) are plain +//! uniforms (shaders/gles/prelude.glsl). +//! * makeScene copies the scene to CPU memory and creates no GL object. A +//! context is current on one thread only, and makeScene runs on the build +//! worker. adoptScene, on the owner thread, makes the buffers. +//! * GL counts window y from the bottom row. The NDC is the same as Metal's, +//! so the picture needs no flip on screen. A snapshot flips the rows when +//! it reads them back, and the pattern shader flips gl_FragCoord.y. +const std = @import("std"); +const builtin = @import("builtin"); +const scene = @import("../scene/types.zig"); +const batch = @import("../scene/batch.zig"); +const png = @import("../util/png.zig"); + +pub const Uniforms = scene.Uniforms; + +/// RGBA colour 0..1. +pub const Color = extern struct { r: f32, g: f32, b: f32, a: f32 }; + +/// This backend draws. Whether a context is actually there stays Gpu.init's +/// answer to give. +pub const renders = true; + +/// How to interpret Options.native_handle. The values are the C ABI's +/// (CHARTTABLE_NATIVE_*), so capi converts with no table. +pub const NativeKind = enum(c_int) { + none = 0, // snapshot only: the backend makes its own headless context + gles_context = 11, // *const GlesContext: the host's current context +}; + +/// The host's entry point loader, as `charttable_gles_get_proc` declares it. +pub const GetProcFn = *const fn (name: [*:0]const u8, user: ?*anyopaque) callconv(.c) ?*anyopaque; + +/// `charttable_gles_context`: how charttable finds the host's GL functions. +pub const GlesContext = extern struct { + get_proc_address: ?GetProcFn, + user: ?*anyopaque, +}; + +pub const Options = struct { + width: u32, + height: u32, + want_msaa: bool = false, + native_handle: ?*anyopaque = null, + native_kind: NativeKind = .none, +}; + +// ---- the GL entry points, hand-declared ----------------------------------- +// +// The values and signatures are the frozen ones of the OpenGL ES 3.0 +// registry. Declaring them here keeps the build free of GL headers and +// libraries: every function is loaded by name at init. + +const cc: std.builtin.CallingConvention = if (builtin.os.tag == .windows) .winapi else .c; + +const GL_NO_ERROR: u32 = 0; +const GL_TRIANGLES: u32 = 0x0004; +const GL_ONE: u32 = 1; +const GL_SRC_ALPHA: u32 = 0x0302; +const GL_ONE_MINUS_SRC_ALPHA: u32 = 0x0303; +const GL_FUNC_ADD: u32 = 0x8006; +const GL_UNSIGNED_BYTE: u32 = 0x1401; +const GL_UNSIGNED_INT: u32 = 0x1405; +const GL_FLOAT: u32 = 0x1406; +const GL_RGBA: u32 = 0x1908; +const GL_RGBA8: u32 = 0x8058; +const GL_VERSION: u32 = 0x1F02; +const GL_RENDERER: u32 = 0x1F01; +const GL_TEXTURE_2D: u32 = 0x0DE1; +const GL_TEXTURE0: u32 = 0x84C0; +const GL_TEXTURE_MAG_FILTER: u32 = 0x2800; +const GL_TEXTURE_MIN_FILTER: u32 = 0x2801; +const GL_TEXTURE_WRAP_S: u32 = 0x2802; +const GL_TEXTURE_WRAP_T: u32 = 0x2803; +const GL_LINEAR: i32 = 0x2601; +const GL_CLAMP_TO_EDGE: i32 = 0x812F; +const GL_ARRAY_BUFFER: u32 = 0x8892; +const GL_ELEMENT_ARRAY_BUFFER: u32 = 0x8893; +const GL_UNIFORM_BUFFER: u32 = 0x8A11; +const GL_PIXEL_PACK_BUFFER: u32 = 0x88EB; +const GL_PIXEL_UNPACK_BUFFER: u32 = 0x88EC; +const GL_STATIC_DRAW: u32 = 0x88E4; +const GL_DYNAMIC_DRAW: u32 = 0x88E8; +const GL_STREAM_DRAW: u32 = 0x88E0; +const GL_VERTEX_SHADER: u32 = 0x8B31; +const GL_FRAGMENT_SHADER: u32 = 0x8B30; +const GL_COMPILE_STATUS: u32 = 0x8B81; +const GL_LINK_STATUS: u32 = 0x8B82; +const GL_INFO_LOG_LENGTH: u32 = 0x8B84; +const GL_INVALID_INDEX: u32 = 0xFFFF_FFFF; +const GL_FRAMEBUFFER: u32 = 0x8D40; +const GL_READ_FRAMEBUFFER: u32 = 0x8CA8; +const GL_DRAW_FRAMEBUFFER: u32 = 0x8CA9; +const GL_RENDERBUFFER: u32 = 0x8D41; +const GL_COLOR_ATTACHMENT0: u32 = 0x8CE0; +const GL_FRAMEBUFFER_COMPLETE: u32 = 0x8CD5; +const GL_COLOR_BUFFER_BIT: u32 = 0x4000; + +// glGet names, for the state `Saved` keeps. +const GL_VIEWPORT: u32 = 0x0BA2; +const GL_COLOR_WRITEMASK: u32 = 0x0C23; +const GL_COLOR_CLEAR_VALUE: u32 = 0x0C22; +const GL_BLEND_SRC_RGB: u32 = 0x80C9; +const GL_BLEND_DST_RGB: u32 = 0x80C8; +const GL_BLEND_SRC_ALPHA: u32 = 0x80CB; +const GL_BLEND_DST_ALPHA: u32 = 0x80CA; +const GL_BLEND_EQUATION_RGB: u32 = 0x8009; +const GL_BLEND_EQUATION_ALPHA: u32 = 0x883D; +const GL_DRAW_FRAMEBUFFER_BINDING: u32 = 0x8CA6; +const GL_READ_FRAMEBUFFER_BINDING: u32 = 0x8CAA; +const GL_RENDERBUFFER_BINDING: u32 = 0x8CA7; +const GL_CURRENT_PROGRAM: u32 = 0x8B8D; +const GL_VERTEX_ARRAY_BINDING: u32 = 0x85B5; +const GL_ARRAY_BUFFER_BINDING: u32 = 0x8894; +const GL_UNIFORM_BUFFER_BINDING: u32 = 0x8A28; +const GL_UNIFORM_BUFFER_START: u32 = 0x8A29; +const GL_UNIFORM_BUFFER_SIZE: u32 = 0x8A2A; +const GL_PIXEL_PACK_BUFFER_BINDING: u32 = 0x88ED; +const GL_PIXEL_UNPACK_BUFFER_BINDING: u32 = 0x88EF; +const GL_ACTIVE_TEXTURE: u32 = 0x84E0; +const GL_TEXTURE_BINDING_2D: u32 = 0x8069; +const GL_SAMPLER_BINDING: u32 = 0x8919; +const GL_UNPACK_ROW_LENGTH: u32 = 0x0CF2; +const GL_UNPACK_SKIP_ROWS: u32 = 0x0CF3; +const GL_UNPACK_SKIP_PIXELS: u32 = 0x0CF4; +const GL_UNPACK_ALIGNMENT: u32 = 0x0CF5; +const GL_UNPACK_IMAGE_HEIGHT: u32 = 0x806E; +const GL_UNPACK_SKIP_IMAGES: u32 = 0x806D; +const GL_PACK_ROW_LENGTH: u32 = 0x0D02; +const GL_PACK_SKIP_ROWS: u32 = 0x0D03; +const GL_PACK_SKIP_PIXELS: u32 = 0x0D04; +const GL_PACK_ALIGNMENT: u32 = 0x0D05; + +/// The capabilities a frame turns off (all but BLEND, which it turns on). +const caps = [_]u32{ + 0x0BE2, // GL_BLEND + 0x0B71, // GL_DEPTH_TEST + 0x0B90, // GL_STENCIL_TEST + 0x0C11, // GL_SCISSOR_TEST + 0x0B44, // GL_CULL_FACE + 0x8C89, // GL_RASTERIZER_DISCARD + 0x809E, // GL_SAMPLE_ALPHA_TO_COVERAGE + 0x8037, // GL_POLYGON_OFFSET_FILL +}; +const GL_BLEND = caps[0]; + +/// The pixel-store parameters an upload or a readback sets to their defaults. +const pixel_store = [_]struct { name: u32, value: i32 }{ + .{ .name = GL_UNPACK_ROW_LENGTH, .value = 0 }, + .{ .name = GL_UNPACK_SKIP_ROWS, .value = 0 }, + .{ .name = GL_UNPACK_SKIP_PIXELS, .value = 0 }, + .{ .name = GL_UNPACK_ALIGNMENT, .value = 4 }, + .{ .name = GL_UNPACK_IMAGE_HEIGHT, .value = 0 }, + .{ .name = GL_UNPACK_SKIP_IMAGES, .value = 0 }, + .{ .name = GL_PACK_ROW_LENGTH, .value = 0 }, + .{ .name = GL_PACK_SKIP_ROWS, .value = 0 }, + .{ .name = GL_PACK_SKIP_PIXELS, .value = 0 }, + .{ .name = GL_PACK_ALIGNMENT, .value = 4 }, +}; + +/// Every function the backend calls. The field name is the GL name without +/// its `gl` prefix; `load` adds it back. +const Fns = struct { + GetError: *const fn () callconv(cc) u32, + GetString: *const fn (name: u32) callconv(cc) ?[*:0]const u8, + GetIntegerv: *const fn (name: u32, data: [*]i32) callconv(cc) void, + GetInteger64i_v: *const fn (target: u32, index: u32, data: [*]i64) callconv(cc) void, + GetBooleanv: *const fn (name: u32, data: [*]u8) callconv(cc) void, + GetFloatv: *const fn (name: u32, data: [*]f32) callconv(cc) void, + IsEnabled: *const fn (cap: u32) callconv(cc) u8, + Enable: *const fn (cap: u32) callconv(cc) void, + Disable: *const fn (cap: u32) callconv(cc) void, + BlendFuncSeparate: *const fn (sr: u32, dr: u32, sa: u32, da: u32) callconv(cc) void, + BlendEquationSeparate: *const fn (rgb: u32, a: u32) callconv(cc) void, + ColorMask: *const fn (r: u8, g: u8, b: u8, a: u8) callconv(cc) void, + Viewport: *const fn (x: i32, y: i32, w: i32, h: i32) callconv(cc) void, + ClearColor: *const fn (r: f32, g: f32, b: f32, a: f32) callconv(cc) void, + Clear: *const fn (mask: u32) callconv(cc) void, + PixelStorei: *const fn (name: u32, v: i32) callconv(cc) void, + + CreateShader: *const fn (kind: u32) callconv(cc) u32, + ShaderSource: *const fn (sh: u32, n: i32, src: [*]const [*]const u8, len: ?[*]const i32) callconv(cc) void, + CompileShader: *const fn (sh: u32) callconv(cc) void, + GetShaderiv: *const fn (sh: u32, name: u32, out: *i32) callconv(cc) void, + GetShaderInfoLog: *const fn (sh: u32, cap: i32, len: ?*i32, log: [*]u8) callconv(cc) void, + DeleteShader: *const fn (sh: u32) callconv(cc) void, + CreateProgram: *const fn () callconv(cc) u32, + AttachShader: *const fn (p: u32, sh: u32) callconv(cc) void, + LinkProgram: *const fn (p: u32) callconv(cc) void, + GetProgramiv: *const fn (p: u32, name: u32, out: *i32) callconv(cc) void, + GetProgramInfoLog: *const fn (p: u32, cap: i32, len: ?*i32, log: [*]u8) callconv(cc) void, + DeleteProgram: *const fn (p: u32) callconv(cc) void, + UseProgram: *const fn (p: u32) callconv(cc) void, + GetUniformBlockIndex: *const fn (p: u32, name: [*:0]const u8) callconv(cc) u32, + UniformBlockBinding: *const fn (p: u32, block: u32, binding: u32) callconv(cc) void, + GetUniformLocation: *const fn (p: u32, name: [*:0]const u8) callconv(cc) i32, + Uniform1i: *const fn (loc: i32, v: i32) callconv(cc) void, + Uniform1f: *const fn (loc: i32, v: f32) callconv(cc) void, + Uniform2f: *const fn (loc: i32, x: f32, y: f32) callconv(cc) void, + Uniform4f: *const fn (loc: i32, x: f32, y: f32, z: f32, w: f32) callconv(cc) void, + + GenBuffers: *const fn (n: i32, out: [*]u32) callconv(cc) void, + DeleteBuffers: *const fn (n: i32, ids: [*]const u32) callconv(cc) void, + BindBuffer: *const fn (target: u32, id: u32) callconv(cc) void, + BindBufferBase: *const fn (target: u32, index: u32, id: u32) callconv(cc) void, + BindBufferRange: *const fn (target: u32, index: u32, id: u32, off: isize, size: isize) callconv(cc) void, + BufferData: *const fn (target: u32, size: isize, data: ?*const anyopaque, usage: u32) callconv(cc) void, + BufferSubData: *const fn (target: u32, off: isize, size: isize, data: *const anyopaque) callconv(cc) void, + GenVertexArrays: *const fn (n: i32, out: [*]u32) callconv(cc) void, + DeleteVertexArrays: *const fn (n: i32, ids: [*]const u32) callconv(cc) void, + BindVertexArray: *const fn (id: u32) callconv(cc) void, + EnableVertexAttribArray: *const fn (loc: u32) callconv(cc) void, + VertexAttribPointer: *const fn (loc: u32, n: i32, kind: u32, norm: u8, stride: i32, off: ?*const anyopaque) callconv(cc) void, + VertexAttribIPointer: *const fn (loc: u32, n: i32, kind: u32, stride: i32, off: ?*const anyopaque) callconv(cc) void, + DrawArrays: *const fn (mode: u32, first: i32, count: i32) callconv(cc) void, + DrawElements: *const fn (mode: u32, count: i32, kind: u32, off: ?*const anyopaque) callconv(cc) void, + + GenTextures: *const fn (n: i32, out: [*]u32) callconv(cc) void, + DeleteTextures: *const fn (n: i32, ids: [*]const u32) callconv(cc) void, + BindTexture: *const fn (target: u32, id: u32) callconv(cc) void, + ActiveTexture: *const fn (unit: u32) callconv(cc) void, + BindSampler: *const fn (unit: u32, id: u32) callconv(cc) void, + TexParameteri: *const fn (target: u32, name: u32, v: i32) callconv(cc) void, + TexImage2D: *const fn (target: u32, level: i32, ifmt: i32, w: i32, h: i32, border: i32, fmt: u32, kind: u32, px: ?*const anyopaque) callconv(cc) void, + TexSubImage2D: *const fn (target: u32, level: i32, x: i32, y: i32, w: i32, h: i32, fmt: u32, kind: u32, px: *const anyopaque) callconv(cc) void, + + GenFramebuffers: *const fn (n: i32, out: [*]u32) callconv(cc) void, + DeleteFramebuffers: *const fn (n: i32, ids: [*]const u32) callconv(cc) void, + BindFramebuffer: *const fn (target: u32, id: u32) callconv(cc) void, + FramebufferRenderbuffer: *const fn (target: u32, att: u32, rtarget: u32, rb: u32) callconv(cc) void, + CheckFramebufferStatus: *const fn (target: u32) callconv(cc) u32, + GenRenderbuffers: *const fn (n: i32, out: [*]u32) callconv(cc) void, + DeleteRenderbuffers: *const fn (n: i32, ids: [*]const u32) callconv(cc) void, + BindRenderbuffer: *const fn (target: u32, id: u32) callconv(cc) void, + RenderbufferStorage: *const fn (target: u32, fmt: u32, w: i32, h: i32) callconv(cc) void, + ReadPixels: *const fn (x: i32, y: i32, w: i32, h: i32, fmt: u32, kind: u32, px: *anyopaque) callconv(cc) void, +}; + +/// Load every entry point of `Fns` through `loader.proc(name)`. A missing one +/// fails init with its name in the log, not with a crash at the first draw. +fn loadFns(loader: anytype) error{MissingEntryPoint}!Fns { + var f: Fns = undefined; + inline for (@typeInfo(Fns).@"struct".fields) |fld| { + const name: [*:0]const u8 = "gl" ++ fld.name; + const p = loader.proc(name) orelse { + std.debug.print("gles: no entry point {s}\n", .{name}); + return error.MissingEntryPoint; + }; + @field(f, fld.name) = @ptrCast(@alignCast(p)); + } + return f; +} + +const HostLoader = struct { + get: GetProcFn, + user: ?*anyopaque, + fn proc(self: HostLoader, name: [*:0]const u8) ?*anyopaque { + return self.get(name, self.user); + } +}; + +// ---- the headless context for snapshot-only use -------------------------- + +/// The standard library opens no shared library on Windows. A Windows host +/// gives its own context (an ANGLE one, say), and a snapshot-only Gpu there +/// fails init. +const DynLib = if (builtin.os.tag == .windows) struct { + fn open(path: []const u8) error{Unsupported}!@This() { + _ = path; + return error.Unsupported; + } + fn close(self: *@This()) void { + _ = self; + } + fn lookup(self: *@This(), comptime T: type, name: [:0]const u8) ?T { + _ = self; + _ = name; + return null; + } +} else std.DynLib; + +/// A context of our own, from libEGL opened at run time. It exists only for a +/// Gpu with no host context (NativeKind.none): a snapshot, or a test. Nothing +/// links against EGL, so a host that gives its own context never loads it. +const Egl = struct { + const egl_names: []const [:0]const u8 = switch (builtin.os.tag) { + .windows => &.{"libEGL.dll"}, + else => if (builtin.abi == .android) &.{"libEGL.so"} else &.{ "libEGL.so.1", "libEGL.so" }, + }; + const gles_names: []const [:0]const u8 = switch (builtin.os.tag) { + .windows => &.{"libGLESv2.dll"}, + else => if (builtin.abi == .android) &.{"libGLESv2.so"} else &.{ "libGLESv2.so.2", "libGLESv2.so" }, + }; + + const EGL_NONE: i32 = 0x3038; + const EGL_RENDERABLE_TYPE: i32 = 0x3040; + const EGL_OPENGL_ES3_BIT: i32 = 0x0040; + const EGL_SURFACE_TYPE: i32 = 0x3033; + const EGL_PBUFFER_BIT: i32 = 0x0001; + const EGL_RED_SIZE: i32 = 0x3024; + const EGL_GREEN_SIZE: i32 = 0x3023; + const EGL_BLUE_SIZE: i32 = 0x3022; + const EGL_ALPHA_SIZE: i32 = 0x3021; + const EGL_WIDTH: i32 = 0x3057; + const EGL_HEIGHT: i32 = 0x3056; + const EGL_CONTEXT_CLIENT_VERSION: i32 = 0x3098; + const EGL_OPENGL_ES_API: u32 = 0x30A0; + const EGL_PLATFORM_SURFACELESS_MESA: u32 = 0x31DD; + + const Ptr = ?*anyopaque; + const GetProcAddress = *const fn (name: [*:0]const u8) callconv(cc) Ptr; + const GetDisplay = *const fn (native: Ptr) callconv(cc) Ptr; + const GetPlatformDisplay = *const fn (platform: u32, native: Ptr, attrs: ?[*]const i32) callconv(cc) Ptr; + const Initialize = *const fn (dpy: Ptr, major: ?*i32, minor: ?*i32) callconv(cc) u32; + const BindAPI = *const fn (api: u32) callconv(cc) u32; + const ChooseConfig = *const fn (dpy: Ptr, attrs: [*]const i32, out: *Ptr, cap: i32, n: *i32) callconv(cc) u32; + const CreateContext = *const fn (dpy: Ptr, cfg: Ptr, share: Ptr, attrs: [*]const i32) callconv(cc) Ptr; + const CreatePbufferSurface = *const fn (dpy: Ptr, cfg: Ptr, attrs: [*]const i32) callconv(cc) Ptr; + const MakeCurrent = *const fn (dpy: Ptr, draw: Ptr, read: Ptr, ctx: Ptr) callconv(cc) u32; + const DestroyContext = *const fn (dpy: Ptr, ctx: Ptr) callconv(cc) u32; + const DestroySurface = *const fn (dpy: Ptr, surf: Ptr) callconv(cc) u32; + + lib: DynLib, + gles: ?DynLib, + get_proc: GetProcAddress, + make_current: MakeCurrent, + destroy_context: DestroyContext, + destroy_surface: DestroySurface, + dpy: Ptr = null, + ctx: Ptr = null, + surf: Ptr = null, + + fn openFirst(names: []const [:0]const u8) ?DynLib { + for (names) |n| { + if (DynLib.open(n)) |l| return l else |_| {} + } + return null; + } + + fn open() !Egl { + var lib = openFirst(egl_names) orelse return error.NoEgl; + errdefer lib.close(); + var e = Egl{ + .lib = lib, + .gles = openFirst(gles_names), + .get_proc = lib.lookup(GetProcAddress, "eglGetProcAddress") orelse return error.NoEgl, + .make_current = lib.lookup(MakeCurrent, "eglMakeCurrent") orelse return error.NoEgl, + .destroy_context = lib.lookup(DestroyContext, "eglDestroyContext") orelse return error.NoEgl, + .destroy_surface = lib.lookup(DestroySurface, "eglDestroySurface") orelse return error.NoEgl, + }; + errdefer if (e.gles) |*g| g.close(); + const get_display = lib.lookup(GetDisplay, "eglGetDisplay") orelse return error.NoEgl; + const initialize = lib.lookup(Initialize, "eglInitialize") orelse return error.NoEgl; + const bind_api = lib.lookup(BindAPI, "eglBindAPI") orelse return error.NoEgl; + const choose = lib.lookup(ChooseConfig, "eglChooseConfig") orelse return error.NoEgl; + const create_ctx = lib.lookup(CreateContext, "eglCreateContext") orelse return error.NoEgl; + const create_pb = lib.lookup(CreatePbufferSurface, "eglCreatePbufferSurface") orelse return error.NoEgl; + + // Mesa's surfaceless platform needs no window system, which is what a + // headless test machine has. Any other EGL takes the default display. + if (e.get_proc("eglGetPlatformDisplayEXT")) |raw| { + const gpd: GetPlatformDisplay = @ptrCast(@alignCast(raw)); + const d = gpd(EGL_PLATFORM_SURFACELESS_MESA, null, null); + if (d != null and initialize(d, null, null) != 0) e.dpy = d; + } + if (e.dpy == null) { + const d = get_display(null); + if (d == null or initialize(d, null, null) == 0) return error.NoEglDisplay; + e.dpy = d; + } + if (bind_api(EGL_OPENGL_ES_API) == 0) return error.NoGles; + + const rgba = [_]i32{ EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8 }; + const with_pb = [_]i32{ EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT } ++ rgba ++ [_]i32{EGL_NONE}; + const any_surf = [_]i32{ EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT } ++ rgba ++ [_]i32{EGL_NONE}; + var cfg: Ptr = null; + var n: i32 = 0; + var pbuffer_ok = true; + if (choose(e.dpy, &with_pb, &cfg, 1, &n) == 0 or n == 0) { + pbuffer_ok = false; + if (choose(e.dpy, &any_surf, &cfg, 1, &n) == 0 or n == 0) return error.NoEglConfig; + } + const ctx_attrs = [_]i32{ EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE }; + e.ctx = create_ctx(e.dpy, cfg, null, &ctx_attrs); + if (e.ctx == null) return error.NoEglContext; + errdefer _ = e.destroy_context(e.dpy, e.ctx); + // A surfaceless context (EGL_KHR_surfaceless_context) first: the + // backend draws only into its own framebuffer object. + if (e.make_current(e.dpy, null, null, e.ctx) == 0) { + if (!pbuffer_ok) return error.NoEglSurface; + const pb_attrs = [_]i32{ EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE }; + e.surf = create_pb(e.dpy, cfg, &pb_attrs); + if (e.surf == null) return error.NoEglSurface; + if (e.make_current(e.dpy, e.surf, e.surf, e.ctx) == 0) { + _ = e.destroy_surface(e.dpy, e.surf); + return error.NoEglSurface; + } + } + return e; + } + + /// The core functions from libGLESv2 first: EGL before 1.5 need not + /// return core functions from eglGetProcAddress. + fn proc(self: *Egl, name: [*:0]const u8) ?*anyopaque { + if (self.gles) |*g| { + if (g.lookup(*anyopaque, std.mem.span(name))) |p| return p; + } + return self.get_proc(name); + } + + fn makeCurrent(self: *const Egl) void { + _ = self.make_current(self.dpy, self.surf, self.surf, self.ctx); + } + + /// The display stays initialized: eglTerminate would end every other + /// context on it in this process, and there can be several Gpus. + fn close(self: *Egl) void { + _ = self.make_current(self.dpy, null, null, null); + if (self.surf != null) _ = self.destroy_surface(self.dpy, self.surf); + _ = self.destroy_context(self.dpy, self.ctx); + if (self.gles) |*g| g.close(); + self.lib.close(); + } +}; + +/// A stand-in for a host in the tests of the C ABI (capi.zig): a headless +/// context, the loader a host would pass, and a framebuffer to draw into. +pub const TestHost = struct { + egl: Egl, + gl: Fns, + fbo: u32 = 0, + rb: u32 = 0, + + pub fn open(w: u32, h: u32) !*TestHost { + const self = try std.testing.allocator.create(TestHost); + errdefer std.testing.allocator.destroy(self); + self.egl = try Egl.open(); + errdefer self.egl.close(); + self.gl = try loadFns(&self.egl); + var id: [1]u32 = .{0}; + self.gl.GenRenderbuffers(1, &id); + self.rb = id[0]; + self.gl.BindRenderbuffer(GL_RENDERBUFFER, self.rb); + self.gl.RenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, @intCast(w), @intCast(h)); + self.gl.GenFramebuffers(1, &id); + self.fbo = id[0]; + self.gl.BindFramebuffer(GL_FRAMEBUFFER, self.fbo); + self.gl.FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, self.rb); + if (self.gl.CheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) return error.FramebufferIncomplete; + return self; + } + + pub fn getProc(name: [*:0]const u8, user: ?*anyopaque) callconv(.c) ?*anyopaque { + const self: *TestHost = @ptrCast(@alignCast(user.?)); + return self.egl.proc(name); + } + + /// The RGBA of one pixel of the framebuffer, x and y from the bottom left. + pub fn pixel(self: *TestHost, x: u32, y: u32) [4]u8 { + var px: [4]u8 = undefined; + self.gl.BindFramebuffer(GL_READ_FRAMEBUFFER, self.fbo); + self.gl.ReadPixels(@intCast(x), @intCast(y), 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, &px); + return px; + } + + /// Fill the framebuffer with one color, as a host's own drawing would. + pub fn clearTo(self: *TestHost, r: f32, g: f32, b: f32) void { + self.gl.BindFramebuffer(GL_FRAMEBUFFER, self.fbo); + self.gl.ClearColor(r, g, b, 1); + self.gl.Clear(GL_COLOR_BUFFER_BIT); + } + + /// The framebuffer the host has bound when it calls charttable. + pub fn boundFramebuffer(self: *TestHost) i32 { + return Saved.int(&self.gl, GL_DRAW_FRAMEBUFFER_BINDING); + } + + pub fn close(self: *TestHost) void { + self.egl.makeCurrent(); + self.gl.DeleteFramebuffers(1, &[1]u32{self.fbo}); + self.gl.DeleteRenderbuffers(1, &[1]u32{self.rb}); + self.egl.close(); + std.testing.allocator.destroy(self); + } +}; + +// ---- the GL state a call restores ----------------------------------------- + +/// The state a call changes, read before it starts and written back when it +/// ends. See the state contract in the header of this file. +const Saved = struct { + draw_fbo: i32, + read_fbo: i32, + renderbuffer: i32, + viewport: [4]i32, + enabled: [caps.len]u8, + blend: [6]i32, // src rgb, dst rgb, src a, dst a, eq rgb, eq a + color_mask: [4]u8, + clear_color: [4]f32, + program: i32, + vao: i32, + array_buffer: i32, + uniform_buffer: i32, + ubo0: i64, + ubo0_start: i64, + ubo0_size: i64, + pack_buffer: i32, + unpack_buffer: i32, + active_texture: i32, + texture0: i32, + sampler0: i32, + store: [pixel_store.len]i32, + + fn int(f: *const Fns, name: u32) i32 { + var v: [4]i32 = .{ 0, 0, 0, 0 }; + f.GetIntegerv(name, &v); + return v[0]; + } + + fn save(f: *const Fns) Saved { + var s: Saved = undefined; + s.draw_fbo = int(f, GL_DRAW_FRAMEBUFFER_BINDING); + s.read_fbo = int(f, GL_READ_FRAMEBUFFER_BINDING); + s.renderbuffer = int(f, GL_RENDERBUFFER_BINDING); + f.GetIntegerv(GL_VIEWPORT, &s.viewport); + for (caps, 0..) |c, i| s.enabled[i] = f.IsEnabled(c); + for ([_]u32{ GL_BLEND_SRC_RGB, GL_BLEND_DST_RGB, GL_BLEND_SRC_ALPHA, GL_BLEND_DST_ALPHA, GL_BLEND_EQUATION_RGB, GL_BLEND_EQUATION_ALPHA }, 0..) |n, i| + s.blend[i] = int(f, n); + f.GetBooleanv(GL_COLOR_WRITEMASK, &s.color_mask); + f.GetFloatv(GL_COLOR_CLEAR_VALUE, &s.clear_color); + s.program = int(f, GL_CURRENT_PROGRAM); + s.vao = int(f, GL_VERTEX_ARRAY_BINDING); + s.array_buffer = int(f, GL_ARRAY_BUFFER_BINDING); + s.uniform_buffer = int(f, GL_UNIFORM_BUFFER_BINDING); + var v: [1]i64 = .{0}; + f.GetInteger64i_v(GL_UNIFORM_BUFFER_BINDING, 0, &v); + s.ubo0 = v[0]; + f.GetInteger64i_v(GL_UNIFORM_BUFFER_START, 0, &v); + s.ubo0_start = v[0]; + f.GetInteger64i_v(GL_UNIFORM_BUFFER_SIZE, 0, &v); + s.ubo0_size = v[0]; + s.pack_buffer = int(f, GL_PIXEL_PACK_BUFFER_BINDING); + s.unpack_buffer = int(f, GL_PIXEL_UNPACK_BUFFER_BINDING); + s.active_texture = int(f, GL_ACTIVE_TEXTURE); + f.ActiveTexture(GL_TEXTURE0); + s.texture0 = int(f, GL_TEXTURE_BINDING_2D); + s.sampler0 = int(f, GL_SAMPLER_BINDING); + for (pixel_store, 0..) |p, i| s.store[i] = int(f, p.name); + + // The defaults every call relies on. A frame sets the rest itself. + f.BindVertexArray(0); + f.BindBuffer(GL_PIXEL_PACK_BUFFER, 0); + f.BindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); + f.BindSampler(0, 0); + for (pixel_store) |p| f.PixelStorei(p.name, p.value); + return s; + } + + fn restore(s: *const Saved, f: *const Fns) void { + f.BindFramebuffer(GL_DRAW_FRAMEBUFFER, @bitCast(s.draw_fbo)); + f.BindFramebuffer(GL_READ_FRAMEBUFFER, @bitCast(s.read_fbo)); + f.BindRenderbuffer(GL_RENDERBUFFER, @bitCast(s.renderbuffer)); + f.Viewport(s.viewport[0], s.viewport[1], s.viewport[2], s.viewport[3]); + for (caps, 0..) |c, i| if (s.enabled[i] != 0) f.Enable(c) else f.Disable(c); + f.BlendFuncSeparate(@bitCast(s.blend[0]), @bitCast(s.blend[1]), @bitCast(s.blend[2]), @bitCast(s.blend[3])); + f.BlendEquationSeparate(@bitCast(s.blend[4]), @bitCast(s.blend[5])); + f.ColorMask(s.color_mask[0], s.color_mask[1], s.color_mask[2], s.color_mask[3]); + f.ClearColor(s.clear_color[0], s.clear_color[1], s.clear_color[2], s.clear_color[3]); + f.UseProgram(@bitCast(s.program)); + f.BindVertexArray(@bitCast(s.vao)); + f.BindBuffer(GL_ARRAY_BUFFER, @bitCast(s.array_buffer)); + const ubo0: u32 = @intCast(s.ubo0); + if (ubo0 != 0 and s.ubo0_size > 0) + f.BindBufferRange(GL_UNIFORM_BUFFER, 0, ubo0, @intCast(s.ubo0_start), @intCast(s.ubo0_size)) + else + f.BindBufferBase(GL_UNIFORM_BUFFER, 0, ubo0); + // After the indexed binding, which also sets the generic one. + f.BindBuffer(GL_UNIFORM_BUFFER, @bitCast(s.uniform_buffer)); + f.BindBuffer(GL_PIXEL_PACK_BUFFER, @bitCast(s.pack_buffer)); + f.BindBuffer(GL_PIXEL_UNPACK_BUFFER, @bitCast(s.unpack_buffer)); + f.ActiveTexture(GL_TEXTURE0); + f.BindTexture(GL_TEXTURE_2D, @bitCast(s.texture0)); + f.BindSampler(0, @bitCast(s.sampler0)); + f.ActiveTexture(@bitCast(s.active_texture)); + for (pixel_store, 0..) |p, i| f.PixelStorei(p.name, s.store[i]); + } +}; + +// ---- the shaders ----------------------------------------------------------- + +const prelude_src = @embedFile("gles_prelude"); +const fill_vert_src = @embedFile("gles_fill_vert"); +const fill_frag_src = @embedFile("gles_fill_frag"); +const pattern_vert_src = @embedFile("gles_pattern_vert"); +const pattern_frag_src = @embedFile("gles_pattern_frag"); +const sprite_vert_src = @embedFile("gles_sprite_vert"); +const sprite_frag_src = @embedFile("gles_sprite_frag"); +const sdf_frag_src = @embedFile("gles_sdf_frag"); + +/// One linked program and the locations of its per-draw uniforms. A location +/// is -1 where the program does not use the uniform, and GL ignores a set +/// there. +const Prog = struct { + id: u32 = 0, + clip: i32 = -1, + cell: i32 = -1, + halo: i32 = -1, + fb_h: i32 = -1, +}; + +const Tex = struct { id: u32 = 0 }; +const PatternTex = struct { tex: ?Tex = null, w: f32 = 1, h: f32 = 1 }; + +pub const Gpu = struct { + gl: Fns, + /// Our own context, when the host gave none. + egl: ?Egl = null, + + width: u32, + height: u32, + host_pt_w: f32 = 0, + host_pt_h: f32 = 0, + pixel_density: f32 = 1.0, + host_density: f32 = 0, // host-declared scale; 0 = derive from the target + pattern_scale: f32 = 1, + + clear: Color = .{ .r = 0.576, .g = 0.682, .b = 0.733, .a = 1.0 }, + scene: ?Scene = null, + + fill: Prog = .{}, + pattern: Prog = .{}, + sprite: Prog = .{}, + sdf: Prog = .{}, + ubo: u32 = 0, + + sprite_tex: ?Tex = null, + sprite_w: u32 = 0, + sprite_h: u32 = 0, + glyph_tex: ?Tex = null, + glyph_bold_tex: ?Tex = null, + glyph_italic_tex: ?Tex = null, + + /// The snapshot target, made on the first renderOffscreen at this size. + off_fbo: u32 = 0, + off_rb: u32 = 0, + off_w: u32 = 0, + off_h: u32 = 0, + + pub fn init(opts: Options) !Gpu { + var egl: ?Egl = null; + const fns = switch (opts.native_kind) { + .gles_context => blk: { + const ctx: *const GlesContext = @ptrCast(@alignCast(opts.native_handle orelse return error.NoContext)); + const get = ctx.get_proc_address orelse return error.NoContext; + break :blk try loadFns(HostLoader{ .get = get, .user = ctx.user }); + }, + .none => blk: { + egl = try Egl.open(); + errdefer egl.?.close(); + break :blk try loadFns(&egl.?); + }, + }; + var g = Gpu{ .gl = fns, .egl = egl, .width = opts.width, .height = opts.height }; + errdefer g.deinit(); + + const ver = g.gl.GetString(GL_VERSION) orelse return error.NoContext; + const ren = g.gl.GetString(GL_RENDERER); + std.log.debug("gles: {s} ({s})", .{ ver, if (ren) |r| r else "?" }); + + const s = Saved.save(&g.gl); + defer s.restore(&g.gl); + g.fill = try g.buildProgram(fill_vert_src, fill_frag_src); + g.pattern = try g.buildProgram(pattern_vert_src, pattern_frag_src); + g.sprite = try g.buildProgram(sprite_vert_src, sprite_frag_src); + g.sdf = try g.buildProgram(sprite_vert_src, sdf_frag_src); + var b: [1]u32 = .{0}; + g.gl.GenBuffers(1, &b); + g.ubo = b[0]; + g.gl.BindBuffer(GL_UNIFORM_BUFFER, g.ubo); + g.gl.BufferData(GL_UNIFORM_BUFFER, @sizeOf(Uniforms), null, GL_STREAM_DRAW); + return g; + } + + /// Make our own context current. The host's is current already: making it + /// so is the host's half of the contract. + fn bind(self: *Gpu) void { + if (self.egl) |*e| e.makeCurrent(); + } + + fn compile(self: *Gpu, kind: u32, body: []const u8) !u32 { + const sh = self.gl.CreateShader(kind); + if (sh == 0) return error.ShaderFailed; + const srcs = [2][*]const u8{ prelude_src.ptr, body.ptr }; + const lens = [2]i32{ @intCast(prelude_src.len), @intCast(body.len) }; + self.gl.ShaderSource(sh, 2, &srcs, &lens); + self.gl.CompileShader(sh); + var ok: i32 = 0; + self.gl.GetShaderiv(sh, GL_COMPILE_STATUS, &ok); + if (ok == 0) { + var log: [2048]u8 = undefined; + var n: i32 = 0; + self.gl.GetShaderInfoLog(sh, log.len, &n, &log); + std.debug.print("gles: shader compile failed: {s}\n", .{log[0..@intCast(@max(n, 0))]}); + self.gl.DeleteShader(sh); + return error.ShaderFailed; + } + return sh; + } + + fn buildProgram(self: *Gpu, vsrc: []const u8, fsrc: []const u8) !Prog { + const vs = try self.compile(GL_VERTEX_SHADER, vsrc); + defer self.gl.DeleteShader(vs); + const fs = try self.compile(GL_FRAGMENT_SHADER, fsrc); + defer self.gl.DeleteShader(fs); + const p = self.gl.CreateProgram(); + if (p == 0) return error.ShaderFailed; + self.gl.AttachShader(p, vs); + self.gl.AttachShader(p, fs); + self.gl.LinkProgram(p); + var ok: i32 = 0; + self.gl.GetProgramiv(p, GL_LINK_STATUS, &ok); + if (ok == 0) { + var log: [2048]u8 = undefined; + var n: i32 = 0; + self.gl.GetProgramInfoLog(p, log.len, &n, &log); + std.debug.print("gles: program link failed: {s}\n", .{log[0..@intCast(@max(n, 0))]}); + self.gl.DeleteProgram(p); + return error.ShaderFailed; + } + const block = self.gl.GetUniformBlockIndex(p, "U"); + if (block != GL_INVALID_INDEX) self.gl.UniformBlockBinding(p, block, 0); + // Every sampler reads texture unit 0. + self.gl.UseProgram(p); + for ([_][*:0]const u8{ "cell", "atlas" }) |n| { + const loc = self.gl.GetUniformLocation(p, n); + if (loc >= 0) self.gl.Uniform1i(loc, 0); + } + return .{ + .id = p, + .clip = self.gl.GetUniformLocation(p, "u_clip"), + .cell = self.gl.GetUniformLocation(p, "u_cell"), + .halo = self.gl.GetUniformLocation(p, "u_halo"), + .fb_h = self.gl.GetUniformLocation(p, "u_fb_h"), + }; + } + + pub fn deinit(self: *Gpu) void { + self.bind(); + self.freeSceneHeld(); + inline for (.{ "sprite_tex", "glyph_tex", "glyph_bold_tex", "glyph_italic_tex" }) |name| { + if (@field(self, name)) |*t| self.destroyTexture(t); + @field(self, name) = null; + } + self.releaseOffscreen(); + if (self.ubo != 0) self.gl.DeleteBuffers(1, &[1]u32{self.ubo}); + self.ubo = 0; + inline for (.{ "fill", "pattern", "sprite", "sdf" }) |name| { + if (@field(self, name).id != 0) self.gl.DeleteProgram(@field(self, name).id); + @field(self, name) = .{}; + } + if (self.egl) |*e| e.close(); + self.egl = null; + } + + // ---- size ------------------------------------------------------------------ + + /// width/height are logical points. The pixel size is the points times + /// the pixel density; a render into a host framebuffer then takes the + /// framebuffer's own size (renderFramebuffer). + pub fn resize(self: *Gpu, width_pts: u32, height_pts: u32) void { + self.host_pt_w = @floatFromInt(width_pts); + self.host_pt_h = @floatFromInt(height_pts); + const d = if (self.pixel_density > 0) self.pixel_density else 1.0; + self.width = @intFromFloat(@round(self.host_pt_w * d)); + self.height = @intFromFloat(@round(self.host_pt_h * d)); + } + + pub fn setPixelDensity(self: *Gpu, d: f32) void { + if (d > 0.2 and d < 8.0) { + self.host_density = d; + self.pixel_density = d; + } + } + + /// Only the D3D12 backend hands a swapchain to its host to compose. + pub fn swapchainPtr(self: *Gpu) ?*anyopaque { + _ = self; + return null; + } + + // ---- atlases / textures ---------------------------------------------------- + + fn makeTexture(self: *Gpu, rgba: []const u8, w: u32, h: u32) !Tex { + if (w == 0 or h == 0 or rgba.len < @as(usize, w) * h * 4) return error.BadImage; + var id: [1]u32 = .{0}; + self.gl.GenTextures(1, &id); + if (id[0] == 0) return error.TextureFailed; + self.gl.BindTexture(GL_TEXTURE_2D, id[0]); + self.gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + self.gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + self.gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + self.gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + // Drop errors still pending from earlier calls, so the check below + // reads this upload's own. Bounded: a lost context may never clear. + var pending: usize = 0; + while (pending < 16 and self.gl.GetError() != GL_NO_ERROR) : (pending += 1) {} + self.gl.TexImage2D(GL_TEXTURE_2D, 0, @intCast(GL_RGBA8), @intCast(w), @intCast(h), 0, GL_RGBA, GL_UNSIGNED_BYTE, rgba.ptr); + if (self.gl.GetError() != GL_NO_ERROR) { + self.gl.DeleteTextures(1, &id); + return error.TextureFailed; + } + return .{ .id = id[0] }; + } + + fn destroyTexture(self: *Gpu, t: *Tex) void { + if (t.id != 0) self.gl.DeleteTextures(1, &[1]u32{t.id}); + t.* = .{}; + } + + /// Replace an atlas texture. The old one goes only once the new one is up, + /// so a failed upload leaves the atlas that was there. + fn replaceAtlas(self: *Gpu, slot: *?Tex, rgba: []const u8, w: u32, h: u32) !void { + self.bind(); + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + const t = try self.makeTexture(rgba, w, h); + if (slot.*) |*old| self.destroyTexture(old); + slot.* = t; + } + + pub fn uploadSpriteAtlas(self: *Gpu, rgba: []const u8, w: u32, h: u32) !void { + try self.replaceAtlas(&self.sprite_tex, rgba, w, h); + self.sprite_w = w; + self.sprite_h = h; + } + pub fn uploadGlyphAtlas(self: *Gpu, rgba: []const u8, w: u32, h: u32) !void { + try self.replaceAtlas(&self.glyph_tex, rgba, w, h); + } + pub fn uploadGlyphAtlasBold(self: *Gpu, rgba: []const u8, w: u32, h: u32) !void { + try self.replaceAtlas(&self.glyph_bold_tex, rgba, w, h); + } + pub fn uploadGlyphAtlasItalic(self: *Gpu, rgba: []const u8, w: u32, h: u32) !void { + try self.replaceAtlas(&self.glyph_italic_tex, rgba, w, h); + } + + /// Replace a horizontal band of the sprite atlas in place. False means the + /// caller should upload the atlas whole instead. + pub fn updateSpriteAtlasRows(self: *Gpu, rgba: []const u8, w: u32, h: u32, y0: u32, rows: u32) bool { + const t = self.sprite_tex orelse return false; + if (w != self.sprite_w or h != self.sprite_h) return false; + if (rows == 0 or y0 + rows > h) return false; + const off = @as(usize, y0) * w * 4; + const need = @as(usize, rows) * w * 4; + if (rgba.len < off + need) return false; + self.bind(); + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + self.gl.BindTexture(GL_TEXTURE_2D, t.id); + self.gl.TexSubImage2D(GL_TEXTURE_2D, 0, 0, @intCast(y0), @intCast(w), @intCast(rows), GL_RGBA, GL_UNSIGNED_BYTE, rgba[off..].ptr); + return true; + } + + fn atlasHave(self: *const Gpu) u8 { + var m: u8 = 0; + if (self.sprite_tex != null) m |= scene.AtlasBit.bit(.sprite); + if (self.glyph_tex != null) m |= scene.AtlasBit.bit(.glyph); + if (self.glyph_bold_tex != null) m |= scene.AtlasBit.bit(.glyph_bold); + if (self.glyph_italic_tex != null) m |= scene.AtlasBit.bit(.glyph_italic); + return m; + } + + fn atlasTexture(self: *const Gpu, atlas: scene.Atlas) ?Tex { + return switch (atlas) { + .glyph => self.glyph_tex, + .glyph_bold => self.glyph_bold_tex, + .glyph_italic => self.glyph_italic_tex, + else => self.sprite_tex, + }; + } + + // ---- the scene ------------------------------------------------------------- + + pub const SceneData = struct { + vertices: []const scene.Vertex = &.{}, + paint: []const scene.PaintVertex = &.{}, + paint_hi: []const scene.PaintVertex = &.{}, + indices: []const u32 = &.{}, + quads: []const scene.Quad = &.{}, + quad_paint: []const scene.PaintVertex = &.{}, + ranges: []const scene.Range = &.{}, + patterns: []const scene.PatternCell = &.{}, + }; + + pub const Scene = struct { + alloc: std.mem.Allocator, + /// The CPU copy makeScene takes on the build worker. adoptScene turns + /// it into the GL objects below and frees it. + staged: ?SceneData = null, + vbuf: u32 = 0, // scene.Vertex, indexed + ibuf: u32 = 0, // u32 indices + pbuf: u32 = 0, // scene.PaintVertex, one per vertex + phbuf: u32 = 0, // the zoom pair's upper half + qbuf: u32 = 0, // scene.Quad, six per quad, non-indexed + qpbuf: u32 = 0, // paint, one per quad vertex + pbuf_bytes: usize = 0, + qpbuf_bytes: usize = 0, + tri_vao: u32 = 0, + quad_vao: u32 = 0, + ranges: []scene.Range = &.{}, + patterns: []PatternTex = &.{}, + /// Scratch for the batch, sized to the range count, which is the + /// ceiling: draws only merge. + draws: []scene.Draw = &.{}, + }; + + /// Copy the scene for adoptScene. It touches no GL object, so the build + /// worker may call it while the owner thread draws. + pub fn makeScene(self: *Gpu, alloc: std.mem.Allocator, data: SceneData) !Scene { + _ = self; + return .{ .alloc = alloc, .staged = try copyData(alloc, data) }; + } + + fn copyData(alloc: std.mem.Allocator, data: SceneData) !SceneData { + var out = SceneData{}; + errdefer freeData(alloc, &out); + out.vertices = try alloc.dupe(scene.Vertex, data.vertices); + out.paint = try alloc.dupe(scene.PaintVertex, data.paint); + out.paint_hi = try alloc.dupe(scene.PaintVertex, data.paint_hi); + out.indices = try alloc.dupe(u32, data.indices); + out.quads = try alloc.dupe(scene.Quad, data.quads); + out.quad_paint = try alloc.dupe(scene.PaintVertex, data.quad_paint); + out.ranges = try alloc.dupe(scene.Range, data.ranges); + const cells = try alloc.alloc(scene.PatternCell, data.patterns.len); + for (cells) |*c| c.* = .{ .w = 0, .h = 0, .rgba = &.{} }; + out.patterns = cells; + for (data.patterns, cells) |src, *dst| + dst.* = .{ .w = src.w, .h = src.h, .rgba = try alloc.dupe(u8, src.rgba) }; + return out; + } + + fn freeData(alloc: std.mem.Allocator, d: *SceneData) void { + alloc.free(d.vertices); + alloc.free(d.paint); + alloc.free(d.paint_hi); + alloc.free(d.indices); + alloc.free(d.quads); + alloc.free(d.quad_paint); + alloc.free(d.ranges); + for (d.patterns) |c| alloc.free(c.rgba); + alloc.free(d.patterns); + d.* = .{}; + } + + fn makeBuffer(self: *Gpu, target: u32, bytes: []const u8) u32 { + if (bytes.len == 0) return 0; + var id: [1]u32 = .{0}; + self.gl.GenBuffers(1, &id); + self.gl.BindBuffer(target, id[0]); + self.gl.BufferData(target, @intCast(bytes.len), bytes.ptr, if (target == GL_ARRAY_BUFFER) GL_DYNAMIC_DRAW else GL_STATIC_DRAW); + return id[0]; + } + + fn attrib(self: *Gpu, loc: u32, n: i32, kind: u32, stride: usize, off: usize) void { + self.gl.EnableVertexAttribArray(loc); + const p: ?*const anyopaque = if (off == 0) null else @ptrFromInt(off); + if (kind == GL_UNSIGNED_INT) + self.gl.VertexAttribIPointer(loc, n, kind, @intCast(stride), p) + else + self.gl.VertexAttribPointer(loc, n, kind, @intFromBool(kind == GL_UNSIGNED_BYTE), @intCast(stride), p); + } + + /// Build the GL objects of a scene from `data`. Owner thread, with the + /// state saved by the caller. A pattern texture that fails stays null and + /// its range draws nothing. + fn realize(self: *Gpu, alloc: std.mem.Allocator, data: SceneData) !Scene { + var out = Scene{ .alloc = alloc }; + errdefer self.freeSceneValue(&out); + + const V = scene.Vertex; + const Q = scene.Quad; + const P = scene.PaintVertex; + if (data.vertices.len > 0 and data.indices.len > 0) { + var vao: [1]u32 = .{0}; + self.gl.GenVertexArrays(1, &vao); + out.tri_vao = vao[0]; + self.gl.BindVertexArray(out.tri_vao); + out.vbuf = self.makeBuffer(GL_ARRAY_BUFFER, std.mem.sliceAsBytes(data.vertices)); + self.attrib(0, 2, GL_FLOAT, @sizeOf(V), 0); // a_pos + self.attrib(1, 2, GL_FLOAT, @sizeOf(V), 8); // a_off + self.attrib(2, 1, GL_UNSIGNED_INT, @sizeOf(V), 16); // a_zwin + self.attrib(3, 1, GL_UNSIGNED_INT, @sizeOf(V), 20); // a_flags + self.attrib(4, 1, GL_FLOAT, @sizeOf(V), 24); // a_depth + // Stream B rides parallel buffers. A scene with no paint stream + // reads the geometry there, as the Vulkan backend binds it; a + // scene with no upper half reads the lower one twice, and the + // shader's mix collapses to a no-op. + out.pbuf = self.makeBuffer(GL_ARRAY_BUFFER, std.mem.sliceAsBytes(data.paint)); + out.pbuf_bytes = data.paint.len * @sizeOf(P); + out.phbuf = self.makeBuffer(GL_ARRAY_BUFFER, std.mem.sliceAsBytes(data.paint_hi)); + const pb = if (out.pbuf != 0) out.pbuf else out.vbuf; + self.gl.BindBuffer(GL_ARRAY_BUFFER, pb); + self.attrib(5, 4, GL_UNSIGNED_BYTE, @sizeOf(P), 0); // a_color + self.gl.BindBuffer(GL_ARRAY_BUFFER, if (out.phbuf != 0) out.phbuf else pb); + self.attrib(6, 4, GL_UNSIGNED_BYTE, @sizeOf(P), 0); // a_color_hi + out.ibuf = self.makeBuffer(GL_ELEMENT_ARRAY_BUFFER, std.mem.sliceAsBytes(data.indices)); + self.gl.BindVertexArray(0); + } + if (data.quads.len > 0) { + var vao: [1]u32 = .{0}; + self.gl.GenVertexArrays(1, &vao); + out.quad_vao = vao[0]; + self.gl.BindVertexArray(out.quad_vao); + out.qbuf = self.makeBuffer(GL_ARRAY_BUFFER, std.mem.sliceAsBytes(data.quads)); + self.attrib(0, 2, GL_FLOAT, @sizeOf(Q), 0); // a_pos + self.attrib(1, 2, GL_FLOAT, @sizeOf(Q), 8); // a_off + self.attrib(2, 2, GL_FLOAT, @sizeOf(Q), 16); // a_uv + self.attrib(3, 1, GL_FLOAT, @sizeOf(Q), 24); // a_weight + self.attrib(4, 1, GL_UNSIGNED_INT, @sizeOf(Q), 28); // a_zwin + self.attrib(5, 1, GL_UNSIGNED_INT, @sizeOf(Q), 32); // a_pack + self.attrib(6, 1, GL_FLOAT, @sizeOf(Q), 36); // a_depth + out.qpbuf = self.makeBuffer(GL_ARRAY_BUFFER, std.mem.sliceAsBytes(data.quad_paint)); + out.qpbuf_bytes = data.quad_paint.len * @sizeOf(P); + self.gl.BindBuffer(GL_ARRAY_BUFFER, if (out.qpbuf != 0) out.qpbuf else out.qbuf); + self.attrib(7, 4, GL_UNSIGNED_BYTE, @sizeOf(P), 0); // a_color + self.attrib(8, 4, GL_UNSIGNED_BYTE, @sizeOf(P), 0); // a_color_hi + self.gl.BindVertexArray(0); + } + if (data.ranges.len > 0) { + out.ranges = try alloc.dupe(scene.Range, data.ranges); + out.draws = try alloc.alloc(scene.Draw, data.ranges.len); + } + if (data.patterns.len > 0) { + out.patterns = try alloc.alloc(PatternTex, data.patterns.len); + @memset(out.patterns, .{}); + for (data.patterns, out.patterns) |cell, *pt| { + if (cell.w == 0 or cell.h == 0 or cell.rgba.len == 0) continue; + pt.* = .{ + .tex = self.makeTexture(cell.rgba, cell.w, cell.h) catch null, + .w = @floatFromInt(cell.w), + .h = @floatFromInt(cell.h), + }; + } + } + return out; + } + + /// Land a scene. A staged one becomes GL objects here, on the owner + /// thread. If that fails, the map shows no scene until the next one. + pub fn adoptScene(self: *Gpu, sc: Scene) void { + var landed = sc; + self.bind(); + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + self.freeSceneHeld(); + if (landed.staged) |staged| { + var d = staged; + const alloc = landed.alloc; + defer freeData(alloc, &d); + landed = self.realize(alloc, d) catch |e| { + std.debug.print("gles: scene upload failed: {s}\n", .{@errorName(e)}); + return; + }; + } + self.scene = landed; + } + + pub fn uploadScene(self: *Gpu, alloc: std.mem.Allocator, data: SceneData) !void { + self.bind(); + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + const sc = try self.realize(alloc, data); + self.freeSceneHeld(); + self.scene = sc; + } + + fn rewrite(self: *Gpu, buf: u32, cap: usize, bytes: []const u8) void { + if (buf == 0 or bytes.len == 0) return; + self.bind(); + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + self.gl.BindBuffer(GL_ARRAY_BUFFER, buf); + self.gl.BufferSubData(GL_ARRAY_BUFFER, 0, @intCast(@min(bytes.len, cap)), bytes.ptr); + } + + /// Repaint without rebuilding geometry: only the paint stream changes. + pub fn updatePaint(self: *Gpu, paint: []const scene.PaintVertex) !void { + const sc = if (self.scene) |*x| x else return; + self.rewrite(sc.pbuf, sc.pbuf_bytes, std.mem.sliceAsBytes(paint)); + } + + /// The quad half of the same contract (a raster cross-fade). + pub fn updateQuadPaint(self: *Gpu, quad_paint: []const scene.PaintVertex) !void { + const sc = if (self.scene) |*x| x else return; + self.rewrite(sc.qpbuf, sc.qpbuf_bytes, std.mem.sliceAsBytes(quad_paint)); + } + + /// Free a scene that makeScene staged and nobody adopted. A staged scene + /// holds CPU memory only, so this needs no context. + pub fn freeStagedScene(self: *Gpu, sc: *Scene) void { + if (sc.staged) |*d| freeData(sc.alloc, d); + sc.staged = null; + if (sc.vbuf != 0 or sc.qbuf != 0 or sc.patterns.len > 0 or sc.ranges.len > 0) { + self.bind(); + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + self.freeSceneValue(sc); + } + } + + fn freeSceneValue(self: *Gpu, sc: *Scene) void { + if (sc.staged) |*d| freeData(sc.alloc, d); + sc.staged = null; + for ([_]*u32{ &sc.vbuf, &sc.ibuf, &sc.pbuf, &sc.phbuf, &sc.qbuf, &sc.qpbuf }) |b| { + if (b.* != 0) self.gl.DeleteBuffers(1, &[1]u32{b.*}); + b.* = 0; + } + for ([_]*u32{ &sc.tri_vao, &sc.quad_vao }) |v| { + if (v.* != 0) self.gl.DeleteVertexArrays(1, &[1]u32{v.*}); + v.* = 0; + } + for (sc.patterns) |*pt| if (pt.tex) |*t| self.destroyTexture(t); + if (sc.patterns.len > 0) sc.alloc.free(sc.patterns); + if (sc.ranges.len > 0) sc.alloc.free(sc.ranges); + if (sc.draws.len > 0) sc.alloc.free(sc.draws); + sc.patterns = &.{}; + sc.ranges = &.{}; + sc.draws = &.{}; + } + + pub fn freeScene(self: *Gpu) void { + if (self.scene == null) return; + self.bind(); + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + self.freeSceneHeld(); + } + + fn freeSceneHeld(self: *Gpu) void { + if (self.scene) |*sc| { + self.freeSceneValue(sc); + self.scene = null; + } + } + + // ---- the frame ------------------------------------------------------------- + + fn batchScene(self: *const Gpu, sc: *const Scene) []const scene.Draw { + if (sc.ranges.len == 0 or sc.draws.len == 0) return &.{}; + const opts = scene.BatchOpts{ + .exclude_opaque_tris = false, + .atlas_have = self.atlasHave(), + .halo = .{ self.clear.r, self.clear.g, self.clear.b, 1 }, + }; + const n = batch.batch(sc.ranges, opts, sc.draws); + return if (n > sc.draws.len) &.{} else sc.draws[0..n]; + } + + /// Clear `fbo` and draw the scene into it, in paint order. The caller + /// saved the state and restores it. + fn drawInto(self: *Gpu, fbo: u32, w: u32, h: u32, u: Uniforms) void { + const gl = &self.gl; + gl.BindFramebuffer(GL_FRAMEBUFFER, fbo); + gl.Viewport(0, 0, @intCast(w), @intCast(h)); + for (caps) |c| gl.Disable(c); + gl.Enable(GL_BLEND); + gl.BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + gl.BlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); + gl.ColorMask(1, 1, 1, 1); + gl.ClearColor(self.clear.r, self.clear.g, self.clear.b, self.clear.a); + gl.Clear(GL_COLOR_BUFFER_BIT); + + const sc = if (self.scene) |*x| x else return; // no scene: clear only + // One block per frame: orphan the buffer so the driver does not wait + // for the last frame to finish reading it. + gl.BindBuffer(GL_UNIFORM_BUFFER, self.ubo); + gl.BufferData(GL_UNIFORM_BUFFER, @sizeOf(Uniforms), &u, GL_STREAM_DRAW); + gl.BindBufferBase(GL_UNIFORM_BUFFER, 0, self.ubo); + gl.ActiveTexture(GL_TEXTURE0); + + const fb_h: f32 = @floatFromInt(h); + var bound_prog: u32 = 0; + var bound_tex: u32 = 0; + var bound_prim: ?scene.Prim = null; + for (self.batchScene(sc)) |d| { + const tri = d.prim == .triangles; + var prog: *const Prog = undefined; + var tex: u32 = 0; + var cell: [2]f32 = u.cell_px; + if (tri) { + if (sc.tri_vao == 0) continue; + prog = &self.fill; + if (d.pipeline == .pattern) { + if (d.pattern >= sc.patterns.len) continue; + const pt = sc.patterns[d.pattern]; + const t = pt.tex orelse continue; + const cs = self.pixel_density * self.pattern_scale; + cell = .{ pt.w * cs, pt.h * cs }; + prog = &self.pattern; + tex = t.id; + } + } else { + if (sc.quad_vao == 0) continue; + const t = if (d.pipeline == .raster) blk: { + if (d.pattern >= sc.patterns.len) continue; + break :blk sc.patterns[d.pattern].tex orelse continue; + } else self.atlasTexture(d.atlas) orelse continue; + prog = if (d.pipeline == .sdf) &self.sdf else &self.sprite; + tex = t.id; + } + + if (prog.id != bound_prog) { + gl.UseProgram(prog.id); + bound_prog = prog.id; + } + if (bound_prim == null or bound_prim.? != d.prim) { + gl.BindVertexArray(if (tri) sc.tri_vao else sc.quad_vao); + bound_prim = d.prim; + } + if (tex != 0 and tex != bound_tex) { + gl.BindTexture(GL_TEXTURE_2D, tex); + bound_tex = tex; + } + gl.Uniform4f(prog.clip, d.clip[0], d.clip[1], d.clip[2], d.clip[3]); + gl.Uniform2f(prog.cell, cell[0], cell[1]); + gl.Uniform4f(prog.halo, d.color[0], d.color[1], d.color[2], d.color[3]); + gl.Uniform1f(prog.fb_h, fb_h); + if (tri) { + const off: ?*const anyopaque = if (d.first == 0) null else @ptrFromInt(@as(usize, d.first) * 4); + gl.DrawElements(GL_TRIANGLES, @intCast(d.count), GL_UNSIGNED_INT, off); + } else { + gl.DrawArrays(GL_TRIANGLES, @intCast(d.first), @intCast(d.count)); + } + } + } + + /// Render into the framebuffer the host has bound for drawing, at the + /// current pixel size. False with no host context: a snapshot-only Gpu + /// has no window. + pub fn renderWindow(self: *Gpu, u: Uniforms) bool { + if (self.egl != null) return false; + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + self.drawInto(@bitCast(s.draw_fbo), self.width, self.height, u); + return true; + } + + /// Render into a framebuffer of the host's context (0 is the default + /// one), at its size in pixels. The size becomes the Gpu's. + pub fn renderFramebuffer(self: *Gpu, u: Uniforms, fbo: u32, w: u32, h: u32) bool { + if (w == 0 or h == 0) return false; + self.width = w; + self.height = h; + if (self.host_density == 0 and self.host_pt_w > 0) { + const d = @as(f32, @floatFromInt(w)) / self.host_pt_w; + if (d > 0.2 and d < 8.0) self.pixel_density = d; + } + self.bind(); + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + self.drawInto(fbo, w, h, u); + return true; + } + + fn releaseOffscreen(self: *Gpu) void { + if (self.off_fbo != 0) self.gl.DeleteFramebuffers(1, &[1]u32{self.off_fbo}); + if (self.off_rb != 0) self.gl.DeleteRenderbuffers(1, &[1]u32{self.off_rb}); + self.off_fbo = 0; + self.off_rb = 0; + self.off_w = 0; + self.off_h = 0; + } + + fn ensureOffscreen(self: *Gpu) !void { + if (self.off_fbo != 0 and self.off_w == self.width and self.off_h == self.height) return; + self.releaseOffscreen(); + var id: [1]u32 = .{0}; + self.gl.GenRenderbuffers(1, &id); + self.off_rb = id[0]; + self.gl.BindRenderbuffer(GL_RENDERBUFFER, self.off_rb); + self.gl.RenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, @intCast(self.width), @intCast(self.height)); + self.gl.GenFramebuffers(1, &id); + self.off_fbo = id[0]; + self.gl.BindFramebuffer(GL_FRAMEBUFFER, self.off_fbo); + self.gl.FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, self.off_rb); + if (self.gl.CheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { + self.releaseOffscreen(); + return error.FramebufferIncomplete; + } + self.off_w = self.width; + self.off_h = self.height; + } + + /// Render one frame offscreen and read the pixels back (RGBA8, top-down). + pub fn renderOffscreen(self: *Gpu, alloc: std.mem.Allocator, u: Uniforms) ![]u8 { + if (self.width == 0 or self.height == 0) return error.EmptyTarget; + self.bind(); + const s = Saved.save(&self.gl); + defer s.restore(&self.gl); + try self.ensureOffscreen(); + self.drawInto(self.off_fbo, self.width, self.height, u); + const w: usize = self.width; + const h: usize = self.height; + const px = try alloc.alloc(u8, w * h * 4); + errdefer alloc.free(px); + self.gl.BindFramebuffer(GL_READ_FRAMEBUFFER, self.off_fbo); + self.gl.ReadPixels(0, 0, @intCast(w), @intCast(h), GL_RGBA, GL_UNSIGNED_BYTE, px.ptr); + // GL reads the bottom row first. + const row = w * 4; + var tmp: [4096 * 4]u8 = undefined; + var y: usize = 0; + while (y < h / 2) : (y += 1) { + const a = px[y * row ..][0..row]; + const b = px[(h - 1 - y) * row ..][0..row]; + var x: usize = 0; + while (x < row) : (x += tmp.len) { + const n = @min(tmp.len, row - x); + @memcpy(tmp[0..n], a[x..][0..n]); + @memcpy(a[x..][0..n], b[x..][0..n]); + @memcpy(b[x..][0..n], tmp[0..n]); + } + } + return px; + } + + pub fn savePng(self: *Gpu, alloc: std.mem.Allocator, path: []const u8, u: Uniforms) !void { + const pixels = try self.renderOffscreen(alloc, u); + defer alloc.free(pixels); + try png.write(alloc, path, pixels, self.width, self.height); + } +}; + +test "gles: a snapshot-only Gpu clears to its background and restores the state it changed" { + var g = Gpu.init(.{ .width = 8, .height = 4 }) catch return error.SkipZigTest; + defer g.deinit(); + g.clear = .{ .r = 1, .g = 0, .b = 0, .a = 1 }; + // State a host could have set. The frame must hand it back. + g.gl.ClearColor(0.25, 0.5, 0.75, 1); + g.gl.Enable(caps[3]); // GL_SCISSOR_TEST + g.gl.Viewport(1, 2, 3, 4); + const before = Saved.save(&g.gl); + + const px = try g.renderOffscreen(std.testing.allocator, std.mem.zeroes(Uniforms)); + defer std.testing.allocator.free(px); + try std.testing.expectEqual(@as(usize, 8 * 4 * 4), px.len); + var i: usize = 0; + while (i < px.len) : (i += 4) try std.testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, px[i..][0..4]); + + const after = Saved.save(&g.gl); + try std.testing.expectEqualSlices(f32, &before.clear_color, &after.clear_color); + try std.testing.expectEqualSlices(u8, &before.enabled, &after.enabled); + try std.testing.expectEqualSlices(i32, &before.viewport, &after.viewport); + try std.testing.expectEqual(before.draw_fbo, after.draw_fbo); + try std.testing.expectEqual(before.program, after.program); +} + +test "gles: a render into a host framebuffer draws top-up and adopts the target size" { + var g = Gpu.init(.{ .width = 4, .height = 4 }) catch return error.SkipZigTest; + defer g.deinit(); + // The host's framebuffer: a renderbuffer, 16x8. + var ids: [1]u32 = .{0}; + g.gl.GenRenderbuffers(1, &ids); + const rb = ids[0]; + defer g.gl.DeleteRenderbuffers(1, &[1]u32{rb}); + g.gl.BindRenderbuffer(GL_RENDERBUFFER, rb); + g.gl.RenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, 16, 8); + g.gl.GenFramebuffers(1, &ids); + const fbo = ids[0]; + defer g.gl.DeleteFramebuffers(1, &[1]u32{fbo}); + g.gl.BindFramebuffer(GL_FRAMEBUFFER, fbo); + g.gl.FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rb); + try std.testing.expectEqual(GL_FRAMEBUFFER_COMPLETE, g.gl.CheckFramebufferStatus(GL_FRAMEBUFFER)); + g.gl.BindFramebuffer(GL_FRAMEBUFFER, 0); + + // One triangle over the top half of the view: NDC y from 0 to 1. + const verts = [_]scene.Vertex{ + std.mem.zeroInit(scene.Vertex, .{ .x = -1, .y = 0, .zmin = 0, .zmax = 0xFFFF, .depth = 0.5 }), + std.mem.zeroInit(scene.Vertex, .{ .x = 3, .y = 0, .zmin = 0, .zmax = 0xFFFF, .depth = 0.5 }), + std.mem.zeroInit(scene.Vertex, .{ .x = -1, .y = 2, .zmin = 0, .zmax = 0xFFFF, .depth = 0.5 }), + }; + const green = scene.PaintVertex{ .color = .{ 0, 255, 0, 255 } }; + const paint = [_]scene.PaintVertex{ green, green, green }; + const ranges = [_]scene.Range{std.mem.zeroInit(scene.Range, .{ .first = 0, .count = 3 })}; + try g.uploadScene(std.testing.allocator, .{ + .vertices = &verts, + .paint = &paint, + .indices = &.{ 0, 1, 2 }, + .ranges = &ranges, + }); + g.clear = .{ .r = 0, .g = 0, .b = 1, .a = 1 }; + var u = std.mem.zeroes(Uniforms); + u.mvp = .{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; + u.size_scale = 1; + u.clip_rect = scene.CLIP_NONE; + try std.testing.expect(g.renderFramebuffer(u, fbo, 16, 8)); + try std.testing.expectEqual(@as(u32, 16), g.width); + try std.testing.expectEqual(@as(u32, 8), g.height); + + // GL row 7 is the top of the picture: green. Row 0 is the bottom: blue. + var px: [16 * 8 * 4]u8 = undefined; + const s = Saved.save(&g.gl); + defer s.restore(&g.gl); + g.gl.BindFramebuffer(GL_READ_FRAMEBUFFER, fbo); + g.gl.ReadPixels(0, 0, 16, 8, GL_RGBA, GL_UNSIGNED_BYTE, &px); + try std.testing.expectEqualSlices(u8, &.{ 0, 255, 0, 255 }, px[(7 * 16 + 8) * 4 ..][0..4]); + try std.testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, px[(0 * 16 + 8) * 4 ..][0..4]); + + // A snapshot of the same frame comes back top-down. + const snap = try g.renderOffscreen(std.testing.allocator, u); + defer std.testing.allocator.free(snap); + try std.testing.expectEqualSlices(u8, &.{ 0, 255, 0, 255 }, snap[(0 * 16 + 8) * 4 ..][0..4]); + try std.testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, snap[(7 * 16 + 8) * 4 ..][0..4]); +} + +test "gles: a staged scene holds no GL object until it is adopted" { + var g = Gpu.init(.{ .width = 4, .height = 4 }) catch return error.SkipZigTest; + defer g.deinit(); + const ranges = [_]scene.Range{std.mem.zeroInit(scene.Range, .{ .first = 0, .count = 0 })}; + var sc = try g.makeScene(std.testing.allocator, .{ .ranges = &ranges }); + try std.testing.expect(sc.staged != null); + try std.testing.expectEqual(@as(u32, 0), sc.tri_vao); + g.adoptScene(sc); + try std.testing.expect(g.scene.?.staged == null); + try std.testing.expectEqual(@as(usize, 1), g.scene.?.ranges.len); + // And one nobody adopts frees without a context. + sc = try g.makeScene(std.testing.allocator, .{ .ranges = &ranges }); + g.freeStagedScene(&sc); +} + +test "gles: pattern and sprite draws sample their textures" { + var g = Gpu.init(.{ .width = 8, .height = 8 }) catch return error.SkipZigTest; + defer g.deinit(); + const a = std.testing.allocator; + const red = [_]u8{ 255, 0, 0, 255 } ** 4; + try g.uploadSpriteAtlas(&red, 2, 2); + + // A pattern fill over the whole view, from a 2x2 yellow cell. + const tri = [_]scene.Vertex{ + std.mem.zeroInit(scene.Vertex, .{ .x = -1, .y = -1, .zmax = 0xFFFF, .depth = 0.5 }), + std.mem.zeroInit(scene.Vertex, .{ .x = 3, .y = -1, .zmax = 0xFFFF, .depth = 0.5 }), + std.mem.zeroInit(scene.Vertex, .{ .x = -1, .y = 3, .zmax = 0xFFFF, .depth = 0.5 }), + }; + const yellow = [_]u8{ 255, 255, 0, 255 } ** 4; + const cells = [_]scene.PatternCell{.{ .w = 2, .h = 2, .rgba = &yellow }}; + // A sprite quad over the left half, drawn after the fill. + const corners = [_][4]f32{ .{ -1, -1, 0, 1 }, .{ 0, -1, 1, 1 }, .{ 0, 1, 1, 0 }, .{ -1, -1, 0, 1 }, .{ 0, 1, 1, 0 }, .{ -1, 1, 0, 0 } }; + var quads: [6]scene.Quad = undefined; + for (&quads, corners) |*q, c| q.* = std.mem.zeroInit(scene.Quad, .{ .x = c[0], .y = c[1], .u = c[2], .v = c[3], .zmax = 0xFFFF, .depth = 0.25 }); + const white = scene.PaintVertex{ .color = .{ 255, 255, 255, 255 } }; + const qpaint = [_]scene.PaintVertex{white} ** 6; + const ranges = [_]scene.Range{ + std.mem.zeroInit(scene.Range, .{ .first = 0, .count = 3, .kind = .pattern, .pattern = 0 }), + std.mem.zeroInit(scene.Range, .{ .first = 0, .count = 6, .kind = .symbol, .prim = .quads, .atlas = .sprite }), + }; + try g.uploadScene(a, .{ + .vertices = &tri, + .indices = &.{ 0, 1, 2 }, + .quads = &quads, + .quad_paint = &qpaint, + .ranges = &ranges, + .patterns = &cells, + }); + var u = std.mem.zeroes(Uniforms); + u.mvp = .{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; + u.size_scale = 1; + u.cell_px = .{ 1, 1 }; + u.clip_rect = scene.CLIP_NONE; + const px = try g.renderOffscreen(a, u); + defer a.free(px); + try std.testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, px[(4 * 8 + 1) * 4 ..][0..4]); + try std.testing.expectEqualSlices(u8, &.{ 255, 255, 0, 255 }, px[(4 * 8 + 6) * 4 ..][0..4]); +}