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.
707 lines
No EOL
39 KiB
C++
707 lines
No EOL
39 KiB
C++
//SPDX-License-Identifier: LGPL-3.0-only
|
|
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
|
|
|
module;
|
|
|
|
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <linux/input-event-codes.h>
|
|
#include <xkbcommon/xkbcommon.h>
|
|
#include "../lib/xdg-shell-client-protocol.h"
|
|
#include "../lib/wayland-xdg-decoration-unstable-v1-client-protocol.h"
|
|
#include "../lib/fractional-scale-v1.h"
|
|
#include "../lib/viewporter.h"
|
|
#include "../lib/text-input-unstable-v3-client-protocol.h"
|
|
#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
|
|
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
|
|
#include "vulkan/vulkan.h"
|
|
#endif
|
|
#ifdef CRAFTER_GRAPHICS_WINDOW_WIN32
|
|
#include <windows.h>
|
|
#endif
|
|
|
|
export module Crafter.Graphics:Window;
|
|
import std;
|
|
import :Types;
|
|
import :Keys;
|
|
import Crafter.Event;
|
|
#ifdef CRAFTER_GRAPHICS_WINDOW_DOM
|
|
import :WebGPU;
|
|
import :DescriptorHeapWebGPU;
|
|
#endif
|
|
|
|
export namespace Crafter {
|
|
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
|
|
struct Semaphores {
|
|
// Swap chain image presentation
|
|
VkSemaphore presentComplete;
|
|
// Command buffer submission and execution
|
|
VkSemaphore renderComplete;
|
|
};
|
|
struct RenderPass;
|
|
struct DescriptorHeapVulkan;
|
|
#else
|
|
struct RenderPass;
|
|
struct DescriptorHeapWebGPU;
|
|
#endif
|
|
|
|
// 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
|
|
// 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.
|
|
enum class PresentMode {
|
|
Fifo,
|
|
Mailbox,
|
|
Immediate,
|
|
};
|
|
|
|
struct Window {
|
|
FrameTime currentFrameTime;
|
|
std::uint32_t width;
|
|
std::uint32_t height;
|
|
std::chrono::time_point<std::chrono::high_resolution_clock> lastFrameBegin;
|
|
Event<void> onClose;
|
|
Event<void> onBeforeUpdate;
|
|
Event<FrameTime> onUpdate;
|
|
// 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
|
|
// 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).
|
|
Event<void> onResize;
|
|
bool open = true;
|
|
bool updating = false;
|
|
// 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;
|
|
// 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;
|
|
Event<const std::string_view> onTextInput;
|
|
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
|
|
// 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.
|
|
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;
|
|
Vector<float, 2> currentMousePos;
|
|
Vector<float, 2> lastMousePos;
|
|
Vector<float, 2> mouseDelta;
|
|
bool mouseLeftHeld = false;
|
|
bool mouseRightHeld = false;
|
|
|
|
#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
|
|
|
|
Window() = default;
|
|
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;
|
|
// 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
|
|
// 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.
|
|
~Window();
|
|
|
|
// 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.
|
|
void StartSync();
|
|
|
|
// 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();
|
|
|
|
void StartUpdate();
|
|
void StopUpdate();
|
|
// Makes the swapchain again with the new mode and fires onResize, as
|
|
// 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
|
|
// environment variable CRAFTER_PRESENT_IMMEDIATE overrides the mode,
|
|
// for benchmarks.
|
|
void SetPresentMode(PresentMode mode);
|
|
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
|
|
// the keyboard focus comes back to this window.
|
|
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);
|
|
// Like SetPresentMode, a resize asked for while a frame is being
|
|
// recorded takes effect once that frame has been presented, width and
|
|
// 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.
|
|
void Resize(std::uint32_t width, std::uint32_t height);
|
|
void Render();
|
|
void Update();
|
|
// 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();
|
|
|
|
#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;
|
|
void LogTiming();
|
|
#endif
|
|
|
|
#ifdef CRAFTER_GRAPHICS_WINDOW_WIN32
|
|
HWND hwnd = nullptr;
|
|
HBITMAP cursorBitmap = nullptr;
|
|
HCURSOR cursorHandle = nullptr;
|
|
std::uint16_t cursorSizeX = 0;
|
|
std::uint16_t cursorSizeY = 0;
|
|
#endif
|
|
|
|
#ifdef CRAFTER_GRAPHICS_WINDOW_WAYLAND
|
|
// 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;
|
|
|
|
// 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;
|
|
|
|
// 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;
|
|
|
|
// 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
|
|
// configure's states set. And it fires from the event dispatch
|
|
// 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;
|
|
|
|
float scale = 1.0f;
|
|
bool configured = false;
|
|
// Pending size from the most recent xdg_toplevel.configure, in
|
|
// surface-local (logical DP) units, until the xdg_surface.configure
|
|
// that ends its batch; 0 means "compositor has no preference, keep
|
|
// current".
|
|
std::int32_t pendingLogicalWidth = 0;
|
|
std::int32_t pendingLogicalHeight = 0;
|
|
// 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
|
|
// onToplevelState when that changed one.
|
|
bool pendingActivated = false;
|
|
bool pendingSuspended = false;
|
|
void ApplyToplevelState();
|
|
// 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
|
|
// the scale is not a whole number (#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.
|
|
std::int32_t logicalWidth = 0;
|
|
std::int32_t logicalHeight = 0;
|
|
bool logicalConfigured = false;
|
|
// Before a swapchain is made: works the size the window was not
|
|
// given out of the one it was, with the scale of that moment. 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 the
|
|
// next swapchain applies a scale that changed, whatever it is made
|
|
// for (the time until then is #165), without moving a configured
|
|
// window off the size the compositor gave it. No Vulkan call.
|
|
void MatchSizesToScale();
|
|
// 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
|
|
// the scale of that moment. 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.
|
|
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();
|
|
xdg_toplevel* xdgToplevel = nullptr;
|
|
zxdg_toplevel_decoration_v1* decoration = nullptr;
|
|
wp_viewport* wpViewport = nullptr;
|
|
wl_surface* surface = nullptr;
|
|
xdg_surface* xdgSurface = nullptr;
|
|
wl_callback* cb = nullptr;
|
|
wl_surface* cursorSurface = nullptr;
|
|
wl_buffer* cursorWlBuffer = nullptr;
|
|
std::uint32_t cursorBufferOldSize = 0;
|
|
// 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;
|
|
|
|
static void xdg_surface_handle_preferred_scale(void* data, wp_fractional_scale_v1*, std::uint32_t scale);
|
|
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*);
|
|
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*);
|
|
|
|
constexpr static xdg_toplevel_listener xdg_toplevel_listener = {
|
|
.configure = xdg_toplevel_configure,
|
|
.close = xdg_toplevel_handle_close,
|
|
// 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,
|
|
};
|
|
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,
|
|
};
|
|
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;
|
|
#endif
|
|
|
|
#ifndef CRAFTER_GRAPHICS_WINDOW_DOM
|
|
VkCommandBuffer StartInit();
|
|
void FinishInit();
|
|
VkCommandBuffer GetCmd();
|
|
void EndCmd(VkCommandBuffer cmd);
|
|
// 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).
|
|
void CreateSwapchain();
|
|
// 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.
|
|
void RecreateSwapchainAndImages();
|
|
// 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
|
|
// sizes with the scale of that moment (MatchSizesToScale), so width
|
|
// 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.
|
|
void RebuildSwapchain();
|
|
// 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
|
|
// for last. True when width or height changed, so that the
|
|
// swapchain has to be made again. A configured size may leave them
|
|
// as they are, where the scale changed with it: then only the
|
|
// surface's size changes, which the next frame sends. No Vulkan
|
|
// call: Render() rebuilds.
|
|
bool TakeDeferredSize();
|
|
// 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.
|
|
void RebuildIfDeferred();
|
|
|
|
// 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;
|
|
|
|
// ── 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.
|
|
static constexpr std::uint8_t numFrames = 3;
|
|
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:
|
|
// 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.
|
|
bool recording = false;
|
|
bool swapchainRebuildPending = false;
|
|
std::uint32_t deferredWidth = 0;
|
|
std::uint32_t deferredHeight = 0;
|
|
VkSurfaceKHR vulkanSurface = VK_NULL_HANDLE;
|
|
VkSwapchainKHR swapChain = VK_NULL_HANDLE;
|
|
// 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;
|
|
// 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;
|
|
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;
|
|
// 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.
|
|
std::vector<bool> imageInitialised;
|
|
std::thread thread;
|
|
// 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
|
|
// submitInfo's command buffer, which follow currentFrame/currentImage).
|
|
// presentInfo.pImageIndices and pSwapchains point at the
|
|
// currentImage/swapChain members, so they track value changes
|
|
// (including swapchain recreation) automatically.
|
|
VkSubmitInfo submitInfo;
|
|
VkCommandBufferBeginInfo cmdBufInfo;
|
|
VkImageMemoryBarrier acquireBarrier;
|
|
VkImageMemoryBarrier presentBarrier;
|
|
VkPresentInfoKHR presentInfo;
|
|
|
|
// ── Multi-frame-in-flight synchronisation (issue #40) ──────────────
|
|
// 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.
|
|
|
|
// 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
|
|
// 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;
|
|
|
|
// Signaled by the queue submit, waited + reset before
|
|
// 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.
|
|
std::array<VkFence, numFrames> waitFences{};
|
|
|
|
// Signaled by vkAcquireNextImageKHR, waited by the queue submit. Keyed
|
|
// 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{};
|
|
|
|
// Free-running count of Render() calls; currentFrame is this modulo
|
|
// numFrames.
|
|
std::uint64_t frameCounter = 0;
|
|
VkPipelineStageFlags submitPipelineStages = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
|
|
std::vector<RenderPass*> passes;
|
|
DescriptorHeapVulkan* descriptorHeap = nullptr;
|
|
std::optional<std::array<float, 4>> clearColor;
|
|
#else
|
|
// 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.
|
|
static constexpr std::uint8_t numFrames = 1;
|
|
std::uint32_t currentFrame = 0;
|
|
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();
|
|
#endif
|
|
};
|
|
} |