From b5416d1219ea1ae0c3a49425cd222496f1a175e5 Mon Sep 17 00:00:00 2001 From: alexei-zebra Date: Fri, 9 Oct 2026 23:07:58 +0300 Subject: [PATCH] Fix the issues found while reviewing the Wayland frame work A review of the branch turned up a number of defects, gaps and leftovers; this commit addresses all of them. Defects: - the shadow uniform array held seven entries while eight locations were written, so the last one landed outside the object; - CursorShape::LAST stayed in the middle of the enum after the new corner shapes were appended, which made the GLFW cursor table read out of bounds; the extra shapes are now mapped onto the ones GLFW knows, and the table is only filled for those; - GlStateGuard asked glIsEnabled for an attribute pname, so it always got GL_INVALID_ENUM and never restored the vertex attribute arrays; - the early returns in wayland_window_initialize left the global window and input pointers dangling when falling back to GLFW; - the icon textures were listed nowhere, so none of them ever loaded; - a shader failure disabled the shadow after the surface had already been sized for it, and VOXEL_DECORATIONS outlived the switch cleanup. Behavior: - the keyboard now releases every pressed key when it loses focus, and a repeat rate of zero means no repeat; - the fourth UTF-8 lead byte is decoded with the right mask, control characters no longer reach text fields, and a vanished clipboard offer clears the cached text; - compositor side decorations disable ours again instead of leaving two titles, the window destructor releases the rest of the state, and the content inset is computed before the GUI acts so the HUD and the container never disagree for a frame; the HUD clamps it; - the window controls fall back to minimize, maximize and close, and the icons are drawn from textures only. Cleanups: one monotonic timer instead of three, one vertex shader shared by both renderers with a link check, one button layout parser, the inset rule moved into Screen, the scissor stack moved into the base Window (about 110 duplicated lines), named shadow and evdev constants, trimmed includes, a README note about the Wayland dependencies, and the long lines introduced by this branch wrapped. --- README.md | 7 + res/preload.json | 3 + src/CMakeLists.txt | 4 +- src/engine/Engine.cpp | 13 +- src/engine/WindowBar.cpp | 43 ++---- src/frontend/hud.cpp | 9 +- src/frontend/screens/MenuScreen.hpp | 4 + src/frontend/screens/Screen.cpp | 5 + src/frontend/screens/Screen.hpp | 4 + src/graphics/core/commons.hpp | 2 +- src/graphics/ui/GUI.hpp | 7 + src/window/Window.cpp | 65 ++++++++ src/window/Window.hpp | 9 +- src/window/detail/GLFWWindow.cpp | 91 ++++-------- src/window/wayland/WaylandCommon.cpp | 34 ++++- src/window/wayland/WaylandCommon.hpp | 13 +- src/window/wayland/WaylandDecorations.cpp | 85 ++++++----- src/window/wayland/WaylandInit.cpp | 67 +++++++-- src/window/wayland/WaylandInput.hpp | 49 ++++-- src/window/wayland/WaylandListeners.cpp | 52 ++++--- src/window/wayland/WaylandListeners.hpp | 13 +- src/window/wayland/WaylandSettings.cpp | 5 +- src/window/wayland/WaylandSettings.hpp | 1 - src/window/wayland/WaylandWindow.cpp | 172 +++++++++------------- src/window/wayland/WaylandWindow.hpp | 168 +++++++++++---------- 25 files changed, 523 insertions(+), 402 deletions(-) diff --git a/README.md b/README.md index d040e7707..4443ca07f 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,13 @@ apt-get install entt-devel libglfw3-devel libGLEW-devel libglm-devel libpng-deve ```sh sudo apt install libglfw3 libglfw3-dev libglew-dev libglm-dev libpng-dev libopenal-dev libluajit-5.1-dev libvorbis-dev libcurl4-openssl-dev libssl-dev libfreetype6-dev + +#### Wayland (optional, enabled by default on Linux) + +The native Wayland backend needs `wayland-client`, `wayland-egl`, +`wayland-scanner`, `wayland-protocols`, `libxkbcommon` and EGL. Build with +`-DVOXELENGINE_WAYLAND=OFF` to fall back to GLFW; `libsystemd` (sd-bus) is +picked up automatically for the desktop button layout. ``` > [!TIP] diff --git a/res/preload.json b/res/preload.json index 51acb129c..b20c3602b 100644 --- a/res/preload.json +++ b/res/preload.json @@ -30,6 +30,9 @@ "gui/warning", "gui/error", "gui/cross", + "gui/minimize_w", + "gui/maximize_w", + "gui/restore_w", "gui/refresh", "gui/folder_icon", "gui/settings_icon", diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3ee250a4d..7cee11a0a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -127,8 +127,8 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND VOXELENGINE_WAYLAND) target_sources( VoxelCoreSrc PRIVATE ${WAYLAND_SOURCES} ${wayland_sources}) - target_include_directories(VoxelCoreSrc PUBLIC ${WAYLAND_GENERATED}) - target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_WAYLAND=1) + target_include_directories(VoxelCoreSrc PRIVATE ${WAYLAND_GENERATED}) + target_compile_definitions(VoxelCoreSrc PRIVATE VOXELENGINE_WAYLAND=1) if(libsystemd_FOUND) target_compile_definitions(VoxelCoreSrc PUBLIC VOXELENGINE_SDBUS=1) target_link_libraries(VoxelCoreSrc PRIVATE PkgConfig::libsystemd) diff --git a/src/engine/Engine.cpp b/src/engine/Engine.cpp index 3e5edb371..a9ddccbc1 100644 --- a/src/engine/Engine.cpp +++ b/src/engine/Engine.cpp @@ -1,15 +1,12 @@ -#include - -#include - #include "Engine.hpp" -#include "frontend/screens/MenuScreen.hpp" #include "WindowBar.hpp" #ifndef GLEW_STATIC #define GLEW_STATIC #endif +#include + #include "AssetsManagement.hpp" #include "audio/audio.hpp" #include "coders/commons.hpp" @@ -276,6 +273,7 @@ void Engine::updateFrontend() { assets->update(); updateHotkeys(); audio::update(delta); + gui->setContentInset(screen->getContentInset(*window)); gui->act(delta, window->getSize()); screen->update(delta); gui->postAct(); @@ -324,11 +322,6 @@ void Engine::renderFrame() { screen->draw(time.getDelta()); DrawContext ctx(nullptr, *window, nullptr); - gui->setContentInset( - dynamic_cast(screen.get()) != nullptr - ? 0 - : window->getDecorationHeight() - ); gui->draw(ctx, *assets->getStorage()); draw_window_bar(*this); } diff --git a/src/engine/WindowBar.cpp b/src/engine/WindowBar.cpp index 618df3a1e..0c28c0f7c 100644 --- a/src/engine/WindowBar.cpp +++ b/src/engine/WindowBar.cpp @@ -1,11 +1,11 @@ #include "WindowBar.hpp" #include "Engine.hpp" -#include "debug/Logger.hpp" #include "graphics/core/Batch2D.hpp" #include #include #include "graphics/core/Shader.hpp" +#include "constants.hpp" #include "graphics/core/Font.hpp" #include "graphics/core/Texture.hpp" #include "graphics/ui/GUI.hpp" @@ -23,9 +23,15 @@ namespace { return converter.from_bytes(text); } - constexpr const char* BAR_FONT = "normal"; + const std::string BAR_FONT = FONT_DEFAULT; } +/// @brief Draws the window bar the backend cannot draw itself. +/// +/// The bar lives in window coordinates while the GUI container is shifted +/// down by its height in game, so the GUI camera cannot be reused here: the +/// bar sets its own viewport and projection. It borrows the GUI batch only +/// because the ui shader it needs is the one the GUI already loads. void draw_window_bar(Engine& engine) { auto& window = engine.getWindow(); const int height = window.getDecorationHeight(); @@ -34,14 +40,17 @@ void draw_window_bar(Engine& engine) { } auto* batch = engine.getGUI().getBatch2D(); auto font = engine.requireAssets().getShared(BAR_FONT); - if (batch == nullptr || font == nullptr) { + if (font == nullptr) { return; } const auto size = window.getSize(); const float barHeight = static_cast(height); - glViewport(0, 0, static_cast(size.x), static_cast(size.y)); - if (auto shader = engine.requireAssets().get("ui"); shader != nullptr) { + glViewport( + 0, 0, static_cast(size.x), static_cast(size.y) + ); + auto shader = engine.requireAssets().get("ui"); + if (shader != nullptr) { shader->use(); shader->uniformMatrix( "u_projview", @@ -98,7 +107,6 @@ void draw_window_bar(Engine& engine) { batch->untexture(); } - const float thickness = 2.0f; for (size_t i = 0; i < buttons.size(); i++) { const auto& item = buttons[i]; const float x = item.x; @@ -132,29 +140,8 @@ void draw_window_bar(Engine& engine) { iconSize, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, ink ); batch->untexture(); - continue; - } - if (item.button == DecorationButton::CLOSE) { - for (int step = 0; step < 8; step++) { - batch->rect(cx - 5.0f + step, cy - 5.0f + step, thickness, thickness); - batch->rect(cx + 3.0f - step, cy - 5.0f + step, thickness, thickness); - } - } else if (item.button == DecorationButton::MINIMIZE) { - batch->rect(cx - 6.0f, cy - 1.0f, 12.0f, thickness); - } else if (!window.isMaximized()) { - batch->rect(cx - 6.0f, cy - 6.0f, 12.0f, thickness); - batch->rect(cx - 6.0f, cy + 4.0f, 12.0f, thickness); - batch->rect(cx - 6.0f, cy - 6.0f, thickness, 12.0f); - batch->rect(cx + 4.0f, cy - 6.0f, thickness, 12.0f); - } else { - batch->rect(cx - 7.0f, cy + 1.0f, 11.0f, thickness); - batch->rect(cx - 7.0f, cy + 1.0f, thickness, 6.0f); - batch->rect(cx + 2.0f, cy + 1.0f, thickness, 6.0f); - batch->rect(cx - 7.0f, cy + 5.0f, 11.0f, thickness); - batch->rect(cx - 2.0f, cy - 5.0f, 9.0f, thickness); - batch->rect(cx - 2.0f, cy - 5.0f, thickness, 6.0f); - batch->rect(cx + 5.0f, cy - 5.0f, thickness, 6.0f); } + } batch->flush(); } diff --git a/src/frontend/hud.cpp b/src/frontend/hud.cpp index 50748323e..cf5fdb303 100644 --- a/src/frontend/hud.cpp +++ b/src/frontend/hud.cpp @@ -625,9 +625,14 @@ void Hud::setDebug(bool flag) { void Hud::draw(const DrawContext& ctx){ const auto& viewport = ctx.getViewport(); - uint inset = static_cast(ctx.getWindow().getDecorationHeight()); + const int inset = gui.getContentInset(); + const int contentHeight = std::max( + 1, static_cast(viewport.y) - inset + ); - updateElementsPosition(glm::uvec2(viewport.x, viewport.y - inset)); + updateElementsPosition( + glm::uvec2(viewport.x, static_cast(contentHeight)) + ); uicamera->setFov(viewport.y); uicamera->setAspectRatio(viewport.x / static_cast(viewport.y)); diff --git a/src/frontend/screens/MenuScreen.hpp b/src/frontend/screens/MenuScreen.hpp index a8caf0fef..7f8f02ad5 100644 --- a/src/frontend/screens/MenuScreen.hpp +++ b/src/frontend/screens/MenuScreen.hpp @@ -15,6 +15,10 @@ public: void onOpen() override; + int getContentInset(const Window&) const override { + return 0; + } + void update(float delta) override; void draw(float delta) override; diff --git a/src/frontend/screens/Screen.cpp b/src/frontend/screens/Screen.cpp index 3fd648258..16e84e716 100644 --- a/src/frontend/screens/Screen.cpp +++ b/src/frontend/screens/Screen.cpp @@ -1,4 +1,5 @@ #include "Screen.hpp" +#include "window/Window.hpp" #include "graphics/core/Batch2D.hpp" #include "engine/Engine.hpp" @@ -10,3 +11,7 @@ Screen::Screen(Engine& engine) Screen::~Screen() { } + +int Screen::getContentInset(const Window& window) const { + return window.getDecorationHeight(); +} diff --git a/src/frontend/screens/Screen.hpp b/src/frontend/screens/Screen.hpp index c24dc8b38..44039b968 100644 --- a/src/frontend/screens/Screen.hpp +++ b/src/frontend/screens/Screen.hpp @@ -4,6 +4,7 @@ class Engine; class Batch2D; +class Window; /// @brief Screen is a mainloop state class Screen : public util::ObjectsKeeper { @@ -18,4 +19,7 @@ public: virtual void draw(float delta) = 0; virtual void onEngineShutdown() {}; virtual const char* getName() const = 0; + + /// @brief Inset of the GUI content from the top of the window + virtual int getContentInset(const Window& window) const; }; diff --git a/src/graphics/core/commons.hpp b/src/graphics/core/commons.hpp index 6c09d5b43..230c9b0db 100644 --- a/src/graphics/core/commons.hpp +++ b/src/graphics/core/commons.hpp @@ -56,7 +56,7 @@ enum class CursorShape { SE_RESIZE, SW_RESIZE, - LAST=NOT_ALLOWED + LAST=SW_RESIZE }; namespace advanced_pipeline { diff --git a/src/graphics/ui/GUI.hpp b/src/graphics/ui/GUI.hpp index 4ccc51147..6cf84b919 100644 --- a/src/graphics/ui/GUI.hpp +++ b/src/graphics/ui/GUI.hpp @@ -123,6 +123,8 @@ namespace gui { /// @param assets active assets storage void draw(const DrawContext& pctx, Assets& assets); + /// @brief Offset of the main container from the top of the window, + /// e.g. the height of the engine drawn window bar int viewportOffset = 0; /// @brief Get the cursor position in the main container coordinates @@ -133,6 +135,11 @@ namespace gui { viewportOffset = inset; } + int getContentInset() const { + return viewportOffset; + } + + /// @brief Batch used to draw the window bar on top of the GUI Batch2D* getBatch2D() { return batch2D.get(); } diff --git a/src/window/Window.cpp b/src/window/Window.cpp index 48ba76076..e57535dec 100644 --- a/src/window/Window.cpp +++ b/src/window/Window.cpp @@ -6,6 +6,14 @@ #include +#ifndef GLEW_STATIC +#define GLEW_STATIC +#endif + +#include + +#include + static debug::Logger logger("window"); #ifdef VOXELENGINE_WAYLAND @@ -34,3 +42,60 @@ std::tuple< #endif return glfw_window_initialize(settings, std::move(title)); } + +void Window::pushScissor(glm::vec4 area) { + if (scissorStack.empty()) { + glEnable(GL_SCISSOR_TEST); + } + scissorStack.push(scissorArea); + + area.z += glm::ceil(area.x); + area.w += glm::ceil(area.y); + + area.x = glm::max(area.x, scissorArea.x); + area.y = glm::max(area.y, scissorArea.y); + + area.z = glm::min(area.z, scissorArea.z); + area.w = glm::min(area.w, scissorArea.w); + + if (area.z < 0.0f || area.w < 0.0f) { + glScissor(0, 0, 0, 0); + } else { + glScissor( + area.x, + size.y - area.w, + std::max(0, static_cast(glm::ceil(area.z - area.x))), + std::max(0, static_cast(glm::ceil(area.w - area.y))) + ); + } + scissorArea = area; +} + +void Window::popScissor() { + if (scissorStack.empty()) { + logger.warning() << "extra Window::popScissor call"; + return; + } + glm::vec4 area = scissorStack.top(); + scissorStack.pop(); + if (area.z < 0.0f || area.w < 0.0f) { + glScissor(0, 0, 0, 0); + } else { + glScissor( + area.x, + size.y - area.w, + std::max(0, static_cast(area.z - area.x)), + std::max(0, static_cast(area.w - area.y)) + ); + } + if (scissorStack.empty()) { + glDisable(GL_SCISSOR_TEST); + } + scissorArea = area; +} + +void Window::resetScissor() { + scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); + scissorStack = std::stack(); + glDisable(GL_SCISSOR_TEST); +} diff --git a/src/window/Window.hpp b/src/window/Window.hpp index 020e36c0a..d0a62394a 100644 --- a/src/window/Window.hpp +++ b/src/window/Window.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -80,9 +81,9 @@ public: virtual void setIcon(const ImageData* image) = 0; - virtual void pushScissor(glm::vec4 area) = 0; - virtual void popScissor() = 0; - virtual void resetScissor() = 0; + virtual void pushScissor(glm::vec4 area); + virtual void popScissor(); + virtual void resetScissor(); virtual void setShouldRefresh() = 0; virtual bool checkShouldRefresh() = 0; @@ -104,6 +105,8 @@ public: > initialize(DisplaySettings* settings, std::string title); protected: glm::ivec2 size; + std::stack scissorStack; + glm::vec4 scissorArea {}; WindowMode mode = WindowMode::WINDOWED; }; diff --git a/src/window/detail/GLFWWindow.cpp b/src/window/detail/GLFWWindow.cpp index 88161de93..ee772c3cd 100644 --- a/src/window/detail/GLFWWindow.cpp +++ b/src/window/detail/GLFWWindow.cpp @@ -185,6 +185,26 @@ static void glfw_error_callback(int error, const char* description) { static GLFWcursor* standard_cursors[static_cast(CursorShape::LAST) + 1] = {}; +/// @brief Map extra cursor shapes onto the ones GLFW knows about +static int cursor_index(CursorShape shape) { + switch (shape) { + case CursorShape::N_RESIZE: + case CursorShape::S_RESIZE: + return static_cast(CursorShape::NS_RESIZE); + case CursorShape::E_RESIZE: + case CursorShape::W_RESIZE: + return static_cast(CursorShape::EW_RESIZE); + case CursorShape::NE_RESIZE: + case CursorShape::SW_RESIZE: + return static_cast(CursorShape::NESW_RESIZE); + case CursorShape::NW_RESIZE: + case CursorShape::SE_RESIZE: + return static_cast(CursorShape::NWSE_RESIZE); + default: + return static_cast(shape); + } +} + class GLFWInput : public BaseInput { public: GLFWInput(GLFWwindow* window) @@ -245,7 +265,9 @@ public: ~GLFWWindow() { for (int i = 0; i <= static_cast(CursorShape::LAST); i++) { - glfwDestroyCursor(standard_cursors[i]); + if (standard_cursors[i] != nullptr) { + glfwDestroyCursor(standard_cursors[i]); + } } glfwTerminate(); } @@ -307,7 +329,7 @@ public: } cursor = shape; // nullptr cursor is valid for GLFW - glfwSetCursor(window, standard_cursors[static_cast(shape)]); + glfwSetCursor(window, standard_cursors[cursor_index(shape)]); } void setMode(WindowMode mode) override { @@ -397,64 +419,7 @@ public: } } - void pushScissor(glm::vec4 area) override { - if (scissorStack.empty()) { - glEnable(GL_SCISSOR_TEST); - } - scissorStack.push(scissorArea); - - area.z += glm::ceil(area.x); - area.w += glm::ceil(area.y); - - area.x = glm::max(area.x, scissorArea.x); - area.y = glm::max(area.y, scissorArea.y); - - area.z = glm::min(area.z, scissorArea.z); - area.w = glm::min(area.w, scissorArea.w); - - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(glm::ceil(area.z - area.x))), - std::max(0, static_cast(glm::ceil(area.w - area.y))) - ); - } - scissorArea = area; - } - - void resetScissor() override { - scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); - scissorStack = std::stack(); - glDisable(GL_SCISSOR_TEST); - } - - void popScissor() override { - if (scissorStack.empty()) { - logger.warning() << "extra Window::popScissor call"; - return; - } - glm::vec4 area = scissorStack.top(); - scissorStack.pop(); - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(area.z - area.x)), - std::max(0, static_cast(area.w - area.y)) - ); - } - if (scissorStack.empty()) { - glDisable(GL_SCISSOR_TEST); - } - scissorArea = area; - } - - std::unique_ptr takeScreenshot() override { + std::unique_ptr takeScreenshot() override { glBindFramebuffer(GL_FRAMEBUFFER, 0); auto data = std::make_unique(size.x * size.y * 3); glPixelStorei(GL_PACK_ALIGNMENT, 1); @@ -475,8 +440,6 @@ private: GLFWwindow* window; CursorShape cursor = CursorShape::ARROW; int framerate = -1; - std::stack scissorStack; - glm::vec4 scissorArea {}; double prevSwap = 0.0; int posX = 0; int posY = 0; @@ -547,7 +510,9 @@ static void iconify_callback(GLFWwindow* window, int iconified) { } static void create_standard_cursors() { - for (int i = 0; i <= static_cast(CursorShape::LAST); i++) { + // GLFW knows only the shapes up to NOT_ALLOWED, the rest are mapped + // onto them by cursor_index() + for (int i = 0; i <= static_cast(CursorShape::NOT_ALLOWED); i++) { int cursor = GLFW_ARROW_CURSOR + i; // GLFW 3.3 does not support some cursors if (GLFW_VERSION_MAJOR <= 3 && GLFW_VERSION_MINOR <= 3 && diff --git a/src/window/wayland/WaylandCommon.cpp b/src/window/wayland/WaylandCommon.cpp index 5ea51bbae..be4afff39 100644 --- a/src/window/wayland/WaylandCommon.cpp +++ b/src/window/wayland/WaylandCommon.cpp @@ -5,6 +5,21 @@ debug::Logger waylandLogger("window"); +const char* WAYLAND_VERTEX_SHADER = + "#version 330 core\n" + "layout(location = 0) in vec2 aPos;\n" + "out vec2 vUV;\n" + "void main() {\n" + " vUV = aPos * 0.5 + 0.5;\n" + " gl_Position = vec4(aPos, 0.0, 1.0);\n" + "}\n"; + +double waylandNow() { + return std::chrono::duration( + std::chrono::steady_clock::now().time_since_epoch() + ).count(); +} + GlStateGuard::GlStateGuard() { glGetIntegerv(GL_CURRENT_PROGRAM, &values[0]); @@ -25,12 +40,20 @@ GlStateGuard::GlStateGuard() { glGetIntegerv(GL_VIEWPORT, viewport); glGetIntegerv(GL_COLOR_WRITEMASK, colorMask); for (int i = 0; i < 3; i++) { - attribFlags[i] = glIsEnabled(GL_VERTEX_ATTRIB_ARRAY_ENABLED + i); + GLint attribEnabled = 0; + glGetVertexAttribiv( + i, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &attribEnabled + ); + attribFlags[i] = attribEnabled != 0; glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_SIZE, &attribs[i][0]); glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_TYPE, &attribs[i][1]); - glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &attribs[i][2]); + glGetVertexAttribiv( + i, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &attribs[i][2] + ); glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &attribs[i][3]); - glGetVertexAttribiv(i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &attribs[i][5]); + glGetVertexAttribiv( + i, GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING, &attribs[i][5] + ); void* pointer = nullptr; glGetVertexAttribPointerv(i, GL_VERTEX_ATTRIB_ARRAY_POINTER, &pointer); attribs[i][6] = static_cast(reinterpret_cast(pointer)); @@ -102,11 +125,6 @@ class WaylandWindow; WaylandInput* input = nullptr; WaylandWindow* window = nullptr; -bool decorations_enabled() { - const char* value = getenv("VOXEL_DECORATIONS"); - return value == nullptr || strcmp(value, "none") != 0; -} - bool serverDecorations = false; int keycode_from_keysym(xkb_keysym_t sym) { diff --git a/src/window/wayland/WaylandCommon.hpp b/src/window/wayland/WaylandCommon.hpp index 3407a0ef1..f1378a2ec 100644 --- a/src/window/wayland/WaylandCommon.hpp +++ b/src/window/wayland/WaylandCommon.hpp @@ -28,15 +28,9 @@ #include #include #include -#include #include #include -const wl_registry_listener& registry_listener(); -const wl_data_device_listener& data_device_listener(); -const xdg_surface_listener& surface_listener(); -const xdg_toplevel_listener& toplevel_listener(); - struct GlStateGuard { GLint values[16] {}; GLint attribs[3][7] {}; @@ -52,6 +46,12 @@ GLuint compile_program(const char* vertexSource, const char* fragmentSource); extern debug::Logger waylandLogger; +/// @brief Monotonic time in seconds, shared by the whole backend +double waylandNow(); + +/// @brief Fullscreen triangle vertex shader used by the backend renderers +extern const char* WAYLAND_VERTEX_SHADER; + struct WaylandState { wl_display* display = nullptr; wl_registry* registry = nullptr; @@ -97,7 +97,6 @@ template void ignore_event(Args...) { } -bool decorations_enabled(); void dispatch_events(int timeoutMs); int keycode_from_keysym(xkb_keysym_t sym); diff --git a/src/window/wayland/WaylandDecorations.cpp b/src/window/wayland/WaylandDecorations.cpp index ead71b136..e9f0b1341 100644 --- a/src/window/wayland/WaylandDecorations.cpp +++ b/src/window/wayland/WaylandDecorations.cpp @@ -4,10 +4,7 @@ #include #include -#include #include -#include -#include namespace { constexpr const char* LAYOUT_SCHEMA = "org.gnome.desktop.wm.preferences"; @@ -19,7 +16,8 @@ namespace { while (start <= text.size()) { const size_t end = text.find(',', start); const std::string name = text.substr( - start, end == std::string::npos ? std::string::npos : end - start + start, + end == std::string::npos ? std::string::npos : end - start ); if (name == "close") { buttons.push_back(DecorationButton::CLOSE); @@ -36,8 +34,30 @@ namespace { return buttons; } + void split_layout( + const std::string& value, std::vector& left, + std::vector& right + ) { + std::string text = value; + text.erase( + std::remove_if(text.begin(), text.end(), [] (char c) { + return c == '\'' || c == '"' || c == '\n' || c == '\r'; + }), + text.end() + ); + const size_t separator = text.find(':'); + if (separator == std::string::npos) { + left.clear(); + right = parse_buttons(text); + } else { + left = parse_buttons(text.substr(0, separator)); + right = parse_buttons(text.substr(separator + 1)); + } + } + bool read_button_layout( - std::vector& left, std::vector& right + std::vector& left, + std::vector& right ) { FILE* pipe = popen( "gsettings get org.gnome.desktop.wm.preferences button-layout" @@ -53,46 +73,20 @@ namespace { if (line == nullptr || status != 0) { return false; } - std::string value(buffer); - value.erase( - std::remove_if(value.begin(), value.end(), [] (char c) { - return c == '\'' || c == '"' || c == '\n' || c == '\r'; - }), - value.end() - ); - const size_t separator = value.find(':'); - if (separator == std::string::npos) { - left.clear(); - right = parse_buttons(value); - } else { - left = parse_buttons(value.substr(0, separator)); - right = parse_buttons(value.substr(separator + 1)); - } + split_layout(std::string(buffer), left, right); return true; } constexpr double DRAG_THRESHOLD = 5.0; + constexpr double LAYOUT_CHECK_INTERVAL = 2.0; constexpr double DOUBLE_CLICK_TIME = 0.4; constexpr double DOUBLE_CLICK_DISTANCE = 8.0; } void WaylandWindow::applyLayoutValue(const std::string& rawValue) { - std::string value = rawValue; - value.erase( - std::remove_if(value.begin(), value.end(), [] (char c) { - return c == '\'' || c == '"' || c == '\n' || c == '\r'; - }), - value.end() - ); - const size_t separator = value.find(':'); std::vector left; std::vector right; - if (separator == std::string::npos) { - right = parse_buttons(value); - } else { - left = parse_buttons(value.substr(0, separator)); - right = parse_buttons(value.substr(separator + 1)); - } + split_layout(rawValue, left, right); if (left == leftButtons && right == rightButtons) { return; } @@ -127,7 +121,7 @@ void WaylandWindow::updateButtonLayout() { return; } const double current = now(); - if (current - lastLayoutCheck < 2.0) { + if (current - lastLayoutCheck < LAYOUT_CHECK_INTERVAL) { return; } lastLayoutCheck = current; @@ -145,6 +139,14 @@ void WaylandWindow::updateButtonLayout() { } void WaylandWindow::updateBarGeometry() { + if (leftButtons.empty() && rightButtons.empty()) { + // desktop layout is unavailable, fall back to the usual three controls + rightButtons = { + DecorationButton::MINIMIZE, + DecorationButton::MAXIMIZE, + DecorationButton::CLOSE, + }; + } barButtons.clear(); const float width = static_cast(size.x); constexpr float pitch = BAR_BUTTON + BAR_GAP; @@ -166,7 +168,8 @@ void WaylandWindow::updateBarGeometry() { } } -const std::vector& WaylandWindow::getDecorationButtons() const { +const std::vector& +WaylandWindow::getDecorationButtons() const { return barButtons; } @@ -183,10 +186,16 @@ int WaylandWindow::getDecorationHoveredButton() const { } void WaylandWindow::enableOwnDecorations() { - if (!decorations_enabled()) { + barEnabled = true; + setShouldRefresh(); +} + +void WaylandWindow::disableOwnDecorations() { + if (!barEnabled) { return; } - barEnabled = true; + barEnabled = false; + resize(size.x, size.y); setShouldRefresh(); } diff --git a/src/window/wayland/WaylandInit.cpp b/src/window/wayland/WaylandInit.cpp index d8904a487..25823cd9e 100644 --- a/src/window/wayland/WaylandInit.cpp +++ b/src/window/wayland/WaylandInit.cpp @@ -11,6 +11,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { state.display = wl_display_connect(nullptr); if (state.display == nullptr) { waylandLogger.error() << "could not connect to the Wayland display"; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } state.registry = wl_display_get_registry(state.display); @@ -27,6 +33,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { waylandLogger.error() << "the compositor does not provide xdg-shell"; wl_display_disconnect(state.display); state.display = nullptr; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } @@ -44,15 +56,15 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { state.dataDeviceManager, state.seat ); static const wl_data_device_listener deviceListener = [] { - wl_data_device_listener value {}; - value.data_offer = data_device_data_offer; - value.enter = ignore_event<>; - value.leave = ignore_event<>; - value.motion = ignore_event<>; - value.drop = ignore_event<>; - value.selection = data_device_selection; - return value; - }(); + wl_data_device_listener value {}; + value.data_offer = data_device_data_offer; + value.enter = ignore_event<>; + value.leave = ignore_event<>; + value.motion = ignore_event<>; + value.drop = ignore_event<>; + value.selection = data_device_selection; + return value; + }(); wl_data_device_add_listener(state.dataDevice, &deviceListener, nullptr); } @@ -105,7 +117,13 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { while (!window->configured) { if (wl_display_dispatch(state.display) == -1) { waylandLogger.error() << "the Wayland connection was lost"; - return {nullptr, nullptr}; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } + return {nullptr, nullptr}; } } @@ -115,6 +133,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { if (window->eglDisplay == EGL_NO_DISPLAY || eglInitialize(window->eglDisplay, nullptr, nullptr) == EGL_FALSE) { waylandLogger.error() << "could not initialize EGL"; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } eglBindAPI(EGL_OPENGL_API); @@ -156,7 +180,13 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { << "no EGL config with alpha, the drop shadow is off"; if (!chooseConfig(0, requestedSamples) && !chooseConfig(0, 0)) { waylandLogger.error() << "no suitable EGL config"; - return {nullptr, nullptr}; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } + return {nullptr, nullptr}; } window->shadowEnabled = false; } @@ -185,6 +215,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { window->eglContext ) == EGL_FALSE) { waylandLogger.error() << "could not create the OpenGL context"; + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } eglSwapInterval(window->eglDisplay, 0); @@ -194,6 +230,12 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { if (glewError != GLEW_OK && glewError != GLEW_ERROR_NO_GLX_DISPLAY) { waylandLogger.error() << "failed to initialize GLEW:\n" << glewGetErrorString(glewError); + window = nullptr; + input = nullptr; + if (state.display != nullptr) { + wl_display_disconnect(state.display); + state.display = nullptr; + } return {nullptr, nullptr}; } @@ -208,7 +250,8 @@ wayland_window_initialize(DisplaySettings* settings, std::string title) { glGetIntegerv(GL_MAX_TEXTURE_SIZE, maxTextureSize); if (maxTextureSize[0] > 0) { Texture::MAX_RESOLUTION = maxTextureSize[0]; - waylandLogger.info() << "max texture size is " << Texture::MAX_RESOLUTION; + waylandLogger.info() + << "max texture size is " << Texture::MAX_RESOLUTION; } waylandLogger.info() << "GL Vendor: " << reinterpret_cast(glGetString(GL_VENDOR)); diff --git a/src/window/wayland/WaylandInput.hpp b/src/window/wayland/WaylandInput.hpp index a83e52d84..bf9071a30 100644 --- a/src/window/wayland/WaylandInput.hpp +++ b/src/window/wayland/WaylandInput.hpp @@ -16,6 +16,9 @@ #include #include +/// @brief Offset between the evdev keycode and the xkb one +static constexpr uint32_t XKB_KEYCODE_OFFSET = 8; + class WaylandInput : public BaseInput { public: void pollEvents(bool waitForRefresh) override; @@ -83,7 +86,9 @@ public: close(clipboardFd); clipboardFd = -1; } - wl_data_device_set_selection(state.dataDevice, source, state.inputSerial); + wl_data_device_set_selection( + state.dataDevice, source, state.inputSerial + ); wl_display_flush(state.display); } @@ -154,6 +159,20 @@ public: applyCursor(); } + /// @brief Release every pressed key, e.g. when the keyboard focus is lost + void releasePressedKeys() { + const auto keys = pressedKeys; + for (auto key : keys) { + onKeyCallback(static_cast(key), false); + } + repeatKeycode = 0; + } + + /// @brief Forget the cached clipboard text + void clearClipboardText() { + clipboard.clear(); + } + void onRelativeMotion(double dx, double dy) { delta.x += dx; delta.y += dy; @@ -163,7 +182,7 @@ public: if (state.xkbState == nullptr || state.xkbKeymap == nullptr) { return; } - xkb_keycode_t code = key + 8; + xkb_keycode_t code = key + XKB_KEYCODE_OFFSET; const xkb_keysym_t* syms = nullptr; if (xkb_keymap_key_get_syms_by_level( state.xkbKeymap, code, 0, 0, &syms @@ -244,9 +263,7 @@ private: } static double now() { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch() - ).count(); + return waylandNow(); } void appendCodepoints(xkb_keycode_t code) { @@ -264,18 +281,26 @@ private: codepoint = (codepoint << 6) | (bytes[i] & 0x3F); continue; } - if (codepoint != 0) { + if (codepoint >= 0x20 && codepoint != 0x7F) { codepoints.push_back(codepoint); } - codepoint = (bytes[i] & 0x80) ? (bytes[i] & 0x1F) : bytes[i]; + if ((bytes[i] & 0x80) == 0) { + codepoint = bytes[i]; + } else if ((bytes[i] & 0xE0) == 0xC0) { + codepoint = bytes[i] & 0x1F; + } else if ((bytes[i] & 0xF0) == 0xE0) { + codepoint = bytes[i] & 0x0F; + } else { + codepoint = bytes[i] & 0x07; + } } - if (codepoint != 0) { + if (codepoint >= 0x20 && codepoint != 0x7F) { codepoints.push_back(codepoint); } } void updateRepeat() { - if (repeatKeycode == 0 || !state.xkbState) { + if (repeatKeycode == 0 || state.repeatRate == 0 || !state.xkbState) { return; } int keycode = 0; @@ -321,8 +346,10 @@ private: ) { if (input) { const std::string& text = input->sourceText; - if (!text.empty() && write(fd, text.data(), text.size()) < 0) { - waylandLogger.warning() << "could not write to the clipboard"; + if (!text.empty() && + write(fd, text.data(), text.size()) < 0) { + waylandLogger.warning() + << "could not write to the clipboard"; } } close(fd); diff --git a/src/window/wayland/WaylandListeners.cpp b/src/window/wayland/WaylandListeners.cpp index ed2efe249..10e4ed0e3 100644 --- a/src/window/wayland/WaylandListeners.cpp +++ b/src/window/wayland/WaylandListeners.cpp @@ -53,19 +53,15 @@ static void pointer_button( uint32_t buttonState ) { state.inputSerial = serial; - int index = -1; - switch (button) { - case 0x110: index = 0; break; - case 0x111: index = 1; break; - case 0x112: index = 2; break; - case 0x113: index = 3; break; - case 0x114: index = 4; break; - case 0x115: index = 5; break; - case 0x116: index = 6; break; - case 0x117: index = 7; break; - } + // BTN_LEFT .. BTN_TASK from linux/input-event-codes.h + constexpr uint32_t EVDEV_BUTTON_FIRST = 0x110; + constexpr uint32_t EVDEV_BUTTON_LAST = 0x117; + int index = button >= EVDEV_BUTTON_FIRST && button <= EVDEV_BUTTON_LAST + ? static_cast(button - EVDEV_BUTTON_FIRST) + : -1; const bool pressed = buttonState == WL_POINTER_BUTTON_STATE_PRESSED; - if (index >= 0 && window && window->handleBarButton(serial, index, pressed)) { + if (index >= 0 && window && + window->handleBarButton(serial, index, pressed)) { return; } if (index >= 0 && input) { @@ -129,6 +125,9 @@ static void keyboard_enter( } static void keyboard_leave(void*, wl_keyboard*, uint32_t, wl_surface*) { + if (input) { + input->releasePressedKeys(); + } } static void keyboard_key( @@ -154,8 +153,10 @@ static void keyboard_modifiers( } } -static void keyboard_repeat_info(void*, wl_keyboard*, int32_t rate, int32_t delay) { - state.repeatRate = rate > 0 ? rate : 25; +static void keyboard_repeat_info( + void*, wl_keyboard*, int32_t rate, int32_t delay +) { + state.repeatRate = rate > 0 ? static_cast(rate) : 0; state.repeatDelay = delay > 0 ? delay : 400; } @@ -273,8 +274,13 @@ void data_device_selection(void*, wl_data_device*, wl_data_offer* offer) { wl_data_offer_destroy(input->selection); } input->selection = offer; - input->selectionMimes = std::move(input->pendingMimes); input->pendingMimes.clear(); + if (offer == nullptr) { + input->selectionMimes.clear(); + input->clearClipboardText(); + return; + } + input->selectionMimes = std::move(input->pendingMimes); input->requestClipboardText(); } @@ -314,14 +320,18 @@ void registry_global( std::min(version, 3u) ) ); - } else if (strcmp(interface, wp_cursor_shape_manager_v1_interface.name) == 0) { + } else if ( + strcmp(interface, wp_cursor_shape_manager_v1_interface.name) == 0 + ) { state.cursorShapeManager = static_cast( wl_registry_bind( registry, name, &wp_cursor_shape_manager_v1_interface, std::min(version, 2u) ) ); - } else if (strcmp(interface, zwp_pointer_constraints_v1_interface.name) == 0) { + } else if ( + strcmp(interface, zwp_pointer_constraints_v1_interface.name) == 0 + ) { state.pointerConstraints = static_cast( wl_registry_bind( registry, name, &zwp_pointer_constraints_v1_interface, 1 @@ -360,8 +370,12 @@ void zxdg_decoration_configure( void*, zxdg_toplevel_decoration_v1*, uint32_t mode ) { serverDecorations = mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; - if (!serverDecorations && window != nullptr) { - window->enableOwnDecorations(); + if (window != nullptr) { + if (serverDecorations) { + window->disableOwnDecorations(); + } else { + window->enableOwnDecorations(); + } } } diff --git a/src/window/wayland/WaylandListeners.hpp b/src/window/wayland/WaylandListeners.hpp index a8ea8bf28..c78e9dd5e 100644 --- a/src/window/wayland/WaylandListeners.hpp +++ b/src/window/wayland/WaylandListeners.hpp @@ -2,13 +2,20 @@ #include "window/wayland/WaylandCommon.hpp" -void toplevel_configure(void*, xdg_toplevel*, int32_t width, int32_t height, wl_array* states); +void toplevel_configure( + void*, xdg_toplevel*, int32_t width, int32_t height, wl_array* states +); void toplevel_close(void*, xdg_toplevel*); void toplevel_configure_bounds(void*, xdg_toplevel*, int32_t, int32_t); void toplevel_wm_capabilities(void*, xdg_toplevel*, wl_array*); void xdg_surface_configure(void*, xdg_surface* surface, uint32_t serial); void data_device_data_offer(void*, wl_data_device*, wl_data_offer* offer); void data_device_selection(void*, wl_data_device*, wl_data_offer* offer); -void registry_global(void*, wl_registry* registry, uint32_t name, const char* interface, uint32_t version); +void registry_global( + void*, wl_registry* registry, uint32_t name, const char* interface, + uint32_t version +); void registry_global_remove(void*, wl_registry*, uint32_t); -void zxdg_decoration_configure(void*, zxdg_toplevel_decoration_v1*, uint32_t mode); +void zxdg_decoration_configure( + void*, zxdg_toplevel_decoration_v1*, uint32_t mode +); diff --git a/src/window/wayland/WaylandSettings.cpp b/src/window/wayland/WaylandSettings.cpp index 58817b16f..aeb2360b3 100644 --- a/src/window/wayland/WaylandSettings.cpp +++ b/src/window/wayland/WaylandSettings.cpp @@ -30,7 +30,8 @@ namespace { } if (type == 's') { const char* text = nullptr; - if (sd_bus_message_read(message, "s", &text) < 0 || text == nullptr) { + if (sd_bus_message_read(message, "s", &text) < 0 || + text == nullptr) { return {}; } return text; @@ -167,8 +168,6 @@ bool SettingsWatcher::poll( } impl->changed = false; value = impl->changedValue; - (void)schema; - (void)key; return true; #else return false; diff --git a/src/window/wayland/WaylandSettings.hpp b/src/window/wayland/WaylandSettings.hpp index 30012e9e3..878b379f5 100644 --- a/src/window/wayland/WaylandSettings.hpp +++ b/src/window/wayland/WaylandSettings.hpp @@ -16,7 +16,6 @@ public: private: bool open(); void close(); - bool handleMessage(const char* schema, const char* key, std::string& value); struct Impl; Impl* impl = nullptr; diff --git a/src/window/wayland/WaylandWindow.cpp b/src/window/wayland/WaylandWindow.cpp index aa4eb1474..8467dadd4 100644 --- a/src/window/wayland/WaylandWindow.cpp +++ b/src/window/wayland/WaylandWindow.cpp @@ -1,9 +1,5 @@ #include "window/wayland/WaylandWindow.hpp" -#include -#include -#include - #include "settings.hpp" #include "graphics/core/Texture.hpp" #include "util/platform.hpp" @@ -20,6 +16,9 @@ WaylandWindow::WaylandWindow( } WaylandWindow::~WaylandWindow() { + if (window == this) { + window = nullptr; + } if (state.idleInhibitor) { zwp_idle_inhibitor_v1_destroy(state.idleInhibitor); } @@ -81,12 +80,30 @@ WaylandWindow::~WaylandWindow() { if (eglDisplay != EGL_NO_DISPLAY) { eglTerminate(eglDisplay); } + if (state.pointer) { + wl_pointer_destroy(state.pointer); + state.pointer = nullptr; + } + if (state.keyboard) { + wl_keyboard_destroy(state.keyboard); + state.keyboard = nullptr; + } + if (state.seat) { + wl_seat_destroy(state.seat); + state.seat = nullptr; + } + if (state.xkbState) { + xkb_state_unref(state.xkbState); + state.xkbState = nullptr; + } + if (state.xkbKeymap) { + xkb_keymap_unref(state.xkbKeymap); + state.xkbKeymap = nullptr; + } } double WaylandWindow::time() { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch() - ).count(); + return now(); } void WaylandWindow::swapBuffers() { @@ -297,7 +314,9 @@ void WaylandWindow::resize(int width, int height) { scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); } -void WaylandWindow::onConfigure(int32_t width, int32_t height, wl_array* states) { +void WaylandWindow::onConfigure( + int32_t width, int32_t height, wl_array* states +) { pendingWidth = width; pendingHeight = height; stateMaximized = false; @@ -339,63 +358,6 @@ void WaylandWindow::applyConfigure() { setShouldRefresh(); } -void WaylandWindow::pushScissor(glm::vec4 area) { - if (scissorStack.empty()) { - glEnable(GL_SCISSOR_TEST); - } - scissorStack.push(scissorArea); - - area.z += glm::ceil(area.x); - area.w += glm::ceil(area.y); - - area.x = glm::max(area.x, scissorArea.x); - area.y = glm::max(area.y, scissorArea.y); - - area.z = glm::min(area.z, scissorArea.z); - area.w = glm::min(area.w, scissorArea.w); - - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(glm::ceil(area.z - area.x))), - std::max(0, static_cast(glm::ceil(area.w - area.y))) - ); - } - scissorArea = area; -} - -void WaylandWindow::popScissor() { - if (scissorStack.empty()) { - waylandLogger.warning() << "extra Window::popScissor call"; - return; - } - glm::vec4 area = scissorStack.top(); - scissorStack.pop(); - if (area.z < 0.0f || area.w < 0.0f) { - glScissor(0, 0, 0, 0); - } else { - glScissor( - area.x, - size.y - area.w, - std::max(0, static_cast(area.z - area.x)), - std::max(0, static_cast(area.w - area.y)) - ); - } - if (scissorStack.empty()) { - glDisable(GL_SCISSOR_TEST); - } - scissorArea = area; -} - -void WaylandWindow::resetScissor() { - scissorArea = glm::vec4(0.0f, 0.0f, size.x, size.y); - scissorStack = std::stack(); - glDisable(GL_SCISSOR_TEST); -} - std::unique_ptr WaylandWindow::takeScreenshot() { glBindFramebuffer(GL_FRAMEBUFFER, 0); GLint readBuffer = 0; @@ -424,14 +386,6 @@ void WaylandWindow::setFramerate(int framerate) { } void WaylandWindow::initStretchRenderer() { - static const char* vertexSource = - "#version 330 core\n" - "layout(location = 0) in vec2 aPos;\n" - "out vec2 vUV;\n" - "void main() {\n" - " vUV = aPos * 0.5 + 0.5;\n" - " gl_Position = vec4(aPos, 0.0, 1.0);\n" - "}\n"; static const char* fragmentSource = "#version 330 core\n" "in vec2 vUV;\n" @@ -440,18 +394,15 @@ void WaylandWindow::initStretchRenderer() { "void main() {\n" " color = texture(uTexture, vUV);\n" "}\n"; - GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); - glShaderSource(vertexShader, 1, &vertexSource, nullptr); - glCompileShader(vertexShader); - GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); - glShaderSource(fragmentShader, 1, &fragmentSource, nullptr); - glCompileShader(fragmentShader); - stretchProgram = glCreateProgram(); - glAttachShader(stretchProgram, vertexShader); - glAttachShader(stretchProgram, fragmentShader); - glLinkProgram(stretchProgram); - glDeleteShader(vertexShader); - glDeleteShader(fragmentShader); + stretchProgram = compile_program(WAYLAND_VERTEX_SHADER, fragmentSource); + GLint stretchLinked = 0; + glGetProgramiv(stretchProgram, GL_LINK_STATUS, &stretchLinked); + if (stretchProgram == 0 || stretchLinked == 0) { + waylandLogger.error() << "failed to build the stretch shader"; + stretchProgram = 0; + return; + } + stretchTextureUniform = glGetUniformLocation(stretchProgram, "uTexture"); const float vertices[] {-1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f}; glGenVertexArrays(1, &stretchVao); @@ -472,14 +423,6 @@ void WaylandWindow::initShadowRenderer() { if (!shadowEnabled) { return; } - static const char* vertexSource = - "#version 330 core\n" - "layout(location = 0) in vec2 aPos;\n" - "out vec2 vUV;\n" - "void main() {\n" - " vUV = aPos * 0.5 + 0.5;\n" - " gl_Position = vec4(aPos, 0.0, 1.0);\n" - "}\n"; static const char* fragmentSource = "#version 330 core\n" "in vec2 vUV;\n" @@ -506,7 +449,8 @@ void WaylandWindow::initShadowRenderer() { " t * 0.17087277)))))))));\n" " return x >= 0.0 ? tau : 2.0 - tau;\n" "}\n" - "float boxDistance(vec2 p, vec2 center, vec2 halfSize, float radius) {\n" + "float boxDistance(vec2 p, vec2 center, vec2 halfSize, float radius)" + " {\n" " vec2 q = abs(p - center) - (halfSize - vec2(radius));\n" " return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - radius;\n" "}\n" @@ -519,12 +463,13 @@ void WaylandWindow::initShadowRenderer() { " uRadius + uSpread\n" " );\n" " float sigma = max(uBlur * 0.5, 0.001);\n" - " float alpha = uStrength * 0.5 * erfcApprox(shadow / (sigma * 1.41421356));\n" + " float alpha = uStrength * 0.5 * " + "erfcApprox(shadow / (sigma * 1.41421356));\n" " float side = boxDistance(p, center, halfSize, uRadius);\n" " float border = side > 0.0 && side <= 1.0 ? uBorder : 0.0;\n" " color = vec4(0.0, 0.0, 0.0, max(alpha, border));\n" "}\n"; - shadowProgram = compile_program(vertexSource, fragmentSource); + shadowProgram = compile_program(WAYLAND_VERTEX_SHADER, fragmentSource); GLint linked = 0; glGetProgramiv(shadowProgram, GL_LINK_STATUS, &linked); if (shadowProgram == 0 || linked == 0) { @@ -537,6 +482,7 @@ void WaylandWindow::initShadowRenderer() { } waylandLogger.error() << "failed to build the shadow shader: " << log; shadowEnabled = false; + resize(size.x, size.y); return; } const char* names[] { @@ -549,6 +495,15 @@ void WaylandWindow::initShadowRenderer() { } +namespace { + constexpr float SHADOW_BLUR = 7.0f; + constexpr float SHADOW_SPREAD = 1.0f; + constexpr float SHADOW_STRENGTH = 0.5f; + constexpr float SHADOW_STRENGTH_BACKDROP = 0.3f; + constexpr float SHADOW_BORDER = 0.1f; + constexpr float SHADOW_BORDER_BACKDROP = 0.05f; +} + void WaylandWindow::drawShadow() { const int margin = marginSize(); if (margin <= 0 || shadowProgram == 0) { @@ -574,11 +529,17 @@ void WaylandWindow::drawShadow() { static_cast(size.x), static_cast(size.y) ); - glUniform1f(shadowUniforms[2], 7.0f); - glUniform1f(shadowUniforms[3], activated ? 0.5f : 0.3f); + glUniform1f(shadowUniforms[2], SHADOW_BLUR); + glUniform1f( + shadowUniforms[3], + activated ? SHADOW_STRENGTH : SHADOW_STRENGTH_BACKDROP + ); glUniform1f(shadowUniforms[4], 0.0f); - glUniform1f(shadowUniforms[5], 1.0f); - glUniform1f(shadowUniforms[6], activated ? 0.1f : 0.05f); + glUniform1f(shadowUniforms[5], SHADOW_SPREAD); + glUniform1f( + shadowUniforms[6], + activated ? SHADOW_BORDER : SHADOW_BORDER_BACKDROP + ); glUniform1f(shadowUniforms[7], 0.0f); glBindVertexArray(stretchVao); glDrawArrays(GL_TRIANGLES, 0, 3); @@ -628,7 +589,7 @@ void WaylandWindow::composeFrame() { glUseProgram(stretchProgram); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, cacheTexture); - glUniform1i(glGetUniformLocation(stretchProgram, "uTexture"), 0); + glUniform1i(stretchTextureUniform, 0); glBindVertexArray(stretchVao); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); @@ -660,6 +621,9 @@ void WaylandWindow::resizeCache(int width, int height) { glBindTexture(GL_TEXTURE_2D, 0); } +/// @brief Copies the frame the engine just drew into a texture. +/// Runs every frame: composeFrame() rebuilds the window from this texture, +/// which keeps the engine itself unaware of the shadow margins. void WaylandWindow::cacheContent() { GlStateGuard state; if (stretchProgram == 0) { @@ -692,7 +656,7 @@ void WaylandWindow::drawStretched() { glUseProgram(stretchProgram); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, cacheTexture); - glUniform1i(glGetUniformLocation(stretchProgram, "uTexture"), 0); + glUniform1i(stretchTextureUniform, 0); glBindVertexArray(stretchVao); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); @@ -790,7 +754,5 @@ const wl_callback_listener& WaylandWindow::frameListener() { } double WaylandWindow::now() { - return std::chrono::duration( - std::chrono::steady_clock::now().time_since_epoch() - ).count(); + return waylandNow(); } diff --git a/src/window/wayland/WaylandWindow.hpp b/src/window/wayland/WaylandWindow.hpp index 38a822992..a50c81313 100644 --- a/src/window/wayland/WaylandWindow.hpp +++ b/src/window/wayland/WaylandWindow.hpp @@ -15,84 +15,85 @@ #include class WaylandWindow : public Window { -public: -WaylandInput& input; -DisplaySettings* settings; -EGLDisplay eglDisplay = EGL_NO_DISPLAY; -EGLContext eglContext = EGL_NO_CONTEXT; -EGLSurface eglSurface = EGL_NO_SURFACE; -wl_egl_window* eglWindow = nullptr; -int32_t pendingWidth = 0; -int32_t pendingHeight = 0; -bool stateMaximized = false; -bool stateSuspended = false; -bool stateActivated = true; -bool configured = false; -static constexpr double RESIZE_TIMEOUT = 0.4; -static constexpr double FRAME_TIMEOUT = 0.025; -static constexpr double RESIZE_PAUSE = 0.12; -static constexpr double MIN_CACHE_TIMEOUT = 0.3; -static constexpr double MAX_CACHE_TIMEOUT = 3.0; -int framerate = -1; -double prevSwap = 0.0; -double lastResize = 0.0; -bool barEnabled = false; -bool fullscreen = false; -std::string title = "VoxelCore"; -int hoveredButton = -1; -bool pointerInBar = false; -SettingsWatcher settingsWatcher; -bool layoutRead = false; -void applyLayoutValue(const std::string& value); + public: + WaylandInput& input; + DisplaySettings* settings; + EGLDisplay eglDisplay = EGL_NO_DISPLAY; + EGLContext eglContext = EGL_NO_CONTEXT; + EGLSurface eglSurface = EGL_NO_SURFACE; + wl_egl_window* eglWindow = nullptr; + int32_t pendingWidth = 0; + int32_t pendingHeight = 0; + bool stateMaximized = false; + bool stateSuspended = false; + bool stateActivated = true; + bool configured = false; + static constexpr double RESIZE_TIMEOUT = 0.4; + static constexpr double FRAME_TIMEOUT = 0.025; + static constexpr double RESIZE_PAUSE = 0.12; + static constexpr double MIN_CACHE_TIMEOUT = 0.3; + static constexpr double MAX_CACHE_TIMEOUT = 3.0; + int framerate = -1; + double prevSwap = 0.0; + double lastResize = 0.0; + bool barEnabled = false; + bool fullscreen = false; + std::string title = "VoxelCore"; + int hoveredButton = -1; + bool pointerInBar = false; + SettingsWatcher settingsWatcher; + bool layoutRead = false; + void applyLayoutValue(const std::string& value); std::vector leftButtons; std::vector rightButtons; std::vector barButtons; double lastLayoutCheck = 0.0; -double lastBarPress = 0.0; -double lastBarPressX = 0.0; -double lastBarPressY = 0.0; -double barPressX = 0.0; -double barPressY = 0.0; -uint32_t barPressSerial = 0; -bool barPressed = false; -bool initialSizeApplied = false; -mutable bool frameRendered = false; -bool sizeChanged = false; -bool barDragging = false; -int barPressedButton = -1; -int initialWidth = 0; -int initialHeight = 0; -double pointerX = 0.0; -double pointerY = 0.0; -bool frameOnCallback = false; -double frameInterval = 0.0; -double nextFrameTime = 0.0; -double frameCost = 0.0; -double cacheTimeout = 0.5; -bool resizing = false; -bool renderPending = true; -bool presentPending = true; -double lastPresent = 0.0; -wl_callback* frameCallback = nullptr; -bool frameDone = false; -GLuint stretchProgram = 0; -GLuint stretchVao = 0; -GLuint stretchVbo = 0; -GLuint cacheFbo = 0; -GLuint cacheTexture = 0; -int cacheWidth = 0; -int cacheHeight = 0; -double lastCacheTime = 0.0; -double lastSwapEnd = 0.0; -bool shouldRefresh = true; -bool shouldClose = false; -bool maximized = false; -bool suspended = false; -bool activated = true; -bool focusWarning = false; -std::stack scissorStack; -glm::vec4 scissorArea {}; - WaylandWindow( WaylandInput& input, DisplaySettings* settings, int width, int height ); + double lastBarPress = 0.0; + double lastBarPressX = 0.0; + double lastBarPressY = 0.0; + double barPressX = 0.0; + double barPressY = 0.0; + uint32_t barPressSerial = 0; + bool barPressed = false; + bool initialSizeApplied = false; + mutable bool frameRendered = false; + bool sizeChanged = false; + bool barDragging = false; + int barPressedButton = -1; + int initialWidth = 0; + int initialHeight = 0; + double pointerX = 0.0; + double pointerY = 0.0; + bool frameOnCallback = false; + double frameInterval = 0.0; + double nextFrameTime = 0.0; + double frameCost = 0.0; + double cacheTimeout = 0.5; + bool resizing = false; + bool renderPending = true; + bool presentPending = true; + double lastPresent = 0.0; + wl_callback* frameCallback = nullptr; + bool frameDone = false; + GLuint stretchProgram = 0; + GLint stretchTextureUniform = -1; + GLuint stretchVao = 0; + GLuint stretchVbo = 0; + GLuint cacheFbo = 0; + GLuint cacheTexture = 0; + int cacheWidth = 0; + int cacheHeight = 0; + double lastCacheTime = 0.0; + double lastSwapEnd = 0.0; + bool shouldRefresh = true; + bool shouldClose = false; + bool maximized = false; + bool suspended = false; + bool activated = true; + bool focusWarning = false; + WaylandWindow( + WaylandInput& input, DisplaySettings* settings, int width, int height + ); ~WaylandWindow() override; double time() override; void swapBuffers() override; @@ -101,6 +102,9 @@ glm::vec4 scissorArea {}; bool isMaximized() const override; bool isFocused() const override; bool isIconified() const override; + /// @brief Whether the engine is going to draw a frame now. + /// The answer is remembered, so swapBuffers() can tell a freshly drawn + /// frame from a buffer the engine skipped (it would be undefined). bool isFrameRequired() const override; bool isShouldClose() const override; void setShouldClose(bool flag) override; @@ -113,9 +117,6 @@ glm::vec4 scissorArea {}; int getDecorationHeight() const override; int getDecorationHoveredButton() const override; - - - static constexpr int BAR_HEIGHT = 48; static constexpr int BAR_BUTTON = 24; static constexpr int BAR_PADDING = 12; @@ -126,7 +127,7 @@ glm::vec4 scissorArea {}; bool shadowEnabled = false; GLuint shadowProgram = 0; - GLint shadowUniforms[7] {}; + GLint shadowUniforms[8] {}; int marginSize() const; @@ -151,11 +152,8 @@ glm::vec4 scissorArea {}; void makeContentOpaque(int x, int y, int width, int height); - int decorationOffset() const { - return barVisible() ? BAR_HEIGHT : 0; - } - - const std::vector& getDecorationButtons() const override; + const std::vector& getDecorationButtons() const + override; void updateButtonLayout(); @@ -172,9 +170,6 @@ glm::vec4 scissorArea {}; void resize(int width, int height); void onConfigure(int32_t width, int32_t height, wl_array* states); void applyConfigure(); - void pushScissor(glm::vec4 area) override; - void popScissor() override; - void resetScissor() override; std::unique_ptr takeScreenshot() override; void setFramerate(int framerate) override; void initStretchRenderer(); @@ -182,6 +177,7 @@ glm::vec4 scissorArea {}; void cacheContent(); void drawStretched(); void enableOwnDecorations(); + void disableOwnDecorations(); bool barVisible() const; int barButtonAt(double x, double y) const; uint32_t barEdgeAt(double x, double y) const;