Crafter.Graphics/AGENTS.consumer.md

170 lines
55 KiB
Markdown
Raw Normal View History

## Crafter.Graphics
The Crafter engine's graphics library: a C++ module, `import Crafter.Graphics;`, that opens a window, drives a Vulkan 1.3+ device through `VK_EXT_descriptor_heap` (bindless: no descriptor-set layouts, push data through `vkCmdPushDataEXT`), traces rays through `VK_KHR_ray_tracing_pipeline`, draws UI from compute shaders, and reads keyboards, mice, touch, gamepads and the clipboard. A `wasm32-*` build of the same surface runs in the browser on WebGPU with a software ray tracer. Everything is in `namespace Crafter`. The vectors and matrices are Crafter.Math's (`import Crafter.Math;`) and the compressed asset formats Crafter.Asset's (`import Crafter.Asset;`); both ship notes of their own. Window callbacks are `Crafter::Event<T>` from Crafter.Event (`import Crafter.Event;`): `EventListener<void> sub(&window.onMouseMove, [&] { ... });` subscribes, and the listener's destructor unsubscribes. Source, examples and issues: https://forgejo.catcrafts.net/Catcrafts/Crafter.Graphics (LGPL-3.0-only; the examples under `examples/` are MIT and meant to be copied). These notes are its `AGENTS.consumer.md`: a fix to them goes there, not into the copy crafter-build writes.
### Building against it
fix(win32): link the Vulkan loader without a Vulkan SDK, link libuuid, and check that a Win32 executable links Build - The MinGW toolchains ship no import library for vulkan-1.dll, so without a Vulkan SDK's every Win32 executable stopped at "unable to find library -lvulkan-1". project.cpp now makes one with the llvm-dlltool beside the toolchain's llvm-ar, from Vulkan-Loader's loader/vulkan-1.def. That is the loader's own list of what vulkan-1.dll exports, fetched with GitFetch, unpinned like Vulkan-Headers, so the API the library compiles against and the exports it links against move together. The import library the Wine runs used, made from the calls the library happened to make, went stale with the next new call (234fcce added vkEnumerateInstanceExtensionProperties). The loader's list does not, and a call it does not export fails at link time instead of when the exe starts. - It is made into build/vulkan-1-<target>/ when a stamp beside it, holding the command and the .def it was made from, no longer matches; a fetch or a copy says nothing through the .def's mtime. It goes into the link by its absolute path rather than through -L, so it shadows no consumer's Vulkan SDK library. A failed fetch or llvm-dlltool run is a Progress::Diagnostic warning, and the link falls back to the library a previous load made, or to -lvulkan-1. - -luuid joins the Win32 link flags: the gamepad code compares against IID_IUnknown and IID_IAgileObject, and StartSync's Gamepad::Tick pulls it into every executable (#184). - project.cpp uses ShellQuote, exported from crafter-build 3.0.0, which is now the minimum. Tests - Win32Link: an executable that uses the library as an application does (Device::Initialize, a Window, StartSync) links. Without Wine it runs as --runner=cmd:true, which builds it and runs nothing; under Wine it also opens a window and closes it. It fails to link without -luuid (IID_IUnknown, IID_IAgileObject) and without the import library ("unable to find library -lvulkan-1"). Under the Flatpak it needs tests/Win32Link/libc-single-threaded.c, which stands in for Catcrafts/Crafter.Build#43 and goes with it. - With the native crafter-build on the host, which has Wine and finds the host's mingw-w64 itself, PointerWin32, TextWin32 and Win32Link now build and pass under Wine with nothing added. Docs - AGENTS.md: the minimum crafter-build, the Vulkan-Loader fetch and what project.cpp runs, the Win32Link check in the commands and the done-list, and a one-line Wine recipe in place of the hand-built import library, shim and project.cpp edit. AGENTS.consumer.md: the minimum, how the import library is made, and the __libc_single_threaded workaround under the Flatpak. README: the minimum, the Win32 build command, and that it needs no Vulkan SDK. Closes #184. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:27:09 +01:00
- The library's `project.cpp` needs crafter-build 3.0.0 or later; older ones fail to compile it, for every target.
- The target picks the backend, in the library and in your code. Any `wasm32-*` target builds the DOM + WebGPU library; everything else builds Vulkan, with Wayland on Linux (there is no X11 backend) or Win32 on `x86_64-w64-mingw32`. The library defines `CRAFTER_GRAPHICS_WINDOW_WAYLAND`, `_WIN32` or `_DOM` for its own units only, so a wasm consumer sets `cfg.target = "wasm32-wasip1"`, `cfg.defines.push_back({"CRAFTER_GRAPHICS_WINDOW_DOM", ""})`, `cfg.compileFlags.push_back("-msimd128")` (the dependency PCMs were compiled with it) and `EnableWasiBrowserRuntime(cfg)`, as `examples/HelloUI/project.cpp` does. Portable code `#ifdef CRAFTER_GRAPHICS_WINDOW_DOM`s at the few sites where the backends differ; the library has no shared signatures that are no-ops on one side.
- The library's link flags (the Vulkan loader, `wayland-client`, `xkbcommon`, `udev`, or the Win32 libraries) come with the dependency. On `x86_64-w64-mingw32` that includes an import library for `vulkan-1.dll`, so linking for Win32 needs no Vulkan SDK. The library makes it at configure time with the `llvm-dlltool` beside crafter-build's `llvm-ar`, from the loader's own export list (Vulkan-Loader's `loader/vulkan-1.def`, fetched unpinned). Under the Flatpak, linking for Win32 needs crafter-build 5.0.0 or later: an older one puts the host's glibc headers on the MinGW include path, and the link fails on `__libc_single_threaded` (Crafter.Build #43). Its shaders (`ui-*.comp.spv` and `ui-*.comp.sets.spv`) and, for wasm, `dom-env.js` and `dom-webgpu.js` are copied into your executable's bin directory, as are your `cfg.shaders` outputs (`<name>.spv` from `<name>.glsl`) and `cfg.files`. Paths are resolved against the working directory at runtime, so run from the bin directory, as `crafter-build -r` does.
- Your own shaders: `cfg.shaders.emplace_back(fs::path("raygen.glsl"), std::string("main"), ShaderType::RayGen)`, with `Compute`, `RayGen`, `Miss`, `ClosestHit`, `AnyHit`, `Intersect` and `Callable`. A compute shader for the UI heap is registered twice, see "Custom compute shaders". WGSL for the DOM build ships through `cfg.files` and is loaded at runtime.
- Project args the library understands, passed through your `args`: `--local` (sibling checkouts of Crafter.Event, Crafter.Math and Crafter.Asset instead of clones), `--timing` (meant to add frame timing counters; the build does not compile with it at the moment, issue #178), `--no-webgpu` (wasm: a DOM-only page without the WebGPU bridge, which otherwise requests a GPU adapter on every load and replaces the page body with an error where WebGPU is missing).
- Needs at runtime: Vulkan 1.3 (1.4 is used where the GPU has it), a presentable surface, and the features the library's own shaders use. `VK_EXT_descriptor_heap` and ray tracing are optional groups, see "Device and features". Mesa's llvmpipe runs the compute/UI path, and recent Mesa advertises the heap.
### A program, and what the loop does
```cpp
Device::Initialize({.vulkan10 = {.shaderInt16 = VK_TRUE}}); // the features your shaders use; on the DOM build Initialize() takes none
Window window(1280, 720, "Title"); // `static` on the DOM build
VkCommandBuffer init = window.StartInit(); // a one-time setup command buffer
DescriptorHeapVulkan heap;
heap.Initialize(/*images*/ 16, /*buffers*/ 16, /*samplers*/ 4);
window.descriptorHeap = &heap; // bound at the start of every frame
// create buffers, images, meshes, pipelines and passes, recording into `init` ...
window.passes.push_back(&pass); // RenderPass*: a UIRenderer, an RTPass, your own
window.FinishInit(); // submits `init` and waits for it
window.Render(); // one frame
window.StartUpdate(); // frames on the compositor's clock from here
window.StartSync(); // the event loop; never returns
```
- Include `vulkan/vulkan.h` yourself, before the imports (the examples wrap it in `#ifndef CRAFTER_GRAPHICS_WINDOW_DOM`): the library includes it only in its own global module fragments, and neither Vulkan's types nor its macros (`VK_TRUE`, the `VK_*` flags) cross an `import`. On the DOM build `Device::Initialize()` takes no arguments and `DeviceFeatures` does not exist, which is why the dual-target examples keep a separate DOM `main`.
- `StartSync` runs the platform loop until `open` is false (`onClose` fires first). Each pass of the loop dispatches platform events into the `Window` events, runs `Gamepad::Tick()` and `onBeforeUpdate`, and runs `Update()` for a window that is due. On Wayland a window on the compositor's clock updates from its frame callback during that event dispatch, before the pass's `onBeforeUpdate`, and the loop wakes for every event, so `onBeforeUpdate` fires several times per frame; on Win32 and in the browser `onBeforeUpdate` precedes the same pass's `Update`. `updateInterval`, set before `StartUpdate`, makes a window update every so often whether visible or not; pair it with `SetPresentMode(PresentMode::Mailbox)` so a present never waits for the display. `AddPollFd(fd, callback)` (Wayland) wakes the loop for a socket or an eventfd.
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
- `Update()` computes `mouseDelta` and calls `Render()`, which waits for the fence of its frame slot (three frames in flight, `Window::numFrames`; the slot is `window.currentFrame`), acquires a swapchain image (`window.currentImage`; the swapchain has as many images as its present mode needs, not necessarily three), writes it into this window's swapchain slots of the heap, reclaims deferred deletions, begins `drawCmdBuffers[currentFrame]`, binds the heap (or the descriptor set), fires `onUpdate(FrameTime)`, records every pass in `passes` in order with a barrier on the swapchain image between them, transitions the image to present, submits and presents. Per-frame GPU work of your own (a TLAS rebuild, a physics dispatch) is recorded from `onUpdate` into `window.drawCmdBuffers[window.currentFrame]`; the heaps are bound by then and the passes come after. A `Resize` or `SetPresentMode` from a listener of the frame (an input action ticked in `onUpdate`, say) takes effect after its present. `onResize` fires after a swapchain rebuild (a new size or present mode); the swapchain slots follow by themselves, and anything else that holds the old images or is sized after the window is made again there.
fix(wayland): round a configured size's pixels half away from zero, and work both sizes out exactly from the scale's 120ths A size the compositor configured became the buffers' size as ceil(size * scale), in float. The protocol, as bundled in lib/fractional-scale-v1.h, has the buffer's size as the surface's times the scale, and says that "For toplevel surfaces, the size is rounded halfway away from zero": wherever the product's fraction is below a half, rounding up gave a pixel more than that. 89111e0 left this as the rest of #201, and the comment on #165 asks for it. And the sum was done in float, with the scale as a float, which a scale that is no whole number of eighths is not exactly: a product that is a whole number of pixels could come out just above it, and rounding up then went a pixel past it, as 50 at 1.2 came to 61. The other way, the surface's size for a window the application sized, ceil(pixels / scale), had the same trouble: 171 pixels at 2.85 came to 61, where they are 60. Window: ScaledPixels rounds half away from zero, and both it and SurfaceLength work in 64-bit integers from the 120ths the compositor sends: MatchSizesToScale from those of the scale the window draws at, which a new member, drawnScale_, keeps beside scale, as they are not preferredScale while a new scale waits, and the tests of whether a scale gives the window new pixels from preferredScale. SurfaceLength still rounds up, so that the surface of a window the application sized is no smaller than its pixels at the scale. ScaledPixels never gives less than one pixel: below a scale of a half a length of one rounds to none, where rounding up gave one, and a swapchain cannot be made 0 wide or high. Nor more than the largest 32-bit value, which a configured length can pass at a scale above 2 (2^30 at 4 comes to 2^32), where the cast to 32 bits would wrap it, to none in that case; and SurfaceLength stops at the largest int32, which a length worked out from 32-bit pixels can pass. The configure listener's test for a configure at the size the window has uses the same sum, so a configured size the window took is found to be the one it has, and so do the tests, in TakeDeferredSize after a present and in MatchSizesToScale, of whether a size or a scale comes to new pixels; and the listener tells that no new scale waits from the 120ths, preferredScale against drawnScale_, where 61f2698 compared the two scales as floats. So 392x796 at 2.85, the size in #201's phone trace, takes 1117x2269 pixels where it took 1118x2269. A window of 320x240 pixels at 1.75, shown at 183x138, takes 320x242 for a configure of that size, where it took 321x242. Docs: the consumer notes say how a configured size's pixels are rounded, and that the surface of a window the application sized is rounded up; the guide's gotchas, that both are worked out in integers from the 120ths; both, that the pixels are never fewer than one nor more than the largest 32-bit value, and that the surface's length never passes the largest int32. The gotcha and the interface's comment on logicalWidth give, as a reason not to work the surface's size back from the pixels, that a configured size worked back from them lands above itself wherever its product with the scale is not whole. That held while both roundings went up; now it lands above where that product has a fraction of a half or more, short of the 32-bit limits the two sums stop at, and both say so. Tests: ConfigureResize takes the new numbers in its cases of #201's trace and of the window at 1.75, and adds the protocol's own example (100x50 at 1.5 is 150x75), halves that go up (853x101 at 1.5 is 1280x152), fractions below a half that go down (101x853 at 1.25 is 126x1066, which rounding up made 127x1067), and whole numbers the sum in float came out above (50x25 at 1.2 is 60x30, which came to 61x31), each acknowledged in the listener when it is configured again; a configure of 1x300 at 0.4, whose width rounds to no pixel, taken as 1x120; a configure of 2^30x300 at 4, whose width is the largest 32-bit value, and pixels of that value at a half, whose surface is the largest int32 wide; and a window of 342x171 pixels at 2.85, whose surface is 120x60, which came to 121x61. And it works configured sizes into pixels and back with a window's own MatchSizesToScale: 853x101 at 1.5 comes back as 854x102, and 392x796 at 2.85 as 392x797. ResizeViewport works the pixels and the surface's size out as the window now does, and its comments say which way each is rounded.
2026-11-27 10:07:37 +01:00
- On Wayland the compositor resizes a window with a configure (a maximize, a tile, a drag of its border, a phone's on-screen keyboard coming or going), and the window answers it with a frame, not in the configure's listener, which only keeps the size. The next `Render()` starts by making the swapchain again at it and firing `onResize`, before the frame's `onUpdate`, with the queue idle and no frame being recorded, as `Resize` fires it; and the frame it then presents brings, with the present's commit, the first buffer of the new size together with the surface's new size and the configure's acknowledgement. (A size configured while a frame is being recorded is taken at the end of that `Render()`, after its present, and the frame after it brings it, unless it comes with a new scale to the pixels the window has: then both wait for the next `Render()`, see below.) So `onResize` for such a resize comes from inside `Render()`: for a consumer that calls `Update()` itself, a `try` around it covers the rebuild's Vulkan calls, while a window under `StartUpdate` draws where its frames always do: from its frame callback, inside the event dispatch, when it is on the compositor's clock, and from `StartSync`'s loop, after the dispatch, when it is on its own (`updateInterval`). Until that frame's present the window keeps its old size on screen, and then changes size with the buffer drawn for the new one, where it used to change at the configure and show the last frame scaled until the next. The exception is a present that fails: what the frame sent ahead of it stays pending for the surface's next commit. A window that updates from `StartUpdate` needs nothing: its next `Update()`, from the frame callback or from its clock, is that frame. On the compositor's clock that counts on the frame callbacks going on while a configure waits for its answer, as KWin's do. A window that draws on demand (it calls `Update()` itself when something changed) must ask for a frame when `onFrameOwed` fires, as it does from `onResize`: `onFrameOwed` (Wayland only, `Event<void>`) fires from the configure, after `onToplevelState`, whenever the configure leaves a frame owed, and from a scale the compositor asks for by itself (below), and nothing has been rebuilt by then. The listener marks the window as wanting a frame and lets its loop draw it; it does not call `Update()` itself, because the event fires wherever the events are dispatched, and that may be inside a frame being recorded (a listener of that frame made a `Window` or called `Clipboard::GetText`), which `onResize` never is. Without that frame the configure is never answered and the window never takes the new size. A window that has stopped updating (`StopUpdate`) is in the same position. `Resize` and `SetPresentMode` called outside a frame still rebuild at once and fire `onResize` from the call; the surface takes the new size with the next frame there too. A rebuild that throws is tried again by the next `Render()`. A Wayland window has two sizes: `width` and `height`, the pixels of its buffers, and `logicalWidth` and `logicalHeight`, the surface's size in surface-local units, which is what a configure gives and what the compositor lays the window out by. `scale` is the scale the window draws at, its buffers' pixels per surface-local unit (1 where the compositor has no `wp_fractional_scale_v1` or no `wp_viewporter`), which the pointer's and the touches' positions are turned into pixels with and the caret `SetTextInput` gives is turned back into surface-local units with; `preferredScale` is the scale the compositor asked for last, in 120ths as `wp_fractional_scale_v1` sends it (120 is 1). The two sizes are worked out from one another only when a size or a scale is taken at a frame boundary of `Render()` and when a swapchain is made, where `preferredScale` becomes `scale` as below, so while a frame is being recorded `scale` is the one the two sizes were worked out with, and from a new scale to the boundary that takes it only `preferredScale` has it. A size the compositor configured is the surface's size
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
- A `RenderPass` is `Record(cmd, frameIdx, window)` plus `SwapchainStage()`, which must return the stage that touches the swapchain image (`COMPUTE_SHADER`, `RAY_TRACING_SHADER` or `TRANSFER`): the frame's barriers take their stage and access masks from it. `frameIdx` is the frame slot, `window.currentFrame`, not the image: the frame's image is `window.images[window.currentImage]`. The image stays in `VK_IMAGE_LAYOUT_GENERAL` through the whole pass list, with `STORAGE | TRANSFER_SRC` usage and `TRANSFER_DST` where the surface allows it (`window.swapchainUsage`). Nothing clears it: draw a background quad, or clear from a transfer pass where `TRANSFER_DST` is there.
fix(wayland): take a new preferred scale at a frame boundary, and convert input with the scale the window draws at xdg_surface_handle_preferred_scale set Window::scale and did nothing else (#165). The buffers' size and the surface's follow the scale only where the window works one out from the other, which it did when it made a swapchain and when a frame took a configured size. So a scale that changed by itself, with no configure (the issue's case is a window moved to an output of another scale), reached them only at the next of those, and until then the window drew at the old scale. The pointer's and the touches' positions are turned into pixels with Window::scale, and the text input's caret back into surface-local units with it, so those were converted with the new scale while the frames were still drawn at the old one. The issue suggests making the swapchain again in the listener. That predates 89111e0, which moved the configure's rebuild out of its listener into Render() for #199 and #200; the scale takes the same way. Window: the listener keeps the scale in a new member, preferredScale, as wp_fractional_scale_v1 sends it, in 120ths, and Window::scale is the scale the window draws at. MatchSizesToScale, where the window works out the size it was not given from the one it was, sets it from preferredScale where it takes a new scale, and nothing else in the library sets it. TakeDeferredSize takes a preferredScale that is not the scale the window draws at, at a frame boundary of Render(), as it takes a configured size, and with one where one waits. A window the compositor sized keeps its surface's size and takes the pixels for it at the new scale, so Render() makes the swapchain again there and onResize fires where those pixels differ. One the application sized keeps its pixels and makes no swapchain, and its surface takes the size they come to at the new scale, which the next frame sends with its buffer (SendFrameSurfaceState). Before the start of the next frame the scale is taken only with a swapchain made where it gives the window new pixels: a window the compositor sized whose surface comes to other pixels at it, as after a present or with the swapchain a SetPresentMode makes outside a frame. Anywhere else it would change only the conversions and the size the surface is to take, which goes out with the next frame, and until that frame's commit the compositor maps the surface, and the pointer and the touches on it, by the destination it has: a click in between would be converted for a frame not drawn yet, landing where the new scale puts it on the one drawn at the old scale, and the onResize of a swapchain made for another reason at the pixels the window has would not tell the application of the scale. So a scale that leaves the pixels as they are waits for the start of the next frame (for a window the application sized, whose pixels are its own, and one the compositor sized that it leaves at its pixels), also where a present mode, a rebuild that waited or a Resize makes a swapchain before then, and so does a configured size that comes to the pixels the window has with it (an output's scale changed under a window that fills it). TakeDeferredSize and RebuildIfDeferred are told which of the two boundaries they run at (FrameBoundary), and MatchSizesToScale whether it takes the scale whatever it does to the pixels (takeScale), as at a frame's start and in the constructor. The listener sends no request and makes no Vulkan call, so the window goes on drawing at the old scale, and converting with it, until then; a scale that a listener of a frame dispatched is taken at the boundary after its present where it gives the window new pixels, and at the start of the next frame otherwise. From the window's first swapchain on, the listener fires onFrameOwed where the scale is not the one the window draws at, so that a window that draws on demand learns that a frame is owed, as it does from a configure; for a window the application sized no onResize comes. Before the first swapchain the listener only keeps the scale, which the constructor takes before it makes the swapchain, as it did. A scale of 0, with which no size can be worked out, is not taken. Where MatchSizesToScale changes the scale, it takes what the window holds in pixels of the scale before to the new one: currentMousePos, lastMousePos and mouseDelta, and the touch slots of the window's fingers. The compositor gives those in surface-local units and sends nothing for a pointer or a finger that rests, so a pointer resting over the window would otherwise stand at the old scale's pixels in the frames drawn at the new one until it moved, and the next delta would be the change of grid. The pointer's position as the compositor gave it is kept beside, in surface-local units, in a new member, surfaceMousePos, which no scale moves. And it sends the caret SetTextInput was given again, converted with the new scale, as the window does when the keyboard focus comes back: for a window the application sized, the surface changes size around pixels that stay, and the rectangle the input method holds would otherwise stay in the old units. The configure listener's test for a configure at the size the window has compares the buffers with the pixels for that size at preferredScale, the scale the frame takes with the size, as it compared them at Window::scale while the listener set that. While a new scale waits it finds no configure at the size the window has: one for the size the surface has waits for the frame that takes the scale and takes its size with it, so that the window is not made one the compositor sized while it draws at the scale before, at pixels that are not that size's at the scale it draws at. Input: Map took its delta for MouseDeltaBind from currentMousePos and a last position of its own, which the window's conversion does not reach, so a pointer that rests would read the change of grid as a delta at the Map's next Tick, which a camera bound to MouseDeltaBind turns by. On Wayland it takes it from surfaceMousePos, as the surface-local motion since its last Tick in the window's pixels of now: none for a pointer that rests, whatever scales the window took in between, where a last position taken along to each new scale would come back with a float residue through two of them. A position the application writes into currentMousePos itself does not reach it there. Device: the pointer's and the touches' handlers keep the position the compositor gave in surfaceMousePos (the first finger's for the pointer it stands in for), and touch_down, touch_motion and an enter's move work it into the pixels they store with the scale in force at the store. They store after listeners, of onTouchDown, onTouchMove and onMouseEnter, that may take a new scale (a SetPresentMode outside a frame for a window the compositor sized, the Render() of a frame callback one of them dispatched), and a position worked out before those listeners would be in the pixels of the scale before. The conversions read Window::scale, which is now the scale of the frames drawn since the boundary that took it. Docs: the README, the consumer notes and the guide's gotchas say what scale and preferredScale are and when a scale is taken; the first two said that scale could be newer than the sizes (#165). The README, the consumer notes and the comment on SetTextInput say what goes to the new scale with it, and that the caret is sent again; the consumer notes name surfaceMousePos, the Map's delta from it, and that a position the application writes into currentMousePos does not reach the Map. The bug-prover lens section names preferredScale as what changes in any dispatch, and the scale among what waits for a frame boundary, and that before the next frame's start it is taken only where it gives the window new pixels; the consumer notes, that a size configured during a frame waits with a new scale where the two come to the pixels the window has. Tests: ConfigureResize names the scale in 120ths, as the compositor does, and drives the scale's listener on a window whose surfaces are proxies. The listener sends nothing, leaves the scale and both sizes as they are, and fires onFrameOwed. Until a frame boundary takes the scale, a pointer motion to the surface's middle is at the middle of the buffers drawn at the scale before, and so is a finger that goes down there on the window the application sized; a caret given in the pixels of the window the compositor sized goes to a text input proxy converted with that scale. The next boundary takes it: a window the compositor sized keeps 400x300 and goes from 800x600 to 600x450 pixels at 1.5, which makes the swapchain, and its surface is sent nothing; one the application sized keeps its 640x480 pixels and makes no swapchain, and its surface goes from 320x240 to 640x480 at 1, sent with the frame. After it the motion, the finger's move and the caret are converted with the new scale. And before any new motion or call, the boundary has taken what the window held to the new scale: the pointer of the window the compositor sized is at the middle of the new buffers, the one the first finger stands in for on the other window is where its surface-local place comes to, a second finger that went down before the boundary lifts after it where its surface-local place comes to, and each boundary sends the caret again, converted, with no SetTextInput. An Input::Map attached to the window and ticked across a boundary that takes 1.5 reads no delta for a pointer that rests, and a motion of 10 units after it as 15 pixels; ticked across two boundaries between two Ticks on a window the compositor sized, 1.75 taken by a swapchain made outside a frame at the pixels it gives the window and 1 again by a frame's start, with the pointer resting at surface 100.25, it reads no delta and fires no event. On a window the compositor sized, a listener of onTouchDown, of onTouchMove and of onMouseEnter that takes a scale that waits has the click the finger stands in for, the finger's move and the move after the enter in the pixels of that scale. A scale that comes back before a frame owes nothing; one that comes while a frame is being recorded leaves that frame at the scale it began with, and the window the compositor sized takes it at the boundary after the present, with its new pixels, where the one the application sized takes it at the next frame's start: the boundary after the present takes nothing, a motion after it is still at the pixels of the frame on screen, and the caret is sent again only at the next frame's start (the fixture steps the boundary after the present, End, apart from the next frame's start, Begin); a configure that comes with it to the pixels the window has waits for that start as well, which takes the two together, the frame bringing the surface its size and the acknowledgement, and so does a scale that leaves a small window the compositor sized at its pixels; a configure without a size while a scale waits is acknowledged in the listener, and one for the size the surface has waits for the frame that takes the scale, also where its pixels at that scale are the window's (101x101 pixels at 2, a surface of 51x51, a scale of 237/120); before the first swapchain the listener only keeps the scale, which MatchSizesToScale takes, and a scale of 0 is not taken. In the cases there were, the check that nothing is owed counts a scale that waits as well, the frame whose scale changes while it is recorded is followed to the boundary that takes it, a swapchain made between frames is checked to leave no scale waiting for a window the compositor sized, and for one the application sized to take none, a motion until the next frame's start landing at the pixels of the frame on screen, also where the swapchain is made after a present that found it out of date, with a configure that comes with the scale to the window's pixels waiting too, and the case of a scale and then a configure counts onFrameOwed for both. ResizeViewport drives the scale against the compositor, where it has the fractional scale and the viewporter: on its window as the application sized it, and maximized where the compositor configures a size for that, it calls the listener with a scale the window does not draw at and then with the compositor's own. Each time it checks that the listener rebuilds nothing and fires onFrameOwed, that the next Render() takes the scale, with no swapchain and no onResize for the application's size and with a new swapchain and one onResize from inside Render() for the maximized one, and that a pointer motion to the surface's middle is at the buffers' middle, to within the rounding of one size from the other, before that Render() and after it, and that the pointer, resting across that Render(), is where its surface-local place comes to at the new scale. The log's checks hold each of those commits to its buffer at the scales the marks name.
2026-11-27 10:07:37 +01:00
- `window.width` and `height` are physical pixels, as is `currentMousePos`. `CaptureNextFrame(path)` saves the next frame as a PNG. `SetTitle`, `SetAppId`, `SetCursorImage`, `SetDefaultCursor`; `SetTextInput(active, x, y, w, h, purpose, hints)` tells the compositor's input method a text field has focus, which opens an on-screen keyboard on a phone. `purpose` is what the field holds (`TextInputPurpose::Normal`, `Alpha`, `Digits`, `Number`, `Phone`, `Url`, `Email`, `Name`, `Password`, `Pin`, `Date`, `Time`, `Datetime`, `Terminal`), by which the keyboard picks its layout, and `hints` how it treats what is typed (`kTextInputHintCompletion`, `Spellcheck`, `AutoCapitalization`, `Lowercase`, `Uppercase`, `Titlecase`, `HiddenText`, `SensitiveData`, `Latin`, `Multiline`, or-ed together). Without `hints` a field gets `TextInputDefaultHints(purpose)`: completion, spellcheck and capitals for `Normal`, hidden and not learnt for `Password` and `Pin`, none for the rest; `kTextInputHintNone` asks for none. Name the purpose of every field that is not prose. Call it again when the caret moves, with the same purpose and hints; on Wayland the window sends the caret it holds again, converted, when its scale changes, and a caret that the new scale moves in pixels is one that moved. A call that changes either while a field has focus tells the input method the focus moved to another field (it enables anew), which ends the composition under way without an `onPreedit`, as `SetTextInput(false)` does, so commit or drop your composing text first. A move to another field of the same purpose and hints looks to the window like a caret that moved and sends no enable: call `SetTextInput(false)` before the new field's `SetTextInput(true, ...)`. The input method's changes come in batches (text-input-v3's `done`), each fired as `onTextInputDelete`, `onTextInput` and `onPreedit` in that order, and the batches in the order they arrived: one that arrives while a listener of another is running (the listener made a `Window` or called `Clipboard::GetText`, which dispatch the events) waits until that one is through. Only these wait: a key, pointer or touch event the same dispatch brings fires at once, before a batch that waits.
fix(font-atlas): give glyphs that find no room a cell when the next frame begins, evicting the least recently drawn The atlas packed glyphs onto shelves and never gave a place back (#55). Once its 1024x1024 image was full, EnsureAndGet returned nullptr for each new glyph before caching anything, so every new string holding one rasterised it again, and ShapeText dropped it together with its advance: the rest of the line closed up over the gap, and stayed that way. FontAtlas - A glyph is measured, not rasterised, until it gets a cell. One that finds no free room keeps its advance and box and draws blank for a frame. EnsureAndGet always returns the glyph, now a reference; Glyph::Resident() says whether it has a cell, Glyph::handle which one (slot and generation). - Evictions wait for the next frame: its first EnsureAndGet, Touch or Update places the glyphs that waited, once every glyph the frame before drew has been marked. Evicting while a frame is still asking for glyphs took ones it drew further down, which then took others in turn: a page switched back to could rasterise most of itself again rather than what it was missing, and on the DOM backend an over-full view could do so every frame. - A glyph keeps its cell for framesInFlight + 1 frames after it was drawn. The frame loop waits frame u's fence at the start of frame u + framesInFlight, but Device::frameCounter reads that from the end of the frame before, and input callbacks and onBeforeUpdate run in between. - FontAtlas::Packer places glyphs. Until the rows run out it fills shelves exactly as before. Then a glyph takes the same columns of one shelf at least as tall, or of several in a row as tall together, the free rows below the last shelf counting as one more: free texels, and, when the frame begins, glyphs nothing in flight draws, the least recently drawn first. A glyph spanning shelves lets in one taller than every shelf, and a few glyphs drawn every frame pin only their columns. Merging whole shelves instead, tried first, left a random workload without room for a glyph while a median 43% of the atlas was in flight; spanning, at 65%. - A box that found no room in a frame is remembered, with every box at least as big, as a small set per mode, until the frame ends or (without eviction) something is evicted: a saturated atlas no longer searches every shelf for each of its missing glyphs. - An evicted glyph is forgotten, and its texels are zeroed and uploaded with the glyph that takes its place: a neighbour's filtering at its edge must read padding or zero, not a stale glyph. - Touch(handles) marks every glyph whose handle still holds its cell, and says whether all did. InvalidateFont(font) forgets the font's glyphs and those waiting for a cell, whose Font* the next frame would read. The glyph index is looked up at rasterisation, so a Font replaced in place never gets one past its glyphs. GlyphsRasterized() counts, for tests. UIRenderer - A shaped run keeps a handle per glyph it draws. A hit touches them all, so the atlas keeps what is drawn every frame, and shapes the run again when one was evicted or one had no room. A glyph without room draws blank but advances the pen. - InvalidateFont clears the atlas's glyphs of the font too, as its comment and AGENTS.md always said it did. - Record calls the atlas's Update before onBuild, every frame, so the waiting glyphs are placed and uploaded first. Dispatch uploads the atlas before any kernel, a Tier 1 one sampling FontAtlasImageSlot() included: a glyph placed earlier in onBuild can sit in a cell another glyph had. DispatchText and DispatchFused no longer do it themselves. Device, Window (DOM) - Device::frameCounter and Device::framesInFlight exist on the DOM backend too, the counter bumped at the end of Window::Render, with one frame in flight: a frame's writeTexture lands before that frame's submit but after every earlier one. HelloUI - One set of item buffers and slots per frame in flight, by frameIdx. A frame still on the GPU read the items the next frame's onBuild was rewriting; with cells changing hands, those can name cells it drew other glyphs in. Tests - FontAtlasPacker: the packer with made-up boxes and no device: the fill order, least recently drawn first, framesInFlight + 1 frames held, nothing without evict, wide glyphs, tall glyphs spanning shelves and the free rows, Touch past a stale handle, stale handles, dirty spans, and the invariants over a random workload placed the way the atlas places. - FontAtlasEviction: fills the atlas through ShapeText frame by frame. The line that no longer fits keeps its advance and its glyphs' places; its missing glyphs aren't rasterised while nothing can go; when only line 0 is cold, only its glyphs give way; a frame's own misses evict nothing in it; a frame later the line and twenty more are whole, pixel for pixel, line 0 losing a larger share than the glyphs drawn after it; a stale cached run is shaped again; no stale texel is left; InvalidateFont reaches the atlas. Against master, with its two calls to the new API stubbed out, an earlier version failed ten checks. - UIDispatchAtlasFlush: a custom ui.Dispatch after ShapeText leaves the atlas uploaded. Needs a compositor. - ShapeTextCache: a hit rasterises nothing; after InvalidateFont the re-shaped run draws the same, from new cells. Docs - README and AGENTS.consumer.md: the atlas's eviction, the frame a glyph waits, shaping text every frame into per-frame item buffers, InvalidateFont, EnsureAndGet's signature and Lookup's lifetime, and that the atlas, like the deletion queue, assumes one rendering window and evicts nothing without one. - AGENTS.md: FontAtlas::Packer among the pure-logic helpers, eviction without a Window, and InvalidateFont. Breaking: FontAtlas::EnsureAndGet returns const Glyph& and never fails; check Glyph::Resident() before drawing from its UVs. FontAtlas::Touch is no longer noexcept. A GlyphItem is good for the frame it was shaped for, once the atlas has filled up, and item buffers must be per frame. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 09:10:42 +01:00
- Several windows can exist (on Wayland `Device::windows` lists them; the other backends keep no list), and may share a heap, each writing only its own swapchain slots, but they share one frame clock: one rendering window is the assumption behind the deletion queue, the staging rings and the font atlas's evictions. Without a `Window`, nothing advances `Device::frameCounter`: a program that draws text without one steps it itself after each frame's work, or its full atlas never frees a cell and new glyphs stay blank.
fix(window): a Window constructor that throws leaves nothing of the window behind The native constructor registered the window before the steps that can throw: on Wayland it put the window in Device::windows and gave its xdg_surface, its xdg_toplevel and its fractional scale the window as listener data, and on Win32 it made the HWND, whose WM_NCCREATE puts the window in GWLP_USERDATA, and showed it. When a later step threw (a Vulkan error, a surface that offers no storage-writable format), the window had not been constructed, so ~Window did not run: all of that kept pointing at it after the exception, and the Vulkan surface, once made, leaked. #169 has what an application that catches the error and carries on then reads and writes. Window: the constructor delegates to the default constructor, which makes nothing. The body of a delegating constructor runs once its target has returned, and an exception that leaves it invokes the object's destructor ([except.ctor]). So ~Window, the window's one teardown, now also releases what a constructor that threw had made, before the exception reaches the caller. It was already written for members that were never made, which are null or empty and release nothing. That does what the guard the issue suggests would, by the language's own rule: ~Window runs unless construction completes, with nothing of it factored out or repeated in the constructor, and no function-try-block is needed, whose handler may not touch the members. ~Window now runs after a Vulkan command has failed, and the specification leaves such a command's outputs without a defined value ("Error Codes", in its fundamentals: undefined contents, poison ones since 1.4.369), so the Vulkan surface, the swapchain, its image views, the fences and the acquire semaphores are made into a local and go into their members once made. The command buffers still go into theirs directly: an allocation that fails sets every entry to null. The render-finished semaphores went through a local already; their vector now has room for all of them before the first is made, as a push_back that grew it and threw would have left the semaphore just made in no member. CreateSwapchain serves the rebuilds as well, where a vkCreateSwapchainKHR that fails now leaves the member as it was. Tests: WindowConstructorThrow (new, Wayland) makes a window beside another and fails its swapchain's capabilities query, through a function of its own in Device::vkGetPhysicalDeviceSurfaceCapabilities2KHR with Device::surfaceMaintenance1Supported set. It checks that the constructor throws that error; that Device::windows then holds the other window alone; that the failed window's Vulkan surface (the test defines vkDestroySurfaceKHR, which the library calls by name, and passes each call on to the loader) and each of its Wayland objects (read off a WAYLAND_DEBUG log, between the failure and the catch) were destroyed before the exception reached the test; that the compositor raised no protocol error; and that a window made after it renders and closes. The checks of the failed window come before the test dispatches the connection's events again, which without the fix can bring an enter event that walks Device::windows with the freed window in it. WindowConstructorThrowWin32 (new) does the same on Win32 for the HWND and the Vulkan surface, and makes a window after it; it needs Wine, as PointerWin32 does. Under Wine 11.20 it passes. Without the fix both fail: WindowConstructorThrow its checks of Device::windows, of the Vulkan surface and of each Wayland object, and WindowConstructorThrowWin32 those of the HWND and the Vulkan surface. Docs: the README, the constructors' comment in the interface and the consumer notes say that a constructor that throws leaves nothing of the window behind; AGENTS.template.md lists the two tests.
2026-11-26 09:50:23 +01:00
- On Wayland and Win32 a `Window` constructor that throws (a Vulkan error, or a surface that offers no format the swapchain can be written through as a storage image) leaves nothing of the window behind (#169): the destructor has run for what it had made by the time the exception reaches you, so on Wayland the window is not in `Device::windows` and its Wayland objects are destroyed, on Win32 its HWND is, and on both so is its Vulkan surface. The error can be caught and the program go on.
### Device and features
- `Device::Initialize(required = {}, optional = {})` creates the instance, weighs every GPU and creates the device. `DeviceFeatures` holds the five core feature structs, `vulkan10` to `vulkan14`; only their `VkBool32`s are read, so `{.vulkan12 = {.shaderFloat16 = VK_TRUE}}` is a complete argument. The library enables what its own shaders use and nothing more: a `uint16_t` spec constant needs `.vulkan10.shaderInt16`, fp16 arithmetic `.vulkan12.shaderFloat16`, 16-bit storage `.vulkan11.storageBuffer16BitAccess`, scalar layout `.vulkan12.scalarBlockLayout`. A GPU lacking a required feature is skipped; when none is left the call throws naming each GPU's gaps, and may be called again asking for less. Optional features are enabled where the GPU has them; `Device::enabledFeatures` says which, `supportedFeatures` what the GPU has, `apiVersion` the version in use (`vulkan14` features need a 1.4 GPU; `maintenance5` is always on). `CRAFTER_GRAPHICS_DEVICE=<n>` picks GPU `n`.
- `VulkanShader` checks every module's SPIR-V capabilities against what was enabled and throws naming the file and the field to pass (`vulkan10.shaderInt16`), or saying the GPU lacks it. Most drivers accept such a module silently, so this is the error you get here instead of a wrong frame on another machine.
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
- Optional groups, decided once at `Initialize`: `Device::descriptorHeapSupported` (`VK_EXT_descriptor_heap`), `rayTracingSupported` (needs the heap too), `memoryDecompressionSupported` (`VK_EXT_memory_decompression`: `.cmesh` and `.ctex` decompress on the GPU; otherwise the library decodes them on the CPU), `deviceFaultSupported`, `swapchainMaintenance1Supported` (`VK_KHR_swapchain_maintenance1`, with the instance's `surface_maintenance1`, `surfaceMaintenance1Supported`: a swapchain names its present mode and gets that mode's own image count; otherwise the stricter of the mode's and the surface's). The RT entry points throw through `Device::RequireRayTracing` without ray tracing; the compute/UI path runs everywhere.
- `Device::device`, `queue`, `commandPool`, `physDevice`, `instance`, `memoryProperties`, `deviceProperties`, `rayTracingProperties` and `descriptorHeapProperties` are public statics for raw Vulkan. `Device::GetMemoryType(typeBits, required, preferred = 0)` and `PreferDirectDeviceWrite(bytes)` are the allocation helpers.
- `Device::pipelineCache` is shared by every pipeline and written to `Device::pipelineCachePath` (`pipeline_cache.bin` in the working directory) at exit. Set the path before `Initialize`, and gitignore the file.
### Lifetimes
Frames are pipelined three deep and nothing waits for the GPU at steady state, so:
- Every library object that owns a Vulkan handle (`VulkanBuffer`, `Mesh`, `TlasWithBuffer`, `VulkanShader`, `ComputeShader`, `PipelineRTVulkan`, and `ImageVulkan`'s staging buffer) is move-only and releases the handle through `Device::EnqueueDeletion`; the render loop frees it `Device::framesInFlight` frames later. Destroying one mid-frame is safe, and so is destroying it from another thread. `VulkanBuffer::Clear()` frees at once and is only for a GPU known to be idle; `DeferredClear()` is the queued form. A program with no `Window` reclaims nothing on its own: call `Device::DrainDeletions()` after `vkQueueWaitIdle(Device::queue)`.
- Static owners (a `static Mesh`, a `static VulkanBuffer`) are fine: their destructors run after the driver has unloaded, and the queue allows for that by never being destroyed itself. `RenderingElement3D::tlases` is leaked for the same reason.
- `Window` is neither movable nor copyable, and its destructor waits for the device, so a window can be closed and another opened.
- `ImageVulkan` has no destructor: call `Destroy()` once the GPU is done with it. `FontAtlas` waits for the queue and destroys its own image.
- Heap slots (`ImageSlot`, `BufferSlot`, `SamplerSlot`) are RAII handles that return the slot on destruction, and a returned slot is handed out again at once. Free a slot only when no frame in flight reads it (after a `vkQueueWaitIdle`, or at a scene switch), and before its heap goes. In descriptor-set mode a slot write destroys the previous view immediately: same rule.
fix(font-atlas): give glyphs that find no room a cell when the next frame begins, evicting the least recently drawn The atlas packed glyphs onto shelves and never gave a place back (#55). Once its 1024x1024 image was full, EnsureAndGet returned nullptr for each new glyph before caching anything, so every new string holding one rasterised it again, and ShapeText dropped it together with its advance: the rest of the line closed up over the gap, and stayed that way. FontAtlas - A glyph is measured, not rasterised, until it gets a cell. One that finds no free room keeps its advance and box and draws blank for a frame. EnsureAndGet always returns the glyph, now a reference; Glyph::Resident() says whether it has a cell, Glyph::handle which one (slot and generation). - Evictions wait for the next frame: its first EnsureAndGet, Touch or Update places the glyphs that waited, once every glyph the frame before drew has been marked. Evicting while a frame is still asking for glyphs took ones it drew further down, which then took others in turn: a page switched back to could rasterise most of itself again rather than what it was missing, and on the DOM backend an over-full view could do so every frame. - A glyph keeps its cell for framesInFlight + 1 frames after it was drawn. The frame loop waits frame u's fence at the start of frame u + framesInFlight, but Device::frameCounter reads that from the end of the frame before, and input callbacks and onBeforeUpdate run in between. - FontAtlas::Packer places glyphs. Until the rows run out it fills shelves exactly as before. Then a glyph takes the same columns of one shelf at least as tall, or of several in a row as tall together, the free rows below the last shelf counting as one more: free texels, and, when the frame begins, glyphs nothing in flight draws, the least recently drawn first. A glyph spanning shelves lets in one taller than every shelf, and a few glyphs drawn every frame pin only their columns. Merging whole shelves instead, tried first, left a random workload without room for a glyph while a median 43% of the atlas was in flight; spanning, at 65%. - A box that found no room in a frame is remembered, with every box at least as big, as a small set per mode, until the frame ends or (without eviction) something is evicted: a saturated atlas no longer searches every shelf for each of its missing glyphs. - An evicted glyph is forgotten, and its texels are zeroed and uploaded with the glyph that takes its place: a neighbour's filtering at its edge must read padding or zero, not a stale glyph. - Touch(handles) marks every glyph whose handle still holds its cell, and says whether all did. InvalidateFont(font) forgets the font's glyphs and those waiting for a cell, whose Font* the next frame would read. The glyph index is looked up at rasterisation, so a Font replaced in place never gets one past its glyphs. GlyphsRasterized() counts, for tests. UIRenderer - A shaped run keeps a handle per glyph it draws. A hit touches them all, so the atlas keeps what is drawn every frame, and shapes the run again when one was evicted or one had no room. A glyph without room draws blank but advances the pen. - InvalidateFont clears the atlas's glyphs of the font too, as its comment and AGENTS.md always said it did. - Record calls the atlas's Update before onBuild, every frame, so the waiting glyphs are placed and uploaded first. Dispatch uploads the atlas before any kernel, a Tier 1 one sampling FontAtlasImageSlot() included: a glyph placed earlier in onBuild can sit in a cell another glyph had. DispatchText and DispatchFused no longer do it themselves. Device, Window (DOM) - Device::frameCounter and Device::framesInFlight exist on the DOM backend too, the counter bumped at the end of Window::Render, with one frame in flight: a frame's writeTexture lands before that frame's submit but after every earlier one. HelloUI - One set of item buffers and slots per frame in flight, by frameIdx. A frame still on the GPU read the items the next frame's onBuild was rewriting; with cells changing hands, those can name cells it drew other glyphs in. Tests - FontAtlasPacker: the packer with made-up boxes and no device: the fill order, least recently drawn first, framesInFlight + 1 frames held, nothing without evict, wide glyphs, tall glyphs spanning shelves and the free rows, Touch past a stale handle, stale handles, dirty spans, and the invariants over a random workload placed the way the atlas places. - FontAtlasEviction: fills the atlas through ShapeText frame by frame. The line that no longer fits keeps its advance and its glyphs' places; its missing glyphs aren't rasterised while nothing can go; when only line 0 is cold, only its glyphs give way; a frame's own misses evict nothing in it; a frame later the line and twenty more are whole, pixel for pixel, line 0 losing a larger share than the glyphs drawn after it; a stale cached run is shaped again; no stale texel is left; InvalidateFont reaches the atlas. Against master, with its two calls to the new API stubbed out, an earlier version failed ten checks. - UIDispatchAtlasFlush: a custom ui.Dispatch after ShapeText leaves the atlas uploaded. Needs a compositor. - ShapeTextCache: a hit rasterises nothing; after InvalidateFont the re-shaped run draws the same, from new cells. Docs - README and AGENTS.consumer.md: the atlas's eviction, the frame a glyph waits, shaping text every frame into per-frame item buffers, InvalidateFont, EnsureAndGet's signature and Lookup's lifetime, and that the atlas, like the deletion queue, assumes one rendering window and evicts nothing without one. - AGENTS.md: FontAtlas::Packer among the pure-logic helpers, eviction without a Window, and InvalidateFont. Breaking: FontAtlas::EnsureAndGet returns const Glyph& and never fails; check Glyph::Resident() before drawing from its UVs. FontAtlas::Touch is no longer noexcept. A GlyphItem is good for the frame it was shaped for, once the atlas has filled up, and item buffers must be per frame. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 09:10:42 +01:00
- `RenderingElement3D::elements` holds raw pointers: `Add`/`Remove` elements whose storage does not move (reserve the vector, or make them `static`). `UIRenderer::ShapeText` and `FontAtlas` cache by `Font*`: call `ui.InvalidateFont(font)`, which clears both, before destroying or replacing a `Font` (the atlas keeps the `Font*` of a glyph waiting for a cell until the next frame).
### The bindless heap
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
`DescriptorHeapVulkan::Initialize(images, buffers, samplers)` sizes one resource heap and one sampler heap per frame in flight (`resourceHeap[Window::numFrames]`, `samplerHeap[...]`, mapped `VulkanBuffer`s) and the slot allocators. `AllocateImageSlots(n)`, `AllocateBufferSlots(n)` and `AllocateSamplerSlots(n)` return `{firstElement, count}` ranges (contiguous; freed runs are reused), `Free*Slots` returns them, and running out throws naming the pool and the counts. `Initialize` throws too when its buffer slots would need shader-visible indices past 16 bits.
- **Buffer slot indices are relative.** `AllocateBufferSlots` indexes the heap's buffer region, which starts after the image region, while a GLSL `descriptor_heap` SSBO array indexes buffer descriptors from heap byte 0. The shader-visible index is `heap.bufferStartElement + raw`. The RAII `BufferSlot` converts to exactly that (its `operator std::uint16_t()`), `UIRenderer::RegisterBuffer` returns one, and raw code passes `heap.bufferStartElement` as a spec constant: the RT examples declare `layout(constant_id = 0) const uint16_t bufferStart = 0us;` and index `topLevelAS[bufferStart]`, which is why they ask for `shaderInt16`. Image slots index the heap as they are, in image-descriptor units; samplers live in their own heap. A wrong buffer index reads zeros, which looks like every field of every item being zero. In descriptor-set mode `bufferStartElement` is 0, so code that goes through the conversion is right in both.
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
- Writing a descriptor by hand: `Device::vkWriteResourceDescriptorsEXT` into `heap.resourceHeap[f].value + heap.ImageByteOffset(imageRange.firstElement)` or `heap.BufferByteOffset(bufferRange.firstElement)`, `Device::descriptorHeapProperties.imageDescriptorSize` or `bufferDescriptorSize` bytes long, for each frame `f`, then `heap.resourceHeap[f].FlushDevice()`. `BufferByteOffset` takes the raw index `AllocateBufferSlots` returned and adds the region start itself; handing it a `BufferSlot`, which converts to the absolute index, adds the start twice and puts the descriptor in the wrong place. `ImageByteOffset` takes an image slot as it is. Per-frame resources (`tlases[f]`) are written into frame `f`'s heap; a shared resource into every frame's. The swapchain image is neither, since frames and images pair up differently from frame to frame: list its image slot once with `heap.AddSwapchainSlot(slot, window)`, and the window writes the image each frame draws into there, a storage image in `GENERAL`, in both binding models and across resizes (a slot listed during a frame is written for that frame). `examples/VulkanTriangle/main.cpp` is the pattern. The `UIRenderer::Register*` helpers do this for you in both binding models.
fix(descriptor-heap): round the buffer region up, align the reserved range for buffers too, and never size a heap at zero DescriptorHeapVulkan - The buffer region started at images * imageDescriptorSize / bufferDescriptorSize, rounded down. A descriptor_heap array indexes the heap from byte 0 in strides of its descriptor size, so buffer slot 0 has to sit on a whole buffer descriptor past the images. Where the image descriptors were not a whole number of buffer descriptors, the first buffer descriptors overwrote the last image descriptors. Where they were less than one, the start was bumped to descriptor 1, but the heap was still sized as if the buffers began right after the images, so the last buffer descriptors went into the implementation's reserved range. Every descriptor size is a power of two, so both cases need image descriptors smaller than buffer descriptors, which NVIDIA (32 and 16 bytes) and llvmpipe (64 and 16) do not have. The start now rounds up and the heap is sized from it (#163). - The reserved range sat at a multiple of imageDescriptorAlignment only, where vkCmdBindResourceHeapEXT also wants bufferDescriptorAlignment (VUID-vkCmdBindResourceHeapEXT-pBindInfo-11435 and -11436). It now starts on a multiple of the larger. The buffer descriptors need no more than the rounding: each alignment is at most its descriptor size, so a whole number of descriptors is aligned. - bufferStartElement is 16 bits and took the division unchecked, so an image region past 65535 buffer descriptors (16384 images on llvmpipe) wrapped the buffer region around onto the images. Slot counts whose buffer indices do not fit 16 bits, 0xFFFF being the empty slot, now throw, naming the counts. A heap without buffer slots has no buffer region, which starts at 0 as in descriptor-set mode, so image-only heaps have no index to fit. - On a driver that reserves nothing (llvmpipe), a heap without sampler slots was a zero-size buffer, which every Initialize(1, 1, 0) made, and Window::Render bound its address each frame. Each heap now holds at least one descriptor, as each binding does in descriptor-set mode. That grows NVIDIA's sampler heap by one descriptor when no sampler slots are asked for; the resource heaps of the slot counts in the tree keep their layouts byte for byte. - ComputeLayout holds the arithmetic, pure over the descriptor-heap properties, and Initialize goes through it. GetBufferOffset and GetBufferOffsetElement, which had their own copies of the old arithmetic and never had a caller, are gone. - Bind(cmd, frame) binds a frame's heaps with the reserved ranges Initialize stored, or in descriptor-set mode the frame's descriptor set. Window::Render and the RTVolume example worked the reserved-range offset out from the heap's size with the image-alignment mask, and call Bind now. The window's per-heap cache of bind structs goes with it: keyed on the heap pointer, it kept binding the old buffers after a re-Initialize that reallocated them. The heap still ends with its reserved range, so code that derives the offset from the size keeps getting the right one. Tests - DescriptorHeapLayout: the issue's two layouts, the reserved range where buffer descriptors are aligned more strictly than image ones, every legal combination of descriptor sizes and alignments up to 256 bytes, no heap empty, the NVIDIA and llvmpipe layouts, the 16-bit limit and image-only heaps. Pure CPU, no device. Against the old arithmetic it fails 12 of its 18 checks. Docs - README.md's heap bullet and AGENTS.consumer.md say how to bind the heap outside the frame loop, and the consumer notes that Initialize throws when buffer indices would pass 16 bits. AGENTS.md lists ComputeLayout among the functions the pure-logic tests drive. Closes #163. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:02:58 +01:00
- Binding the heap outside the frame loop: `Window::Render` binds `window.descriptorHeap` in every frame it records. A command buffer it does not record that dispatches against the heap (`window.StartInit()`'s, say) calls `heap.Bind(cmd, frame)`, which binds that frame's heaps with their reserved ranges, or in descriptor-set mode its descriptor set. Don't build the `VkBindHeapInfoEXT` by hand: where the reserved range sits is the heap's to decide.
- **Descriptor-set fallback.** On a driver without `VK_EXT_descriptor_heap` (Mesa Turnip on Adreno) `Device::descriptorHeapSupported` is false and the same slots live in one bindless descriptor set per frame; slot handles, item structs, `UIDispatchHeader` and the `UIRenderer` API are unchanged, so application code does not branch. Ray tracing is unavailable there. `CRAFTER_GRAPHICS_NO_DESCRIPTOR_HEAP` forces this path on a driver that has the heap, to test it. Raw `vkWriteResourceDescriptorsEXT` code is heap-only; a consumer that must run on such a driver stays on the `UIRenderer::Register*` helpers.
### Buffers, images, samplers
- `VulkanBuffer<T, Mapped>`: `Create(usage, memoryFlags, count, preferredFlags = 0)`; `Resize(...)` reuses the allocation when the request fits and the usage matches, otherwise queues the old one and creates; `size` (bytes), `buffer`, `address` (non-zero only with `VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT`), `memoryPropertyFlagsChosen`. With `Mapped`, `value` is the `T*` of a persistent map: after writing, call `FlushDevice()` (whole buffer), `FlushDevice(offset, bytes)` (a range, rounded to `nonCoherentAtomSize`) or `FlushDevice(cmd, dstAccess, dstStage)`, which flushes and records the host-write barrier; all three are no-ops on coherent memory. `FlushHost()` is the invalidate for readback. A UI item buffer is `GraphicsBuffer<QuadItem, true>` with `STORAGE_BUFFER | SHADER_DEVICE_ADDRESS` usage and `HOST_VISIBLE` memory with `DEVICE_LOCAL` as the preferred fourth argument (the examples pass both as required, which throws on a GPU without a host-visible device-local type), flushed each frame before the dispatch that reads it.
- Static geometry: `VulkanBuffer<T, false>::UploadDeviceLocal(usage, src, count, cmd, dstAccess, dstStage)` places the buffer in device memory, written directly on ReBAR and UMA and staged through a per-frame staging ring on a small BAR, and records the barrier to `dstStage`. `UploadDeviceLocalRange(src, offset, count, cmd, dstAccess, dstStage)` re-uploads the dirty window `[offset, offset + count)`; `src` points at the first dirty element (`vertices.data() + offset`), not at the array's start. A re-upload into a buffer a frame may still read is ordered after those reads on the GPU.
- `ImageVulkan<Pixel>` (`Image2D<Pixel>` is the portable alias): `Create(width, height, mipLevels, cmd, format, usage, layout, consumerStage = RAY_TRACING_SHADER, streamed = false)` makes the image and a mapped staging buffer `image.buffer`; fill `image.buffer.value` and `Update(cmd, layout)` copies it in, builds the mip chain by blits and transitions to `layout` for `consumerStage`. `Update(const CompressedTextureAsset&, cmd, layout)` decompresses a `.ctex` on the GPU, or the CPU. A static image releases its staging after the first upload; `streamed = true` keeps it (the font atlas, through `UpdateRegion`). Pass `VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT` as `consumerStage` for an image a compute shader samples; the RT default is corrected to compute on a device without ray tracing. `image`, `imageView` and `descriptor` are public for raw descriptor writes; `Destroy()` releases.
fix(device): stop requiring samplerAnisotropy, and remove SamplerVulkan, the class it was required for Device::Initialize counted samplerAnisotropy among the library's own features because SamplerVulkan turned anisotropic filtering on (#168). Nothing in this repository has made a SamplerVulkan since 6e94cc6, which replaced Sponza's with a sampler-heap write. So Initialize enabled the feature for every application where the GPU had it, and skipped a GPU without it, for a class this repository no longer used. Design rule 8 has the library enable only the device features its own shaders use. SamplerVulkan: removed. #168's other suggestion keeps it, with deferred deletion, a clamp to maxSamplerAnisotropy and anisotropy left to the application. But the VkSampler it makes has no way into the heap, which takes a sampler's create-info rather than a sampler object: vkWriteSamplerDescriptorsEXT writes the descriptor straight from the VkSamplerCreateInfo. In descriptor-set mode the heap makes each slot's VkSampler itself, in DescriptorHeapVulkan::WriteSamplerSets, from the same create-info. A class that fitted the heap would hold a SamplerSlot and that write; a one-call sampler write for code without a UIRenderer is #177's, which asks for heap-mode writers on DescriptorHeapVulkan for images, buffers and samplers alike. The partition leaves project.cpp's ifaces and the umbrella module. Device: samplerAnisotropy leaves the library's features. No sampler the library, its tests or its examples make sets anisotropyEnable. An application that wants anisotropic filtering asks Device::Initialize for the feature. Docs: AGENTS.template.md counts 40 partitions and no longer lists :SamplerVulkan. AGENTS.consumer.md describes samplers as slots written from a create-info: through UIRenderer::RegisterSampler, or, without a UIRenderer, through vkWriteSamplerDescriptorsEXT as Sponza does, or WriteSamplerSets in descriptor-set mode. It says that anisotropyEnable needs .vulkan10.samplerAnisotropy from the application. The README names samplerAnisotropy among the features an application asks for. Tests: FeatureRequests checks, in its main run and in its Vulkan 1.3 child (CRAFTER_GRAPHICS_NO_VULKAN_1_4), that samplerAnisotropy is off after a Device::Initialize that does not ask for it. With the requirement put back, the check fails in both, on the RTX 4090 here, which has the feature.
2026-11-26 09:25:32 +01:00
- Samplers live in sampler slots, written from a `VkSamplerCreateInfo`. `UIRenderer::RegisterSampler(const VkSamplerCreateInfo&)` writes the sampler into every frame's sampler heap (in descriptor-set mode into every frame's set, through a `VkSampler` the heap creates and owns) and returns a `SamplerSlot`; `RegisterLinearClampSampler()` registers a linear, clamp-to-edge one. Without a `UIRenderer`, in heap mode (ray tracing), call `Device::vkWriteSamplerDescriptorsEXT` with the create-info for each frame `f`, into `heap.samplerHeap[f].value + heap.SamplerByteOffset(range.firstElement)`, `Device::descriptorHeapProperties.samplerDescriptorSize` bytes, then flush, as `examples/Sponza/main.cpp` does; in descriptor-set mode `heap.WriteSamplerSets(range.firstElement, info)` does it. The library makes no anisotropic sampler and does not enable `samplerAnisotropy`: a create-info with `anisotropyEnable` needs `.vulkan10.samplerAnisotropy` among `Device::Initialize`'s required features (or its optional ones, checked in `Device::enabledFeatures`).
### UI
Three tiers, on purpose: Tier 1 is any compute shader you write (`ComputeShader`, `UIRenderer::Dispatch`); Tier 2 the four standard kernels, their item structs and the `UIRenderer` helpers; Tier 3 stateless functions that append items to your buffers. The library has no widget tree, layout engine, theme, hit-testing or focus management: state lives in your PODs, hit-testing is `Rect::Contains` against the rects you drew, and a Tier 3 component that does not fit is copied out of `implementations/Crafter.Graphics-UIComponents.cpp` and edited, not subclassed.
Setup: `FontAtlas atlas; atlas.Initialize(init);` then `UIRenderer ui; ui.fontAtlas = &atlas; ui.Initialize(window, heap, init); window.passes.push_back(&ui);`. `Initialize` loads the five kernels by file name from the working directory (`ui-quads.comp.spv` and so on; the `.sets.spv` builds must sit beside them) and registers the swapchain images and the atlas. Then, per item buffer, `auto slot = ui.RegisterBuffer(buf);` gives a `BufferSlot` ready for a shader.
Per frame, in an `EventListener<UIBuildArgs>` on `ui.onBuild` (fired from the pass's `Record` with `{cmd, frameIdx}`):
fix(font-atlas): give glyphs that find no room a cell when the next frame begins, evicting the least recently drawn The atlas packed glyphs onto shelves and never gave a place back (#55). Once its 1024x1024 image was full, EnsureAndGet returned nullptr for each new glyph before caching anything, so every new string holding one rasterised it again, and ShapeText dropped it together with its advance: the rest of the line closed up over the gap, and stayed that way. FontAtlas - A glyph is measured, not rasterised, until it gets a cell. One that finds no free room keeps its advance and box and draws blank for a frame. EnsureAndGet always returns the glyph, now a reference; Glyph::Resident() says whether it has a cell, Glyph::handle which one (slot and generation). - Evictions wait for the next frame: its first EnsureAndGet, Touch or Update places the glyphs that waited, once every glyph the frame before drew has been marked. Evicting while a frame is still asking for glyphs took ones it drew further down, which then took others in turn: a page switched back to could rasterise most of itself again rather than what it was missing, and on the DOM backend an over-full view could do so every frame. - A glyph keeps its cell for framesInFlight + 1 frames after it was drawn. The frame loop waits frame u's fence at the start of frame u + framesInFlight, but Device::frameCounter reads that from the end of the frame before, and input callbacks and onBeforeUpdate run in between. - FontAtlas::Packer places glyphs. Until the rows run out it fills shelves exactly as before. Then a glyph takes the same columns of one shelf at least as tall, or of several in a row as tall together, the free rows below the last shelf counting as one more: free texels, and, when the frame begins, glyphs nothing in flight draws, the least recently drawn first. A glyph spanning shelves lets in one taller than every shelf, and a few glyphs drawn every frame pin only their columns. Merging whole shelves instead, tried first, left a random workload without room for a glyph while a median 43% of the atlas was in flight; spanning, at 65%. - A box that found no room in a frame is remembered, with every box at least as big, as a small set per mode, until the frame ends or (without eviction) something is evicted: a saturated atlas no longer searches every shelf for each of its missing glyphs. - An evicted glyph is forgotten, and its texels are zeroed and uploaded with the glyph that takes its place: a neighbour's filtering at its edge must read padding or zero, not a stale glyph. - Touch(handles) marks every glyph whose handle still holds its cell, and says whether all did. InvalidateFont(font) forgets the font's glyphs and those waiting for a cell, whose Font* the next frame would read. The glyph index is looked up at rasterisation, so a Font replaced in place never gets one past its glyphs. GlyphsRasterized() counts, for tests. UIRenderer - A shaped run keeps a handle per glyph it draws. A hit touches them all, so the atlas keeps what is drawn every frame, and shapes the run again when one was evicted or one had no room. A glyph without room draws blank but advances the pen. - InvalidateFont clears the atlas's glyphs of the font too, as its comment and AGENTS.md always said it did. - Record calls the atlas's Update before onBuild, every frame, so the waiting glyphs are placed and uploaded first. Dispatch uploads the atlas before any kernel, a Tier 1 one sampling FontAtlasImageSlot() included: a glyph placed earlier in onBuild can sit in a cell another glyph had. DispatchText and DispatchFused no longer do it themselves. Device, Window (DOM) - Device::frameCounter and Device::framesInFlight exist on the DOM backend too, the counter bumped at the end of Window::Render, with one frame in flight: a frame's writeTexture lands before that frame's submit but after every earlier one. HelloUI - One set of item buffers and slots per frame in flight, by frameIdx. A frame still on the GPU read the items the next frame's onBuild was rewriting; with cells changing hands, those can name cells it drew other glyphs in. Tests - FontAtlasPacker: the packer with made-up boxes and no device: the fill order, least recently drawn first, framesInFlight + 1 frames held, nothing without evict, wide glyphs, tall glyphs spanning shelves and the free rows, Touch past a stale handle, stale handles, dirty spans, and the invariants over a random workload placed the way the atlas places. - FontAtlasEviction: fills the atlas through ShapeText frame by frame. The line that no longer fits keeps its advance and its glyphs' places; its missing glyphs aren't rasterised while nothing can go; when only line 0 is cold, only its glyphs give way; a frame's own misses evict nothing in it; a frame later the line and twenty more are whole, pixel for pixel, line 0 losing a larger share than the glyphs drawn after it; a stale cached run is shaped again; no stale texel is left; InvalidateFont reaches the atlas. Against master, with its two calls to the new API stubbed out, an earlier version failed ten checks. - UIDispatchAtlasFlush: a custom ui.Dispatch after ShapeText leaves the atlas uploaded. Needs a compositor. - ShapeTextCache: a hit rasterises nothing; after InvalidateFont the re-shaped run draws the same, from new cells. Docs - README and AGENTS.consumer.md: the atlas's eviction, the frame a glyph waits, shaping text every frame into per-frame item buffers, InvalidateFont, EnsureAndGet's signature and Lookup's lifetime, and that the atlas, like the deletion queue, assumes one rendering window and evicts nothing without one. - AGENTS.md: FontAtlas::Packer among the pure-logic helpers, eviction without a Window, and InvalidateFont. Breaking: FontAtlas::EnsureAndGet returns const Glyph& and never fails; check Glyph::Resident() before drawing from its UVs. FontAtlas::Touch is no longer noexcept. A GlyphItem is good for the frame it was shaped for, once the atlas has filled up, and item buffers must be per frame. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 09:10:42 +01:00
1. Rebuild the item arrays in your mapped buffers, in draw order: later items overdraw earlier ones. Lay out with `Rect::FromWindow(window)`, `SubRect(size, Anchor)` and `Inset(...)`. Keep one set of item buffers (and slots) per frame in flight, `Window::numFrames` of them, and fill the one at `frameIdx`: a frame still on the GPU reads its items as it runs, and a later frame's items written into the same buffer can name atlas cells that frame drew other glyphs in (`examples/HelloUI`).
2. `buf.FlushDevice(cmd, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT)` for each buffer with items.
3. Dispatch: `ui.DispatchQuads(cmd, slot, count, clipRectPx = {0, 0, 1e9, 1e9})`, `DispatchCircles`, `DispatchImages`, `DispatchText`, or `ui.DispatchFused(cmd, {quadsSlot, qc}, {circlesSlot, cc}, {imagesSlot, ic}, {glyphsSlot, gc})`, which composites the four categories in that fixed order (quads, circles, images, text) with one load and one store; an empty category costs nothing. The two forms mix; a custom `ui.Dispatch` between two `DispatchFused` calls is the flush point.
- The item structs are `std430` PODs mirrored byte for byte in `shaders/ui-shared.glsl`, and frozen: `QuadItem` (64 bytes: `x, y, w, h`, `r, g, b, a`, corner radii `cTL, cTR, cBR, cBL`, `outline, oR, oG, oB`), `CircleItem` (48: `cx, cy, radius, _p0`, colour, outline), `ImageItem` (64: rect, `u0, v0, u1, v1`, tint, `texSlot, sampSlot, _p1, _p2`), `GlyphItem` (48: rect, atlas uv, colour). Colours are straight alpha, blended source-over; coordinates are window pixels.
- Cost: every kernel dispatches one workgroup per 8x8 screen tile and each pixel walks every item (behind a per-tile cull), so a dispatch is `O(W*H*N)`, fine up to a few hundred items at 1080p. Splitting one buffer into several dispatches does not help. Thousands of items want a different shader (tile binning), which is Tier 1.
fix(ui): decode the font atlas's SDF in atlas pixels, so text edges ramp over one screen pixel Shaders - ui-text and ui-fused turned a sample of the R8_UNORM atlas into a distance with (128/255 - sdf) * 32. stb_truetype writes kOnEdgeValue + kPixelDistScale * distance into each byte, so an atlas pixel is kPixelDistScale / 255 of a sample; 32 made every distance 1024/255 (about 4) times too large, and the coverage ramp, meant to span one screen pixel, spanned a quarter of one: nearly every edge pixel came out fully on or fully off, and text looked pixelated at every size. On an RTX 4090, UIFallbackParity's 22 px label had 98 partly covered pixels where stb_truetype's own rasterizer has 415. Wrong since the v3 UI (1f56973), and copied into the fused kernel (574242d). - The decode now lives once, in ui-shared.glsl: UI_SDF_ON_EDGE and UI_SDF_PIXEL_DIST_SCALE are FontAtlas's two constants in the encoder's own units, uiSdfDistance decodes a sample, uiGlyphRamp works out a glyph's ramp when it is loaded and uiGlyphCoverage the coverage per pixel. Both kernels call them, and a copy of either should; the UI_ prefix keeps them clear of a copied kernel's own names. - stb_truetype truncates, so a byte b stands for [b, b + 1) of the encoded value and the decode takes its middle: decoding b pulled every outline 1/64 atlas pixel inwards. - The ramp is capped at what a byte holds, about 4 atlas pixels each way of the outline. With the corrected decode a wider one left every glyph quad's padding translucent below 4 px. - The UV span is taken with abs(): a glyph turned by swapping its UVs got a negative scale, a ramp of 0.0001 and hard edges. - A glyph scaled differently along x and y ramps along the distance's gradient, from two one-texel differences. With the corrected decode, one width for both axes, the more minified one's, would leave a row stretched three times with stems three pixels soft. Glyphs scaled alike, as ShapeText's are, keep one multiply-add per pixel, the ramp's reciprocal worked out with the glyph. - The atlas size is queried rather than FontAtlas::kAtlasSize hard-coded as 1024. WebGPU - The WGSL text kernel decoded the distance right but ramped over one atlas pixel whatever the size: half a screen pixel at 16 px, two at 64 px. It now repeats ui-shared.glsl's decode, cap, abs and gradient path, and renders TextAntialiasing's scene as Vulkan does (run through Deno's WebGPU: 1.02, 1.07 and 1.09 times the reference's edge pixels, where the old kernel gave 0.55, 2.19 and 0.89). FontAtlas - kOnEdgeValue and kPixelDistScale say the kernels carry copies of them. Tests - TextAntialiasing draws one string at 14 px, 64 px and 14 px stretched three times, a 'g' turned by its UVs and empty atlas texels shrunk to 12.8 atlas pixels per screen pixel, through DispatchText and again through DispatchFused, and holds them to stb_truetype's antialiased rasterizer, to the mirror image and to nothing. On master the two plain rows have 0.31 and 0.21 times the reference's edge pixels; with the decode fixed alone the stretched row had 1.62 times, the turned 'g' was 127 codes off its mirror and the empty texels drew 48. Now: 1.02, 1.07 and 1.09 times, 0 and 0, on the 4090, on llvmpipe and on descriptor sets. It skips a swapchain that isn't 8-bit, which the capture can't read, and captures the first frame. - FontAtlasDecode reads ui-shared.glsl and dom-webgpu.js and holds their copies of the two constants to FontAtlas's. No GPU. Docs - AGENTS.consumer.md has a custom text shader decode through the helpers and gives the encoding; README says so in a line; AGENTS.md lists the tests and where the decode lives. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:22:12 +01:00
- Text: `Font font("font.ttf")` (TrueType through stb_truetype); `font.GetLineWidth(text, px)`, `LineHeight(px)`, `AscentPx(px)`, `NearestCursorByte(text, px, x)`. The atlas is a 1024 by 1024 SDF atlas at a 32 px base size, filled lazily per codepoint and re-uploaded by dirty rectangle. Glyphs scale from it with the edge ramped over one screen pixel at any size and aspect, on both backends; far above 32 px corners round off and fine detail goes, and below about 4 px the ramp narrows and thin strokes bolden. `ui.ShapeText(font, px, x, baselineY, utf8, color, out, capacity, &advance, TextAlign::Left)` writes `GlyphItem`s: single line, no kerning, no wrapping, a shaped-run cache behind it. Once the atlas is full, a glyph that finds no free room draws blank for one frame but keeps its advance, and gets a cell when the next frame begins, taken from the glyphs drawn least recently, never one drawn in the last `Device::framesInFlight + 1` frames. So a `GlyphItem` holds for the frame it was shaped for: shape text every frame (the Tier 3 components do, and a cached run costs a copy) rather than drawing a glyph buffer filled in an earlier frame. `atlas.EnsureAndGet(font, codepoint)` returns `const Glyph&` and never fails; its UVs hold only when `Resident()`, and a `Lookup` pointer only until the atlas's next `EnsureAndGet`, `Touch` or `Update`. A Tier 1 kernel that samples `FontAtlasImageSlot()` through `ui.Dispatch` sees the frame's new glyphs: every dispatch uploads the atlas first.
- Tier 3: fill a `UIBuffer` (`quads`, `quadCount`, `quadCap`; `glyphs`, `glyphCount`, `glyphCap`; `images`, `imageCount`, `imageCap`; `atlas`; `renderer`; a null pointer makes the components that need it no-ops) and call `DrawButton(buf, rect, label, hovered, pressed, font, px, ButtonColors)`, `DrawCheckbox(buf, rect, checked, hovered, CheckboxColors)`, `DrawSlider(buf, rect, t01, dragging, SliderColors)`, `DrawProgressBar(buf, rect, t01, ProgressColors)`, `DrawText(buf, text, x, baselineY, font, px, color, align)` (returns the advance) and `DrawImage(buf, rect, textureSlot, samplerSlot, tint, uv)`. Colours are small `*Colors` aggregates you hold; there is no `Theme`.
- `InputField` is the model for a stateful component: a POD (`value`, `type`, `focused`, `cursorPos`), free functions you call from your own listeners (`InputField_OnText(field, utf8)` from `onTextInput`, `InputField_OnKey(field, code)` from `onRawKeyDown`, `InputField_HitTestCursor(field, rect, clickX, font, px, colors)`), `InputField_TryParse<T>(field)`, and `DrawInputField(buf, field, rect, font, px, colors, caretVisible)`; the blink is yours.
- Images in the UI: `auto tex = ui.RegisterImage(image, VK_FORMAT_R8G8B8A8_UNORM);` (an `ImageSlot`; the layout defaults to `SHADER_READ_ONLY_OPTIMAL`), `auto samp = ui.RegisterLinearClampSampler();`, then both go into `ImageItem::texSlot` and `sampSlot`. `ui.OutImageSlot()`, `FontAtlasImageSlot()` and `FontAtlasSamplerSlot()` expose the renderer's own slots.
### Custom compute shaders (Tier 1)
A GLSL compute shader that dispatches beside the standard kernels follows `shaders/ui-shared.glsl`, which the build puts on the include path:
```glsl
#version 460
#extension GL_GOOGLE_include_directive : enable
#include "ui-shared.glsl"
struct MyItem { vec4 a; }; // mirrored in C++ with a static_assert on its size
layout(UI_HEAP_BUFFERS, std430) readonly buffer MyBuf { MyItem items[]; } myHeap[];
layout(push_constant) uniform PC { UIDispatchHeader hdr; /* your fields after it */ } pc;
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
void main() {
ivec2 px;
if (!uiResolveScreenPixel(pc.hdr, px)) return;
// read myHeap[pc.hdr.itemBuffer].items[i]; imageLoad/imageStore uiImages[pc.hdr.outImage]
}
```
- Declare bindless resources with `UI_HEAP_IMAGES`, `UI_HEAP_TEXTURES`, `UI_HEAP_SAMPLERS` and `UI_HEAP_BUFFERS`, never a literal `descriptor_heap` or a set and binding, and register the source twice in `project.cpp`: once plain, once with `sets.defines = {"CRAFTER_GRAPHICS_DESCRIPTOR_SETS"}; sets.variant = "sets";`, which yields `<name>.spv` and `<name>.sets.spv`. `ComputeShader::Load("<name>.spv", heap)` picks the build the device needs and throws naming a missing file. `examples/CustomShader/project.cpp` has the lines.
- `UIDispatchHeader` (48 bytes; in C++ `outImage, itemBuffer, surfaceWidth, surfaceHeight, clipX, clipY, clipW, clipH, itemCount, frameIdx, flags, _pad`, and in GLSL the same bytes as `uint outImage, itemBuffer; uvec2 surfaceSize; vec4 clipRectPx; uint itemCount, frameIdx, flags, _pad`) must be the first member of the push block; `ui.FillHeader(slot, count, clipRectPx, flags)` fills it. The high bit of `flags` (`kUIFlagClip`) is the renderer's, the rest are yours. Keep the push block a multiple of 4 bytes and within 256; the descriptor-set path throws past the device's `maxPushConstantsSize`.
- `ui.Dispatch(cmd, shader, &pc, sizeof(pc), ceil(W / 8), ceil(H / 8))` binds, pushes and dispatches, with a `SHADER_WRITE -> SHADER_READ | SHADER_WRITE` barrier on the swapchain image before every dispatch but the frame's first, so a custom shader sees what the dispatch before it drew. `ComputeShader::Dispatch(cmd, push, bytes, gx, gy, gz, tlasAddress = 0)` is the same without the barrier; a compute shader that ray-queries the TLAS passes `RenderingElement3D::tlases[frameIdx].address`, for the NVIDIA workaround below.
fix(ui): decode the font atlas's SDF in atlas pixels, so text edges ramp over one screen pixel Shaders - ui-text and ui-fused turned a sample of the R8_UNORM atlas into a distance with (128/255 - sdf) * 32. stb_truetype writes kOnEdgeValue + kPixelDistScale * distance into each byte, so an atlas pixel is kPixelDistScale / 255 of a sample; 32 made every distance 1024/255 (about 4) times too large, and the coverage ramp, meant to span one screen pixel, spanned a quarter of one: nearly every edge pixel came out fully on or fully off, and text looked pixelated at every size. On an RTX 4090, UIFallbackParity's 22 px label had 98 partly covered pixels where stb_truetype's own rasterizer has 415. Wrong since the v3 UI (1f56973), and copied into the fused kernel (574242d). - The decode now lives once, in ui-shared.glsl: UI_SDF_ON_EDGE and UI_SDF_PIXEL_DIST_SCALE are FontAtlas's two constants in the encoder's own units, uiSdfDistance decodes a sample, uiGlyphRamp works out a glyph's ramp when it is loaded and uiGlyphCoverage the coverage per pixel. Both kernels call them, and a copy of either should; the UI_ prefix keeps them clear of a copied kernel's own names. - stb_truetype truncates, so a byte b stands for [b, b + 1) of the encoded value and the decode takes its middle: decoding b pulled every outline 1/64 atlas pixel inwards. - The ramp is capped at what a byte holds, about 4 atlas pixels each way of the outline. With the corrected decode a wider one left every glyph quad's padding translucent below 4 px. - The UV span is taken with abs(): a glyph turned by swapping its UVs got a negative scale, a ramp of 0.0001 and hard edges. - A glyph scaled differently along x and y ramps along the distance's gradient, from two one-texel differences. With the corrected decode, one width for both axes, the more minified one's, would leave a row stretched three times with stems three pixels soft. Glyphs scaled alike, as ShapeText's are, keep one multiply-add per pixel, the ramp's reciprocal worked out with the glyph. - The atlas size is queried rather than FontAtlas::kAtlasSize hard-coded as 1024. WebGPU - The WGSL text kernel decoded the distance right but ramped over one atlas pixel whatever the size: half a screen pixel at 16 px, two at 64 px. It now repeats ui-shared.glsl's decode, cap, abs and gradient path, and renders TextAntialiasing's scene as Vulkan does (run through Deno's WebGPU: 1.02, 1.07 and 1.09 times the reference's edge pixels, where the old kernel gave 0.55, 2.19 and 0.89). FontAtlas - kOnEdgeValue and kPixelDistScale say the kernels carry copies of them. Tests - TextAntialiasing draws one string at 14 px, 64 px and 14 px stretched three times, a 'g' turned by its UVs and empty atlas texels shrunk to 12.8 atlas pixels per screen pixel, through DispatchText and again through DispatchFused, and holds them to stb_truetype's antialiased rasterizer, to the mirror image and to nothing. On master the two plain rows have 0.31 and 0.21 times the reference's edge pixels; with the decode fixed alone the stretched row had 1.62 times, the turned 'g' was 127 codes off its mirror and the empty texels drew 48. Now: 1.02, 1.07 and 1.09 times, 0 and 0, on the 4090, on llvmpipe and on descriptor sets. It skips a swapchain that isn't 8-bit, which the capture can't read, and captures the first frame. - FontAtlasDecode reads ui-shared.glsl and dom-webgpu.js and holds their copies of the two constants to FontAtlas's. No GPU. Docs - AGENTS.consumer.md has a custom text shader decode through the helpers and gives the encoding; README says so in a line; AGENTS.md lists the tests and where the decode lives. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:22:12 +01:00
- A shader that draws text from the font atlas (`ui.FontAtlasImageSlot()` and `FontAtlasSamplerSlot()`), a copy of `ui-text.comp.glsl` among them, decodes it with `ui-shared.glsl`'s helpers rather than arithmetic of its own: `uiGlyphAtlasSize(texSlot, samplerSlot)`, then `uiGlyphRamp(item.uv, 1.0 / item.rect.zw, atlasSize)` once per glyph and `uiGlyphCoverage(texSlot, samplerSlot, uv, ramp, atlasSize)` per pixel, with dynamically uniform slots. A texel holds stb_truetype's `UI_SDF_ON_EDGE + UI_SDF_PIXEL_DIST_SCALE * d` (128 + 32 d), `d` the distance from the outline in atlas pixels, positive inside, truncated to a byte; `uiSdfDistance(sample)` gives `d` back. Multiplying a sample by 32 instead of dividing by 32/255 gives a ramp a quarter of a pixel wide, and pixelated text.
- Keep the one-workgroup-per-screen-tile shape for anything that composites. A workgroup per item races on overlapping pixels: Vulkan orders nothing between the workgroups of one dispatch.
- A `ComputeShader` can also run outside the UI pass, dispatched from `onUpdate` into the frame's command buffer with barriers of your own.
### Ray tracing (Vulkan)
Heap-only: check `Device::rayTracingSupported`, or expect `std::runtime_error` from the first RT call. `examples/VulkanTriangle/main.cpp` is the whole setup.
- Shaders: `VulkanShader shader("raygen.spv", "main", VK_SHADER_STAGE_RAYGEN_BIT_KHR, &specInfo);` (`nullptr` for no specialisation); `ShaderBindingTableVulkan table; table.Init(shaders);`; `PipelineRTVulkan pipeline; pipeline.Init(cmd, raygenGroups, missGroups, hitGroups, table, maxRecursionDepth = 1);` with spans of `VkRayTracingShaderGroupCreateInfoKHR` indexing the shader array. **`maxRecursionDepth` counts the raygen as 1**: a closest-hit that traces a shadow ray needs 2, and tracing past the pipeline's depth loses the device.
- Geometry: `Mesh mesh; mesh.Build(std::span<Vector<float, 3, 3>> vertices, std::span<std::uint32_t> indices, cmd, RTBuildOptions{});` builds a BLAS and sets `mesh.blasAddr`; `Build(const CompressedMeshAsset&, cmd)` builds from a `.cmesh`, decompressed on the GPU where supported; `BuildProcedural(aabbs, opaque, cmd)` builds from `RTAabb` boxes for a `VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_KHR` with an intersection shader, and has an overload taking a device address a compute pass wrote. `RTBuildOptions` is `.preference` (`FastTrace`, `FastBuild`), `.allowUpdate` and `.noDuplicateAnyHit`; with `allowUpdate`, `Refit(vertices, indices, cmd)` and its dirty-range overload update in place and keep `blasAddr`. A rebuild into storage that still fits keeps `blasAddr` too; read it again after a rebuild that grows.
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
- Instances: a `RenderingElement3D` holds a `VkAccelerationStructureInstanceKHR instance` (`transform`, `mask`, `instanceCustomIndex`, `instanceShaderBindingTableRecordOffset`, `flags`, `accelerationStructureReference = mesh.blasAddr`; Crafter.Math's `MatrixRowMajor<float, 4, 3, 1>::Store(reinterpret_cast<float*>(instance.transform.matrix))` writes the transform), `userMetadata` (copied per instance id into `tlases[f].metadataBuffer`) and `transformOwnedByGpu`. `RenderingElement3D::Add(&e)` and `Remove(&e)` register it. `RenderingElement3D::BuildTLAS(cmd, frameIndex, preference = FastTrace)` builds or refits `tlases[frameIndex]` from every registered element: once per frame slot at setup (`0`, `1`, `2`), and per frame from `onUpdate` for `window.currentFrame` when instances move. `e.MarkHostDataDirty()` after a change to an element's host fields lets the per-frame copy skip unchanged slots. `tlases[f].address` goes into a `VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR` descriptor of frame `f` (see "The bindless heap") and changes only when the TLAS outgrows its storage.
- The pass: `RTPass rtPass(&pipeline); rtPass.pushPtr = &camera; rtPass.pushBytes = sizeof(camera);` pushes your data at offset 0 of the shaders' push block before every trace (the bytes are read at record time, so updating `camera` before the frame is enough); `width` and `height` trace at a size other than the window's. `window.passes.push_back(&rtPass);`.
fix(window): size the swapchain for its present mode, and key frames in flight by frame instead of image Window - CreateSwapchain asked for exactly numFrames (3) images whatever the surface said, read them into a three-element array, and keyed the command buffers, the fences and the descriptor-heap copy holding "its" swapchain image by the acquired image index. A swapchain of another size fell back to FIFO (asked for MAILBOX or IMMEDIATE) or threw, and a surface whose minimum is above three got a create info below it (#160). Mesa's MAILBOX needs four images: Turnip on phoc, llvmpipe on any Wayland compositor. - The present mode is picked first, then the swapchain is sized by SwapchainCapabilities: the surface's counts for that mode where the instance has surface_maintenance1. With swapchain_maintenance1 the swapchain names its mode (VkSwapchainPresentModesCreateInfoKHR), which is what makes the mode's own count the one that applies, at creation and to the forward progress of a UINT64_MAX acquire; without it the stricter of the mode's and the surface's counts for all modes. It asks for numFrames or that minimum where more, never past the maximum (SwapchainMinImageCount). Turnip's FIFO keeps its three images and MAILBOX gets four. The FIFO fallback and presentModeUnfit are gone. - images, imageViewInfos (was imageViews: they are create-infos), the made imageViews that descriptor sets take, imageInitialised and the render-finished semaphores are per image, as many as the driver made. The views are made once per swapchain. The semaphores only grow, since a present of the old swapchain may still wait on one. - Frames in flight stay numFrames, keyed by currentFrame, frameCounter % numFrames: the command buffer, the fence, the acquire semaphore, the heap copy (or set), RenderingElement3D::tlases, the frameIdx a pass is recorded with. currentImage is the acquired image. currentBuffer is gone, so code that used it stops compiling instead of picking the wrong one; RenderPass::Record's frameIdx keeps its name and is now the frame slot, as RenderPass.cppm says. - The frame's fence is waited before the acquire. The acquire semaphores need no spare then, and a frame waits for exactly the one numFrames before it, which the deletion queue and the staging rings count on and fences keyed by image did not promise once images come back out of order. The swapchain slots are written before the fence is reset. - From the acquire to the present the window is recording: a Resize or SetPresentMode from a listener (a VSync key ticked in onUpdate) takes effect after the present, through RebuildSwapchain, together with a present that found the swapchain out of date. Rebuilding mid-frame used to destroy the image the frame was drawing into; with images sized per swapchain it would also index past the new one's end. DescriptorHeapVulkan - Frames and images pair up differently from frame to frame, so no heap copy can keep one swapchain image. AddSwapchainSlot(slot, window) lists an image slot as that window's swapchain image, and Window::Render writes the image a frame acquired into its window's listed slots in that frame's copy, or its set, before onUpdate, skipping a slot that holds it already. A slot is one window's, so two windows can share a heap without writing each other's slots under each other's frames in flight. A slot listed during a frame its window records is written at once. A slot past the heap's image slots, an empty ImageSlot's 0xFFFF among them, is refused. Freeing a slot unlists it, as does initialising the heap in either binding model. WriteImageSet, the one use of which this replaces, is gone, and with it the per-frame dimension of setImageViews. Device - VK_KHR_surface_maintenance1 (or EXT) and VK_KHR_get_surface_capabilities2 are enabled where the loader has them (surfaceMaintenance1Supported, vkGetPhysicalDeviceSurfaceCapabilities2KHR), and the matching swapchain_maintenance1 with its feature where the device has it (swapchainMaintenance1Supported). - DistinctGpus groups the physical devices by GPU as CRAFTER_GRAPHICS_DEVICE numbers them, for ChooseGpu and tests. UI - UIRenderer lists its output slot instead of writing every copy itself, and again on every resize; the resize listener is gone on both backends. The headers' frameIdx is currentFrame. Examples - VulkanTriangle, Sponza, SponzaBench and RTVolume list their output slot and write only the per-frame TLASes. They wrote imageViews[f] into copy f once, which a resize left pointing at destroyed images. Tests - SwapchainImageCount: SwapchainMinImageCount on the numbers drivers report; every offered mode keeps its mode and gets what the window asks for; every frame presents the colour it drew, read back a texel per frame; a switch and a resize asked for during a frame wait for its present; a slot listed during a frame holds its image at once; two windows on one heap draw their own colours. The frame checks run again in child processes, through CRAFTER_GRAPHICS_DEVICE, on a GPU whose swapchains have more images than frames (this one, else llvmpipe), in each binding model the parent didn't cover; a child skips only for a GPU that can't run the library, and checks it runs the model it was asked for. - FrameLoopSync checks the frame slot follows the frame counter and counts the swapchain's own images. HeapASRead, HeapDynamicIndexHit and RTPassPushData list their swapchain slot and drop their resize rewrites. Docs - README, AGENTS.md and AGENTS.consumer.md: frames and images, the swapchain slots, rebuilds held to the present, the new optional groups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 08:51:18 +01:00
- In GLSL, with the extensions the examples enable (`GL_EXT_ray_tracing`, `GL_EXT_descriptor_heap`, `GL_EXT_nonuniform_qualifier` for a non-constant heap index, `GL_EXT_shader_explicit_arithmetic_types_int16` for a `uint16_t` spec constant, and `GL_EXT_shader_image_load_formatted` or a `writeonly` image): `layout(descriptor_heap) uniform accelerationStructureEXT topLevelAS[];`, `layout(descriptor_heap) uniform writeonly image2D image[];`, indices from spec constants or push data. The output image is the swapchain image at an image slot listed with `AddSwapchainSlot`, in `VK_IMAGE_LAYOUT_GENERAL`. Start from `examples/VulkanTriangle/raygen.glsl`.
- **NVIDIA.** On the proprietary driver (still on `615.78.08`) reading an acceleration structure through the heap loses the device. The library works around it transparently: `VulkanShader` rewrites the SPIR-V so the heap AS read becomes a TLAS-address load from the push block plus `OpConvertUToAccelerationStructureKHR`, and `RTPass` and `ComputeShader` push the address. Nothing changes in your shaders or code, except that the rewrite appends an 8-byte member after your push block, and that it turns `shaderInt64` on for itself only: a shader of yours that declares `Int64` still has to ask for `shaderInt64`, or it runs on NVIDIA alone. `CRAFTER_GRAPHICS_NO_AS_WORKAROUND` disables the rewrite, to probe a new driver. Second note: on `610.43.02`, indexing a `descriptor_heap` array with a runtime value inside a hit shader faulted (fixed in `615.78.08`). The portable pattern, which the Sponza example uses, is one descriptor at a spec-constant slot and dynamic indexing inside it: all geometry in one SSBO indexed by element offset, materials in one `texture2DArray` indexed by layer. `examples/Sponza/README.md` has the GLSL.
### Input
fix(wayland): take a new preferred scale at a frame boundary, and convert input with the scale the window draws at xdg_surface_handle_preferred_scale set Window::scale and did nothing else (#165). The buffers' size and the surface's follow the scale only where the window works one out from the other, which it did when it made a swapchain and when a frame took a configured size. So a scale that changed by itself, with no configure (the issue's case is a window moved to an output of another scale), reached them only at the next of those, and until then the window drew at the old scale. The pointer's and the touches' positions are turned into pixels with Window::scale, and the text input's caret back into surface-local units with it, so those were converted with the new scale while the frames were still drawn at the old one. The issue suggests making the swapchain again in the listener. That predates 89111e0, which moved the configure's rebuild out of its listener into Render() for #199 and #200; the scale takes the same way. Window: the listener keeps the scale in a new member, preferredScale, as wp_fractional_scale_v1 sends it, in 120ths, and Window::scale is the scale the window draws at. MatchSizesToScale, where the window works out the size it was not given from the one it was, sets it from preferredScale where it takes a new scale, and nothing else in the library sets it. TakeDeferredSize takes a preferredScale that is not the scale the window draws at, at a frame boundary of Render(), as it takes a configured size, and with one where one waits. A window the compositor sized keeps its surface's size and takes the pixels for it at the new scale, so Render() makes the swapchain again there and onResize fires where those pixels differ. One the application sized keeps its pixels and makes no swapchain, and its surface takes the size they come to at the new scale, which the next frame sends with its buffer (SendFrameSurfaceState). Before the start of the next frame the scale is taken only with a swapchain made where it gives the window new pixels: a window the compositor sized whose surface comes to other pixels at it, as after a present or with the swapchain a SetPresentMode makes outside a frame. Anywhere else it would change only the conversions and the size the surface is to take, which goes out with the next frame, and until that frame's commit the compositor maps the surface, and the pointer and the touches on it, by the destination it has: a click in between would be converted for a frame not drawn yet, landing where the new scale puts it on the one drawn at the old scale, and the onResize of a swapchain made for another reason at the pixels the window has would not tell the application of the scale. So a scale that leaves the pixels as they are waits for the start of the next frame (for a window the application sized, whose pixels are its own, and one the compositor sized that it leaves at its pixels), also where a present mode, a rebuild that waited or a Resize makes a swapchain before then, and so does a configured size that comes to the pixels the window has with it (an output's scale changed under a window that fills it). TakeDeferredSize and RebuildIfDeferred are told which of the two boundaries they run at (FrameBoundary), and MatchSizesToScale whether it takes the scale whatever it does to the pixels (takeScale), as at a frame's start and in the constructor. The listener sends no request and makes no Vulkan call, so the window goes on drawing at the old scale, and converting with it, until then; a scale that a listener of a frame dispatched is taken at the boundary after its present where it gives the window new pixels, and at the start of the next frame otherwise. From the window's first swapchain on, the listener fires onFrameOwed where the scale is not the one the window draws at, so that a window that draws on demand learns that a frame is owed, as it does from a configure; for a window the application sized no onResize comes. Before the first swapchain the listener only keeps the scale, which the constructor takes before it makes the swapchain, as it did. A scale of 0, with which no size can be worked out, is not taken. Where MatchSizesToScale changes the scale, it takes what the window holds in pixels of the scale before to the new one: currentMousePos, lastMousePos and mouseDelta, and the touch slots of the window's fingers. The compositor gives those in surface-local units and sends nothing for a pointer or a finger that rests, so a pointer resting over the window would otherwise stand at the old scale's pixels in the frames drawn at the new one until it moved, and the next delta would be the change of grid. The pointer's position as the compositor gave it is kept beside, in surface-local units, in a new member, surfaceMousePos, which no scale moves. And it sends the caret SetTextInput was given again, converted with the new scale, as the window does when the keyboard focus comes back: for a window the application sized, the surface changes size around pixels that stay, and the rectangle the input method holds would otherwise stay in the old units. The configure listener's test for a configure at the size the window has compares the buffers with the pixels for that size at preferredScale, the scale the frame takes with the size, as it compared them at Window::scale while the listener set that. While a new scale waits it finds no configure at the size the window has: one for the size the surface has waits for the frame that takes the scale and takes its size with it, so that the window is not made one the compositor sized while it draws at the scale before, at pixels that are not that size's at the scale it draws at. Input: Map took its delta for MouseDeltaBind from currentMousePos and a last position of its own, which the window's conversion does not reach, so a pointer that rests would read the change of grid as a delta at the Map's next Tick, which a camera bound to MouseDeltaBind turns by. On Wayland it takes it from surfaceMousePos, as the surface-local motion since its last Tick in the window's pixels of now: none for a pointer that rests, whatever scales the window took in between, where a last position taken along to each new scale would come back with a float residue through two of them. A position the application writes into currentMousePos itself does not reach it there. Device: the pointer's and the touches' handlers keep the position the compositor gave in surfaceMousePos (the first finger's for the pointer it stands in for), and touch_down, touch_motion and an enter's move work it into the pixels they store with the scale in force at the store. They store after listeners, of onTouchDown, onTouchMove and onMouseEnter, that may take a new scale (a SetPresentMode outside a frame for a window the compositor sized, the Render() of a frame callback one of them dispatched), and a position worked out before those listeners would be in the pixels of the scale before. The conversions read Window::scale, which is now the scale of the frames drawn since the boundary that took it. Docs: the README, the consumer notes and the guide's gotchas say what scale and preferredScale are and when a scale is taken; the first two said that scale could be newer than the sizes (#165). The README, the consumer notes and the comment on SetTextInput say what goes to the new scale with it, and that the caret is sent again; the consumer notes name surfaceMousePos, the Map's delta from it, and that a position the application writes into currentMousePos does not reach the Map. The bug-prover lens section names preferredScale as what changes in any dispatch, and the scale among what waits for a frame boundary, and that before the next frame's start it is taken only where it gives the window new pixels; the consumer notes, that a size configured during a frame waits with a new scale where the two come to the pixels the window has. Tests: ConfigureResize names the scale in 120ths, as the compositor does, and drives the scale's listener on a window whose surfaces are proxies. The listener sends nothing, leaves the scale and both sizes as they are, and fires onFrameOwed. Until a frame boundary takes the scale, a pointer motion to the surface's middle is at the middle of the buffers drawn at the scale before, and so is a finger that goes down there on the window the application sized; a caret given in the pixels of the window the compositor sized goes to a text input proxy converted with that scale. The next boundary takes it: a window the compositor sized keeps 400x300 and goes from 800x600 to 600x450 pixels at 1.5, which makes the swapchain, and its surface is sent nothing; one the application sized keeps its 640x480 pixels and makes no swapchain, and its surface goes from 320x240 to 640x480 at 1, sent with the frame. After it the motion, the finger's move and the caret are converted with the new scale. And before any new motion or call, the boundary has taken what the window held to the new scale: the pointer of the window the compositor sized is at the middle of the new buffers, the one the first finger stands in for on the other window is where its surface-local place comes to, a second finger that went down before the boundary lifts after it where its surface-local place comes to, and each boundary sends the caret again, converted, with no SetTextInput. An Input::Map attached to the window and ticked across a boundary that takes 1.5 reads no delta for a pointer that rests, and a motion of 10 units after it as 15 pixels; ticked across two boundaries between two Ticks on a window the compositor sized, 1.75 taken by a swapchain made outside a frame at the pixels it gives the window and 1 again by a frame's start, with the pointer resting at surface 100.25, it reads no delta and fires no event. On a window the compositor sized, a listener of onTouchDown, of onTouchMove and of onMouseEnter that takes a scale that waits has the click the finger stands in for, the finger's move and the move after the enter in the pixels of that scale. A scale that comes back before a frame owes nothing; one that comes while a frame is being recorded leaves that frame at the scale it began with, and the window the compositor sized takes it at the boundary after the present, with its new pixels, where the one the application sized takes it at the next frame's start: the boundary after the present takes nothing, a motion after it is still at the pixels of the frame on screen, and the caret is sent again only at the next frame's start (the fixture steps the boundary after the present, End, apart from the next frame's start, Begin); a configure that comes with it to the pixels the window has waits for that start as well, which takes the two together, the frame bringing the surface its size and the acknowledgement, and so does a scale that leaves a small window the compositor sized at its pixels; a configure without a size while a scale waits is acknowledged in the listener, and one for the size the surface has waits for the frame that takes the scale, also where its pixels at that scale are the window's (101x101 pixels at 2, a surface of 51x51, a scale of 237/120); before the first swapchain the listener only keeps the scale, which MatchSizesToScale takes, and a scale of 0 is not taken. In the cases there were, the check that nothing is owed counts a scale that waits as well, the frame whose scale changes while it is recorded is followed to the boundary that takes it, a swapchain made between frames is checked to leave no scale waiting for a window the compositor sized, and for one the application sized to take none, a motion until the next frame's start landing at the pixels of the frame on screen, also where the swapchain is made after a present that found it out of date, with a configure that comes with the scale to the window's pixels waiting too, and the case of a scale and then a configure counts onFrameOwed for both. ResizeViewport drives the scale against the compositor, where it has the fractional scale and the viewporter: on its window as the application sized it, and maximized where the compositor configures a size for that, it calls the listener with a scale the window does not draw at and then with the compositor's own. Each time it checks that the listener rebuilds nothing and fires onFrameOwed, that the next Render() takes the scale, with no swapchain and no onResize for the application's size and with a new swapchain and one onResize from inside Render() for the maximized one, and that a pointer motion to the surface's middle is at the buffers' middle, to within the rounding of one size from the other, before that Render() and after it, and that the pointer, resting across that Render(), is where its surface-local place comes to at the new scale. The log's checks hold each of those commits to its buffer at the scales the marks name.
2026-11-27 10:07:37 +01:00
- `Window` events, `Event<void>` unless noted: `onMouseMove` (then `currentMousePos`, `lastMousePos`, `mouseDelta`), `onMouseEnter` and `onMouseLeave` with `mouseInside` (native only: the DOM build declares the two events but never fires them, and has no `mouseInside`), `onMouseLeftClick`, `onMouseLeftHold`, `onMouseLeftRelease` and the right-button trio (`mouseLeftHeld`, `mouseRightHeld`), `onMouseScroll` (`Event<std::uint32_t>`: whole detents, reinterpret the payload as `int32`, positive is wheel down, every backend normalised to one per notch), `onRawKeyDown`, `onRawKeyHold`, `onRawKeyUp` (`Event<KeyCode>`, raw platform codes; `heldKeys`), `onTextInput` (`Event<const std::string_view>`, UTF-8; repeats are synthesised on Wayland), `onPreedit` and `onTextInputDelete` (input methods), `onTouchDown`, `onTouchMove`, `onTouchUp` (`Event<TouchPoint>`; the first finger also drives the pointer events), `onClose`, `onResize`, `onBeforeUpdate`, `onUpdate` (`Event<FrameTime>`: `now`, `delta`). On Wayland `lastInputTime` is the compositor's `time` of the pointer, touch or scroll event a listener is being invoked for (milliseconds from an undefined base, wrapping at 2^32, set before the event fires; an event the compositor sends without a time — an enter and the move that follows it, a leave, a touch cancel and its release — keeps the last one's): a consumer that dates gestures — a fling's velocity, a tap against a long press — reads it instead of its own clock at dispatch, since events queued while the loop was busy keep the times they happened at. A listener that dispatches Wayland events itself (it makes a `Window`, or calls `Clipboard::GetText`) has them set it too, for itself from there on and for the listeners of its event that come after it. The other backends have no such member. On Wayland `activated` and `suspended` are what the compositor says of the window's place on the screen (xdg_toplevel's states: it counts as the active window; it is not ordinarily being repainted — covered by another window, say, or its outputs switched off for a screen lock — which a compositor with an xdg_wm_base older than version 6 never says), and `onToplevelState` fires after a configure changed either, with both already set. Which of the two a lock screen or another window in front changes is the compositor's choice, so the test for "the user is looking at this window" — is the message it shows read? — is `activated && !suspended`; by it a window that is visible but not the active one is not looked at. The constructor takes the first configure before a listener can be added: read the two once after it, then follow the event. Both are false until a configure sets them, which that first one need not do. The other backends have neither member. `onFrameOwed`, Wayland's too, is the cue of a resize or a new scale for a window that draws on demand: see "A program, and what the loop does".
- Keys: `Key(CrafterKeys::Space)` is `consteval` and folds to the platform's raw code (a Win32 scancode, a Linux keycode), so bindings stay portable in source and compare against `onRawKeyDown`'s `KeyCode` at runtime. Bindings serialised with `Input::BindingToString` are platform-specific.
fix(wayland): keys come without text while no keymap has loaded, and a keymap that loads frees the one before Device::keyboard_keymap made no state for a keymap of another format than xkb_v1 or one it could not map: after such a first keymap the state stayed null, and keyboard_modifiers and keyboard_key passed it unchecked to libxkbcommon. For a keymap that did not compile, first or later, keyboard_keymap called xkb_state_new on the null keymap, which crashed (SIGSEGV) in the handler itself. Each keymap that loaded also made a context, a keymap and a state of its own, and released none of the earlier ones (#167). Device, keyboard_keymap: a keymap that does not load is ignored, which leaves the keymap and state there were. #167 has the earlier ones go once new ones exist, and the handler already left them for a keymap of another format or one it could not map; a context or a state that libxkbcommon fails to make is ignored the same way. A keymap that loads replaces the keymap and state and releases the earlier ones. Every keymap is compiled in one context, made with the first that is mapped: Device::xkb_context no longer gets one from a static initializer, and is null before that. Device, keyboard_key and keyboard_modifiers: without a state the key brings no text and the modifiers are only kept, so a key still fires onRawKeyDown and onRawKeyUp with the kernel's code, and only its onTextInput is lost. Device, the modifiers: a new state is set from the modifiers and group the compositor last sent. wayland.xml (1.26) keeps them in wl_keyboard's logical state, which the keymap is no part of: the modifiers event sets them and a leave resets them to zero. A state made for a keymap that came without a modifiers event started from none, so a Caps Lock that was on stopped typing capitals until the next modifiers event. keyboard_modifiers now keeps the values it was sent, keyboard_keymap sets a new state from them, and keyboard_leave zeroes them and sets the state from those zeros. Device, the statics: Device::xkb_keymap and xkb_state are freed when the next keymap loads, where the earlier ones leaked, so an application that reads them reads them at each use. Their comment and AGENTS.consumer.md say so, and when they are null. Tests: KeyboardKeymap (new) drives the wl_keyboard callbacks directly, with keymaps in memfds, on a default-constructed Window, each case in a child process. A first keymap of the no_keymap format, one whose fd cannot be mapped (a pipe's) and one that does not compile each have their fd closed and make no state, and a key after modifiers then fires onRawKeyDown and onRawKeyUp without text. After a keymap that loaded, each of the three leaves it in place, until one loads. A second keymap replaces the first in the same context, and on glibc 100 more leave less than 16 KiB more on the heap. Caps Lock carries into the state of a keymap that comes without modifiers, a leave clears it from the state and a state made after the leave has none, and modifiers sent before the first keymap apply to it. Run against the handlers before this change, with libxkbcommon 1.13.2, all seven cases fail: five die of signal 11 (SIGSEGV), the 100 keymaps leave 769056 bytes more on the heap and are not compiled in the first one's context, and the Caps Lock is kept through the leave and lost to the next keymap. Docs: the consumer notes say what a key brings without a keymap, that a keymap that does not load is ignored, and when Device::xkb_keymap and xkb_state are null and when they are freed. AGENTS.template.md names KeyboardKeymap among the tests that drive the Wayland listeners directly.
2026-11-26 09:25:11 +01:00
- On Wayland a key's `onTextInput` comes from the compositor's keymap. Without one that loaded, keys still fire `onRawKeyDown` and `onRawKeyUp`, without text; a keymap that does not load, such as one of the `no_keymap` format or one the libxkbcommon the application runs with cannot compile, is ignored and leaves the one there was. `Device::xkb_keymap` and `Device::xkb_state` are that keymap and its state, for reading keysyms or modifiers yourself (the XKB keycode is the `KeyCode` plus 8): null until a keymap loads, and freed when the next one loads, so read them at each use and check for null.
- `Input::Map`: `auto& jump = map.AddAction("Jump", Input::ActionType::Button);` (`Button`, `Axis1D`, `Vector2`), `jump.bindings = { Input::KeyBind{Key(CrafterKeys::Space)}, Input::GamepadButtonBind{id, Gamepad::Button::South} };` (also `MouseButtonBind`, `MouseScrollBind`, `MouseDeltaBind{scale}`, `GamepadAxisBind`, `GamepadStickBind{id, Gamepad::Stick::Left}`, `WASDBind{up, down, left, right}`), `map.Attach(window);`, and `map.Tick();` once per frame, after `Gamepad::Tick()`, which the loop runs before `onBeforeUpdate`. Every `Tick` recomputes the mouse delta and drains the scroll accumulator, and on Wayland `onBeforeUpdate` fires on every loop wake, so either tick from `onUpdate`, or tick in `onBeforeUpdate` and consume the delta and scroll actions in that same listener, as the Sponza example does. Read `action.pressed`, `value` or `vector2`, or subscribe to `onPerformed`, `onCanceled`, `onValueChanged`, `onVector2Changed`. `StartRebind(action, CaptureMask, callback)` captures the next input.
- `Gamepad::connected`, `onConnected`, `onDisconnected`, per-device `buttons[]`, `axes[]` and events, `Rumble(dev, low, high, duration)`, `FindById(id)`; buttons are named by position (`South`, `East`, `West`, `North`). `Clipboard::SetText(text)` and `GetText()` (`std::optional<std::string>`).
### WebGPU and the DOM build
The same C++ surface, with these differences:
- The `Window` is the page, and `Device::Initialize()` takes no arguments. Make the window `static`: `StartSync` hands control to `requestAnimationFrame` and `_Exit(0)`s without running static destructors, so nothing after it runs on any target. `StayAlive` is `StartSync` without the animation loop, for pages that only touch the DOM, and is `StartSync` natively. `Window::numFrames` is 1, so `tlases[0]` and `BuildTLAS(cmd, 0)`. `GraphicsCommandBuffer` is an opaque `std::uint32_t`.
- `GraphicsBuffer<T, true>::Create(count)`, `FlushDevice()` without a command buffer (`queue.writeBuffer`), `FlushDeviceRange`, `FlushDeviceSlot`, and `EnqueueReadback` with `PollReadback` for GPU to CPU. `Image2D<T>::Create(w, h)` is `rgba8unorm`, `Update(const CompressedTextureAsset&)` decompresses on the CPU, `AllocateSlot(heap)` registers it; `Image2DArray<T>` stacks layers with a CPU mip chain; `StorageImage2D` is a GPU-written float texture. `AllocateLinearClampSampler(heap)` and `AllocateLinearRepeatSampler(heap)`.
- `DispatchImages` has a six-argument overload with one texture and one sampler for the whole dispatch (WebGPU bind groups); the four-argument overload binds the font atlas instead. `DispatchFused` issues the four kernels in order through the four-argument overloads, so quads, circles and text match the Vulkan result but an images category does not: draw images with the six-argument `DispatchImages` on this backend.
- Custom compute in the UI pass: `WebGPUComputeShader::Load(wgslPath, bindings, rayQuery = false)`, where each `UICustomBinding` is `{group >= 2, binding, kind, format, pushOffset}` with `kind` one of `Buffer`, `SampledTexture`, `Sampler`, `SampledTextureArray`, `BufferReadWrite`, `StorageTexture`; the renderer reads the slot at `pushOffset` out of your push data and binds that handle. Group 0 binding 0 is the header uniform and group 1 the ping-pong images, both declared by your WGSL; with `rayQuery` true the library injects its own group 1 (the RT heap and the `rayQuery*` API) and your shader must not declare one. Standalone compute: `PlainComputeShader::Load(wgsl, pushUniformSize, bindings, rayQuery)` and `Dispatch(push, bytes, handles, gx, gy, gz)` run anywhere in the frame, `handles` parallel to `bindings`. It has no library bind groups: group 0 binding 0 is your optional push uniform (`pushUniformSize` bytes, 0 for none) and your bindings start at group 1, or at group 2 with `rayQuery`, which reserves group 1 the same way.
- Ray tracing is a library-built wavefront tracer composed from your WGSL stages: `WebGPUShader(fs::path("raygen.wgsl"), entryFn, WebGPURTStage::Raygen | Miss | ClosestHit | AnyHit | Intersection | Resolve)` (wrap the path: a bare string literal is ambiguous with the constructor that takes the source itself), with the entry signatures documented in `interfaces/Crafter.Graphics-ShaderBindingTableWebGPU.cppm`; `ShaderBindingTableWebGPU::Init`, `RTShaderGroup{.type = RTShaderGroupType::General | TrianglesHitGroup | ProceduralHitGroup, ...}`, `PipelineRTWebGPU::Init(cmd, raygen, miss, hit, sbt, bindings, hdrOutputFormat)`. Raygen calls `rtEmitPrimaryRay`; closest-hit and miss run in the SHADE stage and call `rtEmitRay` (continuation and shadow rays) and `rtAccumulate` (atomic, any number of rays per pixel). `RTPass` adds `maxDepth` (bounces), `raysPerPixel` (the ray buffer budget), `handlesPtr` and `handlesCount` (your bindings' handles) and `outTexHandle` (HDR output). `Mesh::Build`, `BuildProcedural` and `RenderingElement3D` keep their API, but `Refit` and the host-span `RefitProcedural` rebuild the host BVH under a new `blasAddr`: set `instance.accelerationStructureReference` again before the next `BuildTLAS`, or portable deforming-mesh code keeps tracing the old geometry here. Only the device-buffer `RefitProcedural` keeps the handle.
- `Crafter::Dom::HtmlElement` and `HtmlElementPtr` (move-only DOM handles with typed listeners), `Crafter::Router` (history, location, query parsing) and `Crafter::Dom::*Event` exist only here. `WebGPU::SetCanvasMount(elementId)` renders into an element instead of the page.
- Examples with a DOM build ship `.glsl` and `.wgsl` side by side; `RTStress`, `RayQueryPick`, `HDRBloom` and `RTMultiShadow` are WebGPU-only.
### Environment variables
All are "set to any value", read once at `Device::Initialize` or swapchain creation.
| Variable | Effect |
|---|---|
| `CRAFTER_GRAPHICS_VALIDATION` | The Khronos validation layer with GPU-assisted validation, plus info messages; off by default. `Device::validationErrorCount` counts the errors. |
| `CRAFTER_GRAPHICS_DEVICE=<n>` | Use GPU number `n` as Vulkan lists them, never another; an error when it can't run the application. |
| `CRAFTER_GRAPHICS_NO_DESCRIPTOR_HEAP` | Take the descriptor-set path on a driver that has the heap (and lose ray tracing), as a heap-less driver would. |
| `CRAFTER_GRAPHICS_NO_AS_WORKAROUND` | Turn the NVIDIA SPIR-V rewrite off, to check a new driver. |
| `CRAFTER_GRAPHICS_NO_VULKAN_1_4` | Create a Vulkan 1.3 instance on a 1.4 GPU. |
| `CRAFTER_PRESENT_IMMEDIATE` | Present immediately, uncapped, for benchmarks. |
### Testing a consumer
`Device::Initialize` on Linux connects to Wayland right after creating the instance, so even a windowless test needs a compositor (`WAYLAND_DISPLAY`). `Window::CaptureNextFrame(png)` followed by `Render()` writes a frame to read back and compare; decode it with a private copy of `stb_image.h` (`STB_IMAGE_STATIC`), since the library compiles only the writer. Assert `Device::validationErrorCount == 0` only when `CRAFTER_GRAPHICS_VALIDATION` is set, as the count stays zero without the layer. Return 77 (crafter-build's skip) when `!Device::rayTracingSupported` and the test needs it. A test with GPU work and no `Window` calls `vkQueueWaitIdle(Device::queue)` and `Device::DrainDeletions()` before it ends. The library's own `tests/` has one of each kind to copy.
### Examples to copy from
`HelloWindow` (a window), `HelloUI` (all three UI tiers, text, hit-testing), `CustomShader` (a Tier 1 shader in GLSL and WGSL, registered twice), `VulkanTriangle` (the smallest RT setup, raw descriptor writes), `Sponza` (`.cmesh` and `.ctex` through `Mesh::Build` and `Image2D`, texture arrays, a free camera on `Input::Map`), `RTVolume` (procedural geometry with intersection and any-hit shaders), `InputSystem` (actions, rebinding, gamepads), `HelloDom` (DOM and router, no GPU), `Decompression` (the asset round trip). All MIT.