# tinygfx **Repository Path**: oddity/tinygfx ## Basic Information - **Project Name**: tinygfx - **Description**: 跨平台、轻量2D、3D渲染库 - **Primary Language**: Unknown - **License**: BSD-2-Clause - **Default Branch**: develop - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-11-06 - **Last Updated**: 2026-11-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # tinygfx A from-scratch lightweight cross-platform **2D vector + 3D drawing** library. Pure rendering — no window, no layout, no UI. A recorded command list is replayed by a pluggable backend into a render target. Seven 2D backends are implemented (CPU, GDI+, D2D, Quartz2D, Cairo, DX11, OpenGL); DX11 and OpenGL additionally implement the 3D drawing mode. Vulkan has an opt-in 2D path (`--vulkan=y`: seven of the eight renderdiff cells match DX11; only the non-NORMAL blend modes are still landing); Metal / DX12 / WebGPU are declared enum slots only. - **Pure C ABI** header + C++ implementation, compiles to a static library - **Opaque handles** — zero internal leakage in public header - **Three-layer object tree** — `device` (backend session, owns shared resources) → `context2d` / `context3d` (usage modes); `texture` / `render_target` / `renderer` are created from the device - **Record → submit → present** pipeline — `command_list2d` and `command_list3d` share one `renderer_submit` entry (kind-tag dispatch) - **Two-layer interface** — `flat/` pure C API + `wrapper/` optional C++ RAII sugar (namespace `tg`) - **Capability as a type** — `context3d_create` succeeds only on 3D backends and returns `NOT_SUPPORTED` on 2D-only ones; `tinygfx_backend_supports3d()` probes without opening a device - **Cross-platform present** — Win32 (GDI `StretchDIBits`), macOS (Quartz), Linux X11 (`XPutImage`) / Wayland (`wl_shm`); GPU backends use their own swapchain / window surface. The window system is identified by `platformId` - **Additive ABI evolution** — public descriptor/output structs carry `structSize` (`Color`, `Point`, `Rect`, `Matrix` etc. are plain value types and do not); enum fields are guarded to stay 32-bit. Input descriptors require `structSize >= sizeof(desc)`, so existing ones must not grow — new shapes get a new struct/entry point - **No chaining, explicit errors** — every mutating call returns an `Error`; no hidden state ## Documentation User-facing behaviour contracts live in [`docs/user/`](docs/user/README.md): | Doc | Covers | |---|---| | [quick-start.md](docs/user/quick-start.md) | Minimal C / C++ example: device, context, record, submit, read pixels | | [coordinate-domains.md](docs/user/coordinate-domains.md) | Canvas coordinates, BGRA32 memory order, physical sizes, 3D conventions | | [error-handling.md](docs/user/error-handling.md) | Error taxonomy, outError convention, per-device + global last error | | [render-integration.md](docs/user/render-integration.md) | Presenting into a window library (tinywind) via the native surface | | [render-targets.md](docs/user/render-targets.md) | Offscreen / window / external-texture targets, MSAA, 2D↔3D interop | | [interop.md](docs/user/interop.md) | Adopting your `ID3D11Device` / texture; finding out what AUTO picked | Design & project docs: [architecture.md](docs/project/architecture.md), [design-2d3d.md](docs/project/design-2d3d.md) (2D/3D unification, the definitive design), [api-review.md](docs/project/api-review.md), [roadmap.md](docs/project/roadmap.md), [backend-alignment.md](docs/project/backend-alignment.md). Release history: [CHANGELOG.md](CHANGELOG.md). ## Quick Start ### C API ```c #include #include int main(void) { tinygfx_error err = TINYGFX_OK; /* AUTO (0) picks the best backend for this host at create time: Windows D2D->DX11->CPU, macOS Quartz2D->CPU, Linux GL->CPU. Ask which one won with tinygfx_device_get_backend(). */ tinygfx_device_desc d = {0}; d.structSize = sizeof(d); d.backend = TINYGFX_BACKEND_AUTO; tinygfx_device* dev = tinygfx_device_create(&d, &err); if (!dev) return 1; tinygfx_context2d* ctx = tinygfx_context2d_create(dev, &err); if (!ctx) return 1; /* Paints are handles too: color / gradient / stroke state. */ tinygfx_paint* p = tinygfx_context2d_create_paint(ctx, &err); tinygfx_paint_set_color(p, 1.0f, 0.2f, 0.2f); /* solid red */ tinygfx_path* path = tinygfx_context2d_create_path(ctx, &err); tinygfx_path_add_rect(path, 10.0f, 10.0f, 100.0f, 60.0f); tinygfx_command_list2d* cmd = tinygfx_context2d_create_command_list(ctx); tinygfx_command_list2d_clear(cmd, NULL); /* NULL = transparent */ tinygfx_command_list2d_fill_path(cmd, path, p); /* render targets and renderers belong to the DEVICE, not the context. */ tinygfx_render_target* target = tinygfx_device_create_render_target( dev, 320, 240, TINYGFX_PIXEL_BGRA8, TINYGFX_RT_OFFSCREEN, &err); tinygfx_renderer* renderer = tinygfx_device_create_renderer(dev, &err); tinygfx_renderer_clear(renderer, target, NULL); tinygfx_renderer_submit(renderer, cmd, target); const uint8_t* pixels = NULL; size_t bytes = 0; tinygfx_render_target_get_pixels(target, &pixels, &bytes); /* pixels is BGRA32, w*h*4 bytes; valid until resize/destroy. */ tinygfx_render_target_destroy(target); tinygfx_renderer_destroy(renderer); tinygfx_command_list2d_destroy(cmd); tinygfx_path_destroy(path); tinygfx_paint_destroy(p); tinygfx_context2d_destroy(ctx); tinygfx_device_destroy(dev); return 0; } ``` ### C++ wrapper ```cpp #include using namespace tg; int main() { Error err = Error::Ok; Device dev = Device::create(Backend::Auto, &err); if (!dev.valid()) return 1; Context2D ctx = Context2D::create(dev, &err); if (!ctx.valid()) return 1; Paint p = Paint::create(ctx, &err); p.setColor(1.0f, 0.2f, 0.2f); Path rect = Path::create(ctx, &err); rect.addRect(Rect(10, 10, 100, 60)); CommandList2D cmd = CommandList2D::create(ctx, &err); cmd.clear(Color(1, 1, 1)); cmd.fillPath(rect, p); Renderer renderer = Renderer::create(dev, &err); RenderTarget target = RenderTarget::create(dev, 320, 240, &err); renderer.clear(target, Color(1, 1, 1)); renderer.submit(cmd, target); return 0; } ``` Presenting into a real window: see [render-integration.md](docs/user/render-integration.md) and `examples/integration/hello.cc`. For the 3D mode (geometry / material / `command_list3d`) see [design-2d3d.md](docs/project/design-2d3d.md) §5.2 and `examples/scene3d/`. ## Build ```bash xmake f -m debug --tests=y --examples=y -y # one-time config xmake -r -y ./bin/tinygfx_test_unit.exe # or build///debug/ ``` Options: `--build2d=y` / `--build3d=y` (both default on) compile the two usage modes independently (see `docs/project/design-2d3d.md` §8 for exactly what each gate removes); `--cairo=y` opts into the Cairo backend (Linux, needs `libcairo2-dev`); `--tools=y` builds the offline `tinygfx_shader_cross` GLSL→HLSL converter (default off, not part of the library; see `docs/project/shader-cross.md`). CI builds and runs all three `2D/3D` combinations. CI builds and runs all three `2D/3D` combinations. The whole tree, including the `tinywind` submodule used by examples, builds with xmake — no CMake/Ninja toolchain is required. ## Project Structure ``` tinygfx/ ├── include/tinygfx/ │ ├── tinygfx.h # aggregate C header │ ├── tinygfx.hpp # aggregate C++ wrapper (namespace tg) │ ├── flat/ # pure C ABI (no platform headers leaked) │ │ ├── types.h # value types, error codes, backend enum, descriptors │ │ ├── device.h # root: create / interop / last error / budget │ │ ├── context2d.h / context3d.h │ │ ├── path.h / paint.h / font.h / texture.h / resource.h │ │ ├── command_list2d.h / command_list3d.h │ │ ├── geometry.h / material.h / mat4.h │ │ └── render_target.h / renderer.h │ └── wrapper/ # optional C++ RAII sugar (namespace tg) │ └── common.hpp / types.hpp / device.hpp / context2d.hpp / context3d.hpp / │ path.hpp / paint.hpp / font.hpp / texture.hpp / resource.hpp / │ command_list2d.hpp / command_list3d.hpp / geometry.hpp / │ material.hpp / render_target.hpp / renderer.hpp ├── src/ │ ├── core/ # platform-independent logic (namespace tinygfx) │ │ ├── device / context2d / context3d / backend / backend3d │ │ ├── command_list2d / command_list3d / path / paint / font │ │ ├── thread_pool # CPU row-level parallel rasterization │ │ ├── lru_cache # bounded derived-resource caches │ │ └── gpu/ # shared by the self-rasterized GPU backends │ │ └── tess.{h,cc} # CPU tessellation, no GPU dependency │ ├── c_api/ # extern "C" bridge only (no logic) │ └── backends/ │ ├── cpu/ gdip/ d2d/ quartz2d/ cairo/ # 2D-only backends │ ├── d3d/ # D3D11 plumbing shared by D2D and DX11 │ ├── dx11/ # 2D + 3D (Windows) │ └── gl/ # 2D + 3D (Win/WGL, Linux/EGL, macOS/CGL) ├── tests/ │ ├── unit/ renderdiff/ benchmark/ │ └── renderdiff/scene3d.* # 3D interop / replay invariants ├── examples/ │ ├── demo/ targets/ integration/ scene3d/ ├── 3rd/ # tinywind (examples), doctest (tests), stb ├── res/fonts/ # vendored demo/test font (Smiley Sans, OFL) └── docs/ project/ user/ ``` ## Supported Features ### 2D (v0.1, all seven backends) - **Command list** — clear, save/restore, matrix, clip rect and path stacks, fill/stroke path / rect / round rect - **Paths** — moveTo/lineTo/quadTo/cubicTo/close, shape builders, winding & even-odd rules, arcTo, addPath / reverse / transform, bounds, hit tests - **Paints** — solid, linear/radial gradients, opacity, stroke width / cap / join, dash + dash offset, miter limit, per-paint antialias - **Bitmap & texture** — `draw_bitmap`, bitmap patterns, unified `texture` with in-place `update()`, `draw_image` (CLAMP/REPEAT/MIRROR × NEAREST/LINEAR) - **Text** — TTF/OTF from memory (vendored stb_truetype), glyph outlines through the AA polygon pipeline, UTF-8, baseline, per-glyph advance; **layout metrics** (`tinygfx_font_measure_text` / `tinygfx_font_glyph_positions`) share the recorder's decoder and advance order, so measured width always equals drawn width - **CPU backend** — scanline rasterizer with **row-level parallelism** (see `docs/project/thread-pool.md`), 5 blend modes, AA - **Render targets** — BGRA32 offscreen, window-bound, external-texture interop, configurable MSAA sample count (`create_render_target_ex`), borrowed `get_pixels` - **Present** — Win32 / macOS / Linux X11 + Wayland, selected by `platformId` ### 3D (DX11 and OpenGL backends) - `context3d` as capability handle; `tinygfx_backend_supports3d()` predicate - Geometry (vertex layouts, index buffers, in-place `update`), six built-in materials (unlit / textured / lambert / phong / wireframe / normal_vis) - `command_list3d`: clear (color/depth/stencil), camera, viewport, scissor, draw - Offscreen RT + depth, window target with depth, `color_texture` interop, color readback; 3D→2D (`draw_image`) and 2D→3D (`material_set_texture`) are the same `tinygfx_texture` type - NDC z ∈ [0,1], right-handed Y-up world; **BGRA8 UNORM targets with straight alpha**. The DX11 / GL 3D path encodes to sRGB on write (see [color-management.md](docs/project/color-management.md) §6.2) so 3D matches the 2D colour-management work (§6.4); HDR / wide-gamut support remains unplanned (see [product-scope.md](docs/project/product-scope.md) P2-3) - **Custom 3D shaders** — `context3d_create_shader` / `material_set_shader`, one source per backend (GLSL 330 core VS+FS, HLSL SM4.0 with two entry points). SPIR-V is deliberately **not** an input; see [custom-shader.md](docs/project/custom-shader.md). `tools/shader_cross` (opt-in `--tools=y`) translates the GLSL half into the HLSL half offline, so one `tinygfx_shader_desc` works on both backends — see [shader-cross.md](docs/project/shader-cross.md). - `BUILD_2D` / `BUILD_3D` compile gating; all three macro combinations are buildable and pass the unit tests - 3D pixel regression: two tol-0 invariants (`3d[interop]`, `3d[replay]`) plus committed per-backend/driver/platform scene signatures under `res/*.sig` ### Not yet implemented / known gaps - **Text**: shaping (kerning, ligatures, complex scripts), BiDi, line breaking / paragraph layout, font fallback, glyph atlas / SDF. Today: single-run UTF-8 → glyph outlines with per-glyph advance, plus layout metrics (total advance, ascent/descent/lineGap, ink box, per-codepoint pen positions and byte offsets) - **Backends**: Vulkan has an opt-in **M1 2D path** (`xmake f --vulkan=y`): fills, gradients, strokes, text, bitmap patterns, MSAA, path clips and draw batching are implemented; OVERLAY returns `NOT_IMPLEMENTED`, and the non-NORMAL blend modes still blend in linear light (GL/DX11 use the stored domain) — see [vulkan-backend.md](docs/project/vulkan-backend.md) §13. Metal / DX12 / WebGPU are declared slots only - **2D**: custom shaders, instancing / batch control, partial command-list updates, cross-backend AA consistency contract, asynchronous asset loading. Colour management (linear-space blending + sRGB encoding) is **implemented for the CPU / D2D / DX11 / OpenGL backends** (A1 + A2); **GDI+ and Cairo are legacy references with no linear blending**, and **Quartz2D is blocked on macOS 10.13** (no usable float-linear CG context) — see [color-management.md](docs/project/color-management.md) §7.5 - **3D**: picking / depth readback, multi-viewport camera stack, runtime material editing, mesh index updates, instancing, stencil test control, compute / MRT / multi-pass - **Platform**: per-monitor DPI, Wayland fractional scale and GPU window target, translucent present on Cocoa / Wayland Out of scope by design (not planned): scene graph, animation/skinning, asset formats/loaders, culling/LOD, light manager, heavyweight 3D (thousands of draw calls), runtime shader translation — see [design-2d3d.md](docs/project/design-2d3d.md) §2.3. P3 (custom 3D shaders) is **done** and is part of the v0.1 API surface above. Full capability matrix with acceptance criteria and phasing: [product-scope.md](docs/project/product-scope.md). Status history: [roadmap.md](docs/project/roadmap.md); current renderdiff baselines: [backend-alignment.md](docs/project/backend-alignment.md). ## Design Principles 1. Explicit over implicit — no chaining, every call returns its `Error`. 2. Pure C ABI stable, C++ wrapper optional. 3. Record once, render many — command lists are data, not callbacks. 4. Opaque handles — no internal leakage in public header. 5. Backends are interchangeable — the public API never mentions a GPU API. 6. The renderer never assumes the window system — present takes raw handles + `platformId`. 7. No custom type aliases (`tv_u8` etc.) — use standard C types directly. 8. Naming: C API prefix `tinygfx_`, internal namespace `tinygfx`, C++ wrapper namespace `tg`. Enum-macro style aligned with tinywind (`TV_ENUM` / `TV_CENUM_COMPARE`; the macro names predate the rename and stay for source compatibility with tinywind's convention). 9. **Design first** — any design decision lands in a formal doc under `docs/project/` before code changes. ## Engineering Conventions Followed from the tinyflow / tinywind project conventions: 1. `tinygfx_*` API is implemented **only** in the `src/c_api/` bridge files — all wrapped in `extern "C" { ... }`. The bridge only converts handles, validates arguments and maps exceptions to error codes (pure forwarding); any business logic — format conversion, pixel snapshots, geometry/sampling algorithms — lives in core or the owning backend. 2. Internal implementation has its own headers, split by module into multiple files; one file must not implement several unrelated features. 3. Keep files small; group a module's files into a directory if many (tests mirror `src/`). 4. Platform-specific code lives in per-platform files (`{win32,linux,cocoa}/`); the raster cores are platform-free. 5. `extern "C"` present bridges never throw (MSVC `/EHc`) — they return `bool`, the C++ caller converts failure to an exception. 6. Enum constants live in C enums; ABI struct fields that hold enum values are guarded by `static_assert(sizeof(enum) == 4)` in the wrapper. 7. Correctness gate: `tinygfx_test_unit` plus `tinygfx_test_renderdiff` (the eight 2D cell diff counts must match the recorded per-driver baseline, and the two 3D invariants must be `0 / 307200`). The 3D scene also has committed compact signatures under `res/renderdiff_3d_*.sig`; `xmake run tinygfx_test_renderdiff --3d-only` gates on them plus the invariants without needing fonts or a window. On a new driver, record once with `--update-3d-baseline` from the repo root (see `docs/project/design-2d3d.md`, "3D pixel regression"). ## License BSD 2-Clause. See [LICENSE](LICENSE). Bundled third-party components and their licenses: [THIRD_PARTY.md](THIRD_PARTY.md).