From b4703dee83c2522b97f816eed40d40bdf1f18770 Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:24:57 +0530 Subject: [PATCH 1/5] maximize button --- CHANGELOG.md | 1 + kit/intern/kit_window_win32.c | 5 +++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ca2cafd..a5ba6a3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -187,6 +187,7 @@ All notable changes to **blenderui** (BUI). The format follows - Out-of-range `rgb()` channels clamp (`rgb(300 -20 0)` is red) instead of being gamut-mapped. - `:nth-last-child(An+B of S)` counts the following siblings that match `S` (it saw none, since they aren't built when rules match; `S` may name the element's ancestors). - `light-dark()`, the system colors (`Canvas`, `LinkText` ...) and `@media (prefers-color-scheme)` follow the theme's mode (they were always dark). Light mode uses a browser's light system colors. Windows re-render when the theme changes, with no `notify_all()` needed. +- **Windows: the system's maximize button maximizes again.** The kit took every press on a maximize button as the app's, so on a window with the system's title bar the press went to the app and Windows never maximized; only a title bar the app draws (`WindowDecorations::Client`) hands its maximize button's presses to the app now. - **Android: the app runs again after Back.** The host's state (`g_quit`, the wake callback, keep-alive, the stop check) starts over on each `BK_android_attach`, so a relaunch in the same process is not a dead window; the activity is `singleTask`, so a second launch brings the running one back instead of attaching a second activity. `BK_android_detach` (new; `android_main` calls it before the glue frees the app) ends wakes from other threads, which used the freed looper. A Lua script that fails after opening its window shows its error (the error window came back NULL and crashed). A second finger joining a one-finger scroll no longer jumps it; `BK_window_timer` returns -1 (not 0) when the window's timers are full, as `BUI_kit.h` says; a failed window allocation returns NULL (the C demo checks it); a frame whose post fails is redrawn. `build.py` aligns the APK with `zipalign 4` (the libraries are deflated: `-P 16` aligned nothing and failed on build-tools 34) and builds a Rust app's crate with `--lib`. - **WebAssembly: an unstyled canvas keeps its size after a zoom.** At a pixel ratio of 1 its CSS size was not pinned, so after a zoom or a move to a retina screen it grew on every frame; every resize now sizes the backing store and pins it. `build.py --serve` serves `.wasm` and `.js` with their web types on Windows (the override was set on a `functools.partial`, where it did nothing). The wasm workflow runs on changes to the kit, the GPU raster, core and blenderui too, and the smoke test's click check compares against the hovered button, so it can fail. - **QuickJS (`bui run`, `bui build`, Android `--js`): timers set from promise jobs run.** A `setTimeout` made in a `.then` was missed (a headless app quit with it pending, a windowed one stalled until the next event); timers now run one task at a time with the promise jobs after each, as in HTML's event loop, and the next deadline is read after the last job. A pump that runs out of rounds with work left schedules the next one. `setTimeout(f, Infinity)` (or `NaN`, negative, past 2^31-1 ms) is a 0 ms delay, as in browsers, instead of panicking the runtime. diff --git a/kit/intern/kit_window_win32.c b/kit/intern/kit_window_win32.c index 0a2360a8..66d050d1 100644 --- a/kit/intern/kit_window_win32.c +++ b/kit/intern/kit_window_win32.c @@ -930,7 +930,8 @@ static LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) case WM_NCMOUSEMOVE: case WM_NCLBUTTONDOWN: case WM_NCLBUTTONDBLCLK: - if (wp == HTMAXBUTTON) { /* the app's maximize button: its pointer, as the client's */ + /* the app's maximize button: its pointer, as the client's (the system's stays the system's) */ + if (wp == HTMAXBUTTON && win->override == 2) { POINT pt = {GET_X_LPARAM(lp), GET_Y_LPARAM(lp)}; ScreenToClient(hwnd, &pt); if (msg == WM_NCMOUSEMOVE) { @@ -950,7 +951,7 @@ static LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) } break; case WM_SETCURSOR: - if (LOWORD(lp) == HTCLIENT || LOWORD(lp) == HTMAXBUTTON) { + if (LOWORD(lp) == HTCLIENT || (LOWORD(lp) == HTMAXBUTTON && win->override == 2)) { SetCursor(cursor_handle(win->cursor)); return TRUE; } From 3f203891d6d20d9b9a669a7cee781f9edb8b3f85 Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:25:20 +0530 Subject: [PATCH 2/5] d3d12 backend --- CHANGELOG.md | 2 + bindings/rust/blenderui-sys/src/lib.rs | 11 + bindings/rust/blenderui/src/window.rs | 38 +- gpu/CMakeLists.txt | 7 +- gpu/include/GPU_raster.h | 24 + gpu/intern/gpu_d3d11.c | 2436 +++-------------- gpu/intern/gpu_d3d11.h | 13 +- gpu/intern/gpu_d3d12.c | 1474 ++++++++++ gpu/intern/gpu_device.c | 1578 +++++++++++ gpu/intern/gpu_device.h | 274 ++ gpu/intern/gpu_dx.c | 200 ++ gpu/intern/gpu_dx.h | 60 + gpu/intern/gpu_gl.c | 6 + gpu/intern/gpu_raster.c | 54 + gpu/tests/CMakeLists.txt | 9 + gpu/tests/test_gpu_api.h | 26 + gpu/tests/test_gpu_effect.c | 3 +- gpu/tests/test_gpu_parity.c | 9 +- gpu/tests/test_raster_alpha.c | 3 +- .../src/content/docs/concepts/rendering.mdx | 3 +- .../docs/reference/environment-variables.mdx | 6 +- 21 files changed, 4171 insertions(+), 2065 deletions(-) create mode 100644 gpu/intern/gpu_d3d12.c create mode 100644 gpu/intern/gpu_device.c create mode 100644 gpu/intern/gpu_device.h create mode 100644 gpu/intern/gpu_dx.c create mode 100644 gpu/intern/gpu_dx.h create mode 100644 gpu/tests/test_gpu_api.h diff --git a/CHANGELOG.md b/CHANGELOG.md index a5ba6a3e..a74f51f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to **blenderui** (BUI). The format follows ## [Unreleased] ### Added +- **Windows: a Direct3D 12 renderer, opt-in.** `Application::gpu_api(GpuApi::D3d12)` (C: `BUI_gpu_set_api`), `BUI_GPU_API=d3d12` or `bui build --gpu d3d12` start the GPU renderer on Direct3D 12; Direct3D 11 stays the default, and a device that can't start on 12 starts on 11. Both backends now share one core (`gpu/intern/gpu_device.c`) and fill a table of 15 device operations; the frames they draw are byte-identical. Direct3D 12 costs about 0.4 to 1 ms more CPU per presented frame here, so it is for apps that embed BUI in Direct3D 12 or profile it with Nsight's GPU Trace. `BUI_GPU_DEBUG=2` turns on the Direct3D 12 debug layer. +- **Windows: `BUI_GPU_ADAPTER=high-performance` renders on the discrete GPU.** Direct3D took the display's adapter, on a hybrid laptop the integrated GPU, where NVIDIA Nsight and other vendor profilers see nothing; this asks DXGI for the high-performance one (`EnumAdapterByGpuPreference`). The default stays the display's GPU, which uses less power. - **Android: real apps in Rust.** `blenderui::android_main!(run)` writes the entry point the NativeActivity shell calls, so the app crate has no `unsafe`; before `run` it gives the activity's JNI handles to `ndk-context` (cpal and other crates that call into Java need them) and sends stdout, stderr and panics to logcat (tag `bui`). The kit points `HOME` at the app's files folder and `XDG_CACHE_HOME` / `TMPDIR` at its cache folder on attach (`dirs::cache_dir()` worked nowhere), and `BK_android_activity()` gives the `ANativeActivity *`. `build.py` takes `--label`, `--package` and `--permission` (repeatable: `INTERNET` for an app that goes online) and links the system libraries the Rust staticlib needs (rustc's `native-static-libs`, through `cargo rustc`, so dependencies don't build again): an app that plays sound through cpal links AAudio. Characters Roboto lacks come from the phone's Noto fonts (`/system/fonts`, `/product/fonts` in the font folders). SpotiTube's Android build is the first app that uses it. - **Back on Android walks back through an app's screens.** `App::prevent_default()` in a key listener marks the key as taken (`BK_key_taken` in C, for any binding that sees raw key events): `BK_key` returns 1 and nothing else acts on it. Back is the key `Escape`, so a listener that closes a screen on it keeps the app open, and only a Back that nothing took finishes the activity. - **WebAssembly frames copy twice as fast.** The kit's pixels become the canvas's RGBA bytes in a loop the compiler vectorizes: a 1280 x 800 redraw drops from about 10 ms to 5 ms under Node.js. `examples/wasm/bench.mjs` times it. diff --git a/bindings/rust/blenderui-sys/src/lib.rs b/bindings/rust/blenderui-sys/src/lib.rs index c0821d06..7caff02d 100644 --- a/bindings/rust/blenderui-sys/src/lib.rs +++ b/bindings/rust/blenderui-sys/src/lib.rs @@ -99,6 +99,11 @@ pub const BK_EFFECT_MAX_INPUTS: usize = 8; pub const BUI_TARGET_RGBA8: c_int = 0; pub const BUI_TARGET_RGBA16F: c_int = 1; pub const BUI_TARGET_RGBA32F: c_int = 2; +/// GPU renderer graphics APIs (`BuiGpuApi`, `BUI_gpu_set_api`): Windows picks Direct3D 11 or 12. +pub const BUI_GPU_API_DEFAULT: c_int = 0; +pub const BUI_GPU_API_D3D11: c_int = 1; +pub const BUI_GPU_API_D3D12: c_int = 2; +pub const BUI_GPU_API_OPENGL: c_int = 3; pub const BK_EFFECT_MAX_FLOATS: usize = 256; pub const BK_EFFECT_MAX_SOURCE: usize = 65536; @@ -537,6 +542,12 @@ unsafe extern "C" { pub fn BUI_gpu_default() -> c_int; pub fn BUI_gpu_set_slug(on: c_int); pub fn BUI_gpu_slug() -> c_int; + /// The graphics API new GPU devices start on (`BUI_GPU_API_*`; the `BUI_GPU_API` variable overrides). + pub fn BUI_gpu_set_api(api: c_int); + /// What new devices start on: `BUI_GPU_API`, else `BUI_gpu_set_api`, else the baked default, else Direct3D 11. + pub fn BUI_gpu_api() -> c_int; + /// The API a raster's device runs on (after any fall back); `BUI_GPU_API_DEFAULT` on the CPU. + pub fn BUI_raster_gpu_api(r: *const BuiRaster) -> c_int; pub fn BK_window_set_gpu(win: *mut BKWindow, on: c_int); pub fn BK_window_gpu(win: *mut BKWindow) -> c_int; pub fn BUI_text_add_font(family: *const c_char, flags: c_int, data: *const c_void, diff --git a/bindings/rust/blenderui/src/window.rs b/bindings/rust/blenderui/src/window.rs index 97479ede..c260f9f1 100644 --- a/bindings/rust/blenderui/src/window.rs +++ b/bindings/rust/blenderui/src/window.rs @@ -236,10 +236,29 @@ pub struct WindowOptions { pub window_decorations: WindowDecorations, } +/// The GPU renderer's graphics API on Windows (Linux has OpenGL only: there this is ignored). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum GpuApi { + /// Direct3D 11, the default. + D3d11, + /// Direct3D 12. A device that cannot start on it starts on Direct3D 11. + D3d12, +} + +impl GpuApi { + const fn raw(self) -> c_int { + match self { + Self::D3d11 => sys::BUI_GPU_API_D3D11, + Self::D3d12 => sys::BUI_GPU_API_D3D12, + } + } +} + /// The application entry point (gpui's `Application`). pub struct Application { headless: bool, gpu: Option, + gpu_api: Option, slug: Option, keep_alive: bool, theme: Option, @@ -254,10 +273,10 @@ impl Default for Application { impl Application { /// Native windows. pub fn new() -> Application { - Application { headless: false, gpu: None, slug: None, keep_alive: false, theme: None } + Application { headless: false, gpu: None, gpu_api: None, slug: None, keep_alive: false, theme: None } } - /// Draw every window on the GPU (Direct3D 11 on Windows): the same + /// Draw every window on the GPU (Direct3D 11 on Windows, or 12: [`Application::gpu_api`]): the same /// pixels as the software raster, with rasterization off the CPU. Falls /// back to software where no device exists. The `BUI_GPU` environment /// variable (1/0) overrides this. @@ -266,6 +285,15 @@ impl Application { self } + /// The graphics API the GPU renderer uses on Windows: [`GpuApi::D3d11`] (the default) or + /// [`GpuApi::D3d12`], which falls back to Direct3D 11 where it cannot start. The + /// `BUI_GPU_API` environment variable (`d3d11`/`d3d12`) overrides this; without either, a + /// default baked into the executable (`bui` CLI) applies, then Direct3D 11. + pub fn gpu_api(mut self, api: GpuApi) -> Application { + self.gpu_api = Some(api); + self + } + /// How the GPU renderer draws text: `true` for Slug (glyph outlines in /// the pixel shader, sharp at any size), `false` for a per-glyph bitmap /// atlas like Blender's (less GPU work). Defaults to the `slug` feature; @@ -292,7 +320,7 @@ impl Application { /// Off-screen windows (tests, screenshots, CI): nothing is shown, the /// `simulate_*` and `draw` methods drive it. pub fn headless() -> Application { - Application { headless: true, gpu: None, slug: None, keep_alive: false, theme: None } + Application { headless: true, gpu: None, gpu_api: None, slug: None, keep_alive: false, theme: None } } /// The kit's global settings for this application (renderer, text, theme, off-screen scale). @@ -300,6 +328,10 @@ impl Application { if let Some(on) = self.gpu { unsafe { sys::BUI_gpu_set_default(on as c_int) }; } + if let Some(api) = self.gpu_api { + // SAFETY: sets a global choice, read when a device is created. + unsafe { sys::BUI_gpu_set_api(api.raw()) }; + } if let Some(on) = self.slug { crate::set_slug(on); } diff --git a/gpu/CMakeLists.txt b/gpu/CMakeLists.txt index e9f7d2d6..0c1d8885 100644 --- a/gpu/CMakeLists.txt +++ b/gpu/CMakeLists.txt @@ -10,7 +10,12 @@ set(SRC intern/gpu_raster.c intern/gpu_fonts.c # font folders, families by name, fallback fonts per script intern/gpu_effect.c # the registry and dialect of application shaders (BUI_effect_*) - intern/gpu_d3d11.c # without BUI_GPU (features.json), the stubs that keep rasters on the CPU + # the GPU renderer on Windows: the API-independent core (without BUI_GPU, features.json, the + # stubs that keep rasters on the CPU) over a Direct3D 11 or 12 backend, picked per device + intern/gpu_device.c + intern/gpu_dx.c # what the Direct3D backends share + intern/gpu_d3d11.c + intern/gpu_d3d12.c ) add_library(bui_gpu STATIC ${SRC}) diff --git a/gpu/include/GPU_raster.h b/gpu/include/GPU_raster.h index fcf4d9f9..fdb39910 100644 --- a/gpu/include/GPU_raster.h +++ b/gpu/include/GPU_raster.h @@ -337,6 +337,30 @@ int BUI_raster_is_gpu(const BuiRaster *r); * BUI_GPU environment variable (1/0). Off by default. */ void BUI_gpu_set_default(int on); int BUI_gpu_default(void); +/* The graphics API of the GPU renderer on Windows (Linux has OpenGL only). Direct3D 11 is the + * default; Direct3D 12 is opt-in, and a device that cannot start on it starts on Direct3D 11. */ +typedef enum BuiGpuApi { + BUI_GPU_API_DEFAULT = 0, /* no choice: what comes next in the order below */ + BUI_GPU_API_D3D11 = 1, + BUI_GPU_API_D3D12 = 2, + BUI_GPU_API_OPENGL = 3, /* what BUI_raster_gpu_api says on Linux */ +} BuiGpuApi; +/* The app's choice for devices created from now on (BUI_GPU_API_DEFAULT clears it; other values + * are ignored). */ +void BUI_gpu_set_api(BuiGpuApi api); +/* The API new devices start on, first of: the BUI_GPU_API environment variable ("d3d11" or + * "d3d12"; anything else is ignored, with a message under BUI_GPU_DEBUG=1), BUI_gpu_set_api(), + * the default baked into the program (below), Direct3D 11. */ +BuiGpuApi BUI_gpu_api(void); +/* The API raster `r`'s device runs on (after any fall back); BUI_GPU_API_DEFAULT when it draws on + * the CPU. */ +BuiGpuApi BUI_raster_gpu_api(const BuiRaster *r); +/* The baked default: a fixed-size marker in the program's data that tools may patch in a built + * executable (the `bui` CLI does). It is exactly BUI_GPU_API_MARKER_LEN bytes: the ASCII text + * "BUIGPUAPI=d3d11" (or "BUIGPUAPI=d3d12") followed by NUL bytes, so the patch is a same-length + * replacement of "d3d11" by "d3d12". Any other value after the '=' means no baked default. */ +#define BUI_GPU_API_MARKER "BUIGPUAPI=d3d11" +#define BUI_GPU_API_MARKER_LEN 32 /* How the GPU renderer draws text: 1 = Slug (glyph outlines evaluated in the * pixel shader; sharp at any size), 0 = per-glyph bitmap atlas (Blender's * approach; less GPU work). Takes effect on the next frame. Without a choice diff --git a/gpu/intern/gpu_d3d11.c b/gpu/intern/gpu_d3d11.c index 47ad1d20..5f8d9976 100644 --- a/gpu/intern/gpu_d3d11.c +++ b/gpu/intern/gpu_d3d11.c @@ -1,339 +1,94 @@ -/* BUI GPU renderer: Direct3D 11 backend — see gpu_d3d11.h. +/* BUI GPU renderer: the Direct3D 11 backend of gpu_device.c (the default on Windows). * - * Like Blender's widget drawing (interface_widgets.cc batches widget bases - * into GPU_SHADER_2D_WIDGET_BASE_INST draws), every primitive becomes one - * instance of a single uber-shader, so a frame of thousands of widgets and - * text runs is a handful of DrawInstanced calls. Differences from Blender, - * for a retained UI: - * - frames render into a persistent target: only damaged regions are - * redrawn (the kit's damage tracking) and the swap chain gets dirty rects, - * so the compositor only recomposes what changed; - * - text is pre-shaped glyph runs (the same masks the software raster draws) - * packed into one R8 atlas, images into one BGRA atlas; - * - the device is created on a worker thread so the first frame never waits - * for the driver (the software raster draws until it is ready). + * Every primitive is one instance of the uber-shader in gpu/shaders/bui_ui.hlsl, drawn with + * DrawInstanced into a persistent render target; present copies the damaged rects into a + * flip-model swap chain (a bitblt one for alpha windows) and presents them as dirty rects. * * SPDX-License-Identifier: GPL-2.0-or-later */ #if defined(_WIN32) && defined(BUI_GPU) /* BUI_GPU: features.json */ -# ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN -# endif # define COBJMACROS -# include +# include "gpu_dx.h" + # include # include -# include # include # include # include -# include "GPU_raster.h" -# include "gpu_d3d11.h" -# include "gpu_d3d11_shaders.h" -# include "gpu_effect.h" - static const GUID k_IID_IDXGIDevice = { 0x54ec77fa, 0x1377, 0x44e6, {0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}}; -static const GUID k_IID_IDXGIFactory2 = { - 0x50c83a1c, 0xe072, 0x4c48, {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0}}; static const GUID k_IID_ID3D11Texture2D = { 0x6f15aaf2, 0xd208, 0x4e89, {0x9a, 0xb4, 0x48, 0x95, 0x35, 0xd3, 0x4f, 0x9c}}; static const GUID k_IID_ID3D11DeviceContext1 = { 0xbb2c6faa, 0xb5fb, 0x4082, {0x8e, 0x6b, 0x38, 0x8b, 0x8c, 0xfa, 0x90, 0xe1}}; -# define REL(p) \ - do { \ - if (p) { \ - IUnknown_Release((IUnknown *)(p)); \ - (p) = NULL; \ - } \ - } while (0) - -/* -------------------------------------------------------------------- */ -/** \name Atlases (shelf packing) - * \{ */ - -# define SHELVES 128 - -typedef struct Atlas { - int size; - int bpp; /* 1 (R8) or 4 (BGRA8) */ +struct BuiGpuTex { ID3D11Texture2D *tex; ID3D11ShaderResourceView *srv; - int shelf_y[SHELVES], shelf_h[SHELVES], shelf_x[SHELVES]; - int nshelves, next_y; -} Atlas; - -/* cache entry: key -> placement */ -typedef struct Slot { - uint64_t k1, k2; /* 0 = empty */ - int x, y; -} Slot; - -# define MASK_MAP 16384 /* power of two */ -# define MASK_MAP_FILL 12000 -# define IMG_MAP 1024 -# define IMG_MAP_FILL 700 - -/* Slug glyph data: curves (2 RGBA32F texels each) and bands (RG32_UINT - * texels), both addressed linearly over 4096-wide textures. */ -# define SLUG_W 4096 -# define SLUG_H 64 -# define SLUG_MAP 8192 /* power of two */ -# define SLUG_MAP_FILL 6000 -# define SLUG_MAX_BANDS 16 - -typedef struct SlugGlyph { - uint32_t key; /* (face + 1) << 16 | glyph; 0 = empty */ - int ok; /* 0: empty glyph */ - float bbox[4], band[4]; - int loc[4]; -} SlugGlyph; - -typedef struct Batch { - int tri; /* 0: quad instances, 1: triangles, 2: textured mesh (indexed), 3: one effect draw - * (first: its FxCall) */ - int first, count; - int img; /* quads: the RGBA texture their images sample (-1 none yet, 0 atlas, n: big[n - 1]) */ - /* meshes: texture (0: white), sampler, scissor x0 y0 x1 y1 */ - int tex, nearest; - int clip[4]; -} Batch; - -/* An image too big for the atlas, or a video frame, in a texture of its own. */ -# define BIG_MAX 32 -# define BIG_BUDGET ((size_t)256 << 20) /* bytes of big-image textures kept */ -# define BIG_IDLE 120 /* frames unused before one is freed */ -typedef struct BigTex { - uint64_t key, base; /* 0 = empty */ - int w, h; - int format; /* BUI_PIXMAP_*: NV12 is luma in tex, chroma in uv_tex */ - int stream; /* `base` is a stream: its frames update the textures in place */ - unsigned used; /* the frame it was last drawn in */ - ID3D11Texture2D *tex, *uv_tex; - ID3D11ShaderResourceView *srv, *uv_srv; -} BigTex; - -/* A registry texture (BUI_texture_*) on this device, by registry slot. */ -typedef struct DevTex { - int id; /* 0 = empty */ - unsigned gen; - int w, h; - ID3D11Texture2D *tex; - ID3D11ShaderResourceView *srv; - ID3D11RenderTargetView *rtv; /* a render target (BUI_target_create): effects draw into it */ -} DevTex; - -typedef struct TriV { - float x, y; - float c[4]; - float clip[4]; -} TriV; + ID3D11RenderTargetView *rtv; /* BUI_TEX_TARGET */ +}; -/* An effect (gpu_effect.h) on this device, by registry slot: compiled on first use. */ -typedef struct DevFx { - int id; /* 0 = empty */ - int failed; /* compiling it failed: the log is the effect's error */ - int n_inputs, n_floats; +struct BuiGpuProg { ID3D11VertexShader *vs; ID3D11PixelShader *ps; - ID3D11Buffer *cb; /* b1: box, 2 / target size, then one register per float */ -} DevFx; - -/* One recorded effect draw. */ -typedef struct FxCall { - int effect; /* 0: not a draw but a clear of `dst` (its 4 floats at `floats`) */ - int dst; /* 0: the frame; else the render target it draws into */ - float rect[4]; - int inputs[BUI_EFFECT_MAX_INPUTS]; - int clip[4]; - int floats; /* where its n_floats of the effect are in BuiGpu.fxf */ -} FxCall; - -struct BuiGpu { - HWND hwnd; - volatile LONG state; /* 0 pending, 1 ready, -1 failed */ - HANDLE thread; + ID3D11Buffer *cb; /* b1: BuiGpuFxConsts */ +}; +typedef struct D11 { ID3D11Device *dev; ID3D11DeviceContext *ctx; + ID3D11DeviceContext1 *ctx1; /* alpha frames: ClearView clears the rects of a redrawn region */ IDXGIFactory2 *factory; IDXGISwapChain1 *swap; - int sw, sh; /* swap chain size */ - /* alpha: frames keep premultiplied alpha. The swap chain is a bitblt one (DWM blur-behind - * shows its alpha, as in SDL) and ClearView clears the rects of a redrawn region. */ - int alpha; - ID3D11DeviceContext1 *ctx1; - int swap_fresh; - ID3D11VertexShader *vs_quad, *vs_tri, *vs_mesh; - ID3D11PixelShader *ps_quad, *ps_tri, *ps_mesh; - ID3D11InputLayout *il_quad, *il_tri, *il_mesh; - ID3D11Buffer *cb, *ib, *tb, *mvb, *mib; - UINT ib_cap, tb_cap, mvb_cap, mib_cap; /* in elements */ + /* by batch kind (bui_dx_programs) */ + ID3D11VertexShader *vs[BUI_DX_PROGRAMS]; + ID3D11PixelShader *ps[BUI_DX_PROGRAMS]; + ID3D11InputLayout *il[BUI_DX_PROGRAMS]; + ID3D11Buffer *cb, *vb[BUI_DX_PROGRAMS], *mib; /* vertex data by batch kind, mesh indices */ + UINT vb_cap[BUI_DX_PROGRAMS], mib_cap; /* in elements */ ID3D11BlendState *blend; ID3D11RasterizerState *rs, *rs_scissor; ID3D11SamplerState *smp_linear, *smp_point; - ID3D11Texture2D *white_tex; /* 1x1 white: meshes without a texture */ - ID3D11ShaderResourceView *white_srv; - DevTex *dtex; - int n_dtex; - unsigned dtex_free_gen; - DevFx *dfx; - int n_dfx; - unsigned dfx_free_gen; ID3D11Texture2D *target; ID3D11RenderTargetView *rtv; - int tw, th; /* target texture size (>= the frame) */ - int fw, fh; /* the frame size the target holds */ - int w, h; /* frame size */ - - Atlas mask, rgba; - BigTex big[BIG_MAX]; - size_t big_bytes; - unsigned frame, forget_seen; - int max_tex; /* the feature level's largest texture side */ - Slot *mask_map, *img_map; - int mask_n, img_n; - unsigned mask_gen; - - int slug; /* -1: off (env or unavailable), 0: not created yet, 1: ready */ - ID3D11Texture2D *curve_tex, *band_tex; - ID3D11ShaderResourceView *curve_srv, *band_srv; - SlugGlyph *slug_map; - int slug_n, curve_next, band_next; - unsigned slug_gen; - - BuiGpuInst *inst; - int n_inst, cap_inst; - TriV *tv; - int n_tv, cap_tv; - BuiMeshVertex *mv; - int n_mv, cap_mv; - uint32_t *mi; - int n_mi, cap_mi; - FxCall *fx; - int n_fx, cap_fx; - float *fxf; - int n_fxf, cap_fxf; - Batch *b; - int n_b, cap_b; - - RECT dmg[16]; - int n_dmg, dmg_full; - /* the last present's damage (whole: the whole frame): with two flip buffers, the buffer being - * drawn is two frames old, so it needs this frame's damage and that one's, not everything */ - RECT prev[16]; - int n_prev, prev_whole; -}; - -static int atlas_create(BuiGpu *g, Atlas *a, int size, int bpp) -{ - memset(a, 0, sizeof(*a)); - a->size = size; - a->bpp = bpp; - D3D11_TEXTURE2D_DESC td = {0}; - td.Width = td.Height = (UINT)size; - td.MipLevels = td.ArraySize = 1; - td.Format = bpp == 1 ? DXGI_FORMAT_R8_UNORM : DXGI_FORMAT_B8G8R8A8_UNORM; - td.SampleDesc.Count = 1; - td.Usage = D3D11_USAGE_DEFAULT; - td.BindFlags = D3D11_BIND_SHADER_RESOURCE; - if (FAILED(ID3D11Device_CreateTexture2D(g->dev, &td, NULL, &a->tex))) { - return 0; - } - if (FAILED(ID3D11Device_CreateShaderResourceView(g->dev, (ID3D11Resource *)a->tex, NULL, - &a->srv))) - { - REL(a->tex); - return 0; - } - return 1; -} + int tw, th; +} D11; -static void atlas_clear(Atlas *a) -{ - a->nshelves = 0; - a->next_y = 0; -} - -/* Finds room for w x h (+1 px gutter). 0 when full. */ -static int atlas_place(Atlas *a, int w, int h, int *r_x, int *r_y) -{ - const int pw = w + 1, ph = h + 1; - if (pw > a->size || ph > a->size) { - return 0; - } - int best = -1; - for (int i = 0; i < a->nshelves; i++) { - if (a->shelf_h[i] >= ph && a->shelf_h[i] <= ph + ph / 4 + 2 && a->shelf_x[i] + pw <= a->size && - (best < 0 || a->shelf_h[i] < a->shelf_h[best])) - { - best = i; - } - } - if (best < 0) { - const int sh = (ph + 3) & ~3; /* round up: more strings share a shelf */ - if (a->nshelves == SHELVES || a->next_y + sh > a->size) { - return 0; - } - best = a->nshelves++; - a->shelf_y[best] = a->next_y; - a->shelf_h[best] = sh; - a->shelf_x[best] = 0; - a->next_y += sh; - } - *r_x = a->shelf_x[best]; - *r_y = a->shelf_y[best]; - a->shelf_x[best] += pw; - return 1; -} +# define DEV(g) ((D11 *)(g)->dev) -static void atlas_upload(BuiGpu *g, Atlas *a, int x, int y, int w, int h, const void *data, - int pitch) +static DXGI_FORMAT dxgi_format(BuiGpuFormat fmt) { - D3D11_BOX box = {(UINT)x, (UINT)y, 0, (UINT)(x + w), (UINT)(y + h), 1}; - ID3D11DeviceContext_UpdateSubresource(g->ctx, (ID3D11Resource *)a->tex, 0, &box, data, - (UINT)pitch, 0); + static const DXGI_FORMAT map[] = { + DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, + DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT, + DXGI_FORMAT_R32G32_UINT, + }; + return map[fmt]; } -/** \} */ - /* -------------------------------------------------------------------- */ /** \name Device (worker thread) * \{ */ -static void dfx_release(DevFx *f) -{ - REL(f->vs); - REL(f->ps); - REL(f->cb); - memset(f, 0, sizeof(*f)); -} - typedef HRESULT(WINAPI *CreateDeviceFn)(IDXGIAdapter *, D3D_DRIVER_TYPE, HMODULE, UINT, const D3D_FEATURE_LEVEL *, UINT, UINT, ID3D11Device **, D3D_FEATURE_LEVEL *, ID3D11DeviceContext **); -/* BUI_GPU_DEBUG=1: why the GPU path wasn't taken */ -static int fail(const char *what, HRESULT hr) +static int d11_init(BuiGpu *g) { - const char *dbg = getenv("BUI_GPU_DEBUG"); - if (dbg && dbg[0] == '1') { - fprintf(stderr, "bui gpu: %s failed (0x%08lx)\n", what, (unsigned long)hr); + D11 *d = (D11 *)calloc(1, sizeof(D11)); + if (!d) { + return 0; } - return 0; -} - -static int device_init(BuiGpu *g) -{ + g->dev = d; HMODULE dll = LoadLibraryW(L"d3d11.dll"); if (!dll) { - return fail("loading d3d11.dll", 0); + return bui_gpu_fail("loading d3d11.dll", 0); } CreateDeviceFn create = (CreateDeviceFn)(void *)GetProcAddress(dll, "D3D11CreateDevice"); if (!create) { @@ -344,1340 +99,229 @@ static int device_init(BuiGpu *g) const char *warp = getenv("BUI_GPU_WARP"); const D3D_DRIVER_TYPE type = (warp && warp[0] == '1') ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE; + /* an explicit adapter takes D3D_DRIVER_TYPE_UNKNOWN */ + IDXGIAdapter *pref = type == D3D_DRIVER_TYPE_HARDWARE ? bui_dx_preferred_adapter() : NULL; + const D3D_DRIVER_TYPE driver = pref ? D3D_DRIVER_TYPE_UNKNOWN : type; D3D_FEATURE_LEVEL got; - HRESULT hr = create(NULL, type, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT, levels, 4, - D3D11_SDK_VERSION, &g->dev, &got, &g->ctx); - if (FAILED(hr)) { /* 11_1 unknown to the runtime: retry without it */ - hr = create(NULL, type, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT, levels + 1, 3, - D3D11_SDK_VERSION, &g->dev, &got, &g->ctx); - } - if (FAILED(hr)) { - return fail("D3D11CreateDevice", hr); - } - if (g->alpha && FAILED(hr = ID3D11DeviceContext_QueryInterface(g->ctx, &k_IID_ID3D11DeviceContext1, - (void **)&g->ctx1))) - { - return fail("ID3D11DeviceContext1", hr); /* Windows 8: ClearView */ - } - g->max_tex = got >= D3D_FEATURE_LEVEL_11_0 ? D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION : 8192; - const char *max_env = getenv("BUI_GPU_MAX_TEXTURE"); /* tests: force tiling */ - if (max_env && atoi(max_env) >= 64) { - g->max_tex = atoi(max_env) < g->max_tex ? atoi(max_env) : g->max_tex; - } - IDXGIDevice *xd = NULL; - IDXGIAdapter *ad = NULL; - if (FAILED(ID3D11Device_QueryInterface(g->dev, &k_IID_IDXGIDevice, (void **)&xd)) || - FAILED(IDXGIDevice_GetAdapter(xd, &ad)) || - FAILED(IDXGIAdapter_GetParent(ad, &k_IID_IDXGIFactory2, (void **)&g->factory))) - { - REL(ad); - REL(xd); - return fail("DXGI factory", 0); - } - REL(ad); - REL(xd); - - ID3D11Device *d = g->dev; - if (FAILED(ID3D11Device_CreateVertexShader(d, g_vs_quad, sizeof(g_vs_quad), NULL, &g->vs_quad)) || - FAILED(ID3D11Device_CreatePixelShader(d, g_ps_quad, sizeof(g_ps_quad), NULL, &g->ps_quad)) || - FAILED(ID3D11Device_CreateVertexShader(d, g_vs_tri, sizeof(g_vs_tri), NULL, &g->vs_tri)) || - FAILED(ID3D11Device_CreatePixelShader(d, g_ps_tri, sizeof(g_ps_tri), NULL, &g->ps_tri)) || - FAILED(ID3D11Device_CreateVertexShader(d, g_vs_mesh, sizeof(g_vs_mesh), NULL, &g->vs_mesh)) || - FAILED(ID3D11Device_CreatePixelShader(d, g_ps_mesh, sizeof(g_ps_mesh), NULL, &g->ps_mesh))) - { - return fail("shaders", 0); - } -# define INST(name, idx, off) \ - {name, idx, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, off, D3D11_INPUT_PER_INSTANCE_DATA, 1} - const D3D11_INPUT_ELEMENT_DESC il_quad[] = { - INST("RECT", 0, 0), INST("BOUNDS", 0, 16), INST("COLOR", 0, 32), INST("COLOR", 1, 48), - INST("COLOR", 2, 64), INST("COLOR", 3, 80), INST("PARAMS", 0, 96), INST("EXTRA", 0, 112), - }; -# undef INST - const D3D11_INPUT_ELEMENT_DESC il_tri[] = { - {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"CLIP", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0}, - }; - const D3D11_INPUT_ELEMENT_DESC il_mesh[] = { /* BuiMeshVertex (= ImDrawVert) */ - {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0}, - {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0}, - }; - if (FAILED(ID3D11Device_CreateInputLayout(d, il_quad, 8, g_vs_quad, sizeof(g_vs_quad), - &g->il_quad)) || - FAILED(ID3D11Device_CreateInputLayout(d, il_tri, 3, g_vs_tri, sizeof(g_vs_tri), &g->il_tri)) || - FAILED(ID3D11Device_CreateInputLayout(d, il_mesh, 3, g_vs_mesh, sizeof(g_vs_mesh), - &g->il_mesh))) - { - return fail("input layouts", 0); - } - D3D11_BUFFER_DESC bd = {0}; - bd.ByteWidth = 16; - bd.Usage = D3D11_USAGE_DYNAMIC; - bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; - bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - if (FAILED(ID3D11Device_CreateBuffer(d, &bd, NULL, &g->cb))) { - return fail("constant buffer", 0); - } - D3D11_BLEND_DESC bl = {0}; - bl.RenderTarget[0].BlendEnable = TRUE; - bl.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; - bl.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; - bl.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; - bl.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; - bl.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; - bl.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; - bl.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; - if (FAILED(ID3D11Device_CreateBlendState(d, &bl, &g->blend))) { - return fail("blend state", 0); - } - D3D11_RASTERIZER_DESC rd = {0}; - rd.FillMode = D3D11_FILL_SOLID; - rd.CullMode = D3D11_CULL_NONE; - rd.DepthClipEnable = TRUE; - if (FAILED(ID3D11Device_CreateRasterizerState(d, &rd, &g->rs))) { - return fail("rasterizer state", 0); - } - rd.ScissorEnable = TRUE; /* meshes: the draw command's clip */ - if (FAILED(ID3D11Device_CreateRasterizerState(d, &rd, &g->rs_scissor))) { - return fail("rasterizer state", 0); - } - D3D11_SAMPLER_DESC sd = {0}; - sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; - sd.AddressU = sd.AddressV = sd.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; - sd.MaxLOD = D3D11_FLOAT32_MAX; - sd.ComparisonFunc = D3D11_COMPARISON_ALWAYS; - if (FAILED(ID3D11Device_CreateSamplerState(d, &sd, &g->smp_linear))) { - return fail("sampler", 0); - } - sd.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; - if (FAILED(ID3D11Device_CreateSamplerState(d, &sd, &g->smp_point))) { - return fail("sampler", 0); - } - { - const uint32_t white = 0xFFFFFFFFu; - D3D11_TEXTURE2D_DESC wd = {0}; - wd.Width = wd.Height = 1; - wd.MipLevels = wd.ArraySize = 1; - wd.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - wd.SampleDesc.Count = 1; - wd.Usage = D3D11_USAGE_DEFAULT; - wd.BindFlags = D3D11_BIND_SHADER_RESOURCE; - D3D11_SUBRESOURCE_DATA init = {&white, 4, 4}; - if (FAILED(ID3D11Device_CreateTexture2D(d, &wd, &init, &g->white_tex)) || - FAILED(ID3D11Device_CreateShaderResourceView(d, (ID3D11Resource *)g->white_tex, NULL, - &g->white_srv))) - { - return fail("white texture", 0); - } - } - if (!atlas_create(g, &g->mask, 2048, 1)) { - return fail("atlas", 0); - } - return 1; -} - -static DWORD WINAPI device_thread(void *arg) -{ - BuiGpu *g = (BuiGpu *)arg; - const int ok = device_init(g); - InterlockedExchange(&g->state, ok ? 1 : -1); - return 0; -} - -BuiGpu *bui_gpu_create(void *hwnd, int alpha) -{ - BuiGpu *g = (BuiGpu *)calloc(1, sizeof(BuiGpu)); - if (!g) { - return NULL; - } - g->hwnd = (HWND)hwnd; - g->alpha = alpha; - g->mask_map = (Slot *)calloc(MASK_MAP, sizeof(Slot)); - g->img_map = (Slot *)calloc(IMG_MAP, sizeof(Slot)); - g->thread = CreateThread(NULL, 0, device_thread, g, 0, NULL); - if (!g->thread || !g->mask_map || !g->img_map) { - if (g->thread) { - WaitForSingleObject(g->thread, INFINITE); - CloseHandle(g->thread); - g->thread = NULL; - } - bui_gpu_free(g); - return NULL; - } - return g; -} - -int bui_gpu_state(BuiGpu *g, int wait) -{ - if (wait && g->thread) { - WaitForSingleObject(g->thread, INFINITE); - } - const LONG s = InterlockedCompareExchange(&g->state, 0, 0); - if (s != 0 && g->thread) { - WaitForSingleObject(g->thread, INFINITE); - CloseHandle(g->thread); - g->thread = NULL; - } - return (int)s; -} - -void bui_gpu_free(BuiGpu *g) -{ - if (!g) { - return; - } - if (g->thread) { - WaitForSingleObject(g->thread, INFINITE); - CloseHandle(g->thread); - } - if (g->ctx) { - ID3D11DeviceContext_ClearState(g->ctx); - } - REL(g->mask.srv); - REL(g->mask.tex); - REL(g->rgba.srv); - REL(g->rgba.tex); - for (int i = 0; i < BIG_MAX; i++) { - REL(g->big[i].srv); - REL(g->big[i].tex); - REL(g->big[i].uv_srv); - REL(g->big[i].uv_tex); - } - REL(g->curve_srv); - REL(g->curve_tex); - REL(g->band_srv); - REL(g->band_tex); - for (int i = 0; i < g->n_dtex; i++) { - REL(g->dtex[i].srv); - REL(g->dtex[i].tex); - } - free(g->dtex); - for (int i = 0; i < g->n_dfx; i++) { - dfx_release(&g->dfx[i]); - } - free(g->dfx); - free(g->fx); - free(g->fxf); - REL(g->white_srv); - REL(g->white_tex); - REL(g->smp_linear); - REL(g->smp_point); - REL(g->rs_scissor); - REL(g->mvb); - REL(g->mib); - REL(g->il_mesh); - REL(g->vs_mesh); - REL(g->ps_mesh); - REL(g->rtv); - REL(g->target); - REL(g->rs); - REL(g->blend); - REL(g->cb); - REL(g->ib); - REL(g->tb); - REL(g->il_quad); - REL(g->il_tri); - REL(g->vs_quad); - REL(g->vs_tri); - REL(g->ps_quad); - REL(g->ps_tri); - REL(g->swap); - REL(g->factory); - REL(g->ctx1); - REL(g->ctx); - REL(g->dev); - free(g->inst); - free(g->tv); - free(g->mv); - free(g->mi); - free(g->b); - free(g->mask_map); - free(g->img_map); - free(g->slug_map); - free(g); -} - -/** \} */ - -/* -------------------------------------------------------------------- */ -/** \name Recording - * \{ */ - -static void flush(BuiGpu *g); - -static void big_sweep(BuiGpu *g); - -void bui_gpu_begin(BuiGpu *g, int w, int h) -{ - g->w = w > 0 ? w : 1; - g->h = h > 0 ? h : 1; - g->frame++; - big_sweep(g); -} - -static Batch *batch_new(BuiGpu *g, int tri, int first); - -/* The batch to append to: the last one when it is of the same kind. */ -static Batch *batch_for(BuiGpu *g, int tri, int first) -{ - if (tri < 2 && g->n_b > 0 && g->b[g->n_b - 1].tri == tri) { - return &g->b[g->n_b - 1]; - } - return batch_new(g, tri, first); -} - -static Batch *batch_new(BuiGpu *g, int tri, int first) -{ - if (g->n_b == g->cap_b) { - const int cap = g->cap_b ? g->cap_b * 2 : 64; - Batch *nb = (Batch *)realloc(g->b, sizeof(Batch) * (size_t)cap); - if (!nb) { - return NULL; - } - g->b = nb; - g->cap_b = cap; - } - Batch *b = &g->b[g->n_b++]; - memset(b, 0, sizeof(*b)); - b->tri = tri; - b->first = first; - b->img = -1; - return b; -} - -/* -- textured meshes ----------------------------------------------------------- */ - -static void dtex_release(DevTex *t) -{ - REL(t->rtv); - REL(t->srv); - REL(t->tex); - t->id = 0; -} - -/* The DXGI format of a render target (BUI_TARGET_*). */ -static DXGI_FORMAT target_format(int target) -{ - switch (target - 1) { - case BUI_TARGET_RGBA16F: - return DXGI_FORMAT_R16G16B16A16_FLOAT; - case BUI_TARGET_RGBA32F: - return DXGI_FORMAT_R32G32B32A32_FLOAT; - default: - return DXGI_FORMAT_R8G8B8A8_UNORM; - } -} - -/* Creates or refreshes the device copy of registry texture `id`. */ -static ID3D11ShaderResourceView *dtex_get(BuiGpu *g, int id) -{ - BuiTexView v; - if (id <= 0 || !bui_texture_view(id, &v)) { - return g->white_srv; - } - const int slot = (id & 0xFFFF) - 1; - if (slot >= g->n_dtex) { - const int n = slot + 16; - DevTex *nd = (DevTex *)realloc(g->dtex, sizeof(DevTex) * (size_t)n); - if (!nd) { - return g->white_srv; - } - memset(nd + g->n_dtex, 0, sizeof(DevTex) * (size_t)(n - g->n_dtex)); - g->dtex = nd; - g->n_dtex = n; - } - DevTex *t = &g->dtex[slot]; - if (t->id == id && t->gen == v.gen) { - return t->srv; - } - if (t->id == id && t->w == v.w && t->h == v.h) { - /* updated: draws recorded so far still need the old pixels */ - flush(g); - int rects[32][4]; - int n = bui_texture_changes(id, t->gen, rects, 32); - if (n < 0) { - rects[0][0] = rects[0][1] = 0; - rects[0][2] = v.w; - rects[0][3] = v.h; - n = 1; - } - for (int i = 0; i < n; i++) { - const int *r = rects[i]; - D3D11_BOX box = {(UINT)r[0], (UINT)r[1], 0, (UINT)(r[0] + r[2]), (UINT)(r[1] + r[3]), 1}; - ID3D11DeviceContext_UpdateSubresource(g->ctx, (ID3D11Resource *)t->tex, 0, &box, - v.rgba + ((size_t)r[1] * v.w + r[0]) * 4, - (UINT)v.w * 4, 0); - } - t->gen = v.gen; - return t->srv; - } - if (t->id) { - flush(g); - dtex_release(t); - } - D3D11_TEXTURE2D_DESC td = {0}; - td.Width = (UINT)v.w; - td.Height = (UINT)v.h; - td.MipLevels = td.ArraySize = 1; - td.Format = v.target ? target_format(v.target) : DXGI_FORMAT_R8G8B8A8_UNORM; - td.SampleDesc.Count = 1; - td.Usage = D3D11_USAGE_DEFAULT; - td.BindFlags = D3D11_BIND_SHADER_RESOURCE | (v.target ? D3D11_BIND_RENDER_TARGET : 0); - D3D11_SUBRESOURCE_DATA init = {v.rgba, (UINT)v.w * 4, 0}; - /* a render target starts as zeros (a texture made without data is undefined: it is cleared) */ - if (FAILED(ID3D11Device_CreateTexture2D(g->dev, &td, v.target ? NULL : &init, &t->tex)) || - FAILED(ID3D11Device_CreateShaderResourceView(g->dev, (ID3D11Resource *)t->tex, NULL, - &t->srv)) || - (v.target && - FAILED(ID3D11Device_CreateRenderTargetView(g->dev, (ID3D11Resource *)t->tex, NULL, - &t->rtv)))) - { - dtex_release(t); - return g->white_srv; - } - if (t->rtv) { - const float zero[4] = {0, 0, 0, 0}; - ID3D11DeviceContext_ClearRenderTargetView(g->ctx, t->rtv, zero); - } - t->id = id; - t->gen = v.gen; - t->w = v.w; - t->h = v.h; - return t->srv; -} - -/* The device texture a recorded batch samples (already made by dtex_get). */ -static ID3D11ShaderResourceView *dtex_srv(BuiGpu *g, int id) -{ - const int slot = (id & 0xFFFF) - 1; - if (id > 0 && slot < g->n_dtex && g->dtex[slot].id == id && g->dtex[slot].srv) { - return g->dtex[slot].srv; - } - return g->white_srv; -} - -/* Frees device copies of textures freed in the registry. */ -static void dtex_sweep(BuiGpu *g) -{ - const unsigned fg = bui_texture_free_gen(); - if (fg == g->dtex_free_gen) { - return; - } - g->dtex_free_gen = fg; - BuiTexView v; - for (int i = 0; i < g->n_dtex; i++) { - if (g->dtex[i].id && !bui_texture_view(g->dtex[i].id, &v)) { - flush(g); - dtex_release(&g->dtex[i]); - } - } -} - -static int grow(void **p, int *cap, int need, size_t size) -{ - if (need <= *cap) { - return 1; - } - int c = *cap ? *cap : 4096; - while (c < need) { - c *= 2; - } - void *np = realloc(*p, size * (size_t)c); - if (!np) { - return 0; - } - *p = np; - *cap = c; - return 1; -} - -void bui_gpu_mesh(BuiGpu *g, - const BuiMeshVertex *vtx, - int n_vtx, - const void *idx, - int idx32, - int n_idx, - float ox, - float oy, - int tex, - int nearest, - const int clip[4]) -{ - n_idx -= n_idx % 3; - if (n_idx <= 0 || n_vtx <= 0) { - return; - } - dtex_sweep(g); - dtex_get(g, tex); /* may flush: before anything of this mesh is recorded */ - if (!grow((void **)&g->mv, &g->cap_mv, g->n_mv + n_vtx, sizeof(BuiMeshVertex)) || - !grow((void **)&g->mi, &g->cap_mi, g->n_mi + n_idx, sizeof(uint32_t))) - { - return; - } - Batch *b = NULL; - if (g->n_b > 0) { /* same texture, sampler and clip: one draw */ - Batch *last = &g->b[g->n_b - 1]; - if (last->tri == 2 && last->tex == tex && last->nearest == nearest && - memcmp(last->clip, clip, sizeof(int[4])) == 0) - { - b = last; - } - } - if (!b) { - b = batch_for(g, 2, g->n_mi); - if (!b) { - return; - } - b->tex = tex; - b->nearest = nearest; - memcpy(b->clip, clip, sizeof(int[4])); - } - const uint32_t base = (uint32_t)g->n_mv; - for (int i = 0; i < n_vtx; i++) { - BuiMeshVertex *v = &g->mv[g->n_mv++]; - *v = vtx[i]; - v->x += ox; - v->y += oy; - } - const uint16_t *i16 = (const uint16_t *)idx; - const uint32_t *i32 = (const uint32_t *)idx; - uint32_t *out = g->mi + g->n_mi; - int n = 0; - for (int i = 0; i < n_idx; i += 3) { - const uint32_t a = idx32 ? i32[i] : i16[i], c1 = idx32 ? i32[i + 1] : i16[i + 1], - c2 = idx32 ? i32[i + 2] : i16[i + 2]; - if (a >= (uint32_t)n_vtx || c1 >= (uint32_t)n_vtx || c2 >= (uint32_t)n_vtx) { - continue; - } - out[n++] = base + a; - out[n++] = base + c1; - out[n++] = base + c2; - } - g->n_mi += n; - b->count += n; -} - -/* Appends an instance to quad batch `b`. */ -static BuiGpuInst *inst_in(BuiGpu *g, Batch *b, int kind, int x0, int y0, int x1, int y1); - -BuiGpuInst *bui_gpu_inst_image(BuiGpu *g, int tex, int x0, int y0, int x1, int y1) -{ - Batch *b = g->n_b > 0 ? &g->b[g->n_b - 1] : NULL; - if (!b || b->tri != 0 || (b->img >= 0 && b->img != tex)) { - b = batch_new(g, 0, g->n_inst); /* another texture: another draw */ - } - if (!b) { - return NULL; - } - b->img = tex; - return inst_in(g, b, BG_IMAGE, x0, y0, x1, y1); -} - -BuiGpuInst *bui_gpu_inst(BuiGpu *g, int kind, int x0, int y0, int x1, int y1) -{ - Batch *b = batch_for(g, 0, g->n_inst); - return b ? inst_in(g, b, kind, x0, y0, x1, y1) : NULL; -} - -static BuiGpuInst *inst_in(BuiGpu *g, Batch *b, int kind, int x0, int y0, int x1, int y1) -{ - if (g->n_inst == g->cap_inst) { - const int cap = g->cap_inst ? g->cap_inst * 2 : 1024; - BuiGpuInst *ni = (BuiGpuInst *)realloc(g->inst, sizeof(BuiGpuInst) * (size_t)cap); - if (!ni) { - return NULL; - } - g->inst = ni; - g->cap_inst = cap; - } - b->count++; - BuiGpuInst *in = &g->inst[g->n_inst++]; - memset(in, 0, sizeof(*in)); - in->bounds[0] = (float)x0; - in->bounds[1] = (float)y0; - in->bounds[2] = (float)x1; - in->bounds[3] = (float)y1; - in->p[0] = (float)kind; - return in; -} - -void bui_gpu_triangles(BuiGpu *g, - const float (*co)[2], - const float (*col)[4], - int count, - const int clip[4]) -{ - count -= count % 3; - if (count <= 0) { - return; - } - if (g->n_tv + count > g->cap_tv) { - int cap = g->cap_tv ? g->cap_tv : 1024; - while (cap < g->n_tv + count) { - cap *= 2; - } - TriV *nt = (TriV *)realloc(g->tv, sizeof(TriV) * (size_t)cap); - if (!nt) { - return; - } - g->tv = nt; - g->cap_tv = cap; - } - Batch *b = batch_for(g, 1, g->n_tv); - if (!b) { - return; - } - for (int i = 0; i < count; i++) { - TriV *v = &g->tv[g->n_tv++]; - v->x = co[i][0]; - v->y = co[i][1]; - memcpy(v->c, col[i], sizeof(v->c)); - for (int k = 0; k < 4; k++) { - v->clip[k] = (float)clip[k]; - } - } - b->count += count; -} - -/* -- effects (application shaders) -------------------------------------------------- */ - -typedef HRESULT(WINAPI *D3DCompileFn)(LPCVOID, SIZE_T, LPCSTR, const D3D_SHADER_MACRO *, - ID3DInclude *, LPCSTR, LPCSTR, UINT, UINT, ID3DBlob **, - ID3DBlob **); - -/* d3dcompiler_47.dll (Windows 8.1 and later ship it) is loaded when the first effect is drawn: - * nothing links against it and no SDK is needed. System folder first, then the app's own. */ -static D3DCompileFn g_d3d_compile; - -static BOOL CALLBACK d3d_compiler_load(PINIT_ONCE once, PVOID param, PVOID *ctx) -{ - (void)once; - (void)param; - (void)ctx; - HMODULE m = LoadLibraryExW(L"d3dcompiler_47.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); - if (!m) { - m = LoadLibraryExW(L"d3dcompiler_47.dll", NULL, LOAD_LIBRARY_SEARCH_APPLICATION_DIR); - } - if (m) { - g_d3d_compile = (D3DCompileFn)(void *)GetProcAddress(m, "D3DCompile"); - } - return TRUE; -} - -/* Loaded once, whichever thread draws the first effect (devices of several windows or tests - * compile at the same time): another thread waits for the load rather than seeing it unfinished. */ -static D3DCompileFn d3d_compiler(void) -{ - static INIT_ONCE once = INIT_ONCE_STATIC_INIT; - InitOnceExecuteOnce(&once, d3d_compiler_load, NULL, NULL); - return g_d3d_compile; -} - -/* One stage of the assembled source; on failure the compiler's text goes to `log`. */ -static ID3DBlob *fx_stage(D3DCompileFn compile, const char *src, const char *name, - const char *entry, const char *target, char *log, size_t log_n) -{ - ID3DBlob *code = NULL, *err = NULL; - const HRESULT hr = compile(src, strlen(src), name, NULL, NULL, entry, target, - (1u << 15) /* D3DCOMPILE_OPTIMIZATION_LEVEL3 */, 0, &code, &err); - if (FAILED(hr)) { - snprintf(log, log_n, "%.*s", - err ? (int)ID3D10Blob_GetBufferSize(err) : 0, - err ? (const char *)ID3D10Blob_GetBufferPointer(err) : "compile failed"); - REL(code); - } - REL(err); - return FAILED(hr) ? NULL : code; -} - -/* Compiles `v` for this device; false (with the log) when it fails. */ -static int fx_build(BuiGpu *g, const BuiEffectView *v, DevFx *f, char *log, size_t log_n) -{ - D3DCompileFn compile = d3d_compiler(); - if (!compile) { - snprintf(log, log_n, "d3dcompiler_47.dll is not available: the effect cannot run on this system"); - return 0; - } - char *src = bui_effect_assemble(BUI_FX_HLSL, v); - if (!src) { - snprintf(log, log_n, "out of memory"); - return 0; - } - ID3DBlob *psb = fx_stage(compile, src, v->name, "bui_ps", "ps_4_0", log, log_n); - free(src); - ID3DBlob *vsb = psb ? fx_stage(compile, bui_fx_hlsl_vs, "effect_vs", "bui_vs", "vs_4_0", log, log_n) : NULL; - int ok = 0; - if (vsb) { - D3D11_BUFFER_DESC bd = {0}; - bd.ByteWidth = (UINT)(sizeof(float) * (8 + 4 * (size_t)(v->n_floats > 0 ? v->n_floats : 1))); - bd.Usage = D3D11_USAGE_DYNAMIC; - bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; - bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - ok = SUCCEEDED(ID3D11Device_CreateVertexShader(g->dev, ID3D10Blob_GetBufferPointer(vsb), - ID3D10Blob_GetBufferSize(vsb), NULL, &f->vs)) && - SUCCEEDED(ID3D11Device_CreatePixelShader(g->dev, ID3D10Blob_GetBufferPointer(psb), - ID3D10Blob_GetBufferSize(psb), NULL, &f->ps)) && - SUCCEEDED(ID3D11Device_CreateBuffer(g->dev, &bd, NULL, &f->cb)); - if (!ok) { - snprintf(log, log_n, "the device rejected the compiled shader"); - } - } - REL(vsb); - REL(psb); - return ok; -} - -/* The device's pipeline of effect `v`, compiled on first use. NULL: no room. */ -static DevFx *dfx_get(BuiGpu *g, const BuiEffectView *v) -{ - const int slot = BUI_EFFECT_SLOT(v->id); - if (slot >= g->n_dfx) { - const int n = slot + 8; - DevFx *nd = (DevFx *)realloc(g->dfx, sizeof(DevFx) * (size_t)n); - if (!nd) { - return NULL; - } - memset(nd + g->n_dfx, 0, sizeof(DevFx) * (size_t)(n - g->n_dfx)); - g->dfx = nd; - g->n_dfx = n; - } - DevFx *f = &g->dfx[slot]; - if (f->id == v->id) { - return f; - } - if (f->id) { /* a freed effect's slot, reused */ - flush(g); - dfx_release(f); - } - char log[BUI_EFFECT_LOG] = ""; - f->id = v->id; - f->n_inputs = v->n_inputs; - f->n_floats = v->n_floats; - if (!fx_build(g, v, f, log, sizeof(log))) { - dfx_release(f); - f->id = v->id; - f->failed = 1; - fail(log, 0); - } - bui_effect_set_error(v->id, log); - return f; -} - -/* Frees the pipelines of effects freed in the registry. */ -static void dfx_sweep(BuiGpu *g) -{ - const unsigned fg = bui_effect_free_gen(); - if (fg == g->dfx_free_gen) { - return; - } - g->dfx_free_gen = fg; - BuiEffectView v; - for (int i = 0; i < g->n_dfx; i++) { - if (g->dfx[i].id && !bui_effect_view(g->dfx[i].id, &v)) { - flush(g); - dfx_release(&g->dfx[i]); - } - } -} - -/* The device texture `id` is, once dtex_get made it (NULL: not live here). */ -static DevTex *dtex_dev(BuiGpu *g, int id) -{ - const int slot = (id & 0xFFFF) - 1; - return id > 0 && slot >= 0 && slot < g->n_dtex && g->dtex[slot].id == id ? &g->dtex[slot] : NULL; -} - -int bui_gpu_effect(BuiGpu *g, - int dst, - int effect, - const float rect[4], - const int inputs[BUI_EFFECT_MAX_INPUTS], - const float *floats, - int n_floats, - const int clip[4]) -{ - BuiEffectView v; - if (!bui_effect_view(effect, &v)) { - return 0; - } - dfx_sweep(g); - DevFx *f = dfx_get(g, &v); - if (!f || f->failed) { - return 0; - } - dtex_sweep(g); - if (dst) { - dtex_get(g, dst); - const DevTex *d = dtex_dev(g, dst); - if (!d || !d->rtv) { - return 0; /* not a render target, or the device could not make it */ - } - for (int k = 0; k < v.n_inputs; k++) { - if (inputs[k] == dst) { - return 0; /* a pass cannot sample the target it draws into */ - } - } - } - for (int k = 0; k < v.n_inputs; k++) { - dtex_get(g, inputs[k]); /* may flush: before anything of this draw is recorded */ - } - if (!grow((void **)&g->fx, &g->cap_fx, g->n_fx + 1, sizeof(FxCall)) || - !grow((void **)&g->fxf, &g->cap_fxf, g->n_fxf + v.n_floats, sizeof(float))) - { - return 0; - } - Batch *b = batch_new(g, 3, g->n_fx); /* never merged: each draw has its own shader state */ - if (!b) { - return 0; - } - b->count = 1; - FxCall *c = &g->fx[g->n_fx++]; - c->effect = effect; - c->dst = dst; - memcpy(c->rect, rect, sizeof(c->rect)); - memcpy(c->inputs, inputs, sizeof(c->inputs)); - memcpy(c->clip, clip, sizeof(c->clip)); - c->floats = g->n_fxf; - const int n = floats && n_floats > 0 ? (n_floats < v.n_floats ? n_floats : v.n_floats) : 0; - if (n > 0) { - memcpy(g->fxf + g->n_fxf, floats, sizeof(float) * (size_t)n); - } - memset(g->fxf + g->n_fxf + n, 0, sizeof(float) * (size_t)(v.n_floats - n)); - g->n_fxf += v.n_floats; - return 1; -} - -int bui_gpu_target_clear(BuiGpu *g, int target, const float rgba[4]) -{ - dtex_sweep(g); - dtex_get(g, target); - const DevTex *d = dtex_dev(g, target); - if (!d || !d->rtv || !grow((void **)&g->fx, &g->cap_fx, g->n_fx + 1, sizeof(FxCall)) || - !grow((void **)&g->fxf, &g->cap_fxf, g->n_fxf + 4, sizeof(float))) - { - return 0; - } - Batch *b = batch_new(g, 3, g->n_fx); - if (!b) { - return 0; - } - b->count = 1; - FxCall *c = &g->fx[g->n_fx++]; - memset(c, 0, sizeof(*c)); - c->dst = target; /* effect 0: a clear */ - c->floats = g->n_fxf; - memcpy(g->fxf + g->n_fxf, rgba, sizeof(float) * 4); - g->n_fxf += 4; - return 1; -} - -static uint64_t mix64(uint64_t h) -{ - h ^= h >> 33; - h *= 0xff51afd7ed558ccdull; - h ^= h >> 33; - return h; -} - -static void mask_reset(BuiGpu *g) -{ - flush(g); /* recorded instances still point into the old layout */ - atlas_clear(&g->mask); - memset(g->mask_map, 0, sizeof(Slot) * MASK_MAP); - g->mask_n = 0; -} - -int bui_gpu_mask(BuiGpu *g, const void *key, unsigned gen, const uint8_t *mask, int w, int h, - int *r_x, int *r_y) -{ - if (w + 1 > g->mask.size || h + 1 > g->mask.size) { - return 0; - } - if (gen != g->mask_gen) { /* text runs were freed: their keys may be reused */ - g->mask_gen = gen; - mask_reset(g); - } - const uint64_t k1 = key ? (uint64_t)(uintptr_t)key : 0, k2 = ((uint64_t)w << 32) | (uint32_t)h; - uint32_t idx = 0; - if (key) { - idx = (uint32_t)mix64(k1) & (MASK_MAP - 1); - for (;;) { - Slot *s = &g->mask_map[idx]; - if (s->k1 == 0) { - break; - } - if (s->k1 == k1 && s->k2 == k2) { - *r_x = s->x; - *r_y = s->y; - return 1; - } - idx = (idx + 1) & (MASK_MAP - 1); - } - if (g->mask_n >= MASK_MAP_FILL) { - mask_reset(g); - return bui_gpu_mask(g, key, gen, mask, w, h, r_x, r_y); - } - } - int x, y; - if (!atlas_place(&g->mask, w, h, &x, &y)) { - mask_reset(g); /* empty now, and the map slot must be found again */ - return bui_gpu_mask(g, key, gen, mask, w, h, r_x, r_y); - } - atlas_upload(g, &g->mask, x, y, w, h, mask, w); - if (key) { - Slot *s = &g->mask_map[idx]; - s->k1 = k1; - s->k2 = k2; - s->x = x; - s->y = y; - g->mask_n++; - } - *r_x = x; - *r_y = y; - return 1; -} - -/* -------------------------------------------------------------------- */ -/** \name Slug glyphs - * - * Eric Lengyel's Slug algorithm (https://github.com/EricLengyel/Slug): - * glyph outlines live on the GPU as quadratic curves, split into horizontal - * and vertical bands; the pixel shader casts a ray each way through the - * pixel's bands and integrates exact coverage. Resolution independent, one - * quad per glyph, no rasterizing or atlas packing on the CPU. - * \{ */ - -static int slug_tex(BuiGpu *g, DXGI_FORMAT fmt, ID3D11Texture2D **r_tex, - ID3D11ShaderResourceView **r_srv) -{ - D3D11_TEXTURE2D_DESC td = {0}; - td.Width = SLUG_W; - td.Height = SLUG_H; - td.MipLevels = td.ArraySize = 1; - td.Format = fmt; - td.SampleDesc.Count = 1; - td.Usage = D3D11_USAGE_DEFAULT; - td.BindFlags = D3D11_BIND_SHADER_RESOURCE; - return SUCCEEDED(ID3D11Device_CreateTexture2D(g->dev, &td, NULL, r_tex)) && - SUCCEEDED(ID3D11Device_CreateShaderResourceView(g->dev, (ID3D11Resource *)*r_tex, NULL, - r_srv)); -} - -int bui_gpu_slug_on(BuiGpu *g) -{ - if (g->slug == 0) { - g->slug = -1; - if (slug_tex(g, DXGI_FORMAT_R32G32B32A32_FLOAT, &g->curve_tex, &g->curve_srv) && - slug_tex(g, DXGI_FORMAT_R32G32_UINT, &g->band_tex, &g->band_srv) && - (g->slug_map = (SlugGlyph *)calloc(SLUG_MAP, sizeof(SlugGlyph))) != NULL) - { - g->slug = 1; - } - } - return g->slug > 0; -} - -static void slug_reset(BuiGpu *g) -{ - flush(g); /* recorded instances still point at the old data */ - memset(g->slug_map, 0, sizeof(SlugGlyph) * SLUG_MAP); - g->slug_n = g->curve_next = g->band_next = 0; -} - -/* Uploads `count` texels at linear index `at`, row by row. */ -static void slug_upload(BuiGpu *g, ID3D11Texture2D *tex, int at, const void *data, int count, - int texel) -{ - const char *p = (const char *)data; - while (count > 0) { - const int x = at % SLUG_W, y = at / SLUG_W; - const int n = count < SLUG_W - x ? count : SLUG_W - x; - D3D11_BOX box = {(UINT)x, (UINT)y, 0, (UINT)(x + n), (UINT)(y + 1), 1}; - ID3D11DeviceContext_UpdateSubresource(g->ctx, (ID3D11Resource *)tex, 0, &box, p, - (UINT)(n * texel), 0); - p += (size_t)n * texel; - at += n; - count -= n; - } -} - -typedef struct SlugSort { - float key; - uint32_t curve; -} SlugSort; - -static int slug_cmp(const void *a, const void *b) -{ - const float ka = ((const SlugSort *)a)->key, kb = ((const SlugSort *)b)->key; - return ka < kb ? 1 : ka > kb ? -1 : 0; /* descending */ -} - -static float min3(float a, float b, float c) -{ - return a < b ? (a < c ? a : c) : (b < c ? b : c); -} -static float max3(float a, float b, float c) -{ - return a > b ? (a > c ? a : c) : (b > c ? b : c); -} - -/* Builds and uploads a glyph's curve and band data. */ -static int slug_build(BuiGpu *g, SlugGlyph *sg, const float *cv, int n, const float bb[4]) -{ - const int nb = n < 8 ? 1 : (n / 4 < SLUG_MAX_BANDS ? n / 4 : SLUG_MAX_BANDS); - const float w = bb[2] - bb[0] > 1.0f ? bb[2] - bb[0] : 1.0f; - const float h = bb[3] - bb[1] > 1.0f ? bb[3] - bb[1] : 1.0f; - /* horizontal bands split y, vertical bands split x */ - const float hs = (float)nb / h, vs = (float)nb / w; - const float eps = 1.0f / 1024.0f * (w > h ? w : h); - - /* worst case every curve lands in every band */ - const int max_entries = 2 * nb * n; - const int need_band = 2 * nb + max_entries, need_curve = 2 * n; - if (need_curve > SLUG_W * SLUG_H / 4 || need_band > SLUG_W * SLUG_H / 4) { - return 0; /* absurd glyph */ + HRESULT hr = create(pref, driver, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT, levels, 4, + D3D11_SDK_VERSION, &d->dev, &got, &d->ctx); + if (FAILED(hr)) { /* 11_1 unknown to the runtime: retry without it */ + hr = create(pref, driver, NULL, D3D11_CREATE_DEVICE_BGRA_SUPPORT, levels + 1, 3, + D3D11_SDK_VERSION, &d->dev, &got, &d->ctx); } - if (g->curve_next + need_curve > SLUG_W * SLUG_H || g->band_next + need_band > SLUG_W * SLUG_H || - g->slug_n >= SLUG_MAP_FILL) - { - return -1; /* full: caller resets and retries */ + REL(pref); + if (FAILED(hr)) { + return bui_gpu_fail("D3D11CreateDevice", hr); } - float *ct = (float *)malloc(sizeof(float) * 8 * (size_t)n); - uint32_t *bt = (uint32_t *)malloc(sizeof(uint32_t) * 2 * (size_t)need_band); - SlugSort *tmp = (SlugSort *)malloc(sizeof(SlugSort) * (size_t)n); - if (!ct || !bt || !tmp) { - free(ct); - free(bt); - free(tmp); - return 0; + if (g->alpha && FAILED(hr = ID3D11DeviceContext_QueryInterface(d->ctx, &k_IID_ID3D11DeviceContext1, + (void **)&d->ctx1))) + { + return bui_gpu_fail("ID3D11DeviceContext1", hr); /* Windows 8: ClearView */ } - const int cbase = g->curve_next; /* even: a curve never straddles a row */ - for (int i = 0; i < n; i++) { - const float *q = cv + 6 * i; - float *t = ct + 8 * i; - t[0] = q[0]; - t[1] = q[1]; - t[2] = q[2]; - t[3] = q[3]; - t[4] = q[4]; - t[5] = q[5]; - t[6] = t[7] = 0.0f; + g->max_tex = got >= D3D_FEATURE_LEVEL_11_0 ? D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION : 8192; + IDXGIDevice *xd = NULL; + IDXGIAdapter *ad = NULL; + if (FAILED(ID3D11Device_QueryInterface(d->dev, &k_IID_IDXGIDevice, (void **)&xd)) || + FAILED(IDXGIDevice_GetAdapter(xd, &ad)) || + FAILED(IDXGIAdapter_GetParent(ad, &bui_IID_IDXGIFactory2, (void **)&d->factory))) + { + REL(ad); + REL(xd); + return bui_gpu_fail("DXGI factory", 0); } - const int bbase = g->band_next; - int at = 2 * nb; /* entries follow the 2 * nb headers */ - for (int dir = 0; dir < 2; dir++) { - for (int b = 0; b < nb; b++) { - /* band range in font units */ - const float s = dir == 0 ? hs : vs, o = dir == 0 ? bb[1] : bb[0]; - const float lo = o + (float)b / s - eps, hi = o + (float)(b + 1) / s + eps; - int m = 0; - for (int i = 0; i < n; i++) { - const float *q = cv + 6 * i; - /* dir 0 (horizontal rays) uses y extents, sorted by max x; dir 1 the reverse */ - const float a0 = dir == 0 ? q[1] : q[0], a1 = dir == 0 ? q[3] : q[2], - a2 = dir == 0 ? q[5] : q[4]; - const float amin = min3(a0, a1, a2), amax = max3(a0, a1, a2); - if (amax < lo || amin > hi || (a0 == a1 && a1 == a2)) { - continue; /* outside, or parallel to the ray: never crosses it */ - } - tmp[m].key = dir == 0 ? max3(q[0], q[2], q[4]) : max3(q[1], q[3], q[5]); - tmp[m].curve = (uint32_t)(cbase + 2 * i); - m++; - } - qsort(tmp, (size_t)m, sizeof(SlugSort), slug_cmp); - const int hdr = dir * nb + b; - bt[2 * hdr] = (uint32_t)m; - bt[2 * hdr + 1] = (uint32_t)(bbase + at); - for (int k = 0; k < m; k++) { - bt[2 * (at + k)] = tmp[k].curve; - bt[2 * (at + k) + 1] = 0; - } - at += m; + bui_dx_report("Direct3D 11", ad); + REL(ad); + REL(xd); + + ID3D11Device *dv = d->dev; + for (int i = 0; i < BUI_DX_PROGRAMS; i++) { + const BuiDxProgram *p = &bui_dx_programs[i]; + D3D11_INPUT_ELEMENT_DESC el[8]; + for (UINT k = 0; k < p->n_inputs; k++) { + const BuiDxInput *in = &p->inputs[k]; + const D3D11_INPUT_ELEMENT_DESC e = {in->semantic, in->index, in->format, 0, in->offset, + in->instanced ? D3D11_INPUT_PER_INSTANCE_DATA : + D3D11_INPUT_PER_VERTEX_DATA, + in->instanced}; + el[k] = e; + } + if (FAILED(ID3D11Device_CreateVertexShader(dv, p->vs, p->vs_size, NULL, &d->vs[i])) || + FAILED(ID3D11Device_CreatePixelShader(dv, p->ps, p->ps_size, NULL, &d->ps[i])) || + FAILED(ID3D11Device_CreateInputLayout(dv, el, p->n_inputs, p->vs, p->vs_size, &d->il[i]))) + { + return bui_gpu_fail("shaders", 0); } } - slug_upload(g, g->curve_tex, cbase, ct, 2 * n, 16); - slug_upload(g, g->band_tex, bbase, bt, at, 8); - g->curve_next += 2 * n; - g->band_next += at; - free(ct); - free(bt); - free(tmp); - memcpy(sg->bbox, bb, sizeof(float[4])); - sg->band[0] = hs; - sg->band[1] = -bb[1] * hs; - sg->band[2] = vs; - sg->band[3] = -bb[0] * vs; - sg->loc[0] = bbase; - sg->loc[1] = nb; - sg->loc[2] = nb; - sg->loc[3] = 0; - sg->ok = 1; - return 1; -} - -int bui_gpu_slug_glyph(BuiGpu *g, int face, int glyph, unsigned gen, float r_bbox[4], - float r_band[4], int r_loc[4]) -{ - if (g->slug <= 0 || face < 0 || face > 0x7ffe || glyph < 0 || glyph > 0xffff) { - return 0; + D3D11_BUFFER_DESC bd = {0}; + bd.ByteWidth = 16; + bd.Usage = D3D11_USAGE_DYNAMIC; + bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + if (FAILED(ID3D11Device_CreateBuffer(dv, &bd, NULL, &d->cb))) { + return bui_gpu_fail("constant buffer", 0); + } + D3D11_BLEND_DESC bl = {0}; + bl.RenderTarget[0].BlendEnable = TRUE; + bl.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; + bl.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; + bl.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + bl.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + bl.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; + bl.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + bl.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; + if (FAILED(ID3D11Device_CreateBlendState(dv, &bl, &d->blend))) { + return bui_gpu_fail("blend state", 0); } - if (gen != g->slug_gen) { /* faces were freed: ids may be reused */ - g->slug_gen = gen; - slug_reset(g); + D3D11_RASTERIZER_DESC rd = {0}; + rd.FillMode = D3D11_FILL_SOLID; + rd.CullMode = D3D11_CULL_NONE; + rd.DepthClipEnable = TRUE; + if (FAILED(ID3D11Device_CreateRasterizerState(dv, &rd, &d->rs))) { + return bui_gpu_fail("rasterizer state", 0); } - const uint32_t key = ((uint32_t)(face + 1) << 16) | (uint32_t)glyph; - uint32_t idx = (key * 2654435761u) >> 19 & (SLUG_MAP - 1); - SlugGlyph *sg; - for (;;) { - sg = &g->slug_map[idx]; - if (sg->key == 0 || sg->key == key) { - break; - } - idx = (idx + 1) & (SLUG_MAP - 1); + rd.ScissorEnable = TRUE; /* meshes: the draw command's clip */ + if (FAILED(ID3D11Device_CreateRasterizerState(dv, &rd, &d->rs_scissor))) { + return bui_gpu_fail("rasterizer state", 0); } - if (sg->key == 0) { - float *cv = NULL; - int n = 0; - float bb[4]; - sg->ok = 0; - if (bui_text_glyph_outline(face, glyph, &cv, &n, bb)) { - int got = slug_build(g, sg, cv, n, bb); - if (got < 0) { - slug_reset(g); - free(cv); - return bui_gpu_slug_glyph(g, face, glyph, gen, r_bbox, r_band, r_loc); - } - } - free(cv); - sg->key = key; - g->slug_n++; + D3D11_SAMPLER_DESC sd = {0}; + sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + sd.AddressU = sd.AddressV = sd.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP; + sd.MaxLOD = D3D11_FLOAT32_MAX; + sd.ComparisonFunc = D3D11_COMPARISON_ALWAYS; + if (FAILED(ID3D11Device_CreateSamplerState(dv, &sd, &d->smp_linear))) { + return bui_gpu_fail("sampler", 0); } - if (!sg->ok) { - return 0; + sd.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; + if (FAILED(ID3D11Device_CreateSamplerState(dv, &sd, &d->smp_point))) { + return bui_gpu_fail("sampler", 0); } - memcpy(r_bbox, sg->bbox, sizeof(float[4])); - memcpy(r_band, sg->band, sizeof(float[4])); - memcpy(r_loc, sg->loc, sizeof(int[4])); return 1; } -/** \} */ - -static void img_reset(BuiGpu *g) -{ - flush(g); - atlas_clear(&g->rgba); - memset(g->img_map, 0, sizeof(Slot) * IMG_MAP); - g->img_n = 0; -} - -int bui_gpu_image(BuiGpu *g, uint64_t key, const uint32_t *argb, int w, int h, int *r_x, int *r_y) +static void d11_exit(BuiGpu *g) { - if (!g->rgba.tex && !atlas_create(g, &g->rgba, 2048, 4)) { - return 0; - } - if (w + 1 > g->rgba.size || h + 1 > g->rgba.size) { - return 0; /* TODO: images larger than the atlas */ + D11 *d = DEV(g); + if (d->ctx) { + ID3D11DeviceContext_ClearState(d->ctx); } - /* key: BuiPixmap.key or its content hash (gpu_raster.c), with the size */ - const uint64_t k1 = key, k2 = ((uint64_t)w << 32) | (uint32_t)h; - uint32_t idx = (uint32_t)mix64(k1) & (IMG_MAP - 1); - for (;;) { - Slot *s = &g->img_map[idx]; - if (s->k1 == 0) { - break; - } - if (s->k1 == k1 && s->k2 == k2) { - *r_x = s->x; - *r_y = s->y; - return 1; - } - idx = (idx + 1) & (IMG_MAP - 1); + REL(d->smp_linear); + REL(d->smp_point); + REL(d->rs_scissor); + REL(d->mib); + for (int i = 0; i < BUI_DX_PROGRAMS; i++) { + REL(d->vb[i]); + REL(d->il[i]); + REL(d->vs[i]); + REL(d->ps[i]); } - int x, y; - if (g->img_n >= IMG_MAP_FILL || !atlas_place(&g->rgba, w, h, &x, &y)) { - img_reset(g); - return bui_gpu_image(g, key, argb, w, h, r_x, r_y); - } - atlas_upload(g, &g->rgba, x, y, w, h, argb, w * 4); - Slot *s = &g->img_map[idx]; - s->k1 = k1; - s->k2 = k2; - s->x = x; - s->y = y; - g->img_n++; - *r_x = x; - *r_y = y; - return 1; + REL(d->rtv); + REL(d->target); + REL(d->rs); + REL(d->blend); + REL(d->cb); + REL(d->swap); + REL(d->factory); + REL(d->ctx1); + REL(d->ctx); + REL(d->dev); + free(d); } -/* -- big images: textures of their own ------------------------------------------------ */ +/** \} */ -static size_t big_size(int format, int w, int h) -{ - return format == BUI_PIXMAP_ARGB ? (size_t)w * h * 4 : (size_t)w * h * 3 / 2; -} +/* -------------------------------------------------------------------- */ +/** \name Textures and effects + * \{ */ -static void big_release(BuiGpu *g, BigTex *t) +static void d11_tex_free(BuiGpu *g, BuiGpuTex *t) { - if (t->srv) { - g->big_bytes -= big_size(t->format, t->w, t->h); - } + (void)g; + REL(t->rtv); REL(t->srv); REL(t->tex); - REL(t->uv_srv); - REL(t->uv_tex); - memset(t, 0, sizeof(*t)); + free(t); } -/* One plane: a texture and its view, initialized from `data`. */ -static int big_plane(BuiGpu *g, DXGI_FORMAT fmt, int w, int h, const void *data, UINT pitch, - int dynamic, ID3D11Texture2D **r_tex, ID3D11ShaderResourceView **r_srv) +static BuiGpuTex *d11_tex_create(BuiGpu *g, BuiGpuFormat fmt, int w, int h, const void *data, + int pitch, int flags) { + D11 *d = DEV(g); + BuiGpuTex *t = (BuiGpuTex *)calloc(1, sizeof(BuiGpuTex)); + if (!t) { + return NULL; + } D3D11_TEXTURE2D_DESC td = {0}; td.Width = (UINT)w; td.Height = (UINT)h; td.MipLevels = td.ArraySize = 1; - td.Format = fmt; + td.Format = dxgi_format(fmt); td.SampleDesc.Count = 1; - td.Usage = dynamic ? D3D11_USAGE_DEFAULT : D3D11_USAGE_IMMUTABLE; - td.BindFlags = D3D11_BIND_SHADER_RESOURCE; - D3D11_SUBRESOURCE_DATA init = {data, pitch, 0}; - if (FAILED(ID3D11Device_CreateTexture2D(g->dev, &td, &init, r_tex)) || - FAILED(ID3D11Device_CreateShaderResourceView(g->dev, (ID3D11Resource *)*r_tex, NULL, r_srv))) + td.Usage = (flags & BUI_TEX_IMMUTABLE) && data ? D3D11_USAGE_IMMUTABLE : D3D11_USAGE_DEFAULT; + td.BindFlags = D3D11_BIND_SHADER_RESOURCE | ((flags & BUI_TEX_TARGET) ? D3D11_BIND_RENDER_TARGET : 0); + D3D11_SUBRESOURCE_DATA init = {data, (UINT)pitch, 0}; + if (FAILED(ID3D11Device_CreateTexture2D(d->dev, &td, data ? &init : NULL, &t->tex)) || + FAILED(ID3D11Device_CreateShaderResourceView(d->dev, (ID3D11Resource *)t->tex, NULL, &t->srv)) || + ((flags & BUI_TEX_TARGET) && + FAILED(ID3D11Device_CreateRenderTargetView(d->dev, (ID3D11Resource *)t->tex, NULL, &t->rtv)))) { - REL(*r_tex); - return 0; - } - return 1; -} - -/* `px` into slot `t`'s textures: created, or (a stream's next frame) updated in place. */ -static int big_upload(BuiGpu *g, BigTex *t, int create, const uint32_t *px, int stride) -{ - const int nv12 = t->format != BUI_PIXMAP_ARGB; - const uint8_t *uv = (const uint8_t *)px + (size_t)t->w * t->h; - if (!create) { - ID3D11DeviceContext_UpdateSubresource(g->ctx, (ID3D11Resource *)t->tex, 0, NULL, px, - (UINT)stride * (nv12 ? 1 : 4), 0); - if (nv12) { - ID3D11DeviceContext_UpdateSubresource(g->ctx, (ID3D11Resource *)t->uv_tex, 0, NULL, uv, - (UINT)t->w, 0); - } - return 1; - } - if (!nv12) { /* 0xAARRGGBB in memory order */ - return big_plane(g, DXGI_FORMAT_B8G8R8A8_UNORM, t->w, t->h, px, (UINT)stride * 4, t->stream, - &t->tex, &t->srv); - } - if (!big_plane(g, DXGI_FORMAT_R8_UNORM, t->w, t->h, px, (UINT)t->w, t->stream, &t->tex, &t->srv)) { - return 0; + d11_tex_free(g, t); + return NULL; } - if (!big_plane(g, DXGI_FORMAT_R8G8_UNORM, t->w / 2, t->h / 2, uv, (UINT)t->w, t->stream, - &t->uv_tex, &t->uv_srv)) - { - REL(t->srv); - REL(t->tex); - return 0; + if (t->rtv) { /* a texture made without data is undefined: it is cleared */ + const float zero[4] = {0, 0, 0, 0}; + ID3D11DeviceContext_ClearRenderTargetView(d->ctx, t->rtv, zero); } - return 1; + return t; } -/* Frees what the kit freed (BUI_image_forget) and what went unused. */ -static void big_sweep(BuiGpu *g) +static void d11_tex_update(BuiGpu *g, BuiGpuTex *t, int x, int y, int w, int h, const void *data, + int pitch) { - uint64_t gone[64]; - const int n = bui_image_forgotten(&g->forget_seen, gone, 64); /* -1: missed some */ - for (int i = 0; i < BIG_MAX; i++) { - BigTex *t = &g->big[i]; - if (!t->key) { - continue; - } - int drop = g->frame - t->used > BIG_IDLE || (n < 0 && t->used != g->frame); - for (int k = 0; k < n && !drop; k++) { - drop = gone[k] == t->base; - } - if (drop) { - big_release(g, t); - } - } + D3D11_BOX box = {(UINT)x, (UINT)y, 0, (UINT)(x + w), (UINT)(y + h), 1}; + ID3D11DeviceContext_UpdateSubresource(DEV(g)->ctx, (ID3D11Resource *)t->tex, 0, &box, data, + (UINT)pitch, 0); } -int bui_gpu_max_texture(BuiGpu *g) +static void d11_fx_free(BuiGpu *g, BuiGpuProg *p) { - return g->max_tex > 0 ? g->max_tex : 8192; + (void)g; + REL(p->vs); + REL(p->ps); + REL(p->cb); + free(p); } -int bui_gpu_image_tex(BuiGpu *g, uint64_t key, uint64_t base, int stream, int format, - const uint32_t *px, int stride, int w, int h) +static BuiGpuProg *d11_fx_build(BuiGpu *g, const BuiEffectView *v, char *log, size_t log_n) { - if (w <= 0 || h <= 0 || w > bui_gpu_max_texture(g) || h > bui_gpu_max_texture(g)) { - return 0; - } - int free_slot = -1, lru = -1; - for (int i = 0; i < BIG_MAX; i++) { - BigTex *t = &g->big[i]; - if (t->key && t->w == w && t->h == h && t->format == format && - (t->key == key || (stream && t->stream && t->base == base))) - { - if (t->key != key) { /* the stream's next frame: in place, no new texture */ - big_upload(g, t, 0, px, stride); - t->key = key; - } - t->used = g->frame; - return i + 1; - } - if (!t->key) { - free_slot = free_slot < 0 ? i : free_slot; - } - else if (t->used != g->frame && (lru < 0 || t->used < g->big[lru].used)) { - lru = i; /* not drawn this frame: no recorded batch samples it */ - } + D11 *d = DEV(g); + ID3DBlob *vsb, *psb; + if (!bui_dx_fx_compile(v, "4_0", &vsb, &psb, log, log_n)) { + return NULL; } - const size_t bytes = big_size(format, w, h); - while (lru >= 0 && (free_slot < 0 || g->big_bytes + bytes > BIG_BUDGET)) { - big_release(g, &g->big[lru]); - free_slot = free_slot < 0 ? lru : free_slot; - lru = -1; - for (int i = 0; i < BIG_MAX; i++) { - const BigTex *t = &g->big[i]; - if (t->key && t->used != g->frame && (lru < 0 || t->used < g->big[lru].used)) { - lru = i; - } + BuiGpuProg *p = (BuiGpuProg *)calloc(1, sizeof(BuiGpuProg)); + D3D11_BUFFER_DESC bd = {0}; + bd.ByteWidth = (UINT)(sizeof(float) * (8 + 4 * (size_t)(v->n_floats > 0 ? v->n_floats : 1))); + bd.Usage = D3D11_USAGE_DYNAMIC; + bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + const int ok = p && + SUCCEEDED(ID3D11Device_CreateVertexShader(d->dev, ID3D10Blob_GetBufferPointer(vsb), + ID3D10Blob_GetBufferSize(vsb), NULL, + &p->vs)) && + SUCCEEDED(ID3D11Device_CreatePixelShader(d->dev, ID3D10Blob_GetBufferPointer(psb), + ID3D10Blob_GetBufferSize(psb), NULL, + &p->ps)) && + SUCCEEDED(ID3D11Device_CreateBuffer(d->dev, &bd, NULL, &p->cb)); + REL(vsb); + REL(psb); + if (!ok) { + snprintf(log, log_n, "the device rejected the compiled shader"); + if (p) { + d11_fx_free(g, p); } + return NULL; } - if (free_slot < 0) { - return 0; - } - BigTex *t = &g->big[free_slot]; - t->w = w; - t->h = h; - t->format = format; - t->stream = stream; - if (!big_upload(g, t, 1, px, stride)) { - memset(t, 0, sizeof(*t)); - return 0; - } - t->key = key; - t->base = base; - t->used = g->frame; - g->big_bytes += bytes; - return free_slot + 1; -} - -void bui_gpu_damage(BuiGpu *g, int x, int y, int w, int h) -{ - if (w <= 0 || h <= 0 || g->n_dmg == (int)(sizeof(g->dmg) / sizeof(g->dmg[0]))) { - g->dmg_full = 1; - return; - } - RECT *r = &g->dmg[g->n_dmg++]; - r->left = x; - r->top = y; - r->right = x + w; - r->bottom = y + h; + return p; } /** \} */ @@ -1686,67 +330,36 @@ void bui_gpu_damage(BuiGpu *g, int x, int y, int w, int h) /** \name Drawing + present * \{ */ -/* Resizing steps: the target and the swap chain are made a multiple of GPU_SLACK px wide and - * high and kept while the frame stays within [cap - 2 * GPU_SLACK, cap], so a drag-resize - * reallocates every few dozen sizes, not at each one. A bitblt (alpha) swap chain stretches its - * buffer over the window, so it stays exact. */ -# define GPU_SLACK 256 - -static int slack_cap(const BuiGpu *g, int need) -{ - if (g->alpha) { - return need; - } - const int cap = (need + GPU_SLACK - 1) / GPU_SLACK * GPU_SLACK; - return cap < g->max_tex ? cap : need; -} - -static int slack_fits(const BuiGpu *g, int cap, int need) -{ - return cap >= need && (g->alpha ? cap == need : cap - need < 2 * GPU_SLACK); -} - -static int ensure_target(BuiGpu *g) -{ - if (g->target && slack_fits(g, g->tw, g->w) && slack_fits(g, g->th, g->h)) { - if (g->fw != g->w || g->fh != g->h) { /* another size in the same texture: a redraw follows */ - g->fw = g->w; - g->fh = g->h; - const float clear[4] = {0, 0, 0, g->alpha ? 0.0f : 1.0f}; - ID3D11DeviceContext_ClearRenderTargetView(g->ctx, g->rtv, clear); - g->dmg_full = 1; +static int d11_target(BuiGpu *g, int tw, int th) +{ + D11 *d = DEV(g); + if (!d->target || d->tw != tw || d->th != th) { + REL(d->rtv); + REL(d->target); + D3D11_TEXTURE2D_DESC td = {0}; + td.Width = (UINT)tw; + td.Height = (UINT)th; + td.MipLevels = td.ArraySize = 1; + td.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + td.SampleDesc.Count = 1; + td.Usage = D3D11_USAGE_DEFAULT; + td.BindFlags = D3D11_BIND_RENDER_TARGET; + if (FAILED(ID3D11Device_CreateTexture2D(d->dev, &td, NULL, &d->target)) || + FAILED(ID3D11Device_CreateRenderTargetView(d->dev, (ID3D11Resource *)d->target, NULL, + &d->rtv))) + { + REL(d->target); + return 0; } - return 1; - } - REL(g->rtv); - REL(g->target); - D3D11_TEXTURE2D_DESC td = {0}; - td.Width = (UINT)slack_cap(g, g->w); - td.Height = (UINT)slack_cap(g, g->h); - td.MipLevels = td.ArraySize = 1; - td.Format = DXGI_FORMAT_B8G8R8A8_UNORM; - td.SampleDesc.Count = 1; - td.Usage = D3D11_USAGE_DEFAULT; - td.BindFlags = D3D11_BIND_RENDER_TARGET; - if (FAILED(ID3D11Device_CreateTexture2D(g->dev, &td, NULL, &g->target)) || - FAILED(ID3D11Device_CreateRenderTargetView(g->dev, (ID3D11Resource *)g->target, NULL, - &g->rtv))) - { - REL(g->target); - return 0; + d->tw = tw; + d->th = th; } - g->tw = (int)td.Width; - g->th = (int)td.Height; - g->fw = g->w; - g->fh = g->h; const float clear[4] = {0, 0, 0, g->alpha ? 0.0f : 1.0f}; - ID3D11DeviceContext_ClearRenderTargetView(g->ctx, g->rtv, clear); - g->dmg_full = 1; + ID3D11DeviceContext_ClearRenderTargetView(d->ctx, d->rtv, clear); return 1; } -static int ensure_buffer(BuiGpu *g, ID3D11Buffer **buf, UINT *cap, UINT need, UINT stride, - UINT bind) +static int ensure_buffer(D11 *d, ID3D11Buffer **buf, UINT *cap, UINT need, UINT stride, UINT bind) { if (*buf && *cap >= need) { return 1; @@ -1761,7 +374,7 @@ static int ensure_buffer(BuiGpu *g, ID3D11Buffer **buf, UINT *cap, UINT need, UI bd.Usage = D3D11_USAGE_DYNAMIC; bd.BindFlags = bind; bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - if (FAILED(ID3D11Device_CreateBuffer(g->dev, &bd, NULL, buf))) { + if (FAILED(ID3D11Device_CreateBuffer(d->dev, &bd, NULL, buf))) { *cap = 0; return 0; } @@ -1769,53 +382,49 @@ static int ensure_buffer(BuiGpu *g, ID3D11Buffer **buf, UINT *cap, UINT need, UI return 1; } -static void upload(BuiGpu *g, ID3D11Buffer *buf, const void *data, size_t bytes) +static void upload(D11 *d, ID3D11Buffer *buf, const void *data, size_t bytes) { D3D11_MAPPED_SUBRESOURCE m; - if (SUCCEEDED(ID3D11DeviceContext_Map(g->ctx, (ID3D11Resource *)buf, 0, D3D11_MAP_WRITE_DISCARD, + if (SUCCEEDED(ID3D11DeviceContext_Map(d->ctx, (ID3D11Resource *)buf, 0, D3D11_MAP_WRITE_DISCARD, 0, &m))) { memcpy(m.pData, data, bytes); - ID3D11DeviceContext_Unmap(g->ctx, (ID3D11Resource *)buf, 0); + ID3D11DeviceContext_Unmap(d->ctx, (ID3D11Resource *)buf, 0); } } /* One recorded effect draw: its shaders, floats and inputs, scissored to its clip. */ -static void fx_draw(BuiGpu *g, const FxCall *fc) +static void fx_draw(BuiGpu *g, const BuiGpuFxCall *fc) { - ID3D11DeviceContext *c = g->ctx; + D11 *d = DEV(g); + ID3D11DeviceContext *c = d->ctx; const float blend_factor[4] = {0, 0, 0, 0}; /* a pass into a render target: its view and size stand in for the frame's until it is drawn */ - const DevTex *dst = fc->dst ? dtex_dev(g, fc->dst) : NULL; - if (fc->dst && (!dst || !dst->rtv)) { + const BuiGpuDevTex *dst = fc->dst ? bui_gpu_dtex(g, fc->dst) : NULL; + if (fc->dst && (!dst || !dst->tex->rtv)) { return; } if (!fc->effect) { /* a clear of the target */ - ID3D11DeviceContext_ClearRenderTargetView(c, dst->rtv, g->fxf + fc->floats); + ID3D11DeviceContext_ClearRenderTargetView(c, dst->tex->rtv, g->fxf + fc->floats); return; } - const int slot = BUI_EFFECT_SLOT(fc->effect); - const DevFx *f = slot >= 0 && slot < g->n_dfx ? &g->dfx[slot] : NULL; - if (!f || f->id != fc->effect || !f->ps) { + const BuiGpuDevFx *f = bui_gpu_dfx(g, fc->effect); + if (!f) { return; } - float data[8 + 4 * BUI_EFFECT_MAX_FLOATS] = {0}; - memcpy(data, fc->rect, sizeof(fc->rect)); - data[4] = 2.0f / (float)(dst ? dst->w : g->tw); - data[5] = 2.0f / (float)(dst ? dst->h : g->th); - for (int i = 0; i < f->n_floats; i++) { /* HLSL gives each element of an array a register */ - data[8 + 4 * i] = g->fxf[fc->floats + i]; - } - upload(g, f->cb, data, sizeof(float) * (size_t)(8 + 4 * (f->n_floats > 0 ? f->n_floats : 1))); + BuiGpuFxConsts consts; + upload(d, f->prog->cb, consts.data, + bui_gpu_fx_consts(g, fc, f->n_floats, dst ? dst->w : d->tw, dst ? dst->h : d->th, &consts)); ID3D11ShaderResourceView *srv[BUI_EFFECT_MAX_INPUTS]; for (int k = 0; k < f->n_inputs; k++) { - srv[k] = dtex_srv(g, fc->inputs[k]); + srv[k] = bui_gpu_dtex_tex(g, fc->inputs[k])->srv; } if (dst) { /* nothing the last draw bound may be the target about to be written */ ID3D11ShaderResourceView *none[BUI_EFFECT_MAX_INPUTS] = {0}; ID3D11DeviceContext_PSSetShaderResources(c, 8, BUI_EFFECT_MAX_INPUTS, none); - ID3D11DeviceContext_OMSetRenderTargets(c, 1, (ID3D11RenderTargetView *const *)&dst->rtv, NULL); + ID3D11DeviceContext_OMSetRenderTargets(c, 1, (ID3D11RenderTargetView *const *)&dst->tex->rtv, + NULL); ID3D11DeviceContext_OMSetBlendState(c, NULL, blend_factor, 0xffffffffu); const D3D11_VIEWPORT vp = {0, 0, (float)dst->w, (float)dst->h, 0, 1}; ID3D11DeviceContext_RSSetViewports(c, 1, &vp); @@ -1823,270 +432,189 @@ static void fx_draw(BuiGpu *g, const FxCall *fc) if (f->n_inputs > 0) { ID3D11DeviceContext_PSSetShaderResources(c, 8, (UINT)f->n_inputs, srv); } - ID3D11DeviceContext_VSSetShader(c, f->vs, NULL, 0); - ID3D11DeviceContext_PSSetShader(c, f->ps, NULL, 0); - ID3D11DeviceContext_VSSetConstantBuffers(c, 1, 1, (ID3D11Buffer *const *)&f->cb); - ID3D11DeviceContext_PSSetConstantBuffers(c, 1, 1, (ID3D11Buffer *const *)&f->cb); + ID3D11DeviceContext_VSSetShader(c, f->prog->vs, NULL, 0); + ID3D11DeviceContext_PSSetShader(c, f->prog->ps, NULL, 0); + ID3D11DeviceContext_VSSetConstantBuffers(c, 1, 1, (ID3D11Buffer *const *)&f->prog->cb); + ID3D11DeviceContext_PSSetConstantBuffers(c, 1, 1, (ID3D11Buffer *const *)&f->prog->cb); const D3D11_RECT sr = {fc->clip[0], fc->clip[1], fc->clip[2], fc->clip[3]}; ID3D11DeviceContext_RSSetScissorRects(c, 1, &sr); ID3D11DeviceContext_Draw(c, 4, 0); if (dst) { /* back to the frame: its view, its size and its blending */ ID3D11ShaderResourceView *none[BUI_EFFECT_MAX_INPUTS] = {0}; ID3D11DeviceContext_PSSetShaderResources(c, 8, BUI_EFFECT_MAX_INPUTS, none); - ID3D11DeviceContext_OMSetRenderTargets(c, 1, &g->rtv, NULL); - ID3D11DeviceContext_OMSetBlendState(c, g->blend, blend_factor, 0xffffffffu); - const D3D11_VIEWPORT vp = {0, 0, (float)g->tw, (float)g->th, 0, 1}; + ID3D11DeviceContext_OMSetRenderTargets(c, 1, &d->rtv, NULL); + ID3D11DeviceContext_OMSetBlendState(c, d->blend, blend_factor, 0xffffffffu); + const D3D11_VIEWPORT vp = {0, 0, (float)d->tw, (float)d->th, 0, 1}; ID3D11DeviceContext_RSSetViewports(c, 1, &vp); } } -static void flush(BuiGpu *g) +static ID3D11ShaderResourceView *srv_of(const BuiGpuTex *t) { - if (g->n_b == 0) { - return; - } - if (!ensure_target(g)) { - g->n_b = g->n_inst = g->n_tv = g->n_mv = g->n_mi = g->n_fx = g->n_fxf = 0; - return; - } - ID3D11DeviceContext *c = g->ctx; - if (g->n_inst && ensure_buffer(g, &g->ib, &g->ib_cap, (UINT)g->n_inst, sizeof(BuiGpuInst), - D3D11_BIND_VERTEX_BUFFER)) - { - upload(g, g->ib, g->inst, sizeof(BuiGpuInst) * (size_t)g->n_inst); - } - if (g->n_tv && - ensure_buffer(g, &g->tb, &g->tb_cap, (UINT)g->n_tv, sizeof(TriV), D3D11_BIND_VERTEX_BUFFER)) - { - upload(g, g->tb, g->tv, sizeof(TriV) * (size_t)g->n_tv); - } - if (g->n_mv && ensure_buffer(g, &g->mvb, &g->mvb_cap, (UINT)g->n_mv, sizeof(BuiMeshVertex), - D3D11_BIND_VERTEX_BUFFER)) - { - upload(g, g->mvb, g->mv, sizeof(BuiMeshVertex) * (size_t)g->n_mv); + return t ? t->srv : NULL; +} + +static void d11_draw(BuiGpu *g) +{ + D11 *d = DEV(g); + ID3D11DeviceContext *c = d->ctx; + for (int k = 0; k < BUI_DX_PROGRAMS; k++) { + int n; + const void *data = bui_gpu_batch_data(g, (BuiGpuBatchKind)k, &n); + const UINT stride = bui_dx_programs[k].stride; + if (n && ensure_buffer(d, &d->vb[k], &d->vb_cap[k], (UINT)n, stride, D3D11_BIND_VERTEX_BUFFER)) { + upload(d, d->vb[k], data, (size_t)stride * n); + } } - if (g->n_mi && ensure_buffer(g, &g->mib, &g->mib_cap, (UINT)g->n_mi, sizeof(uint32_t), + if (g->n_mi && ensure_buffer(d, &d->mib, &d->mib_cap, (UINT)g->n_mi, sizeof(uint32_t), D3D11_BIND_INDEX_BUFFER)) { - upload(g, g->mib, g->mi, sizeof(uint32_t) * (size_t)g->n_mi); + upload(d, d->mib, g->mi, sizeof(uint32_t) * (size_t)g->n_mi); } - const float cbd[4] = {2.0f / (float)g->tw, 2.0f / (float)g->th, 0, 0}; - upload(g, g->cb, cbd, sizeof(cbd)); + const float cbd[4] = {2.0f / (float)d->tw, 2.0f / (float)d->th, 0, 0}; + upload(d, d->cb, cbd, sizeof(cbd)); - ID3D11DeviceContext_OMSetRenderTargets(c, 1, &g->rtv, NULL); + ID3D11DeviceContext_OMSetRenderTargets(c, 1, &d->rtv, NULL); const float bf[4] = {0, 0, 0, 0}; - ID3D11DeviceContext_OMSetBlendState(c, g->blend, bf, 0xffffffffu); - D3D11_VIEWPORT vp = {0, 0, (float)g->tw, (float)g->th, 0, 1}; + ID3D11DeviceContext_OMSetBlendState(c, d->blend, bf, 0xffffffffu); + D3D11_VIEWPORT vp = {0, 0, (float)d->tw, (float)d->th, 0, 1}; ID3D11DeviceContext_RSSetViewports(c, 1, &vp); - ID3D11DeviceContext_RSSetState(c, g->rs); - ID3D11DeviceContext_VSSetConstantBuffers(c, 0, 1, &g->cb); - ID3D11ShaderResourceView *srv[4] = {g->mask.srv, g->rgba.srv, g->curve_srv, g->band_srv}; + ID3D11DeviceContext_RSSetState(c, d->rs); + ID3D11DeviceContext_VSSetConstantBuffers(c, 0, 1, &d->cb); + ID3D11ShaderResourceView *srv[4] = {srv_of(g->mask.tex), srv_of(g->rgba.tex), + srv_of(g->curve_tex), srv_of(g->band_tex)}; ID3D11DeviceContext_PSSetShaderResources(c, 0, 4, srv); - int cur = -1, img = 0; + int cur = -1; + const BuiGpuTex *img = g->rgba.tex; for (int i = 0; i < g->n_b; i++) { - const Batch *b = &g->b[i]; + const BuiGpuBatch *b = &g->b[i]; if (b->count == 0) { continue; } - if (b->tri != cur) { - if (cur == 2 || cur == 3) { /* the scissored states */ - ID3D11DeviceContext_RSSetState(c, g->rs); - } - cur = b->tri; - UINT off = 0; - if (b->tri == 2) { - UINT stride = sizeof(BuiMeshVertex); - ID3D11DeviceContext_IASetInputLayout(c, g->il_mesh); - ID3D11DeviceContext_IASetVertexBuffers(c, 0, 1, &g->mvb, &stride, &off); - ID3D11DeviceContext_IASetIndexBuffer(c, g->mib, DXGI_FORMAT_R32_UINT, 0); - ID3D11DeviceContext_IASetPrimitiveTopology(c, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - ID3D11DeviceContext_VSSetShader(c, g->vs_mesh, NULL, 0); - ID3D11DeviceContext_PSSetShader(c, g->ps_mesh, NULL, 0); - ID3D11DeviceContext_RSSetState(c, g->rs_scissor); - } - else if (!b->tri) { - UINT stride = sizeof(BuiGpuInst); - ID3D11DeviceContext_IASetInputLayout(c, g->il_quad); - ID3D11DeviceContext_IASetVertexBuffers(c, 0, 1, &g->ib, &stride, &off); - ID3D11DeviceContext_IASetPrimitiveTopology(c, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); - ID3D11DeviceContext_VSSetShader(c, g->vs_quad, NULL, 0); - ID3D11DeviceContext_PSSetShader(c, g->ps_quad, NULL, 0); + if ((int)b->kind != cur) { + if (cur == BUI_BATCH_MESH || cur == BUI_BATCH_FX) { /* the scissored states */ + ID3D11DeviceContext_RSSetState(c, d->rs); } - else if (b->tri == 3) { /* effects: a quad from SV_VertexID, no vertex data */ + cur = (int)b->kind; + /* quads: 4 vertices from SV_VertexID per instance, as effects (which have no vertex data) */ + ID3D11DeviceContext_IASetPrimitiveTopology(c, b->kind == BUI_BATCH_QUADS || b->kind == BUI_BATCH_FX ? + D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : + D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + if (b->kind == BUI_BATCH_FX) { ID3D11DeviceContext_IASetInputLayout(c, NULL); - ID3D11DeviceContext_IASetPrimitiveTopology(c, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); - ID3D11DeviceContext_PSSetSamplers(c, 0, 1, &g->smp_linear); - ID3D11DeviceContext_RSSetState(c, g->rs_scissor); + ID3D11DeviceContext_PSSetSamplers(c, 0, 1, &d->smp_linear); + ID3D11DeviceContext_RSSetState(c, d->rs_scissor); } else { - UINT stride = sizeof(TriV); - ID3D11DeviceContext_IASetInputLayout(c, g->il_tri); - ID3D11DeviceContext_IASetVertexBuffers(c, 0, 1, &g->tb, &stride, &off); - ID3D11DeviceContext_IASetPrimitiveTopology(c, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); - ID3D11DeviceContext_VSSetShader(c, g->vs_tri, NULL, 0); - ID3D11DeviceContext_PSSetShader(c, g->ps_tri, NULL, 0); + const UINT stride = bui_dx_programs[b->kind].stride, off = 0; + ID3D11DeviceContext_IASetInputLayout(c, d->il[b->kind]); + ID3D11DeviceContext_IASetVertexBuffers(c, 0, 1, &d->vb[b->kind], &stride, &off); + ID3D11DeviceContext_VSSetShader(c, d->vs[b->kind], NULL, 0); + ID3D11DeviceContext_PSSetShader(c, d->ps[b->kind], NULL, 0); + } + if (b->kind == BUI_BATCH_MESH) { + ID3D11DeviceContext_IASetIndexBuffer(c, d->mib, DXGI_FORMAT_R32_UINT, 0); + ID3D11DeviceContext_RSSetState(c, d->rs_scissor); } } - if (b->tri == 2) { - ID3D11ShaderResourceView *ts = dtex_srv(g, b->tex); + if (b->kind == BUI_BATCH_MESH) { + ID3D11ShaderResourceView *ts = bui_gpu_dtex_tex(g, b->tex)->srv; ID3D11DeviceContext_PSSetShaderResources(c, 4, 1, &ts); - ID3D11DeviceContext_PSSetSamplers(c, 0, 1, b->nearest ? &g->smp_point : &g->smp_linear); + ID3D11DeviceContext_PSSetSamplers(c, 0, 1, b->nearest ? &d->smp_point : &d->smp_linear); const D3D11_RECT sr = {b->clip[0], b->clip[1], b->clip[2], b->clip[3]}; ID3D11DeviceContext_RSSetScissorRects(c, 1, &sr); ID3D11DeviceContext_DrawIndexed(c, (UINT)b->count, (UINT)b->first, 0); } - else if (!b->tri) { - const int want = b->img > 0 && g->big[b->img - 1].srv ? b->img : 0; + else if (b->kind == BUI_BATCH_QUADS) { + BuiGpuTex *uv; + BuiGpuTex *want = bui_gpu_batch_image(g, b, &uv); if (want != img) { /* t1: the atlas, or a big image's own texture (t5: NV12 chroma) */ img = want; - ID3D11ShaderResourceView *t1 = img ? g->big[img - 1].srv : g->rgba.srv; - ID3D11ShaderResourceView *t5 = img ? g->big[img - 1].uv_srv : NULL; + ID3D11ShaderResourceView *t1 = srv_of(img), *t5 = srv_of(uv); ID3D11DeviceContext_PSSetShaderResources(c, 1, 1, &t1); ID3D11DeviceContext_PSSetShaderResources(c, 5, 1, &t5); } ID3D11DeviceContext_DrawInstanced(c, 4, (UINT)b->count, 0, (UINT)b->first); } - else if (b->tri == 3) { + else if (b->kind == BUI_BATCH_FX) { fx_draw(g, &g->fx[b->first]); } else { ID3D11DeviceContext_Draw(c, (UINT)b->count, (UINT)b->first); } } - if (cur == 2 || cur == 3) { - ID3D11DeviceContext_RSSetState(c, g->rs); + if (cur == BUI_BATCH_MESH || cur == BUI_BATCH_FX) { + ID3D11DeviceContext_RSSetState(c, d->rs); } - g->n_b = g->n_inst = g->n_tv = g->n_mv = g->n_mi = g->n_fx = g->n_fxf = 0; } -static int ensure_swap(BuiGpu *g) +static int d11_swap(BuiGpu *g, int cw, int ch) { - if (g->swap && slack_fits(g, g->sw, g->w) && slack_fits(g, g->sh, g->h)) { - return 1; - } - const int cw = slack_cap(g, g->w), ch = slack_cap(g, g->h); - if (g->swap) { - ID3D11DeviceContext_OMSetRenderTargets(g->ctx, 0, NULL, NULL); - if (FAILED(IDXGISwapChain1_ResizeBuffers(g->swap, 0, (UINT)cw, (UINT)ch, DXGI_FORMAT_UNKNOWN, - 0))) - { - return 0; - } + D11 *d = DEV(g); + if (d->swap) { + ID3D11DeviceContext_OMSetRenderTargets(d->ctx, 0, NULL, NULL); + return SUCCEEDED(IDXGISwapChain1_ResizeBuffers(d->swap, 0, (UINT)cw, (UINT)ch, + DXGI_FORMAT_UNKNOWN, 0)); } - else { - DXGI_SWAP_CHAIN_DESC1 sd = {0}; - sd.Width = (UINT)cw; - sd.Height = (UINT)ch; - sd.Format = DXGI_FORMAT_B8G8R8A8_UNORM; - sd.SampleDesc.Count = 1; - sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; - sd.BufferCount = 2; - if (g->alpha) { - /* bitblt model, as SDL's transparent D3D11 windows: Present copies the alpha channel into - * the window's surface, which DWM blends (the host enables blur-behind) */ - sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; - sd.Scaling = DXGI_SCALING_STRETCH; - } - else { - sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; - sd.Scaling = DXGI_SCALING_NONE; - sd.AlphaMode = DXGI_ALPHA_MODE_IGNORE; - } - if (FAILED(IDXGIFactory2_CreateSwapChainForHwnd(g->factory, (IUnknown *)g->dev, g->hwnd, &sd, - NULL, NULL, &g->swap))) - { - return 0; - } - IDXGIFactory2_MakeWindowAssociation(g->factory, g->hwnd, DXGI_MWA_NO_ALT_ENTER); + DXGI_SWAP_CHAIN_DESC1 sd = bui_dx_swap_desc(cw, ch); + if (g->alpha) { + /* bitblt model, as SDL's transparent D3D11 windows: Present copies the alpha channel into + * the window's surface, which DWM blends (the host enables blur-behind) */ + sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + sd.Scaling = DXGI_SCALING_STRETCH; + sd.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED; + } + if (FAILED(IDXGIFactory2_CreateSwapChainForHwnd(d->factory, (IUnknown *)d->dev, g->hwnd, &sd, + NULL, NULL, &d->swap))) + { + return 0; } - g->sw = cw; - g->sh = ch; - g->swap_fresh = 1; + IDXGIFactory2_MakeWindowAssociation(d->factory, g->hwnd, DXGI_MWA_NO_ALT_ENTER); return 1; } -void bui_gpu_clear(BuiGpu *g, int x, int y, int w, int h) +static void d11_clear(BuiGpu *g, const RECT *r) { - flush(g); /* what was recorded for earlier regions comes first */ - if (!g->ctx1 || !g->target || g->fw != g->w || g->fh != g->h) { - return; /* a new target starts transparent */ - } + D11 *d = DEV(g); const float clear[4] = {0, 0, 0, 0}; - const RECT rect = {x, y, x + w, y + h}; - ID3D11DeviceContext1_ClearView(g->ctx1, (ID3D11View *)g->rtv, clear, &rect, 1); + ID3D11DeviceContext1_ClearView(d->ctx1, (ID3D11View *)d->rtv, clear, r, 1); } -int bui_gpu_present(BuiGpu *g, int full) +static void copy_rect(D11 *d, ID3D11Texture2D *dst, const D3D11_BOX *b) { - flush(g); - if (!g->target || !ensure_swap(g)) { - g->n_dmg = g->dmg_full = 0; - return g->target != NULL && !g->alpha; /* no alpha surface: the renderer is given up */ - } + ID3D11DeviceContext_CopySubresourceRegion(d->ctx, (ID3D11Resource *)dst, 0, b->left, b->top, 0, + (ID3D11Resource *)d->target, 0, b); +} + +static int d11_present(BuiGpu *g, int whole, const RECT *copy, int n_copy, const RECT *dirty, + int n_dirty) +{ + D11 *d = DEV(g); ID3D11Texture2D *back = NULL; - if (FAILED(IDXGISwapChain1_GetBuffer(g->swap, 0, &k_IID_ID3D11Texture2D, (void **)&back))) { - return 0; - } - for (int i = 0; i < g->n_dmg; i++) { /* clamp: DXGI rejects rects outside the buffer */ - RECT *r = &g->dmg[i]; - r->left = r->left < 0 ? 0 : r->left; - r->top = r->top < 0 ? 0 : r->top; - r->right = r->right > g->w ? g->w : r->right; - r->bottom = r->bottom > g->h ? g->h : r->bottom; - if (r->right <= r->left || r->bottom <= r->top) { - *r = g->dmg[--g->n_dmg]; - i--; - } - } - const int whole = full || g->dmg_full || g->swap_fresh || g->n_dmg == 0 || g->alpha; - /* copying rects adding up to half the frame or more: one copy of it all is cheaper */ - long area = 0; - for (int k = 0; k < 2 && !whole && !g->prev_whole; k++) { - const RECT *rs = k ? g->prev : g->dmg; - for (int i = 0, n = k ? g->n_prev : g->n_dmg; i < n; i++) { - area += (long)(rs[i].right - rs[i].left) * (rs[i].bottom - rs[i].top); - } + if (FAILED(IDXGISwapChain1_GetBuffer(d->swap, 0, &k_IID_ID3D11Texture2D, (void **)&back))) { + return BUI_PRESENT_LOST; } - if (whole || g->prev_whole || area * 2 >= (long)g->w * g->h) { - /* the buffer is two frames old (or of the bitblt model): the whole frame */ + if (whole) { /* the target can be larger than the window (it grows in steps): copy the frame, not the resource */ const D3D11_BOX frame = {0, 0, 0, (UINT)g->w, (UINT)g->h, 1}; - ID3D11DeviceContext_CopySubresourceRegion(g->ctx, (ID3D11Resource *)back, 0, 0, 0, 0, - (ID3D11Resource *)g->target, 0, &frame); + copy_rect(d, back, &frame); } - else { /* what changed this frame and the last one: the rest is already there */ - for (int k = 0; k < 2; k++) { - const RECT *rs = k ? g->prev : g->dmg; - for (int i = 0, n = k ? g->n_prev : g->n_dmg; i < n; i++) { - const D3D11_BOX b = {(UINT)rs[i].left, (UINT)rs[i].top, 0, (UINT)rs[i].right, (UINT)rs[i].bottom, 1}; - ID3D11DeviceContext_CopySubresourceRegion(g->ctx, (ID3D11Resource *)back, 0, b.left, b.top, 0, - (ID3D11Resource *)g->target, 0, &b); - } - } + for (int i = 0; i < n_copy; i++) { + const D3D11_BOX b = {(UINT)copy[i].left, (UINT)copy[i].top, 0, (UINT)copy[i].right, + (UINT)copy[i].bottom, 1}; + copy_rect(d, back, &b); } REL(back); - g->prev_whole = whole; - g->n_prev = whole ? 0 : g->n_dmg; - memcpy(g->prev, g->dmg, sizeof(RECT) * (size_t)g->n_prev); DXGI_PRESENT_PARAMETERS pp = {0}; - if (!(full || g->dmg_full || g->swap_fresh) && g->n_dmg > 0) { - pp.DirtyRectsCount = (UINT)g->n_dmg; - pp.pDirtyRects = g->dmg; - } - const HRESULT hr = IDXGISwapChain1_Present1(g->swap, 0, 0, &pp); - /* occluded or minimized: DWM dropped the frame, so the next one must be whole */ - g->swap_fresh = hr == DXGI_STATUS_OCCLUDED; - g->n_dmg = g->dmg_full = 0; - return !(hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET); + pp.DirtyRectsCount = (UINT)n_dirty; + pp.pDirtyRects = n_dirty ? (RECT *)dirty : NULL; + return bui_dx_present_status(IDXGISwapChain1_Present1(d->swap, 0, 0, &pp)); } -int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h) +static int d11_read(BuiGpu *g, uint32_t *dst, int w, int h) { - flush(g); - if (!g->target || g->fw != w || g->fh != h) { - return 0; - } + D11 *d = DEV(g); D3D11_TEXTURE2D_DESC td = {0}; td.Width = (UINT)w; td.Height = (UINT)h; @@ -2096,24 +624,20 @@ int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h) td.Usage = D3D11_USAGE_STAGING; td.CPUAccessFlags = D3D11_CPU_ACCESS_READ; ID3D11Texture2D *st = NULL; - if (FAILED(ID3D11Device_CreateTexture2D(g->dev, &td, NULL, &st))) { + if (FAILED(ID3D11Device_CreateTexture2D(d->dev, &td, NULL, &st))) { return 0; } const D3D11_BOX frame = {0, 0, 0, (UINT)w, (UINT)h, 1}; - ID3D11DeviceContext_CopySubresourceRegion(g->ctx, (ID3D11Resource *)st, 0, 0, 0, 0, - (ID3D11Resource *)g->target, 0, &frame); + ID3D11DeviceContext_CopySubresourceRegion(d->ctx, (ID3D11Resource *)st, 0, 0, 0, 0, + (ID3D11Resource *)d->target, 0, &frame); D3D11_MAPPED_SUBRESOURCE m; int ok = 0; - if (SUCCEEDED(ID3D11DeviceContext_Map(g->ctx, (ID3D11Resource *)st, 0, D3D11_MAP_READ, 0, &m))) { - /* like the raster: 0x00RRGGBB, or premultiplied 0xAARRGGBB with alpha */ - const uint32_t mask = g->alpha ? 0xFFFFFFFFu : 0xFFFFFFu; + if (SUCCEEDED(ID3D11DeviceContext_Map(d->ctx, (ID3D11Resource *)st, 0, D3D11_MAP_READ, 0, &m))) { for (int y = 0; y < h; y++) { - const uint32_t *src = (const uint32_t *)((const uint8_t *)m.pData + (size_t)y * m.RowPitch); - for (int x = 0; x < w; x++) { - dst[(size_t)y * w + x] = src[x] & mask; - } + memcpy(dst + (size_t)y * w, (const uint8_t *)m.pData + (size_t)y * m.RowPitch, + sizeof(uint32_t) * (size_t)w); } - ID3D11DeviceContext_Unmap(g->ctx, (ID3D11Resource *)st, 0); + ID3D11DeviceContext_Unmap(d->ctx, (ID3D11Resource *)st, 0); ok = 1; } REL(st); @@ -2122,206 +646,22 @@ int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h) /** \} */ -#elif !defined(BUI_GPU_GL) /* no GPU backend here (gpu_gl.c provides one on Linux; - * built without BUI_GPU): every raster stays in software */ - -# include "gpu_d3d11.h" - -int bui_gpu_slug_on(BuiGpu *g) -{ - (void)g; - return 0; -} -int bui_gpu_slug_glyph(BuiGpu *g, int face, int glyph, unsigned gen, float r_bbox[4], - float r_band[4], int r_loc[4]) -{ - (void)g; - (void)face; - (void)glyph; - (void)gen; - (void)r_bbox; - (void)r_band; - (void)r_loc; - return 0; -} - -# include - -# include "gpu_d3d11.h" - -BuiGpu *bui_gpu_create(void *hwnd, int alpha) -{ - (void)hwnd; - (void)alpha; - return NULL; -} -void bui_gpu_free(BuiGpu *g) -{ - (void)g; -} -int bui_gpu_state(BuiGpu *g, int wait) -{ - (void)g; - (void)wait; - return -1; -} -void bui_gpu_begin(BuiGpu *g, int w, int h) -{ - (void)g; - (void)w; - (void)h; -} -int bui_gpu_image_tex(BuiGpu *g, uint64_t key, uint64_t base, int stream, int format, - const uint32_t *argb, int stride, int w, int h) -{ - (void)g; - (void)key; - (void)base; - (void)stream; - (void)format; - (void)argb; - (void)stride; - (void)w; - (void)h; - return 0; -} -int bui_gpu_max_texture(BuiGpu *g) -{ - (void)g; - return 0; -} -BuiGpuInst *bui_gpu_inst_image(BuiGpu *g, int tex, int x0, int y0, int x1, int y1) -{ - (void)g; - (void)tex; - (void)x0; - (void)y0; - (void)x1; - (void)y1; - return NULL; -} -BuiGpuInst *bui_gpu_inst(BuiGpu *g, int kind, int x0, int y0, int x1, int y1) -{ - (void)g; - (void)kind; - (void)x0; - (void)y0; - (void)x1; - (void)y1; - return NULL; -} -int bui_gpu_mask(BuiGpu *g, const void *key, unsigned gen, const uint8_t *mask, int w, int h, - int *r_x, int *r_y) -{ - (void)g; - (void)key; - (void)gen; - (void)mask; - (void)w; - (void)h; - (void)r_x; - (void)r_y; - return 0; -} -int bui_gpu_image(BuiGpu *g, uint64_t key, const uint32_t *argb, int w, int h, int *r_x, int *r_y) -{ - (void)g; - (void)key; - (void)argb; - (void)w; - (void)h; - (void)r_x; - (void)r_y; - return 0; -} -void bui_gpu_triangles( - BuiGpu *g, const float (*co)[2], const float (*col)[4], int count, const int clip[4]) -{ - (void)g; - (void)co; - (void)col; - (void)count; - (void)clip; -} -void bui_gpu_mesh(BuiGpu *g, - const struct BuiMeshVertex *vtx, - int n_vtx, - const void *idx, - int idx32, - int n_idx, - float ox, - float oy, - int tex, - int nearest, - const int clip[4]) -{ - (void)g; - (void)vtx; - (void)n_vtx; - (void)idx; - (void)idx32; - (void)n_idx; - (void)ox; - (void)oy; - (void)tex; - (void)nearest; - (void)clip; -} -int bui_gpu_effect(BuiGpu *g, - int dst, - int effect, - const float rect[4], - const int inputs[BUI_EFFECT_MAX_INPUTS], - const float *floats, - int n_floats, - const int clip[4]) -{ - (void)g; - (void)dst; - (void)effect; - (void)rect; - (void)inputs; - (void)floats; - (void)n_floats; - (void)clip; - return 0; -} -int bui_gpu_target_clear(BuiGpu *g, int target, const float rgba[4]) -{ - (void)g; - (void)target; - (void)rgba; - return 0; -} -void bui_gpu_clear(BuiGpu *g, int x, int y, int w, int h) -{ - (void)g; - (void)x; - (void)y; - (void)w; - (void)h; -} -void bui_gpu_damage(BuiGpu *g, int x, int y, int w, int h) -{ - (void)g; - (void)x; - (void)y; - (void)w; - (void)h; -} -int bui_gpu_present(BuiGpu *g, int full) -{ - (void)g; - (void)full; - return 0; -} -int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h) -{ - (void)g; - (void)dst; - (void)w; - (void)h; - return 0; -} +const BuiGpuOps bui_gpu_d3d11_ops = { + BUI_GPU_API_D3D11, + d11_init, + d11_exit, + d11_tex_create, + d11_tex_update, + d11_tex_free, + d11_fx_build, + d11_fx_free, + d11_target, + d11_draw, + d11_clear, + d11_swap, + d11_present, + NULL, /* submit: the immediate context sends work on its own */ + d11_read, +}; -#endif /* _WIN32 */ +#endif /* _WIN32 && BUI_GPU */ diff --git a/gpu/intern/gpu_d3d11.h b/gpu/intern/gpu_d3d11.h index f1ac3d13..ee5bc2b2 100644 --- a/gpu/intern/gpu_d3d11.h +++ b/gpu/intern/gpu_d3d11.h @@ -1,9 +1,11 @@ -/* BUI GPU renderer (Direct3D 11) — private interface for gpu_raster.c. +/* BUI GPU renderer — private interface for gpu_raster.c. * * A BuiRaster in GPU mode records its primitives as instances instead of - * rasterizing them; this backend draws them into a persistent render target + * rasterizing them; the renderer draws them into a persistent render target * (so damage-region redraws work exactly like the software raster) and - * presents it with a flip-model swap chain plus dirty rects. + * presents it with a flip-model swap chain plus dirty rects. On Windows it is + * gpu_device.c over a Direct3D 11 (gpu_d3d11.c) or Direct3D 12 (gpu_d3d12.c) + * backend; on Linux gpu_gl.c (OpenGL 3.3). * * SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once @@ -44,11 +46,14 @@ typedef struct BuiGpuInst { typedef struct BuiGpu BuiGpu; /* Starts creating the device on a worker thread (the first frames keep - * using the software raster). NULL when D3D11 isn't available. */ + * using the software raster), on the API BUI_gpu_api() names. NULL when no + * GPU renderer is available. */ /* `alpha`: frames keep premultiplied alpha (the target starts transparent, and the window * shows it with per-pixel alpha). */ BuiGpu *bui_gpu_create(void *hwnd, int alpha); void bui_gpu_free(BuiGpu *g); +/* The API the (ready) device runs on. */ +BuiGpuApi bui_gpu_api_of(const BuiGpu *g); /* 1 once the device is ready, -1 when creation failed, 0 while pending * (never 0 with `wait`). */ int bui_gpu_state(BuiGpu *g, int wait); diff --git a/gpu/intern/gpu_d3d12.c b/gpu/intern/gpu_d3d12.c new file mode 100644 index 00000000..ce47f5a8 --- /dev/null +++ b/gpu/intern/gpu_d3d12.c @@ -0,0 +1,1474 @@ +/* BUI GPU renderer: the Direct3D 12 backend of gpu_device.c (opt-in: BUI_gpu_set_api, + * BUI_GPU_API; gpu_device.c falls back to Direct3D 11 when this one cannot start). + * + * The same pipeline as gpu_d3d11.c, drawn from the same shader bytecode (bui_ui.hlsl, shader model + * 4.0, which Direct3D 12 takes with a root signature): + * - one root signature for every program: b0 the frame's constants (root constants), b1 an + * effect's constants (a root CBV), t0..t5 the renderer's textures and t8.. an effect's inputs + * (two descriptor tables), s0 (a sampler table: linear or point); + * - one command list, recorded across a frame and executed at present (or read); FRAMES frame + * contexts, each with its command allocator, its share of the upload ring (instances, vertices, + * constants and texture uploads are written into persistently mapped upload buffers), its + * shader-visible descriptor heap (tables are copied in from CPU heaps where every texture keeps + * its views) and the objects freed while it was recorded; a fence says when a context is free + * again, so the CPU runs at most FRAMES frames ahead of the GPU; + * - textures track their state; uploads leave them in COPY_DEST and the next draw moves them all + * back to PIXEL_SHADER_RESOURCE in one barrier; + * - a flip-model swap chain on the window (opaque) or, for alpha windows (flip-model swap chains + * on a window ignore alpha), a premultiplied composition swap chain shown by DirectComposition; + * the damaged rects of the persistent target are copied into it, as on Direct3D 11. + * BUI_GPU_DEBUG=2 turns on the debug layer and prints its warnings and errors. + * + * SPDX-License-Identifier: GPL-2.0-or-later */ + +#if defined(_WIN32) && defined(BUI_GPU) /* BUI_GPU: features.json */ + +# define COBJMACROS +# include "gpu_dx.h" + +# include +# include + +# include +# include +# include + +static const GUID k_IID_ID3D12Device = { + 0x189819f1, 0x1db6, 0x4b57, {0xbe, 0x54, 0x18, 0x21, 0x33, 0x9b, 0x85, 0xf7}}; +static const GUID k_IID_ID3D12CommandQueue = { + 0x0ec870a6, 0x5d7e, 0x4c22, {0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed}}; +static const GUID k_IID_ID3D12CommandAllocator = { + 0x6102dee4, 0xaf59, 0x4b09, {0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24}}; +static const GUID k_IID_ID3D12GraphicsCommandList = { + 0x5b160d0f, 0xac1b, 0x4185, {0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55}}; +static const GUID k_IID_ID3D12Fence = { + 0x0a753dcf, 0xc4d8, 0x4b91, {0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76}}; +static const GUID k_IID_ID3D12DescriptorHeap = { + 0x8efb471d, 0x616c, 0x4f49, {0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51}}; +static const GUID k_IID_ID3D12Resource = { + 0x696442be, 0xa72e, 0x4059, {0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad}}; +static const GUID k_IID_ID3D12RootSignature = { + 0xc54a6b66, 0x72df, 0x4ee8, {0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14}}; +static const GUID k_IID_ID3D12PipelineState = { + 0x765a30f3, 0xf624, 0x4c6f, {0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45}}; +static const GUID k_IID_ID3D12Debug = { + 0x344488b7, 0x6846, 0x474b, {0xb9, 0x89, 0xf0, 0x27, 0x44, 0x82, 0x45, 0xe0}}; +static const GUID k_IID_ID3D12InfoQueue = { + 0x0742a90b, 0xc387, 0x483f, {0xb9, 0x46, 0x30, 0xa7, 0xe4, 0xe6, 0x14, 0x58}}; +static const GUID k_IID_ID3D12DebugDevice = { + 0x3febd6dd, 0x4973, 0x4787, {0x81, 0x94, 0xe4, 0x5f, 0x9e, 0x28, 0x92, 0x3e}}; +static const GUID k_IID_IDXGISwapChain3 = { + 0x94d99bdb, 0xf1f8, 0x4ab0, {0xb2, 0x36, 0x7d, 0xa0, 0x17, 0x0e, 0xda, 0xb1}}; +static const GUID k_IID_IDCompositionDevice = { + 0xc37ea93a, 0xe7aa, 0x450d, {0xb1, 0x6f, 0x97, 0x46, 0xcb, 0x04, 0x07, 0xf3}}; + +# define FRAMES 2 /* frame contexts: the CPU runs this many ahead */ +# define UPLOAD_CHUNK ((size_t)4 << 20) /* upload buffers are made this big (or as needed) */ +# define VIEWS 4096 /* shader-visible descriptors per frame context */ +# define HEAP_BLOCK 1024 /* CPU descriptors per heap block */ +# define HEAP_BLOCKS 64 +# define TEX_TABLE 6 /* t0..t5 */ +# define FX_TABLE BUI_EFFECT_MAX_INPUTS /* t8.. */ +# define PEND_MAX 64 + +enum { ROOT_FRAME = 0, ROOT_FX_CB, ROOT_TEX, ROOT_FX_TEX, ROOT_SAMPLER }; + +struct BuiGpuTex { + ID3D12Resource *res; + D3D12_RESOURCE_STATES state; + DXGI_FORMAT fmt; + int texel; /* bytes */ + int srv, rtv; /* CPU descriptor slots (rtv: -1 unless BUI_TEX_TARGET) */ + int pending; /* in D12.pend: back to PIXEL_SHADER_RESOURCE before the next draw */ +}; + +/* Effect pipelines by what they draw into: the frame (blended), then render targets of + * BUI_TARGET_RGBA8, _RGBA16F, _RGBA32F (replaced, as on Direct3D 11). */ +# define FX_PSOS 4 +struct BuiGpuProg { + ID3DBlob *vs, *ps; + ID3D12PipelineState *pso[FX_PSOS]; /* made on first use */ +}; + +typedef struct Chunk { + ID3D12Resource *buf; + uint8_t *cpu; + D3D12_GPU_VIRTUAL_ADDRESS gpu; + size_t size, used; +} Chunk; + +typedef struct Frame { + ID3D12CommandAllocator *alloc; + UINT64 fence; /* its work is done once the fence reaches this */ + Chunk *chunks; + int n_chunks, at_chunk; + ID3D12DescriptorHeap *views; /* shader visible */ + D3D12_CPU_DESCRIPTOR_HANDLE views_cpu; + D3D12_GPU_DESCRIPTOR_HANDLE views_gpu; + int n_views, cap_views; + IUnknown **dead; /* released once its work is done */ + int n_dead, cap_dead; +} Frame; + +/* A CPU descriptor heap: the views every texture keeps, copied into tables when drawn. */ +typedef struct CpuHeap { + D3D12_DESCRIPTOR_HEAP_TYPE type; + ID3D12DescriptorHeap *block[HEAP_BLOCKS]; + D3D12_CPU_DESCRIPTOR_HANDLE start[HEAP_BLOCKS]; + int n_block, next; + int *free_slots; + int n_free; + UINT inc; +} CpuHeap; + +/* An upload ring allocation. */ +typedef struct Upload { + ID3D12Resource *buf; + size_t offset; + uint8_t *cpu; + D3D12_GPU_VIRTUAL_ADDRESS gpu; +} Upload; + +/* DirectComposition (alpha windows). dcomp.h declares its interfaces for C++ only (overloads), so + * the few methods used here are declared by their vtable slots (as in dcomp.h's order). */ +typedef struct DcUnknown DcUnknown; +typedef struct DcDeviceVtbl { + HRESULT(STDMETHODCALLTYPE *QueryInterface)(DcUnknown *, REFIID, void **); + ULONG(STDMETHODCALLTYPE *AddRef)(DcUnknown *); + ULONG(STDMETHODCALLTYPE *Release)(DcUnknown *); + HRESULT(STDMETHODCALLTYPE *Commit)(DcUnknown *); + void *WaitForCommitCompletion, *GetFrameStatistics; + HRESULT(STDMETHODCALLTYPE *CreateTargetForHwnd)(DcUnknown *, HWND, BOOL, DcUnknown **); + HRESULT(STDMETHODCALLTYPE *CreateVisual)(DcUnknown *, DcUnknown **); +} DcDeviceVtbl; +typedef struct DcTargetVtbl { + void *QueryInterface, *AddRef, *Release; + HRESULT(STDMETHODCALLTYPE *SetRoot)(DcUnknown *, DcUnknown *); +} DcTargetVtbl; +typedef struct DcVisualVtbl { + /* IUnknown, then SetOffsetX x2, SetOffsetY x2, SetTransform x2, SetTransformParent, SetEffect, + * SetBitmapInterpolationMode, SetBorderMode, SetClip x2 */ + void *slots[15]; + HRESULT(STDMETHODCALLTYPE *SetContent)(DcUnknown *, IUnknown *); +} DcVisualVtbl; +struct DcUnknown { + const void *vtbl; +}; + +typedef struct D12 { + ID3D12Device *dev; + ID3D12CommandQueue *queue; + ID3D12GraphicsCommandList *list; + ID3D12Fence *fence; + HANDLE event; + UINT64 fence_value; + Frame frame[FRAMES]; + int cur; + int open; /* the list is recording */ + int lost; /* the device was removed */ + + ID3D12RootSignature *root; + ID3D12PipelineState *pso[BUI_DX_PROGRAMS]; + ID3D12DescriptorHeap *samplers; /* shader visible: linear, point */ + D3D12_GPU_DESCRIPTOR_HANDLE sampler_gpu[2]; + UINT view_inc; + CpuHeap srv_heap, rtv_heap; + int null_srv; + + BuiGpuTex *pend[PEND_MAX]; + int n_pend; + + IDXGIFactory4 *factory; + IDXGISwapChain3 *swap; + ID3D12Resource *back[2]; + DcUnknown *dcomp, *dcomp_target, *dcomp_visual; + + BuiGpuTex *target; + int tw, th; + + ID3D12InfoQueue *info; /* BUI_GPU_DEBUG=2 */ + int n_errors, n_warnings; +} D12; + +# define DEV(g) ((D12 *)(g)->dev) + +/* ID3D12DescriptorHeap::GetCPU/GPUDescriptorHandleForHeapStart return a struct, which a C++ member + * function returns through a hidden pointer after `this`; the C declarations of older SDKs say + * otherwise. Called through the vtable with the real signature, they work with every header. */ +typedef void(STDMETHODCALLTYPE *CpuStartFn)(ID3D12DescriptorHeap *, D3D12_CPU_DESCRIPTOR_HANDLE *); +typedef void(STDMETHODCALLTYPE *GpuStartFn)(ID3D12DescriptorHeap *, D3D12_GPU_DESCRIPTOR_HANDLE *); + +static D3D12_CPU_DESCRIPTOR_HANDLE cpu_start(ID3D12DescriptorHeap *h) +{ + D3D12_CPU_DESCRIPTOR_HANDLE r; + ((CpuStartFn)(void *)h->lpVtbl->GetCPUDescriptorHandleForHeapStart)(h, &r); + return r; +} + +static D3D12_GPU_DESCRIPTOR_HANDLE gpu_start(ID3D12DescriptorHeap *h) +{ + D3D12_GPU_DESCRIPTOR_HANDLE r; + ((GpuStartFn)(void *)h->lpVtbl->GetGPUDescriptorHandleForHeapStart)(h, &r); + return r; +} + +static DXGI_FORMAT dxgi_format(BuiGpuFormat fmt, int *r_texel) +{ + static const DXGI_FORMAT map[] = { + DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_B8G8R8A8_UNORM, + DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT, + DXGI_FORMAT_R32G32_UINT, + }; + static const int texel[] = {1, 2, 4, 4, 8, 16, 8}; + *r_texel = texel[fmt]; + return map[fmt]; +} + +/* -------------------------------------------------------------------- */ +/** \name Debug layer (BUI_GPU_DEBUG=2) + * \{ */ + +/* Prints the warnings and errors the debug layer stored since the last call. `live`: they are + * ReportLiveDeviceObjects' list, where anything but the device itself is a leak. */ +static void debug_drain(D12 *d, int live) +{ + if (!d->info) { + return; + } + const UINT64 n = ID3D12InfoQueue_GetNumStoredMessages(d->info); + for (UINT64 i = 0; i < n; i++) { + SIZE_T len = 0; + if (FAILED(ID3D12InfoQueue_GetMessage(d->info, i, NULL, &len))) { + continue; + } + D3D12_MESSAGE *m = (D3D12_MESSAGE *)malloc(len); + if (m && SUCCEEDED(ID3D12InfoQueue_GetMessage(d->info, i, m, &len)) && + !(live && strncmp(m->pDescription, "Live ID3D12Device ", 18) == 0)) + { + const int err = live || m->Severity <= D3D12_MESSAGE_SEVERITY_ERROR; + d->n_errors += err; + d->n_warnings += !err; + fprintf(stderr, "bui gpu: d3d12 %s: %s\n", live ? "leak" : err ? "error" : "warning", + m->pDescription); + } + free(m); + } + ID3D12InfoQueue_ClearStoredMessages(d->info); +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Frame contexts, the upload ring and descriptors + * \{ */ + +static void wait_fence(D12 *d, UINT64 value) +{ + /* a removed device completes every value (UINT64_MAX): nothing waits forever */ + if (ID3D12Fence_GetCompletedValue(d->fence) < value && + SUCCEEDED(ID3D12Fence_SetEventOnCompletion(d->fence, value, d->event))) + { + WaitForSingleObject(d->event, INFINITE); + } +} + +static void gpu_idle(D12 *d); + +/* Releases `obj` once the work recorded so far is done. */ +static void defer_release(D12 *d, IUnknown *obj) +{ + if (!obj) { + return; + } + Frame *f = &d->frame[d->cur]; + if (f->n_dead == f->cap_dead) { + const int cap = f->cap_dead ? f->cap_dead * 2 : 64; + IUnknown **nd = (IUnknown **)realloc(f->dead, sizeof(IUnknown *) * (size_t)cap); + if (!nd) { /* out of memory: everything recorded runs first */ + gpu_idle(d); + IUnknown_Release(obj); + return; + } + f->dead = nd; + f->cap_dead = cap; + } + f->dead[f->n_dead++] = obj; +} + +static void frame_release(Frame *f) +{ + for (int i = 0; i < f->n_dead; i++) { + IUnknown_Release(f->dead[i]); + } + f->n_dead = 0; +} + +/* Starts recording into the current frame context once the GPU is done with it. */ +static void ctx_begin(D12 *d) +{ + Frame *f = &d->frame[d->cur]; + wait_fence(d, f->fence); + frame_release(f); + for (int i = 0; i < f->n_chunks; i++) { + f->chunks[i].used = 0; + } + f->at_chunk = 0; + f->n_views = 0; + if (FAILED(ID3D12CommandAllocator_Reset(f->alloc)) || + FAILED(ID3D12GraphicsCommandList_Reset(d->list, f->alloc, NULL))) + { + d->lost = 1; + return; + } + d->open = 1; + ID3D12DescriptorHeap *heaps[2] = {f->views, d->samplers}; + ID3D12GraphicsCommandList_SetDescriptorHeaps(d->list, 2, heaps); + ID3D12GraphicsCommandList_SetGraphicsRootSignature(d->list, d->root); +} + +/* Executes what was recorded and moves to the next frame context (ctx_begin starts it). */ +static void ctx_submit(D12 *d) +{ + if (d->open) { + d->open = 0; + if (SUCCEEDED(ID3D12GraphicsCommandList_Close(d->list))) { + ID3D12CommandList *lists[1] = {(ID3D12CommandList *)d->list}; + ID3D12CommandQueue_ExecuteCommandLists(d->queue, 1, lists); + } + } + ID3D12CommandQueue_Signal(d->queue, d->fence, ++d->fence_value); + d->frame[d->cur].fence = d->fence_value; + d->cur = (d->cur + 1) % FRAMES; + if (FAILED(ID3D12Device_GetDeviceRemovedReason(d->dev))) { + d->lost = 1; + } + debug_drain(d, 0); +} + +/* Everything recorded runs to completion; recording goes on in a fresh context. */ +static void gpu_idle(D12 *d) +{ + ctx_submit(d); + wait_fence(d, d->fence_value); + ctx_begin(d); +} + +static ID3D12Resource *buffer(D12 *d, D3D12_HEAP_TYPE heap, size_t size, D3D12_RESOURCE_STATES state) +{ + D3D12_HEAP_PROPERTIES hp = {heap, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 1, 1}; + D3D12_RESOURCE_DESC rd; + memset(&rd, 0, sizeof(rd)); + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + rd.Width = size; + rd.Height = rd.DepthOrArraySize = rd.MipLevels = 1; + rd.Format = DXGI_FORMAT_UNKNOWN; + rd.SampleDesc.Count = 1; + rd.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource *r = NULL; + if (FAILED(ID3D12Device_CreateCommittedResource(d->dev, &hp, D3D12_HEAP_FLAG_NONE, &rd, state, NULL, + &k_IID_ID3D12Resource, (void **)&r))) + { + return NULL; + } + return r; +} + +/* `size` bytes of the current frame context's upload ring, `align`ed. 0 when out of memory. */ +static int upload_alloc(D12 *d, size_t size, size_t align, Upload *r) +{ + Frame *f = &d->frame[d->cur]; + for (; f->at_chunk < f->n_chunks; f->at_chunk++) { + Chunk *c = &f->chunks[f->at_chunk]; + const size_t at = (c->used + align - 1) & ~(align - 1); + if (at + size <= c->size) { + c->used = at + size; + r->buf = c->buf; + r->offset = at; + r->cpu = c->cpu + at; + r->gpu = c->gpu + at; + return 1; + } + } + Chunk *nc = (Chunk *)realloc(f->chunks, sizeof(Chunk) * (size_t)(f->n_chunks + 1)); + if (!nc) { + return 0; + } + f->chunks = nc; + Chunk *c = &f->chunks[f->n_chunks]; + memset(c, 0, sizeof(*c)); + c->size = size > UPLOAD_CHUNK ? size : UPLOAD_CHUNK; + c->buf = buffer(d, D3D12_HEAP_TYPE_UPLOAD, c->size, D3D12_RESOURCE_STATE_GENERIC_READ); + const D3D12_RANGE none = {0, 0}; + if (!c->buf || FAILED(ID3D12Resource_Map(c->buf, 0, &none, (void **)&c->cpu))) { + REL(c->buf); + return 0; + } + c->gpu = ID3D12Resource_GetGPUVirtualAddress(c->buf); + f->at_chunk = f->n_chunks++; + return upload_alloc(d, size, align, r); +} + +static int heap_init(D12 *d, CpuHeap *h, D3D12_DESCRIPTOR_HEAP_TYPE type) +{ + h->type = type; + h->inc = ID3D12Device_GetDescriptorHandleIncrementSize(d->dev, type); + return 1; +} + +/* A free slot of `h` (-1 when none can be made). */ +static int slot_alloc(D12 *d, CpuHeap *h) +{ + if (h->n_free > 0) { + return h->free_slots[--h->n_free]; + } + if (h->next == h->n_block * HEAP_BLOCK) { + D3D12_DESCRIPTOR_HEAP_DESC hd = {h->type, HEAP_BLOCK, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + int *nf = (int *)realloc(h->free_slots, sizeof(int) * (size_t)(h->n_block + 1) * HEAP_BLOCK); + if (h->n_block == HEAP_BLOCKS || !nf) { + return -1; + } + h->free_slots = nf; + if (FAILED(ID3D12Device_CreateDescriptorHeap(d->dev, &hd, &k_IID_ID3D12DescriptorHeap, + (void **)&h->block[h->n_block]))) + { + return -1; + } + h->start[h->n_block] = cpu_start(h->block[h->n_block]); + h->n_block++; + } + return h->next++; +} + +static void slot_free(CpuHeap *h, int slot) +{ + if (slot >= 0) { + h->free_slots[h->n_free++] = slot; + } +} + +static D3D12_CPU_DESCRIPTOR_HANDLE slot_cpu(const CpuHeap *h, int slot) +{ + D3D12_CPU_DESCRIPTOR_HANDLE c = h->start[slot / HEAP_BLOCK]; + c.ptr += (SIZE_T)(slot % HEAP_BLOCK) * h->inc; + return c; +} + +static void heap_exit(CpuHeap *h) +{ + for (int i = 0; i < h->n_block; i++) { + REL(h->block[i]); + } + free(h->free_slots); +} + +/* The current frame context's shader-visible heap holds `need` more descriptors (a context with + * draws recorded is sent off when it does not: the next one starts empty, and grows if need be). */ +static void views_reserve(D12 *d, int need) +{ + Frame *f = &d->frame[d->cur]; + if (f->cap_views - f->n_views >= need) { + return; + } + if (f->n_views > 0) { + ctx_submit(d); + ctx_begin(d); + f = &d->frame[d->cur]; + } + if (f->cap_views < need) { /* idle (ctx_begin waited for it) and nothing bound from it yet */ + const int cap = need > 2 * f->cap_views ? need : 2 * f->cap_views; + D3D12_DESCRIPTOR_HEAP_DESC hd = {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, (UINT)cap, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ID3D12DescriptorHeap *nh = NULL; + if (FAILED(ID3D12Device_CreateDescriptorHeap(d->dev, &hd, &k_IID_ID3D12DescriptorHeap, + (void **)&nh))) + { + return; + } + defer_release(d, (IUnknown *)f->views); + f->views = nh; + f->views_cpu = cpu_start(nh); + f->views_gpu = gpu_start(nh); + f->cap_views = cap; + ID3D12DescriptorHeap *heaps[2] = {f->views, d->samplers}; + ID3D12GraphicsCommandList_SetDescriptorHeaps(d->list, 2, heaps); + } +} + +/* A descriptor table of the textures' views (NULL: a null view), in the current context. */ +static D3D12_GPU_DESCRIPTOR_HANDLE table(D12 *d, BuiGpuTex *const *tex, int n) +{ + Frame *f = &d->frame[d->cur]; + D3D12_GPU_DESCRIPTOR_HANDLE gpu = f->views_gpu; + if (f->n_views + n > f->cap_views) { /* views_reserve said otherwise: draw with what is there */ + return gpu; + } + gpu.ptr += (UINT64)f->n_views * d->view_inc; + for (int i = 0; i < n; i++) { + D3D12_CPU_DESCRIPTOR_HANDLE dst = f->views_cpu; + dst.ptr += (SIZE_T)(f->n_views + i) * d->view_inc; + ID3D12Device_CopyDescriptorsSimple(d->dev, 1, dst, + slot_cpu(&d->srv_heap, tex[i] ? tex[i]->srv : d->null_srv), + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } + f->n_views += n; + return gpu; +} + +static void barrier(D12 *d, ID3D12Resource *res, D3D12_RESOURCE_STATES from, + D3D12_RESOURCE_STATES to) +{ + D3D12_RESOURCE_BARRIER b; + memset(&b, 0, sizeof(b)); + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition.pResource = res; + b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b.Transition.StateBefore = from; + b.Transition.StateAfter = to; + ID3D12GraphicsCommandList_ResourceBarrier(d->list, 1, &b); +} + +/* `t` in state `s` for what is recorded next. */ +static void use(D12 *d, BuiGpuTex *t, D3D12_RESOURCE_STATES s) +{ + if (t->state != s) { + barrier(d, t->res, t->state, s); + t->state = s; + } +} + +/* Textures uploaded to since the last draw: sampled again, in one barrier. */ +static void pend_flush(D12 *d) +{ + D3D12_RESOURCE_BARRIER b[PEND_MAX]; + int n = 0; + for (int i = 0; i < d->n_pend; i++) { + BuiGpuTex *t = d->pend[i]; + t->pending = 0; + if (t->state != D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE) { + memset(&b[n], 0, sizeof(b[n])); + b[n].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b[n].Transition.pResource = t->res; + b[n].Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + b[n].Transition.StateBefore = t->state; + b[n].Transition.StateAfter = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + t->state = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + n++; + } + } + d->n_pend = 0; + if (n) { + ID3D12GraphicsCommandList_ResourceBarrier(d->list, (UINT)n, b); + } +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Textures + * \{ */ + +static void d12_tex_free(BuiGpu *g, BuiGpuTex *t) +{ + D12 *d = DEV(g); + if (t->pending) { + for (int i = 0; i < d->n_pend; i++) { + if (d->pend[i] == t) { + d->pend[i] = d->pend[--d->n_pend]; + break; + } + } + } + /* views are copied into tables when recorded: their slots are free at once */ + slot_free(&d->srv_heap, t->srv); + slot_free(&d->rtv_heap, t->rtv); + defer_release(d, (IUnknown *)t->res); + free(t); +} + +/* A texture; a BUI_TEX_TARGET one starts cleared to `clear`, its optimized clear value. */ +static BuiGpuTex *tex_make(D12 *d, BuiGpuFormat fmt, int w, int h, int flags, const float clear[4]) +{ + BuiGpuTex *t = d->open ? (BuiGpuTex *)calloc(1, sizeof(BuiGpuTex)) : NULL; /* closed: lost */ + if (!t) { + return NULL; + } + t->srv = t->rtv = -1; + t->fmt = dxgi_format(fmt, &t->texel); + const int target = (flags & BUI_TEX_TARGET) != 0; + D3D12_HEAP_PROPERTIES hp = {D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, + D3D12_MEMORY_POOL_UNKNOWN, 1, 1}; + D3D12_RESOURCE_DESC rd; + memset(&rd, 0, sizeof(rd)); + rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rd.Width = (UINT64)w; + rd.Height = (UINT)h; + rd.DepthOrArraySize = rd.MipLevels = 1; + rd.Format = t->fmt; + rd.SampleDesc.Count = 1; + rd.Flags = target ? D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET : D3D12_RESOURCE_FLAG_NONE; + D3D12_CLEAR_VALUE cv; + cv.Format = t->fmt; + memcpy(cv.Color, clear, sizeof(cv.Color)); + /* committed resources start zeroed: one made without data is sampled as it is */ + t->state = target ? D3D12_RESOURCE_STATE_RENDER_TARGET : D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; + if (FAILED(ID3D12Device_CreateCommittedResource(d->dev, &hp, D3D12_HEAP_FLAG_NONE, &rd, t->state, + target ? &cv : NULL, &k_IID_ID3D12Resource, + (void **)&t->res)) || + (t->srv = slot_alloc(d, &d->srv_heap)) < 0 || + (target && (t->rtv = slot_alloc(d, &d->rtv_heap)) < 0)) + { + REL(t->res); + slot_free(&d->srv_heap, t->srv); + free(t); + return NULL; + } + D3D12_SHADER_RESOURCE_VIEW_DESC sd; + memset(&sd, 0, sizeof(sd)); + sd.Format = t->fmt; + sd.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + sd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + sd.Texture2D.MipLevels = 1; + ID3D12Device_CreateShaderResourceView(d->dev, t->res, &sd, slot_cpu(&d->srv_heap, t->srv)); + if (target) { + ID3D12Device_CreateRenderTargetView(d->dev, t->res, NULL, slot_cpu(&d->rtv_heap, t->rtv)); + ID3D12GraphicsCommandList_ClearRenderTargetView(d->list, slot_cpu(&d->rtv_heap, t->rtv), clear, 0, + NULL); + } + return t; +} + +static void d12_tex_update(BuiGpu *g, BuiGpuTex *t, int x, int y, int w, int h, const void *data, + int pitch) +{ + D12 *d = DEV(g); + if (w <= 0 || h <= 0 || !d->open) { + return; + } + const UINT row = (UINT)(w * t->texel); + const UINT rp = (row + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1); + if (!t->pending && d->n_pend == PEND_MAX) { + pend_flush(d); + } + Upload u; + if (!upload_alloc(d, (size_t)rp * h, D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT, &u)) { + return; + } + for (int j = 0; j < h; j++) { + memcpy(u.cpu + (size_t)rp * j, (const uint8_t *)data + (size_t)pitch * j, row); + } + use(d, t, D3D12_RESOURCE_STATE_COPY_DEST); + if (!t->pending) { + t->pending = 1; + d->pend[d->n_pend++] = t; + } + D3D12_TEXTURE_COPY_LOCATION dst, src; + memset(&dst, 0, sizeof(dst)); + memset(&src, 0, sizeof(src)); + dst.pResource = t->res; + dst.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dst.SubresourceIndex = 0; + src.pResource = u.buf; + src.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + src.PlacedFootprint.Offset = u.offset; + src.PlacedFootprint.Footprint.Format = t->fmt; + src.PlacedFootprint.Footprint.Width = (UINT)w; + src.PlacedFootprint.Footprint.Height = (UINT)h; + src.PlacedFootprint.Footprint.Depth = 1; + src.PlacedFootprint.Footprint.RowPitch = rp; + ID3D12GraphicsCommandList_CopyTextureRegion(d->list, &dst, (UINT)x, (UINT)y, 0, &src, NULL); +} + +static BuiGpuTex *d12_tex_create(BuiGpu *g, BuiGpuFormat fmt, int w, int h, const void *data, + int pitch, int flags) +{ + const float zero[4] = {0, 0, 0, 0}; + BuiGpuTex *t = tex_make(DEV(g), fmt, w, h, flags, zero); + if (t && data) { + d12_tex_update(g, t, 0, 0, w, h, data, pitch); + } + return t; +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Pipelines and effects + * \{ */ + +/* A pipeline of the root signature drawing into `rt`, premultiplied blending or none. */ +static ID3D12PipelineState *pso_make(D12 *d, const void *vs, size_t vs_size, const void *ps, + size_t ps_size, const BuiDxInput *in, UINT n_in, + DXGI_FORMAT rt, int blend) +{ + D3D12_INPUT_ELEMENT_DESC el[8]; + for (UINT k = 0; k < n_in; k++) { + el[k].SemanticName = in[k].semantic; + el[k].SemanticIndex = in[k].index; + el[k].Format = in[k].format; + el[k].InputSlot = 0; + el[k].AlignedByteOffset = in[k].offset; + el[k].InputSlotClass = in[k].instanced ? D3D12_INPUT_CLASSIFICATION_PER_INSTANCE_DATA : + D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA; + el[k].InstanceDataStepRate = in[k].instanced; + } + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd; + memset(&pd, 0, sizeof(pd)); + pd.pRootSignature = d->root; + pd.VS.pShaderBytecode = vs; + pd.VS.BytecodeLength = vs_size; + pd.PS.pShaderBytecode = ps; + pd.PS.BytecodeLength = ps_size; + D3D12_RENDER_TARGET_BLEND_DESC *b = &pd.BlendState.RenderTarget[0]; + b->BlendEnable = blend ? TRUE : FALSE; + b->SrcBlend = b->SrcBlendAlpha = D3D12_BLEND_ONE; + b->DestBlend = b->DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA; + b->BlendOp = b->BlendOpAlpha = D3D12_BLEND_OP_ADD; + b->LogicOp = D3D12_LOGIC_OP_NOOP; + b->RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pd.SampleMask = 0xFFFFFFFFu; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_ALWAYS; + const D3D12_DEPTH_STENCILOP_DESC keep = {D3D12_STENCIL_OP_KEEP, D3D12_STENCIL_OP_KEEP, + D3D12_STENCIL_OP_KEEP, D3D12_COMPARISON_FUNC_ALWAYS}; + pd.DepthStencilState.FrontFace = pd.DepthStencilState.BackFace = keep; + pd.InputLayout.pInputElementDescs = n_in ? el : NULL; + pd.InputLayout.NumElements = n_in; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.NumRenderTargets = 1; + pd.RTVFormats[0] = rt; + pd.SampleDesc.Count = 1; + ID3D12PipelineState *pso = NULL; + if (FAILED(ID3D12Device_CreateGraphicsPipelineState(d->dev, &pd, &k_IID_ID3D12PipelineState, + (void **)&pso))) + { + return NULL; + } + return pso; +} + +static void d12_fx_free(BuiGpu *g, BuiGpuProg *p) +{ + D12 *d = DEV(g); + for (int i = 0; i < FX_PSOS; i++) { + defer_release(d, (IUnknown *)p->pso[i]); + } + REL(p->vs); + REL(p->ps); + free(p); +} + +static BuiGpuProg *d12_fx_build(BuiGpu *g, const BuiEffectView *v, char *log, size_t log_n) +{ + D12 *d = DEV(g); + BuiGpuProg *p = (BuiGpuProg *)calloc(1, sizeof(BuiGpuProg)); + if (!p) { + snprintf(log, log_n, "out of memory"); + return NULL; + } + if (!bui_dx_fx_compile(v, "5_0", &p->vs, &p->ps, log, log_n)) { + free(p); + return NULL; + } + /* the frame's pipeline now, so a shader the device rejects fails here, with its log */ + p->pso[0] = pso_make(d, ID3D10Blob_GetBufferPointer(p->vs), ID3D10Blob_GetBufferSize(p->vs), + ID3D10Blob_GetBufferPointer(p->ps), ID3D10Blob_GetBufferSize(p->ps), NULL, 0, + DXGI_FORMAT_B8G8R8A8_UNORM, 1); + if (!p->pso[0]) { + snprintf(log, log_n, "the device rejected the compiled shader"); + d12_fx_free(g, p); + return NULL; + } + return p; +} + +/* Effect `p`'s pipeline for pipeline slot `i` (FX_PSOS), made on first use. */ +static ID3D12PipelineState *fx_pso(D12 *d, BuiGpuProg *p, int i) +{ + static const BuiGpuFormat fmt[FX_PSOS] = {BUI_FMT_BGRA8, BUI_FMT_RGBA8, BUI_FMT_RGBA16F, + BUI_FMT_RGBA32F}; + if (!p->pso[i]) { + int texel; + p->pso[i] = pso_make(d, ID3D10Blob_GetBufferPointer(p->vs), ID3D10Blob_GetBufferSize(p->vs), + ID3D10Blob_GetBufferPointer(p->ps), ID3D10Blob_GetBufferSize(p->ps), NULL, + 0, dxgi_format(fmt[i], &texel), i == 0); + } + return p->pso[i]; +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Device (worker thread) + * \{ */ + +typedef HRESULT(WINAPI *CreateDeviceFn)(IUnknown *, D3D_FEATURE_LEVEL, REFIID, void **); +typedef HRESULT(WINAPI *SerializeFn)(const D3D12_ROOT_SIGNATURE_DESC *, D3D_ROOT_SIGNATURE_VERSION, + ID3DBlob **, ID3DBlob **); +typedef HRESULT(WINAPI *GetDebugFn)(REFIID, void **); +typedef HRESULT(WINAPI *FactoryFn)(REFIID, void **); + +static int root_init(D12 *d, SerializeFn serialize) +{ + const D3D12_DESCRIPTOR_RANGE tex = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, TEX_TABLE, 0, 0, 0}; + const D3D12_DESCRIPTOR_RANGE fx = {D3D12_DESCRIPTOR_RANGE_TYPE_SRV, FX_TABLE, 8, 0, 0}; + const D3D12_DESCRIPTOR_RANGE smp = {D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER p[5]; + memset(p, 0, sizeof(p)); + p[ROOT_FRAME].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + p[ROOT_FRAME].Constants.ShaderRegister = 0; + p[ROOT_FRAME].Constants.Num32BitValues = 4; + p[ROOT_FRAME].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + p[ROOT_FX_CB].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; + p[ROOT_FX_CB].Descriptor.ShaderRegister = 1; + p[ROOT_FX_CB].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + const D3D12_DESCRIPTOR_RANGE *ranges[3] = {&tex, &fx, &smp}; + for (int i = 0; i < 3; i++) { + p[ROOT_TEX + i].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + p[ROOT_TEX + i].DescriptorTable.NumDescriptorRanges = 1; + p[ROOT_TEX + i].DescriptorTable.pDescriptorRanges = ranges[i]; + p[ROOT_TEX + i].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + } + D3D12_ROOT_SIGNATURE_DESC rs = {5, p, 0, NULL, + D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT}; + ID3DBlob *blob = NULL, *err = NULL; + HRESULT hr = serialize(&rs, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &err); + if (SUCCEEDED(hr)) { + hr = ID3D12Device_CreateRootSignature(d->dev, 0, ID3D10Blob_GetBufferPointer(blob), + ID3D10Blob_GetBufferSize(blob), &k_IID_ID3D12RootSignature, + (void **)&d->root); + } + REL(blob); + REL(err); + return SUCCEEDED(hr) ? 1 : bui_gpu_fail("root signature", hr); +} + +static int samplers_init(D12 *d) +{ + D3D12_DESCRIPTOR_HEAP_DESC hd = {D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + if (FAILED(ID3D12Device_CreateDescriptorHeap(d->dev, &hd, &k_IID_ID3D12DescriptorHeap, + (void **)&d->samplers))) + { + return bui_gpu_fail("sampler heap", 0); + } + const UINT inc = ID3D12Device_GetDescriptorHandleIncrementSize(d->dev, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + D3D12_CPU_DESCRIPTOR_HANDLE c = cpu_start(d->samplers); + D3D12_GPU_DESCRIPTOR_HANDLE gh = gpu_start(d->samplers); + D3D12_SAMPLER_DESC sd; + memset(&sd, 0, sizeof(sd)); + sd.AddressU = sd.AddressV = sd.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; + sd.MaxLOD = D3D12_FLOAT32_MAX; + sd.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; + for (int i = 0; i < 2; i++) { /* linear, point (as gpu_d3d11.c) */ + sd.Filter = i ? D3D12_FILTER_MIN_MAG_MIP_POINT : D3D12_FILTER_MIN_MAG_MIP_LINEAR; + ID3D12Device_CreateSampler(d->dev, &sd, c); + d->sampler_gpu[i] = gh; + c.ptr += inc; + gh.ptr += inc; + } + return 1; +} + +/* The adapter: BUI_GPU_WARP's software one, BUI_GPU_ADAPTER's, else the first (the display's, + * which D3D12CreateDevice takes for NULL too). */ +static IDXGIAdapter *adapter(D12 *d) +{ + IDXGIAdapter *ad = NULL; + const char *warp = getenv("BUI_GPU_WARP"); + if (warp && warp[0] == '1') { + return SUCCEEDED(IDXGIFactory4_EnumWarpAdapter(d->factory, &bui_IID_IDXGIAdapter, (void **)&ad)) ? + ad : + NULL; + } + ad = bui_dx_preferred_adapter(); + if (!ad && FAILED(IDXGIFactory4_EnumAdapters(d->factory, 0, &ad))) { + ad = NULL; + } + return ad; +} + +static int d12_init(BuiGpu *g) +{ + D12 *d = (D12 *)calloc(1, sizeof(D12)); + if (!d) { + return 0; + } + g->dev = d; + d->null_srv = -1; + HMODULE dll = LoadLibraryW(L"d3d12.dll"); + HMODULE dxgi = LoadLibraryW(L"dxgi.dll"); + if (!dll || !dxgi) { + return bui_gpu_fail("loading d3d12.dll", 0); + } + CreateDeviceFn create = (CreateDeviceFn)(void *)GetProcAddress(dll, "D3D12CreateDevice"); + SerializeFn serialize = (SerializeFn)(void *)GetProcAddress(dll, "D3D12SerializeRootSignature"); + GetDebugFn get_debug = (GetDebugFn)(void *)GetProcAddress(dll, "D3D12GetDebugInterface"); + FactoryFn factory = (FactoryFn)(void *)GetProcAddress(dxgi, "CreateDXGIFactory1"); + if (!create || !serialize || !factory || + FAILED(factory(&bui_IID_IDXGIFactory4, (void **)&d->factory))) + { + return bui_gpu_fail("Direct3D 12 runtime", 0); + } + if (bui_gpu_debug() >= 2 && get_debug) { + ID3D12Debug *dbg = NULL; + if (SUCCEEDED(get_debug(&k_IID_ID3D12Debug, (void **)&dbg))) { + ID3D12Debug_EnableDebugLayer(dbg); + REL(dbg); + } + else { + bui_gpu_fail("the Direct3D 12 debug layer (Graphics Tools)", 0); + } + } + IDXGIAdapter *ad = adapter(d); + HRESULT hr = create((IUnknown *)ad, D3D_FEATURE_LEVEL_11_0, &k_IID_ID3D12Device, (void **)&d->dev); + if (SUCCEEDED(hr)) { + bui_dx_report("Direct3D 12", ad); + } + REL(ad); + if (FAILED(hr)) { + return bui_gpu_fail("D3D12CreateDevice", hr); + } + if (bui_gpu_debug() >= 2 && + SUCCEEDED(ID3D12Device_QueryInterface(d->dev, &k_IID_ID3D12InfoQueue, (void **)&d->info))) + { + D3D12_MESSAGE_SEVERITY deny[] = {D3D12_MESSAGE_SEVERITY_INFO, D3D12_MESSAGE_SEVERITY_MESSAGE}; + /* a performance hint, not a fault: render targets are cleared to any colour + * (BUI_raster_target_clear), their optimized clear value is the one they start with */ + D3D12_MESSAGE_ID ids[] = {D3D12_MESSAGE_ID_CLEARRENDERTARGETVIEW_MISMATCHINGCLEARVALUE}; + D3D12_INFO_QUEUE_FILTER filter; + memset(&filter, 0, sizeof(filter)); + filter.DenyList.NumSeverities = 2; + filter.DenyList.pSeverityList = deny; + filter.DenyList.NumIDs = 1; + filter.DenyList.pIDList = ids; + ID3D12InfoQueue_PushStorageFilter(d->info, &filter); + } + g->max_tex = D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; + D3D12_COMMAND_QUEUE_DESC qd = {D3D12_COMMAND_LIST_TYPE_DIRECT, 0, D3D12_COMMAND_QUEUE_FLAG_NONE, 0}; + if (FAILED(ID3D12Device_CreateCommandQueue(d->dev, &qd, &k_IID_ID3D12CommandQueue, + (void **)&d->queue)) || + FAILED(ID3D12Device_CreateFence(d->dev, 0, D3D12_FENCE_FLAG_NONE, &k_IID_ID3D12Fence, + (void **)&d->fence)) || + !(d->event = CreateEventW(NULL, FALSE, FALSE, NULL))) + { + return bui_gpu_fail("command queue", 0); + } + d->view_inc = ID3D12Device_GetDescriptorHandleIncrementSize(d->dev, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + for (int i = 0; i < FRAMES; i++) { + Frame *f = &d->frame[i]; + D3D12_DESCRIPTOR_HEAP_DESC hd = {D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, VIEWS, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + if (FAILED(ID3D12Device_CreateCommandAllocator(d->dev, D3D12_COMMAND_LIST_TYPE_DIRECT, + &k_IID_ID3D12CommandAllocator, + (void **)&f->alloc)) || + FAILED(ID3D12Device_CreateDescriptorHeap(d->dev, &hd, &k_IID_ID3D12DescriptorHeap, + (void **)&f->views))) + { + return bui_gpu_fail("frame contexts", 0); + } + f->views_cpu = cpu_start(f->views); + f->views_gpu = gpu_start(f->views); + f->cap_views = VIEWS; + } + if (FAILED(ID3D12Device_CreateCommandList(d->dev, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, + d->frame[0].alloc, NULL, + &k_IID_ID3D12GraphicsCommandList, (void **)&d->list)) || + FAILED(ID3D12GraphicsCommandList_Close(d->list))) + { + return bui_gpu_fail("command list", 0); + } + heap_init(d, &d->srv_heap, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + heap_init(d, &d->rtv_heap, D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + if ((d->null_srv = slot_alloc(d, &d->srv_heap)) < 0) { + return bui_gpu_fail("descriptor heap", 0); + } + D3D12_SHADER_RESOURCE_VIEW_DESC nd; + memset(&nd, 0, sizeof(nd)); + nd.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + nd.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + nd.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + nd.Texture2D.MipLevels = 1; + ID3D12Device_CreateShaderResourceView(d->dev, NULL, &nd, slot_cpu(&d->srv_heap, d->null_srv)); + if (!samplers_init(d) || !root_init(d, serialize)) { + return 0; + } + for (int i = 0; i < BUI_DX_PROGRAMS; i++) { + const BuiDxProgram *p = &bui_dx_programs[i]; + d->pso[i] = pso_make(d, p->vs, p->vs_size, p->ps, p->ps_size, p->inputs, p->n_inputs, + DXGI_FORMAT_B8G8R8A8_UNORM, 1); + if (!d->pso[i]) { + return bui_gpu_fail("pipeline state", 0); + } + } + ctx_begin(d); + return !d->lost; +} + +static void d12_exit(BuiGpu *g) +{ + D12 *d = DEV(g); + if (d->queue && d->fence) { /* nothing of ours may be in flight */ + ID3D12CommandQueue_Signal(d->queue, d->fence, ++d->fence_value); + wait_fence(d, d->fence_value); + } + if (d->target) { + d12_tex_free(g, d->target); + } + for (int i = 0; i < 2; i++) { + REL(d->back[i]); + } + REL(d->swap); + REL(d->dcomp_visual); + REL(d->dcomp_target); + REL(d->dcomp); + for (int i = 0; i < FRAMES; i++) { + Frame *f = &d->frame[i]; + frame_release(f); + free(f->dead); + for (int k = 0; k < f->n_chunks; k++) { + REL(f->chunks[k].buf); + } + free(f->chunks); + REL(f->views); + REL(f->alloc); + } + for (int i = 0; i < BUI_DX_PROGRAMS; i++) { + REL(d->pso[i]); + } + REL(d->root); + REL(d->samplers); + heap_exit(&d->srv_heap); + heap_exit(&d->rtv_heap); + REL(d->list); + REL(d->fence); + if (d->event) { + CloseHandle(d->event); + } + REL(d->queue); + REL(d->factory); + if (d->info) { /* what is still alive now is a leak: the device is all that should be left */ + debug_drain(d, 0); + ID3D12DebugDevice *dd = NULL; + if (SUCCEEDED(ID3D12Device_QueryInterface(d->dev, &k_IID_ID3D12DebugDevice, (void **)&dd))) { + ID3D12DebugDevice_ReportLiveDeviceObjects(dd, D3D12_RLDO_DETAIL | D3D12_RLDO_IGNORE_INTERNAL); + REL(dd); + } + debug_drain(d, 1); + fprintf(stderr, "bui gpu: d3d12 debug layer: %d errors (leaks included), %d warnings\n", + d->n_errors, + d->n_warnings); + } + REL(d->info); + REL(d->dev); + free(d); +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Drawing + present + * \{ */ + +static D3D12_CPU_DESCRIPTOR_HANDLE rtv_of(const D12 *d, const BuiGpuTex *t) +{ + return slot_cpu(&d->rtv_heap, t->rtv); +} + +static int d12_target(BuiGpu *g, int tw, int th) +{ + D12 *d = DEV(g); + const float clear[4] = {0, 0, 0, g->alpha ? 0.0f : 1.0f}; + if (!d->target || d->tw != tw || d->th != th) { + if (d->target) { + d12_tex_free(g, d->target); + } + d->target = tex_make(d, BUI_FMT_BGRA8, tw, th, BUI_TEX_TARGET, clear); + if (!d->target) { + return 0; + } + d->tw = tw; + d->th = th; + return 1; /* made cleared */ + } + use(d, d->target, D3D12_RESOURCE_STATE_RENDER_TARGET); + ID3D12GraphicsCommandList_ClearRenderTargetView(d->list, rtv_of(d, d->target), clear, 0, NULL); + return 1; +} + +static void viewport(D12 *d, int w, int h) +{ + const D3D12_VIEWPORT vp = {0, 0, (float)w, (float)h, 0, 1}; + ID3D12GraphicsCommandList_RSSetViewports(d->list, 1, &vp); +} + +static void scissor(D12 *d, int x0, int y0, int x1, int y1) +{ + const D3D12_RECT r = {x0, y0, x1, y1}; + ID3D12GraphicsCommandList_RSSetScissorRects(d->list, 1, &r); +} + +/* One recorded effect draw: its pipeline, floats and inputs, scissored to its clip. */ +static void fx_draw(BuiGpu *g, const BuiGpuFxCall *fc) +{ + D12 *d = DEV(g); + ID3D12GraphicsCommandList *c = d->list; + /* a pass into a render target: its view and size stand in for the frame's until it is drawn */ + const BuiGpuDevTex *dst = fc->dst ? bui_gpu_dtex(g, fc->dst) : NULL; + if (fc->dst && (!dst || dst->tex->rtv < 0)) { + return; + } + if (!fc->effect) { /* a clear of the target */ + use(d, dst->tex, D3D12_RESOURCE_STATE_RENDER_TARGET); + ID3D12GraphicsCommandList_ClearRenderTargetView(c, rtv_of(d, dst->tex), g->fxf + fc->floats, 0, + NULL); + return; + } + const BuiGpuDevFx *f = bui_gpu_dfx(g, fc->effect); + ID3D12PipelineState *pso = f ? fx_pso(d, f->prog, dst ? dst->target : 0) : NULL; + Upload u; + BuiGpuFxConsts consts; + const size_t n = f ? bui_gpu_fx_consts(g, fc, f->n_floats, dst ? dst->w : d->tw, + dst ? dst->h : d->th, &consts) : + 0; + if (!pso || !upload_alloc(d, n, D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT, &u)) { + return; + } + memcpy(u.cpu, consts.data, n); + BuiGpuTex *in[FX_TABLE] = {0}; + for (int k = 0; k < f->n_inputs; k++) { + in[k] = bui_gpu_dtex_tex(g, fc->inputs[k]); + use(d, in[k], D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + } + ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(c, ROOT_FX_TEX, table(d, in, FX_TABLE)); + ID3D12GraphicsCommandList_SetGraphicsRootConstantBufferView(c, ROOT_FX_CB, u.gpu); + ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(c, ROOT_SAMPLER, d->sampler_gpu[0]); + if (dst) { + use(d, dst->tex, D3D12_RESOURCE_STATE_RENDER_TARGET); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv = rtv_of(d, dst->tex); + ID3D12GraphicsCommandList_OMSetRenderTargets(c, 1, &rtv, FALSE, NULL); + viewport(d, dst->w, dst->h); + } + ID3D12GraphicsCommandList_SetPipelineState(c, pso); + scissor(d, fc->clip[0], fc->clip[1], fc->clip[2], fc->clip[3]); + ID3D12GraphicsCommandList_DrawInstanced(c, 4, 1, 0, 0); + if (dst) { /* back to the frame */ + const D3D12_CPU_DESCRIPTOR_HANDLE rtv = rtv_of(d, d->target); + ID3D12GraphicsCommandList_OMSetRenderTargets(c, 1, &rtv, FALSE, NULL); + viewport(d, d->tw, d->th); + } +} + +/* The vertex data of batch kind `k` in the upload ring. */ +static D3D12_VERTEX_BUFFER_VIEW vertices(D12 *d, const BuiGpu *g, int k) +{ + D3D12_VERTEX_BUFFER_VIEW v = {0, 0, bui_dx_programs[k].stride}; + int n; + const void *data = bui_gpu_batch_data(g, (BuiGpuBatchKind)k, &n); + Upload u; + if (n && upload_alloc(d, (size_t)v.StrideInBytes * n, 16, &u)) { + memcpy(u.cpu, data, (size_t)v.StrideInBytes * n); + v.BufferLocation = u.gpu; + v.SizeInBytes = v.StrideInBytes * (UINT)n; + } + return v; +} + +static void d12_draw(BuiGpu *g) +{ + D12 *d = DEV(g); + if (d->lost || !d->open) { + return; + } + views_reserve(d, (g->n_b + 1) * (TEX_TABLE + FX_TABLE)); + ID3D12GraphicsCommandList *c = d->list; + D3D12_VERTEX_BUFFER_VIEW vb[BUI_DX_PROGRAMS]; + for (int k = 0; k < BUI_DX_PROGRAMS; k++) { + vb[k] = vertices(d, g, k); + } + D3D12_INDEX_BUFFER_VIEW ib = {0, 0, DXGI_FORMAT_R32_UINT}; + Upload u; + if (g->n_mi && upload_alloc(d, sizeof(uint32_t) * (size_t)g->n_mi, 16, &u)) { + memcpy(u.cpu, g->mi, sizeof(uint32_t) * (size_t)g->n_mi); + ib.BufferLocation = u.gpu; + ib.SizeInBytes = (UINT)(sizeof(uint32_t) * (size_t)g->n_mi); + } + pend_flush(d); + use(d, d->target, D3D12_RESOURCE_STATE_RENDER_TARGET); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv = rtv_of(d, d->target); + ID3D12GraphicsCommandList_OMSetRenderTargets(c, 1, &rtv, FALSE, NULL); + viewport(d, d->tw, d->th); + const float cbd[4] = {2.0f / (float)d->tw, 2.0f / (float)d->th, 0, 0}; + ID3D12GraphicsCommandList_SetGraphicsRoot32BitConstants(c, ROOT_FRAME, 4, cbd, 0); + + /* t0..t5: mask atlas, image atlas (or a big image), Slug curves, Slug bands, mesh texture, NV12 + * chroma */ + BuiGpuTex *tex[TEX_TABLE] = {g->mask.tex, g->rgba.tex, g->curve_tex, g->band_tex, NULL, NULL}; + int tex_dirty = 1; + int cur = -1; + for (int i = 0; i < g->n_b; i++) { + const BuiGpuBatch *b = &g->b[i]; + if (b->count == 0) { + continue; + } + if ((int)b->kind != cur) { + cur = (int)b->kind; + /* quads: 4 vertices from SV_VertexID per instance, as effects (which have no vertex data) */ + ID3D12GraphicsCommandList_IASetPrimitiveTopology( + c, b->kind == BUI_BATCH_QUADS || b->kind == BUI_BATCH_FX ? D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP : + D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + if (b->kind != BUI_BATCH_FX) { + ID3D12GraphicsCommandList_SetPipelineState(c, d->pso[b->kind]); + ID3D12GraphicsCommandList_IASetVertexBuffers(c, 0, 1, &vb[b->kind]); + } + if (b->kind == BUI_BATCH_MESH) { + ID3D12GraphicsCommandList_IASetIndexBuffer(c, &ib); + } + else if (b->kind != BUI_BATCH_FX) { /* scissored: meshes and effects, to their clip */ + scissor(d, 0, 0, d->tw, d->th); + } + } + if (b->kind == BUI_BATCH_MESH) { + BuiGpuTex *t = bui_gpu_dtex_tex(g, b->tex); + use(d, t, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); + tex_dirty |= tex[4] != t; + tex[4] = t; + ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(c, ROOT_SAMPLER, + d->sampler_gpu[b->nearest ? 1 : 0]); + scissor(d, b->clip[0], b->clip[1], b->clip[2], b->clip[3]); + } + else if (b->kind == BUI_BATCH_QUADS) { + BuiGpuTex *uv; + BuiGpuTex *img = bui_gpu_batch_image(g, b, &uv); + tex_dirty |= tex[1] != img || tex[5] != uv; + tex[1] = img; + tex[5] = uv; + } + if (tex_dirty && (b->kind == BUI_BATCH_MESH || b->kind == BUI_BATCH_QUADS)) { + tex_dirty = 0; + ID3D12GraphicsCommandList_SetGraphicsRootDescriptorTable(c, ROOT_TEX, table(d, tex, TEX_TABLE)); + } + if (b->kind == BUI_BATCH_MESH) { + ID3D12GraphicsCommandList_DrawIndexedInstanced(c, (UINT)b->count, 1, (UINT)b->first, 0, 0); + } + else if (b->kind == BUI_BATCH_QUADS) { + ID3D12GraphicsCommandList_DrawInstanced(c, 4, (UINT)b->count, 0, (UINT)b->first); + } + else if (b->kind == BUI_BATCH_FX) { + fx_draw(g, &g->fx[b->first]); + cur = -1; /* its pipeline replaced the renderer's */ + } + else { + ID3D12GraphicsCommandList_DrawInstanced(c, (UINT)b->count, 1, (UINT)b->first, 0); + } + } +} + +static void d12_clear(BuiGpu *g, const RECT *r) +{ + D12 *d = DEV(g); + const float clear[4] = {0, 0, 0, 0}; + use(d, d->target, D3D12_RESOURCE_STATE_RENDER_TARGET); + ID3D12GraphicsCommandList_ClearRenderTargetView(d->list, rtv_of(d, d->target), clear, 1, r); +} + +static int back_buffers(D12 *d) +{ + for (UINT i = 0; i < 2; i++) { + if (FAILED(IDXGISwapChain3_GetBuffer(d->swap, i, &k_IID_ID3D12Resource, (void **)&d->back[i]))) { + return 0; + } + } + return 1; +} + +/* Shows composition swap chain `swap` in the window (alpha windows): a DirectComposition visual + * over the window's own surface. */ +static int dcomp_show(D12 *d, HWND hwnd, IDXGISwapChain1 *swap) +{ + typedef HRESULT(WINAPI * CreateFn)(IUnknown *, REFIID, void **); + HMODULE dll = LoadLibraryW(L"dcomp.dll"); + CreateFn create = dll ? (CreateFn)(void *)GetProcAddress(dll, "DCompositionCreateDevice") : NULL; + if (!create || FAILED(create(NULL, &k_IID_IDCompositionDevice, (void **)&d->dcomp))) { + return bui_gpu_fail("DirectComposition", 0); + } + const DcDeviceVtbl *dv = (const DcDeviceVtbl *)d->dcomp->vtbl; + if (FAILED(dv->CreateTargetForHwnd(d->dcomp, hwnd, TRUE, &d->dcomp_target)) || + FAILED(dv->CreateVisual(d->dcomp, &d->dcomp_visual)) || + FAILED(((const DcVisualVtbl *)d->dcomp_visual->vtbl)->SetContent(d->dcomp_visual, + (IUnknown *)swap)) || + FAILED(((const DcTargetVtbl *)d->dcomp_target->vtbl)->SetRoot(d->dcomp_target, + d->dcomp_visual)) || + FAILED(dv->Commit(d->dcomp))) + { + return bui_gpu_fail("DirectComposition visual", 0); + } + return 1; +} + +static int d12_swap(BuiGpu *g, int cw, int ch) +{ + D12 *d = DEV(g); + if (d->swap) { /* no buffer may be in use or referenced */ + gpu_idle(d); + REL(d->back[0]); + REL(d->back[1]); + return SUCCEEDED(IDXGISwapChain3_ResizeBuffers(d->swap, 0, (UINT)cw, (UINT)ch, + DXGI_FORMAT_UNKNOWN, 0)) && + back_buffers(d); + } + DXGI_SWAP_CHAIN_DESC1 sd = bui_dx_swap_desc(cw, ch); + IDXGISwapChain1 *s1 = NULL; + HRESULT hr; + if (g->alpha) { + /* a window's flip-model swap chain ignores alpha; a composition one keeps it */ + sd.AlphaMode = DXGI_ALPHA_MODE_PREMULTIPLIED; + sd.Scaling = DXGI_SCALING_STRETCH; + hr = IDXGIFactory4_CreateSwapChainForComposition(d->factory, (IUnknown *)d->queue, &sd, NULL, &s1); + if (SUCCEEDED(hr) && !dcomp_show(d, g->hwnd, s1)) { + hr = E_FAIL; + } + } + else { + hr = IDXGIFactory4_CreateSwapChainForHwnd(d->factory, (IUnknown *)d->queue, g->hwnd, &sd, NULL, + NULL, &s1); + if (SUCCEEDED(hr)) { + IDXGIFactory4_MakeWindowAssociation(d->factory, g->hwnd, DXGI_MWA_NO_ALT_ENTER); + } + } + if (SUCCEEDED(hr)) { + hr = IDXGISwapChain1_QueryInterface(s1, &k_IID_IDXGISwapChain3, (void **)&d->swap); + } + REL(s1); + if (FAILED(hr) || !back_buffers(d)) { + REL(d->back[0]); + REL(d->back[1]); + REL(d->swap); + REL(d->dcomp_visual); + REL(d->dcomp_target); + REL(d->dcomp); + return bui_gpu_fail("swap chain", hr); + } + return 1; +} + +static void copy_box(D12 *d, ID3D12Resource *dst, const D3D12_BOX *b) +{ + D3D12_TEXTURE_COPY_LOCATION to, from; + memset(&to, 0, sizeof(to)); + memset(&from, 0, sizeof(from)); + to.pResource = dst; + to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + from.pResource = d->target->res; + from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + ID3D12GraphicsCommandList_CopyTextureRegion(d->list, &to, b->left, b->top, 0, &from, b); +} + +static int d12_present(BuiGpu *g, int whole, const RECT *copy, int n_copy, const RECT *dirty, + int n_dirty) +{ + D12 *d = DEV(g); + if (d->lost || !d->open) { + return BUI_PRESENT_LOST; + } + ID3D12Resource *back = d->back[IDXGISwapChain3_GetCurrentBackBufferIndex(d->swap) & 1]; + barrier(d, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST); + use(d, d->target, D3D12_RESOURCE_STATE_COPY_SOURCE); + if (whole) { + /* the target can be larger than the window (it grows in steps): copy the frame, not the resource */ + const D3D12_BOX frame = {0, 0, 0, (UINT)g->w, (UINT)g->h, 1}; + copy_box(d, back, &frame); + } + for (int i = 0; i < n_copy; i++) { + const D3D12_BOX b = {(UINT)copy[i].left, (UINT)copy[i].top, 0, (UINT)copy[i].right, + (UINT)copy[i].bottom, 1}; + copy_box(d, back, &b); + } + barrier(d, back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT); + use(d, d->target, D3D12_RESOURCE_STATE_RENDER_TARGET); + ctx_submit(d); + DXGI_PRESENT_PARAMETERS pp = {0}; + pp.DirtyRectsCount = (UINT)n_dirty; + pp.pDirtyRects = n_dirty ? (RECT *)dirty : NULL; + const int st = bui_dx_present_status(IDXGISwapChain3_Present1(d->swap, 0, 0, &pp)); + ctx_begin(d); + return d->lost ? BUI_PRESENT_LOST : st; +} + +static void d12_submit(BuiGpu *g) +{ + D12 *d = DEV(g); + if (d->open) { + ctx_submit(d); + ctx_begin(d); + } +} + +static int d12_read(BuiGpu *g, uint32_t *dst, int w, int h) +{ + D12 *d = DEV(g); + if (d->lost || !d->open) { + return 0; + } + const UINT rp = ((UINT)w * 4 + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) & + ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1); + const size_t size = (size_t)rp * h; + ID3D12Resource *rb = buffer(d, D3D12_HEAP_TYPE_READBACK, size, D3D12_RESOURCE_STATE_COPY_DEST); + if (!rb) { + return 0; + } + D3D12_TEXTURE_COPY_LOCATION to, from; + memset(&to, 0, sizeof(to)); + memset(&from, 0, sizeof(from)); + to.pResource = rb; + to.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + to.PlacedFootprint.Footprint.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + to.PlacedFootprint.Footprint.Width = (UINT)w; + to.PlacedFootprint.Footprint.Height = (UINT)h; + to.PlacedFootprint.Footprint.Depth = 1; + to.PlacedFootprint.Footprint.RowPitch = rp; + from.pResource = d->target->res; + from.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + const D3D12_BOX frame = {0, 0, 0, (UINT)w, (UINT)h, 1}; + use(d, d->target, D3D12_RESOURCE_STATE_COPY_SOURCE); + ID3D12GraphicsCommandList_CopyTextureRegion(d->list, &to, 0, 0, 0, &from, &frame); + use(d, d->target, D3D12_RESOURCE_STATE_RENDER_TARGET); + gpu_idle(d); + const D3D12_RANGE all = {0, size}, none = {0, 0}; + uint8_t *p = NULL; + int ok = 0; + if (!d->lost && SUCCEEDED(ID3D12Resource_Map(rb, 0, &all, (void **)&p))) { + for (int y = 0; y < h; y++) { + memcpy(dst + (size_t)y * w, p + (size_t)y * rp, sizeof(uint32_t) * (size_t)w); + } + ID3D12Resource_Unmap(rb, 0, &none); + ok = 1; + } + REL(rb); /* idle: nothing uses it */ + return ok; +} + +/** \} */ + +const BuiGpuOps bui_gpu_d3d12_ops = { + BUI_GPU_API_D3D12, + d12_init, + d12_exit, + d12_tex_create, + d12_tex_update, + d12_tex_free, + d12_fx_build, + d12_fx_free, + d12_target, + d12_draw, + d12_clear, + d12_swap, + d12_present, + d12_submit, + d12_read, +}; + +#endif /* _WIN32 && BUI_GPU */ diff --git a/gpu/intern/gpu_device.c b/gpu/intern/gpu_device.c new file mode 100644 index 00000000..4c8e9500 --- /dev/null +++ b/gpu/intern/gpu_device.c @@ -0,0 +1,1578 @@ +/* BUI GPU renderer core — see gpu_device.h. + * + * Like Blender's widget drawing (interface_widgets.cc batches widget bases + * into GPU_SHADER_2D_WIDGET_BASE_INST draws), every primitive becomes one + * instance of a single uber-shader, so a frame of thousands of widgets and + * text runs is a handful of instanced draws. Differences from Blender, + * for a retained UI: + * - frames render into a persistent target: only damaged regions are + * redrawn (the kit's damage tracking) and the swap chain gets dirty rects, + * so the compositor only recomposes what changed; + * - text is pre-shaped glyph runs (the same masks the software raster draws) + * packed into one R8 atlas, images into one BGRA atlas; + * - the device is created on a worker thread so the first frame never waits + * for the driver (the software raster draws until it is ready). + * + * SPDX-License-Identifier: GPL-2.0-or-later */ + +#if defined(_WIN32) && defined(BUI_GPU) /* BUI_GPU: features.json */ + +# include "gpu_device.h" + +# include +# include +# include + +# define MASK_MAP 16384 /* power of two */ +# define MASK_MAP_FILL 12000 +# define IMG_MAP 1024 +# define IMG_MAP_FILL 700 + +/* Slug glyph data: curves (2 RGBA32F texels each) and bands (RG32_UINT + * texels), both addressed linearly over 4096-wide textures. */ +# define SLUG_W 4096 +# define SLUG_H 64 +# define SLUG_MAP 8192 /* power of two */ +# define SLUG_MAP_FILL 6000 +# define SLUG_MAX_BANDS 16 + +# define BIG_BUDGET ((size_t)256 << 20) /* bytes of big-image textures kept */ +# define BIG_IDLE 120 /* frames unused before one is freed */ + +int bui_gpu_debug(void) +{ + const char *dbg = getenv("BUI_GPU_DEBUG"); + return dbg && dbg[0] >= '1' && dbg[0] <= '9' ? dbg[0] - '0' : 0; +} + +int bui_gpu_fail(const char *what, long hr) +{ + if (bui_gpu_debug()) { + fprintf(stderr, "bui gpu: %s failed (0x%08lx)\n", what, (unsigned long)hr); + } + return 0; +} + +static void tex_drop(BuiGpu *g, BuiGpuTex **t) +{ + if (*t) { + g->ops->tex_free(g, *t); + *t = NULL; + } +} + +/* -------------------------------------------------------------------- */ +/** \name Atlases (shelf packing) + * \{ */ + +static int atlas_create(BuiGpu *g, BuiGpuAtlas *a, int size, int bpp) +{ + memset(a, 0, sizeof(*a)); + a->size = size; + a->bpp = bpp; + a->tex = g->ops->tex_create(g, bpp == 1 ? BUI_FMT_R8 : BUI_FMT_BGRA8, size, size, NULL, 0, 0); + return a->tex != NULL; +} + +static void atlas_clear(BuiGpuAtlas *a) +{ + a->nshelves = 0; + a->next_y = 0; +} + +/* Finds room for w x h (+1 px gutter). 0 when full. */ +static int atlas_place(BuiGpuAtlas *a, int w, int h, int *r_x, int *r_y) +{ + const int pw = w + 1, ph = h + 1; + if (pw > a->size || ph > a->size) { + return 0; + } + int best = -1; + for (int i = 0; i < a->nshelves; i++) { + if (a->shelf_h[i] >= ph && a->shelf_h[i] <= ph + ph / 4 + 2 && a->shelf_x[i] + pw <= a->size && + (best < 0 || a->shelf_h[i] < a->shelf_h[best])) + { + best = i; + } + } + if (best < 0) { + const int sh = (ph + 3) & ~3; /* round up: more strings share a shelf */ + if (a->nshelves == BUI_GPU_SHELVES || a->next_y + sh > a->size) { + return 0; + } + best = a->nshelves++; + a->shelf_y[best] = a->next_y; + a->shelf_h[best] = sh; + a->shelf_x[best] = 0; + a->next_y += sh; + } + *r_x = a->shelf_x[best]; + *r_y = a->shelf_y[best]; + a->shelf_x[best] += pw; + return 1; +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Device (worker thread) + * \{ */ + +/* The device and what the core keeps on it from the start. */ +static int device_init(BuiGpu *g) +{ + if (!g->ops->init(g)) { + return 0; + } + const char *max_env = getenv("BUI_GPU_MAX_TEXTURE"); /* tests: force tiling */ + if (max_env && atoi(max_env) >= 64) { + g->max_tex = atoi(max_env) < g->max_tex ? atoi(max_env) : g->max_tex; + } + const uint32_t white = 0xFFFFFFFFu; + g->white = g->ops->tex_create(g, BUI_FMT_RGBA8, 1, 1, &white, 4, BUI_TEX_IMMUTABLE); + if (!g->white) { + return bui_gpu_fail("white texture", 0); + } + if (!atlas_create(g, &g->mask, 2048, 1)) { + return bui_gpu_fail("atlas", 0); + } + return 1; +} + +/* Everything on the device, the backend's own objects last. */ +static void device_exit(BuiGpu *g) +{ + if (!g->dev) { + return; + } + tex_drop(g, &g->mask.tex); + tex_drop(g, &g->rgba.tex); + for (int i = 0; i < BUI_GPU_BIG_MAX; i++) { + tex_drop(g, &g->big[i].tex); + tex_drop(g, &g->big[i].uv); + } + tex_drop(g, &g->curve_tex); + tex_drop(g, &g->band_tex); + for (int i = 0; i < g->n_dtex; i++) { + tex_drop(g, &g->dtex[i].tex); + } + for (int i = 0; i < g->n_dfx; i++) { + if (g->dfx[i].prog) { + g->ops->fx_free(g, g->dfx[i].prog); + g->dfx[i].prog = NULL; + } + } + tex_drop(g, &g->white); + g->ops->exit(g); + g->dev = NULL; +} + +static DWORD WINAPI device_thread(void *arg) +{ + BuiGpu *g = (BuiGpu *)arg; + int ok = device_init(g); + if (!ok && g->ops->api == BUI_GPU_API_D3D12) { + device_exit(g); + bui_gpu_fail("Direct3D 12 (falling back to Direct3D 11)", 0); + g->ops = &bui_gpu_d3d11_ops; + ok = device_init(g); + } + InterlockedExchange(&g->state, ok ? 1 : -1); + return 0; +} + +BuiGpu *bui_gpu_create(void *hwnd, int alpha) +{ + BuiGpu *g = (BuiGpu *)calloc(1, sizeof(BuiGpu)); + if (!g) { + return NULL; + } + g->ops = BUI_gpu_api() == BUI_GPU_API_D3D12 ? &bui_gpu_d3d12_ops : &bui_gpu_d3d11_ops; + g->hwnd = (HWND)hwnd; + g->alpha = alpha; + g->mask_map = (BuiGpuSlot *)calloc(MASK_MAP, sizeof(BuiGpuSlot)); + g->img_map = (BuiGpuSlot *)calloc(IMG_MAP, sizeof(BuiGpuSlot)); + g->thread = g->mask_map && g->img_map ? CreateThread(NULL, 0, device_thread, g, 0, NULL) : NULL; + if (!g->thread) { + bui_gpu_free(g); + return NULL; + } + return g; +} + +int bui_gpu_state(BuiGpu *g, int wait) +{ + if (wait && g->thread) { + WaitForSingleObject(g->thread, INFINITE); + } + const LONG s = InterlockedCompareExchange(&g->state, 0, 0); + if (s != 0 && g->thread) { + WaitForSingleObject(g->thread, INFINITE); + CloseHandle(g->thread); + g->thread = NULL; + } + return (int)s; +} + +BuiGpuApi bui_gpu_api_of(const BuiGpu *g) +{ + return g->ops->api; +} + +void bui_gpu_free(BuiGpu *g) +{ + if (!g) { + return; + } + if (g->thread) { + WaitForSingleObject(g->thread, INFINITE); + CloseHandle(g->thread); + } + device_exit(g); + free(g->dtex); + free(g->dfx); + free(g->fx); + free(g->fxf); + free(g->inst); + free(g->tv); + free(g->mv); + free(g->mi); + free(g->b); + free(g->mask_map); + free(g->img_map); + free(g->slug_map); + free(g); +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Recording + * \{ */ + +static void flush(BuiGpu *g); + +static void big_sweep(BuiGpu *g); + +void bui_gpu_begin(BuiGpu *g, int w, int h) +{ + g->w = w > 0 ? w : 1; + g->h = h > 0 ? h : 1; + g->frame++; + big_sweep(g); +} + +static BuiGpuBatch *batch_new(BuiGpu *g, BuiGpuBatchKind kind, int first) +{ + if (g->n_b == g->cap_b) { + const int cap = g->cap_b ? g->cap_b * 2 : 64; + BuiGpuBatch *nb = (BuiGpuBatch *)realloc(g->b, sizeof(BuiGpuBatch) * (size_t)cap); + if (!nb) { + return NULL; + } + g->b = nb; + g->cap_b = cap; + } + BuiGpuBatch *b = &g->b[g->n_b++]; + memset(b, 0, sizeof(*b)); + b->kind = kind; + b->first = first; + b->img = -1; + return b; +} + +/* The batch to append to: the last one when it is of the same kind. */ +static BuiGpuBatch *batch_for(BuiGpu *g, BuiGpuBatchKind kind, int first) +{ + if (kind < BUI_BATCH_MESH && g->n_b > 0 && g->b[g->n_b - 1].kind == kind) { + return &g->b[g->n_b - 1]; + } + return batch_new(g, kind, first); +} + +/* -- textured meshes ----------------------------------------------------------- */ + +static void dtex_release(BuiGpu *g, BuiGpuDevTex *t) +{ + tex_drop(g, &t->tex); + t->id = 0; +} + +/* The format of a render target (BUI_TARGET_*). */ +static BuiGpuFormat target_format(int target) +{ + switch (target - 1) { + case BUI_TARGET_RGBA16F: + return BUI_FMT_RGBA16F; + case BUI_TARGET_RGBA32F: + return BUI_FMT_RGBA32F; + default: + return BUI_FMT_RGBA8; + } +} + +/* Creates or refreshes the device copy of registry texture `id`. */ +static void dtex_get(BuiGpu *g, int id) +{ + BuiTexView v; + if (id <= 0 || !bui_texture_view(id, &v)) { + return; + } + const int slot = (id & 0xFFFF) - 1; + if (slot >= g->n_dtex) { + const int n = slot + 16; + BuiGpuDevTex *nd = (BuiGpuDevTex *)realloc(g->dtex, sizeof(BuiGpuDevTex) * (size_t)n); + if (!nd) { + return; + } + memset(nd + g->n_dtex, 0, sizeof(BuiGpuDevTex) * (size_t)(n - g->n_dtex)); + g->dtex = nd; + g->n_dtex = n; + } + BuiGpuDevTex *t = &g->dtex[slot]; + if (t->id == id && t->gen == v.gen) { + return; + } + if (t->id == id && t->w == v.w && t->h == v.h) { + /* updated: draws recorded so far still need the old pixels */ + flush(g); + int rects[32][4]; + int n = bui_texture_changes(id, t->gen, rects, 32); + if (n < 0) { + rects[0][0] = rects[0][1] = 0; + rects[0][2] = v.w; + rects[0][3] = v.h; + n = 1; + } + for (int i = 0; i < n; i++) { + const int *r = rects[i]; + g->ops->tex_update(g, t->tex, r[0], r[1], r[2], r[3], + v.rgba + ((size_t)r[1] * v.w + r[0]) * 4, v.w * 4); + } + t->gen = v.gen; + return; + } + if (t->id) { + flush(g); + dtex_release(g, t); + } + /* a render target starts as zeros */ + t->tex = g->ops->tex_create(g, v.target ? target_format(v.target) : BUI_FMT_RGBA8, v.w, v.h, + v.target ? NULL : v.rgba, v.w * 4, v.target ? BUI_TEX_TARGET : 0); + if (!t->tex) { + return; + } + t->id = id; + t->gen = v.gen; + t->w = v.w; + t->h = v.h; + t->target = v.target; +} + +const BuiGpuDevTex *bui_gpu_dtex(const BuiGpu *g, int id) +{ + const int slot = (id & 0xFFFF) - 1; + return id > 0 && slot >= 0 && slot < g->n_dtex && g->dtex[slot].id == id ? &g->dtex[slot] : NULL; +} + +BuiGpuTex *bui_gpu_dtex_tex(const BuiGpu *g, int id) +{ + const BuiGpuDevTex *t = bui_gpu_dtex(g, id); + return t ? t->tex : g->white; +} + +/* Frees device copies of textures freed in the registry. */ +static void dtex_sweep(BuiGpu *g) +{ + const unsigned fg = bui_texture_free_gen(); + if (fg == g->dtex_free_gen) { + return; + } + g->dtex_free_gen = fg; + BuiTexView v; + for (int i = 0; i < g->n_dtex; i++) { + if (g->dtex[i].id && !bui_texture_view(g->dtex[i].id, &v)) { + flush(g); + dtex_release(g, &g->dtex[i]); + } + } +} + +static int grow(void **p, int *cap, int need, size_t size) +{ + if (need <= *cap) { + return 1; + } + int c = *cap ? *cap : 4096; + while (c < need) { + c *= 2; + } + void *np = realloc(*p, size * (size_t)c); + if (!np) { + return 0; + } + *p = np; + *cap = c; + return 1; +} + +void bui_gpu_mesh(BuiGpu *g, + const BuiMeshVertex *vtx, + int n_vtx, + const void *idx, + int idx32, + int n_idx, + float ox, + float oy, + int tex, + int nearest, + const int clip[4]) +{ + n_idx -= n_idx % 3; + if (n_idx <= 0 || n_vtx <= 0) { + return; + } + dtex_sweep(g); + dtex_get(g, tex); /* may flush: before anything of this mesh is recorded */ + if (!grow((void **)&g->mv, &g->cap_mv, g->n_mv + n_vtx, sizeof(BuiMeshVertex)) || + !grow((void **)&g->mi, &g->cap_mi, g->n_mi + n_idx, sizeof(uint32_t))) + { + return; + } + BuiGpuBatch *b = NULL; + if (g->n_b > 0) { /* same texture, sampler and clip: one draw */ + BuiGpuBatch *last = &g->b[g->n_b - 1]; + if (last->kind == BUI_BATCH_MESH && last->tex == tex && last->nearest == nearest && + memcmp(last->clip, clip, sizeof(int[4])) == 0) + { + b = last; + } + } + if (!b) { + b = batch_for(g, BUI_BATCH_MESH, g->n_mi); + if (!b) { + return; + } + b->tex = tex; + b->nearest = nearest; + memcpy(b->clip, clip, sizeof(int[4])); + } + const uint32_t base = (uint32_t)g->n_mv; + for (int i = 0; i < n_vtx; i++) { + BuiMeshVertex *v = &g->mv[g->n_mv++]; + *v = vtx[i]; + v->x += ox; + v->y += oy; + } + const uint16_t *i16 = (const uint16_t *)idx; + const uint32_t *i32 = (const uint32_t *)idx; + uint32_t *out = g->mi + g->n_mi; + int n = 0; + for (int i = 0; i < n_idx; i += 3) { + const uint32_t a = idx32 ? i32[i] : i16[i], c1 = idx32 ? i32[i + 1] : i16[i + 1], + c2 = idx32 ? i32[i + 2] : i16[i + 2]; + if (a >= (uint32_t)n_vtx || c1 >= (uint32_t)n_vtx || c2 >= (uint32_t)n_vtx) { + continue; + } + out[n++] = base + a; + out[n++] = base + c1; + out[n++] = base + c2; + } + g->n_mi += n; + b->count += n; +} + +/* Appends an instance to quad batch `b`. */ +static BuiGpuInst *inst_in(BuiGpu *g, BuiGpuBatch *b, int kind, int x0, int y0, int x1, int y1) +{ + if (g->n_inst == g->cap_inst) { + const int cap = g->cap_inst ? g->cap_inst * 2 : 1024; + BuiGpuInst *ni = (BuiGpuInst *)realloc(g->inst, sizeof(BuiGpuInst) * (size_t)cap); + if (!ni) { + return NULL; + } + g->inst = ni; + g->cap_inst = cap; + } + b->count++; + BuiGpuInst *in = &g->inst[g->n_inst++]; + memset(in, 0, sizeof(*in)); + in->bounds[0] = (float)x0; + in->bounds[1] = (float)y0; + in->bounds[2] = (float)x1; + in->bounds[3] = (float)y1; + in->p[0] = (float)kind; + return in; +} + +BuiGpuInst *bui_gpu_inst_image(BuiGpu *g, int tex, int x0, int y0, int x1, int y1) +{ + BuiGpuBatch *b = g->n_b > 0 ? &g->b[g->n_b - 1] : NULL; + if (!b || b->kind != BUI_BATCH_QUADS || (b->img >= 0 && b->img != tex)) { + b = batch_new(g, BUI_BATCH_QUADS, g->n_inst); /* another texture: another draw */ + } + if (!b) { + return NULL; + } + b->img = tex; + return inst_in(g, b, BG_IMAGE, x0, y0, x1, y1); +} + +BuiGpuInst *bui_gpu_inst(BuiGpu *g, int kind, int x0, int y0, int x1, int y1) +{ + BuiGpuBatch *b = batch_for(g, BUI_BATCH_QUADS, g->n_inst); + return b ? inst_in(g, b, kind, x0, y0, x1, y1) : NULL; +} + +const void *bui_gpu_batch_data(const BuiGpu *g, BuiGpuBatchKind k, int *r_count) +{ + *r_count = k == BUI_BATCH_QUADS ? g->n_inst : k == BUI_BATCH_TRIS ? g->n_tv : g->n_mv; + return k == BUI_BATCH_QUADS ? (const void *)g->inst : + k == BUI_BATCH_TRIS ? (const void *)g->tv : + (const void *)g->mv; +} + +BuiGpuTex *bui_gpu_batch_image(const BuiGpu *g, const BuiGpuBatch *b, BuiGpuTex **r_uv) +{ + const BuiGpuBig *big = b->img > 0 && g->big[b->img - 1].tex ? &g->big[b->img - 1] : NULL; + *r_uv = big ? big->uv : NULL; + return big ? big->tex : g->rgba.tex; +} + +void bui_gpu_triangles(BuiGpu *g, + const float (*co)[2], + const float (*col)[4], + int count, + const int clip[4]) +{ + count -= count % 3; + if (count <= 0) { + return; + } + if (g->n_tv + count > g->cap_tv) { + int cap = g->cap_tv ? g->cap_tv : 1024; + while (cap < g->n_tv + count) { + cap *= 2; + } + BuiGpuTriV *nt = (BuiGpuTriV *)realloc(g->tv, sizeof(BuiGpuTriV) * (size_t)cap); + if (!nt) { + return; + } + g->tv = nt; + g->cap_tv = cap; + } + BuiGpuBatch *b = batch_for(g, BUI_BATCH_TRIS, g->n_tv); + if (!b) { + return; + } + for (int i = 0; i < count; i++) { + BuiGpuTriV *v = &g->tv[g->n_tv++]; + v->x = co[i][0]; + v->y = co[i][1]; + memcpy(v->c, col[i], sizeof(v->c)); + for (int k = 0; k < 4; k++) { + v->clip[k] = (float)clip[k]; + } + } + b->count += count; +} + +/* -- effects (application shaders) -------------------------------------------------- */ + +static void dfx_release(BuiGpu *g, BuiGpuDevFx *f) +{ + if (f->prog) { + g->ops->fx_free(g, f->prog); + } + memset(f, 0, sizeof(*f)); +} + +/* The device's pipeline of effect `v`, compiled on first use. NULL: no room. */ +static BuiGpuDevFx *dfx_get(BuiGpu *g, const BuiEffectView *v) +{ + const int slot = BUI_EFFECT_SLOT(v->id); + if (slot >= g->n_dfx) { + const int n = slot + 8; + BuiGpuDevFx *nd = (BuiGpuDevFx *)realloc(g->dfx, sizeof(BuiGpuDevFx) * (size_t)n); + if (!nd) { + return NULL; + } + memset(nd + g->n_dfx, 0, sizeof(BuiGpuDevFx) * (size_t)(n - g->n_dfx)); + g->dfx = nd; + g->n_dfx = n; + } + BuiGpuDevFx *f = &g->dfx[slot]; + if (f->id == v->id) { + return f; + } + if (f->id) { /* a freed effect's slot, reused */ + flush(g); + dfx_release(g, f); + } + char log[BUI_EFFECT_LOG] = ""; + f->id = v->id; + f->n_inputs = v->n_inputs; + f->n_floats = v->n_floats; + f->prog = g->ops->fx_build(g, v, log, sizeof(log)); + if (!f->prog) { + f->failed = 1; + bui_gpu_fail(log, 0); + } + bui_effect_set_error(v->id, log); + return f; +} + +/* Frees the pipelines of effects freed in the registry. */ +static void dfx_sweep(BuiGpu *g) +{ + const unsigned fg = bui_effect_free_gen(); + if (fg == g->dfx_free_gen) { + return; + } + g->dfx_free_gen = fg; + BuiEffectView v; + for (int i = 0; i < g->n_dfx; i++) { + if (g->dfx[i].id && !bui_effect_view(g->dfx[i].id, &v)) { + flush(g); + dfx_release(g, &g->dfx[i]); + } + } +} + +const BuiGpuDevFx *bui_gpu_dfx(const BuiGpu *g, int effect) +{ + const int slot = BUI_EFFECT_SLOT(effect); + const BuiGpuDevFx *f = slot >= 0 && slot < g->n_dfx ? &g->dfx[slot] : NULL; + return f && f->id == effect && f->prog ? f : NULL; +} + +size_t bui_gpu_fx_consts(const BuiGpu *g, const BuiGpuFxCall *fc, int n_floats, int tw, int th, + BuiGpuFxConsts *r_consts) +{ + float *data = r_consts->data; + memcpy(data, fc->rect, sizeof(fc->rect)); + data[4] = 2.0f / (float)tw; + data[5] = 2.0f / (float)th; + data[6] = data[7] = 0.0f; + for (int i = 0; i < n_floats; i++) { /* HLSL gives each element of an array a register */ + float *reg = data + 8 + 4 * i; + reg[0] = g->fxf[fc->floats + i]; + reg[1] = reg[2] = reg[3] = 0.0f; + } + if (n_floats == 0) { + memset(data + 8, 0, sizeof(float) * 4); + } + return sizeof(float) * (size_t)(8 + 4 * (n_floats > 0 ? n_floats : 1)); +} + +int bui_gpu_effect(BuiGpu *g, + int dst, + int effect, + const float rect[4], + const int inputs[BUI_EFFECT_MAX_INPUTS], + const float *floats, + int n_floats, + const int clip[4]) +{ + BuiEffectView v; + if (!bui_effect_view(effect, &v)) { + return 0; + } + dfx_sweep(g); + BuiGpuDevFx *f = dfx_get(g, &v); + if (!f || f->failed) { + return 0; + } + dtex_sweep(g); + if (dst) { + dtex_get(g, dst); + const BuiGpuDevTex *d = bui_gpu_dtex(g, dst); + if (!d || !d->target) { + return 0; /* not a render target, or the device could not make it */ + } + for (int k = 0; k < v.n_inputs; k++) { + if (inputs[k] == dst) { + return 0; /* a pass cannot sample the target it draws into */ + } + } + } + for (int k = 0; k < v.n_inputs; k++) { + dtex_get(g, inputs[k]); /* may flush: before anything of this draw is recorded */ + } + if (!grow((void **)&g->fx, &g->cap_fx, g->n_fx + 1, sizeof(BuiGpuFxCall)) || + !grow((void **)&g->fxf, &g->cap_fxf, g->n_fxf + v.n_floats, sizeof(float))) + { + return 0; + } + /* never merged: each draw has its own shader state */ + BuiGpuBatch *b = batch_new(g, BUI_BATCH_FX, g->n_fx); + if (!b) { + return 0; + } + b->count = 1; + BuiGpuFxCall *c = &g->fx[g->n_fx++]; + c->effect = effect; + c->dst = dst; + memcpy(c->rect, rect, sizeof(c->rect)); + memcpy(c->inputs, inputs, sizeof(c->inputs)); + memcpy(c->clip, clip, sizeof(c->clip)); + c->floats = g->n_fxf; + const int n = floats && n_floats > 0 ? (n_floats < v.n_floats ? n_floats : v.n_floats) : 0; + if (n > 0) { + memcpy(g->fxf + g->n_fxf, floats, sizeof(float) * (size_t)n); + } + memset(g->fxf + g->n_fxf + n, 0, sizeof(float) * (size_t)(v.n_floats - n)); + g->n_fxf += v.n_floats; + return 1; +} + +int bui_gpu_target_clear(BuiGpu *g, int target, const float rgba[4]) +{ + dtex_sweep(g); + dtex_get(g, target); + const BuiGpuDevTex *d = bui_gpu_dtex(g, target); + if (!d || !d->target || !grow((void **)&g->fx, &g->cap_fx, g->n_fx + 1, sizeof(BuiGpuFxCall)) || + !grow((void **)&g->fxf, &g->cap_fxf, g->n_fxf + 4, sizeof(float))) + { + return 0; + } + BuiGpuBatch *b = batch_new(g, BUI_BATCH_FX, g->n_fx); + if (!b) { + return 0; + } + b->count = 1; + BuiGpuFxCall *c = &g->fx[g->n_fx++]; + memset(c, 0, sizeof(*c)); + c->dst = target; /* effect 0: a clear */ + c->floats = g->n_fxf; + memcpy(g->fxf + g->n_fxf, rgba, sizeof(float) * 4); + g->n_fxf += 4; + return 1; +} + +static uint64_t mix64(uint64_t h) +{ + h ^= h >> 33; + h *= 0xff51afd7ed558ccdull; + h ^= h >> 33; + return h; +} + +static void mask_reset(BuiGpu *g) +{ + flush(g); /* recorded instances still point into the old layout */ + atlas_clear(&g->mask); + memset(g->mask_map, 0, sizeof(BuiGpuSlot) * MASK_MAP); + g->mask_n = 0; +} + +int bui_gpu_mask(BuiGpu *g, const void *key, unsigned gen, const uint8_t *mask, int w, int h, + int *r_x, int *r_y) +{ + if (w + 1 > g->mask.size || h + 1 > g->mask.size) { + return 0; + } + if (gen != g->mask_gen) { /* text runs were freed: their keys may be reused */ + g->mask_gen = gen; + mask_reset(g); + } + const uint64_t k1 = key ? (uint64_t)(uintptr_t)key : 0, k2 = ((uint64_t)w << 32) | (uint32_t)h; + uint32_t idx = 0; + if (key) { + idx = (uint32_t)mix64(k1) & (MASK_MAP - 1); + for (;;) { + BuiGpuSlot *s = &g->mask_map[idx]; + if (s->k1 == 0) { + break; + } + if (s->k1 == k1 && s->k2 == k2) { + *r_x = s->x; + *r_y = s->y; + return 1; + } + idx = (idx + 1) & (MASK_MAP - 1); + } + if (g->mask_n >= MASK_MAP_FILL) { + mask_reset(g); + return bui_gpu_mask(g, key, gen, mask, w, h, r_x, r_y); + } + } + int x, y; + if (!atlas_place(&g->mask, w, h, &x, &y)) { + mask_reset(g); /* empty now, and the map slot must be found again */ + return bui_gpu_mask(g, key, gen, mask, w, h, r_x, r_y); + } + g->ops->tex_update(g, g->mask.tex, x, y, w, h, mask, w); + if (key) { + BuiGpuSlot *s = &g->mask_map[idx]; + s->k1 = k1; + s->k2 = k2; + s->x = x; + s->y = y; + g->mask_n++; + } + *r_x = x; + *r_y = y; + return 1; +} + +/* -------------------------------------------------------------------- */ +/** \name Slug glyphs + * + * Eric Lengyel's Slug algorithm (https://github.com/EricLengyel/Slug): + * glyph outlines live on the GPU as quadratic curves, split into horizontal + * and vertical bands; the pixel shader casts a ray each way through the + * pixel's bands and integrates exact coverage. Resolution independent, one + * quad per glyph, no rasterizing or atlas packing on the CPU. + * \{ */ + +int bui_gpu_slug_on(BuiGpu *g) +{ + if (g->slug == 0) { + g->slug = -1; + g->curve_tex = g->ops->tex_create(g, BUI_FMT_RGBA32F, SLUG_W, SLUG_H, NULL, 0, 0); + g->band_tex = g->curve_tex ? g->ops->tex_create(g, BUI_FMT_RG32UI, SLUG_W, SLUG_H, NULL, 0, 0) : + NULL; + if (g->band_tex && (g->slug_map = (BuiGpuSlugGlyph *)calloc(SLUG_MAP, sizeof(BuiGpuSlugGlyph)))) + { + g->slug = 1; + } + } + return g->slug > 0; +} + +static void slug_reset(BuiGpu *g) +{ + flush(g); /* recorded instances still point at the old data */ + memset(g->slug_map, 0, sizeof(BuiGpuSlugGlyph) * SLUG_MAP); + g->slug_n = g->curve_next = g->band_next = 0; +} + +/* Uploads `count` texels at linear index `at`, row by row. */ +static void slug_upload(BuiGpu *g, BuiGpuTex *tex, int at, const void *data, int count, int texel) +{ + const char *p = (const char *)data; + while (count > 0) { + const int x = at % SLUG_W, y = at / SLUG_W; + const int n = count < SLUG_W - x ? count : SLUG_W - x; + g->ops->tex_update(g, tex, x, y, n, 1, p, n * texel); + p += (size_t)n * texel; + at += n; + count -= n; + } +} + +typedef struct SlugSort { + float key; + uint32_t curve; +} SlugSort; + +static int slug_cmp(const void *a, const void *b) +{ + const float ka = ((const SlugSort *)a)->key, kb = ((const SlugSort *)b)->key; + return ka < kb ? 1 : ka > kb ? -1 : 0; /* descending */ +} + +static float min3(float a, float b, float c) +{ + return a < b ? (a < c ? a : c) : (b < c ? b : c); +} +static float max3(float a, float b, float c) +{ + return a > b ? (a > c ? a : c) : (b > c ? b : c); +} + +/* Builds and uploads a glyph's curve and band data. */ +static int slug_build(BuiGpu *g, BuiGpuSlugGlyph *sg, const float *cv, int n, const float bb[4]) +{ + const int nb = n < 8 ? 1 : (n / 4 < SLUG_MAX_BANDS ? n / 4 : SLUG_MAX_BANDS); + const float w = bb[2] - bb[0] > 1.0f ? bb[2] - bb[0] : 1.0f; + const float h = bb[3] - bb[1] > 1.0f ? bb[3] - bb[1] : 1.0f; + /* horizontal bands split y, vertical bands split x */ + const float hs = (float)nb / h, vs = (float)nb / w; + const float eps = 1.0f / 1024.0f * (w > h ? w : h); + + /* worst case every curve lands in every band */ + const int max_entries = 2 * nb * n; + const int need_band = 2 * nb + max_entries, need_curve = 2 * n; + if (need_curve > SLUG_W * SLUG_H / 4 || need_band > SLUG_W * SLUG_H / 4) { + return 0; /* absurd glyph */ + } + if (g->curve_next + need_curve > SLUG_W * SLUG_H || g->band_next + need_band > SLUG_W * SLUG_H || + g->slug_n >= SLUG_MAP_FILL) + { + return -1; /* full: caller resets and retries */ + } + float *ct = (float *)malloc(sizeof(float) * 8 * (size_t)n); + uint32_t *bt = (uint32_t *)malloc(sizeof(uint32_t) * 2 * (size_t)need_band); + SlugSort *tmp = (SlugSort *)malloc(sizeof(SlugSort) * (size_t)n); + if (!ct || !bt || !tmp) { + free(ct); + free(bt); + free(tmp); + return 0; + } + const int cbase = g->curve_next; /* even: a curve never straddles a row */ + for (int i = 0; i < n; i++) { + const float *q = cv + 6 * i; + float *t = ct + 8 * i; + t[0] = q[0]; + t[1] = q[1]; + t[2] = q[2]; + t[3] = q[3]; + t[4] = q[4]; + t[5] = q[5]; + t[6] = t[7] = 0.0f; + } + const int bbase = g->band_next; + int at = 2 * nb; /* entries follow the 2 * nb headers */ + for (int dir = 0; dir < 2; dir++) { + for (int b = 0; b < nb; b++) { + /* band range in font units */ + const float s = dir == 0 ? hs : vs, o = dir == 0 ? bb[1] : bb[0]; + const float lo = o + (float)b / s - eps, hi = o + (float)(b + 1) / s + eps; + int m = 0; + for (int i = 0; i < n; i++) { + const float *q = cv + 6 * i; + /* dir 0 (horizontal rays) uses y extents, sorted by max x; dir 1 the reverse */ + const float a0 = dir == 0 ? q[1] : q[0], a1 = dir == 0 ? q[3] : q[2], + a2 = dir == 0 ? q[5] : q[4]; + const float amin = min3(a0, a1, a2), amax = max3(a0, a1, a2); + if (amax < lo || amin > hi || (a0 == a1 && a1 == a2)) { + continue; /* outside, or parallel to the ray: never crosses it */ + } + tmp[m].key = dir == 0 ? max3(q[0], q[2], q[4]) : max3(q[1], q[3], q[5]); + tmp[m].curve = (uint32_t)(cbase + 2 * i); + m++; + } + qsort(tmp, (size_t)m, sizeof(SlugSort), slug_cmp); + const int hdr = dir * nb + b; + bt[2 * hdr] = (uint32_t)m; + bt[2 * hdr + 1] = (uint32_t)(bbase + at); + for (int k = 0; k < m; k++) { + bt[2 * (at + k)] = tmp[k].curve; + bt[2 * (at + k) + 1] = 0; + } + at += m; + } + } + slug_upload(g, g->curve_tex, cbase, ct, 2 * n, 16); + slug_upload(g, g->band_tex, bbase, bt, at, 8); + g->curve_next += 2 * n; + g->band_next += at; + free(ct); + free(bt); + free(tmp); + memcpy(sg->bbox, bb, sizeof(float[4])); + sg->band[0] = hs; + sg->band[1] = -bb[1] * hs; + sg->band[2] = vs; + sg->band[3] = -bb[0] * vs; + sg->loc[0] = bbase; + sg->loc[1] = nb; + sg->loc[2] = nb; + sg->loc[3] = 0; + sg->ok = 1; + return 1; +} + +int bui_gpu_slug_glyph(BuiGpu *g, int face, int glyph, unsigned gen, float r_bbox[4], + float r_band[4], int r_loc[4]) +{ + if (g->slug <= 0 || face < 0 || face > 0x7ffe || glyph < 0 || glyph > 0xffff) { + return 0; + } + if (gen != g->slug_gen) { /* faces were freed: ids may be reused */ + g->slug_gen = gen; + slug_reset(g); + } + const uint32_t key = ((uint32_t)(face + 1) << 16) | (uint32_t)glyph; + uint32_t idx = (key * 2654435761u) >> 19 & (SLUG_MAP - 1); + BuiGpuSlugGlyph *sg; + for (;;) { + sg = &g->slug_map[idx]; + if (sg->key == 0 || sg->key == key) { + break; + } + idx = (idx + 1) & (SLUG_MAP - 1); + } + if (sg->key == 0) { + float *cv = NULL; + int n = 0; + float bb[4]; + sg->ok = 0; + if (bui_text_glyph_outline(face, glyph, &cv, &n, bb)) { + int got = slug_build(g, sg, cv, n, bb); + if (got < 0) { + slug_reset(g); + free(cv); + return bui_gpu_slug_glyph(g, face, glyph, gen, r_bbox, r_band, r_loc); + } + } + free(cv); + sg->key = key; + g->slug_n++; + } + if (!sg->ok) { + return 0; + } + memcpy(r_bbox, sg->bbox, sizeof(float[4])); + memcpy(r_band, sg->band, sizeof(float[4])); + memcpy(r_loc, sg->loc, sizeof(int[4])); + return 1; +} + +/** \} */ + +static void img_reset(BuiGpu *g) +{ + flush(g); + atlas_clear(&g->rgba); + memset(g->img_map, 0, sizeof(BuiGpuSlot) * IMG_MAP); + g->img_n = 0; +} + +int bui_gpu_image(BuiGpu *g, uint64_t key, const uint32_t *argb, int w, int h, int *r_x, int *r_y) +{ + if (!g->rgba.tex && !atlas_create(g, &g->rgba, 2048, 4)) { + return 0; + } + if (w + 1 > g->rgba.size || h + 1 > g->rgba.size) { + return 0; /* TODO: images larger than the atlas */ + } + /* key: BuiPixmap.key or its content hash (gpu_raster.c), with the size */ + const uint64_t k1 = key, k2 = ((uint64_t)w << 32) | (uint32_t)h; + uint32_t idx = (uint32_t)mix64(k1) & (IMG_MAP - 1); + for (;;) { + BuiGpuSlot *s = &g->img_map[idx]; + if (s->k1 == 0) { + break; + } + if (s->k1 == k1 && s->k2 == k2) { + *r_x = s->x; + *r_y = s->y; + return 1; + } + idx = (idx + 1) & (IMG_MAP - 1); + } + int x, y; + if (g->img_n >= IMG_MAP_FILL || !atlas_place(&g->rgba, w, h, &x, &y)) { + img_reset(g); + return bui_gpu_image(g, key, argb, w, h, r_x, r_y); + } + g->ops->tex_update(g, g->rgba.tex, x, y, w, h, argb, w * 4); + BuiGpuSlot *s = &g->img_map[idx]; + s->k1 = k1; + s->k2 = k2; + s->x = x; + s->y = y; + g->img_n++; + *r_x = x; + *r_y = y; + return 1; +} + +/* -- big images: textures of their own ------------------------------------------------ */ + +static size_t big_size(int format, int w, int h) +{ + return format == BUI_PIXMAP_ARGB ? (size_t)w * h * 4 : (size_t)w * h * 3 / 2; +} + +static void big_release(BuiGpu *g, BuiGpuBig *t) +{ + if (t->tex) { + g->big_bytes -= big_size(t->format, t->w, t->h); + } + tex_drop(g, &t->tex); + tex_drop(g, &t->uv); + memset(t, 0, sizeof(*t)); +} + +/* `px` into slot `t`'s textures: created, or (a stream's next frame) updated in place. */ +static int big_upload(BuiGpu *g, BuiGpuBig *t, int create, const uint32_t *px, int stride) +{ + const int nv12 = t->format != BUI_PIXMAP_ARGB; + const uint8_t *uv = (const uint8_t *)px + (size_t)t->w * t->h; + if (!create) { + g->ops->tex_update(g, t->tex, 0, 0, t->w, t->h, px, stride * (nv12 ? 1 : 4)); + if (nv12) { + g->ops->tex_update(g, t->uv, 0, 0, t->w / 2, t->h / 2, uv, t->w); + } + return 1; + } + const int flags = t->stream ? 0 : BUI_TEX_IMMUTABLE; + if (!nv12) { /* 0xAARRGGBB in memory order */ + t->tex = g->ops->tex_create(g, BUI_FMT_BGRA8, t->w, t->h, px, stride * 4, flags); + return t->tex != NULL; + } + t->tex = g->ops->tex_create(g, BUI_FMT_R8, t->w, t->h, px, t->w, flags); + t->uv = t->tex ? g->ops->tex_create(g, BUI_FMT_RG8, t->w / 2, t->h / 2, uv, t->w, flags) : NULL; + if (!t->uv) { + tex_drop(g, &t->tex); + return 0; + } + return 1; +} + +/* Frees what the kit freed (BUI_image_forget) and what went unused. */ +static void big_sweep(BuiGpu *g) +{ + uint64_t gone[64]; + const int n = bui_image_forgotten(&g->forget_seen, gone, 64); /* -1: missed some */ + for (int i = 0; i < BUI_GPU_BIG_MAX; i++) { + BuiGpuBig *t = &g->big[i]; + if (!t->key) { + continue; + } + int drop = g->frame - t->used > BIG_IDLE || (n < 0 && t->used != g->frame); + for (int k = 0; k < n && !drop; k++) { + drop = gone[k] == t->base; + } + if (drop) { + big_release(g, t); + } + } +} + +int bui_gpu_max_texture(BuiGpu *g) +{ + return g->max_tex > 0 ? g->max_tex : 8192; +} + +int bui_gpu_image_tex(BuiGpu *g, uint64_t key, uint64_t base, int stream, int format, + const uint32_t *px, int stride, int w, int h) +{ + if (w <= 0 || h <= 0 || w > bui_gpu_max_texture(g) || h > bui_gpu_max_texture(g)) { + return 0; + } + int free_slot = -1, lru = -1; + for (int i = 0; i < BUI_GPU_BIG_MAX; i++) { + BuiGpuBig *t = &g->big[i]; + if (t->key && t->w == w && t->h == h && t->format == format && + (t->key == key || (stream && t->stream && t->base == base))) + { + if (t->key != key) { /* the stream's next frame: in place, no new texture */ + big_upload(g, t, 0, px, stride); + t->key = key; + } + t->used = g->frame; + return i + 1; + } + if (!t->key) { + free_slot = free_slot < 0 ? i : free_slot; + } + else if (t->used != g->frame && (lru < 0 || t->used < g->big[lru].used)) { + lru = i; /* not drawn this frame: no recorded batch samples it */ + } + } + const size_t bytes = big_size(format, w, h); + while (lru >= 0 && (free_slot < 0 || g->big_bytes + bytes > BIG_BUDGET)) { + big_release(g, &g->big[lru]); + free_slot = free_slot < 0 ? lru : free_slot; + lru = -1; + for (int i = 0; i < BUI_GPU_BIG_MAX; i++) { + const BuiGpuBig *t = &g->big[i]; + if (t->key && t->used != g->frame && (lru < 0 || t->used < g->big[lru].used)) { + lru = i; + } + } + } + if (free_slot < 0) { + return 0; + } + BuiGpuBig *t = &g->big[free_slot]; + t->w = w; + t->h = h; + t->format = format; + t->stream = stream; + if (!big_upload(g, t, 1, px, stride)) { + memset(t, 0, sizeof(*t)); + return 0; + } + t->key = key; + t->base = base; + t->used = g->frame; + g->big_bytes += bytes; + return free_slot + 1; +} + +void bui_gpu_damage(BuiGpu *g, int x, int y, int w, int h) +{ + if (w <= 0 || h <= 0 || g->n_dmg == (int)(sizeof(g->dmg) / sizeof(g->dmg[0]))) { + g->dmg_full = 1; + return; + } + RECT *r = &g->dmg[g->n_dmg++]; + r->left = x; + r->top = y; + r->right = x + w; + r->bottom = y + h; +} + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Drawing + present + * \{ */ + +/* Resizing steps: the target and the swap chain are made a multiple of GPU_SLACK px wide and + * high and kept while the frame stays within [cap - 2 * GPU_SLACK, cap], so a drag-resize + * reallocates every few dozen sizes, not at each one. An alpha window's swap chain is shown at + * the window's size, so it stays exact. */ +# define GPU_SLACK 256 + +static int slack_cap(const BuiGpu *g, int need) +{ + if (g->alpha) { + return need; + } + const int cap = (need + GPU_SLACK - 1) / GPU_SLACK * GPU_SLACK; + return cap < g->max_tex ? cap : need; +} + +static int slack_fits(const BuiGpu *g, int cap, int need) +{ + return cap >= need && (g->alpha ? cap == need : cap - need < 2 * GPU_SLACK); +} + +static int ensure_target(BuiGpu *g) +{ + if (g->has_target && slack_fits(g, g->tw, g->w) && slack_fits(g, g->th, g->h)) { + if (g->fw != g->w || g->fh != g->h) { /* another size in the same texture: a redraw follows */ + g->fw = g->w; + g->fh = g->h; + g->dmg_full = 1; + return g->ops->target(g, g->tw, g->th); /* the same size: cleared */ + } + return 1; + } + const int tw = slack_cap(g, g->w), th = slack_cap(g, g->h); + g->has_target = g->ops->target(g, tw, th); + if (!g->has_target) { + return 0; + } + g->tw = tw; + g->th = th; + g->fw = g->w; + g->fh = g->h; + g->dmg_full = 1; + return 1; +} + +static void flush(BuiGpu *g) +{ + if (g->n_b == 0) { + return; + } + if (ensure_target(g)) { + g->ops->draw(g); + } + g->n_b = g->n_inst = g->n_tv = g->n_mv = g->n_mi = g->n_fx = g->n_fxf = 0; +} + +static int ensure_swap(BuiGpu *g) +{ + if (!g->hwnd) { /* offscreen */ + return 0; + } + if (g->has_swap && slack_fits(g, g->sw, g->w) && slack_fits(g, g->sh, g->h)) { + return 1; + } + const int cw = slack_cap(g, g->w), ch = slack_cap(g, g->h); + g->has_swap = g->ops->swap(g, cw, ch); + if (!g->has_swap) { + return 0; + } + g->sw = cw; + g->sh = ch; + g->swap_fresh = 1; + return 1; +} + +void bui_gpu_clear(BuiGpu *g, int x, int y, int w, int h) +{ + flush(g); /* what was recorded for earlier regions comes first */ + if (!g->alpha || !g->has_target || g->fw != g->w || g->fh != g->h) { + return; /* a new target starts transparent */ + } + const RECT rect = {x, y, x + w, y + h}; + g->ops->clear(g, &rect); +} + +int bui_gpu_present(BuiGpu *g, int full) +{ + flush(g); + if (!g->has_target || !ensure_swap(g)) { + g->n_dmg = g->dmg_full = 0; + if (g->ops->submit) { + g->ops->submit(g); + } + return g->has_target && !g->alpha; /* no alpha surface: the renderer is given up */ + } + for (int i = 0; i < g->n_dmg; i++) { /* clamp: DXGI rejects rects outside the buffer */ + RECT *r = &g->dmg[i]; + r->left = r->left < 0 ? 0 : r->left; + r->top = r->top < 0 ? 0 : r->top; + r->right = r->right > g->w ? g->w : r->right; + r->bottom = r->bottom > g->h ? g->h : r->bottom; + if (r->right <= r->left || r->bottom <= r->top) { + *r = g->dmg[--g->n_dmg]; + i--; + } + } + const int whole = full || g->dmg_full || g->swap_fresh || g->n_dmg == 0 || g->alpha; + /* copying rects adding up to half the frame or more: one copy of it all is cheaper */ + long area = 0; + for (int k = 0; k < 2 && !whole && !g->prev_whole; k++) { + const RECT *rs = k ? g->prev : g->dmg; + for (int i = 0, n = k ? g->n_prev : g->n_dmg; i < n; i++) { + area += (long)(rs[i].right - rs[i].left) * (rs[i].bottom - rs[i].top); + } + } + /* the buffer is two frames old (or of the bitblt model): the whole frame; else what changed + * this frame and the last one, the rest is already there */ + const int copy_whole = whole || g->prev_whole || area * 2 >= (long)g->w * g->h; + RECT copy[32]; + int n_copy = 0; + if (!copy_whole) { + memcpy(copy, g->dmg, sizeof(RECT) * (size_t)g->n_dmg); + memcpy(copy + g->n_dmg, g->prev, sizeof(RECT) * (size_t)g->n_prev); + n_copy = g->n_dmg + g->n_prev; + } + g->prev_whole = whole; + g->n_prev = whole ? 0 : g->n_dmg; + memcpy(g->prev, g->dmg, sizeof(RECT) * (size_t)g->n_prev); + const int dirty = !(full || g->dmg_full || g->swap_fresh) && g->n_dmg > 0; + const int st = g->ops->present(g, copy_whole, copy, n_copy, g->dmg, dirty ? g->n_dmg : 0); + g->swap_fresh = st == BUI_PRESENT_OCCLUDED; + g->n_dmg = g->dmg_full = 0; + return st != BUI_PRESENT_LOST; +} + +int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h) +{ + flush(g); + if (!g->has_target || g->fw != w || g->fh != h || !g->ops->read(g, dst, w, h)) { + return 0; + } + /* like the raster: 0x00RRGGBB, or premultiplied 0xAARRGGBB with alpha */ + if (!g->alpha) { + for (size_t i = 0, n = (size_t)w * h; i < n; i++) { + dst[i] &= 0xFFFFFFu; + } + } + return 1; +} + +/** \} */ + +#else /* no GPU renderer on Windows here (built without BUI_GPU; Linux has gpu_gl.c): every + * raster stays in software */ + +# include "gpu_d3d11.h" + +# if !defined(BUI_GPU_GL) + +# include + +int bui_gpu_slug_on(BuiGpu *g) +{ + (void)g; + return 0; +} +int bui_gpu_slug_glyph(BuiGpu *g, int face, int glyph, unsigned gen, float r_bbox[4], + float r_band[4], int r_loc[4]) +{ + (void)g; + (void)face; + (void)glyph; + (void)gen; + (void)r_bbox; + (void)r_band; + (void)r_loc; + return 0; +} +BuiGpu *bui_gpu_create(void *hwnd, int alpha) +{ + (void)hwnd; + (void)alpha; + return NULL; +} +void bui_gpu_free(BuiGpu *g) +{ + (void)g; +} +int bui_gpu_state(BuiGpu *g, int wait) +{ + (void)g; + (void)wait; + return -1; +} +BuiGpuApi bui_gpu_api_of(const BuiGpu *g) +{ + (void)g; + return BUI_GPU_API_DEFAULT; +} +void bui_gpu_begin(BuiGpu *g, int w, int h) +{ + (void)g; + (void)w; + (void)h; +} +int bui_gpu_image_tex(BuiGpu *g, uint64_t key, uint64_t base, int stream, int format, + const uint32_t *argb, int stride, int w, int h) +{ + (void)g; + (void)key; + (void)base; + (void)stream; + (void)format; + (void)argb; + (void)stride; + (void)w; + (void)h; + return 0; +} +int bui_gpu_max_texture(BuiGpu *g) +{ + (void)g; + return 0; +} +BuiGpuInst *bui_gpu_inst_image(BuiGpu *g, int tex, int x0, int y0, int x1, int y1) +{ + (void)g; + (void)tex; + (void)x0; + (void)y0; + (void)x1; + (void)y1; + return NULL; +} +BuiGpuInst *bui_gpu_inst(BuiGpu *g, int kind, int x0, int y0, int x1, int y1) +{ + (void)g; + (void)kind; + (void)x0; + (void)y0; + (void)x1; + (void)y1; + return NULL; +} +int bui_gpu_mask(BuiGpu *g, const void *key, unsigned gen, const uint8_t *mask, int w, int h, + int *r_x, int *r_y) +{ + (void)g; + (void)key; + (void)gen; + (void)mask; + (void)w; + (void)h; + (void)r_x; + (void)r_y; + return 0; +} +int bui_gpu_image(BuiGpu *g, uint64_t key, const uint32_t *argb, int w, int h, int *r_x, int *r_y) +{ + (void)g; + (void)key; + (void)argb; + (void)w; + (void)h; + (void)r_x; + (void)r_y; + return 0; +} +void bui_gpu_triangles( + BuiGpu *g, const float (*co)[2], const float (*col)[4], int count, const int clip[4]) +{ + (void)g; + (void)co; + (void)col; + (void)count; + (void)clip; +} +void bui_gpu_mesh(BuiGpu *g, + const struct BuiMeshVertex *vtx, + int n_vtx, + const void *idx, + int idx32, + int n_idx, + float ox, + float oy, + int tex, + int nearest, + const int clip[4]) +{ + (void)g; + (void)vtx; + (void)n_vtx; + (void)idx; + (void)idx32; + (void)n_idx; + (void)ox; + (void)oy; + (void)tex; + (void)nearest; + (void)clip; +} +int bui_gpu_effect(BuiGpu *g, + int dst, + int effect, + const float rect[4], + const int inputs[BUI_EFFECT_MAX_INPUTS], + const float *floats, + int n_floats, + const int clip[4]) +{ + (void)g; + (void)dst; + (void)effect; + (void)rect; + (void)inputs; + (void)floats; + (void)n_floats; + (void)clip; + return 0; +} +int bui_gpu_target_clear(BuiGpu *g, int target, const float rgba[4]) +{ + (void)g; + (void)target; + (void)rgba; + return 0; +} +void bui_gpu_clear(BuiGpu *g, int x, int y, int w, int h) +{ + (void)g; + (void)x; + (void)y; + (void)w; + (void)h; +} +void bui_gpu_damage(BuiGpu *g, int x, int y, int w, int h) +{ + (void)g; + (void)x; + (void)y; + (void)w; + (void)h; +} +int bui_gpu_present(BuiGpu *g, int full) +{ + (void)g; + (void)full; + return 0; +} +int bui_gpu_read(BuiGpu *g, uint32_t *dst, int w, int h) +{ + (void)g; + (void)dst; + (void)w; + (void)h; + return 0; +} + +# endif /* !BUI_GPU_GL */ + +#endif /* _WIN32 && BUI_GPU */ diff --git a/gpu/intern/gpu_device.h b/gpu/intern/gpu_device.h new file mode 100644 index 00000000..04b27943 --- /dev/null +++ b/gpu/intern/gpu_device.h @@ -0,0 +1,274 @@ +/* BUI GPU renderer core: the half of a GPU renderer that does not depend on the graphics API. + * + * gpu_device.c implements the whole private interface gpu_raster.c draws through + * (gpu_d3d11.h): recording instances, triangles, meshes and effect draws into batches, the + * shelf-packed glyph and image atlases and their caches, Slug glyph bands, big images and video + * streams, the texture and effect registries' device copies, the persistent frame target's size + * and the damage of each present. What only a graphics API can do (making textures, compiling + * effects, drawing the batches, presenting) is a backend's BuiGpuOps table: + * - gpu_d3d11.c: Direct3D 11 (the default on Windows); + * - gpu_d3d12.c: Direct3D 12 (opt-in: BUI_gpu_set_api, BUI_GPU_API). + * One device is one backend for its whole life: the table is picked when the device is created + * (BUI_gpu_api, GPU_raster.h), and Direct3D 12 falls back to Direct3D 11 when it cannot start. + * Blender splits its GPU module the same way: gpu/intern holds what every backend shares and + * gpu/opengl, gpu/vulkan, gpu/metal fill a GPUBackend (gpu_backend.hh) of device objects. + * + * SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +#endif +#include + +#include +#include + +#include "gpu_d3d11.h" +#include "gpu_effect.h" + +/* A backend's texture (with the views it is drawn through) and compiled effect. */ +typedef struct BuiGpuTex BuiGpuTex; +typedef struct BuiGpuProg BuiGpuProg; + +/* Texture formats the core asks for. */ +typedef enum BuiGpuFormat { + BUI_FMT_R8 = 0, /* text masks, NV12 luma */ + BUI_FMT_RG8, /* NV12 chroma */ + BUI_FMT_BGRA8, /* 0xAARRGGBB pixels (images) */ + BUI_FMT_RGBA8, /* registry textures, BUI_TARGET_RGBA8 */ + BUI_FMT_RGBA16F, /* BUI_TARGET_RGBA16F */ + BUI_FMT_RGBA32F, /* BUI_TARGET_RGBA32F, Slug curves */ + BUI_FMT_RG32UI, /* Slug bands */ +} BuiGpuFormat; + +enum { + BUI_TEX_IMMUTABLE = 1, /* never updated after creation */ + BUI_TEX_TARGET = 2, /* effects draw into it; it starts transparent black */ +}; + +/* What a backend's present reports. */ +enum { BUI_PRESENT_OK = 0, BUI_PRESENT_OCCLUDED = 1, BUI_PRESENT_LOST = 2 }; + +typedef struct BuiGpuOps { + BuiGpuApi api; + /* Worker thread: the device and its pipeline (sets g->dev and g->max_tex). 0 when it cannot + * start; `exit` then frees what was made. */ + int (*init)(BuiGpu *g); + /* Frees g->dev and everything it holds. The core frees its textures and effects first. */ + void (*exit)(BuiGpu *g); + /* A w x h texture, filled from `data` (rows `pitch` bytes apart) or, without, undefined (a + * BUI_TEX_TARGET one: cleared). NULL when the device cannot make it. */ + BuiGpuTex *(*tex_create)(BuiGpu *g, BuiGpuFormat fmt, int w, int h, const void *data, int pitch, + int flags); + /* Replaces a rect of `t` (drawn after what was flushed before, before what is recorded after). */ + void (*tex_update)(BuiGpu *g, BuiGpuTex *t, int x, int y, int w, int h, const void *data, + int pitch); + void (*tex_free)(BuiGpu *g, BuiGpuTex *t); + /* Compiles effect `v` (gpu_effect.h). NULL with the compiler's text in `log` when it fails. */ + BuiGpuProg *(*fx_build)(BuiGpu *g, const BuiEffectView *v, char *log, size_t log_n); + void (*fx_free)(BuiGpu *g, BuiGpuProg *p); + /* The persistent frame target at tw x th (remade only when its size changes), cleared to + * transparent (alpha frames) or opaque black. 0 when it cannot be made. */ + int (*target)(BuiGpu *g, int tw, int th); + /* Draws the recorded batches (BuiGpu.b ...) into the frame target, in order. */ + void (*draw)(BuiGpu *g); + /* Sets a rect of the frame target to transparent. */ + void (*clear)(BuiGpu *g, const RECT *r); + /* The window's swap chain at cw x ch, made or resized. 0 when there is none. */ + int (*swap)(BuiGpu *g, int cw, int ch); + /* Copies the frame (whole: its w x h; else the `copy` rects) into the swap chain's buffer and + * presents it, with `dirty` rects (n_dirty 0: everything changed). BUI_PRESENT_*. */ + int (*present)(BuiGpu *g, int whole, const RECT *copy, int n_copy, const RECT *dirty, + int n_dirty); + /* Ends a frame that is not presented (no window): its work goes to the GPU. NULL: nothing to do. */ + void (*submit)(BuiGpu *g); + /* The frame target's w x h top-left as 0xAARRGGBB rows into `dst`. 0 when it fails. */ + int (*read)(BuiGpu *g, uint32_t *dst, int w, int h); +} BuiGpuOps; + +extern const BuiGpuOps bui_gpu_d3d11_ops; +extern const BuiGpuOps bui_gpu_d3d12_ops; + +/* -------------------------------------------------------------------- */ +/** \name Recorded draws + * \{ */ + +/* Atlases: shelf packing in one texture. */ +#define BUI_GPU_SHELVES 128 +typedef struct BuiGpuAtlas { + int size; + int bpp; /* 1 (R8) or 4 (BGRA8) */ + BuiGpuTex *tex; + int shelf_y[BUI_GPU_SHELVES], shelf_h[BUI_GPU_SHELVES], shelf_x[BUI_GPU_SHELVES]; + int nshelves, next_y; +} BuiGpuAtlas; + +/* cache entry: key -> placement */ +typedef struct BuiGpuSlot { + uint64_t k1, k2; /* 0 = empty */ + int x, y; +} BuiGpuSlot; + +typedef struct BuiGpuSlugGlyph { + uint32_t key; /* (face + 1) << 16 | glyph; 0 = empty */ + int ok; /* 0: empty glyph */ + float bbox[4], band[4]; + int loc[4]; +} BuiGpuSlugGlyph; + +typedef enum BuiGpuBatchKind { + BUI_BATCH_QUADS = 0, /* instances (BuiGpuInst) */ + BUI_BATCH_TRIS = 1, /* colored triangles (BuiGpuTriV) */ + BUI_BATCH_MESH = 2, /* a textured mesh (BuiMeshVertex, indexed) */ + BUI_BATCH_FX = 3, /* one effect draw or target clear (first: its BuiGpuFxCall) */ +} BuiGpuBatchKind; + +typedef struct BuiGpuBatch { + BuiGpuBatchKind kind; + int first, count; + int img; /* quads: the RGBA texture their images sample (-1 none yet, 0 atlas, n: big[n - 1]) */ + /* meshes: texture (0: white), sampler, scissor x0 y0 x1 y1 */ + int tex, nearest; + int clip[4]; +} BuiGpuBatch; + +/* An image too big for the atlas, or a video frame, in a texture of its own. */ +#define BUI_GPU_BIG_MAX 32 +typedef struct BuiGpuBig { + uint64_t key, base; /* 0 = empty */ + int w, h; + int format; /* BUI_PIXMAP_*: NV12 is luma in tex, chroma in uv */ + int stream; /* `base` is a stream: its frames update the textures in place */ + unsigned used; /* the frame it was last drawn in */ + BuiGpuTex *tex, *uv; +} BuiGpuBig; + +/* A registry texture (BUI_texture_*) on this device, by registry slot. */ +typedef struct BuiGpuDevTex { + int id; /* 0 = empty */ + unsigned gen; + int w, h; + int target; /* a render target (BUI_target_create): 1 + BUI_TARGET_*, effects draw into it */ + BuiGpuTex *tex; +} BuiGpuDevTex; + +typedef struct BuiGpuTriV { + float x, y; + float c[4]; + float clip[4]; +} BuiGpuTriV; + +/* An effect (gpu_effect.h) on this device, by registry slot: compiled on first use. */ +typedef struct BuiGpuDevFx { + int id; /* 0 = empty */ + int failed; /* compiling it failed: the log is the effect's error */ + int n_inputs, n_floats; + BuiGpuProg *prog; +} BuiGpuDevFx; + +/* One recorded effect draw. */ +typedef struct BuiGpuFxCall { + int effect; /* 0: not a draw but a clear of `dst` (its 4 floats at `floats`) */ + int dst; /* 0: the frame; else the render target it draws into */ + float rect[4]; + int inputs[BUI_EFFECT_MAX_INPUTS]; + int clip[4]; + int floats; /* where its n_floats of the effect are in BuiGpu.fxf */ +} BuiGpuFxCall; + +/* An effect's constant buffer (b1): box, 2 / target size, then one register per float (HLSL gives + * each element of an array a register). Its size in bytes is bui_gpu_fx_cb_size. */ +typedef struct BuiGpuFxConsts { + float data[8 + 4 * BUI_EFFECT_MAX_FLOATS]; +} BuiGpuFxConsts; + +/** \} */ + +struct BuiGpu { + const BuiGpuOps *ops; + void *dev; /* the backend's device */ + HWND hwnd; + /* alpha: frames keep premultiplied alpha (the target starts transparent) */ + int alpha; + volatile LONG state; /* 0 pending, 1 ready, -1 failed */ + HANDLE thread; + + int has_target; /* ops->target made it */ + int tw, th; /* target texture size (>= the frame) */ + int fw, fh; /* the frame size the target holds */ + int w, h; /* frame size */ + int has_swap, sw, sh; /* swap chain size */ + int swap_fresh; /* the swap chain was (re)made or its last frame dropped: present it whole */ + int max_tex; /* the device's largest texture side */ + + BuiGpuTex *white; /* 1x1 white: meshes without a texture, unbound inputs */ + BuiGpuDevTex *dtex; + int n_dtex; + unsigned dtex_free_gen; + BuiGpuDevFx *dfx; + int n_dfx; + unsigned dfx_free_gen; + + BuiGpuAtlas mask, rgba; + BuiGpuBig big[BUI_GPU_BIG_MAX]; + size_t big_bytes; + unsigned frame, forget_seen; + BuiGpuSlot *mask_map, *img_map; + int mask_n, img_n; + unsigned mask_gen; + + int slug; /* -1: off (unavailable), 0: not created yet, 1: ready */ + BuiGpuTex *curve_tex, *band_tex; + BuiGpuSlugGlyph *slug_map; + int slug_n, curve_next, band_next; + unsigned slug_gen; + + BuiGpuInst *inst; + int n_inst, cap_inst; + BuiGpuTriV *tv; + int n_tv, cap_tv; + BuiMeshVertex *mv; + int n_mv, cap_mv; + uint32_t *mi; + int n_mi, cap_mi; + BuiGpuFxCall *fx; + int n_fx, cap_fx; + float *fxf; + int n_fxf, cap_fxf; + BuiGpuBatch *b; + int n_b, cap_b; + + RECT dmg[16]; + int n_dmg, dmg_full; + /* the last present's damage (whole: the whole frame): with two flip buffers, the buffer being + * drawn is two frames old, so it needs this frame's damage and that one's, not everything */ + RECT prev[16]; + int n_prev, prev_whole; +}; + +/* -------------------------------------------------------------------- */ +/** \name What the backends share + * \{ */ + +/* BUI_GPU_DEBUG: 0 off, 1 report why the GPU path wasn't taken (and which device it took), 2 also + * the API's debug layer (Direct3D 12) with its messages. */ +int bui_gpu_debug(void); +/* Reports (BUI_GPU_DEBUG) that `what` failed with `hr`; returns 0. */ +int bui_gpu_fail(const char *what, long hr); + +/* The device texture of registry texture `id` once recorded (NULL: not live here). */ +const BuiGpuDevTex *bui_gpu_dtex(const BuiGpu *g, int id); +/* The texture a recorded draw samples for registry texture `id` (g->white when not live). */ +BuiGpuTex *bui_gpu_dtex_tex(const BuiGpu *g, int id); +/* The compiled effect a recorded draw runs (NULL: none). */ +const BuiGpuDevFx *bui_gpu_dfx(const BuiGpu *g, int effect); +/* The vertex data of batch kind `k` (instances, triangle vertices, mesh vertices) and its count. */ +const void *bui_gpu_batch_data(const BuiGpu *g, BuiGpuBatchKind k, int *r_count); +/* The atlas or big image texture (and NV12 chroma, else NULL) quad batch `b` samples. */ +BuiGpuTex *bui_gpu_batch_image(const BuiGpu *g, const BuiGpuBatch *b, BuiGpuTex **r_uv); +/* An effect call's constant buffer for a target of tw x th; returns its size in bytes. */ +size_t bui_gpu_fx_consts(const BuiGpu *g, const BuiGpuFxCall *fc, int n_floats, int tw, int th, + BuiGpuFxConsts *r_consts); + +/** \} */ diff --git a/gpu/intern/gpu_dx.c b/gpu/intern/gpu_dx.c new file mode 100644 index 00000000..fbba69c0 --- /dev/null +++ b/gpu/intern/gpu_dx.c @@ -0,0 +1,200 @@ +/* What the Direct3D backends share — see gpu_dx.h. + * + * SPDX-License-Identifier: GPL-2.0-or-later */ + +#if defined(_WIN32) && defined(BUI_GPU) /* BUI_GPU: features.json */ + +# define COBJMACROS +# include "gpu_dx.h" + +# include +# include +# include + +/* defined here rather than taken from dxguid.lib: nothing to link */ +const GUID bui_IID_IDXGIFactory2 = { + 0x50c83a1c, 0xe072, 0x4c48, {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0}}; +const GUID bui_IID_IDXGIFactory4 = { + 0x1bc6ea02, 0xef36, 0x464f, {0xbf, 0x0c, 0x21, 0xca, 0x39, 0xe5, 0x16, 0x8a}}; +const GUID bui_IID_IDXGIAdapter = { + 0x2411e7e1, 0x12ac, 0x4ccf, {0xbd, 0x14, 0x97, 0x98, 0xe8, 0x53, 0x4d, 0xc0}}; +const GUID bui_IID_IDXGIAdapter1 = { + 0x29038f61, 0x3839, 0x4626, {0x91, 0xfd, 0x08, 0x68, 0x79, 0x01, 0x1a, 0x05}}; +static const GUID k_IID_IDXGIFactory6 = { + 0xc1b6694f, 0xff09, 0x44a9, {0xb0, 0x3c, 0x77, 0x90, 0x0a, 0x0a, 0x1d, 0x17}}; + +IDXGIAdapter *bui_dx_preferred_adapter(void) +{ + const char *pref = getenv("BUI_GPU_ADAPTER"); + if (!pref || !pref[0] || strcmp(pref, "default") == 0) { + return NULL; + } + if (strcmp(pref, "high-performance") != 0) { + bui_gpu_fail("BUI_GPU_ADAPTER: expected \"high-performance\" or \"default\"", 0); + return NULL; + } + typedef HRESULT(WINAPI * FactoryFn)(REFIID, void **); + HMODULE dxgi = LoadLibraryW(L"dxgi.dll"); + FactoryFn make = dxgi ? (FactoryFn)(void *)GetProcAddress(dxgi, "CreateDXGIFactory1") : NULL; + IDXGIFactory6 *f6 = NULL; + IDXGIAdapter *ad = NULL; + if (!make || FAILED(make(&k_IID_IDXGIFactory6, (void **)&f6))) { + bui_gpu_fail("IDXGIFactory6 (Windows 10 1803+)", 0); + return NULL; + } + if (FAILED(IDXGIFactory6_EnumAdapterByGpuPreference(f6, 0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, + &bui_IID_IDXGIAdapter, (void **)&ad))) + { + ad = NULL; + } + REL(f6); + return ad; +} + +void bui_dx_report(const char *api, IDXGIAdapter *ad) +{ + DXGI_ADAPTER_DESC desc; + if (bui_gpu_debug() && ad && SUCCEEDED(IDXGIAdapter_GetDesc(ad, &desc))) { + fprintf(stderr, "bui gpu: %s on %ls\n", api, desc.Description); + } +} + +int bui_dx_present_status(HRESULT hr) +{ + if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { + return BUI_PRESENT_LOST; + } + /* occluded or minimized: DWM dropped the frame, so the next one must be whole */ + return hr == DXGI_STATUS_OCCLUDED ? BUI_PRESENT_OCCLUDED : BUI_PRESENT_OK; +} + +DXGI_SWAP_CHAIN_DESC1 bui_dx_swap_desc(int w, int h) +{ + DXGI_SWAP_CHAIN_DESC1 sd; + memset(&sd, 0, sizeof(sd)); + sd.Width = (UINT)w; + sd.Height = (UINT)h; + sd.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + sd.SampleDesc.Count = 1; + sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + sd.BufferCount = 2; + sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; + sd.Scaling = DXGI_SCALING_NONE; + sd.AlphaMode = DXGI_ALPHA_MODE_IGNORE; + return sd; +} + +/* -------------------------------------------------------------------- */ +/** \name The renderer's programs + * \{ */ + +# include "gpu_d3d11_shaders.h" + +# define INST(name, idx, off) {name, idx, DXGI_FORMAT_R32G32B32A32_FLOAT, off, 1} +static const BuiDxInput k_quad[] = { + INST("RECT", 0, 0), INST("BOUNDS", 0, 16), INST("COLOR", 0, 32), INST("COLOR", 1, 48), + INST("COLOR", 2, 64), INST("COLOR", 3, 80), INST("PARAMS", 0, 96), INST("EXTRA", 0, 112), +}; +# undef INST +static const BuiDxInput k_tri[] = { + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0}, + {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 8, 0}, + {"CLIP", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 24, 0}, +}; +static const BuiDxInput k_mesh[] = { /* BuiMeshVertex (= ImDrawVert) */ + {"POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0}, + {"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 8, 0}, + {"COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 16, 0}, +}; + +const BuiDxProgram bui_dx_programs[BUI_DX_PROGRAMS] = { + {g_vs_quad, g_ps_quad, sizeof(g_vs_quad), sizeof(g_ps_quad), k_quad, 8, sizeof(BuiGpuInst)}, + {g_vs_tri, g_ps_tri, sizeof(g_vs_tri), sizeof(g_ps_tri), k_tri, 3, sizeof(BuiGpuTriV)}, + {g_vs_mesh, g_ps_mesh, sizeof(g_vs_mesh), sizeof(g_ps_mesh), k_mesh, 3, sizeof(BuiMeshVertex)}, +}; + +/** \} */ + +/* -------------------------------------------------------------------- */ +/** \name Effects: the HLSL compiler + * \{ */ + +typedef HRESULT(WINAPI *D3DCompileFn)(LPCVOID, SIZE_T, LPCSTR, const D3D_SHADER_MACRO *, + ID3DInclude *, LPCSTR, LPCSTR, UINT, UINT, ID3DBlob **, + ID3DBlob **); + +/* d3dcompiler_47.dll (Windows 8.1 and later ship it) is loaded when the first effect is drawn: + * nothing links against it and no SDK is needed. System folder first, then the app's own. */ +static D3DCompileFn g_d3d_compile; + +static BOOL CALLBACK d3d_compiler_load(PINIT_ONCE once, PVOID param, PVOID *ctx) +{ + (void)once; + (void)param; + (void)ctx; + HMODULE m = LoadLibraryExW(L"d3dcompiler_47.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32); + if (!m) { + m = LoadLibraryExW(L"d3dcompiler_47.dll", NULL, LOAD_LIBRARY_SEARCH_APPLICATION_DIR); + } + if (m) { + g_d3d_compile = (D3DCompileFn)(void *)GetProcAddress(m, "D3DCompile"); + } + return TRUE; +} + +/* Loaded once, whichever thread draws the first effect (devices of several windows or tests + * compile at the same time): another thread waits for the load rather than seeing it unfinished. */ +static D3DCompileFn d3d_compiler(void) +{ + static INIT_ONCE once = INIT_ONCE_STATIC_INIT; + InitOnceExecuteOnce(&once, d3d_compiler_load, NULL, NULL); + return g_d3d_compile; +} + +/* One stage of the assembled source; on failure the compiler's text goes to `log`. */ +static ID3DBlob *fx_stage(D3DCompileFn compile, const char *src, const char *name, + const char *entry, const char *target, char *log, size_t log_n) +{ + ID3DBlob *code = NULL, *err = NULL; + const HRESULT hr = compile(src, strlen(src), name, NULL, NULL, entry, target, + (1u << 15) /* D3DCOMPILE_OPTIMIZATION_LEVEL3 */, 0, &code, &err); + if (FAILED(hr)) { + snprintf(log, log_n, "%.*s", + err ? (int)ID3D10Blob_GetBufferSize(err) : 0, + err ? (const char *)ID3D10Blob_GetBufferPointer(err) : "compile failed"); + REL(code); + } + REL(err); + return FAILED(hr) ? NULL : code; +} + +int bui_dx_fx_compile(const BuiEffectView *v, const char *model, ID3DBlob **r_vs, + ID3DBlob **r_ps, char *log, size_t log_n) +{ + *r_vs = *r_ps = NULL; + D3DCompileFn compile = d3d_compiler(); + if (!compile) { + snprintf(log, log_n, "d3dcompiler_47.dll is not available: the effect cannot run on this system"); + return 0; + } + char *src = bui_effect_assemble(BUI_FX_HLSL, v); + if (!src) { + snprintf(log, log_n, "out of memory"); + return 0; + } + char ps[8], vs[8]; + snprintf(ps, sizeof(ps), "ps_%s", model); + snprintf(vs, sizeof(vs), "vs_%s", model); + *r_ps = fx_stage(compile, src, v->name, "bui_ps", ps, log, log_n); + free(src); + *r_vs = *r_ps ? fx_stage(compile, bui_fx_hlsl_vs, "effect_vs", "bui_vs", vs, log, log_n) : NULL; + if (!*r_vs) { + REL(*r_ps); + return 0; + } + return 1; +} + +/** \} */ + +#endif /* _WIN32 && BUI_GPU */ diff --git a/gpu/intern/gpu_dx.h b/gpu/intern/gpu_dx.h new file mode 100644 index 00000000..a8cac542 --- /dev/null +++ b/gpu/intern/gpu_dx.h @@ -0,0 +1,60 @@ +/* What the Direct3D backends (gpu_d3d11.c, gpu_d3d12.c) share: DXGI (the adapter, the swap chain's + * present result) and the HLSL compiler for effects. + * + * SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include "gpu_device.h" + +#include +#include + +#define REL(p) \ + do { \ + if (p) { \ + IUnknown_Release((IUnknown *)(p)); \ + (p) = NULL; \ + } \ + } while (0) + +extern const GUID bui_IID_IDXGIFactory2; +extern const GUID bui_IID_IDXGIFactory4; +extern const GUID bui_IID_IDXGIAdapter; +extern const GUID bui_IID_IDXGIAdapter1; + +/* The adapter `BUI_GPU_ADAPTER` asks for: "high-performance" is DXGI's choice for that preference + * (the discrete GPU of a hybrid laptop, which Nsight and other vendor tools profile); unset or + * "default" is NULL, the display's adapter Windows picks. The caller releases it. */ +IDXGIAdapter *bui_dx_preferred_adapter(void); +/* BUI_GPU_DEBUG: which API and adapter the device runs on. */ +void bui_dx_report(const char *api, IDXGIAdapter *ad); +/* What a swap chain's Present returned, as BUI_PRESENT_*. */ +int bui_dx_present_status(HRESULT hr); +/* The flip-model swap chain of an opaque window: B8G8R8A8, two buffers (the damage of the last + * present is redrawn into the buffer of the one before, gpu_device.c). */ +DXGI_SWAP_CHAIN_DESC1 bui_dx_swap_desc(int w, int h); + +/* The renderer's own programs (gpu/shaders/bui_ui.hlsl, compiled into gpu_d3d11_shaders.h as + * shader model 4.0 bytecode, which both APIs take): one per batch kind that has vertex data. */ +typedef struct BuiDxInput { + const char *semantic; + UINT index; + DXGI_FORMAT format; + UINT offset; + UINT instanced; /* per instance (step rate 1), else per vertex */ +} BuiDxInput; +typedef struct BuiDxProgram { + const void *vs, *ps; + size_t vs_size, ps_size; + const BuiDxInput *inputs; + UINT n_inputs; + UINT stride; /* bytes per vertex (or instance) */ +} BuiDxProgram; +/* by BuiGpuBatchKind: BUI_BATCH_QUADS, BUI_BATCH_TRIS, BUI_BATCH_MESH */ +#define BUI_DX_PROGRAMS 3 +extern const BuiDxProgram bui_dx_programs[BUI_DX_PROGRAMS]; + +/* Compiles effect `v` (gpu_effect.h) to vertex and pixel shader bytecode for shader model + * `model` ("4_0", "5_0"). 0 with the compiler's text in `log` when it fails. */ +int bui_dx_fx_compile(const BuiEffectView *v, const char *model, ID3DBlob **r_vs, + ID3DBlob **r_ps, char *log, size_t log_n); diff --git a/gpu/intern/gpu_gl.c b/gpu/intern/gpu_gl.c index a03979c5..5af7e2d6 100644 --- a/gpu/intern/gpu_gl.c +++ b/gpu/intern/gpu_gl.c @@ -1573,6 +1573,12 @@ int bui_gpu_state(BuiGpu *g, int wait) return __atomic_load_n(&g->state, __ATOMIC_ACQUIRE); } +BuiGpuApi bui_gpu_api_of(const BuiGpu *g) +{ + (void)g; + return BUI_GPU_API_OPENGL; +} + void bui_gpu_free(BuiGpu *g) { if (!g) { diff --git a/gpu/intern/gpu_raster.c b/gpu/intern/gpu_raster.c index 9de56cc2..bd93c171 100644 --- a/gpu/intern/gpu_raster.c +++ b/gpu/intern/gpu_raster.c @@ -272,6 +272,55 @@ int BUI_gpu_default(void) return g_gpu_default > 0; } +static BuiGpuApi g_gpu_api = BUI_GPU_API_DEFAULT; + +/* The baked default (GPU_raster.h): volatile, so the compiler neither folds it into the code nor + * drops it, and a patched executable is read as patched. */ +static volatile const char g_gpu_api_marker[BUI_GPU_API_MARKER_LEN] = BUI_GPU_API_MARKER; + +void BUI_gpu_set_api(BuiGpuApi api) +{ + if (api == BUI_GPU_API_DEFAULT || api == BUI_GPU_API_D3D11 || api == BUI_GPU_API_D3D12) { + g_gpu_api = api; + } +} + +/* "d3d11" / "d3d12" (any case) at `s`, `n` bytes; BUI_GPU_API_DEFAULT for anything else. */ +static BuiGpuApi gpu_api_name(const char *s, size_t n) +{ + if (n != 5 || (s[0] | 0x20) != 'd' || s[1] != '3' || (s[2] | 0x20) != 'd' || s[3] != '1') { + return BUI_GPU_API_DEFAULT; + } + return s[4] == '1' ? BUI_GPU_API_D3D11 : s[4] == '2' ? BUI_GPU_API_D3D12 : BUI_GPU_API_DEFAULT; +} + +BuiGpuApi BUI_gpu_api(void) +{ + const char *env = getenv("BUI_GPU_API"); + if (env && env[0]) { + const BuiGpuApi api = gpu_api_name(env, strlen(env)); + if (api != BUI_GPU_API_DEFAULT) { + return api; + } + const char *dbg = getenv("BUI_GPU_DEBUG"); + if (dbg && dbg[0] >= '1' && dbg[0] <= '9') { + fprintf(stderr, "bui gpu: BUI_GPU_API=%s ignored (expected d3d11 or d3d12)\n", env); + } + } + if (g_gpu_api != BUI_GPU_API_DEFAULT) { + return g_gpu_api; + } + char baked[BUI_GPU_API_MARKER_LEN + 1]; + size_t n = 0; + for (; n < BUI_GPU_API_MARKER_LEN && g_gpu_api_marker[n]; n++) { + baked[n] = g_gpu_api_marker[n]; + } + baked[n] = 0; + const size_t eq = sizeof("BUIGPUAPI=") - 1; + const BuiGpuApi api = n > eq ? gpu_api_name(baked + eq, n - eq) : BUI_GPU_API_DEFAULT; + return api != BUI_GPU_API_DEFAULT ? api : BUI_GPU_API_D3D11; +} + #ifndef BUI_SLUG_DEFAULT # define BUI_SLUG_DEFAULT 1 #endif @@ -379,6 +428,11 @@ int BUI_raster_is_gpu(const BuiRaster *r) return r->gpu != NULL; } +BuiGpuApi BUI_raster_gpu_api(const BuiRaster *r) +{ + return r->gpu ? bui_gpu_api_of(r->gpu) : BUI_GPU_API_DEFAULT; +} + /* back to the software raster (device lost) */ static void gpu_drop(BuiRaster *r) { diff --git a/gpu/tests/CMakeLists.txt b/gpu/tests/CMakeLists.txt index 952c3db6..95b04a04 100644 --- a/gpu/tests/CMakeLists.txt +++ b/gpu/tests/CMakeLists.txt @@ -18,3 +18,12 @@ if(NOT MSVC) target_link_libraries(bui_gpu_effect PRIVATE m) endif() add_test(NAME gpu_effect COMMAND bui_gpu_effect) + +# Windows: the same GPU tests on Direct3D 12 (Direct3D 11 is the default). test_gpu_api.h fails a +# run whose device fell back to Direct3D 11. +if(WIN32) + foreach(t gpu_parity raster_alpha gpu_effect) + add_test(NAME ${t}_d3d12 COMMAND bui_${t}) + set_tests_properties(${t}_d3d12 PROPERTIES ENVIRONMENT "BUI_GPU_API=d3d12") + endforeach() +endif() diff --git a/gpu/tests/test_gpu_api.h b/gpu/tests/test_gpu_api.h new file mode 100644 index 00000000..4e8416cc --- /dev/null +++ b/gpu/tests/test_gpu_api.h @@ -0,0 +1,26 @@ +/* The GPU tests attach their device through this: it runs on the API BUI_gpu_api() names (the + * BUI_GPU_API variable, which the *_d3d12 tests set), and one that fell back to another API ends + * the run as a failure instead of passing on the wrong one. + * SPDX-License-Identifier: GPL-2.0-or-later */ +#pragma once + +#include "GPU_raster.h" + +#include +#include + +/* BUI_raster_gpu_attach(r, NULL, 1): 0 when there is no GPU device (the test skips). */ +static int test_gpu_attach(BuiRaster *r) +{ + if (!BUI_raster_gpu_attach(r, NULL, 1)) { + return 0; + } +#ifdef _WIN32 + if (BUI_raster_gpu_api(r) != BUI_gpu_api()) { + fprintf(stderr, "gpu test: asked for GPU API %d, the device runs on %d (BUI_GPU_DEBUG=1 says why)\n", + (int)BUI_gpu_api(), (int)BUI_raster_gpu_api(r)); + exit(1); + } +#endif + return 1; +} diff --git a/gpu/tests/test_gpu_effect.c b/gpu/tests/test_gpu_effect.c index 0fc62f70..bfa5ce60 100644 --- a/gpu/tests/test_gpu_effect.c +++ b/gpu/tests/test_gpu_effect.c @@ -4,6 +4,7 @@ * Skips (exit 0) where no GPU device can be created. BUI_FX_PPM=dir writes the frame. * SPDX-License-Identifier: GPL-2.0-or-later */ #include "GPU_raster.h" +#include "test_gpu_api.h" #include #include @@ -152,7 +153,7 @@ int main(void) BUI_raster_free(cpu); BuiRaster *gpu = BUI_raster_create(W, H); - if (!BUI_raster_gpu_attach(gpu, NULL, 1)) { + if (!test_gpu_attach(gpu)) { printf("gpu effect: no GPU device, skipped\n"); BUI_raster_free(gpu); return g_fail; diff --git a/gpu/tests/test_gpu_parity.c b/gpu/tests/test_gpu_parity.c index 72129734..20119454 100644 --- a/gpu/tests/test_gpu_parity.c +++ b/gpu/tests/test_gpu_parity.c @@ -4,6 +4,7 @@ * frames and the difference for inspection. * SPDX-License-Identifier: GPL-2.0-or-later */ #include "GPU_raster.h" +#include "test_gpu_api.h" #include #include @@ -290,7 +291,7 @@ static int big_image(int max_texture) #endif } int ok = 1; - if (!BUI_raster_gpu_attach(rs[1], NULL, 1)) { + if (!test_gpu_attach(rs[1])) { printf("big images: no GPU device, skipped\n"); } else { @@ -351,7 +352,7 @@ static int video_frames(void) nv12_frame(f[1], 1); BuiRaster *rs[2] = {BUI_raster_create(640, 200), BUI_raster_create(640, 200)}; int ok = 1; - if (!BUI_raster_gpu_attach(rs[1], NULL, 1)) { + if (!test_gpu_attach(rs[1])) { printf("video frames: no GPU device, skipped\n"); } else { @@ -405,7 +406,7 @@ static int italic_default(void) const float white[4] = {1, 1, 1, 1}; for (int k = 0; k < 3; k++) { /* 0: CPU italic, 1: GPU italic, 2: CPU upright */ BuiRaster *r = BUI_raster_create(IW, IH); - if (k == 1 && !BUI_raster_gpu_attach(r, NULL, 1)) { + if (k == 1 && !test_gpu_attach(r)) { printf("gpu parity: no GPU device, italic skipped\n"); BUI_raster_free(r); return 1; @@ -446,7 +447,7 @@ int main(void) for (int slug = 0; slug < 2; slug++) { set_slug(slug); BuiRaster *gpu = BUI_raster_create(W, H); - if (!BUI_raster_gpu_attach(gpu, NULL, 1)) { + if (!test_gpu_attach(gpu)) { printf("gpu parity: no GPU device, skipped\n"); BUI_raster_free(gpu); break; diff --git a/gpu/tests/test_raster_alpha.c b/gpu/tests/test_raster_alpha.c index 2e980fc1..37808af9 100644 --- a/gpu/tests/test_raster_alpha.c +++ b/gpu/tests/test_raster_alpha.c @@ -2,6 +2,7 @@ * BUI_raster_set_alpha is premultiplied 0xAARRGGBB and BUI_raster_clear makes it transparent. * SPDX-License-Identifier: GPL-2.0-or-later */ #include "GPU_raster.h" +#include "test_gpu_api.h" #include #include @@ -42,7 +43,7 @@ static int gpu_matches_cpu(void) BuiRaster *cpu = BUI_raster_create(16, 16), *gpu = BUI_raster_create(16, 16); BUI_raster_set_alpha(cpu, 1); BUI_raster_set_alpha(gpu, 1); - if (!BUI_raster_gpu_attach(gpu, NULL, 1)) { + if (!test_gpu_attach(gpu)) { printf("raster alpha: no GPU device, GPU part skipped\n"); BUI_raster_free(cpu); BUI_raster_free(gpu); diff --git a/website/src/content/docs/concepts/rendering.mdx b/website/src/content/docs/concepts/rendering.mdx index 9a3740b7..68b65b45 100644 --- a/website/src/content/docs/concepts/rendering.mdx +++ b/website/src/content/docs/concepts/rendering.mdx @@ -84,7 +84,7 @@ The cost of the software raster grows with the number of pixels, which is why ve ## The GPU renderer -The **GPU renderer** uses Direct3D 11 on Windows (`gpu_d3d11.c`) and OpenGL 3.3 on Linux (`gpu_gl.c`). It's modeled on how Blender batches its widgets (`GPU_SHADER_2D_WIDGET_BASE_INST` in `interface_widgets.cc`): +The **GPU renderer** uses Direct3D 11 on Windows (`gpu_d3d11.c`), or Direct3D 12 when an app asks for it (`gpu_d3d12.c`: `Application::gpu_api`, `BUI_GPU_API=d3d12` or `bui build --gpu d3d12`), and OpenGL 3.3 on Linux (`gpu_gl.c`). Both Direct3D backends share one core (`gpu_device.c`) and draw identical pixels; Direct3D 12 costs a little more CPU per frame (about 0.4 to 1 ms here), so Direct3D 11 stays the default. It's modeled on how Blender batches its widgets (`GPU_SHADER_2D_WIDGET_BASE_INST` in `interface_widgets.cc`): - **One shader, many instances.** The kit makes the same drawing calls as on the CPU. In GPU mode, each call records one 128-byte **instance** instead of touching pixels. A single "uber-shader" draws them all, so a frame of thousands of widgets is a handful of instanced draw calls. - **Same formulas, same pixels.** The pixel shader evaluates the software raster's coverage formulas. The `gpu_parity` test draws every primitive both ways and finds 10 of 172,800 pixels that differ by more than 3/255, on both backends. @@ -131,6 +131,7 @@ In short: the GPU halves (or better) the CPU cost per frame. In exchange, the pr | --- | --- | | `gpu=True` seems to do nothing | Run with `BUI_GPU_DEBUG=1`. It prints which step failed to stderr. | | No GPU in a Windows VM or CI | `BUI_GPU_WARP=1` creates the device on WARP, Windows' software Direct3D 11 driver. Handy for testing the GPU path. | +| A hybrid laptop renders on the integrated GPU | Windows gives Direct3D the display's adapter. `BUI_GPU_ADAPTER=high-performance` asks for the discrete GPU, as for profiling it with the vendor's tools (NVIDIA Nsight). | | Headless OpenGL on Linux picks the wrong display | `BUI_GPU_EGL=surfaceless` or `BUI_GPU_EGL=default` picks the EGL platform. | | GPU text looks heavier than you'd like, or costs too much | Try the atlas: `BUI_SLUG=0`. | diff --git a/website/src/content/docs/reference/environment-variables.mdx b/website/src/content/docs/reference/environment-variables.mdx index 2cf39d47..919d3e3d 100644 --- a/website/src/content/docs/reference/environment-variables.mdx +++ b/website/src/content/docs/reference/environment-variables.mdx @@ -44,8 +44,10 @@ set BUI_GPU=1 && python my_app.py | --- | --- | --- | --- | --- | | `BUI_GPU` | on / off | Off (or what the code asked for) | Draws native windows on the GPU: Direct3D 11 on Windows, OpenGL 3.3 on Linux. `BUI_GPU=0` forces the software raster. Overrides the app-wide defaults: `bui.set_gpu()`, `Application::gpu()` and `BUI_gpu_set_default()`. A window that asks for the GPU itself (`Tk(gpu=True)`, `WindowOptions { gpu: Some(true) }`, `BK_window_set_gpu`) still gets it. | `gpu/intern/gpu_raster.c` | | `BUI_SLUG` | on / off | On (the CMake `BUI_SLUG` option) | How the GPU draws text: `1` from glyph outlines (Slug), `0` from a per-glyph bitmap atlas. Overrides `bui.set_slug()`, `.slug()` and `BUI_gpu_set_slug()`. Read once per process. | `gpu/intern/gpu_raster.c` | -| `BUI_GPU_DEBUG` | `1` | Unset | Prints to stderr why the GPU renderer couldn't start (and, on Linux, what it runs on). Only `1` turns it on. | `gpu/intern/gpu_d3d11.c`, `gpu/intern/gpu_gl.c` | -| `BUI_GPU_WARP` | `1` | Unset | Windows: creates the Direct3D 11 device on WARP, Windows' software rasterizer, instead of the graphics card. Useful in VMs and CI. Only `1` turns it on. | `gpu/intern/gpu_d3d11.c` | +| `BUI_GPU_DEBUG` | `1`, `2` | Unset | `1`: prints to stderr why the GPU renderer couldn't start (and, on Linux, what it runs on). `2`: also turns on the Direct3D 12 debug layer, printing its warnings and errors and, at exit, any leaked objects. | `gpu/intern/gpu_device.c`, `gpu/intern/gpu_d3d12.c`, `gpu/intern/gpu_gl.c` | +| `BUI_GPU_API` | `d3d11`, `d3d12` | Unset | Windows: which Direct3D the GPU renderer uses. It wins over the app's choice in code (`Application::gpu_api`) and the one `bui build --gpu` stored in the executable; the default is `d3d11`. A device that can't start on Direct3D 12 starts on Direct3D 11. Other values are ignored (`BUI_GPU_DEBUG=1` says so). | `gpu/intern/gpu_raster.c` | +| `BUI_GPU_WARP` | `1` | Unset | Windows: creates the Direct3D device (11 or 12) on WARP, Windows' software rasterizer, instead of the graphics card. Useful in VMs and CI. Only `1` turns it on. | `gpu/intern/gpu_dx.c` | +| `BUI_GPU_ADAPTER` | `high-performance` | Unset (`default`) | Windows: creates the Direct3D device on the GPU DXGI picks for high performance, the discrete one of a hybrid laptop. Without it Windows picks the display's, often the integrated GPU (less power). Profilers such as NVIDIA Nsight only see work on their vendor's GPU. Other values are ignored (`BUI_GPU_DEBUG=1` says so). | `gpu/intern/gpu_dx.c` | | `BUI_GPU_MAX_TEXTURE` | A number of pixels, 64 or more | The device's limit | Testing: the largest texture side the GPU renderers give one image; images over it are tiled, as on devices with a small limit (the GPU parity test uses 512). | `gpu/intern/gpu_d3d11.c`, `gpu/intern/gpu_gl.c` | | `BUI_GPU_EGL` | `default`, `surfaceless` | Surfaceless first, then default | Linux: which EGL platform offscreen GPU rendering uses (tests, screenshots). | `gpu/intern/gpu_gl.c` | | `BUI_RASTER_THREADS` | A number, 1 to 8 | The processor count, capped at 8 | Windows: the most threads the software raster uses for big canvases. `1` forces one thread. Elsewhere, canvases draw on one thread. | `kit/intern/kit_frame.c` | From 034c79d3bf64b6568b20ea9aafa527306c09680c Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:25:45 +0530 Subject: [PATCH 3/5] cli packaging --- CHANGELOG.md | 1 + bindings/node/cli.js | 133 +++++++++++-- bindings/node/package.json | 1 + bindings/node/test/windows.test.js | 65 +++++++ bindings/node/windows.js | 184 ++++++++++++++++++ docs/javascript.md | 10 + .../javascript/standalone-executables.mdx | 30 +++ 7 files changed, 404 insertions(+), 20 deletions(-) create mode 100644 bindings/node/test/windows.test.js create mode 100644 bindings/node/windows.js diff --git a/CHANGELOG.md b/CHANGELOG.md index a74f51f0..530c028e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to **blenderui** (BUI). The format follows ### Added - **Windows: a Direct3D 12 renderer, opt-in.** `Application::gpu_api(GpuApi::D3d12)` (C: `BUI_gpu_set_api`), `BUI_GPU_API=d3d12` or `bui build --gpu d3d12` start the GPU renderer on Direct3D 12; Direct3D 11 stays the default, and a device that can't start on 12 starts on 11. Both backends now share one core (`gpu/intern/gpu_device.c`) and fill a table of 15 device operations; the frames they draw are byte-identical. Direct3D 12 costs about 0.4 to 1 ms more CPU per presented frame here, so it is for apps that embed BUI in Direct3D 12 or profile it with Nsight's GPU Trace. `BUI_GPU_DEBUG=2` turns on the Direct3D 12 debug layer. +- **`bui` CLI: Windows releases as MSIX, and the Direct3D to start with.** `bui build app.jsx --msix` makes an MSIX package (the installable, Store-ready form of a Win32 app) instead of a bare `.exe`; `--gpu d3d11|d3d12` sets the Direct3D the GPU renderer starts with, stored in the executable. `bui package app.exe --msix` / `--gpu` releases any BUI executable the same way, so Rust and C apps get it too. The package takes `--name`, `--version`, `--display-name`, `--description`, `--publisher`, `--icon`, `--include` and `--cert` (unsigned without one: `Add-AppxPackage -AllowUnsigned` installs it); `makeappx` comes from the Windows SDK. - **Windows: `BUI_GPU_ADAPTER=high-performance` renders on the discrete GPU.** Direct3D took the display's adapter, on a hybrid laptop the integrated GPU, where NVIDIA Nsight and other vendor profilers see nothing; this asks DXGI for the high-performance one (`EnumAdapterByGpuPreference`). The default stays the display's GPU, which uses less power. - **Android: real apps in Rust.** `blenderui::android_main!(run)` writes the entry point the NativeActivity shell calls, so the app crate has no `unsafe`; before `run` it gives the activity's JNI handles to `ndk-context` (cpal and other crates that call into Java need them) and sends stdout, stderr and panics to logcat (tag `bui`). The kit points `HOME` at the app's files folder and `XDG_CACHE_HOME` / `TMPDIR` at its cache folder on attach (`dirs::cache_dir()` worked nowhere), and `BK_android_activity()` gives the `ANativeActivity *`. `build.py` takes `--label`, `--package` and `--permission` (repeatable: `INTERNET` for an app that goes online) and links the system libraries the Rust staticlib needs (rustc's `native-static-libs`, through `cargo rustc`, so dependencies don't build again): an app that plays sound through cpal links AAudio. Characters Roboto lacks come from the phone's Noto fonts (`/system/fonts`, `/product/fonts` in the font folders). SpotiTube's Android build is the first app that uses it. - **Back on Android walks back through an app's screens.** `App::prevent_default()` in a key listener marks the key as taken (`BK_key_taken` in C, for any binding that sees raw key events): `BK_key` returns 1 and nothing else acts on it. Back is the key `Escape`, so a listener that closes a screen on it keeps the app open, and only a Back that nothing took finishes the activity. diff --git a/bindings/node/cli.js b/bindings/node/cli.js index 3be75962..e793abc5 100644 --- a/bindings/node/cli.js +++ b/bindings/node/cli.js @@ -5,16 +5,24 @@ // bui build app.jsx --bun a Bun executable (full Node APIs, ~120 MB) // bui run app.jsx [args] run on the small runtime (no executable) // bui bundle app.jsx -o main.js one script for QuickJS, no runtime (Android: build.py --js) +// bui package app.exe --msix release any BUI executable (Rust, C ...) the same way // // Options: -// -o, --out output file (default: the entry's name, .exe on Windows; -// bundle: main.js); never the entry itself +// -o, --out output file (default: the entry's name, .exe on Windows, .msix with +// --msix; bundle: main.js); never the entry itself // --bun compile with `bun build --compile` instead of QuickJS // --console keep a console window (Windows; default: none, for apps) // --dev development builds (React's, Svelte's dev mode) // --features a,b the kit features the app uses (default: package.json // "bui": {"features": [...]}, else detected in the bundle); // the smallest runtime with them is linked (features.js) +// --gpu d3d11|d3d12 Windows: the Direct3D the app's GPU renderer starts with +// (default d3d11; BUI_GPU_API overrides it when it runs) +// --msix Windows: an MSIX package (install, Store) instead of a bare .exe; +// --name, --version (1.2.3.0), --display-name, --description, +// --publisher "CN=..", --publisher-name, --icon logo.png, +// --include (repeatable), --cert app.pfx [--cert-password p] +// (default: package.json's; unsigned without --cert) // // Bundling uses Bun (https://bun.sh), which must be installed. // SPDX-License-Identifier: GPL-2.0-or-later @@ -25,6 +33,7 @@ const path = require('node:path') const { spawnSync } = require('node:child_process') const features = require('./features.js') const platform = require('./platform.js') +const windows = require('./windows.js') const MAGIC = Buffer.from('BUIAPP01') const { TAG, EXE } = platform @@ -35,18 +44,31 @@ function fail (msg) { } function parse (argv) { - const o = { cmd: argv[0], entry: null, out: null, bun: false, console: false, dev: false, features: null, rest: [] } + const o = { cmd: argv[0], entry: null, out: null, bun: false, console: false, dev: false, features: null, rest: [], + gpu: null, msix: false, pkg: { include: [] } } + // MSIX identity options: --display-name -> pkg.displayName + const pkgOpts = ['--name', '--version', '--publisher', '--publisher-name', '--display-name', '--description', + '--icon', '--cert', '--cert-password'] for (let i = 1; i < argv.length; i++) { const a = argv[i] + const value = () => { + if (i + 1 >= argv.length) fail(`${a} needs a value`) + return argv[++i] + } if (o.cmd === 'run' && o.entry !== null) o.rest.push(a) - else if (a === '-o' || a === '--out') o.out = argv[++i] + else if (a === '-o' || a === '--out') o.out = value() else if (a === '--bun') o.bun = true else if (a === '--console') o.console = true else if (a === '--dev') o.dev = true - else if (a === '--features') o.features = argv[++i].split(',').map((s) => s.trim()).filter(Boolean) + else if (a === '--features') o.features = value().split(',').map((s) => s.trim()).filter(Boolean) + else if (a === '--gpu') o.gpu = value() + else if (a === '--msix') o.msix = true + else if (a === '--include') o.pkg.include.push(value()) + else if (pkgOpts.includes(a)) o.pkg[a.slice(2).replace(/-(.)/g, (_, c) => c.toUpperCase())] = value() else if (a.startsWith('-')) fail(`unknown option ${a}`) else o.entry = a } + if (o.gpu !== null && !windows.GPU_APIS.includes(o.gpu)) fail(`--gpu takes ${windows.GPU_APIS.join(' or ')}, not "${o.gpu}"`) return o } @@ -132,26 +154,94 @@ function outPath (o, fallback) { return out } +/** What the nearest package.json above `file` says about the app (MSIX defaults). */ +function projectInfo (file) { + for (let dir = path.dirname(path.resolve(file)); ; dir = path.dirname(dir)) { + const p = path.join(dir, 'package.json') + if (fs.existsSync(p)) { + try { + const pkg = JSON.parse(fs.readFileSync(p, 'utf8')) + return { + name: pkg.name?.replace(/^@[^/]+\//, ''), + version: pkg.version?.replace(/[-+].*$/, ''), // 1.2.3-beta: the numbers + description: pkg.description + } + } catch { return {} } + } + if (path.dirname(dir) === dir) return {} + } +} + +/** A temporary folder for `f`, removed afterwards. */ +function withTemp (f) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bui-release-')) + try { + return f(dir) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +/** --gpu, then --msix, on `exe` (a file of this run's, changed in place); the package goes to `out`. */ +function release (o, exe, out) { + try { + if (o.gpu) { + const buf = fs.readFileSync(exe) + if (windows.isSigned(buf)) console.warn('bui: the executable is signed; changing its GPU API breaks the signature (sign it again)') + if (windows.patchGpuApi(buf, o.gpu) === 0) fail(`${path.basename(o.entry)} has no BUI GPU renderer to choose with --gpu`) + fs.writeFileSync(exe, buf) + } + if (o.msix) { + const info = projectInfo(o.entry) + const name = path.basename(o.entry).replace(/\.[^.]+$/, '') + const given = Object.fromEntries(Object.entries(o.pkg).filter(([, v]) => v !== undefined)) + const id = windows.msix(exe, out, { name, ...info, ...given }) + console.log(`bui: packaged ${path.relative(process.cwd(), out)} (${id.name} ${id.version}, ` + + `${id.signed ? 'signed' : 'unsigned: Add-AppxPackage -AllowUnsigned installs it'})`) + } + } catch (e) { + fail(e.message) + } +} + function build (o) { const name = path.basename(o.entry).replace(/\.[^.]+$/, '') - const out = outPath(o, `${name}${EXE}`) + const out = outPath(o, o.msix ? `${name}.msix` : `${name}${EXE}`) const t0 = Date.now() - if (o.bun) { - bundleWith({ entry: path.resolve(o.entry), out, bun: true, dev: o.dev, console: o.console || process.platform !== 'win32' }) - } else { - const js = bundle(o.entry, o.dev) - const runtime = fs.readFileSync(runtimePath(chooseRuntime(o, js))) - if (process.platform === 'win32' && !o.console) setGuiSubsystem(runtime) - const trailer = Buffer.alloc(16) - MAGIC.copy(trailer, 0) - trailer.writeBigUInt64LE(BigInt(js.length), 8) - fs.writeFileSync(out, Buffer.concat([runtime, js, trailer])) - if (process.platform !== 'win32') fs.chmodSync(out, 0o755) - } + withTemp((dir) => { + const exe = o.msix ? path.join(dir, `${name}${EXE}`) : out + if (o.bun) { + bundleWith({ entry: path.resolve(o.entry), out: exe, bun: true, dev: o.dev, console: o.console || process.platform !== 'win32' }) + } else { + const js = bundle(o.entry, o.dev) + const runtime = fs.readFileSync(runtimePath(chooseRuntime(o, js))) + if (process.platform === 'win32' && !o.console) setGuiSubsystem(runtime) + const trailer = Buffer.alloc(16) + MAGIC.copy(trailer, 0) + trailer.writeBigUInt64LE(BigInt(js.length), 8) + fs.writeFileSync(exe, Buffer.concat([runtime, js, trailer])) + if (process.platform !== 'win32') fs.chmodSync(exe, 0o755) + } + release(o, exe, out) + }) const mb = (fs.statSync(out).size / 1048576).toFixed(1) console.log(`bui: built ${path.relative(process.cwd(), out)} (${mb} MB, ${o.bun ? 'Bun' : 'QuickJS'}) in ${Date.now() - t0} ms`) } +/** `bui package app.exe`: --gpu / --msix on an executable built any other way (Rust, C ...). */ +function packageExe (o) { + if (!o.gpu && !o.msix) fail('package needs --msix, --gpu or both') + const name = path.basename(o.entry).replace(/\.[^.]+$/, '') + const out = outPath(o, o.msix ? `${name}.msix` : `${name}-${o.gpu}${EXE}`) + withTemp((dir) => { + const exe = path.join(dir, path.basename(o.entry)) // the input is never changed + fs.copyFileSync(o.entry, exe) + release(o, exe, out) + if (!o.msix) fs.copyFileSync(exe, out) + }) + if (!o.msix) console.log(`bui: wrote ${path.relative(process.cwd(), out)} (starts on ${o.gpu})`) +} + function run (o) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bui-run-')) const file = path.join(dir, `${path.basename(o.entry).replace(/\.[^.]+$/, '')}.js`) @@ -162,11 +252,14 @@ function run (o) { } const o = parse(process.argv.slice(2)) -if (!['build', 'run', 'bundle'].includes(o.cmd) || !o.entry) { - console.log(fs.readFileSync(__filename, 'utf8').split('\n').slice(1, 19).map((l) => l.replace(/^\/\/ ?/, '')).join('\n')) +if (!['build', 'run', 'bundle', 'package'].includes(o.cmd) || !o.entry) { + const lines = fs.readFileSync(__filename, 'utf8').split('\n') + const end = lines.findIndex((l) => l.startsWith('// Bundling uses Bun')) + 1 // the header comment + console.log(lines.slice(1, end).map((l) => l.replace(/^\/\/ ?/, '')).join('\n')) process.exit(o.cmd ? 1 : 0) } if (!fs.existsSync(o.entry)) fail(`no such file: ${o.entry}`) if (o.cmd === 'bundle') fs.writeFileSync(outPath(o, 'main.js'), bundle(o.entry, o.dev)) else if (o.cmd === 'build') build(o) +else if (o.cmd === 'package') packageExe(o) else run(o) diff --git a/bindings/node/package.json b/bindings/node/package.json index a0a73f87..05ab4fc6 100644 --- a/bindings/node/package.json +++ b/bindings/node/package.json @@ -57,6 +57,7 @@ "features.js", "features.json", "platform.js", + "windows.js", "README.md", "LICENSE", "THIRD_PARTY_NOTICES.md" diff --git a/bindings/node/test/windows.test.js b/bindings/node/test/windows.test.js new file mode 100644 index 00000000..a6f92008 --- /dev/null +++ b/bindings/node/test/windows.test.js @@ -0,0 +1,65 @@ +'use strict' +// `bui build` / `bui package` release options for Windows (windows.js): the GPU API marker and MSIX. +const test = require('node:test') +const assert = require('node:assert') +const zlib = require('node:zlib') +const { MARKER, MARKER_FIELD, patchGpuApi, isSigned, identity, manifest, solidPng } = require('../windows.js') + +/** An "executable" with the kit's marker (and a look-alike that isn't one) inside. */ +function fakeExe (api = 'd3d11') { + const field = Buffer.alloc(MARKER_FIELD) + field.write(api, 'latin1') + return Buffer.concat([Buffer.from('MZ....'), MARKER, Buffer.from('zzz'), Buffer.from('..'), MARKER, field, Buffer.from('tail')]) +} + +test('--gpu rewrites the marker the kit compiles in, and nothing else', () => { + const buf = fakeExe() + const before = Buffer.from(buf) + assert.strictEqual(patchGpuApi(buf, 'd3d12'), 1) + const at = buf.lastIndexOf(MARKER) + MARKER.length + assert.strictEqual(buf.subarray(at, at + MARKER_FIELD).toString('latin1').replace(/\0+$/, ''), 'd3d12') + assert.strictEqual(buf.length, before.length) + assert.ok(buf.subarray(0, buf.indexOf(MARKER) + MARKER.length + 3).equals(before.subarray(0, before.indexOf(MARKER) + MARKER.length + 3)), + 'a look-alike whose field is no API name stays') + assert.strictEqual(patchGpuApi(buf, 'd3d11'), 1, 'and back') + assert.ok(buf.equals(before)) +}) + +test('--gpu takes only the APIs the kit has; a file without the marker has none to set', () => { + assert.throws(() => patchGpuApi(fakeExe(), 'vulkan'), /d3d11 or d3d12/) + assert.strictEqual(patchGpuApi(Buffer.from('no renderer here'), 'd3d12'), 0) +}) + +test('a file that is no signed PE image is not signed', () => { + assert.strictEqual(isSigned(Buffer.from('MZ')), false) + assert.strictEqual(isSigned(fakeExe()), false) +}) + +test('the MSIX identity is validated where it comes in', () => { + assert.deepStrictEqual(identity({ name: 'my app!', version: '1.2' }), + { name: 'my-app-', version: '1.2.0.0', publisher: 'CN=BUI App, OID.2.25.311729368913984317654407730594956997722=1' }) + assert.throws(() => identity({ name: 'ab' }), /3 to 50/) + assert.throws(() => identity({ name: 'app', version: '1.2.3.4.5' }), /four numbers/) + assert.throws(() => identity({ name: 'app', version: '1.x' }), /four numbers/) + assert.throws(() => identity({ name: 'app', version: '70000' }), /0-65535/) + assert.throws(() => identity({ name: 'app', publisher: 'Me' }), /CN=/) +}) + +test('the manifest escapes what the app is called and runs the executable full trust', () => { + const id = identity({ name: 'app' }) + const m = manifest(id, { name: 'app', displayName: 'Tom & "Jerry" <3' }, 'app.exe') + assert.match(m, /Tom & "Jerry" <3<\/DisplayName>/) + assert.match(m, /Executable="app.exe" EntryPoint="Windows.FullTrustApplication"/) + assert.match(m, //) +}) + +test('the default logos are valid PNGs of the size asked for', () => { + const png = solidPng(44, [1, 2, 3]) + assert.ok(png.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) + assert.strictEqual(png.readUInt32BE(16), 44) + assert.strictEqual(png.readUInt32BE(20), 44) + const idat = png.indexOf('IDAT') + const raw = zlib.inflateSync(png.subarray(idat + 4, idat + 4 + png.readUInt32BE(idat - 4))) + assert.strictEqual(raw.length, 44 * (1 + 44 * 3)) + assert.deepStrictEqual([...raw.subarray(1, 4)], [1, 2, 3]) +}) diff --git a/bindings/node/windows.js b/bindings/node/windows.js new file mode 100644 index 00000000..3c3f888e --- /dev/null +++ b/bindings/node/windows.js @@ -0,0 +1,184 @@ +// Windows release options for a built BUI executable: the GPU API it starts with, and an MSIX +// package (the installable, Store-ready form of a Win32 app). +// +// The GPU API is a marker the kit compiles in (gpu/intern: "BUIGPUAPI=" and the API name, padded +// with NULs to a fixed width): patching it changes the app's default; BUI_GPU_API still overrides +// it at run time, and an app that picks one in code keeps its pick. +// SPDX-License-Identifier: GPL-2.0-or-later +'use strict' +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') +const zlib = require('node:zlib') +const { spawnSync } = require('node:child_process') + +const GPU_APIS = ['d3d11', 'd3d12'] +const MARKER = Buffer.from('BUIGPUAPI=') +/** Bytes after the marker the kit reserves for the API name, NUL-padded: BUI_GPU_API_MARKER_LEN (32, + * gpu/include/GPU_raster.h) less the marker's 10. */ +const MARKER_FIELD = 22 + +/** Set the GPU API `api` is built to start with in executable `buf` (patched in place). Returns how + * many markers it changed; 0 means the executable has no BUI GPU renderer to choose. */ +function patchGpuApi (buf, api) { + if (!GPU_APIS.includes(api)) throw new Error(`--gpu takes ${GPU_APIS.join(' or ')}, not "${api}"`) + let n = 0 + for (let at = buf.indexOf(MARKER); at >= 0; at = buf.indexOf(MARKER, at + MARKER.length)) { + const field = buf.subarray(at + MARKER.length, at + MARKER.length + MARKER_FIELD) + const name = field.toString('latin1').replace(/\0+$/, '') + if (!GPU_APIS.includes(name)) continue // the bytes happened to match: not the kit's marker + field.fill(0) + field.write(api, 'latin1') + n++ + } + return n +} + +/** Whether PE image `buf` carries an Authenticode signature (patching it would break it). */ +function isSigned (buf) { + if (buf.length < 0x40 || buf.readUInt16LE(0) !== 0x5a4d) return false + const pe = buf.readUInt32LE(0x3c) + if (buf.readUInt32LE(pe) !== 0x4550) return false + const opt = pe + 24 + const dirs = opt + (buf.readUInt16LE(opt) === 0x20b ? 112 : 96) // PE32+ : PE32 + return buf.readUInt32LE(dirs + 4 * 8 + 4) !== 0 // the certificate table's size +} + +// -- MSIX ----------------------------------------------------------------------------------------- + +/** The package identity from `opts`, validated as the manifest schema requires. */ +function identity (opts) { + const name = opts.name.replace(/[^A-Za-z0-9.-]/g, '-').replace(/^[.-]+/, '').slice(0, 50) + if (name.length < 3) throw new Error(`--name "${opts.name}": an MSIX name needs 3 to 50 of A-Z a-z 0-9 . -`) + const v = String(opts.version ?? '1.0.0').split('.').map((p) => Number(p)) + while (v.length < 4) v.push(0) + if (v.length > 4 || v.some((p) => !Number.isInteger(p) || p < 0 || p > 65535)) { + throw new Error(`--version "${opts.version}": four numbers 0-65535 (1.2.3.0)`) + } + // without a certificate: the publisher Windows installs unsigned packages from + // (Add-AppxPackage -AllowUnsigned); with one it must be the certificate's subject + const publisher = opts.publisher ?? 'CN=BUI App, OID.2.25.311729368913984317654407730594956997722=1' + if (!/^CN=/.test(publisher)) throw new Error(`--publisher "${publisher}": a distinguished name (CN=...)`) + return { name, version: v.join('.'), publisher } +} + +const xml = (s) => String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') + +function manifest (id, opts, exe) { + const arch = { x64: 'x64', arm64: 'arm64', ia32: 'x86' }[process.arch] ?? 'x64' + const display = xml(opts.displayName ?? opts.name) + return ` + + + + ${display} + ${xml(opts.publisherName ?? id.publisher.replace(/^CN=([^,]*).*$/, '$1'))} + Assets\\StoreLogo.png + + + + + + + + + + + + + + + + +` +} + +/** A `size` x `size` PNG of one colour (the logos an app without an icon gets). */ +function solidPng (size, rgb) { + const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 + return c >>> 0 + }) + const crc = (b) => { + let c = 0xffffffff + for (const x of b) c = crcTable[(c ^ x) & 0xff] ^ (c >>> 8) + return (c ^ 0xffffffff) >>> 0 + } + const chunk = (type, data) => { + const t = Buffer.concat([Buffer.from(type, 'latin1'), data]) + const len = Buffer.alloc(4) + len.writeUInt32BE(data.length) + const sum = Buffer.alloc(4) + sum.writeUInt32BE(crc(t)) + return Buffer.concat([len, t, sum]) + } + const ihdr = Buffer.alloc(13) + ihdr.writeUInt32BE(size, 0) + ihdr.writeUInt32BE(size, 4) + ihdr[8] = 8 // bit depth + ihdr[9] = 2 // RGB + const row = Buffer.alloc(1 + size * 3) + for (let x = 0; x < size; x++) row.set(rgb, 1 + x * 3) + const raw = Buffer.concat(Array.from({ length: size }, () => row)) + return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]) +} + +/** A Windows SDK tool (makeappx, signtool): the newest SDK's, for this machine's architecture. */ +function sdkTool (exe) { + const root = path.join(process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)', 'Windows Kits', '10', 'bin') + const arch = process.arch === 'arm64' ? 'arm64' : 'x64' + const versions = fs.existsSync(root) ? fs.readdirSync(root).filter((d) => /^10\./.test(d)) : [] + versions.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).reverse() + for (const v of versions) { + const p = path.join(root, v, arch, exe) + if (fs.existsSync(p)) return p + } + throw new Error(`${exe} not found: install the Windows SDK (its "MSIX Packaging Tools")`) +} + +function run (tool, args) { + const r = spawnSync(tool, args, { encoding: 'utf8' }) + if (r.status !== 0) throw new Error(`${path.basename(tool)} failed:\n${(r.stdout ?? '') + (r.stderr ?? '')}`) +} + +/** Package executable `exe` (and `opts.include`: more files or folders next to it) as `out`, an + * MSIX. `opts`: name, version, publisher, publisherName, displayName, description, icon (a PNG + * for every logo), cert / certPassword (a .pfx to sign with; its subject is the publisher). */ +function msix (exe, out, opts) { + if (process.platform !== 'win32') throw new Error('--msix packages Windows apps: run it on Windows') + const id = identity(opts) + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bui-msix-')) + try { + const exeName = path.basename(exe) + fs.copyFileSync(exe, path.join(dir, exeName)) + for (const extra of opts.include ?? []) { + fs.cpSync(extra, path.join(dir, path.basename(extra)), { recursive: true }) + } + const assets = path.join(dir, 'Assets') + fs.mkdirSync(assets) + for (const [file, size] of [['StoreLogo.png', 50], ['Square150x150Logo.png', 150], ['Square44x44Logo.png', 44]]) { + if (opts.icon) fs.copyFileSync(opts.icon, path.join(assets, file)) + else fs.writeFileSync(path.join(assets, file), solidPng(size, [0x47, 0x72, 0xb3])) + } + fs.writeFileSync(path.join(dir, 'AppxManifest.xml'), manifest(id, opts, exeName)) + fs.rmSync(out, { force: true }) + run(sdkTool('makeappx.exe'), ['pack', '/o', '/d', dir, '/p', out]) + if (opts.cert) { + const sign = ['sign', '/fd', 'SHA256', '/f', opts.cert] + if (opts.certPassword) sign.push('/p', opts.certPassword) + run(sdkTool('signtool.exe'), [...sign, out]) + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + return { ...id, signed: Boolean(opts.cert) } +} + +module.exports = { GPU_APIS, MARKER, MARKER_FIELD, patchGpuApi, isSigned, identity, manifest, solidPng, msix } diff --git a/docs/javascript.md b/docs/javascript.md index 602d7811..37b5e715 100644 --- a/docs/javascript.md +++ b/docs/javascript.md @@ -380,6 +380,16 @@ Options: - `--console`: keep a console window for logs. By default, Windows builds open no console. - `--dev`: development builds (React's, Svelte's dev mode). +- `--gpu d3d11|d3d12`: Windows, the Direct3D the GPU renderer starts with + (default `d3d11`; `BUI_GPU_API` overrides it at run time). +- `--msix`: Windows, an MSIX package (installable, Store-ready) instead of a + bare `.exe`, with `--name`, `--version`, `--display-name`, `--description`, + `--publisher`, `--publisher-name`, `--icon`, `--include` and `--cert` / + `--cert-password` (unsigned without a certificate: + `Add-AppxPackage -AllowUnsigned` installs it). + +`npx bui package app.exe --msix` (or `--gpu d3d12`) releases any BUI +executable the same way: a Rust or C app's too. The input is never changed. Framework packages add their bundler plugins: with `@blender-ui/svelte` installed, `.svelte` files bundle as they are. diff --git a/website/src/content/docs/javascript/standalone-executables.mdx b/website/src/content/docs/javascript/standalone-executables.mdx index 49cc7654..c0347d9b 100644 --- a/website/src/content/docs/javascript/standalone-executables.mdx +++ b/website/src/content/docs/javascript/standalone-executables.mdx @@ -53,9 +53,39 @@ npx bui run app.jsx # run on the QuickJS runtime, no executable | `--bun` | Compile with `bun build --compile` instead of QuickJS. | | `--console` | Keep a console window for logs. By default, Windows builds open none, as an app should. | | `--dev` | Use React's development build. The default is the production build. | +| `--gpu d3d11` or `--gpu d3d12` | Windows: the Direct3D the GPU renderer starts with. The default is `d3d11`. | +| `--msix` | Windows: build an MSIX package instead of a bare `.exe`. See [Releasing on Windows](#releasing-on-windows). | `bui run` is handy while you work: it bundles your app and runs it on the same QuickJS runtime a build would use, so you see exactly what your users will. +## Releasing on Windows + +A Windows app ships as a plain Win32 `.exe`, or as an **MSIX** package: the installable form of the same app that the Microsoft Store takes, with a clean install and uninstall. (MSIX is what replaced UWP packaging; the app inside stays a normal Win32 program.) + +```sh +npx bui build app.jsx --msix # app.msix +npx bui build app.jsx --msix --gpu d3d12 # starts on Direct3D 12 +npx bui package target/release/app.exe --msix # any BUI executable: Rust, C ... +npx bui package app.exe --gpu d3d12 -o app-dx12.exe +``` + +`bui package` releases an executable built any other way, so Rust and C apps use the same options. It never changes the input file. + +| Option | What it does | +| --- | --- | +| `--name` | The package name: 3 to 50 of `A-Z a-z 0-9 . -`. Default: `package.json`'s `name`, else the file's. | +| `--version` | Four numbers, `1.2.3.0` (fewer are padded). Default: `package.json`'s `version`. | +| `--display-name`, `--description` | What the Start menu and the Store show. | +| `--publisher "CN=..."` | The publisher: with `--cert`, the certificate's subject. | +| `--publisher-name` | The publisher as people read it. | +| `--icon logo.png` | The app's logo. Without it, a plain square. | +| `--include ` | More files next to the executable (fonts, images). Repeat it for more. | +| `--cert app.pfx`, `--cert-password` | Sign the package. Without them it is unsigned. | + +**Unsigned packages** install on a developer's machine with `Add-AppxPackage -AllowUnsigned app.msix` in PowerShell; their publisher is the one Windows reserves for that. To ship, sign with your certificate (the Store signs packages it distributes itself). Packaging needs the Windows SDK's `makeappx` (and `signtool` to sign). + +**`--gpu`** sets which Direct3D the app's GPU renderer starts with. It is stored in the executable, so it works on any BUI app. At run time `BUI_GPU_API=d3d11` or `d3d12` still overrides it, and an app that chooses in code keeps its choice. Changing it on a signed executable breaks the signature, so sign afterwards. + ## QuickJS or Bun? **The default build** runs your code on QuickJS, on BUI's UI thread, the way a browser runs page scripts. Your code and both packages run unchanged. From 537431686b507e7d9bd8dde83cd0c8bfdb619ca5 Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+ppmpreetham@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:26:14 +0530 Subject: [PATCH 4/5] a11y windows --- CHANGELOG.md | 1 + a11y/Cargo.lock | 216 +++++ a11y/Cargo.toml | 51 ++ a11y/include/bui_a11y.h | 58 ++ a11y/src/adapter.rs | 261 ++++++ a11y/src/ffi.rs | 148 ++++ a11y/src/lib.rs | 27 + a11y/src/node.rs | 434 ++++++++++ a11y/src/tree.rs | 350 ++++++++ bindings/rust/Cargo.lock | 158 ++++ bindings/rust/blenderui-sys/Cargo.toml | 7 +- bindings/rust/blenderui-sys/build.rs | 4 +- bindings/rust/blenderui-sys/src/lib.rs | 21 + bindings/rust/blenderui/Cargo.toml | 3 +- bindings/rust/blenderui/examples/a11y.rs | 80 ++ .../rust/blenderui/examples/bench_frames.rs | 57 +- bindings/rust/blenderui/src/a11y.rs | 693 ++++++++++++++++ bindings/rust/blenderui/src/layout.rs | 2 +- bindings/rust/blenderui/src/lib.rs | 2 + bindings/rust/blenderui/src/screen.rs | 6 + bindings/rust/blenderui/src/window.rs | 123 ++- bindings/rust/blenderui/tests/suite/a11y.rs | 218 +++++ bindings/rust/blenderui/tests/suite/main.rs | 1 + bindings/rust/scripts/vendor_c.py | 4 +- features.json | 1 + kit/CMakeLists.txt | 37 + kit/include/BUI_kit.h | 187 ++++- kit/intern/a11y/a11y.c | 783 ++++++++++++++++++ kit/intern/a11y/a11y.h | 31 + kit/intern/a11y/a11y_off.c | 92 ++ kit/intern/image/draw.c | 2 +- kit/intern/image/video.c | 2 +- kit/intern/kit_color.c | 10 +- kit/intern/kit_core.c | 37 +- kit/intern/kit_filebrowser.c | 2 +- kit/intern/kit_frame.c | 2 +- kit/intern/kit_intern.h | 17 + kit/intern/kit_menus.c | 57 +- kit/intern/kit_nodes.c | 4 +- kit/intern/kit_regions.c | 4 +- kit/intern/kit_textarea.c | 2 +- kit/intern/kit_views.c | 39 +- kit/intern/kit_widgets.c | 116 ++- kit/intern/kit_window_win32.c | 44 + kit/intern/screen/screen_node.c | 2 +- website/src/content/docs/project/faq.mdx | 2 +- .../src/content/docs/project/limitations.mdx | 5 +- website/src/content/docs/project/roadmap.mdx | 2 +- 48 files changed, 4315 insertions(+), 90 deletions(-) create mode 100644 a11y/Cargo.lock create mode 100644 a11y/Cargo.toml create mode 100644 a11y/include/bui_a11y.h create mode 100644 a11y/src/adapter.rs create mode 100644 a11y/src/ffi.rs create mode 100644 a11y/src/lib.rs create mode 100644 a11y/src/node.rs create mode 100644 a11y/src/tree.rs create mode 100644 bindings/rust/blenderui/examples/a11y.rs create mode 100644 bindings/rust/blenderui/src/a11y.rs create mode 100644 bindings/rust/blenderui/tests/suite/a11y.rs create mode 100644 kit/intern/a11y/a11y.c create mode 100644 kit/intern/a11y/a11y.h create mode 100644 kit/intern/a11y/a11y_off.c diff --git a/CHANGELOG.md b/CHANGELOG.md index 530c028e..3138f4ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to **blenderui** (BUI). The format follows ## [Unreleased] ### Added +- **Accessibility: screen readers see BUI apps on Windows, through [AccessKit](https://accesskit.dev).** The kit keeps one accessibility tree per window: its widgets add themselves (role, name, value, states, bounds; menus, tabs, enum, list and tree rows as items), and the Rust HTML engine adds the page under its canvas, with roles and names mapped as browsers map HTML and ARIA (HTML-AAM, accname: `aria-labelledby`, `aria-label`, `