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.
247 lines
11 KiB
C++
247 lines
11 KiB
C++
//SPDX-License-Identifier: MIT
|
|
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
|
|
|
// =====================================================================
|
|
// InputSystem — guided tour of Crafter::Input
|
|
// =====================================================================
|
|
//
|
|
// Run this with a window focused. The console narrates each event as
|
|
// it fires; the on-screen window only exists so the OS routes keyboard
|
|
// and mouse input to us. Plug a gamepad in (Xbox / DualShock /
|
|
// Switch Pro) and it will be picked up live.
|
|
//
|
|
// What this demo demonstrates, in order:
|
|
//
|
|
// 1. Three runtime layers stacked end-to-end:
|
|
// - Crafter::Key(CrafterKeys::X) compile-time abstract → raw
|
|
// platform KeyCode
|
|
// - Window::onRawKeyDown raw keyboard channel for UI /
|
|
// text input (NOT used for game
|
|
// input — actions handle that)
|
|
// - Crafter::Input::Map named actions → bindings →
|
|
// events
|
|
// - Crafter::Gamepad hot-plug, button + axis state,
|
|
// rumble
|
|
//
|
|
// 2. All four action types: Button, Axis1D, Vector2, with multiple
|
|
// bindings per action (any-of semantics — press Space OR press
|
|
// gamepad-A; both trigger Jump).
|
|
//
|
|
// 3. Composite bindings: WASDBind (4 keys → Vector2),
|
|
// GamepadStickBind (analog stick → Vector2), MouseDeltaBind
|
|
// (mouse movement → Vector2).
|
|
//
|
|
// 4. Runtime rebinding: press R to enter rebind mode; the next key /
|
|
// mouse button / gamepad button you press becomes the new Jump
|
|
// binding. The captured input does NOT fire Jump that frame.
|
|
//
|
|
// 5. Serialization: bindings are round-tripped to text strings at
|
|
// startup. Use these as the on-disk format for your settings file.
|
|
//
|
|
// 6. Hot-plug: connect / disconnect a gamepad while running. The
|
|
// Map's polling-based evaluation seamlessly switches over —
|
|
// bindings to a vanished gamepad become inert until reconnect.
|
|
//
|
|
// Controls:
|
|
// Space / Gamepad A → Jump
|
|
// WASD / Left stick → Move
|
|
// Mouse-Left / Right Trigger → Fire
|
|
// Mouse delta / Right stick → Look
|
|
// Mouse wheel → Zoom (Axis1D)
|
|
// R → Start rebinding "Jump" — press
|
|
// any key/button next to assign it
|
|
// Esc → Quit
|
|
//
|
|
// Output is intentionally chatty so you can SEE the system working.
|
|
// In a real game, replace the print statements with your gameplay
|
|
// code — that's it.
|
|
// =====================================================================
|
|
|
|
import Crafter.Graphics;
|
|
import Crafter.Event; // EventListener<>: Crafter.Graphics imports
|
|
import Crafter.Math; // Vector<float,2>: it transitively, but
|
|
// C++20 module-reachability rules require
|
|
// us to name them explicitly to instantiate
|
|
// the templates in this TU.
|
|
import std;
|
|
using namespace Crafter;
|
|
using namespace Crafter::Input;
|
|
|
|
int main() {
|
|
Device::Initialize();
|
|
Window window(640, 360, "Crafter Input — give the window focus");
|
|
|
|
// =================================================================
|
|
// Build the action map.
|
|
//
|
|
// AddAction returns a reference; we keep it so we can subscribe.
|
|
// The map owns the actions (vector<unique_ptr>); references stay
|
|
// valid for the map's lifetime.
|
|
// =================================================================
|
|
Map map;
|
|
Action& jump = map.AddAction("Jump", ActionType::Button);
|
|
Action& move = map.AddAction("Move", ActionType::Vector2);
|
|
Action& fire = map.AddAction("Fire", ActionType::Button);
|
|
Action& look = map.AddAction("Look", ActionType::Vector2);
|
|
Action& zoom = map.AddAction("Zoom", ActionType::Axis1D);
|
|
Action& reset = map.AddAction("Reset", ActionType::Button);
|
|
Action& quit = map.AddAction("Quit", ActionType::Button);
|
|
|
|
// =================================================================
|
|
// Default bindings.
|
|
//
|
|
// Key(CrafterKeys::X) is `consteval` — these literals fold to
|
|
// per-platform scancodes at compile time, no runtime translation.
|
|
// Multiple bindings per action are OR'd: pressing EITHER triggers
|
|
// the action.
|
|
//
|
|
// gamepadId == 0 is a sentinel here meaning "first connected
|
|
// gamepad". For multi-player you'd save the stable id from a
|
|
// specific Device and use that.
|
|
// =================================================================
|
|
jump.bindings = {
|
|
KeyBind{ Key(CrafterKeys::Space) },
|
|
GamepadButtonBind{ 0, Gamepad::Button::South },
|
|
};
|
|
move.bindings = {
|
|
WASDBind{
|
|
Key(CrafterKeys::W), Key(CrafterKeys::S),
|
|
Key(CrafterKeys::A), Key(CrafterKeys::D),
|
|
},
|
|
GamepadStickBind{ 0, Gamepad::Stick::Left },
|
|
};
|
|
fire.bindings = {
|
|
MouseButtonBind{ 0 }, // left click
|
|
GamepadAxisBind{ 0, Gamepad::Axis::RightTrigger, false }, // analog R2
|
|
};
|
|
look.bindings = {
|
|
MouseDeltaBind{ 0.01f }, // scale down
|
|
GamepadStickBind{ 0, Gamepad::Stick::Right },
|
|
};
|
|
zoom.bindings = {
|
|
MouseScrollBind{},
|
|
};
|
|
reset.bindings = { KeyBind{ Key(CrafterKeys::R) } };
|
|
quit.bindings = { KeyBind{ Key(CrafterKeys::Escape) } };
|
|
|
|
// =================================================================
|
|
// Serialization round-trip — call sites can save these strings to
|
|
// disk and load them back into Action::bindings later.
|
|
//
|
|
// IMPORTANT: KeyCode values are platform-specific (Win32 scancodes
|
|
// vs. Wayland kernel keycodes). A saved file from one platform
|
|
// does NOT load on the other. Store your config under platform-
|
|
// specific paths.
|
|
// =================================================================
|
|
std::println("─── Default bindings (serialized form) ───");
|
|
for (auto& a : map.actions) {
|
|
for (auto& b : a->bindings) {
|
|
std::string s = BindingToString(b);
|
|
// Parse it back to prove the format roundtrips.
|
|
auto parsed = BindingFromString(s);
|
|
std::println(" {:<6} {} (roundtrip OK: {})",
|
|
a->name, s, parsed.has_value());
|
|
}
|
|
}
|
|
std::println("");
|
|
|
|
// =================================================================
|
|
// Subscribe to action events.
|
|
//
|
|
// EventListeners use the same RAII pattern as the rest of the
|
|
// library — declare them in scope, they unsubscribe when they go
|
|
// out of scope. Capturing references to the Actions is safe
|
|
// because the Map (and therefore its actions) outlive these
|
|
// listeners (both are in main()'s scope).
|
|
// =================================================================
|
|
EventListener<void> jumpPerf(&jump.onPerformed,
|
|
[] { std::println("[Jump] performed"); });
|
|
EventListener<void> jumpCanc(&jump.onCanceled,
|
|
[] { std::println("[Jump] canceled"); });
|
|
|
|
EventListener<Vector<float,2>> moveChanged(&move.onVector2Changed,
|
|
[](Vector<float,2> v) {
|
|
std::println("[Move] ({:+.2f}, {:+.2f})", v.x, v.y);
|
|
});
|
|
|
|
EventListener<void> firePerf(&fire.onPerformed,
|
|
[] { std::println("[Fire] performed"); });
|
|
EventListener<void> fireCanc(&fire.onCanceled,
|
|
[] { std::println("[Fire] canceled"); });
|
|
|
|
EventListener<Vector<float,2>> lookChanged(&look.onVector2Changed,
|
|
[](Vector<float,2> v) {
|
|
// Mouse delta fires every frame the mouse moves; throttle
|
|
// by checking magnitude so the console doesn't drown.
|
|
if (std::abs(v.x) + std::abs(v.y) > 0.01f) {
|
|
std::println("[Look] ({:+.3f}, {:+.3f})", v.x, v.y);
|
|
}
|
|
});
|
|
|
|
EventListener<float> zoomChanged(&zoom.onValueChanged,
|
|
[](float v) { std::println("[Zoom] delta {:+.0f}", v); });
|
|
|
|
EventListener<void> quitPerf(&quit.onPerformed,
|
|
[&] {
|
|
std::println("[Quit] shutting down");
|
|
window.open = false;
|
|
});
|
|
|
|
// =================================================================
|
|
// Rebinding flow.
|
|
//
|
|
// Pressing R fires Reset → we call StartRebind for the Jump
|
|
// action. While rebinding, the next qualifying input does NOT
|
|
// fire Jump (or any other action that uses the same input). It
|
|
// routes to the onCaptured callback exactly once.
|
|
//
|
|
// CaptureMask::Any accepts keyboard | mouse | gamepad. Narrow it
|
|
// (Keyboard, Gamepad, etc.) to restrict what counts as a valid
|
|
// binding for a given action.
|
|
// =================================================================
|
|
EventListener<void> resetPerf(&reset.onPerformed, [&] {
|
|
std::println("[Rebind] Press any key / button to bind \"Jump\" "
|
|
"(Esc to cancel)…");
|
|
map.StartRebind(jump, CaptureMask::Any, [&](Binding captured) {
|
|
jump.bindings.clear();
|
|
jump.bindings.push_back(captured);
|
|
std::println("[Rebind] Jump → {}", BindingToString(captured));
|
|
});
|
|
});
|
|
|
|
// =================================================================
|
|
// Gamepad lifecycle observers.
|
|
//
|
|
// Gamepad::Tick() is called automatically inside Window::StartSync
|
|
// every frame, so these events fire on the main thread alongside
|
|
// every other event. Hot-plug a controller while running and you
|
|
// should see the connect line below.
|
|
// =================================================================
|
|
EventListener<Gamepad::Device*> gpAdded(&Gamepad::onConnected,
|
|
[](Gamepad::Device* d) {
|
|
std::println("[Gamepad] connected: id={} name=\"{}\"",
|
|
d->id, d->name);
|
|
});
|
|
EventListener<Gamepad::Device*> gpRemoved(&Gamepad::onDisconnected,
|
|
[](Gamepad::Device* d) {
|
|
std::println("[Gamepad] disconnected: id={}", d->id);
|
|
});
|
|
|
|
// =================================================================
|
|
// Connect the map to the window. Map polls window state + gamepad
|
|
// state every Tick; we trigger Tick from onBeforeUpdate so it
|
|
// runs after the OS event pump (and Gamepad::Tick) for that frame.
|
|
// =================================================================
|
|
map.Attach(window);
|
|
EventListener<void> tick(&window.onBeforeUpdate, [&] { map.Tick(); });
|
|
|
|
std::println("─── Ready. Focus the window and try the controls. ───");
|
|
window.Render();
|
|
// The window draws nothing, but its frames keep coming: on Wayland a
|
|
// frame is what answers the compositor when it resizes the window.
|
|
window.StartUpdate();
|
|
window.StartSync();
|
|
|
|
std::println("Done.");
|
|
return 0;
|
|
}
|