Crafter.Graphics/interfaces/Crafter.Graphics-Window.cppm

798 lines
45 KiB
Text
Raw Normal View History

2026-07-22 18:09:06 +02:00
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
2025-05-07 19:21:51 +02:00
2025-11-17 00:44:45 +01:00
module;
2026-03-09 20:10:19 +01:00
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
2025-11-22 20:58:42 +01:00
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/input-event-codes.h>
2025-11-17 00:44:45 +01:00
#include <xkbcommon/xkbcommon.h>
#include "../lib/xdg-shell-client-protocol.h"
#include "../lib/wayland-xdg-decoration-unstable-v1-client-protocol.h"
2025-12-29 18:56:06 +01:00
#include "../lib/fractional-scale-v1.h"
#include "../lib/viewporter.h"
#include "../lib/text-input-unstable-v3-client-protocol.h"
2025-11-22 20:58:42 +01:00
#include <string.h>
#include <linux/input.h>
#include <sys/mman.h>
#include <wayland-cursor.h>
#include <errno.h>
#include <fcntl.h>
#include <print>
#include <wayland-client.h>
#include <wayland-client-protocol.h>
#endif
2026-05-18 02:07:48 +02:00
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
2026-03-02 23:53:13 +01:00
#include "vulkan/vulkan.h"
2026-05-18 02:07:48 +02:00
#endif
2026-04-02 16:52:10 +02:00
#ifdef CRAFTER_GRAPHICS_WINDOW_WIN32
#include <windows.h>
#endif
2025-11-17 00:44:45 +01:00
2025-04-16 00:43:33 +02:00
export module Crafter.Graphics:Window;
2025-11-16 15:32:11 +01:00
import std;
2025-11-23 04:04:53 +01:00
import :Types;
2026-05-12 00:24:48 +02:00
import :Keys;
2025-11-23 04:04:53 +01:00
import Crafter.Event;
2026-05-18 04:58:52 +02:00
#ifdef CRAFTER_GRAPHICS_WINDOW_DOM
import :WebGPU;
import :DescriptorHeapWebGPU;
#endif
2025-04-16 00:43:33 +02:00
export namespace Crafter {
2026-05-18 02:07:48 +02:00
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
2026-03-09 20:10:19 +01:00
struct Semaphores {
// Swap chain image presentation
VkSemaphore presentComplete;
// Command buffer submission and execution
VkSemaphore renderComplete;
};
2026-05-01 23:35:37 +02:00
struct RenderPass;
2026-04-05 22:53:59 +02:00
struct DescriptorHeapVulkan;
2026-05-18 04:58:52 +02:00
#else
struct RenderPass;
struct DescriptorHeapWebGPU;
2026-05-18 02:07:48 +02:00
#endif
2026-03-09 20:10:19 +01:00
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
// How a window hands finished frames to the display. Fifo waits for the
// display's refresh; it is the default and the one mode every surface
// has. Mailbox replaces a frame still waiting to be shown, so presenting
// never waits, which suits a window that updates on its own clock
// (Window::updateInterval). Immediate shows each frame at once and may
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
// tear. A mode the surface lacks falls back to Fifo. The mode decides how
// many images the swapchain has (Mesa's Mailbox needs at least four),
// which the frame loop takes as they come. In the browser the page
// presents the canvas and the mode has no effect.
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
enum class PresentMode {
Fifo,
Mailbox,
Immediate,
};
2026-03-09 20:10:19 +01:00
struct Window {
2026-01-30 00:09:37 +01:00
FrameTime currentFrameTime;
2026-03-09 20:10:19 +01:00
std::uint32_t width;
std::uint32_t height;
2025-11-25 18:52:32 +01:00
std::chrono::time_point<std::chrono::high_resolution_clock> lastFrameBegin;
2025-11-23 04:04:53 +01:00
Event<void> onClose;
Event<void> onBeforeUpdate;
2025-11-24 03:38:20 +01:00
Event<FrameTime> onUpdate;
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
// Fires when the swapchain has been recreated, for a new size or a
// new present mode. width/height already reflect the new size, and
// the old images have been destroyed: anything that holds one of
// them, or is sized after the window, is made again here. The heap
// slots that name the swapchain image follow by themselves (see
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// DescriptorHeapVulkan::AddSwapchainSlot). On Wayland a size the
// compositor configures is taken by the next Render(), so for that
// resize this fires from there, before the frame's onUpdate, and
// not from the configure's listener (see onFrameOwed).
2026-05-12 00:24:48 +02:00
Event<void> onResize;
2025-11-23 04:04:53 +01:00
bool open = true;
bool updating = false;
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
// Zero (the default): Update runs when the compositor's frame
// callback says the window is about to show a new frame, so it
// follows the display and stops while the window is hidden or
// minimized. Non-zero: Update runs on this clock instead, visible or
// not, for an app whose output goes somewhere besides the screen.
// Pair it with PresentMode::Mailbox so a present never waits on the
// display. Set it before StartUpdate. Native only: in the browser,
// requestAnimationFrame drives Update.
std::chrono::nanoseconds updateInterval{0};
// The mode SetPresentMode last asked for.
PresentMode presentMode = PresentMode::Fifo;
2026-05-12 00:24:48 +02:00
// Currently-pressed raw key codes. The runtime stores raw platform
// codes only (Win32 PS/2 scancode + extended bit; Wayland kernel
// keycode). Cross-platform default bindings use `Key(CrafterKeys::X)`
// from :Keys to obtain the right code at compile time.
std::unordered_set<KeyCode> heldKeys;
Event<KeyCode> onRawKeyDown;
Event<KeyCode> onRawKeyHold;
Event<KeyCode> onRawKeyUp;
2026-04-16 23:03:24 +02:00
Event<const std::string_view> onTextInput;
2026-03-09 20:10:19 +01:00
Event<void> onMouseRightClick;
Event<void> onMouseLeftClick;
Event<void> onMouseRightHold;
Event<void> onMouseLeftHold;
Event<void> onMouseRightRelease;
Event<void> onMouseLeftRelease;
Event<void> onMouseMove;
Event<void> onMouseEnter;
Event<void> onMouseLeave;
// Mouse wheel, in whole detents per event, sign packed into the
// uint32 payload (reinterpret as int32 to read it). Positive =
// wheel down / toward the user — the DOM deltaY sign. Every
// backend normalizes to ±1 per notch: dom-env.js divides
// WheelEvent deltas by the per-deltaMode detent size, Wayland
// divides the axis value by libinput's 15-units-per-detent,
// Win32 divides by WHEEL_DELTA. Sub-detent motion (smooth-scroll
fix(win32): restore mouse moves, add enter and leave, capture drags, and close and destroy windows cleanly Win32 - WM_MOUSEMOVE is handled again: c9ebd44 put the WM_CHAR case where it was, so currentMousePos stopped following the mouse and onMouseMove never fired. Positions are read signed (GET_X_LPARAM), since under capture they run past the client area. - onMouseEnter and onMouseLeave. The first move over the client area after a leave is the enter, and arms the TME_LEAVE whose WM_MOUSELEAVE is the leave. An enter counts only once that is armed, a leave only after an enter, and a move past the client area is a move only. - A press captures the mouse, so a drag that leaves the window still sends its moves and its release, as Wayland's implicit grab does. Losing the capture releases what is held, and a button-up without its press fires nothing. - WM_CLOSE fires onClose and clears open, as xdg_toplevel.close does, instead of destroying the HWND under the swapchain. WM_DESTROY no longer posts WM_QUIT, which nothing read. - ~Window detaches the HWND and destroys it. It stayed on screen, and its messages went to the freed Window. WndProc hands messages without a Window to DefWindowProc, and looks the Window up again after an event that more work follows, in case a listener destroyed it. - The constructor's message pump leaves input queued for StartSync: the WM_MOUSEMOVE sent when a window appears under the cursor made an onMouseEnter nobody could hear yet. The mouse state is reset before the platform code, no longer after it. - A window after the first finds its class registered, which showed an error box. - The wheel remainder is the window's, no longer a function static that every window shared, and a leave drops it. Window - PointerEnter, PointerMove, PointerLeave and PointerScroll hold the rules both native backends report the pointer by. An enter puts the entry position in currentMousePos before onMouseEnter fires, and is followed by a move, on Wayland too now. scrollRemainder replaces Device::scrollDetentRemainder, and mouseInside is shared. Tests - PointerEnterLeave: enter, move and leave through the wl_pointer callbacks. - PointerWin32: posts a real HWND the messages above and pumps them as StartSync does. Built for x86_64-w64-mingw32 it runs under Wine, and is skipped where Wine is not on PATH. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:29:50 +01:00
// touchpads, free-spinning wheels) is accumulated until a whole
// detent is reached — by PointerScroll natively, by dom-env.js in
// the browser — and dropped when the pointer leaves.
2025-12-30 23:28:38 +01:00
Event<std::uint32_t> onMouseScroll;
// Touch, from the seat's wl_touch. The first finger down also drives
// currentMousePos and the left-button events until it lifts, so a
// pointer-only application works on a touchscreen as it is.
Event<TouchPoint> onTouchDown;
Event<TouchPoint> onTouchMove;
Event<TouchPoint> onTouchUp;
Event<void> onTouchCancel;
std::int32_t primaryTouchId = -1;
// Text input (zwp_text_input_v3): the input method's composing text
// (an empty string clears it) and its deletions around the cursor;
// the text it commits arrives as onTextInput, like a key's.
Event<const std::string_view> onPreedit;
Event<TextDelete> onTextInputDelete;
2026-03-09 20:10:19 +01:00
Vector<float, 2> currentMousePos;
Vector<float, 2> lastMousePos;
Vector<float, 2> mouseDelta;
2025-11-23 04:04:53 +01:00
bool mouseLeftHeld = false;
bool mouseRightHeld = false;
2025-11-22 20:58:42 +01:00
fix(win32): restore mouse moves, add enter and leave, capture drags, and close and destroy windows cleanly Win32 - WM_MOUSEMOVE is handled again: c9ebd44 put the WM_CHAR case where it was, so currentMousePos stopped following the mouse and onMouseMove never fired. Positions are read signed (GET_X_LPARAM), since under capture they run past the client area. - onMouseEnter and onMouseLeave. The first move over the client area after a leave is the enter, and arms the TME_LEAVE whose WM_MOUSELEAVE is the leave. An enter counts only once that is armed, a leave only after an enter, and a move past the client area is a move only. - A press captures the mouse, so a drag that leaves the window still sends its moves and its release, as Wayland's implicit grab does. Losing the capture releases what is held, and a button-up without its press fires nothing. - WM_CLOSE fires onClose and clears open, as xdg_toplevel.close does, instead of destroying the HWND under the swapchain. WM_DESTROY no longer posts WM_QUIT, which nothing read. - ~Window detaches the HWND and destroys it. It stayed on screen, and its messages went to the freed Window. WndProc hands messages without a Window to DefWindowProc, and looks the Window up again after an event that more work follows, in case a listener destroyed it. - The constructor's message pump leaves input queued for StartSync: the WM_MOUSEMOVE sent when a window appears under the cursor made an onMouseEnter nobody could hear yet. The mouse state is reset before the platform code, no longer after it. - A window after the first finds its class registered, which showed an error box. - The wheel remainder is the window's, no longer a function static that every window shared, and a leave drops it. Window - PointerEnter, PointerMove, PointerLeave and PointerScroll hold the rules both native backends report the pointer by. An enter puts the entry position in currentMousePos before onMouseEnter fires, and is followed by a move, on Wayland too now. scrollRemainder replaces Device::scrollDetentRemainder, and mouseInside is shared. Tests - PointerEnterLeave: enter, move and leave through the wl_pointer callbacks. - PointerWin32: posts a real HWND the messages above and pumps them as StartSync does. Built for x86_64-w64-mingw32 it runs under Wine, and is skipped where Wine is not on PATH. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:29:50 +01:00
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
// The pointer is over the window: set before onMouseEnter fires,
// cleared before onMouseLeave does.
bool mouseInside = false;
// The part of a wheel detent PointerScroll has not reported yet.
double scrollRemainder = 0.0;
// The backends report the pointer through these, so that enter,
// move, leave and scroll mean the same on each. PointerEnter puts
// the entry position in currentMousePos before onMouseEnter fires,
// and an enter is a move too: the backend follows it with
// PointerMove. PointerLeave drops the scroll remainder, and fires
// only after an enter. Each fires its event last, since a listener
// may destroy the window, so a backend that makes a second call
// first checks that the window still exists.
void PointerEnter(Vector<float, 2> position);
void PointerMove(Vector<float, 2> position);
void PointerLeave();
// Adds wheel motion in detents, fractions included, and fires
// onMouseScroll for each whole detent it adds up to.
void PointerScroll(double detents);
#endif
2026-03-12 01:07:46 +01:00
Window() = default;
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 constructor that throws (a Vulkan error, a
// surface that offers no format the swapchain can be written through
// as a storage image) leaves nothing of the window behind: ~Window
// has released what it had made by the time the exception reaches
// the caller, so the error can be caught and the program go on
// (#169).
2026-03-09 20:10:19 +01:00
Window(std::uint32_t width, std::uint32_t height);
Window(std::uint32_t width, std::uint32_t height, const std::string_view title);
Window(Window&) = delete;
Window(Window&&) = delete;
Window& operator=(const Window&) = delete;
2026-05-18 02:07:48 +02:00
// DOM mode keeps a process-global pointer to the live Window so
// the JS bridge can deliver document/window events back. If the
// Window is destroyed (e.g. it was stack-allocated in main and
// main returned), the global must be cleared so subsequent
// browser callbacks become no-ops instead of dereferencing
// freed memory. Native builds release what the constructor made:
// after a device wait, the command buffers, semaphores and fences,
// the swapchain and the Vulkan surface, then (Wayland) the cursor,
// viewport, fractional scale, decoration, xdg toplevel, xdg surface
// and wl_surface, and the window leaves Device::windows and the
fix(win32): restore mouse moves, add enter and leave, capture drags, and close and destroy windows cleanly Win32 - WM_MOUSEMOVE is handled again: c9ebd44 put the WM_CHAR case where it was, so currentMousePos stopped following the mouse and onMouseMove never fired. Positions are read signed (GET_X_LPARAM), since under capture they run past the client area. - onMouseEnter and onMouseLeave. The first move over the client area after a leave is the enter, and arms the TME_LEAVE whose WM_MOUSELEAVE is the leave. An enter counts only once that is armed, a leave only after an enter, and a move past the client area is a move only. - A press captures the mouse, so a drag that leaves the window still sends its moves and its release, as Wayland's implicit grab does. Losing the capture releases what is held, and a button-up without its press fires nothing. - WM_CLOSE fires onClose and clears open, as xdg_toplevel.close does, instead of destroying the HWND under the swapchain. WM_DESTROY no longer posts WM_QUIT, which nothing read. - ~Window detaches the HWND and destroys it. It stayed on screen, and its messages went to the freed Window. WndProc hands messages without a Window to DefWindowProc, and looks the Window up again after an event that more work follows, in case a listener destroyed it. - The constructor's message pump leaves input queued for StartSync: the WM_MOUSEMOVE sent when a window appears under the cursor made an onMouseEnter nobody could hear yet. The mouse state is reset before the platform code, no longer after it. - A window after the first finds its class registered, which showed an error box. - The wheel remainder is the window's, no longer a function static that every window shared, and a leave drops it. Window - PointerEnter, PointerMove, PointerLeave and PointerScroll hold the rules both native backends report the pointer by. An enter puts the entry position in currentMousePos before onMouseEnter fires, and is followed by a move, on Wayland too now. scrollRemainder replaces Device::scrollDetentRemainder, and mouseInside is shared. Tests - PointerEnterLeave: enter, move and leave through the wl_pointer callbacks. - PointerWin32: posts a real HWND the messages above and pumps them as StartSync does. Built for x86_64-w64-mingw32 it runs under Wine, and is skipped where Wine is not on PATH. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:29:50 +01:00
// focus pointers, or (Win32) the HWND, detached from this Window
// first so that no message still meant for it arrives here — so a
// window can be closed and another created, which a resident app
// does on every hide and show.
2026-05-18 02:07:48 +02:00
~Window();
2025-11-22 20:58:42 +01:00
2026-08-05 04:08:13 +02:00
// Enter the platform event loop and never return. In DOM mode this
// hands the loop to requestAnimationFrame and _Exit(0)s so the wasm
// instance survives without running static destructors. No caller
// code after this point ever runs, on any target.
2026-03-09 20:10:19 +01:00
void StartSync();
2026-08-05 04:08:13 +02:00
// As StartSync, but does NOT start the animation-frame loop in DOM
// mode — for event-driven pages that only touch the DOM and never
// draw. A rAF tick running forever to do nothing costs battery in
// every open tab. Still never returns.
//
// On native this is identical to StartSync: the event loop is what
// keeps a window alive there, so there is no cheaper option. Call it
// unconditionally and get the browser saving without an #ifdef.
void StayAlive();
2026-03-09 20:10:19 +01:00
void StartUpdate();
void StopUpdate();
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
// Makes the swapchain again with the new mode and fires onResize, as
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 resize does, so call it outside StartInit/FinishInit. Called while
// a frame is being recorded (from onUpdate, a pass, an input action
// ticked there), the new swapchain is made once that frame has been
// presented: the frame still draws into an image of the old one. The
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
// environment variable CRAFTER_PRESENT_IMMEDIATE overrides the mode,
// for benchmarks.
void SetPresentMode(PresentMode mode);
2026-03-09 20:10:19 +01:00
void SetTitle(const std::string_view title);
// The xdg app id, which the compositor matches to a .desktop file
// for the icon, the task switcher and activation.
void SetAppId(const std::string_view id);
// Tells the compositor's input method that a text field has focus
// (an on-screen keyboard opens) and where its caret is, in physical
// pixels, or that none has. Remembered: it is applied again whenever
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
// the keyboard focus comes back to this window, and on Wayland
// whenever the window's scale changes, converted with the new one.
// `purpose` says what
feat(wayland): SetTextInput takes text-input-v3's purposes and its version 1 hints, and enables anew for a field of another kind Window::SetTextInput knew two purposes, Normal and Phone, and Device::ApplyTextInput chose the content hints from them: none for Phone, and completion, spellcheck and auto_capitalization for Normal. Nothing could send another purpose, or hidden_text or sensitive_data: a password field was Normal, with those three hints, or Phone. Types: TextInputPurpose has the fourteen content purposes of the bundled text-input-v3 protocol, in its order, so that the enumerators have the protocol's values; Phone was 1 and is 4. kTextInputHintNone and the ten kTextInputHint* bits are the content hints of version 1 of the protocol, the version Device binds the text input's manager at, with the protocol's values, and kTextInputHintMask is the ten together. TextInputDefaultHints(purpose) is what a field gets when the caller names no hints: the three Normal had, hidden_text and sensitive_data for Password and Pin, none for the other eleven. For Normal and Phone without hints that is the content type they had before. Window: SetTextInput takes the hints as a last, defaulted std::optional<std::uint32_t>, which tells kTextInputHintNone (no hints) from no argument (the purpose's defaults). It keeps only the bits of kTextInputHintMask: version 2's hints are not in version 1's enum. On Win32 and in the browser the call still does nothing. Device, ApplyTextInput: it sends the window's purpose and hints as they are. For a window whose field is enabled it compares them with the ones the enable in force went out with, which the window now keeps, and when either differs it sends an enable before the content type, where it sent the content type without one. The protocol, as bundled in lib/text-input-unstable-v3-client-protocol.h, says of set_content_type's values that "Subsequent attempts to update them may have no effect" and that they "remain valid until the next committed enable or disable request", and of enable that it "must be issued every time the focused text input changes to a new one, including within the current surface". The same text has an enable reset "the state associated with preedit_string, commit_string, and delete_surrounding_text events", so such an enable clears the pending flags and the record of the composing text the window was last told, as the disable path does (6f471ca), and fires no onPreedit. A call with the purpose and hints of the enable in force sends no enable, as before, also when it is for another field: the window does not know one field from another of the same purpose and hints, and a caller marks that move with SetTextInput(false) first. Device, text_input_done: a listener of onTextInputDelete, onTextInput or onPreedit may call SetTextInput, and the disable path's clearing then ran in the middle of a done that was still reading the pending flags and strings it clears: a disable from a listener of onPreedit cleared the string the listeners' string_view points into, and one from a listener of onTextInputDelete reset the flag the commit of the same done waited on, so that commit never reached onTextInput. The enable for a field of another kind clears the same values. A listener may also dispatch the display, as Clipboard::GetText and Window's constructor do, and the next done then ran inside the first, on pending values the first had not yet reset. The handler now moves a done out of the pending values as it arrives, onto a queue, and delivers from there: the deletion, then the commit, then the composing text. A done that arrives while another is being delivered waits on the queue for it, so the window hears the dones in the order they came. Only the dones wait: a key, pointer or touch event that the same dispatch brings still fires where it arrives, ahead of a done that waits, which the consumer notes now say. The commit goes out whatever a listener of the deletion called SetTextInput with. The composing text is reported only when nothing has overtaken it since its done arrived: textInputEpoch, a counter in Device.cpp, moves at a disable, at an enable for a field of another kind, at a leave and at every done, and the handler compares the value a done arrived with against the one after its commit's listeners. A listener may also destroy the window: ~Window calls Device::ForgetTextInputDones, which takes the window out of the queue's entries, the one being delivered among them, and the handler fires nothing more of those. A look-up of the address in Device::windows would take a window opened at that address in the meantime for the one destroyed. Tests: TextInputContent (new) makes the text input a proxy on a wl_display over a socketpair, as TitleWayland makes its proxies, reads the requests off the other end and calls the text input's listener callbacks itself. It checks the purposes and the hint constants against the bundled protocol header's values, the mask, and the default hints of the fourteen purposes; then, on the wire: nothing from a window the text input has not entered; an enable, the content type, the caret and a commit at the enter; no enable for a caret that moves; an enable with its own content type for the other thirteen purposes in turn, after which a composing text equal to the one before them reaches onPreedit again; named hints in place of the defaults; an enable for other hints under the same purpose; a version 2 hint (no_emoji) neither sent nor taken for a change; kTextInputHintNone sent as 0; the caret in surface coordinates at a scale of 2; one disable for a field losing the focus; no enable for a call for another field of the same purpose and hints, and one when a disable comes before it; and after a leave, nothing until the enter, which enables the field the window has by then. For the done, with two listeners on onTextInput and on onPreedit: a first listener of onPreedit that changes the purpose, or disables the field, and the listener after it are given the composing text as the input method sent it; after a listener of onTextInputDelete that changes the hints, or disables the field, the commit of the same done reaches both listeners of onTextInput and that done fires no onPreedit; a done fed from inside a listener of onTextInputDelete is delivered after the one that listener was called for, whose commit reaches the listeners of onTextInput before the fed one's; a done fed from inside a listener of onTextInput is delivered after that listener's done, whose own composing text is not reported; a leave fed from inside a listener of onTextInput is followed by no onPreedit for that done's composing text; and when a listener of onTextInputDelete feeds a done, destroys the window and puts another at its address, listed in Device::windows, neither onTextInput nor onPreedit fires on the new one. Docs: the consumer notes list the purposes and the hints, the default hints, what a call that changes either does to a composition under way, the SetTextInput(false) that marks a move to another field of the same purpose and hints, and the order the input method's dones are delivered in. AGENTS.template.md names TextInputContent among the tests that need no GPU.
2026-11-20 08:08:54 +01:00
// the field holds and `hints` how the input method treats it
// (kTextInputHint*, or-ed together); without hints the field gets
// its purpose's usual ones, TextInputDefaultHints(purpose). The input
// method takes a field's purpose and hints when the field is
// enabled, and a field of another kind is another field to it: a
// call that changes either while a field has focus enables anew,
// which ends the composition under way, as a disable does. A caret
// that moves within one field sends its rectangle alone, and so
// does a move to another field of the same purpose and hints, which
// the window cannot tell from it: mark that move with
// SetTextInput(false) before the new field's call.
void SetTextInput(bool active, std::int32_t x = 0, std::int32_t y = 0, std::int32_t width = 0, std::int32_t height = 0, TextInputPurpose purpose = TextInputPurpose::Normal, std::optional<std::uint32_t> hints = std::nullopt);
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
// Like SetPresentMode, a resize asked for while a frame is being
// recorded takes effect once that frame has been presented, width and
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// height included, which the rest of the frame still draws at. On
// Wayland the surface takes the new size with the first frame drawn
// at it, not here: until that frame is presented the compositor
// shows the last one at the size it was drawn at. And there the
// last size asked for is the one the window takes, whoever asked: a
// size the compositor configured that still waits for its frame
// gives way to this call, and a size this call left waiting gives
// way to a configure that comes after it.
2026-03-09 20:10:19 +01:00
void Resize(std::uint32_t width, std::uint32_t height);
void Render();
void Update();
2026-05-02 21:08:20 +02:00
// Replace the system cursor with a custom image. `pixels` is
// `width*height*4` bytes in R8G8B8A8 memory order (matching
// stb_image's STBI_rgb_alpha output) with straight (non-premultiplied)
// alpha — the conversion to the compositor's expected format is
// handled internally. The hotspot is in image-pixel coordinates.
// Re-callable at any time.
void SetCursorImage(std::uint16_t width, std::uint16_t height,
std::uint16_t hotspotX, std::uint16_t hotspotY,
const std::uint8_t* pixels);
// Restore the default system cursor (releases any previously-uploaded
// cursor pixel buffer).
void SetDefaultCursor();
2026-03-09 20:10:19 +01:00
#ifdef CRAFTER_TIMING
std::chrono::nanoseconds totalUpdate;
std::vector<std::pair<const EventListener<FrameTime>*, std::chrono::nanoseconds>> updateTimings;
std::chrono::nanoseconds totalRender;
std::chrono::nanoseconds vblank;
std::chrono::nanoseconds totalFrame;
std::chrono::time_point<std::chrono::high_resolution_clock> frameEnd;
// Fixed-size ring buffer of the most recent frame times. LogTiming does
// order-independent sum/avg/min/max, so head position is irrelevant to
// the reported stats; this avoids the per-frame memmove a vector::erase
// at the front would incur once full.
static constexpr std::size_t frameTimeCapacity = 100;
std::array<std::chrono::nanoseconds, frameTimeCapacity> frameTimes{};
std::size_t frameTimesHead = 0;
std::size_t frameTimesCount = 0;
2026-03-09 20:10:19 +01:00
void LogTiming();
#endif
2025-11-22 20:58:42 +01:00
2026-04-02 16:52:10 +02:00
#ifdef CRAFTER_GRAPHICS_WINDOW_WIN32
fix(win32): restore mouse moves, add enter and leave, capture drags, and close and destroy windows cleanly Win32 - WM_MOUSEMOVE is handled again: c9ebd44 put the WM_CHAR case where it was, so currentMousePos stopped following the mouse and onMouseMove never fired. Positions are read signed (GET_X_LPARAM), since under capture they run past the client area. - onMouseEnter and onMouseLeave. The first move over the client area after a leave is the enter, and arms the TME_LEAVE whose WM_MOUSELEAVE is the leave. An enter counts only once that is armed, a leave only after an enter, and a move past the client area is a move only. - A press captures the mouse, so a drag that leaves the window still sends its moves and its release, as Wayland's implicit grab does. Losing the capture releases what is held, and a button-up without its press fires nothing. - WM_CLOSE fires onClose and clears open, as xdg_toplevel.close does, instead of destroying the HWND under the swapchain. WM_DESTROY no longer posts WM_QUIT, which nothing read. - ~Window detaches the HWND and destroys it. It stayed on screen, and its messages went to the freed Window. WndProc hands messages without a Window to DefWindowProc, and looks the Window up again after an event that more work follows, in case a listener destroyed it. - The constructor's message pump leaves input queued for StartSync: the WM_MOUSEMOVE sent when a window appears under the cursor made an onMouseEnter nobody could hear yet. The mouse state is reset before the platform code, no longer after it. - A window after the first finds its class registered, which showed an error box. - The wheel remainder is the window's, no longer a function static that every window shared, and a leave drops it. Window - PointerEnter, PointerMove, PointerLeave and PointerScroll hold the rules both native backends report the pointer by. An enter puts the entry position in currentMousePos before onMouseEnter fires, and is followed by a move, on Wayland too now. scrollRemainder replaces Device::scrollDetentRemainder, and mouseInside is shared. Tests - PointerEnterLeave: enter, move and leave through the wl_pointer callbacks. - PointerWin32: posts a real HWND the messages above and pumps them as StartSync does. Built for x86_64-w64-mingw32 it runs under Wine, and is skipped where Wine is not on PATH. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:29:50 +01:00
HWND hwnd = nullptr;
2026-04-02 16:52:10 +02:00
HBITMAP cursorBitmap = nullptr;
HCURSOR cursorHandle = nullptr;
std::uint16_t cursorSizeX = 0;
std::uint16_t cursorSizeY = 0;
#endif
2026-03-09 20:10:19 +01:00
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
feat(wayland): add Window::lastInputTime, the compositor's time of a pointer or touch event The pointer and touch handlers received wl_pointer's and wl_touch's `time` and dropped it, so a consumer could date an event only by its own clock at dispatch. Events queued while the consumer's loop is busy are dispatched together when it comes back, so by that clock a swipe's backlog is a burst, and a press and its release that both waited out a stall happen at one time. Window::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: the button events, a motion's onMouseMove, onMouseScroll, onTouchDown, onTouchMove and onTouchUp, and the pointer events the first finger stands in for. An event the compositor sends without a time keeps the last one's: an enter's onMouseEnter and the move that follows it, onMouseLeave, and a touch_cancel's release and onTouchCancel. A listener that dispatches Wayland events itself (it makes a Window, or calls Clipboard::GetText) runs the handlers of what is queued behind its event, and they set the time too: for that listener from there on, and for the listeners of its event that come after it. The click, move and release the first finger stands in for fire after the touch event's listeners, so the touch handlers set the time again before them. The member is the Wayland backend's alone: the Win32 and DOM handlers set no such time, and design rule 1 keeps the library from "inventing a shared signature that is a no-op on one side". Those builds have no such member, and the consumer notes say so. Tests: InputTime drives the wl_pointer and wl_touch handlers directly, as MouseScroll and PointerEnterLeave do, and reads lastInputTime in every listener: 0 before the first event; each event's own time for a motion, the four button events, a scroll and a touch's down, motion and up; the touch's time for the first finger's click, move and release, also when a listener of the touch event has run another handler in between, as a dispatch from inside it would; the last event's time for an enter and its move, a leave, and a cancel's release and onTouchCancel; a time past 2^31 and the one after the wrap as they came.
2026-11-02 16:01:32 +01:00
// The compositor's time of the pointer, touch or scroll event a
// listener is being invoked for: wl_pointer's and wl_touch's `time`,
// milliseconds from an undefined base, wrapping at 2^32, set before
// the event fires. A consumer that dates its gestures reads this,
// not its own clock at dispatch: events queued while the loop was
// busy keep the times they happened at, so a backlog is not read as
// a burst. An event the compositor sends without a time keeps the
// last one's: an enter's onMouseEnter and the move that follows it,
// onMouseLeave, and a touch_cancel's release and onTouchCancel. 0
// before the first event that has one. 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
// pointer events the first finger stands in for are given the
// touch's time again.
std::uint32_t lastInputTime = 0;
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
// The pointer's position as the compositor last gave it, in
// surface-local units: a motion's, an enter's, the first finger's,
// which stands in for the pointer. A new scale does not move it,
// where it takes currentMousePos, which is it in pixels, along
// (MatchSizesToScale), and Input::Map takes the pointer's delta from
// it, so that a pointer that rests reads none whatever scales the
// window took between two of its Ticks. A position the application
// writes into currentMousePos itself is not in it.
Vector<float, 2> surfaceMousePos{ 0.0f, 0.0f };
feat(wayland): add Window::lastInputTime, the compositor's time of a pointer or touch event The pointer and touch handlers received wl_pointer's and wl_touch's `time` and dropped it, so a consumer could date an event only by its own clock at dispatch. Events queued while the consumer's loop is busy are dispatched together when it comes back, so by that clock a swipe's backlog is a burst, and a press and its release that both waited out a stall happen at one time. Window::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: the button events, a motion's onMouseMove, onMouseScroll, onTouchDown, onTouchMove and onTouchUp, and the pointer events the first finger stands in for. An event the compositor sends without a time keeps the last one's: an enter's onMouseEnter and the move that follows it, onMouseLeave, and a touch_cancel's release and onTouchCancel. A listener that dispatches Wayland events itself (it makes a Window, or calls Clipboard::GetText) runs the handlers of what is queued behind its event, and they set the time too: for that listener from there on, and for the listeners of its event that come after it. The click, move and release the first finger stands in for fire after the touch event's listeners, so the touch handlers set the time again before them. The member is the Wayland backend's alone: the Win32 and DOM handlers set no such time, and design rule 1 keeps the library from "inventing a shared signature that is a no-op on one side". Those builds have no such member, and the consumer notes say so. Tests: InputTime drives the wl_pointer and wl_touch handlers directly, as MouseScroll and PointerEnterLeave do, and reads lastInputTime in every listener: 0 before the first event; each event's own time for a motion, the four button events, a scroll and a touch's down, motion and up; the touch's time for the first finger's click, move and release, also when a listener of the touch event has run another handler in between, as a dispatch from inside it would; the last event's time for an enter and its move, a leave, and a cancel's release and onTouchCancel; a time past 2^31 and the one after the wrap as they came.
2026-11-02 16:01:32 +01:00
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
// Wakes the event loop when `fd` becomes readable and calls
// `onReadable` from it, which must consume what made the descriptor
// readable, or the loop wakes again at once. For a socket, or an
// eventfd another thread signals, so new data can drive an Update
// right away (call Update from the callback) instead of waiting for
// the next one. StartSync's loop serves the descriptors of every
// window. Remove a descriptor before closing it.
void AddPollFd(int fd, std::function<void()> onReadable);
void RemovePollFd(int fd);
struct PollFd {
int fd;
std::function<void()> onReadable;
};
std::vector<PollFd> pollFds;
feat(wayland): keep xdg_toplevel's activated and suspended states on the window A consumer could not tell a window somebody is looking at from one that merely exists. The compositor's word on it comes with every xdg_toplevel configure — the `activated` state, and since version 6 of xdg_wm_base `suspended`, "not ordinarily being repainted", for example for a content covered by another window or outputs switched off for a screen lock — and the window dropped the states array. A messenger built on it took a conversation left open behind a lock screen or another application for one that was being read: its texts were marked read and never notified. Window: `activated` and `suspended` hold the two states, and onToplevelState fires after a configure changed either, with both already set. They are batched as the size is: xdg_toplevel.configure leaves them pending and the xdg_surface.configure that ends the batch applies them (ApplyToplevelState) last, so the handler does nothing with the window after its listeners. The constructor takes the first configure before a listener can be added, so a consumer reads the two once after it. Both are reported and the library combines nothing: which of the two a lock screen or another window in front changes is the compositor's choice, so a consumer that asks whether the user is looking at the window wants `activated && !suspended`, and the consumer notes say so. The members are the Wayland backend's; the Win32 and DOM backends keep no such state. Device: xdg_wm_base is bound at the version the compositor offers, up to 6, where it was bound at 1: `suspended` does not exist below 6 (`activated` is version 1's). Every request the windows make is version 1's. Besides `suspended`, the higher versions bring the window state values it passes over (the tiled ones, 2) and two events, xdg_toplevel's configure_bounds (4) and wm_capabilities (5), which the toplevel's listener takes and drops, since libwayland aborts a client at an event whose handler is null. Tests: ToplevelState feeds the two configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as TitleWayland makes them, and reads the bind off the wire: the states pending until the surface's configure, the last toplevel configure of a batch applied, one event for a batch that changes both, none for a repeat or for other states, an empty array clearing both; an offer of 7, 6, 5 and 1 bound at 6, 6, 5 and 1; a handler in the xdg_wm_base, xdg_surface and xdg_toplevel listeners for every event of the bundled protocol.
2026-11-17 00:49:53 +01:00
// What the compositor says of the window's place on the screen, as
// xdg_toplevel's states give it. `activated`: it counts as the
// active window (no promise of keyboard or pointer focus).
// `suspended`: it is not ordinarily being repainted — the
// protocol's examples are a content covered by another window and
// outputs switched off for a screen lock; the state came with
// version 6 of xdg_wm_base, so under a compositor with an older
// one it stays false. Which of the two a lock screen or another
// window in front changes is the compositor's own choice, so a
// consumer that asks whether the user is looking at the window
// (is the message it shows read?) wants `activated && !suspended`.
// Both are false until a configure sets them, which a new window's
// first one need not do. onToplevelState fires after a configure
// changed either, with both already set; the constructor takes the
// first configure before a listener can be added, so a consumer
// reads the two once after it.
bool activated = false;
bool suspended = false;
Event<void> onToplevelState;
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// Fires after a configure that leaves the window owing the
// compositor a frame: it asked for a size the window does not have,
// or it came while the surface does not show the window as it is
// yet (a swapchain waits for its first frame). Nothing has been
// rebuilt by then. The next Render() makes the swapchain again at
// the new size, fires onResize, and presents a frame whose commit
// carries that buffer, the surface's new size and the configure's
// acknowledgement, so the surface changes size with the first
// buffer drawn for the new one and not before (#199), and a Vulkan
// error at the resize comes out of Render(), not out of the
// configure's listener (#200). Until that frame the compositor
// waits: the window keeps its old size on screen. A window that
// updates from StartUpdate draws it at its next frame callback, or
// on its clock. One that draws on demand asks for a frame here, as
// it does from onResize: this is where it learns of the resize,
// since onResize comes with the frame, and does not come at all
// where the new size takes the pixels the swapchain has (the scale
// changed with it). Fires for every such configure, also when a
// frame was owed already, and after onToplevelState, with the
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
// configure's states set. It fires in the same way after a
// preferred scale that is not the one the window draws at: a frame
// boundary of Render() takes that scale (see preferredScale), with
// new pixels and onResize for a window the compositor sized where
// they differ, with the surface's new size and no onResize for one
// the application sized (#165). And it fires from the event dispatch
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// wherever that runs, which may be inside a frame that is being
// recorded (a listener of that frame made a window or read the
// clipboard): a listener notes that a frame is wanted and leaves
// the drawing to its loop, since Update() must not be called from
// inside a frame.
Event<void> onFrameOwed;
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
// The scale the window draws at: the buffers' pixels per
// surface-local unit, which width x height and logicalWidth x
// logicalHeight were last worked out with (MatchSizesToScale). The
// pointer's and the touches' positions are turned into pixels with
// it, and the caret SetTextInput gives back into surface-local
// units, so that they are in the units of the frames drawn at it.
// Where it changes, the positions the window holds in pixels go to
// the new one (currentMousePos, lastMousePos, mouseDelta, the
// fingers down; surfaceMousePos, the compositor's, stays, and
// Input::Map takes its delta from that), as the compositor sends
// nothing for a pointer or a finger that rests, and the caret goes
// to the input method again, converted with it. It changes only
// where the two sizes are worked out (MatchSizesToScale): in the
// constructor, at the start of a frame, and elsewhere only where it
// gives the window new pixels. 1 where the compositor has no
// wp_fractional_scale_v1 or no wp_viewporter.
2026-05-01 23:35:37 +02:00
float scale = 1.0f;
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
// The scale the compositor asked for last, as
// wp_fractional_scale_v1's preferred_scale sends it: in 120ths, so
// 120 is a scale of 1. Its listener only keeps it. The window takes
// it into `scale` at the start of the next frame, and draws and
// converts input at the scale before until then (#165), and sooner
// 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 the present of the frame whose listener dispatched it
// or with the swapchain a SetPresentMode makes outside a frame. The
// constructor takes one named before the first swapchain. 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, as before (MatchSizesToScale).
std::uint32_t preferredScale = 120;
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
// The scale the window draws at in 120ths, as `scale` holds it in
// float: what MatchSizesToScale works the two sizes out with,
// exactly, also while a new scale waits in preferredScale.
std::uint32_t drawnScale_ = 120;
2025-11-23 04:04:53 +01:00
bool configured = false;
2026-05-12 00:24:48 +02:00
// Pending size from the most recent xdg_toplevel.configure, in
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// surface-local (logical DP) units, until the xdg_surface.configure
// that ends its batch; 0 means "compositor has no preference, keep
// current".
2026-05-12 00:24:48 +02:00
std::int32_t pendingLogicalWidth = 0;
std::int32_t pendingLogicalHeight = 0;
feat(wayland): keep xdg_toplevel's activated and suspended states on the window A consumer could not tell a window somebody is looking at from one that merely exists. The compositor's word on it comes with every xdg_toplevel configure — the `activated` state, and since version 6 of xdg_wm_base `suspended`, "not ordinarily being repainted", for example for a content covered by another window or outputs switched off for a screen lock — and the window dropped the states array. A messenger built on it took a conversation left open behind a lock screen or another application for one that was being read: its texts were marked read and never notified. Window: `activated` and `suspended` hold the two states, and onToplevelState fires after a configure changed either, with both already set. They are batched as the size is: xdg_toplevel.configure leaves them pending and the xdg_surface.configure that ends the batch applies them (ApplyToplevelState) last, so the handler does nothing with the window after its listeners. The constructor takes the first configure before a listener can be added, so a consumer reads the two once after it. Both are reported and the library combines nothing: which of the two a lock screen or another window in front changes is the compositor's choice, so a consumer that asks whether the user is looking at the window wants `activated && !suspended`, and the consumer notes say so. The members are the Wayland backend's; the Win32 and DOM backends keep no such state. Device: xdg_wm_base is bound at the version the compositor offers, up to 6, where it was bound at 1: `suspended` does not exist below 6 (`activated` is version 1's). Every request the windows make is version 1's. Besides `suspended`, the higher versions bring the window state values it passes over (the tiled ones, 2) and two events, xdg_toplevel's configure_bounds (4) and wm_capabilities (5), which the toplevel's listener takes and drops, since libwayland aborts a client at an event whose handler is null. Tests: ToplevelState feeds the two configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as TitleWayland makes them, and reads the bind off the wire: the states pending until the surface's configure, the last toplevel configure of a batch applied, one event for a batch that changes both, none for a repeat or for other states, an empty array clearing both; an offer of 7, 6, 5 and 1 bound at 6, 6, 5 and 1; a handler in the xdg_wm_base, xdg_surface and xdg_toplevel listeners for every event of the bundled protocol.
2026-11-17 00:49:53 +01:00
// The states of that configure, batched like its size:
// ApplyToplevelState makes them the window's at the
// xdg_surface.configure that ends the batch and fires
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// onToplevelState when that changed one.
feat(wayland): keep xdg_toplevel's activated and suspended states on the window A consumer could not tell a window somebody is looking at from one that merely exists. The compositor's word on it comes with every xdg_toplevel configure — the `activated` state, and since version 6 of xdg_wm_base `suspended`, "not ordinarily being repainted", for example for a content covered by another window or outputs switched off for a screen lock — and the window dropped the states array. A messenger built on it took a conversation left open behind a lock screen or another application for one that was being read: its texts were marked read and never notified. Window: `activated` and `suspended` hold the two states, and onToplevelState fires after a configure changed either, with both already set. They are batched as the size is: xdg_toplevel.configure leaves them pending and the xdg_surface.configure that ends the batch applies them (ApplyToplevelState) last, so the handler does nothing with the window after its listeners. The constructor takes the first configure before a listener can be added, so a consumer reads the two once after it. Both are reported and the library combines nothing: which of the two a lock screen or another window in front changes is the compositor's choice, so a consumer that asks whether the user is looking at the window wants `activated && !suspended`, and the consumer notes say so. The members are the Wayland backend's; the Win32 and DOM backends keep no such state. Device: xdg_wm_base is bound at the version the compositor offers, up to 6, where it was bound at 1: `suspended` does not exist below 6 (`activated` is version 1's). Every request the windows make is version 1's. Besides `suspended`, the higher versions bring the window state values it passes over (the tiled ones, 2) and two events, xdg_toplevel's configure_bounds (4) and wm_capabilities (5), which the toplevel's listener takes and drops, since libwayland aborts a client at an event whose handler is null. Tests: ToplevelState feeds the two configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as TitleWayland makes them, and reads the bind off the wire: the states pending until the surface's configure, the last toplevel configure of a batch applied, one event for a batch that changes both, none for a repeat or for other states, an empty array clearing both; an offer of 7, 6, 5 and 1 bound at 6, 6, 5 and 1; a handler in the xdg_wm_base, xdg_surface and xdg_toplevel listeners for every event of the bundled protocol.
2026-11-17 00:49:53 +01:00
bool pendingActivated = false;
bool pendingSuspended = false;
void ApplyToplevelState();
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// The surface's size, in surface-local units: what the viewport's
// destination is, or becomes with the next frame
// (SendFrameSurfaceState). It is state of its own beside width and
// height, the size of the buffers, and not worked back from them
// when it is sent: the scale may have changed since they were
// worked out, and for a size the compositor configured the two
// roundings, there and back, land above it wherever the size times
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
// the scale has a fraction of a half or more, short of the 32-bit
// limits the two sums stop at (#201).
// logicalConfigured says which of the two sizes the window was
// given. True: a configure gave this one, and it is that size
// unchanged, with width and height the pixels it came to when they
// were last worked out (MatchSizesToScale). False: the application
// gave width and height (the constructor's size, a Resize), and
// this is what they came to. Without a viewport the scale stays 1
// and the two sizes are the same numbers.
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
std::int32_t logicalWidth = 0;
std::int32_t logicalHeight = 0;
bool logicalConfigured = false;
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
// Before a swapchain is made, and where a frame boundary takes a
// configured size or a new scale: works the size the window was not
// given out of the one it was, at the scale it draws at, which it
// first makes the one the compositor asked for last (preferredScale
// into scale) where takeScale says so (the start of a frame, the
// constructor) or the scale gives the window new pixels (see
// preferredScale). A window the compositor sized keeps
// logicalWidth x logicalHeight and takes the pixels for it, one the
// application sized keeps its pixels and takes the surface-local
// size they come to. So a new scale reaches the buffers, or the
// surface, without moving a configured window off the size the
// compositor gave it. Where the scale changes, it also takes the
// positions the window holds in pixels to the new one and sends the
// caret again (see scale). No Vulkan call.
void MatchSizesToScale(bool takeScale);
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// The destination last sent to the viewport, 0 before the first.
// Where logicalWidth x logicalHeight differs from it, the surface
// is still to take its size, with the next frame.
std::int32_t sentLogicalWidth = 0;
std::int32_t sentLogicalHeight = 0;
// The size the last configure asked for, in surface-local units,
// while the window does not have it; 0 when none waits. The
// listener only keeps it, and TakeDeferredSize makes it the
// window's when Render() takes it, with the pixels it comes to at
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
// the scale the compositor has asked for by then. A configure for
// the size the window has clears it, and so does a Resize, which is
// then the later word; a configure without a size leaves it.
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
std::int32_t deferredLogicalWidth = 0;
std::int32_t deferredLogicalHeight = 0;
// The configure waiting for the frame that honours it, the last one
// when several came: acknowledging it says that the next commit
// answers it, and the commits before that frame's still show the
// old size (the listener's own, a consumer's request for a frame
// callback). SendFrameSurfaceState acknowledges it once no size
// waits any more. A configure that asks for nothing new while
// nothing is owed is acknowledged in the listener.
std::optional<std::uint32_t> unackedConfigure;
// The swapchainGeneration of the swapchain the last presented frame
// was drawn into: while it is not the current one, the surface
// still shows a buffer of the swapchain before (or nothing yet),
// and a configure that comes then waits for the current one's
// first frame.
std::uint64_t presentedGeneration = 0;
// Before a frame's present: the requests whose state that present's
// commit applies together with the frame's buffer. The viewport's
// destination, when the surface's size is not the one last sent (a
// new size, the window's first frame): logicalWidth x
// logicalHeight as they are, whatever the scale is by now. Set any
// earlier, the next commit would scale the buffer still attached
// to it (#199). And the acknowledgement of unackedConfigure, unless
// a size still waits, which a frame recorded before it came does
// not honour. Sends nothing else and does not commit.
void SendFrameSurfaceState();
2025-11-23 04:04:53 +01:00
xdg_toplevel* xdgToplevel = nullptr;
zxdg_toplevel_decoration_v1* decoration = nullptr;
2025-12-29 18:56:06 +01:00
wp_viewport* wpViewport = nullptr;
2025-11-23 04:04:53 +01:00
wl_surface* surface = nullptr;
xdg_surface* xdgSurface = nullptr;
wl_callback* cb = nullptr;
2026-03-12 01:07:46 +01:00
wl_surface* cursorSurface = nullptr;
wl_buffer* cursorWlBuffer = nullptr;
std::uint32_t cursorBufferOldSize = 0;
2026-05-02 21:08:20 +02:00
// mmap'd view of the SHM cursor buffer — the user-supplied pixels
// are written here in BGRA8888 order. Lifetime matches cursorWlBuffer.
std::uint8_t* cursorMmap_ = nullptr;
std::uint16_t cursorHotspotX_ = 0;
std::uint16_t cursorHotspotY_ = 0;
// Most recent serial from a wl_pointer.enter on this window's surface.
// Needed so `SetCursorImage` can re-issue `wl_pointer_set_cursor`
// mid-session (the hotspot only updates when set_cursor is recalled).
std::uint32_t lastPointerSerial_ = 0;
bool textInputActive_ = false;
bool textInputEnabled_ = false; // enable sent and not taken back since
std::int32_t textInputRect_[4] = { 0, 0, 0, 0 };
TextInputPurpose textInputPurpose_ = TextInputPurpose::Normal;
feat(wayland): SetTextInput takes text-input-v3's purposes and its version 1 hints, and enables anew for a field of another kind Window::SetTextInput knew two purposes, Normal and Phone, and Device::ApplyTextInput chose the content hints from them: none for Phone, and completion, spellcheck and auto_capitalization for Normal. Nothing could send another purpose, or hidden_text or sensitive_data: a password field was Normal, with those three hints, or Phone. Types: TextInputPurpose has the fourteen content purposes of the bundled text-input-v3 protocol, in its order, so that the enumerators have the protocol's values; Phone was 1 and is 4. kTextInputHintNone and the ten kTextInputHint* bits are the content hints of version 1 of the protocol, the version Device binds the text input's manager at, with the protocol's values, and kTextInputHintMask is the ten together. TextInputDefaultHints(purpose) is what a field gets when the caller names no hints: the three Normal had, hidden_text and sensitive_data for Password and Pin, none for the other eleven. For Normal and Phone without hints that is the content type they had before. Window: SetTextInput takes the hints as a last, defaulted std::optional<std::uint32_t>, which tells kTextInputHintNone (no hints) from no argument (the purpose's defaults). It keeps only the bits of kTextInputHintMask: version 2's hints are not in version 1's enum. On Win32 and in the browser the call still does nothing. Device, ApplyTextInput: it sends the window's purpose and hints as they are. For a window whose field is enabled it compares them with the ones the enable in force went out with, which the window now keeps, and when either differs it sends an enable before the content type, where it sent the content type without one. The protocol, as bundled in lib/text-input-unstable-v3-client-protocol.h, says of set_content_type's values that "Subsequent attempts to update them may have no effect" and that they "remain valid until the next committed enable or disable request", and of enable that it "must be issued every time the focused text input changes to a new one, including within the current surface". The same text has an enable reset "the state associated with preedit_string, commit_string, and delete_surrounding_text events", so such an enable clears the pending flags and the record of the composing text the window was last told, as the disable path does (6f471ca), and fires no onPreedit. A call with the purpose and hints of the enable in force sends no enable, as before, also when it is for another field: the window does not know one field from another of the same purpose and hints, and a caller marks that move with SetTextInput(false) first. Device, text_input_done: a listener of onTextInputDelete, onTextInput or onPreedit may call SetTextInput, and the disable path's clearing then ran in the middle of a done that was still reading the pending flags and strings it clears: a disable from a listener of onPreedit cleared the string the listeners' string_view points into, and one from a listener of onTextInputDelete reset the flag the commit of the same done waited on, so that commit never reached onTextInput. The enable for a field of another kind clears the same values. A listener may also dispatch the display, as Clipboard::GetText and Window's constructor do, and the next done then ran inside the first, on pending values the first had not yet reset. The handler now moves a done out of the pending values as it arrives, onto a queue, and delivers from there: the deletion, then the commit, then the composing text. A done that arrives while another is being delivered waits on the queue for it, so the window hears the dones in the order they came. Only the dones wait: a key, pointer or touch event that the same dispatch brings still fires where it arrives, ahead of a done that waits, which the consumer notes now say. The commit goes out whatever a listener of the deletion called SetTextInput with. The composing text is reported only when nothing has overtaken it since its done arrived: textInputEpoch, a counter in Device.cpp, moves at a disable, at an enable for a field of another kind, at a leave and at every done, and the handler compares the value a done arrived with against the one after its commit's listeners. A listener may also destroy the window: ~Window calls Device::ForgetTextInputDones, which takes the window out of the queue's entries, the one being delivered among them, and the handler fires nothing more of those. A look-up of the address in Device::windows would take a window opened at that address in the meantime for the one destroyed. Tests: TextInputContent (new) makes the text input a proxy on a wl_display over a socketpair, as TitleWayland makes its proxies, reads the requests off the other end and calls the text input's listener callbacks itself. It checks the purposes and the hint constants against the bundled protocol header's values, the mask, and the default hints of the fourteen purposes; then, on the wire: nothing from a window the text input has not entered; an enable, the content type, the caret and a commit at the enter; no enable for a caret that moves; an enable with its own content type for the other thirteen purposes in turn, after which a composing text equal to the one before them reaches onPreedit again; named hints in place of the defaults; an enable for other hints under the same purpose; a version 2 hint (no_emoji) neither sent nor taken for a change; kTextInputHintNone sent as 0; the caret in surface coordinates at a scale of 2; one disable for a field losing the focus; no enable for a call for another field of the same purpose and hints, and one when a disable comes before it; and after a leave, nothing until the enter, which enables the field the window has by then. For the done, with two listeners on onTextInput and on onPreedit: a first listener of onPreedit that changes the purpose, or disables the field, and the listener after it are given the composing text as the input method sent it; after a listener of onTextInputDelete that changes the hints, or disables the field, the commit of the same done reaches both listeners of onTextInput and that done fires no onPreedit; a done fed from inside a listener of onTextInputDelete is delivered after the one that listener was called for, whose commit reaches the listeners of onTextInput before the fed one's; a done fed from inside a listener of onTextInput is delivered after that listener's done, whose own composing text is not reported; a leave fed from inside a listener of onTextInput is followed by no onPreedit for that done's composing text; and when a listener of onTextInputDelete feeds a done, destroys the window and puts another at its address, listed in Device::windows, neither onTextInput nor onPreedit fires on the new one. Docs: the consumer notes list the purposes and the hints, the default hints, what a call that changes either does to a composition under way, the SetTextInput(false) that marks a move to another field of the same purpose and hints, and the order the input method's dones are delivered in. AGENTS.template.md names TextInputContent among the tests that need no GPU.
2026-11-20 08:08:54 +01:00
std::uint32_t textInputHints_ = TextInputDefaultHints(TextInputPurpose::Normal);
// The purpose and hints the enable in force went out with: a field
// of another kind is enabled anew (see SetTextInput).
TextInputPurpose textInputEnabledPurpose_ = TextInputPurpose::Normal;
std::uint32_t textInputEnabledHints_ = kTextInputHintNone;
2026-03-09 20:10:19 +01:00
static void xdg_surface_handle_preferred_scale(void* data, wp_fractional_scale_v1*, std::uint32_t scale);
2025-11-23 04:04:53 +01:00
static void wl_surface_frame_done(void *data, wl_callback *cb, uint32_t time);
static void xdg_toplevel_handle_close(void* data, xdg_toplevel*);
static void xdg_surface_handle_configure(void* data, xdg_surface* xdg_surface, std::uint32_t serial);
static void xdg_toplevel_configure(void*, xdg_toplevel*, std::int32_t, std::int32_t, wl_array*);
feat(wayland): keep xdg_toplevel's activated and suspended states on the window A consumer could not tell a window somebody is looking at from one that merely exists. The compositor's word on it comes with every xdg_toplevel configure — the `activated` state, and since version 6 of xdg_wm_base `suspended`, "not ordinarily being repainted", for example for a content covered by another window or outputs switched off for a screen lock — and the window dropped the states array. A messenger built on it took a conversation left open behind a lock screen or another application for one that was being read: its texts were marked read and never notified. Window: `activated` and `suspended` hold the two states, and onToplevelState fires after a configure changed either, with both already set. They are batched as the size is: xdg_toplevel.configure leaves them pending and the xdg_surface.configure that ends the batch applies them (ApplyToplevelState) last, so the handler does nothing with the window after its listeners. The constructor takes the first configure before a listener can be added, so a consumer reads the two once after it. Both are reported and the library combines nothing: which of the two a lock screen or another window in front changes is the compositor's choice, so a consumer that asks whether the user is looking at the window wants `activated && !suspended`, and the consumer notes say so. The members are the Wayland backend's; the Win32 and DOM backends keep no such state. Device: xdg_wm_base is bound at the version the compositor offers, up to 6, where it was bound at 1: `suspended` does not exist below 6 (`activated` is version 1's). Every request the windows make is version 1's. Besides `suspended`, the higher versions bring the window state values it passes over (the tiled ones, 2) and two events, xdg_toplevel's configure_bounds (4) and wm_capabilities (5), which the toplevel's listener takes and drops, since libwayland aborts a client at an event whose handler is null. Tests: ToplevelState feeds the two configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as TitleWayland makes them, and reads the bind off the wire: the states pending until the surface's configure, the last toplevel configure of a batch applied, one event for a batch that changes both, none for a repeat or for other states, an empty array clearing both; an offer of 7, 6, 5 and 1 bound at 6, 6, 5 and 1; a handler in the xdg_wm_base, xdg_surface and xdg_toplevel listeners for every event of the bundled protocol.
2026-11-17 00:49:53 +01:00
static void xdg_toplevel_configure_bounds(void*, xdg_toplevel*, std::int32_t, std::int32_t);
static void xdg_toplevel_wm_capabilities(void*, xdg_toplevel*, wl_array*);
2026-03-09 20:10:19 +01:00
2025-11-23 04:04:53 +01:00
constexpr static xdg_toplevel_listener xdg_toplevel_listener = {
.configure = xdg_toplevel_configure,
.close = xdg_toplevel_handle_close,
feat(wayland): keep xdg_toplevel's activated and suspended states on the window A consumer could not tell a window somebody is looking at from one that merely exists. The compositor's word on it comes with every xdg_toplevel configure — the `activated` state, and since version 6 of xdg_wm_base `suspended`, "not ordinarily being repainted", for example for a content covered by another window or outputs switched off for a screen lock — and the window dropped the states array. A messenger built on it took a conversation left open behind a lock screen or another application for one that was being read: its texts were marked read and never notified. Window: `activated` and `suspended` hold the two states, and onToplevelState fires after a configure changed either, with both already set. They are batched as the size is: xdg_toplevel.configure leaves them pending and the xdg_surface.configure that ends the batch applies them (ApplyToplevelState) last, so the handler does nothing with the window after its listeners. The constructor takes the first configure before a listener can be added, so a consumer reads the two once after it. Both are reported and the library combines nothing: which of the two a lock screen or another window in front changes is the compositor's choice, so a consumer that asks whether the user is looking at the window wants `activated && !suspended`, and the consumer notes say so. The members are the Wayland backend's; the Win32 and DOM backends keep no such state. Device: xdg_wm_base is bound at the version the compositor offers, up to 6, where it was bound at 1: `suspended` does not exist below 6 (`activated` is version 1's). Every request the windows make is version 1's. Besides `suspended`, the higher versions bring the window state values it passes over (the tiled ones, 2) and two events, xdg_toplevel's configure_bounds (4) and wm_capabilities (5), which the toplevel's listener takes and drops, since libwayland aborts a client at an event whose handler is null. Tests: ToplevelState feeds the two configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as TitleWayland makes them, and reads the bind off the wire: the states pending until the surface's configure, the last toplevel configure of a batch applied, one event for a batch that changes both, none for a repeat or for other states, an empty array clearing both; an offer of 7, 6, 5 and 1 bound at 6, 6, 5 and 1; a handler in the xdg_wm_base, xdg_surface and xdg_toplevel listeners for every event of the bundled protocol.
2026-11-17 00:49:53 +01:00
// Events of versions 4 and 5 of xdg_wm_base, which the bind for
// `suspended` brings with it. The window has no use for either,
// but libwayland aborts the client at an event whose handler is
// null.
.configure_bounds = xdg_toplevel_configure_bounds,
.wm_capabilities = xdg_toplevel_wm_capabilities,
2025-11-22 20:58:42 +01:00
};
2025-11-23 04:04:53 +01:00
constexpr static wl_callback_listener wl_callback_listener = {
.done = wl_surface_frame_done,
};
constexpr static xdg_surface_listener xdg_surface_listener = {
.configure = xdg_surface_handle_configure,
2025-11-22 20:58:42 +01:00
};
2025-12-29 18:56:06 +01:00
constexpr static wp_fractional_scale_v1_listener wp_fractional_scale_v1_listener = {
.preferred_scale = xdg_surface_handle_preferred_scale,
};
wp_fractional_scale_v1* wp_scale = nullptr;
2026-03-09 20:10:19 +01:00
#endif
2026-01-27 22:34:24 +01:00
2026-05-18 02:07:48 +02:00
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
2026-02-24 02:32:37 +01:00
VkCommandBuffer StartInit();
void FinishInit();
VkCommandBuffer GetCmd();
void EndCmd(VkCommandBuffer cmd);
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
// Makes the swapchain, after the old one's images have stopped being
// used: every caller has waited for the queue (or has no frames yet).
2026-02-24 02:32:37 +01:00
void CreateSwapchain();
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
// The capabilities a swapchain of `mode` on `surface` is sized by. With
// surface_maintenance1 they are the surface's for that mode, which may
// differ from its answer for all modes (Mesa on Wayland: FIFO 3, all
// modes 4, because MAILBOX needs 4). Those are the ones that apply when
// the swapchain is made naming its mode, which `modePassedAlong` says
// (swapchain_maintenance1's VkSwapchainPresentModesCreateInfoKHR).
// Without that the counts for all modes bind as well, so the minimum
// and maximum are the stricter of the two. Asks for the mode last, as
// the validation layer checks minImageCount against the surface's
// last answer. Static so a test sizes swapchains the way the window
// does.
static VkSurfaceCapabilitiesKHR SwapchainCapabilities(VkPhysicalDevice gpu, VkSurfaceKHR surface,
VkPresentModeKHR mode, bool modePassedAlong);
// The minImageCount CreateSwapchain asks for, from those capabilities:
// numFrames, or the surface's minimum where that is more, and never
// more than its maximum (0 means no maximum). The driver may still
// make more. Static so a test can feed it the numbers drivers report.
static std::uint32_t SwapchainMinImageCount(const VkSurfaceCapabilitiesKHR& capabilities);
// Calls CreateSwapchain(). The new images start in UNDEFINED, and
// Render() transitions each on its first acquire (imageInitialised).
// Does NOT fire onResize — callers do that.
2026-05-12 00:24:48 +02:00
void RecreateSwapchainAndImages();
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// Makes the swapchain again at width x height, where no frame is
// being recorded: waits for the queue, frees the deletion queue,
// makes it and fires onResize. On Wayland it first settles the two
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
// sizes at the scale the window draws at, taking a new one only
// where it gives the window new pixels (MatchSizesToScale), so width
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// and height may change in here for a window the compositor sized.
// It keeps swapchainRebuildPending set from its first step until
// the swapchain is made.
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
void RebuildSwapchain();
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
// Render()'s two frame boundaries: its start, before the fence wait
// and the acquire, and its end, after the present.
enum class FrameBoundary { Start, AfterPresent };
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// Makes the size that waits for a frame boundary the window's: the
// last Resize a listener of a frame asked for (deferredWidth) or,
// on Wayland, the size the compositor configured
// (deferredLogicalWidth). Only one of the two waits, the one asked
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
// for last. On Wayland it takes a scale the compositor asked for
// and the window does not draw at yet as well, with or without a
// configured size: at the start of a frame, and after a present
// only where it gives the window new pixels (see preferredScale).
// Otherwise the scale, and a configured size that comes to the
// pixels the window has with it, wait for the next frame's start.
// True when
// width or height changed, so that the swapchain has to be made
// again. A configured size or a new scale may leave them as they
// are: then only the surface's size changes, which the next frame
// sends, or nothing but `scale` does. No Vulkan call: Render()
// rebuilds.
bool TakeDeferredSize(FrameBoundary boundary);
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// At a frame boundary, where no frame is being recorded: the rebuild
// that waits, if one does. Render() runs it first thing, for what
// came between frames (a configure's size), and again after its
// present, for what its own listeners and its present asked for.
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
void RebuildIfDeferred(FrameBoundary boundary);
2026-05-01 23:35:37 +02:00
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
// Saves the frame the next Render() draws to a PNG at `path`, for
// visual regression tests and screenshots: that Render copies the
// swapchain image into a readback buffer before presenting it, waits
// for the frame, and writes the file. The copy can't come later: a
// presented image belongs to the presentation engine until it is
// acquired again.
void CaptureNextFrame(std::filesystem::path path);
std::optional<std::filesystem::path> pendingCapture;
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
// ── Frames and images ───────────────────────────────────────────
// The frame loop keeps numFrames frames in flight, and that number is
// its own: the swapchain has however many images the driver made for
// the present mode, which may be fewer or more (Mesa's Mailbox has at
// least four; issue #160). Two indices follow from that, set by
// Render() before onUpdate:
//
// currentFrame this frame's slot, frameCounter % numFrames. It
// picks everything that lives per frame in flight:
// the command buffer, the fence and acquire
// semaphore, the descriptor heap copy (or set) the
// frame binds, RenderingElement3D::tlases, the
// frameIdx a RenderPass is recorded with.
// currentImage the swapchain image the frame acquired and draws
// into: images[currentImage].
//
// The two go together differently from frame to frame, so a heap copy
// can't hold "its" swapchain image: Render() writes the acquired one
// into the frame's copy, at the slots DescriptorHeapVulkan::
// AddSwapchainSlot lists for this window, before onUpdate.
2026-03-09 20:10:19 +01:00
static constexpr std::uint8_t numFrames = 3;
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
std::uint32_t currentFrame = 0;
std::uint32_t currentImage = 0;
// True from a frame's acquire to its present: images[currentImage]
// and the frame's heap copy are this frame's, and a swapchain rebuild
// (Resize, SetPresentMode) waits for the present. What is waiting:
fix(wayland): the surface takes a new size with the first frame drawn at it, and a configure's rebuild waits for Render At a resize RebuildSwapchain sent wp_viewport.set_destination for the new size at once, and the configure listener, which had called it, acknowledged the configure and committed the surface. The destination is the surface's size, and it is state the next wl_surface.commit applies whatever buffer is attached then. That commit was the listener's, or the one a consumer makes to ask for a frame callback, and it put the old frame at the new size, where it stayed until the consumer's next frame brought a buffer of that size (#199). The acknowledgement named that commit as the answer to the configure. And the rebuild ran inside libwayland's dispatch: the consumer's loop stood still in it, each new size before a frame cost a swapchain, and a Vulkan error there was thrown from inside the dispatch, where the `try` a consumer has around Update() does not cover it (#200). Window: the configure listener keeps a new size (deferredLogicalWidth and Height, surface-local) and, where a frame is owed, the serial (unackedConfigure), and makes no Vulkan call. Render() takes what waits at its two boundaries (RebuildIfDeferred) and makes the swapchain again where that calls for one: first thing, for what came since the last frame, and after its present, as before, for what its listeners and the present asked for, and now for a size configured while they ran. Right before its present a frame sends what the surface is to take with its buffer (SendFrameSurfaceState): the destination, when the surface's size is not the one last sent (sentLogicalWidth and Height), and the acknowledgement of the configure it answers, the last one when several came. The present's commit then applies them together with the buffer. The constructor sends no destination: the window's first frame does. The surface's size is state of the window for that, beside the buffers' (logicalWidth and Height; logicalConfigured says which of the two sizes the window was given). TakeDeferredSize makes a configured size the surface's, unchanged, and works the pixels out of it with the scale of that moment. MatchSizesToScale does the same before every swapchain is made, and for a window the application sized (the constructor's size, Resize) works the surface's size out of the pixels, which is what RebuildSwapchain and the constructor did when they sent the destination. The destination is that state as it is and not ceil(width / scale) at the present, because the scale is the compositor's to change in any dispatch: between a configure and the frame that takes it, and in the middle of a frame, when a listener reads the clipboard or makes a window. And a size and a scale that change together can come to the pixels the swapchain has: then no swapchain is made, and the frame still brings the surface its size with the acknowledgement. With that the destination of a configured size is the size itself, where it was worked back from the pixels and could come out larger (392x796 at 2.85 came back as 393x797), and a configure at the size the surface has leaves a window the compositor sized alone while the scale stays what it was, where it could make the window grow again (#201). A window the application sized, configured at the size its surface has, takes the pixels for that size once where its own do not come to it (320x240 at 1.75, shown at 183x138, becomes 321x242), and is then left alone in the same way. That much of #201 comes with this change, since the state it asks for is the one this needs. The buffers' size is still rounded up, where the protocol rounds half away from zero: the rest of #201. A swapchain RebuildSwapchain made for another reason after the scale changed (a present mode, a present that found the swapchain out of date) applied the new scale by working the destination out again from the pixels. It still does for a window the application sized. A window the compositor sized keeps the surface's size and takes the pixels for it. The acquire's OUT_OF_DATE path repeated four of RebuildSwapchain's lines and sent no destination: it calls RebuildSwapchain now, and so settles the two sizes as the other rebuilds do. Of a Resize and a configured size the one asked for last is taken, as when the listener resized on the spot: a configure with a size clears a Resize that waits for its frame's present, also when its size is the one the window has, and Resize clears a configured size that waits. A configure that asks for nothing new while nothing is owed is acknowledged in the listener, as before. One that comes while a size waits, or while the surface does not show the window as it is (a swapchain still to be made, one that has presented no frame yet, a size not sent yet), waits for that frame. One for the size the window has, when nothing else is owed, is acknowledged at once and takes the wait away with it, as an acknowledgement of a serial older than the last is a protocol error. A frame being recorded when a size comes does not acknowledge it while that size waits; when a Resize later in the frame takes the size's place, that frame does. The listener still commits, which applies whatever else is pending on the surface, such as a request for a frame callback that StartUpdate made after a frame. For consumers: onResize for a compositor's resize fires from inside Render(), before the onUpdate of the frame that brings the size, with the queue idle and no frame being recorded, as Resize fires it; until that frame the window keeps its old size on screen. A window that draws on demand took onResize as its cue to ask for a frame, and gets onFrameOwed for it: the Wayland backend's alone, fired from the configure after onToplevelState, and only for a window that is still there after that event's listeners, whenever the configure leaves a frame owed. A size the surface does not have yet that comes to the pixels the window has (the scale changed with it) fires onFrameOwed and no onResize. Resize and SetPresentMode outside a frame rebuild at once as they did, and there too the surface takes the new size with the next frame. A rebuild that throws stays pending, since RebuildSwapchain clears swapchainRebuildPending only once the swapchain is made, and the next Render() tries it again. The README, the consumer notes and the guide's gotchas say so, and the bug-prover lens section lists the pending surface state and the scale among the re-entry contexts. Examples: InputSystem and the native mains of VulkanTriangle, RTVolume and Sponza drew one frame and then only ran the event loop, so nothing would have answered a compositor's resize of their windows. They call StartUpdate after that frame, as the examples that draw every frame do. Not changed: a scale that changes by itself still reaches the buffers and the surface only with the next swapchain or the next configured size (#165); the first configure's size (#166); and Win32's WM_SIZE, which still rebuilds from the window procedure. A window under StartUpdate on the compositor's clock still draws from its frame callback, so for it the rebuild, like every frame's Vulkan call, stays inside libwayland's dispatch; one on its own clock is updated by StartSync's loop after the dispatch, as before. #200 is answered for a consumer that calls Update() itself. A present that fails after SendFrameSurfaceState leaves what that sent pending for the surface's next commit, whoever makes it. Tests: ConfigureResize feeds the configure callbacks of a window whose surfaces are proxies on a wl_display over a socketpair, as ToplevelState does, with a made-up swapchain handle and no device, steps the two ends of a frame, and reads the requests off the wire: a configure for a new size sends one bare commit; the frame sends the destination and the acknowledgement before its present, once; several configures before a frame cost one of each, of the last serial; a configure for nothing new, or back to the window's size, is acknowledged in the listener, and the serial that waited never is; a frame being recorded when a size comes does not acknowledge it while the size waits, and does once a Resize has taken its place; the window's first frame and the first at any new size of the surface bring the destination, and a configure before it waits, and so does one for the size a rebuild that threw is still pending for, and one that comes after a present that found the swapchain out of date, whose surface state is not sent a second time; without a viewport the acknowledgement still waits. The destination is the configured size when the scale changes before the frame, when it changes between the frame's start and its present, and when the size and the scale together come to the swapchain's pixels, in either order of the two events, which makes no swapchain; with the numbers of #201's trace, 392x796 at 2.85, it is that size, and three more configures at it change nothing. A swapchain made after the scale changed keeps a configured window's surface size and an application-sized window's pixels. Of a Resize and a configured size the later one is taken, also when it is the size the window has. onFrameOwed fires after onToplevelState and not for a window its listener destroyed; every acknowledgement names a later serial than the one before. ResizeViewport runs a window against the compositor with WAYLAND_DEBUG set and stderr in a file, and replays the log, which has the driver's attach and commit too: at every commit the destination in effect belongs to the buffer in effect, to within a surface-local pixel, and every acknowledgement of a configure that asked for a size, once the surface has a buffer, is committed with a buffer of that size in effect and with that size itself as the destination, through a Resize with a commit before the next frame, a size the compositor configures (the window asks to be maximized), and one it configures while the frame loop of StartUpdate runs (the window asks to be restored), which that loop takes and answers by itself. Where the compositor configures no other size at that request, the step is a SKIP, and the test holds the log to it: no configure for another size came. `ResizeViewport --keyboard` is the manual probe for a phone: it asks for text input and takes it back three times (SetTextInput), which is what brings a phone's on-screen keyboard up and down, and holds the resizes that makes to the same checks.
2026-11-19 04:47:00 +01:00
// a swapchain still to be made, for a new size or present mode, a
// present that found it out of date, or a rebuild that threw, which
// the next Render() tries again (RebuildSwapchain clears the flag
// once the swapchain is made); and the last size a Resize asked
// for, 0 when none did. On Wayland a size the compositor configured
// waits in deferredLogicalWidth, whenever it comes, and takes the
// place of one that waits here, as a later Resize takes its place.
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
bool recording = false;
bool swapchainRebuildPending = false;
std::uint32_t deferredWidth = 0;
std::uint32_t deferredHeight = 0;
2026-02-24 02:32:37 +01:00
VkSurfaceKHR vulkanSurface = VK_NULL_HANDLE;
VkSwapchainKHR swapChain = VK_NULL_HANDLE;
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
// Bumped from a process-wide count whenever CreateSwapchain makes a
// swapchain, so it names one swapchain for good: a new swapchain's
// handle and images may reuse the old one's handle values. The heap
// keys what it wrote into each copy on it.
std::uint64_t swapchainGeneration = 0;
feat: windows on their own clock, deferred deletion for every handle owner, staged re-uploads, and RTPass push data Window - updateInterval runs Update on the window's own clock while the compositor sends no frame callbacks (hidden, minimized): the Wayland loop is a poll() loop, and the Win32 loop sleeps until the next update. Both read the interval each pass. - SetPresentMode (FIFO, Mailbox, Immediate). A mode the surface lacks, or whose swapchain has other than numFrames images (Mesa's Mailbox has four), falls back to FIFO until the mode is set again. - AddPollFd / RemovePollFd wake the Wayland loop on the app's descriptors. - The swapchain has TRANSFER_DST where the surface allows it. - CaptureNextFrame replaces SaveFrame: it records the copy in the frame, before the present, where SaveFrame read an image already presented. A frame unwound past before the write still frees the readback buffer. - Inter-pass barriers on the swapchain image carry the access masks of the stages the passes use. Deferred deletion (issue #101) - VulkanBuffer, Mesh, VulkanShader, ComputeShader and PipelineRTVulkan hand their handles to the deletion queue from their destructors and moves, as a frame in flight may still use them; a static owner goes after the driver has torn down. VulkanShader and PipelineRTVulkan move and can't be copied; re-Load and re-Init queue the old pipeline. - The queue and its mutex are never destroyed, and the queue takes handles from any thread; Device::frameCounter is atomic. Both the queue and the staging rings count frames as one window renders them (documented). - DrainDeletions also lets every buffer's staging ring start over: without a Window nothing else reclaims either, so an app without one calls it after waiting for its work. Meshes and buffers - A Mesh rebuild queues the old acceleration structure and builds into the same storage after a barrier, so the BLAS address stays put when it fits. The refit and rebuild barriers cover compute ray queries too. - RTBuildOptions::noDuplicateAnyHit. Mesh::geometryFlags replaces opaque, and the refit and rebuild fallbacks keep the flags. - A re-upload into a buffer a frame in flight may read (UploadDeviceLocal of the same size, UploadDeviceLocalRange) copies on the GPU, after those reads, through a per-frame staging ring; on ReBAR it used to write the buffer in place. Empty uploads record nothing. - A compressed Mesh::Build that keeps its buffers decompresses into them after the reads of frames in flight, and the hit shaders and ray queries wait for the decompress as well as the BLAS build. Its vertex buffer takes a ranged refit's copies. - Mesh move-assigns (queueing the BLAS it replaces), so it can be replaced in place or erased from a vector. - VulkanBuffer::Create asks for a device address only for buffers with SHADER_DEVICE_ADDRESS usage, as vkGetBufferDeviceAddress requires; the others have address 0. UIRenderer::RegisterBuffer refuses those. - Build inputs are synchronized as shader reads. Other - RTPass pushes the app's own push data and traces at an explicit size. - DescriptorHeapVulkan hands freed slot ranges out again (they leaked), and keeps its free lists sorted. - ImageVulkan's mip chain clamps each level to 1 texel: a non-square image's shorter side went to 0. - VulkanShader throws on a missing file instead of failing in bad_alloc. - CRAFTER_GRAPHICS_DEVICE picks the GPU by its number among the distinct GPUs Vulkan lists; anything but such a number is an error. - The debug messenger prints info messages only with CRAFTER_GRAPHICS_VALIDATION set. - Windows: the WinRT gamepad code moved to a C file (mingw-w64's WinRT headers don't compile as C++), -lcombase dropped, a reference leak fixed. - project.cpp honours --local for Crafter.Event, Math and Asset, as Asset does for Math, and builds every test through one helper, projectArgs included. - Tests: DebugMessengerSeverity, DeletionQueueThreads, DeviceSelection, HeapSlotReuse, MeshLifetime, MipChainNonSquare, PipelineLifetime, RTPassPushData, SwapchainTransferDst, UploadInFlight, VulkanBufferAddress, VulkanShaderLifetime, WindowUpdateClock; others extended. Breaking: SaveFrame is CaptureNextFrame; Mesh::opaque is geometryFlags; a buffer without SHADER_DEVICE_ADDRESS usage has no address; frameCounter is std::atomic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:54 +02:00
// What the swapchain images were created for: STORAGE | TRANSFER_SRC,
// plus TRANSFER_DST where the surface allows it, so a pass can blit or
// clear into the image instead of only writing it from a shader.
VkImageUsageFlags swapchainUsage = 0;
// The mode the swapchain was made with: presentMode, unless the
// surface lacks it or CRAFTER_PRESENT_IMMEDIATE is set.
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
2026-02-24 02:32:37 +01:00
VkFormat colorFormat;
VkColorSpaceKHR colorSpace;
// Supported composite-alpha mode for vulkanSurface. A surface property
// that does not change across swapchain recreation, so it is selected
// once at construction rather than re-derived on every CreateSwapchain
// (i.e. on every resize configure).
VkCompositeAlphaFlagBitsKHR compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
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
// One entry per swapchain image, as many as vkGetSwapchainImagesKHR
// returned; remade with the swapchain. imageViewInfos are the views a
// heap descriptor takes (VkImageDescriptorInfoEXT::pView); imageViews
// the same views made, which a descriptor set takes, owned by the
// window and destroyed with its swapchain.
std::vector<VkImage> images;
std::vector<VkImageViewCreateInfo> imageViewInfos;
std::vector<VkImageView> imageViews;
// Tracks whether each swapchain image has been rendered (and thus
// left in PRESENT_SRC_KHR) at least once. Freshly created swapchain
// images start in VK_IMAGE_LAYOUT_UNDEFINED, so the first per-frame
// barrier must transition from UNDEFINED, not PRESENT_SRC_KHR.
// Reset in CreateSwapchain(). A presentable image may only be touched
// after it has been acquired, so this initial transition happens
// lazily in Render() (post-acquire) rather than up front.
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
std::vector<bool> imageInitialised;
2026-02-24 02:32:37 +01:00
std::thread thread;
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
// Per frame in flight.
VkCommandBuffer drawCmdBuffers[numFrames] = {};
// Per-frame Vulkan info structs whose contents are almost entirely
// invariant. Initialised once in the constructor; Render() patches only
// the few fields that change each frame (the two barriers' image and
// the acquire barrier's oldLayout, and — for the multi-frame-in-flight
// sync below — submitInfo/presentInfo's wait/signal semaphores plus
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
// submitInfo's command buffer, which follow currentFrame/currentImage).
// presentInfo.pImageIndices and pSwapchains point at the
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
// currentImage/swapChain members, so they track value changes
// (including swapchain recreation) automatically.
VkSubmitInfo submitInfo;
VkCommandBufferBeginInfo cmdBufInfo;
VkImageMemoryBarrier acquireBarrier;
VkImageMemoryBarrier presentBarrier;
VkPresentInfoKHR presentInfo;
feat(window): multi-frame-in-flight frame pacing (#40) The renderer was effectively single-buffered despite allocating triple-buffered infrastructure: Render() ended with an unconditional vkQueueWaitIdle, and a single (presentComplete, renderComplete) semaphore pair with zero fences was shared for the Window's lifetime. Rework the pacing model so up to numFrames frames overlap: - Per-swapchain-image VkFence, signaled by the submit and waited+reset before that image's command buffer / descriptor-heap slot is re-recorded. Keyed by acquired image index (drawCmdBuffers, the heap slots, and the swapchain images are all image-indexed — see WriteSwapchainDescriptors). Created signaled so first use passes. - Per-image render-finished (present) semaphore: the presentation engine holds it until the image is re-acquired, so per-image is the only safe key (per-CPU-frame trips VUID-vkQueueSubmit-pSignalSemaphores-00067). - Per-CPU-frame acquire semaphores (image index unknown until acquire returns), sized numFrames+1: in-flight depth is bounded by the per-image fences, so numFrames+1 distinct acquire semaphores guarantee the reused one has no pending op (VUID-vkAcquireNextImageKHR-01779). - Drop the steady-state vkQueueWaitIdle; keep it on resize / OUT_OF_DATE / teardown. Add tests/FrameLoopSync: drives the real frame loop against a live Wayland compositor for 60 frames (>> in-flight slots) and asserts the CPU frame counter advanced, the swapchain rotated across multiple images, and the validation layer stayed silent — the load-bearing check, since the old single-pair design only avoided being an active race because the wait-idle masked it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 15:37:11 +00:00
// ── Multi-frame-in-flight synchronisation (issue #40) ──────────────
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
// Render() waits for its frame slot's fence before it acquires, so
// the command buffer, the heap copy and the acquire semaphore of that
// slot are free again, whichever image the acquire then returns.
feat(window): multi-frame-in-flight frame pacing (#40) The renderer was effectively single-buffered despite allocating triple-buffered infrastructure: Render() ended with an unconditional vkQueueWaitIdle, and a single (presentComplete, renderComplete) semaphore pair with zero fences was shared for the Window's lifetime. Rework the pacing model so up to numFrames frames overlap: - Per-swapchain-image VkFence, signaled by the submit and waited+reset before that image's command buffer / descriptor-heap slot is re-recorded. Keyed by acquired image index (drawCmdBuffers, the heap slots, and the swapchain images are all image-indexed — see WriteSwapchainDescriptors). Created signaled so first use passes. - Per-image render-finished (present) semaphore: the presentation engine holds it until the image is re-acquired, so per-image is the only safe key (per-CPU-frame trips VUID-vkQueueSubmit-pSignalSemaphores-00067). - Per-CPU-frame acquire semaphores (image index unknown until acquire returns), sized numFrames+1: in-flight depth is bounded by the per-image fences, so numFrames+1 distinct acquire semaphores guarantee the reused one has no pending op (VUID-vkAcquireNextImageKHR-01779). - Drop the steady-state vkQueueWaitIdle; keep it on resize / OUT_OF_DATE / teardown. Add tests/FrameLoopSync: drives the real frame loop against a live Wayland compositor for 60 frames (>> in-flight slots) and asserts the CPU frame counter advanced, the swapchain rotated across multiple images, and the validation layer stayed silent — the load-bearing check, since the old single-pair design only avoided being an active race because the wait-idle masked it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 15:37:11 +00:00
// Signaled by the queue submit, waited by vkQueuePresentKHR. Keyed by
// the acquired IMAGE index: the presentation engine keeps this
// semaphore in use until the image is re-acquired, so a per-image
// semaphore is the only safe key. Keying it per-CPU-frame trips
// VUID-vkQueueSubmit-pSignalSemaphores-00067.
// https://docs.vulkan.org/guide/latest/swapchain_semaphore_reuse.html
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
// Grown by CreateSwapchain to the image count and never shrunk: a
// present of the old swapchain may still wait on one, and nothing
// reports when that wait is done, so they live as long as the window.
std::vector<VkSemaphore> renderFinishedSemaphores;
feat(window): multi-frame-in-flight frame pacing (#40) The renderer was effectively single-buffered despite allocating triple-buffered infrastructure: Render() ended with an unconditional vkQueueWaitIdle, and a single (presentComplete, renderComplete) semaphore pair with zero fences was shared for the Window's lifetime. Rework the pacing model so up to numFrames frames overlap: - Per-swapchain-image VkFence, signaled by the submit and waited+reset before that image's command buffer / descriptor-heap slot is re-recorded. Keyed by acquired image index (drawCmdBuffers, the heap slots, and the swapchain images are all image-indexed — see WriteSwapchainDescriptors). Created signaled so first use passes. - Per-image render-finished (present) semaphore: the presentation engine holds it until the image is re-acquired, so per-image is the only safe key (per-CPU-frame trips VUID-vkQueueSubmit-pSignalSemaphores-00067). - Per-CPU-frame acquire semaphores (image index unknown until acquire returns), sized numFrames+1: in-flight depth is bounded by the per-image fences, so numFrames+1 distinct acquire semaphores guarantee the reused one has no pending op (VUID-vkAcquireNextImageKHR-01779). - Drop the steady-state vkQueueWaitIdle; keep it on resize / OUT_OF_DATE / teardown. Add tests/FrameLoopSync: drives the real frame loop against a live Wayland compositor for 60 frames (>> in-flight slots) and asserts the CPU frame counter advanced, the swapchain rotated across multiple images, and the validation layer stayed silent — the load-bearing check, since the old single-pair design only avoided being an active race because the wait-idle masked it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 15:37:11 +00:00
// Signaled by the queue submit, waited + reset before
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
// drawCmdBuffers[frame] and that frame's descriptor-heap copy are
// re-recorded. Keyed by frame slot. Created signaled so the first
// wait on each slot passes through instead of deadlocking.
feat(window): multi-frame-in-flight frame pacing (#40) The renderer was effectively single-buffered despite allocating triple-buffered infrastructure: Render() ended with an unconditional vkQueueWaitIdle, and a single (presentComplete, renderComplete) semaphore pair with zero fences was shared for the Window's lifetime. Rework the pacing model so up to numFrames frames overlap: - Per-swapchain-image VkFence, signaled by the submit and waited+reset before that image's command buffer / descriptor-heap slot is re-recorded. Keyed by acquired image index (drawCmdBuffers, the heap slots, and the swapchain images are all image-indexed — see WriteSwapchainDescriptors). Created signaled so first use passes. - Per-image render-finished (present) semaphore: the presentation engine holds it until the image is re-acquired, so per-image is the only safe key (per-CPU-frame trips VUID-vkQueueSubmit-pSignalSemaphores-00067). - Per-CPU-frame acquire semaphores (image index unknown until acquire returns), sized numFrames+1: in-flight depth is bounded by the per-image fences, so numFrames+1 distinct acquire semaphores guarantee the reused one has no pending op (VUID-vkAcquireNextImageKHR-01779). - Drop the steady-state vkQueueWaitIdle; keep it on resize / OUT_OF_DATE / teardown. Add tests/FrameLoopSync: drives the real frame loop against a live Wayland compositor for 60 frames (>> in-flight slots) and asserts the CPU frame counter advanced, the swapchain rotated across multiple images, and the validation layer stayed silent — the load-bearing check, since the old single-pair design only avoided being an active race because the wait-idle masked it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 15:37:11 +00:00
std::array<VkFence, numFrames> waitFences{};
// Signaled by vkAcquireNextImageKHR, waited by the queue submit. Keyed
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
// by frame slot: the slot's fence is waited before the acquire, and
// that fence follows the submit that waited on the semaphore, so the
// semaphore has no pending operation when it is reused
// (VUID-vkAcquireNextImageKHR-semaphore-01779).
std::array<VkSemaphore, numFrames> imageAcquiredSemaphores{};
feat(window): multi-frame-in-flight frame pacing (#40) The renderer was effectively single-buffered despite allocating triple-buffered infrastructure: Render() ended with an unconditional vkQueueWaitIdle, and a single (presentComplete, renderComplete) semaphore pair with zero fences was shared for the Window's lifetime. Rework the pacing model so up to numFrames frames overlap: - Per-swapchain-image VkFence, signaled by the submit and waited+reset before that image's command buffer / descriptor-heap slot is re-recorded. Keyed by acquired image index (drawCmdBuffers, the heap slots, and the swapchain images are all image-indexed — see WriteSwapchainDescriptors). Created signaled so first use passes. - Per-image render-finished (present) semaphore: the presentation engine holds it until the image is re-acquired, so per-image is the only safe key (per-CPU-frame trips VUID-vkQueueSubmit-pSignalSemaphores-00067). - Per-CPU-frame acquire semaphores (image index unknown until acquire returns), sized numFrames+1: in-flight depth is bounded by the per-image fences, so numFrames+1 distinct acquire semaphores guarantee the reused one has no pending op (VUID-vkAcquireNextImageKHR-01779). - Drop the steady-state vkQueueWaitIdle; keep it on resize / OUT_OF_DATE / teardown. Add tests/FrameLoopSync: drives the real frame loop against a live Wayland compositor for 60 frames (>> in-flight slots) and asserts the CPU frame counter advanced, the swapchain rotated across multiple images, and the validation layer stayed silent — the load-bearing check, since the old single-pair design only avoided being an active race because the wait-idle masked it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 15:37:11 +00:00
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
// Free-running count of Render() calls; currentFrame is this modulo
// numFrames.
feat(window): multi-frame-in-flight frame pacing (#40) The renderer was effectively single-buffered despite allocating triple-buffered infrastructure: Render() ended with an unconditional vkQueueWaitIdle, and a single (presentComplete, renderComplete) semaphore pair with zero fences was shared for the Window's lifetime. Rework the pacing model so up to numFrames frames overlap: - Per-swapchain-image VkFence, signaled by the submit and waited+reset before that image's command buffer / descriptor-heap slot is re-recorded. Keyed by acquired image index (drawCmdBuffers, the heap slots, and the swapchain images are all image-indexed — see WriteSwapchainDescriptors). Created signaled so first use passes. - Per-image render-finished (present) semaphore: the presentation engine holds it until the image is re-acquired, so per-image is the only safe key (per-CPU-frame trips VUID-vkQueueSubmit-pSignalSemaphores-00067). - Per-CPU-frame acquire semaphores (image index unknown until acquire returns), sized numFrames+1: in-flight depth is bounded by the per-image fences, so numFrames+1 distinct acquire semaphores guarantee the reused one has no pending op (VUID-vkAcquireNextImageKHR-01779). - Drop the steady-state vkQueueWaitIdle; keep it on resize / OUT_OF_DATE / teardown. Add tests/FrameLoopSync: drives the real frame loop against a live Wayland compositor for 60 frames (>> in-flight slots) and asserts the CPU frame counter advanced, the swapchain rotated across multiple images, and the validation layer stayed silent — the load-bearing check, since the old single-pair design only avoided being an active race because the wait-idle masked it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 15:37:11 +00:00
std::uint64_t frameCounter = 0;
2026-02-24 02:32:37 +01:00
VkPipelineStageFlags submitPipelineStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
2026-05-01 23:35:37 +02:00
std::vector<RenderPass*> passes;
DescriptorHeapVulkan* descriptorHeap = nullptr;
std::optional<std::array<float, 4>> clearColor;
2026-05-18 02:07:48 +02:00
#else
2026-05-18 04:58:52 +02:00
// DOM mode: the page IS the window. WebGPU device and canvas are
// owned JS-side (see additional/dom-webgpu.js); this struct just
// holds the per-Window state Crafter::Window users expect:
// a list of render passes and a pointer to the descriptor heap.
2026-05-18 02:07:48 +02:00
static constexpr std::uint8_t numFrames = 1;
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
std::uint32_t currentFrame = 0;
2026-05-18 04:58:52 +02:00
std::vector<RenderPass*> passes;
DescriptorHeapWebGPU* descriptorHeap = nullptr;
std::optional<std::array<float, 4>> clearColor;
// DOM-mode StartInit/FinishInit are no-ops returning an opaque
// command-buffer marker so cross-platform user code (HelloUI's
// `auto init = window.StartInit();`) compiles unchanged.
WebGPUCommandEncoderRef StartInit();
void FinishInit();
2026-05-18 02:07:48 +02:00
#endif
2026-02-24 02:32:37 +01:00
};
2025-04-16 00:43:33 +02:00
}