Bläddra i källkod

Animated wallpaper transitions, RGB lighting (--leds via OpenRGB), reversed scene depth, Pantheon shell, system font fallback, PVS-Studio clean, clang build check, faster VM release rig

UwU 1 månad sedan
förälder
incheckning
00d877394a
100 ändrade filer med 4191 tillägg och 730 borttagningar
  1. 19 0
      CMakeLists.txt
  2. 24 14
      README.md
  3. 0 74
      docs/investigations/puppet-and-renderer-notes.md
  4. 3 5
      docs/rendering/CAMERA_SETTINGS.md
  5. 13 9
      docs/rendering/GENERAL_SETTINGS.md
  6. 7 6
      docs/rendering/IMAGE_OBJECTS.md
  7. 18 0
      docs/rendering/OBJECTS.md
  8. 41 38
      docs/textures/TEXTURE_FORMAT.md
  9. 144 13
      src/WallpaperEngine/Application/ApplicationContext.cpp
  10. 36 12
      src/WallpaperEngine/Application/ApplicationContext.h
  11. 130 9
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  12. 4 1
      src/WallpaperEngine/Application/WallpaperApplication.h
  13. 2 1
      src/WallpaperEngine/Audio/Drivers/PulseProcessVolume.cpp
  14. 1 1
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp
  15. 2 1
      src/WallpaperEngine/Audio/Hrtf.cpp
  16. 6 5
      src/WallpaperEngine/Data/Builders/VectorBuilder.h
  17. 4 1
      src/WallpaperEngine/Data/JSON.h
  18. 6 4
      src/WallpaperEngine/Data/Model/DynamicValue.cpp
  19. 1 0
      src/WallpaperEngine/Data/Model/DynamicValue.h
  20. 15 15
      src/WallpaperEngine/Data/Model/Effect.cpp
  21. 2 2
      src/WallpaperEngine/Data/Model/Effect.h
  22. 4 4
      src/WallpaperEngine/Data/Model/Material.h
  23. 18 18
      src/WallpaperEngine/Data/Model/Object.h
  24. 2 2
      src/WallpaperEngine/Data/Model/Project.h
  25. 2 1
      src/WallpaperEngine/Data/Parsers/DynamicValueParser.cpp
  26. 20 11
      src/WallpaperEngine/Data/Parsers/PropertyParser.cpp
  27. 11 0
      src/WallpaperEngine/Data/Utils/BinaryReader.cpp
  28. 2 0
      src/WallpaperEngine/Data/Utils/BinaryReader.h
  29. 25 0
      src/WallpaperEngine/Data/Utils/FloatCompare.h
  30. 2 2
      src/WallpaperEngine/Debugging/CallStack.h
  31. 0 28
      src/WallpaperEngine/Desktop/GnomeShell.cpp
  32. 246 0
      src/WallpaperEngine/Desktop/PantheonShell.cpp
  33. 59 0
      src/WallpaperEngine/Desktop/PantheonShell.h
  34. 26 0
      src/WallpaperEngine/Desktop/SessionBus.cpp
  35. 3 0
      src/WallpaperEngine/Desktop/SessionBus.h
  36. 6 6
      src/WallpaperEngine/Desktop/UserShortcut.cpp
  37. 2 2
      src/WallpaperEngine/FileSystem/Adapters/Types.h
  38. 24 0
      src/WallpaperEngine/Led/LedHub.cpp
  39. 9 0
      src/WallpaperEngine/Led/LedHub.h
  40. 93 0
      src/WallpaperEngine/Led/LedLayout.cpp
  41. 30 0
      src/WallpaperEngine/Led/LedLayout.h
  42. 391 0
      src/WallpaperEngine/Led/LedOutput.cpp
  43. 54 0
      src/WallpaperEngine/Led/LedOutput.h
  44. 186 0
      src/WallpaperEngine/Led/OpenRgbProtocol.cpp
  45. 53 0
      src/WallpaperEngine/Led/OpenRgbProtocol.h
  46. 8 8
      src/WallpaperEngine/Logging/Log.h
  47. 4 3
      src/WallpaperEngine/Media/DBusMediaSource.cpp
  48. 3 1
      src/WallpaperEngine/Render/AlbumTexture.cpp
  49. 5 3
      src/WallpaperEngine/Render/CFBO.cpp
  50. 3 2
      src/WallpaperEngine/Render/CTexture.cpp
  51. 11 4
      src/WallpaperEngine/Render/CWallpaper.cpp
  52. 3 0
      src/WallpaperEngine/Render/CWallpaper.h
  53. 19 11
      src/WallpaperEngine/Render/Camera.cpp
  54. 96 0
      src/WallpaperEngine/Render/DepthRange.cpp
  55. 34 0
      src/WallpaperEngine/Render/DepthRange.h
  56. 41 1
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp
  57. 4 0
      src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h
  58. 0 1
      src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp
  59. 0 1
      src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.cpp
  60. 5 0
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutput.cpp
  61. 1 1
      src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp
  62. 203 60
      src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.cpp
  63. 6 4
      src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.h
  64. 13 6
      src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp
  65. 3 0
      src/WallpaperEngine/Render/Drivers/Output/X11Output.h
  66. 318 0
      src/WallpaperEngine/Render/Fonts/SystemFonts.cpp
  67. 33 0
      src/WallpaperEngine/Render/Fonts/SystemFonts.h
  68. 2 1
      src/WallpaperEngine/Render/FrameMaterial.cpp
  69. 1 0
      src/WallpaperEngine/Render/Helpers/ContextAware.h
  70. 7 2
      src/WallpaperEngine/Render/ImageDecoder.cpp
  71. 231 0
      src/WallpaperEngine/Render/LedFrameGrabber.cpp
  72. 35 0
      src/WallpaperEngine/Render/LedFrameGrabber.h
  73. 2 2
      src/WallpaperEngine/Render/MissingTexture.cpp
  74. 3 3
      src/WallpaperEngine/Render/Objects/CCamera.cpp
  75. 19 12
      src/WallpaperEngine/Render/Objects/CImage.cpp
  76. 6 5
      src/WallpaperEngine/Render/Objects/CMesh.cpp
  77. 6 5
      src/WallpaperEngine/Render/Objects/CParticle.h
  78. 5 11
      src/WallpaperEngine/Render/Objects/CSound.cpp
  79. 61 88
      src/WallpaperEngine/Render/Objects/CText.cpp
  80. 14 13
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  81. 4 3
      src/WallpaperEngine/Render/Objects/PuppetIK.cpp
  82. 8 2
      src/WallpaperEngine/Render/Objects/PuppetMeshFile.cpp
  83. 26 22
      src/WallpaperEngine/Render/Objects/PuppetRig.cpp
  84. 9 19
      src/WallpaperEngine/Render/Objects/TextLayout.cpp
  85. 311 8
      src/WallpaperEngine/Render/RenderContext.cpp
  86. 14 4
      src/WallpaperEngine/Render/RenderContext.h
  87. 0 1
      src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp
  88. 12 4
      src/WallpaperEngine/Render/ShadowMapping.cpp
  89. 25 24
      src/WallpaperEngine/Render/TextureCache.cpp
  90. 1 1
      src/WallpaperEngine/Render/TextureCache.h
  91. 36 0
      src/WallpaperEngine/Render/Transition.h
  92. 27 41
      src/WallpaperEngine/Render/Utils/NoiseUtils.h
  93. 36 12
      src/WallpaperEngine/Render/Volumetrics.cpp
  94. 6 4
      src/WallpaperEngine/Render/WallpaperState.cpp
  95. 79 12
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  96. 8 2
      src/WallpaperEngine/Render/Wallpapers/CScene.h
  97. 340 13
      src/WallpaperEngine/Render/Wallpapers/CSplat.cpp
  98. 32 0
      src/WallpaperEngine/Render/Wallpapers/CSplat.h
  99. 246 25
      src/WallpaperEngine/Render/Wallpapers/CVideo.cpp
  100. 20 0
      src/WallpaperEngine/Render/Wallpapers/CVideo.h

+ 19 - 0
CMakeLists.txt

@@ -479,6 +479,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Media/DBusMediaSource.cpp
     src/WallpaperEngine/Desktop/GnomeShell.h
     src/WallpaperEngine/Desktop/GnomeShell.cpp
+    src/WallpaperEngine/Desktop/PantheonShell.h
+    src/WallpaperEngine/Desktop/PantheonShell.cpp
     src/WallpaperEngine/Desktop/WindowState.h
     src/WallpaperEngine/Desktop/WindowState.cpp
     src/WallpaperEngine/Desktop/KWinScript.h
@@ -568,6 +570,18 @@ set(COMMON_SOURCES
 
     src/WallpaperEngine/Splat/SogLoader.h
     src/WallpaperEngine/Splat/SogLoader.cpp
+    src/WallpaperEngine/Led/LedHub.h
+    src/WallpaperEngine/Led/LedHub.cpp
+    src/WallpaperEngine/Led/LedLayout.h
+    src/WallpaperEngine/Led/LedLayout.cpp
+    src/WallpaperEngine/Led/LedOutput.h
+    src/WallpaperEngine/Led/LedOutput.cpp
+    src/WallpaperEngine/Led/OpenRgbProtocol.h
+    src/WallpaperEngine/Led/OpenRgbProtocol.cpp
+    src/WallpaperEngine/Render/LedFrameGrabber.h
+    src/WallpaperEngine/Render/LedFrameGrabber.cpp
+    src/WallpaperEngine/Render/DepthRange.h
+    src/WallpaperEngine/Render/DepthRange.cpp
     src/WallpaperEngine/Render/Camera.h
     src/WallpaperEngine/Render/Camera.cpp
     src/WallpaperEngine/Render/CObject.h
@@ -604,6 +618,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/Objects/CText.cpp
     src/WallpaperEngine/Render/Objects/TextLayout.h
     src/WallpaperEngine/Render/Objects/TextLayout.cpp
+    src/WallpaperEngine/Render/Fonts/SystemFonts.h
+    src/WallpaperEngine/Render/Fonts/SystemFonts.cpp
     src/WallpaperEngine/Render/Objects/CLight.h
     src/WallpaperEngine/Render/Objects/CLight.cpp
     src/WallpaperEngine/Render/Objects/CCamera.h
@@ -752,6 +768,7 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/DmabufChannel.cpp
         src/WallpaperEngine/Testing/Cases/DynamicValueListeners.cpp
         src/WallpaperEngine/Testing/Cases/Example.cpp
+        src/WallpaperEngine/Testing/Cases/Leds.cpp
         src/WallpaperEngine/Testing/Cases/FramePacer.cpp
         src/WallpaperEngine/Testing/Render/TestingOpenGLDriver.cpp
         src/WallpaperEngine/Testing/Render/TestingOpenGLDriver.h
@@ -760,6 +777,7 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Harnesses/RenderHarness.cpp
         src/WallpaperEngine/Testing/Harnesses/RenderHarness.h
         src/WallpaperEngine/Testing/Cases/MouseCoordinates.cpp
+        src/WallpaperEngine/Testing/Cases/SystemFonts.cpp
         src/WallpaperEngine/Testing/Cases/PropertyParser.cpp
         src/WallpaperEngine/Testing/Cases/SpectrumListeners.cpp
         src/WallpaperEngine/Testing/Cases/SpectrumPipeline.cpp
@@ -773,6 +791,7 @@ if(BUILD_TESTING)
         src/WallpaperEngine/Testing/Cases/ModuleNamespaceTiming.cpp
         src/WallpaperEngine/Testing/Cases/AudioSensitivity.cpp
         src/WallpaperEngine/Testing/Cases/ThumbnailPalette.cpp
+        src/WallpaperEngine/Testing/Cases/Transition.cpp
         src/WallpaperEngine/Testing/Cases/TextInputProperty.cpp
         src/WallpaperEngine/Testing/Cases/TextLayoutRules.cpp
         src/WallpaperEngine/Testing/Cases/MediaCover.cpp

+ 24 - 14
README.md

@@ -70,10 +70,12 @@ KDE Plasma and Wayland:
 Control:
 
 - Multi-monitor handling: per-screen backgrounds (`--screen-root`), one wallpaper spanning several monitors (`--screen-span`), several wallpapers side by side on one monitor (`--screen-slot`), per-screen scaling/zoom/alignment/corner color, and Workshop playlists (`--playlist`).
+- Animated transitions when the wallpaper changes (playlist or hotswap): fade, slide, wipe or zoom, `--transition` and `--transition-duration`.
 - Live hotswap of the running wallpaper and its settings via `SIGUSR1`, separately per engine with `--control-file`, no process restart.
 - A global playback speed multiplier (`--speed`), separate from the FPS cap; battery and idle pause (`--fps-battery`, `--idle-pause`).
 - Video wallpapers can loop just part of the video (`--video-start`/`--video-end`), or several parts one after the other (`--video-segments "2:00-3:00,4:00-5:00"`).
 - More granular audio: restrict sound to a single screen (`--audio-screen`), a separate ambient volume for non-video backgrounds (`--ambient-volume`), per-object sound volume (`--sound-volume`), and a tunable multiplier on audio-reactive properties (`--audio-sensitivity`, with `--list-audio-objects` to see what's wired up).
+- RGB lighting like Wallpaper Engine's LED plugin (`--leds`): the scene, or the layers marked as LED source, shrunk to 80 x 10 and sent to every device of an OpenRGB server.
 - Layer and effect introspection and toggling (`--list-objects`, `--disable-object`, `--list-effects`, `--disable-effect`, ...) for things the wallpaper author didn't expose as a property.
 - Supersampling (`--ssaa`), an expanded canvas for oversize scenes (`--expand-canvas`), `--repair-assets` for wallpapers that only worked in older Wallpaper Engine versions.
 - Web wallpapers in a separate, disposable process with GPU frame transfer through dmabuf (`--web-frames`), SOG depth-photo wallpapers drawn natively.
@@ -131,7 +133,7 @@ sudo epm install gcc-c++ make cmake libXrandr-devel libXinerama-devel libXcompos
 Tagged releases on the [releases page](https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde/releases) have ready-to-run builds, each with (`kde`) and without (`generic`) the KDE Plasma integration:
 
 - **Portable** (`linux-wallpaperengine-kde-portable-x86_64.tar.gz`): runs on any x86_64 distribution with glibc 2.35 or newer (Ubuntu 22.04 and newer, Debian 12+, Fedora, openSUSE, Arch, SteamOS, Bazzite, Silverblue/Kinoite and other image-based systems) without installing anything: it carries FFmpeg, mpv, V8 and the rest, and only uses what every desktop has (Mesa, the display server's and audio server's libraries, the GTK stack CEF needs). A few libraries it brings are only used where the system has no library of that name (`lib/fallback`), the `linux-wallpaperengine` script in the folder takes care of that.
-- **Distribution builds** for Ubuntu 24.04, Fedora 44 and Arch Linux use the distribution's own FFmpeg, mpv and so on: install the runtime packages from the list above (the non `-dev`/`-devel` ones). The Arch build also needs the AUR's `libnode`.
+- **Distribution builds** for Ubuntu 24.04, Fedora 44 and Arch Linux use the distribution's own FFmpeg, mpv and so on: install the runtime packages from the list above (the non `-dev`/`-devel` ones). The Arch build also needs `libnode`, from the AUR or prebuilt from the `libnode-arch` release (see Limitations).
 
 ```bash
 tar xzf linux-wallpaperengine-kde-portable-x86_64.tar.gz
@@ -178,15 +180,15 @@ fullscreen window and automute.
 | EndeavourOS | XFCE (X11) | Supported | |
 | Linux Mint 22.2 | Cinnamon (X11) | Supported | |
 | MX Linux 25.3 | XFCE (X11) | Supported | |
-| Zorin OS | GNOME (Wayland) | Supported | its Xorg session shows nothing in root mode |
+| Zorin OS | GNOME (Wayland and Xorg) | Supported | |
 | Pop!_OS | COSMIC | Supported | |
 | Bazzite | KDE Plasma (Wayland), image based | Supported | portable build or Flatpak |
 | SteamOS | KDE Plasma (Wayland), read-only root | Supported | system libraries cannot be installed on the read-only root, so that step is not part of the test |
-| Steam Deck (SteamOS on Deck hardware) | KDE Plasma (Wayland), read-only root | Work in progress | the engine runs in the Deck-shaped VM, but the VM's screen goes blank in the screenshot checks (Steam takes the display there), so the picture checks do not pass yet |
-| elementary OS | Pantheon (Wayland) | Supported | Gala has no `wlr-layer-shell`, the engine draws through XWayland: only X11 windows pause it, and the wallpaper takes the clicks on the desktop |
+| Steam Deck (SteamOS on Deck hardware) | KDE Plasma (Wayland), read-only root | Supported | tested in a VM shaped like the Deck (1280x800, fake battery), system libraries cannot be installed on the read-only root, so that step is not part of the test |
+| elementary OS | Pantheon (Wayland) | Supported | Gala has no `wlr-layer-shell`, the engine draws through XWayland and the wallpaper takes the clicks on the desktop. Fullscreen windows pause it (X11 ones, native Wayland ones through Gala's D-Bus window list), maximized native ones don't |
 | ChimeraOS | gamescope, GNOME | Not supported | not tested: its Mesa cannot draw in a VM, and gamescope's game session has no desktop to put a wallpaper on. The GNOME desktop mode could theoretically work |
 
-Other distributions and desktops that are not listed (Sway, niri, KDE on X11, other Ubuntu flavours, ...) may well work,
+Other distributions and desktops that are not listed (other Ubuntu flavours, ...; sway, niri, KDE on X11 and more are covered by the headless desktop lab, not by real sessions) may well work,
 they are just not part of the release test.
 
 ## Build
@@ -209,7 +211,7 @@ cmake -DCMAKE_BUILD_TYPE='Release' -DDISABLE_KDE_FEATURES=ON ..
 
 On KDE Plasma the engine loads KWin scripts of its own for the cursor position and for the windows that pause it (maximized, fullscreen, and focused with `--pause-on-focus`), per screen like Wallpaper Engine; nothing needs installing.
 
-On a Wayland compositor that offers no layer shell and isn't GNOME (Gala on elementary OS) the engine falls back to XWayland: it draws into a desktop type background window of its own, like `--screen-root` does on an X11 desktop. Wallpapers, scripts and the pointer work as usual, but only X11 windows pause it (such a compositor tells native Wayland clients nothing about its windows) and the wallpaper window takes the clicks that would reach the desktop.
+On a Wayland compositor that offers no layer shell and isn't GNOME (Gala on elementary OS) the engine falls back to XWayland: it draws into a desktop type background window of its own, like `--screen-root` does on an X11 desktop. Wallpapers, scripts and the pointer work as usual, X11 windows pause it, and on Gala native Wayland windows too, through its `org.pantheon.gala.DesktopIntegration` D-Bus interface (it gives sizes but no fullscreen or maximized flag, so a window at least as large as a screen counts as fullscreen and maximized ones don't pause). The wallpaper window takes the clicks that would reach the desktop.
 
 On sway, Hyprland, niri, labwc and other compositors with the wlr foreign toplevel protocol a fullscreen window pauses only the screen it is on (maximized ones too with `--pause-on-maximized`). sway before 1.12 doesn't say which screen a window that opens fullscreen is on, so such a window pauses every screen there.
 
@@ -234,6 +236,8 @@ linux-wallpaperengine --assets-dir /path/to/assets
 
 Some wallpapers show emoji in their text layers and expect Windows' emoji font, Segoe UI Emoji (`seguiemj.ttf`). It is not part of this repo (it is Microsoft's font), but installing it makes those wallpapers look exactly like on Windows: copy `C:\Windows\Fonts\seguiemj.ttf` from a Windows install to `~/.local/share/fonts/` and run `fc-cache -f`. Without it the emoji come from the Twemoji font in Wallpaper Engine's assets. Wallpapers using `systemfont_*` text likewise look closest with the Windows fonts they name (Arial, Segoe UI, ...) or their metric-compatible clones installed.
 
+Fonts for wallpapers can also be put in `~/.local/share/linux-wallpaperengine/fonts/` (`LWE_FONT_DIR` changes the folder): the text renderer sees them next to the system's fonts without installing them anywhere else, so a Segoe UI, Arial or Segoe UI Emoji file there is used for the wallpapers that ask for it. `linux-wallpaperengine --list-fonts <wallpaper>` lists what a wallpaper's texts need that this system lacks (a Windows font replaced by another one, emoji without Segoe UI Emoji), the engine also says so in its log when a text loads, and we_manager shows the same warning with an "Add font" button.
+
 ## Usage
 
 ```bash
@@ -255,6 +259,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--window <XxYxWxH>` | Run in windowed mode with custom size/position |
 | `--window-normal` | With `--window`: a regular window with a title bar that can be moved, resized, closed and covered by other windows, instead of the borderless window that stays on top |
 | `--window-background` | X11 only, with `--window`: the window acts as the desktop background (desktop type, below every other window, on all workspaces, off the taskbar, never focused, clicks go through, desktop icons stay above it). For desktops that don't show a root window wallpaper, e.g. some Cinnamon setups |
+| `--no-desktop-icons` | X11 only: leave the icons of an opaque desktop window (xfdesktop, caja, pcmanfm-qt) under the wallpaper instead of drawing them above it; the desktop's background is not touched. Same as `LWE_DESKTOP_ICONS=off` |
 | `--screen-root <screen>` | Set as background for a specific screen |
 | `--screen-span <screen-1>,<screen-2>,...` | Stretch a single wallpaper across multiple screens |
 | `--screen-slot <screen>` | Add a slot to a screen, once per wallpaper, so several share it side by side (stacked on a portrait screen); the following `--bg`, `--scaling`, etc. apply to that slot, called `<screen>#<n>` |
@@ -273,6 +278,8 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--brightness`, `--contrast`, `--saturation`, `--hue <0-100>` | Wallpaper Engine's color options, 50 leaves the image unchanged |
 | `--color-options on/off` | Turn the color options (also ones a preset carries) on or off |
 | `--flip on/off` | Mirror the wallpaper horizontally |
+| `--transition <kind>` | Animation when another wallpaper takes over (playlist, hotswap): `none` (default), `fade`, `slide-left`, `slide-right`, `wipe-left`, `wipe-right` or `zoom`. Control file: `transition=` |
+| `--transition-duration <ms>` | Length of the transition, 100 to 5000, default 600. Control file: `transition-duration=` |
 | `--hdr` | Wayland only: HDR (PQ, BT.2020) output to monitors running in HDR mode, HDR videos in HDR |
 | `--layer <layer>` | Wayland only: `wlr-layer-shell` layer (`background`, `bottom`, `top`, `overlay`). Default `bottom`, on KDE `background` can end up under plasmashell's desktop window |
 | `--speed <factor>` | Global playback speed multiplier |
@@ -298,6 +305,7 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--disable-object <id/name>` | Hide an object/layer, repeatable |
 | `--enable-object <id/name>` | Force an object/layer to show, repeatable |
 | `--list-effects` | List every effect with id, editor name and category |
+| `--list-fonts` | List the fonts a wallpaper's texts need that this system doesn't have, and what is drawn instead |
 | `--disable-effect <id/name>`, `--enable-effect <id/name>` | Turn an effect off, or force a hidden one on, repeatable |
 | `--disable-particles` | Disable particles |
 | `--disable-mouse` | Disable mouse interaction |
@@ -317,6 +325,8 @@ The background can be a Steam Workshop ID (`1845706469`) or a path to a backgrou
 | `--sound-volume <id/name>=<val>` | Per-object volume (0-1), repeatable, `*` for unmatched objects |
 | `--audio-sensitivity <id/name>=<mult>` | Scale an object's audio-reactive swing; `0` disables it, `1` is default; repeatable, `*` for unmatched objects |
 | `--list-audio-objects` | List objects whose script reacts to music |
+| `--leds`, `--leds-server <host[:port]>` | Send the scene's colors to the RGB devices of an OpenRGB server (start it with `openrgb --server`, default `127.0.0.1:6742`). Layers with `ledsource` are used (the first one in the scene), else the whole scene |
+| `--leds-brightness <percent>`, `--leds-no-boost`, `--leds-reduce-fps` | Brightness factor, leave the colors as they are instead of raising each led's strongest channel to full (WE's "Boost LED colors"), update 15 times a second instead of 30 |
 | `--dump-structure`, `--render-debug <mode>` | Debugging output, see `--help` |
 | `--no-shader-cache` | Translate and link every shader from scratch instead of using `~/.cache/linux-wallpaperengine/shaders` |
 
@@ -404,8 +414,8 @@ linux-wallpaperengine --disable-object Clock --disable-object 3 2370927443
 
 - Wayland: needs a compositor with `wlr-layer-shell-unstable` and `xdg-output-unstable-v1` (the latter for accurate monitor positioning with `--screen-span`). On KDE Plasma the engine uses KWin's `plasma-shell` surfaces and KWin's cursor position on top of that.
 - GNOME on Wayland: Mutter has no layer-shell, so the engine needs its GNOME Shell extension (`gnome-shell-extension/`, installed next to the binary; GNOME 45 to 50, on 45-48 it starts its `linux-wallpaperengine-gnome-helper` from its own folder). Desktop Icons NG works on top of it, clicks on the empty desktop reach the wallpaper like on Windows. Copy `linux-wallpaperengine@wallpaperenginelover.github.io` to `~/.local/share/gnome-shell/extensions/`, run `gnome-extensions enable linux-wallpaperengine@wallpaperenginelover.github.io` and log out and back in once (we_manager offers to do it). Outputs are the connector names (`DP-1`, `HDMI-A-1`).
-- X11: needs XRandr; target monitors with `--screen-root <name>` as reported by `xrandr`. Doesn't work if something else (GNOME, KDE, Nautilus) is already drawing the desktop background/compositing it.
-- XFCE (xfdesktop) draws an opaque desktop window over the root window, which the wallpaper goes above, so its icons would be hidden. The engine keeps them: while it runs, xfdesktop's background is set to black (xfconf, `image-style`/`color-style`/`rgba1` of every monitor and workspace, the old values are saved and put back on exit, also after a crash), the window's pixels are read through the Composite extension whenever it changes and everything that is not black is drawn over the wallpaper frame. xfdesktop keeps handling every click. Needs the Composite and Damage extensions (always there on Xorg); `LWE_DESKTOP_ICONS=off` leaves xfdesktop alone and the icons under the wallpaper. A desktop that never picked a wallpaper gets `xfce-shapes.svg` (or the first of xfce's own pictures) afterwards, xfdesktop's built-in default can't be set again. Other desktops with an opaque desktop window (MATE, LXQt) still hide their icons.
+- X11: needs XRandr; target monitors with `--screen-root <name>` as reported by `xrandr`. Desktops whose compositor paints its own background over the root window (GNOME, Pantheon, Cinnamon) get a background window of the engine's own automatically; `LWE_X11_BACKGROUND_WINDOW=1` does the same on any other desktop and `0` draws on the root window again.
+- XFCE (xfdesktop) draws an opaque desktop window over the root window, which the wallpaper goes above, so its icons would be hidden. The engine keeps them: while it runs, xfdesktop's background is set to black (xfconf, `image-style`/`color-style`/`rgba1` of every monitor and workspace, the old values are saved and put back on exit, also after a crash), the window's pixels are read through the Composite extension whenever it changes and everything that is not black is drawn over the wallpaper frame. xfdesktop keeps handling every click. Needs the Composite and Damage extensions (always there on Xorg); `LWE_DESKTOP_ICONS=off` leaves xfdesktop alone and the icons under the wallpaper. A desktop that never picked a wallpaper gets `xfce-shapes.svg` (or the first of xfce's own pictures) afterwards, xfdesktop's built-in default can't be set again. MATE's caja and LXQt's pcmanfm-qt get the same treatment (caja's background through gsettings, pcmanfm-qt's with `pcmanfm-qt --wallpaper-mode`, both restored on exit); `--no-desktop-icons` or `LWE_DESKTOP_ICONS=off` leaves all of them alone.
 
 ## Limitations
 
@@ -413,13 +423,13 @@ The scene renderer follows Wallpaper Engine 2.8 closely, but not everything is t
 
 Platform and setup:
 
-- On X11, a compositor or DE drawing its own background will block the wallpaper. Disabling the compositor is currently the only fix.
-- HDR output (`--hdr`) is Wayland only and needs a compositor with the color-management protocol.
-- Some NVIDIA setups hit GLFW/OpenGL init failures; try `__GL_THREADED_OPTIMIZATIONS=0 linux-wallpaperengine` if you run into this.
+- HDR output (`--hdr`) is Wayland only and needs a compositor with the color-management protocol (`wp_color_manager_v1`). X11 has no HDR, neither the server nor any X11 compositor can show it, so that stays the way it is. Checked on a real HDR monitor under KDE Plasma only.
+- On Wayland, web wallpapers and scene wallpapers with click handlers (e.g. bone dragging) take all mouse clicks on the desktop, so the right click menu of the desktop doesn't open while they are shown. A Wayland input region can't be limited to one mouse button, and a click can't be passed on to the surface below. Wallpapers without click handlers don't take clicks where the compositor gives the pointer position (KDE Plasma, Hyprland, GNOME).
+- KDE Plasma 5 on Wayland doesn't pause behind windows: KWin 5 has no `workspace.windowList` in its scripting API (Plasma 6 is fine).
+- elementary OS (Pantheon) has no `wlr-layer-shell`, so the engine draws through XWayland. XWayland only reports the pointer over its own windows, so the wallpaper keeps its input region to follow the cursor (parallax, cursor effects) and takes all clicks on the desktop: the desktop's right click menu doesn't open. That is a limit of XWayland, not something the engine can work around. Windows that cover an output pause it, maximized windows don't.
 - Windows fonts (`systemfont_*`) are replaced by the closest installed match through fontconfig, so text can look slightly different if Arial, Segoe UI etc. or their metric-compatible clones aren't installed.
-- RGB lighting output (iCUE/Chroma `ledsource`) is ignored.
-- Arch has `libnode` only in the AUR, so the Arch release build needs it installed from there.
-- On Wayland, web wallpapers and scene wallpapers with click handlers (e.g. bone dragging) take all mouse clicks on the desktop, so the right click menu of the desktop doesn't open while they are shown. A Wayland input region can't be limited to one mouse button, and a click can't be passed on to the surface below.
+- RGB lighting (`--leds`) goes through an OpenRGB server only (no iCUE or Razer Chroma SDK) and only scene wallpapers feed it, not video or web ones. OpenRGB has no led positions, so a keyboard keeps its grid and the other zones become rows; Wallpaper Engine places every led by its real position.
+- The Arch distribution build needs `libnode` (a Node.js built with `--shared`, Arch's `nodejs` has no shared library). The AUR has it, and the CI keeps a prebuilt package as an asset of the [`libnode-arch` release](https://github.com/WallpaperEngineLover/linux-wallpaperengine-kde/releases/tag/libnode-arch): `sudo pacman -U libnode-*-x86_64.pkg.tar.zst`. we_manager's build section has an "Install libnode" button on Arch that does exactly this. The portable build and `-bin` bring their own V8.
 
 Text:
 

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 0 - 74
docs/investigations/puppet-and-renderer-notes.md


+ 3 - 5
docs/rendering/CAMERA_SETTINGS.md

@@ -1,5 +1,3 @@
-# camera settings
-- camera:
- - eye: where the camera is at
- - center: wherte the camera is pointing at
- - up: the up vector
+# Camera settings
+`camera` of `scene.json`: `center`, `eye`, `up` (vectors). `paths` holds camera paths (keyframed `transforms`, `duration`), switched with the `camerafade` effect.
+`fov`, `nearz` and `farz` are in `general`, see GENERAL_SETTINGS.md; orthographic scenes ignore the clip distances.

+ 13 - 9
docs/rendering/GENERAL_SETTINGS.md

@@ -1,12 +1,16 @@
 # General scene settings
-- ambientcolor: Color to use when clearing the scene
-- bloom: Whether bloom is enabled or not
+`general` of `scene.json` (`Data/Parsers/WallpaperParser.cpp`):
 
-- orthogonalprojection:
- - width: width of the orthogonalprojection
- - height: height of the orthogonal projection
+- orthogonalprojection: `{width, height}` (or `auto`), `null` or anything else means a perspective camera
+- fov, nearz, farz: perspective camera
+- clearcolor: color the scene is cleared to; ambientcolor, skylightcolor: lighting
+- zoom, perspectiveoverridefov
+- bloom, bloomstrength, bloomthreshold, bloomtint, hdr, bloomhdrstrength/threshold/scatter/feather/iterations
+- camerafade, cameraparallax, cameraparallaxamount, cameraparallaxdelay, cameraparallaxmouseinfluence, camerapreview
+- camerashake, camerashakeamplitude, camerashakeroughness, camerashakespeed
+- fogdistance*/fogheight* (color, start, end and their densities): fog
+- gravitydirection, gravitystrength, windenabled, winddirection, windstrength: forces rope chains and particles read
+- lightconfig: number of point, spot, tube and directional lights and their shadow/cookie settings
+- transparentsorting, spritesheetrefreshsync
 
-# camera settings
-- farz: projection's far clip (optional)
-- nearz: projection's near clip (optional)
-- fov: field of view (optional)
+Most of these accept scripts and animations like object properties.

+ 7 - 6
docs/rendering/IMAGE_OBJECTS.md

@@ -1,11 +1,12 @@
 # Image objects
 Image objects are simple quads that display an image in them. These are usually used in orthogonal scenes to display animated effects.
 
-Looks like every image object has two framebuffers used for ping-pong when rendering, these are usually registered as:
-- _rt_imageLayerComposite_{id}_a
-- _rt_imageLayerComposite_{id}_b
+Image objects with effects ping-pong between two framebuffers, `_rt_imageLayerComposite_{id}_a` and `_b`. Only layers with a named buffer
+(a blend mode, `ledsource`, fog, some puppets, or listed in another object's `dependencies`) get a named `_a` other objects can read; the rest share
+pooled buffers.
 
 There's special textures used for various things:
-- _rt_FullFrameBuffer: Represents the things currently rendered to the background's output
-- _rt_HalfCompoBuffer1: Unknown for now
-- _rt_HalfCompoBuffer2: Unknown for now
+- _rt_FullFrameBuffer: the scene as drawn so far
+- _rt_MipMappedFrameBuffer: the scene with mipmaps, for reflections
+- _rt_4FrameBuffer, _rt_8FrameBuffer, _rt_Bloom: the bloom chain
+- _rt_FullAlphaMask: the clipping masks of puppets

+ 18 - 0
docs/rendering/OBJECTS.md

@@ -0,0 +1,18 @@
+# Objects
+
+`objects` of `scene.json` is a list drawn in array order (`parent` only nests transforms and visibility). Every object has `id`, `name`, `origin`, `angles`,
+`scale`, `visible`, `parent`, `dependencies` and `ledsource` where it makes sense; any property can be a plain value, a user property binding
+(`{"user": "name", "value": ...}`) and carry a `script` and animations. Parsing is in `Data/Parsers/ObjectParser.cpp`.
+
+| Key that selects the type | Object |
+|---|---|
+| `image` | image layer, a quad with a material, effects and optionally a puppet (see IMAGE_OBJECTS.md, MDL_FILES.md); `shape` instead of a texture makes a shape layer |
+| `particle` | particle system, `instanceoverride` rescales it |
+| `text` | text layer (`font`, `pointsize`, `anchor`, ...) |
+| `sound` | sound object, `sound` lists the files |
+| `model` | 3D model or model data layer |
+| `light` | `point`, `lpoint`, `lspot`, `ltube`, `ldirectional` |
+| `camera` | scene camera object |
+| none | group or locator |
+
+`ledsource` marks a layer as the source of the RGB lighting output (`--leds`).

+ 41 - 38
docs/textures/TEXTURE_FORMAT.md

@@ -1,45 +1,48 @@
 # Texture storage format
-Wallpaper engine uses a custom texture storage format converted by resourcecompiler.exe
 
-## Header
-| Information | Size | Default value |
-|---|---|---|
-| __File type indicator__ | 8 bytes | TEXV0005 |
-| __Padding__ | 1 byte | Null terminator for string |
-| __Extra file type indicator?__ | 8 bytes | TEXI0001 |
-| __Padding__ | 1 byte | Null terminator for string |
-| __Texture type__ | 4 bytes | 0 => ARGB8888, 4 => DXT5, 6 => DXT3, 7 => DXT1, 8 => RG88, 9 => R8 |
-| __Texture flags__ | 4 bytes | Flags for the texture (1 => Interpolation, 2 => ClampUVs, 4 => IsGif) |
-| __Texture Width__ | 4 bytes | Texture's full width |
-| __Texture Height__ | 4 bytes | Texture's full height |
-| __Width__ | 4 bytes | Image's width |
-| __Height__ | 4 bytes | Image's height |
-| __Unknown data__ | 4 bytes | To be reversed |
-| __Container version__ | 8 bytes | TEXB0003/TEXB0002/TEXB0001 |
-| __Padding__ | 1 byte | Null terminator for string |
-| __Texture information__ | x bytes | Varies depending on the container version |
-
-## TEXB0003
-| Information | Size | Default value |
+Wallpaper Engine converts textures with `resourcecompiler.exe` into `.tex` files. The reader is `Data/Parsers/TextureParser.cpp`, a
+port of `wallpaper64.exe` 2.8.42 `sub_14015E580`. Every value is little endian, strings are NUL terminated.
+
+## File
+`TEXV0004` is a version 0 TEXI section directly followed by a version 0 TEXB section. `TEXV0005` is a list of tagged sections in any order,
+the last four digits of a tag are the section's version; reading stops at the first unknown tag.
+
+| Tag | Content |
+|---|---|
+| `TEXI` | texture header |
+| `TEXB` | image container (mipmaps) |
+| `TEXS` | sprite sheet frames (animated textures) |
+
+## TEXI (`sub_14015C760`)
+| Field | Size | Meaning |
 |---|---|---|
-| __Unknown data__ | 4 bytes | To be reversed |
-| __Free image format__ | 4 bytes | The type of file this texture is based off the FREEIMAGE library |
-| __Mip map levels__ | 4 bytes | The number of mipmap levels stored for this texture |
-| __Mipmap entry__ | x bytes | See Mipmap entries |
+| format | 4 | 0 ARGB8888, 1 RGB888, 2 RGB565, 4 DXT5, 6 DXT3, 7 DXT1, 8 RG88, 9 R8, 10 RG1616f, 11 R16f, 12 BC7, 13 RGBA1010102, 14 RGBA16161616f, 15 RGB161616f; anything else uploads as RGBA8 |
+| flags | 4 | 1 no interpolation, 2 clamp UVs, 4 is animated (sprite sheet), 8 clamp to border, 32 video payload, 64 volume texture (3D, adds a depth), 0x80000 alpha in the G/R channel of RG88/R8, 0xF00000 mask component bits (a painted PBR component each) |
+| texture width, height | 4 + 4 | storage size (power of two padded unless the payload is an encoded image) |
+| image width, height | 4 + 4 | the picture's size |
+| depth | 4 | only with the volume flag |
+| extra word | 4 | only from version 1, unused |
 
-## TEXB0002 and TEXB0001
-| Information | Size | Default value |
+## TEXB (`sub_14015C8D0`)
+Version 1 adds the image count, version 2 a compression word per mipmap, version 3 the FreeImage format, version 4 the user property conditions.
+
+| Field | Size | Meaning |
 |---|---|---|
-| __Unknown data__ | 4 bytes | To be reversed |
-| __Mip map levels__ | 4 bytes | The number of mipmap levels stored for this texture |
-| __Mipmap entry__ | x bytes | See Mipmap entries |
+| image count | 4 | from version 1, else 1 |
+| FreeImage format | 4 | from version 3: `FREE_IMAGE_FORMAT` of the payload, -1 for raw pixels; an encoded image (PNG, JPEG, MP4 for video textures) is decoded after the mipmap is read |
+| condition count | 4 | from version 4, then per condition: group 4, key 4, flags 4, a NUL terminated JSON string (the user property that picks it) |
+
+Then per image: a mipmap count, then per mipmap:
 
-## Mipmap entries
-| Information | Size | Default value |
+| Field | Size | Meaning |
 |---|---|---|
-| __Width__ | 4 bytes | Mipmap's entry width |
-| __Height__| 4 bytes | Mipmap's entry height |
-| __Compression flag__ | 4 bytes | Indicates if the content is compressed or not |
-| __Next image size__ | 4 bytes | Image block size (uncompressed) |
-| __Next image size__ | 4 bytes | Image block size (compressed) |
-| __Mipmap pixels__ | x bytes | Actual bitmap data in the format specified |
+| width, height | 4 + 4 | (depth 4 for volume textures) |
+| compression | 4 | from version 2, bit 0 = LZ4 |
+| uncompressed size | 4 | from version 2 |
+| data size | 4 | bytes in the file |
+| data | | pixels in the TEXI format, rows tightly packed |
+| patches | | only when the container has conditions (even empty): a group count, per group a patch count and per patch 8 words (unused, key, x, y, width, height, format, size) plus the data |
+
+## TEXS (`sub_14015E1D0`)
+Frame count, from version 3 the sprite sheet's frame size (width, height), then per frame: frame number, frame time (float), x, y, width1, width2, height2, height1
+(integers in version 1, floats after). Used for animated textures (`TextureFlags_IsGif`).

+ 144 - 13
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -5,6 +5,7 @@
 #include "WallpaperEngine/Data/Utils/FiniteFloat.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/CFBO.h"
+#include "WallpaperEngine/Render/Transition.h"
 #include "WallpaperEngine/Render/Wallpapers/CVideo.h"
 
 #include <algorithm>
@@ -134,19 +135,19 @@ ApplicationContext::buildPlaylistDefinition (const JSON& playlistJson, const std
 }
 
 ApplicationContext::PlaylistSettings ApplicationContext::parsePlaylistSettings (const JSON& playlistJson) const {
-    PlaylistSettings settings;
+    PlaylistSettings result;
     const auto settingsJson = playlistJson.optional ("settings");
-    settings.delayMinutes = settingsJson ? settingsJson->optional<uint32_t> ("delay", 60) : 60;
-    settings.mode = settingsJson ? settingsJson->optional<std::string> ("mode", "timer") : "timer";
-    settings.order = settingsJson ? settingsJson->optional<std::string> ("order", "sequential") : "sequential";
-    settings.updateOnPause = settingsJson ? settingsJson->optional<bool> ("updateonpause", false) : false;
-    settings.videoSequence = settingsJson ? settingsJson->optional<bool> ("videosequence", false) : false;
+    result.delayMinutes = settingsJson ? settingsJson->optional<uint32_t> ("delay", 60) : 60;
+    result.mode = settingsJson ? settingsJson->optional<std::string> ("mode", "timer") : "timer";
+    result.order = settingsJson ? settingsJson->optional<std::string> ("order", "sequential") : "sequential";
+    result.updateOnPause = settingsJson ? settingsJson->optional<bool> ("updateonpause", false) : false;
+    result.videoSequence = settingsJson ? settingsJson->optional<bool> ("videosequence", false) : false;
     // wallpaper64 sub_140075A90 only reads beginfirst in timer mode and playintro with beginfirst on
-    if (settingsJson && settings.mode == "timer") {
-	settings.beginFirst = settingsJson->optional<bool> ("beginfirst", false);
-	settings.playIntro = settings.beginFirst && settingsJson->optional<bool> ("playintro", false);
+    if (settingsJson && result.mode == "timer") {
+	result.beginFirst = settingsJson->optional<bool> ("beginfirst", false);
+	result.playIntro = result.beginFirst && settingsJson->optional<bool> ("playintro", false);
     }
-    return settings;
+    return result;
 }
 
 std::vector<std::filesystem::path>
@@ -655,10 +656,12 @@ void ApplicationContext::loadSettingsFromArgv () {
     backgroundGroup.add_argument ("-b", "--bg")
 	.help ("After --screen-root, --screen-span or --screen-slot, specifies the background to use")
 	.action ([this, &lastScreen] (const std::string& value) -> void {
-	    this->settings.general.screenBackgrounds[lastScreen] = translateBackground (value);
-	    this->settings.general.defaultBackground = translateBackground (value);
+	    const auto background = translateBackground (value);
+
+	    this->settings.general.screenBackgrounds[lastScreen] = background;
+	    this->settings.general.defaultBackground = background;
 	    if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
-		this->settings.general.spanGroups.back ().background = translateBackground (value);
+		this->settings.general.spanGroups.back ().background = background;
 	    }
 	})
 	.append ();
@@ -1164,6 +1167,43 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.render.frameLimiter = value;
 	});
 
+    performanceGroup.add_argument ("--transition")
+	.help (
+	    "Animation when the wallpaper changes (playlist, hotswap to another wallpaper): none (default), fade, "
+	    "slide-left, slide-right (the old picture moves away), wipe-left, wipe-right (the old picture is erased "
+	    "from "
+	    "the right or the left edge) or zoom (the old picture grows and fades). Control file: transition=<kind>"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    if (!WallpaperEngine::Render::parseTransition (value).has_value ()) {
+		sLog.exception (
+		    "Invalid --transition value: ", value,
+		    " (none, fade, slide-left, slide-right, wipe-left, wipe-right or zoom)"
+		);
+	    }
+
+	    this->settings.render.transition = value;
+	});
+
+    performanceGroup.add_argument ("--transition-duration")
+	.help (
+	    "How long --transition takes in milliseconds (100 to 5000, default 600). Control file: "
+	    "transition-duration=<ms>"
+	)
+	.action ([this] (const std::string& value) -> void {
+	    int ms = 0;
+
+	    try {
+		ms = std::stoi (value);
+	    } catch (const std::exception&) {
+		sLog.exception ("Invalid --transition-duration value: ", value);
+	    }
+
+	    this->settings.render.transitionMs = std::clamp (
+		ms, WallpaperEngine::Render::TRANSITION_MIN_MS, WallpaperEngine::Render::TRANSITION_MAX_MS
+	    );
+	});
+
     performanceGroup.add_argument ("--no-fullscreen-pause")
 	.help ("Prevents the background pausing when an app is fullscreen")
 	.flag ()
@@ -1287,6 +1327,79 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.audio.hrtf = *mode;
 	});
 
+    auto& ledGroup = program.add_group ("LED options");
+
+    ledGroup.add_argument ("--leds")
+	.help (
+	    "Sends the scene's colors to the RGB devices of a running OpenRGB server (openrgb --server), like "
+	    "Wallpaper Engine's LED plugin: layers marked as LED source, else the whole scene, shrunk to 80 x 10 and "
+	    "read at every led's place on its device"
+	)
+	.flag ()
+	.action ([this] (const std::string& value) -> void { this->settings.leds.enabled = true; });
+
+    ledGroup.add_argument ("--leds-server")
+	.help ("Address of the OpenRGB server, host or host:port (default 127.0.0.1:6742). Implies --leds")
+	.action ([this] (const std::string& value) -> void {
+	    const auto colon = value.rfind (':');
+
+	    if (value.empty ()) {
+		sLog.exception ("Invalid --leds-server value: ", value);
+	    }
+
+	    this->settings.leds.enabled = true;
+
+	    if (colon == std::string::npos) {
+		this->settings.leds.host = value;
+		return;
+	    }
+
+	    int port = 0;
+
+	    try {
+		port = std::stoi (value.substr (colon + 1));
+	    } catch (const std::exception&) {
+		sLog.exception ("Invalid port in --leds-server value: ", value);
+	    }
+
+	    if (port < 1 || port > 65535 || colon == 0) {
+		sLog.exception ("Invalid --leds-server value: ", value);
+	    }
+
+	    this->settings.leds.host = value.substr (0, colon);
+	    this->settings.leds.port = static_cast<uint16_t> (port);
+	});
+
+    ledGroup.add_argument ("--leds-brightness")
+	.help ("Brightness factor of the led colors in percent, 100 leaves them as they are (default 100)")
+	.action ([this] (const std::string& value) -> void {
+	    float percent = 0.0f;
+
+	    try {
+		percent = std::stof (value);
+	    } catch (const std::exception&) {
+		sLog.exception ("Invalid --leds-brightness value: ", value);
+	    }
+
+	    if (!(percent >= 0.0f && percent <= 100.0f)) {
+		sLog.exception ("--leds-brightness must be between 0 and 100");
+	    }
+
+	    this->settings.leds.brightness = percent / 100.0f;
+	});
+
+    ledGroup.add_argument ("--leds-no-boost")
+	.help (
+	    "Does not raise every led color's strongest channel to full first (Wallpaper Engine's \"Boost LED colors\")"
+	)
+	.flag ()
+	.action ([this] (const std::string& value) -> void { this->settings.leds.boost = false; });
+
+    ledGroup.add_argument ("--leds-reduce-fps")
+	.help ("Updates the devices 15 times a second at most instead of 30")
+	.flag ()
+	.action ([this] (const std::string& value) -> void { this->settings.leds.reduceFps = true; });
+
     auto& screenshotGroup = program.add_group ("Screenshot options");
 
     screenshotGroup.add_argument ("--screenshot")
@@ -1377,6 +1490,14 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    }
 	});
 
+    configurationGroup.add_argument ("--no-desktop-icons")
+	.help (
+	    "X11 only: leave the icons of an opaque desktop window (xfdesktop, caja, pcmanfm-qt) under the wallpaper "
+	    "instead of drawing them above it, the desktop's background is not touched. Same as LWE_DESKTOP_ICONS=off"
+	)
+	.flag ()
+	.action ([] (const std::string& value) -> void { setenv ("LWE_DESKTOP_ICONS", "off", 1); });
+
     configurationGroup.add_argument ("--disable-particles")
 	.help ("Disables particles for the backgrounds")
 	.flag ()
@@ -1535,6 +1656,16 @@ void ApplicationContext::loadSettingsFromArgv () {
 	.flag ()
 	.store_into (this->settings.general.onlyListEffects);
 
+    configurationGroup.add_argument ("--list-fonts")
+	.help (
+	    "List the fonts a background's texts need that this system doesn't have (a Windows font replaced by "
+	    "another "
+	    "one, emoji without Segoe UI Emoji), with the font drawn instead. Fonts added to the user font folder "
+	    "(LWE_FONT_DIR, default ~/.local/share/linux-wallpaperengine/fonts) count as installed"
+	)
+	.flag ()
+	.store_into (this->settings.general.onlyListFonts);
+
     configurationGroup.add_argument ("--disable-effect")
 	.help (
 	    "Disables an object's visual effect (bloom, blur, glow, etc), matched by effect id or editor name. "

+ 36 - 12
src/WallpaperEngine/Application/ApplicationContext.h

@@ -105,14 +105,15 @@ public:
 
     struct {
 	struct {
-	    bool onlyListProperties;
-	    bool onlyListObjects;
-	    bool onlyListAudioObjects;
-	    bool onlyListEffects;
-	    bool dumpStructure;
-	    bool noShaderCache;
-	    bool disableParticles;
-	    bool expandCanvas;
+	    bool onlyListProperties = false;
+	    bool onlyListObjects = false;
+	    bool onlyListAudioObjects = false;
+	    bool onlyListEffects = false;
+	    bool onlyListFonts = false;
+	    bool dumpStructure = false;
+	    bool noShaderCache = false;
+	    bool disableParticles = false;
+	    bool expandCanvas = false;
 	    bool repairAssets = false;
 	    bool postProcessingDisabled = false;
 	    bool ultraPostProcessing = false;
@@ -143,12 +144,12 @@ public:
 	    std::optional<PlaylistDefinition> defaultPlaylist;
 	    std::vector<SpanGroup> spanGroups;
 	    std::vector<SplitScreen> splitScreens;
-	    bool webHost;
+	    bool webHost = false;
 	    std::string webHostShm;
 	    std::string webHostFrames;
-	    int webHostSocket;
-	    uint32_t webHostWidth;
-	    uint32_t webHostHeight;
+	    int webHostSocket = -1;
+	    uint32_t webHostWidth = 0;
+	    uint32_t webHostHeight = 0;
 	    std::optional<std::filesystem::path> controlFile;
 	} general;
 
@@ -160,6 +161,8 @@ public:
 	    std::string hwdec;
 	    std::string webFrames;
 	    std::string frameLimiter;
+	    std::string transition;
+	    int transitionMs;
 	    bool freezeAnimations;
 	    bool pauseOnFullscreen;
 	    // only fullscreen toplevels that are also activated count (scrollable tiling compositors)
@@ -212,6 +215,16 @@ public:
 	    HRTF_MODE hrtf;
 	} audio;
 
+	struct {
+	    bool enabled;
+	    std::string host;
+	    uint16_t port;
+	    bool boost;
+	    /** WE's brightnessfactor, 1 = as is */
+	    float brightness;
+	    bool reduceFps;
+	} leds;
+
 	struct {
 	    bool enabled;
 	    bool disableparallax;
@@ -231,6 +244,7 @@ public:
             .onlyListObjects = false,
             .onlyListAudioObjects = false,
             .onlyListEffects = false,
+            .onlyListFonts = false,
             .dumpStructure = false,
             .noShaderCache = false,
             .disabledObjects = {},
@@ -271,6 +285,8 @@ public:
             .hwdec = "auto",
             .webFrames = "auto",
             .frameLimiter = "budget",
+            .transition = "none",
+            .transitionMs = 600,
             .freezeAnimations = false,
             .pauseOnFullscreen = true,
             .pauseOnFullscreenOnlyWhenActive = false,
@@ -316,6 +332,14 @@ public:
             .ambientVolume = std::nullopt,
             .hrtf = HRTF_AUTO,
         },
+        .leds = {
+            .enabled = false,
+            .host = "127.0.0.1",
+            .port = 6742,
+            .boost = true,
+            .brightness = 1.0f,
+            .reduceFps = false,
+        },
         .mouse = {
             .enabled = true,
             .disableparallax = false,

+ 130 - 9
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -1,5 +1,7 @@
 #include "WallpaperApplication.h"
+
 #include "ControlFileOwner.h"
+#include "WallpaperEngine/Render/Transition.h"
 
 #include <cstdlib>
 
@@ -12,9 +14,11 @@
 #include "WallpaperEngine/Desktop/HostWayland.h"
 #endif
 #include "WallpaperEngine/FileSystem/Container.h"
+#include "WallpaperEngine/Led/LedHub.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/ThreadGuard.h"
 #include "WallpaperEngine/Render/Drivers/VideoFactories.h"
+#include "WallpaperEngine/Render/Fonts/SystemFonts.h"
 #include "WallpaperEngine/Render/RenderContext.h"
 #include "WallpaperEngine/Render/Shaders/ShaderCache.h"
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
@@ -111,6 +115,7 @@ WallpaperApplication::WallpaperApplication (ApplicationContext& context) : m_con
     this->setupSoundVolume ();
     this->listObjects ();
     this->listEffects ();
+    this->listFonts ();
     this->listAudioObjects ();
     this->setupBrowser ();
     this->initializePlaylists ();
@@ -629,7 +634,7 @@ void WallpaperApplication::advancePlaylist (
 
 	try {
 	    if (this->m_renderContext) {
-		this->installWallpaper (screen, *this->m_backgrounds[screen], nextPath, true);
+		this->installWallpaper (screen, *this->m_backgrounds[screen], nextPath, true, true);
 		this->applyAudioPolicy ();
 	    }
 	} catch (...) {
@@ -745,6 +750,8 @@ struct HotswapRequest {
     std::optional<std::string> videoSegments;
     std::optional<std::string> hwdec;
     std::optional<std::string> hrtf;
+    std::optional<std::string> transition;
+    std::optional<std::string> transitionDuration;
     std::optional<std::string> videoSeek;
     std::optional<std::string> audioScreen;
     std::optional<std::string> ambientVolume;
@@ -904,6 +911,10 @@ HotswapRequest parseHotswapRequest (std::istream& file) {
 	    request.hwdec = value;
 	} else if (key == "hrtf") {
 	    request.hrtf = value;
+	} else if (key == "transition") {
+	    request.transition = value;
+	} else if (key == "transition-duration") {
+	    request.transitionDuration = value;
 	} else if (key == "audio-screen") {
 	    request.audioScreen = value;
 	} else if (key == "ambient-volume") {
@@ -991,7 +1002,8 @@ void WallpaperApplication::checkHotswapRequest () {
 	&& !request.videoEnd.has_value () && !request.videoSegments.has_value () && !request.videoSeek.has_value ()
 	&& !request.audioScreen.has_value () && !request.ambientVolume.has_value () && !request.propertiesProvided
 	&& !request.audioSensitivityProvided && !request.soundVolumeProvided && !request.effectsProvided
-	&& !request.disableAnimations.has_value () && !request.hwdec.has_value () && !request.hrtf.has_value ()) {
+	&& !request.disableAnimations.has_value () && !request.hwdec.has_value () && !request.hrtf.has_value ()
+	&& !request.transition.has_value () && !request.transitionDuration.has_value ()) {
 	sLog.error ("Hotswap requested but control file was empty");
 	return;
     }
@@ -1002,6 +1014,26 @@ void WallpaperApplication::checkHotswapRequest () {
 	return;
     }
 
+    // before the path below: a switch uses the transition that came with it
+    if (request.transition.has_value ()) {
+	if (WallpaperEngine::Render::parseTransition (*request.transition).has_value ()) {
+	    this->m_context.settings.render.transition = *request.transition;
+	} else {
+	    sLog.error ("Hotswap: ignoring invalid transition value: ", *request.transition);
+	}
+    }
+
+    if (request.transitionDuration.has_value ()) {
+	try {
+	    this->m_context.settings.render.transitionMs = std::clamp (
+		std::stoi (*request.transitionDuration), WallpaperEngine::Render::TRANSITION_MIN_MS,
+		WallpaperEngine::Render::TRANSITION_MAX_MS
+	    );
+	} catch (const std::exception&) {
+	    sLog.error ("Hotswap: ignoring invalid transition-duration value: ", *request.transitionDuration);
+	}
+    }
+
     struct OverrideSnapshot {
 	std::vector<std::string> disabledObjects, enabledObjects, disabledEffects, enabledEffects;
 	std::map<std::string, std::string> properties;
@@ -1282,7 +1314,9 @@ void WallpaperApplication::checkHotswapRequest () {
 	    continue;
 	}
 
-	const std::string targetPath = request.path.value_or (this->resolveScreenBackgroundPath (screen));
+	const std::string currentPath = this->resolveScreenBackgroundPath (screen);
+	const std::string targetPath = request.path.value_or (currentPath);
+	const bool animate = request.path.has_value () && targetPath != currentPath;
 
 	try {
 	    auto project = this->loadBackground (targetPath);
@@ -1297,7 +1331,7 @@ void WallpaperApplication::checkHotswapRequest () {
 
 	    try {
 		if (this->m_renderContext) {
-		    this->installWallpaper (screen, *background, targetPath, true);
+		    this->installWallpaper (screen, *background, targetPath, true, animate);
 		}
 	    } catch (...) {
 		project = std::move (background);
@@ -2115,6 +2149,80 @@ void WallpaperApplication::listEffects () const {
     }
 }
 
+void WallpaperApplication::listFontsForProject (const std::string& background, const Project& project) const {
+    if (!project.wallpaper->is<Scene> ()) {
+	return;
+    }
+
+    struct Need {
+	Render::Fonts::FontReport report;
+	std::string kind;
+	std::vector<std::string> objects;
+    };
+
+    std::vector<Need> needs;
+    const auto add
+	= [&needs] (const std::string& kind, const Render::Fonts::FontReport& report, const std::string& object) {
+	      for (auto& need : needs) {
+		  if (need.kind == kind && need.report.family == report.family) {
+		      if (std::ranges::find (need.objects, object) == need.objects.end ()) {
+			  need.objects.push_back (object);
+		      }
+
+		      return;
+		  }
+	      }
+
+	      needs.push_back ({ report, kind, { object } });
+	  };
+
+    for (const auto& object : project.wallpaper->as<Scene> ()->objects) {
+	if (!object->is<Text> ()) {
+	    continue;
+	}
+
+	const auto* text = object->as<Text> ();
+	const auto systemFont = Render::Fonts::systemFontReport (text->font);
+
+	if (!systemFont.family.empty ()) {
+	    add ("font", systemFont, object->name);
+	}
+
+	if (text->text != nullptr && text->text->value != nullptr
+	    && Render::Fonts::containsEmoji (text->text->value->getString ())) {
+	    add ("emoji", Render::Fonts::emojiReport (), object->name);
+	}
+    }
+
+    sLog.out ("Fonts for ", background, ":");
+
+    for (const auto& need : needs) {
+	const char* status = need.report.status == Render::Fonts::FontStatus::Exact ? "installed"
+	    : need.report.status == Render::Fonts::FontStatus::Compatible           ? "compatible"
+										    : "missing";
+	std::string objects;
+
+	for (const auto& name : need.objects) {
+	    objects += (objects.empty () ? "" : ", ") + name;
+	}
+
+	sLog.out (
+	    "  ", need.kind, " family=\"", need.report.family, "\" status=", status, " using=\"", need.report.using_,
+	    "\" objects=\"", objects, "\""
+	);
+    }
+}
+
+void WallpaperApplication::listFonts () const {
+    if (!this->m_context.settings.general.onlyListFonts) {
+	return;
+    }
+
+    for (const auto& [background, info] : this->m_backgrounds) {
+	this->listFontsForProject (background, *info);
+    }
+}
+
 namespace {
 struct AudioReactiveProperty {
     std::string name;
@@ -2414,8 +2522,6 @@ void WallpaperApplication::runWebHost () {
     windowInfo.SetAsWindowless (0);
     // frames come when the main process asks, so they line up with what it presents
     windowInfo.external_begin_frame_enabled = true;
-    // dmabuf frames: the browser paints into GPU buffers (OnAcceleratedPaint) the main process imports, instead of
-    // reading them back (OnPaint)
     const bool dmabufFrames = this->m_context.settings.general.webHostFrames == "dmabuf"
 	&& this->m_context.settings.general.webHostSocket >= 0;
     windowInfo.shared_texture_enabled = dmabufFrames;
@@ -2827,7 +2933,8 @@ const ApplicationContext::SpanGroup* WallpaperApplication::findSpanGroup (const
 }
 
 void WallpaperApplication::installWallpaper (
-    const std::string& screen, const Project& project, const std::filesystem::path& path, const bool holdPrevious
+    const std::string& screen, const Project& project, const std::filesystem::path& path, const bool holdPrevious,
+    const bool animate
 ) try {
     const auto& general = this->m_context.settings.general;
     const auto& window = this->m_context.settings.render.window;
@@ -2857,7 +2964,7 @@ void WallpaperApplication::installWallpaper (
 	    );
 	}
 
-	this->m_renderContext->setWallpaper (screen, std::move (wallpaper), holdPrevious);
+	this->m_renderContext->setWallpaper (screen, std::move (wallpaper), holdPrevious, animate);
 	return;
     }
 
@@ -2901,7 +3008,7 @@ void WallpaperApplication::installWallpaper (
     }
 
     for (const auto& name : spanGroup->screens) {
-	this->m_renderContext->setWallpaper (name, wallpaper, holdPrevious);
+	this->m_renderContext->setWallpaper (name, wallpaper, holdPrevious, animate);
     }
 } catch (const std::exception& e) {
     throw std::runtime_error ("Cannot set up wallpaper '" + path.string () + "' on " + screen + ": " + e.what ());
@@ -3184,9 +3291,23 @@ void WallpaperApplication::cleanup () {
 
 void WallpaperApplication::show () {
     setup ();
+
+    if (const auto& leds = this->m_context.settings.leds; leds.enabled) {
+	WallpaperEngine::Led::sharedOutput ().start (
+	    {
+		.host = leds.host,
+		.port = leds.port,
+		.brightness = { .boost = leds.boost, .factor = leds.brightness },
+		.reduceFps = leds.reduceFps,
+	    }
+	);
+    }
+
     while (this->m_context.state.general.keepRunning) {
 	render ();
     }
+
+    WallpaperEngine::Led::sharedOutput ().stop ();
     WallpaperEngine::Scripting::LocalStorage::flushAll ();
     cleanup ();
 }

+ 4 - 1
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -77,6 +77,8 @@ private:
     void listObjectsForProject (const std::string& background, const Project& project) const;
 
     void listEffects () const;
+    void listFonts () const;
+    void listFontsForProject (const std::string& background, const Project& project) const;
     void listEffectsForProject (const std::string& background, const Project& project) const;
 
     void setupAudioSensitivity ();
@@ -182,7 +184,8 @@ private:
     [[nodiscard]] const ApplicationContext::SpanGroup* findSpanGroup (const std::string& screen) const;
     [[nodiscard]] ApplicationContext::SpanGroup* findSpanGroup (const std::string& screen);
     void installWallpaper (
-	const std::string& screen, const Project& project, const std::filesystem::path& path, bool holdPrevious
+	const std::string& screen, const Project& project, const std::filesystem::path& path, bool holdPrevious,
+	bool animate = false
     );
     [[nodiscard]] std::optional<std::string> resolveHotswapScreen (const std::string& name) const;
     [[nodiscard]] bool hotswapReaches (const HotswapTarget& target, const std::string& screen) const;

+ 2 - 1
src/WallpaperEngine/Audio/Drivers/PulseProcessVolume.cpp

@@ -1,5 +1,6 @@
 #include "PulseProcessVolume.h"
 
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include <cstdlib>
 #include <fstream>
 #include <sstream>
@@ -70,7 +71,7 @@ void PulseProcessVolume::disconnect () {
 }
 
 void PulseProcessVolume::setVolume (float factor) {
-    if (factor == this->m_factor) {
+    if (WallpaperEngine::Data::Utils::sameFloat (factor, this->m_factor)) {
 	return;
     }
 

+ 1 - 1
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp

@@ -318,7 +318,7 @@ SDLAudioDriver::SDLAudioDriver (
 					  .userdata = this };
 
     this->m_deviceID = SDL_OpenAudioDevice (
-	nullptr, false, &requestedSpec, &this->m_audioSpec,
+	nullptr, 0, &requestedSpec, &this->m_audioSpec,
 	SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_CHANNELS_CHANGE | SDL_AUDIO_ALLOW_SAMPLES_CHANGE
     );
 

+ 2 - 1
src/WallpaperEngine/Audio/Hrtf.cpp

@@ -3,6 +3,7 @@
 #include "WallpaperEngine/Audio/DefaultHrtf.generated.h"
 #include "WallpaperEngine/Logging/Log.h"
 
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include <algorithm>
 #include <cmath>
 #include <cstring>
@@ -97,7 +98,7 @@ private:
 	    last = sum;
 	    term *= y * y;
 	    sum += term;
-	} while (sum != last);
+	} while (!WallpaperEngine::Data::Utils::sameFloat (sum, last));
 
 	return sum;
     }

+ 6 - 5
src/WallpaperEngine/Data/Builders/VectorBuilder.h

@@ -37,7 +37,6 @@ class VectorBuilder {
     }
 
 public:
-    // vector size (1-4) of a space-separated string
     static int preparseSize (const std::string& input) {
 	const auto str = normalizeSeparators (input);
 	const char* p = str.c_str ();
@@ -97,15 +96,17 @@ public:
 	    }
 	}
 
+	const auto after = [] (const char* separator) { return separator != nullptr ? separator + 1 : separator; };
+
 	if constexpr (length == 1) {
 	    return { convert<type> (p) };
 	} else if constexpr (length == 2) {
-	    return { convert<type> (p), convert<type> (first + 1) };
+	    return { convert<type> (p), convert<type> (after (first)) };
 	} else if constexpr (length == 3) {
-	    return { convert<type> (p), convert<type> (first + 1), convert<type> (second + 1) };
+	    return { convert<type> (p), convert<type> (after (first)), convert<type> (after (second)) };
 	} else if constexpr (length == 4) {
-	    return { convert<type> (p), convert<type> (first + 1), convert<type> (second + 1),
-		     convert<type> (third + 1) };
+	    return { convert<type> (p), convert<type> (after (first)), convert<type> (after (second)),
+		     convert<type> (after (third)) };
 	}
     }
     template <typename T, typename std::enable_if_t<is_glm_vec<T>::value, int> = 0>

+ 4 - 1
src/WallpaperEngine/Data/JSON.h

@@ -5,6 +5,7 @@
 #include <algorithm>
 #include <glm/detail/qualifier.hpp>
 #include <glm/detail/type_vec1.hpp>
+#include <iostream>
 #include <nlohmann/json.hpp>
 #include <optional>
 #include <string>
@@ -203,7 +204,9 @@ private:
 	    }
 
 	    sLog.error (required ? "Cannot use required '" : "Ignoring '", key, "' (", text, "): ", error.what ());
-	} catch (...) { }
+	} catch (...) {
+	    std::cerr << "Cannot report a JSON type error for '" << key << "'\n";
+	}
     }
 };
 

+ 6 - 4
src/WallpaperEngine/Data/Model/DynamicValue.cpp

@@ -120,10 +120,12 @@ void DynamicValue::update (const int newValue, UpdateSource source) {
 }
 
 void DynamicValue::update (const bool newValue, UpdateSource source) {
-    this->m_vec4 = glm::vec4 (newValue);
-    this->m_vec3 = glm::vec3 (newValue);
-    this->m_vec2 = glm::vec2 (newValue);
-    this->m_float = newValue;
+    const float asFloat = newValue ? 1.0f : 0.0f;
+
+    this->m_vec4 = glm::vec4 (asFloat);
+    this->m_vec3 = glm::vec3 (asFloat);
+    this->m_vec2 = glm::vec2 (asFloat);
+    this->m_float = asFloat;
     this->m_int = newValue;
     this->m_bool = newValue;
     this->m_string = "";

+ 1 - 0
src/WallpaperEngine/Data/Model/DynamicValue.h

@@ -48,6 +48,7 @@ public:
 
     DynamicValue () = default;
     DynamicValue (const DynamicValue& other);
+    DynamicValue& operator= (const DynamicValue& other) = delete;
     explicit DynamicValue (const glm::vec4& value);
     explicit DynamicValue (const glm::vec3& value);
     explicit DynamicValue (const glm::vec2& value);

+ 15 - 15
src/WallpaperEngine/Data/Model/Effect.cpp

@@ -26,30 +26,30 @@ bool EffectConditions::holds (const ComboMap& combos) const {
 
 // sub_1401EA500 picks the size, sub_1400D2C60 divides it by the scale
 glm::uvec2 FBO::bufferSize (const glm::vec2 objectSize) const {
-    int width
+    int bufferWidth
 	= this->width.has_value () ? static_cast<int> (*this->width) : std::max (static_cast<int> (objectSize.x), 4);
-    int height
+    int bufferHeight
 	= this->height.has_value () ? static_cast<int> (*this->height) : std::max (static_cast<int> (objectSize.y), 4);
 
-    if (this->fit.has_value () && width > 0 && height > 0) {
-	const int fit = static_cast<int> (*this->fit);
+    if (this->fit.has_value () && bufferWidth > 0 && bufferHeight > 0) {
+	const int fitSide = static_cast<int> (*this->fit);
 
-	if (width < height) {
-	    const int side = std::min (fit, height);
-	    width = static_cast<int> (
-		static_cast<float> (width) / static_cast<float> (height) * static_cast<float> (side)
+	if (bufferWidth < bufferHeight) {
+	    const int side = std::min (fitSide, bufferHeight);
+	    bufferWidth = static_cast<int> (
+		static_cast<float> (bufferWidth) / static_cast<float> (bufferHeight) * static_cast<float> (side)
 	    );
-	    height = side;
+	    bufferHeight = side;
 	} else {
-	    const int side = std::min (fit, width);
-	    height = static_cast<int> (
-		static_cast<float> (height) / static_cast<float> (width) * static_cast<float> (side)
+	    const int side = std::min (fitSide, bufferWidth);
+	    bufferHeight = static_cast<int> (
+		static_cast<float> (bufferHeight) / static_cast<float> (bufferWidth) * static_cast<float> (side)
 	    );
-	    width = side;
+	    bufferWidth = side;
 	}
     }
 
-    const int scale = std::max (static_cast<int> (this->scale), 1);
+    const int divisor = std::max (static_cast<int> (this->scale), 1);
 
-    return { std::max (width / scale, 2), std::max (height / scale, 2) };
+    return { std::max (bufferWidth / divisor, 2), std::max (bufferHeight / divisor, 2) };
 }

+ 2 - 2
src/WallpaperEngine/Data/Model/Effect.h

@@ -29,8 +29,8 @@ struct EffectConditions {
 struct FBO {
     std::string name;
     std::string format;
-    float scale;
-    bool unique;
+    float scale = 1.0f;
+    bool unique = false;
     glm::vec4 clearColor = {};
     /** "clear" was empty or had all four numbers (wallpaper64.exe 2.8.42 sub_1401E7170, FBO flag 2) */
     bool clearOnCreate = false;

+ 4 - 4
src/WallpaperEngine/Data/Model/Material.h

@@ -33,10 +33,10 @@ enum DepthwriteMode {
 };
 
 struct MaterialPass {
-    BlendingMode blending;
-    CullingMode cullmode;
-    DepthtestMode depthtest;
-    DepthwriteMode depthwrite;
+    BlendingMode blending = BlendingMode_Unknown;
+    CullingMode cullmode = CullingMode_Unknown;
+    DepthtestMode depthtest = DepthtestMode_Unknown;
+    DepthwriteMode depthwrite = DepthwriteMode_Unknown;
     std::string shader;
     TextureMap textures;
     TextureMap usertextures;

+ 18 - 18
src/WallpaperEngine/Data/Model/Object.h

@@ -32,7 +32,7 @@ struct ObjectComponentDependency {
 };
 
 struct ObjectData {
-    int id;
+    int id = 0;
     std::string name;
     std::vector<int> dependencies;
     std::vector<ObjectComponentDependency> componentDependencies;
@@ -84,7 +84,7 @@ struct ImageEffect {
 };
 
 struct ImageAnimationLayer {
-    int id;
+    int id = 0;
     /** Editor label only, the clip is picked by "animation" (the clip id in the puppet .mdl) */
     std::string name;
     UserSettingUniquePtr rate;
@@ -124,7 +124,7 @@ struct ImageData {
     UserSettingUniquePtr visible;
     UserSettingUniquePtr alpha;
     UserSettingUniquePtr color;
-    uint32_t alignment;
+    uint32_t alignment = 0;
     /** the alignment name, scripts may change it (ILayer.alignment, 2.8.42 sub_140212690) */
     UserSettingUniquePtr alignmentName;
     /** In pixels */
@@ -132,7 +132,7 @@ struct ImageData {
     UserSettingUniquePtr parallaxDepth;
     UserSettingUniquePtr colorBlendMode;
     UserSettingUniquePtr brightness;
-    bool clampUVs;
+    bool clampUVs = false;
     UserSettingUniquePtr copyBackground;
     RenderableSettings renderable;
     ModelUniquePtr model;
@@ -851,15 +851,15 @@ using ParticleOperatorUniquePtr = std::unique_ptr<ParticleOperatorBase>;
 
 struct ParticleRenderer {
     std::string name;
-    float length;
-    float maxLength;
-    float minLength;
-    float subdivision;
-    float segments;
-    float uvScale;
-    bool uvScrolling;
-    bool fadeAlpha;
-    bool fadeSize;
+    float length = 0.0f;
+    float maxLength = 0.0f;
+    float minLength = 0.0f;
+    float subdivision = 0.0f;
+    float segments = 0.0f;
+    float uvScale = 0.0f;
+    bool uvScrolling = false;
+    bool fadeAlpha = false;
+    bool fadeSize = false;
     /** "orientation" (sub_1401C22E0): screen 0, upright 1, fixed 2 */
     int orientation = 0;
     /** "axis" normalized, (0, 1, 0) when zero (+12) */
@@ -923,10 +923,10 @@ struct ParticleData {
     std::string particleFile;
 
     std::string animationMode;
-    float sequenceMultiplier;
-    uint32_t maxCount;
-    float startTime;
-    uint32_t flags;
+    float sequenceMultiplier = 1.0f;
+    uint32_t maxCount = 0;
+    float startTime = 0.0f;
+    uint32_t flags = 0;
 
     ModelUniquePtr material;
 
@@ -946,7 +946,7 @@ struct ParticleData {
     /** The override color multiplies the spawn color: no color initializer or a scene older than version 5 */
     bool overrideColorTints = true;
 
-    ParticleInstanceOverride instanceOverride;
+    ParticleInstanceOverride instanceOverride = {};
 };
 
 class Particle : public Object, public ParticleData {

+ 2 - 2
src/WallpaperEngine/Data/Model/Project.h

@@ -14,10 +14,10 @@ struct Project {
     enum Type { Type_Scene = 0, Type_Web = 1, Type_Video = 2, Type_Unknown = 3 };
 
     std::string title;
-    Type type;
+    Type type = Type_Unknown;
     /** Negative if not present */
     std::string workshopId;
-    bool supportsAudioProcessing;
+    bool supportsAudioProcessing = false;
     Properties properties;
     WallpaperUniquePtr wallpaper;
     AssetLocatorUniquePtr assetLocator;

+ 2 - 1
src/WallpaperEngine/Data/Parsers/DynamicValueParser.cpp

@@ -6,6 +6,7 @@
 
 #include "UserSettingParser.h"
 #include "WallpaperEngine/Data/Model/DynamicValue.h"
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 
 using namespace WallpaperEngine::Data::Parsers;
 
@@ -237,7 +238,7 @@ void DynamicValueParser::closeLoop (std::vector<AnimationKeyframe>& keys, const
 	return;
     }
 
-    if (keys.back ().frame != static_cast<float> (frameCount)) {
+    if (!WallpaperEngine::Data::Utils::sameFloat (keys.back ().frame, static_cast<float> (frameCount))) {
 	keys.push_back (AnimationKeyframe { .frame = static_cast<float> (frameCount) });
     }
 

+ 20 - 11
src/WallpaperEngine/Data/Parsers/PropertyParser.cpp

@@ -123,12 +123,18 @@ PropertySharedPtr PropertyParser::parseSlider (const JSON& it, const std::string
     );
 }
 
-PropertySharedPtr PropertyParser::parseText (const JSON& it, const std::string& name) {
-    return std::make_shared<PropertyText> (PropertyData {
+namespace {
+template <typename Kind> PropertySharedPtr makeTextOnly (const JSON& it, const std::string& name) {
+    return std::make_shared<Kind> (PropertyData {
 	.name = name,
 	.text = it.optional<std::string> ("text", ""),
     });
 }
+}
+
+PropertySharedPtr PropertyParser::parseText (const JSON& it, const std::string& name) {
+    return makeTextOnly<PropertyText> (it, name);
+}
 
 PropertySharedPtr PropertyParser::parseSceneTexture (const JSON& it, const std::string& name) {
     return std::make_shared<PropertySceneTexture> (
@@ -159,22 +165,25 @@ PropertySharedPtr PropertyParser::parseFile (const JSON& it, const std::string&
 }
 
 PropertySharedPtr PropertyParser::parseUserShortcut (const JSON& it, const std::string& name) {
-    return std::make_shared<PropertyUserShortcut> (PropertyData {
-	.name = name,
-	.text = it.optional<std::string> ("text", ""),
-    });
+    return makeTextOnly<PropertyUserShortcut> (it, name);
 }
 
-PropertySharedPtr PropertyParser::parseTextInput (const JSON& it, const std::string& name) {
-    const auto value = it.optional ("value");
+namespace {
+std::string textInputDefault (const std::optional<JSON>& value) {
+    if (!value.has_value ()) {
+	return "";
+    }
 
+    return value->is_string () ? value->get<std::string> () : value->dump ();
+}
+}
+
+PropertySharedPtr PropertyParser::parseTextInput (const JSON& it, const std::string& name) {
     return std::make_shared<PropertyTextInput> (
 	PropertyData {
 	    .name = name,
 	    .text = it.optional<std::string> ("text", ""),
 	},
-	!value.has_value ()       ? ""
-	    : value->is_string () ? value->get<std::string> ()
-				  : value->dump ()
+	textInputDefault (it.optional ("value"))
     );
 }

+ 11 - 0
src/WallpaperEngine/Data/Utils/BinaryReader.cpp

@@ -4,6 +4,7 @@
 #include "BinaryReader.h"
 
 #include <cstring>
+#include <limits>
 
 using namespace WallpaperEngine::Data::Utils;
 
@@ -43,6 +44,16 @@ float BinaryReader::nextFloat () const {
     return result;
 }
 
+void BinaryReader::skipUInt32 () const {
+    char buffer[4] = {};
+
+    this->m_input->read (buffer, 4);
+}
+
+void BinaryReader::skipNullTerminatedString () const {
+    this->m_input->ignore (std::numeric_limits<std::streamsize>::max (), '\0');
+}
+
 std::string BinaryReader::nextNullTerminatedString () const {
     std::string output;
 

+ 2 - 0
src/WallpaperEngine/Data/Utils/BinaryReader.h

@@ -18,6 +18,8 @@ public:
     [[nodiscard]] std::string nextNullTerminatedString () const;
     [[nodiscard]] std::string nextSizedString () const;
     void next (char* out, size_t size) const;
+    void skipUInt32 () const;
+    void skipNullTerminatedString () const;
     [[nodiscard]] char next () const;
 
     [[nodiscard]] std::istream& base () const;

+ 25 - 0
src/WallpaperEngine/Data/Utils/FloatCompare.h

@@ -0,0 +1,25 @@
+#pragma once
+
+#include <bit>
+#include <concepts>
+#include <cstdint>
+
+namespace WallpaperEngine::Data::Utils {
+/** Both are the same bits: what a cache key or a "did it change" test wants, a NaN equals itself */
+[[nodiscard]] inline bool sameFloat (const float a, const float b) noexcept {
+    return std::bit_cast<uint32_t> (a) == std::bit_cast<uint32_t> (b);
+}
+
+[[nodiscard]] inline bool sameFloat (const double a, const double b) noexcept {
+    return std::bit_cast<uint64_t> (a) == std::bit_cast<uint64_t> (b);
+}
+
+/** Not zero, in either direction (a NaN is neither) */
+template <std::floating_point T> [[nodiscard]] constexpr bool isNonZero (const T value) noexcept {
+    return value < T (0) || value > T (0);
+}
+
+template <std::floating_point T> [[nodiscard]] constexpr bool isZero (const T value) noexcept {
+    return !isNonZero (value);
+}
+}

+ 2 - 2
src/WallpaperEngine/Debugging/CallStack.h

@@ -57,11 +57,11 @@ public:
 
     class CallInfo {
     public:
-	CallInfo (void) { }
+	CallInfo (void) : offset (0) { }
 	CallInfo (long long unsigned int toffset, const string& tfunction, const string& tmodule) :
 	    offset (toffset), function (tfunction), module (tmodule) { }
 	~CallInfo (void) { }
-	long unsigned int offset;
+	long unsigned int offset = 0;
 	string function;
 	string module;
     };

+ 0 - 28
src/WallpaperEngine/Desktop/GnomeShell.cpp

@@ -16,34 +16,6 @@
 
 using namespace WallpaperEngine::Desktop;
 
-namespace {
-bool desktopListHas (std::string_view name) {
-    const char* desktops = std::getenv ("XDG_CURRENT_DESKTOP");
-
-    if (desktops == nullptr) {
-	return false;
-    }
-
-    std::string_view rest (desktops);
-
-    while (!rest.empty ()) {
-	const auto colon = rest.find (':');
-
-	if (rest.substr (0, colon) == name) {
-	    return true;
-	}
-
-	if (colon == std::string_view::npos) {
-	    break;
-	}
-
-	rest.remove_prefix (colon + 1);
-    }
-
-    return false;
-}
-}
-
 bool WallpaperEngine::Desktop::isGnomeSession () { return desktopListHas ("GNOME"); }
 
 bool WallpaperEngine::Desktop::isCosmicSession () { return desktopListHas ("COSMIC"); }

+ 246 - 0
src/WallpaperEngine/Desktop/PantheonShell.cpp

@@ -0,0 +1,246 @@
+#include "PantheonShell.h"
+#include "SessionBus.h"
+
+#include "WallpaperEngine/Logging/Log.h"
+
+#include <cstdlib>
+#include <cstring>
+#include <string_view>
+
+using namespace WallpaperEngine::Desktop;
+
+bool WallpaperEngine::Desktop::isPantheonSession () { return desktopListHas ("Pantheon"); }
+
+namespace {
+bool readBasic (DBusMessageIter* variant, void* value, int type) {
+    DBusMessageIter inner;
+    dbus_message_iter_recurse (variant, &inner);
+
+    if (dbus_message_iter_get_arg_type (&inner) != type) {
+	return false;
+    }
+
+    dbus_message_iter_get_basic (&inner, value);
+    return true;
+}
+
+void readProperty (PantheonShell::Window& window, const char* key, DBusMessageIter* variant) {
+    if (std::strcmp (key, "has-focus") == 0) {
+	dbus_bool_t value = false;
+
+	if (readBasic (variant, &value, DBUS_TYPE_BOOLEAN)) {
+	    window.focused = value;
+	}
+    } else if (std::strcmp (key, "is-hidden") == 0) {
+	dbus_bool_t value = false;
+
+	if (readBasic (variant, &value, DBUS_TYPE_BOOLEAN)) {
+	    window.hidden = value;
+	}
+    } else if (std::strcmp (key, "width") == 0) {
+	dbus_uint32_t value = 0;
+
+	if (readBasic (variant, &value, DBUS_TYPE_UINT32)) {
+	    window.width = value;
+	}
+    } else if (std::strcmp (key, "height") == 0) {
+	dbus_uint32_t value = 0;
+
+	if (readBasic (variant, &value, DBUS_TYPE_UINT32)) {
+	    window.height = value;
+	}
+    } else if (std::strcmp (key, "workspace-index") == 0) {
+	dbus_int32_t value = 0;
+
+	if (readBasic (variant, &value, DBUS_TYPE_INT32)) {
+	    window.workspace = value;
+	}
+    } else if (std::strcmp (key, "wm-class") == 0) {
+	const char* value = nullptr;
+
+	if (readBasic (variant, &value, DBUS_TYPE_STRING) && value != nullptr) {
+	    window.wmClass = value;
+	}
+    }
+}
+
+bool readWindows (DBusMessageIter* iter, std::vector<PantheonShell::Window>& result) {
+    if (dbus_message_iter_get_arg_type (iter) != DBUS_TYPE_ARRAY) {
+	return false;
+    }
+
+    DBusMessageIter array;
+    dbus_message_iter_recurse (iter, &array);
+
+    for (; dbus_message_iter_get_arg_type (&array) == DBUS_TYPE_STRUCT; dbus_message_iter_next (&array)) {
+	DBusMessageIter fields;
+	dbus_message_iter_recurse (&array, &fields);
+
+	if (!dbus_message_iter_next (&fields) || dbus_message_iter_get_arg_type (&fields) != DBUS_TYPE_ARRAY) {
+	    return false;
+	}
+
+	PantheonShell::Window window;
+	DBusMessageIter entries;
+	dbus_message_iter_recurse (&fields, &entries);
+
+	for (; dbus_message_iter_get_arg_type (&entries) == DBUS_TYPE_DICT_ENTRY; dbus_message_iter_next (&entries)) {
+	    DBusMessageIter entry;
+	    const char* key = nullptr;
+
+	    dbus_message_iter_recurse (&entries, &entry);
+	    dbus_message_iter_get_basic (&entry, &key);
+	    dbus_message_iter_next (&entry);
+
+	    if (key != nullptr && dbus_message_iter_get_arg_type (&entry) == DBUS_TYPE_VARIANT) {
+		readProperty (window, key, &entry);
+	    }
+	}
+
+	result.push_back (std::move (window));
+    }
+
+    return true;
+}
+}
+
+PantheonShell::PantheonShell () {
+    if (!this->connect ()) {
+	return;
+    }
+
+    this->m_available = true;
+    this->refresh ();
+}
+
+PantheonShell::~PantheonShell () {
+    if (this->m_connection == nullptr) {
+	return;
+    }
+
+    // libdbus aborts on removing a filter that was never added
+    if (this->m_filterAdded) {
+	dbus_connection_remove_filter (this->m_connection, &PantheonShell::filter, this);
+    }
+
+    dbus_connection_close (this->m_connection);
+    dbus_connection_unref (this->m_connection);
+}
+
+bool PantheonShell::connect () {
+    DBusError error;
+    dbus_error_init (&error);
+
+    this->m_connection = dbus_bus_get_private (DBUS_BUS_SESSION, &error);
+
+    if (dbus_error_is_set (&error)) {
+	this->m_reason = std::string ("no session bus: ") + error.message;
+	dbus_error_free (&error);
+	this->m_connection = nullptr;
+	return false;
+    }
+
+    dbus_connection_set_exit_on_disconnect (this->m_connection, false);
+
+    DBusMessage* message = dbus_message_new_method_call (
+	"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetNameOwner"
+    );
+    const char* name = BUS_NAME;
+    dbus_message_append_args (message, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID);
+
+    std::string callError;
+    DBusMessage* reply = callBlocking (this->m_connection, message, callError);
+
+    if (reply == nullptr) {
+	this->m_reason = "Gala is not on the session bus (" + callError + ")";
+	return false;
+    }
+
+    const char* owner = nullptr;
+    dbus_message_get_args (reply, nullptr, DBUS_TYPE_STRING, &owner, DBUS_TYPE_INVALID);
+    this->m_owner = owner != nullptr ? owner : "";
+    dbus_message_unref (reply);
+
+    const std::string signals = std::string ("type='signal',sender='") + BUS_NAME + "',interface='" + INTERFACE
+	+ "',path='" + OBJECT_PATH + "'";
+
+    dbus_bus_add_match (this->m_connection, signals.c_str (), nullptr);
+    this->m_filterAdded = dbus_connection_add_filter (this->m_connection, &PantheonShell::filter, this, nullptr);
+
+    if (!this->m_filterAdded) {
+	this->m_reason = "out of memory adding a D-Bus filter";
+	return false;
+    }
+
+    return true;
+}
+
+void PantheonShell::refresh () {
+    std::string error;
+    DBusMessage* reply = callBlocking (
+	this->m_connection, dbus_message_new_method_call (BUS_NAME, OBJECT_PATH, INTERFACE, "GetWindows"), error
+    );
+
+    if (reply == nullptr) {
+	sLog.debugerror ("Gala did not answer GetWindows: ", error);
+	return;
+    }
+
+    std::vector<Window> windows;
+    DBusMessageIter iter;
+
+    if (dbus_message_iter_init (reply, &iter) && readWindows (&iter, windows)) {
+	this->m_windows = std::move (windows);
+    }
+
+    dbus_message_unref (reply);
+
+    reply = callBlocking (
+	this->m_connection, dbus_message_new_method_call (BUS_NAME, OBJECT_PATH, INTERFACE, "GetActiveWorkspace"), error
+    );
+
+    if (reply != nullptr) {
+	dbus_int32_t index = 0;
+
+	if (dbus_message_get_args (reply, nullptr, DBUS_TYPE_INT32, &index, DBUS_TYPE_INVALID)) {
+	    this->m_activeWorkspace = index;
+	}
+
+	dbus_message_unref (reply);
+    }
+}
+
+void PantheonShell::dispatch () {
+    if (this->m_connection == nullptr || !this->m_available) {
+	return;
+    }
+
+    if (!drainBus (this->m_connection)) {
+	sLog.error ("The session bus connection to Gala dropped, window states are not followed any more");
+	this->m_available = false;
+	this->m_windows.clear ();
+	return;
+    }
+
+    if (this->m_dirty) {
+	this->m_dirty = false;
+	this->refresh ();
+    }
+}
+
+DBusHandlerResult PantheonShell::filter (DBusConnection*, DBusMessage* message, void* data) {
+    if (dbus_message_get_type (message) != DBUS_MESSAGE_TYPE_SIGNAL) {
+	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+    }
+
+    auto* self = static_cast<PantheonShell*> (data);
+    const char* sender = dbus_message_get_sender (message);
+
+    if (sender != nullptr && self->m_owner == sender
+	&& (dbus_message_is_signal (message, INTERFACE, "WindowsChanged")
+	    || dbus_message_is_signal (message, INTERFACE, "ActiveWorkspaceChanged"))) {
+	self->m_dirty = true;
+    }
+
+    return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
+}

+ 59 - 0
src/WallpaperEngine/Desktop/PantheonShell.h

@@ -0,0 +1,59 @@
+#pragma once
+
+#include <cstdint>
+#include <dbus/dbus.h>
+#include <string>
+#include <vector>
+
+namespace WallpaperEngine::Desktop {
+bool isPantheonSession ();
+
+/**
+ * Gala's DesktopIntegration interface (what elementary's dock uses): the only way to see native Wayland windows there,
+ * Gala implements no foreign toplevel protocol. It gives size, focus, hidden and workspace but no fullscreen or
+ * maximized flag and no position, so a window that is at least as big as an output counts as covering it.
+ */
+class PantheonShell {
+public:
+    static constexpr const char* BUS_NAME = "org.pantheon.gala";
+    static constexpr const char* OBJECT_PATH = "/org/pantheon/gala/DesktopInterface";
+    static constexpr const char* INTERFACE = "org.pantheon.gala.DesktopIntegration";
+
+    struct Window {
+	std::string wmClass;
+	uint32_t width = 0;
+	uint32_t height = 0;
+	int32_t workspace = 0;
+	bool focused = false;
+	bool hidden = false;
+    };
+
+    PantheonShell ();
+    ~PantheonShell ();
+
+    PantheonShell (const PantheonShell&) = delete;
+    PantheonShell& operator= (const PantheonShell&) = delete;
+
+    [[nodiscard]] bool isAvailable () const { return this->m_available; }
+    [[nodiscard]] const std::string& reason () const { return this->m_reason; }
+
+    void dispatch ();
+
+    [[nodiscard]] const std::vector<Window>& windows () const { return this->m_windows; }
+    [[nodiscard]] int32_t activeWorkspace () const { return this->m_activeWorkspace; }
+
+private:
+    bool connect ();
+    void refresh ();
+    static DBusHandlerResult filter (DBusConnection* connection, DBusMessage* message, void* data);
+
+    DBusConnection* m_connection = nullptr;
+    std::string m_owner;
+    std::string m_reason;
+    bool m_available = false;
+    bool m_filterAdded = false;
+    bool m_dirty = false;
+    int32_t m_activeWorkspace = 0;
+    std::vector<Window> m_windows;
+};
+}

+ 26 - 0
src/WallpaperEngine/Desktop/SessionBus.cpp

@@ -13,6 +13,32 @@ constexpr int CALL_TIMEOUT_MS = 2000;
 constexpr int MAX_READS_PER_DRAIN = 64;
 }
 
+bool WallpaperEngine::Desktop::desktopListHas (std::string_view name) {
+    const char* desktops = std::getenv ("XDG_CURRENT_DESKTOP");
+
+    if (desktops == nullptr) {
+	return false;
+    }
+
+    std::string_view rest (desktops);
+
+    while (!rest.empty ()) {
+	const auto colon = rest.find (':');
+
+	if (rest.substr (0, colon) == name) {
+	    return true;
+	}
+
+	if (colon == std::string_view::npos) {
+	    break;
+	}
+
+	rest.remove_prefix (colon + 1);
+    }
+
+    return false;
+}
+
 std::string WallpaperEngine::Desktop::runtimeDirectory () {
     const char* runtimeDir = std::getenv ("XDG_RUNTIME_DIR");
 

+ 3 - 0
src/WallpaperEngine/Desktop/SessionBus.h

@@ -2,10 +2,13 @@
 
 #include <dbus/dbus.h>
 #include <string>
+#include <string_view>
 
 namespace WallpaperEngine::Desktop {
 std::string runtimeDirectory ();
 
+bool desktopListHas (std::string_view name);
+
 std::string flatpakInfo (const std::string& key);
 
 // this process in names others see (D-Bus, KWin scripts, sockets, shm): the pid, "<instance id>_<pid>" in a Flatpak

+ 6 - 6
src/WallpaperEngine/Desktop/UserShortcut.cpp

@@ -488,17 +488,17 @@ bool UserShortcut::launch () const {
 		    return false;
 		}
 
-		auto arguments = expandExec (exec->second, entry, *desktop);
+		auto command = expandExec (exec->second, entry, *desktop);
 		const auto terminal = entry.find ("Terminal");
 
 		if (terminal != entry.end () && terminal->second == "true") {
 		    auto prefix = terminalPrefix ();
-		    arguments.insert (arguments.begin (), prefix.begin (), prefix.end ());
+		    command.insert (command.begin (), prefix.begin (), prefix.end ());
 		}
 
 		const auto path = entry.find ("Path");
 
-		return spawnDetached (arguments, path != entry.end () ? path->second : "");
+		return spawnDetached (command, path != entry.end () ? path->second : "");
 	    }
 	case Type::Web:
 	    return spawnDetached (
@@ -509,9 +509,9 @@ bool UserShortcut::launch () const {
 	    return spawnDetached ({ "xdg-open", this->target });
 	case Type::File:
 	    if (isExecutableFile (this->target)) {
-		auto arguments = splitExec (this->arguments);
-		arguments.insert (arguments.begin (), this->target);
-		return spawnDetached (arguments, std::filesystem::path (this->target).parent_path ().string ());
+		auto command = splitExec (this->arguments);
+		command.insert (command.begin (), this->target);
+		return spawnDetached (command, std::filesystem::path (this->target).parent_path ().string ());
 	    }
 	    return spawnDetached ({ "xdg-open", this->target });
 	case Type::Command:

+ 2 - 2
src/WallpaperEngine/FileSystem/Adapters/Types.h

@@ -81,7 +81,7 @@ inline std::optional<std::string> resolveShortNameAlias (std::vector<std::string
 	};
 	// names that already fit 8.3 (in any case) never got an alias
 	const bool hasAlias = nameStem.size () > 8 || nameExtension.size () > 3 || !isShortName (nameStem)
-	    || !isShortName (nameExtension) || std::ranges::count (name, '.') > 1;
+	    || !isShortName (nameExtension) || std::count (name.begin (), name.end (), '.') > 1;
 
 	if (!hasAlias) {
 	    return true;
@@ -93,7 +93,7 @@ inline std::optional<std::string> resolveShortNameAlias (std::vector<std::string
 	    || (nameBasis.size () > basis.size () && basis.size () != 7 - (stem.size () - tilde - 1));
     });
 
-    std::ranges::sort (siblings, [] (const std::string& a, const std::string& b) {
+    std::sort (siblings.begin (), siblings.end (), [] (const std::string& a, const std::string& b) {
 	return std::ranges::lexicographical_compare (a, b, [] (unsigned char x, unsigned char y) {
 	    return std::toupper (x) < std::toupper (y);
 	});

+ 24 - 0
src/WallpaperEngine/Led/LedHub.cpp

@@ -0,0 +1,24 @@
+#include "LedHub.h"
+
+#include <atomic>
+
+namespace WallpaperEngine::Led {
+namespace {
+    std::atomic<const void*> s_feeder = nullptr;
+}
+
+LedOutput& sharedOutput () {
+    static LedOutput output;
+    return output;
+}
+
+bool claimFeed (const void* scene) {
+    const void* none = nullptr;
+    return s_feeder.compare_exchange_strong (none, scene) || none == scene;
+}
+
+void releaseFeed (const void* scene) {
+    const void* expected = scene;
+    s_feeder.compare_exchange_strong (expected, nullptr);
+}
+}

+ 9 - 0
src/WallpaperEngine/Led/LedHub.h

@@ -0,0 +1,9 @@
+#pragma once
+
+#include "LedOutput.h"
+
+namespace WallpaperEngine::Led {
+LedOutput& sharedOutput ();
+[[nodiscard]] bool claimFeed (const void* scene);
+void releaseFeed (const void* scene);
+}

+ 93 - 0
src/WallpaperEngine/Led/LedLayout.cpp

@@ -0,0 +1,93 @@
+#include "LedLayout.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace WallpaperEngine::Led {
+std::vector<LedPixel> layoutDevice (const OpenRgb::Device& device) {
+    std::vector<LedPixel> layout (device.ledCount);
+    uint32_t rows = 0;
+
+    for (const auto& zone : device.zones) {
+	rows += zone.matrix.empty () ? 1 : std::max (zone.matrixHeight, 1u);
+    }
+
+    uint32_t firstLed = 0;
+    uint32_t firstRow = 0;
+
+    for (const auto& zone : device.zones) {
+	const uint32_t height = zone.matrix.empty () ? 1 : std::max (zone.matrixHeight, 1u);
+	const auto place = [&] (const uint32_t led, const uint32_t column, const uint32_t row, const uint32_t columns) {
+	    if (led >= zone.leds || firstLed + led >= layout.size () || columns == 0) {
+		return;
+	    }
+
+	    const double xn = (column + 0.5) / columns;
+	    const double yn = (firstRow + row + 0.5) / rows;
+
+	    layout[firstLed + led] = {
+		.x = std::min (static_cast<int> (kFrameWidth * xn), kFrameWidth - 1),
+		.y = std::min (static_cast<int> (kFrameHeight * yn), kFrameHeight - 1),
+	    };
+	};
+
+	if (zone.matrix.empty ()) {
+	    for (uint32_t led = 0; led < zone.leds; led++) {
+		place (led, led, 0, zone.leds);
+	    }
+	} else {
+	    for (uint32_t row = 0; row < zone.matrixHeight; row++) {
+		for (uint32_t column = 0; column < zone.matrixWidth; column++) {
+		    place (zone.matrix[row * zone.matrixWidth + column], column, row, zone.matrixWidth);
+		}
+	    }
+	}
+
+	firstLed += zone.leds;
+	firstRow += height;
+    }
+
+    return layout;
+}
+
+void applyBrightness (const std::span<const uint8_t> in, const std::span<uint8_t> out, const Brightness& brightness) {
+    const size_t pixels = std::min (in.size (), out.size ()) / 3;
+
+    for (size_t i = 0; i < pixels; i++) {
+	const uint8_t* source = in.data () + i * 3;
+	uint8_t* target = out.data () + i * 3;
+	float scale = brightness.factor;
+
+	if (brightness.boost) {
+	    const int strongest = std::max ({ source[0], source[1], source[2] });
+
+	    if (strongest == 0) {
+		target[0] = target[1] = target[2] = 0;
+		continue;
+	    }
+
+	    scale *= 255.0f / static_cast<float> (strongest);
+	}
+
+	for (int channel = 0; channel < 3; channel++) {
+	    target[channel] = static_cast<uint8_t> (
+		std::clamp (static_cast<int> (static_cast<float> (source[channel]) * scale), 0, 255)
+	    );
+	}
+    }
+}
+
+void sampleDevice (
+    const std::span<const uint8_t> frame, const std::span<const LedPixel> layout, std::vector<uint8_t>& out
+) {
+    out.resize (layout.size () * 3);
+
+    for (size_t i = 0; i < layout.size (); i++) {
+	const size_t at = (static_cast<size_t> (layout[i].y) * kFrameWidth + layout[i].x) * 3;
+
+	out[i * 3] = frame[at];
+	out[i * 3 + 1] = frame[at + 1];
+	out[i * 3 + 2] = frame[at + 2];
+    }
+}
+}

+ 30 - 0
src/WallpaperEngine/Led/LedLayout.h

@@ -0,0 +1,30 @@
+#pragma once
+
+#include <cstdint>
+#include <span>
+#include <vector>
+
+#include "OpenRgbProtocol.h"
+
+namespace WallpaperEngine::Led {
+constexpr int kFrameWidth = 80;
+constexpr int kFrameHeight = 10;
+constexpr size_t kFrameBytes = static_cast<size_t> (kFrameWidth) * kFrameHeight * 3;
+
+struct Brightness {
+    bool boost = true;
+    float factor = 1.0f;
+};
+
+struct LedPixel {
+    int x = 0;
+    int y = 0;
+};
+
+[[nodiscard]] std::vector<LedPixel> layoutDevice (const OpenRgb::Device& device);
+
+/** ledextensions64.dll's frame callback (sub_180012448): the boost and the brightness factor, rgb in and out */
+void applyBrightness (std::span<const uint8_t> in, std::span<uint8_t> out, const Brightness& brightness);
+
+void sampleDevice (std::span<const uint8_t> frame, std::span<const LedPixel> layout, std::vector<uint8_t>& out);
+}

+ 391 - 0
src/WallpaperEngine/Led/LedOutput.cpp

@@ -0,0 +1,391 @@
+#include "LedOutput.h"
+
+#include <algorithm>
+#include <chrono>
+
+#include <arpa/inet.h>
+#include <cerrno>
+#include <cstring>
+#include <netdb.h>
+#include <netinet/tcp.h>
+#include <poll.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+#include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Logging/ThreadGuard.h"
+
+namespace WallpaperEngine::Led {
+using namespace std::chrono_literals;
+
+namespace {
+    struct Socket {
+	int fd = -1;
+
+	~Socket () {
+	    if (this->fd >= 0) {
+		close (this->fd);
+	    }
+	}
+
+	bool open (const std::string& host, const uint16_t port) {
+	    addrinfo hints = {};
+	    addrinfo* found = nullptr;
+
+	    hints.ai_family = AF_UNSPEC;
+	    hints.ai_socktype = SOCK_STREAM;
+
+	    if (getaddrinfo (host.c_str (), std::to_string (port).c_str (), &hints, &found) != 0) {
+		return false;
+	    }
+
+	    for (const auto* it = found; it != nullptr && this->fd < 0; it = it->ai_next) {
+		const int candidate
+		    = socket (it->ai_family, it->ai_socktype | SOCK_NONBLOCK | SOCK_CLOEXEC, it->ai_protocol);
+
+		if (candidate < 0) {
+		    continue;
+		}
+
+		bool connected = connect (candidate, it->ai_addr, it->ai_addrlen) == 0;
+
+		if (!connected && errno == EINPROGRESS) {
+		    pollfd wait = { .fd = candidate, .events = POLLOUT };
+		    int error = 0;
+		    socklen_t length = sizeof (error);
+
+		    connected = poll (&wait, 1, 2000) == 1
+			&& getsockopt (candidate, SOL_SOCKET, SO_ERROR, &error, &length) == 0 && error == 0;
+		}
+
+		if (connected) {
+		    this->fd = candidate;
+		} else {
+		    close (candidate);
+		}
+	    }
+
+	    freeaddrinfo (found);
+
+	    if (this->fd >= 0) {
+		const int on = 1;
+		setsockopt (this->fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof (on));
+	    }
+
+	    return this->fd >= 0;
+	}
+
+	[[nodiscard]] bool writeAll (std::span<const uint8_t> bytes) const {
+	    while (!bytes.empty ()) {
+		const ssize_t sent = send (this->fd, bytes.data (), bytes.size (), MSG_NOSIGNAL);
+
+		if (sent < 0 && errno == EINTR) {
+		    continue;
+		}
+
+		if (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
+		    pollfd wait = { .fd = this->fd, .events = POLLOUT };
+
+		    if (poll (&wait, 1, 2000) != 1) {
+			return false;
+		    }
+
+		    continue;
+		}
+
+		if (sent <= 0) {
+		    return false;
+		}
+
+		bytes = bytes.subspan (static_cast<size_t> (sent));
+	    }
+
+	    return true;
+	}
+
+	[[nodiscard]] bool readAll (std::span<uint8_t> bytes, const int timeoutMs) const {
+	    while (!bytes.empty ()) {
+		pollfd wait = { .fd = this->fd, .events = POLLIN };
+
+		if (poll (&wait, 1, timeoutMs) != 1) {
+		    return false;
+		}
+
+		const ssize_t got = recv (this->fd, bytes.data (), bytes.size (), 0);
+
+		if (got < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) {
+		    continue;
+		}
+
+		if (got <= 0) {
+		    return false;
+		}
+
+		bytes = bytes.subspan (static_cast<size_t> (got));
+	    }
+
+	    return true;
+	}
+
+	[[nodiscard]] bool readable () const {
+	    pollfd wait = { .fd = this->fd, .events = POLLIN };
+	    return poll (&wait, 1, 0) == 1;
+	}
+
+	bool readPacket (OpenRgb::Header& header, std::vector<uint8_t>& payload, const int timeoutMs) const {
+	    uint8_t raw[OpenRgb::kHeaderSize];
+
+	    if (!this->readAll (raw, timeoutMs)) {
+		return false;
+	    }
+
+	    const auto parsed = OpenRgb::parseHeader (raw);
+
+	    if (!parsed || parsed->size > (1u << 24)) {
+		return false;
+	    }
+
+	    header = *parsed;
+	    payload.resize (header.size);
+	    return this->readAll (payload, 5000);
+	}
+    };
+
+    struct Target {
+	OpenRgb::Device device;
+	std::vector<LedPixel> layout;
+	std::vector<uint8_t> last;
+	std::chrono::steady_clock::time_point lastSent;
+    };
+}
+
+LedOutput::~LedOutput () { this->stop (); }
+
+void LedOutput::start (const Options& options) {
+    if (this->m_running.exchange (true)) {
+	return;
+    }
+
+    this->m_options = options;
+    this->m_thread = std::thread ([this] { Logging::guardThread ("LED output", [this] { this->run (); }); });
+}
+
+void LedOutput::stop () {
+    if (!this->m_running.exchange (false)) {
+	return;
+    }
+
+    this->m_wake.notify_all ();
+
+    if (this->m_thread.joinable ()) {
+	this->m_thread.join ();
+    }
+}
+
+void LedOutput::submit (const std::span<const uint8_t> rgb) {
+    if (!this->m_running.load () || rgb.size () != kFrameBytes) {
+	return;
+    }
+
+    {
+	const std::lock_guard lock (this->m_mutex);
+	this->m_frame.assign (rgb.begin (), rgb.end ());
+	this->m_fresh = true;
+    }
+
+    this->m_wake.notify_one ();
+}
+
+void LedOutput::run () {
+    bool reported = false;
+
+    while (this->m_running.load ()) {
+	if (this->connectAndServe (this->m_options)) {
+	    reported = false;
+	} else if (!reported) {
+	    sLog.error (
+		"LED output: no OpenRGB server at ", this->m_options.host, ":", this->m_options.port,
+		", trying again every few seconds (start OpenRGB with --server)"
+	    );
+	    reported = true;
+	}
+
+	std::unique_lock lock (this->m_mutex);
+	this->m_wake.wait_for (lock, 3s, [this] { return !this->m_running.load (); });
+    }
+}
+
+bool LedOutput::connectAndServe (const Options& options) {
+    Socket socket;
+
+    if (!socket.open (options.host, options.port)) {
+	return false;
+    }
+
+    std::vector<uint8_t> payload;
+    OpenRgb::Header header;
+    uint32_t protocol = 0;
+
+    {
+	std::vector<uint8_t> ask;
+	OpenRgb::put32 (ask, OpenRgb::kProtocolVersion);
+
+	if (!socket.writeAll (OpenRgb::makePacket (0, OpenRgb::RequestProtocolVersion, ask))) {
+	    return false;
+	}
+
+	if (socket.readPacket (header, payload, 1500) && header.id == OpenRgb::RequestProtocolVersion
+	    && payload.size () >= 4) {
+	    const uint32_t server
+		= payload[0] | (payload[1] << 8) | (payload[2] << 16) | (static_cast<uint32_t> (payload[3]) << 24);
+	    protocol = std::min (server, OpenRgb::kProtocolVersion);
+	}
+    }
+
+    if (protocol < OpenRgb::kProtocolVersion) {
+	if (!this->m_protocolReported) {
+	    sLog.error (
+		"LED output: the OpenRGB server speaks protocol ", protocol, ", needs ", OpenRgb::kProtocolVersion,
+		" (OpenRGB 0.9 or newer)"
+	    );
+	    this->m_protocolReported = true;
+	}
+
+	return true;
+    }
+
+    this->m_protocolReported = false;
+
+    const std::string name = "linux-wallpaperengine";
+
+    if (!socket.writeAll (
+	    OpenRgb::makePacket (
+		0, OpenRgb::SetClientName, { reinterpret_cast<const uint8_t*> (name.c_str ()), name.size () + 1 }
+	    )
+	)) {
+	return false;
+    }
+
+    std::vector<Target> targets;
+    const auto listDevices = [&] () -> bool {
+	targets.clear ();
+
+	if (!socket.writeAll (OpenRgb::makePacket (0, OpenRgb::RequestControllerCount))) {
+	    return false;
+	}
+
+	do {
+	    if (!socket.readPacket (header, payload, 3000)) {
+		return false;
+	    }
+	} while (header.id != OpenRgb::RequestControllerCount);
+
+	if (payload.size () < 4) {
+	    return false;
+	}
+
+	const uint32_t count
+	    = payload[0] | (payload[1] << 8) | (payload[2] << 16) | (static_cast<uint32_t> (payload[3]) << 24);
+
+	for (uint32_t index = 0; index < count; index++) {
+	    std::vector<uint8_t> ask;
+	    OpenRgb::put32 (ask, OpenRgb::kProtocolVersion);
+
+	    if (!socket.writeAll (OpenRgb::makePacket (index, OpenRgb::RequestControllerData, ask))) {
+		return false;
+	    }
+
+	    do {
+		if (!socket.readPacket (header, payload, 3000)) {
+		    return false;
+		}
+	    } while (header.id != OpenRgb::RequestControllerData);
+
+	    auto device = OpenRgb::parseController (payload, index);
+
+	    if (!device || device->ledCount == 0) {
+		continue;
+	    }
+
+	    sLog.out ("LED output: ", device->name, " with ", device->ledCount, " leds");
+	    if (!socket.writeAll (OpenRgb::makePacket (index, OpenRgb::SetCustomMode))) {
+		continue;
+	    }
+
+	    targets.push_back ({ .device = *device, .layout = layoutDevice (*device) });
+	}
+
+	this->m_devices.store (targets.size ());
+	return true;
+    };
+
+    if (!listDevices ()) {
+	return false;
+    }
+
+    if (targets.empty ()) {
+	sLog.out ("LED output: the OpenRGB server has no devices");
+    }
+
+    std::vector<uint8_t> frame (kFrameBytes);
+    std::vector<uint8_t> processed (kFrameBytes);
+    std::vector<uint8_t> colors;
+    auto lastRound = std::chrono::steady_clock::now () - 1h;
+
+    while (this->m_running.load ()) {
+	{
+	    std::unique_lock lock (this->m_mutex);
+
+	    this->m_wake.wait_for (lock, 250ms, [this] { return this->m_fresh || !this->m_running.load (); });
+
+	    if (this->m_fresh) {
+		frame = this->m_frame;
+		this->m_fresh = false;
+	    } else {
+		frame.clear ();
+	    }
+	}
+
+	while (socket.readable ()) {
+	    if (!socket.readPacket (header, payload, 1000)) {
+		return true;
+	    }
+
+	    if (header.id == OpenRgb::DeviceListUpdated && !listDevices ()) {
+		return true;
+	    }
+	}
+
+	if (frame.size () != kFrameBytes) {
+	    continue;
+	}
+
+	const auto now = std::chrono::steady_clock::now ();
+
+	if (options.reduceFps && now - lastRound < 66ms) {
+	    continue;
+	}
+
+	lastRound = now;
+	applyBrightness (frame, processed, options.brightness);
+
+	for (auto& target : targets) {
+	    sampleDevice (processed, target.layout, colors);
+
+	    // devices keep their colors, so an unchanged frame only goes out now and then
+	    if (colors == target.last && now - target.lastSent < 2s) {
+		continue;
+	    }
+
+	    if (!socket.writeAll (OpenRgb::makeUpdateLeds (target.device.index, colors))) {
+		return true;
+	    }
+
+	    target.last = colors;
+	    target.lastSent = now;
+	}
+    }
+
+    return true;
+}
+}

+ 54 - 0
src/WallpaperEngine/Led/LedOutput.h

@@ -0,0 +1,54 @@
+#pragma once
+
+#include <atomic>
+#include <condition_variable>
+#include <cstdint>
+#include <mutex>
+#include <span>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "LedLayout.h"
+
+namespace WallpaperEngine::Led {
+class LedOutput {
+public:
+    struct Options {
+	std::string host = "127.0.0.1";
+	uint16_t port = 6742;
+	Brightness brightness;
+	/** ledextensions64.dll's "reducefps": at most 15 updates a second */
+	bool reduceFps = false;
+    };
+
+    LedOutput () = default;
+    ~LedOutput ();
+    LedOutput (const LedOutput&) = delete;
+    LedOutput& operator= (const LedOutput&) = delete;
+
+    void start (const Options& options);
+    void stop ();
+    [[nodiscard]] bool running () const { return this->m_running.load (); }
+
+    void submit (std::span<const uint8_t> rgb);
+
+    [[nodiscard]] size_t deviceCount () const { return this->m_devices.load (); }
+
+private:
+    struct Connection;
+
+    void run ();
+    bool connectAndServe (const Options& options);
+
+    Options m_options;
+    std::thread m_thread;
+    std::atomic<bool> m_running = false;
+    std::atomic<size_t> m_devices = 0;
+    std::mutex m_mutex;
+    std::condition_variable m_wake;
+    std::vector<uint8_t> m_frame;
+    bool m_fresh = false;
+    bool m_protocolReported = false;
+};
+}

+ 186 - 0
src/WallpaperEngine/Led/OpenRgbProtocol.cpp

@@ -0,0 +1,186 @@
+#include "OpenRgbProtocol.h"
+
+#include <cstring>
+
+namespace WallpaperEngine::Led::OpenRgb {
+void put32 (std::vector<uint8_t>& out, const uint32_t value) {
+    for (int i = 0; i < 4; i++) {
+	out.push_back (static_cast<uint8_t> (value >> (8 * i)));
+    }
+}
+
+namespace {
+    class Reader {
+    public:
+	explicit Reader (const std::span<const uint8_t> bytes) : m_bytes (bytes) { }
+
+	bool u16 (uint32_t& value) {
+	    if (this->m_at + 2 > this->m_bytes.size ()) {
+		return false;
+	    }
+
+	    value = this->m_bytes[this->m_at] | (this->m_bytes[this->m_at + 1] << 8);
+	    this->m_at += 2;
+	    return true;
+	}
+
+	bool u32 (uint32_t& value) {
+	    if (this->m_at + 4 > this->m_bytes.size ()) {
+		return false;
+	    }
+
+	    value = 0;
+
+	    for (int i = 0; i < 4; i++) {
+		value |= static_cast<uint32_t> (this->m_bytes[this->m_at + i]) << (8 * i);
+	    }
+
+	    this->m_at += 4;
+	    return true;
+	}
+
+	bool skip (const size_t count) {
+	    if (this->m_at + count > this->m_bytes.size ()) {
+		return false;
+	    }
+
+	    this->m_at += count;
+	    return true;
+	}
+
+	bool text (std::string& value) {
+	    uint32_t length = 0;
+
+	    if (!this->u16 (length) || this->m_at + length > this->m_bytes.size ()) {
+		return false;
+	    }
+
+	    value.assign (reinterpret_cast<const char*> (this->m_bytes.data () + this->m_at), length);
+
+	    while (!value.empty () && value.back () == '\0') {
+		value.pop_back ();
+	    }
+
+	    this->m_at += length;
+	    return true;
+	}
+
+    private:
+	std::span<const uint8_t> m_bytes;
+	size_t m_at = 0;
+    };
+}
+
+std::vector<uint8_t> makePacket (const uint32_t device, const uint32_t id, const std::span<const uint8_t> payload) {
+    std::vector<uint8_t> out = { 'O', 'R', 'G', 'B' };
+
+    out.reserve (kHeaderSize + payload.size ());
+    put32 (out, device);
+    put32 (out, id);
+    put32 (out, static_cast<uint32_t> (payload.size ()));
+    out.insert (out.end (), payload.begin (), payload.end ());
+    return out;
+}
+
+std::optional<Header> parseHeader (const std::span<const uint8_t> bytes) {
+    if (bytes.size () < kHeaderSize || std::memcmp (bytes.data (), "ORGB", 4) != 0) {
+	return std::nullopt;
+    }
+
+    Header header;
+    const auto read = [&] (const size_t at) {
+	return static_cast<uint32_t> (bytes[at]) | (static_cast<uint32_t> (bytes[at + 1]) << 8)
+	    | (static_cast<uint32_t> (bytes[at + 2]) << 16) | (static_cast<uint32_t> (bytes[at + 3]) << 24);
+    };
+
+    header.device = read (4);
+    header.id = read (8);
+    header.size = read (12);
+    return header;
+}
+
+std::optional<Device> parseController (const std::span<const uint8_t> payload, const uint32_t index) {
+    Reader in (payload);
+    Device device;
+    std::string ignored;
+    uint32_t packetSize = 0;
+    uint32_t deviceType = 0;
+    uint32_t value = 0;
+    uint32_t count = 0;
+
+    device.index = index;
+
+    if (!in.u32 (packetSize) || !in.u32 (deviceType) || !in.text (device.name)) {
+	return std::nullopt;
+    }
+
+    for (int i = 0; i < 5; i++) {
+	if (!in.text (ignored)) {
+	    return std::nullopt;
+	}
+    }
+
+    if (!in.u16 (count) || !in.skip (4)) {
+	return std::nullopt;
+    }
+
+    for (uint32_t mode = 0; mode < count; mode++) {
+	// value, flags, speed and brightness and color count ranges, speed, brightness, direction, color mode: 12 words
+	if (!in.text (ignored) || !in.skip (4 * 12) || !in.u16 (value) || !in.skip (static_cast<size_t> (value) * 4)) {
+	    return std::nullopt;
+	}
+    }
+
+    if (!in.u16 (count)) {
+	return std::nullopt;
+    }
+
+    for (uint32_t i = 0; i < count; i++) {
+	Zone zone;
+	uint32_t matrixBytes = 0;
+
+	if (!in.text (zone.name) || !in.skip (4) || !in.skip (8) || !in.u32 (zone.leds) || !in.u16 (matrixBytes)) {
+	    return std::nullopt;
+	}
+
+	if (matrixBytes > 0) {
+	    if (!in.u32 (zone.matrixHeight) || !in.u32 (zone.matrixWidth)
+		|| static_cast<uint64_t> (zone.matrixHeight) * zone.matrixWidth > 65536) {
+		return std::nullopt;
+	    }
+
+	    zone.matrix.resize (static_cast<size_t> (zone.matrixHeight) * zone.matrixWidth);
+
+	    for (auto& cell : zone.matrix) {
+		if (!in.u32 (cell)) {
+		    return std::nullopt;
+		}
+	    }
+	}
+
+	device.ledCount += zone.leds;
+	device.zones.push_back (std::move (zone));
+    }
+
+    return device;
+}
+
+std::vector<uint8_t> makeUpdateLeds (const uint32_t device, const std::span<const uint8_t> rgb) {
+    const auto leds = static_cast<uint32_t> (rgb.size () / 3);
+    std::vector<uint8_t> payload;
+
+    payload.reserve (6 + leds * 4);
+    put32 (payload, 6 + leds * 4);
+    payload.push_back (static_cast<uint8_t> (leds));
+    payload.push_back (static_cast<uint8_t> (leds >> 8));
+
+    for (uint32_t i = 0; i < leds; i++) {
+	payload.push_back (rgb[i * 3]);
+	payload.push_back (rgb[i * 3 + 1]);
+	payload.push_back (rgb[i * 3 + 2]);
+	payload.push_back (0);
+    }
+
+    return makePacket (device, UpdateLeds, payload);
+}
+}

+ 53 - 0
src/WallpaperEngine/Led/OpenRgbProtocol.h

@@ -0,0 +1,53 @@
+#pragma once
+
+#include <cstdint>
+#include <optional>
+#include <span>
+#include <string>
+#include <vector>
+
+namespace WallpaperEngine::Led {
+namespace OpenRgb {
+    constexpr uint32_t kProtocolVersion = 3;
+    constexpr size_t kHeaderSize = 16;
+
+    enum PacketId : uint32_t {
+	RequestControllerCount = 0,
+	RequestControllerData = 1,
+	RequestProtocolVersion = 40,
+	SetClientName = 50,
+	DeviceListUpdated = 100,
+	UpdateLeds = 1050,
+	SetCustomMode = 1100,
+    };
+
+    void put32 (std::vector<uint8_t>& out, uint32_t value);
+
+    struct Header {
+	uint32_t device = 0;
+	uint32_t id = 0;
+	uint32_t size = 0;
+    };
+
+    struct Zone {
+	std::string name;
+	uint32_t leds = 0;
+	/** row-major led indices inside the zone, 0xFFFFFFFF for an empty cell; empty for a linear zone */
+	std::vector<uint32_t> matrix;
+	uint32_t matrixWidth = 0;
+	uint32_t matrixHeight = 0;
+    };
+
+    struct Device {
+	uint32_t index = 0;
+	std::string name;
+	uint32_t ledCount = 0;
+	std::vector<Zone> zones;
+    };
+
+    [[nodiscard]] std::vector<uint8_t> makePacket (uint32_t device, uint32_t id, std::span<const uint8_t> payload = {});
+    [[nodiscard]] std::optional<Header> parseHeader (std::span<const uint8_t> bytes);
+    [[nodiscard]] std::optional<Device> parseController (std::span<const uint8_t> payload, uint32_t index);
+    [[nodiscard]] std::vector<uint8_t> makeUpdateLeds (uint32_t device, std::span<const uint8_t> rgb);
+}
+}

+ 8 - 8
src/WallpaperEngine/Logging/Log.h

@@ -13,7 +13,7 @@ public:
     void addOutput (std::ostream* stream);
     void addError (std::ostream* stream);
 
-    template <typename... Data> void out (Data... data) {
+    template <typename... Data> void out (const Data&... data) {
 	std::string str = this->buildBuffer (data...);
 	const std::lock_guard lock (this->mMutex);
 
@@ -22,7 +22,7 @@ public:
 	}
     }
 
-    template <typename... Data> void debug (Data... data) {
+    template <typename... Data> void debug (const Data&... data) {
 #if (!NDEBUG) && (!ERRORONLY)
 	std::string str = this->buildBuffer (data...);
 	const std::lock_guard lock (this->mMutex);
@@ -33,7 +33,7 @@ public:
 #endif
     }
 
-    template <typename... Data> void debugerror (Data... data) {
+    template <typename... Data> void debugerror (const Data&... data) {
 #if (!NDEBUG) && (ERRORONLY)
 	std::string str = this->buildBuffer (data...);
 	const std::lock_guard lock (this->mMutex);
@@ -44,7 +44,7 @@ public:
 #endif
     }
 
-    template <typename... Data> void error (Data... data) {
+    template <typename... Data> void error (const Data&... data) {
 	std::string str = this->buildBuffer (data...);
 	const std::lock_guard lock (this->mMutex);
 
@@ -53,7 +53,7 @@ public:
 	}
     }
 
-    template <class EX, typename... Data> [[noreturn]] void exception (Data... data) {
+    template <class EX, typename... Data> [[noreturn]] void exception (const Data&... data) {
 	std::string str = this->buildBuffer (data...);
 
 	{
@@ -67,7 +67,7 @@ public:
 	throw EX (str);
     }
 
-    template <typename... Data> [[noreturn]] void exception (Data... data) {
+    template <typename... Data> [[noreturn]] void exception (const Data&... data) {
 	this->exception<std::runtime_error> (data...);
     }
 
@@ -76,11 +76,11 @@ public:
 private:
     Log ();
 
-    template <typename... Data> std::string buildBuffer (Data... data) {
+    template <typename... Data> std::string buildBuffer (const Data&... data) {
 	std::stringbuf buffer;
 	std::ostream bufferStream (&buffer);
 
-	((bufferStream << std::forward<Data> (data)), ...);
+	((bufferStream << data), ...);
 
 	return buffer.str ();
     }

+ 4 - 3
src/WallpaperEngine/Media/DBusMediaSource.cpp

@@ -1,5 +1,6 @@
 #include "DBusMediaSource.h"
 
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include "WallpaperEngine/Data/Utils/ScopeGuard.h"
 #include "WallpaperEngine/Logging/Log.h"
 
@@ -209,7 +210,7 @@ void DBusMediaSource::parseMetadata (DBusMessageIter& variant) {
 	    int64_t length = 0;
 	    dbus_message_iter_get_basic (&value, &length);
 
-	    if (this->m_mediaInfo.duration != length) {
+	    if (!WallpaperEngine::Data::Utils::sameFloat (this->m_mediaInfo.duration, length)) {
 		this->m_mediaInfo.duration = length;
 		metadataUpdate = true;
 	    }
@@ -294,7 +295,7 @@ void DBusMediaSource::parsePosition (DBusMessageIter& variant) {
     int64_t position = 0;
     dbus_message_iter_get_basic (&variant, &position);
 
-    if (this->m_mediaInfo.position != position) {
+    if (!WallpaperEngine::Data::Utils::sameFloat (this->m_mediaInfo.position, position)) {
 	this->m_mediaInfo.position = position;
 	this->fireMetadataListeners ();
     }
@@ -467,7 +468,7 @@ void DBusMediaSource::performUpdate () {
     dbus_int64_t position = 0;
     dbus_message_iter_get_basic (&variant, &position);
 
-    if (this->m_mediaInfo.position != position) {
+    if (!WallpaperEngine::Data::Utils::sameFloat (this->m_mediaInfo.position, position)) {
 	this->m_mediaInfo.position = position;
 	this->fireMetadataListeners ();
     }

+ 3 - 1
src/WallpaperEngine/Render/AlbumTexture.cpp

@@ -87,7 +87,9 @@ void AlbumTexture::load () const {
 
 	    uploadCoverTexture (this->m_textureID, *image);
 	    return;
-	} catch (AssetLoadException&) { }
+	} catch (AssetLoadException&) {
+	    continue;
+	}
     }
 }
 

+ 5 - 3
src/WallpaperEngine/Render/CFBO.cpp

@@ -176,10 +176,12 @@ void CFBO::setupDepthOnly (const uint32_t width, const uint32_t height) {
 	sLog.exception ("Depth framebuffer ", this->m_name, " is not complete");
     }
 
+    GLdouble previousClearDepth = 1.0;
+    glGetDoublev (GL_DEPTH_CLEAR_VALUE, &previousClearDepth);
     glDepthMask (GL_TRUE);
     glClearDepth (0.0);
     glClear (GL_DEPTH_BUFFER_BIT);
-    glClearDepth (1.0);
+    glClearDepth (previousClearDepth);
 }
 
 CFBO::~CFBO () {
@@ -202,7 +204,7 @@ void CFBO::attachDepthBuffer () {
     glGenRenderbuffers (1, &this->m_depthbuffer);
     glBindRenderbuffer (GL_RENDERBUFFER, this->m_depthbuffer);
     glRenderbufferStorage (
-	GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, static_cast<GLsizei> (this->m_resolution.x),
+	GL_RENDERBUFFER, GL_DEPTH_COMPONENT32F, static_cast<GLsizei> (this->m_resolution.x),
 	static_cast<GLsizei> (this->m_resolution.y)
     );
     glBindRenderbuffer (GL_RENDERBUFFER, 0);
@@ -261,7 +263,7 @@ void CFBO::resize (uint32_t width, uint32_t height, const uint32_t mipLevels) {
     if (this->m_depthbuffer != GL_NONE) {
 	glBindRenderbuffer (GL_RENDERBUFFER, this->m_depthbuffer);
 	glRenderbufferStorage (
-	    GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, static_cast<GLsizei> (width), static_cast<GLsizei> (height)
+	    GL_RENDERBUFFER, GL_DEPTH_COMPONENT32F, static_cast<GLsizei> (width), static_cast<GLsizei> (height)
 	);
 	glBindRenderbuffer (GL_RENDERBUFFER, 0);
     }

+ 3 - 2
src/WallpaperEngine/Render/CTexture.cpp

@@ -16,6 +16,7 @@
 #define STB_IMAGE_IMPLEMENTATION
 #include "RenderContext.h"
 
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include <stb_image.h>
 
 using namespace WallpaperEngine::Render;
@@ -98,7 +99,7 @@ void CTexture::releaseMipmapData () {
 
 void CTexture::uploadImages (const UploadFormat& upload) const {
     struct Decoded {
-	const Mipmap* mipmap;
+	const Mipmap* mipmap = nullptr;
 	stbi_uc* pixels = nullptr;
 	int width = 0;
 	int height = 0;
@@ -441,7 +442,7 @@ void CTexture::update () const {
 
     // wallpaper64.exe 2.8.42 sub_1400EE9E0: once per frame AdvanceGIF with the frame's duration, a new frame is
     // copied over the whole texture
-    if (this->m_gif && this->m_gifTime != g_Time) {
+    if (this->m_gif && !WallpaperEngine::Data::Utils::sameFloat (this->m_gifTime, g_Time)) {
 	this->m_gifTime = g_Time;
 
 	if (this->m_gif->advance (std::max (g_Time - g_TimeLast, 0.0f))) {

+ 11 - 4
src/WallpaperEngine/Render/CWallpaper.cpp

@@ -18,6 +18,7 @@
 
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 
 using namespace WallpaperEngine::Render;
 using WallpaperEngine::Data::Utils::BinaryReader;
@@ -635,8 +636,10 @@ void CWallpaper::present (const glm::ivec4& viewport, const glm::ivec2& globalPo
 
     glBindVertexArray (this->m_vaoBuffer);
 
-    if (ustart != this->m_uploadedUstart || uend != this->m_uploadedUend || vstart != this->m_uploadedVstart
-	|| vend != this->m_uploadedVend) {
+    if (!WallpaperEngine::Data::Utils::sameFloat (ustart, this->m_uploadedUstart)
+	|| !WallpaperEngine::Data::Utils::sameFloat (uend, this->m_uploadedUend)
+	|| !WallpaperEngine::Data::Utils::sameFloat (vstart, this->m_uploadedVstart)
+	|| !WallpaperEngine::Data::Utils::sameFloat (vend, this->m_uploadedVend)) {
 	glBindBuffer (GL_ARRAY_BUFFER, this->m_texCoordBuffer);
 	glBufferSubData (GL_ARRAY_BUFFER, 0, sizeof (texCoords), texCoords);
 	this->m_uploadedUstart = ustart;
@@ -656,7 +659,7 @@ void CWallpaper::present (const glm::ivec4& viewport, const glm::ivec2& globalPo
 	    for (size_t i = 0; i < px.size (); i += 4) {
 		sum += px[i] + px[i + 1] + px[i + 2];
 	    }
-	    const double mean = static_cast<double> (sum) / (px.size () / 4 * 3);
+	    const double mean = static_cast<double> (sum) / static_cast<double> (px.size () / 4 * 3);
 	    sLog.out ("[BRIGHTNESS] frame=", brightnessFrameCounter, " mean=", mean);
 	}
     }
@@ -783,6 +786,7 @@ void CWallpaper::setAlignment (const WallpaperState::Alignment& alignment) { thi
 void CWallpaper::setCornerColor (const glm::vec4& color) { this->m_cornerColor = color; }
 
 void CWallpaper::setImageAdjustments (const ImageAdjustments& adjustments) {
+    this->m_imageAdjustments = adjustments;
     // wallpaper64.exe sub_140181F30: sliders are 0-100 around 50, contrast and saturation go through a square
     // root and brightness through a square before reaching ccsimple
     const float brightness = adjustments.brightness.value_or (50.0f) / 50.0f;
@@ -791,7 +795,10 @@ void CWallpaper::setImageAdjustments (const ImageAdjustments& adjustments) {
     const float hue = adjustments.hue.value_or (50.0f) / 100.0f - 0.5f;
 
     this->m_colorEnabled = adjustments.colorEnabled.value_or (false)
-	&& (contrast != 1.0f || brightness != 1.0f || saturation != 1.0f || hue != 0.0f);
+	&& (!WallpaperEngine::Data::Utils::sameFloat (contrast, 1.0f)
+	    || !WallpaperEngine::Data::Utils::sameFloat (brightness, 1.0f)
+	    || !WallpaperEngine::Data::Utils::sameFloat (saturation, 1.0f)
+	    || WallpaperEngine::Data::Utils::isNonZero (hue));
     this->m_colorParams = { std::pow (brightness, 2.0f), std::pow (contrast, 0.5f), std::pow (saturation, 0.5f), hue };
     this->m_lutStrength = adjustments.filterStrength.value_or (100.0f) / 100.0f;
     this->m_flipHorizontal = adjustments.flipHorizontal.value_or (false);

+ 3 - 0
src/WallpaperEngine/Render/CWallpaper.h

@@ -81,6 +81,8 @@ public:
     void setCornerColor (const glm::vec4& color);
 
     void setImageAdjustments (const ImageAdjustments& adjustments);
+    /** what was set, in WE's slider units: scripts see these as wec_*, wcc_* and alignmentfliph */
+    [[nodiscard]] const ImageAdjustments& getImageAdjustments () const { return this->m_imageAdjustments; }
     [[nodiscard]] bool isFlippedHorizontally () const { return this->m_flipHorizontal; }
     [[nodiscard]] bool hasImageAdjustments () const;
     void setOutputHDR (bool hdr, const glm::vec2& luminance = glm::vec2 (0.0f)) {
@@ -206,6 +208,7 @@ private:
     WallpaperState m_state;
     glm::vec4 m_cornerColor = { 0.0f, 0.0f, 0.0f, 1.0f };
     glm::vec4 m_colorParams = { 1.0f, 1.0f, 1.0f, 0.0f };
+    ImageAdjustments m_imageAdjustments;
     bool m_colorEnabled = false;
     float m_lutStrength = 0.0f;
     std::string m_lutName;

+ 19 - 11
src/WallpaperEngine/Render/Camera.cpp

@@ -5,6 +5,7 @@
 #include <glm/gtc/matrix_transform.hpp>
 
 #include "Camera.h"
+#include "DepthRange.h"
 
 using namespace WallpaperEngine;
 using namespace WallpaperEngine::Render;
@@ -72,9 +73,11 @@ void Camera::setOrthogonalProjection (
     this->m_canvasHeight = canvasHeight > 0.0f ? canvasHeight : height;
 
     // WE's 2D projection keeps -2000..2000 in depth (sub_140183A70), rotated layers and particles poke out of z = 0
-    this->m_fullscreen = glm::ortho<float> (
-	-this->m_canvasWidth / 2.0f, this->m_canvasWidth / 2.0f, -this->m_canvasHeight / 2.0f,
-	this->m_canvasHeight / 2.0f, -2000.0f, 2000.0f
+    this->m_fullscreen = DepthRange::toClip (
+	glm::ortho<float> (
+	    -this->m_canvasWidth / 2.0f, this->m_canvasWidth / 2.0f, -this->m_canvasHeight / 2.0f,
+	    this->m_canvasHeight / 2.0f, -2000.0f, 2000.0f
+	)
     );
     this->m_isOrthogonal = true;
     this->setWorldView (glm::mat4 (1.0f));
@@ -87,14 +90,16 @@ void Camera::setPerspectiveProjection (const float width, const float height) {
     this->m_canvasWidth = width;
     this->m_canvasHeight = height;
 
-    this->m_projection = glm::ortho<float> (-width / 2.0f, width / 2.0f, -height / 2.0f, height / 2.0f, 0.0f, 1000.0f);
+    this->m_projection = DepthRange::toClip (
+	glm::ortho<float> (-width / 2.0f, width / 2.0f, -height / 2.0f, height / 2.0f, 0.0f, 1000.0f)
+    );
     this->m_view = this->m_lookat;
     this->m_lookat = glm::mat4 (1.0f);
 
     // XMMatrixPerspectiveFovRH with the vertical fov in degrees and the render target's aspect (sub_140146660)
     const float fov = glm::clamp (this->getFov (), 0.1f, 179.9f);
     this->m_perspective = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
-	* glm::perspective (glm::radians (fov), width / height, this->getNearZ (), this->getFarZ ());
+	* DepthRange::perspective (glm::radians (fov), width / height, this->getNearZ (), this->getFarZ ());
     this->m_isPerspective = true;
 }
 namespace {
@@ -128,7 +133,7 @@ void Camera::setPerspectiveView (const glm::mat4& view, const float fov) {
     this->m_eye = glm::vec3 (glm::inverse (view)[3]);
     this->m_view = view;
     const float aspect = this->m_outputAspect > 0.0f ? this->m_outputAspect : this->m_width / this->m_height;
-    this->m_perspective = kFlipY * glm::perspective (radians, aspect, this->getNearZ (), this->getFarZ ());
+    this->m_perspective = kFlipY * DepthRange::perspective (radians, aspect, this->getNearZ (), this->getFarZ ());
 
     // "perspective" layers in 3D scenes: sub_140183A70 sets the renderer fov to 2 atan (tan (fov / 2) / 2000), so
     // sub_1401E5B60 always backs off to 2000, keeps the view's rotation and x/y (the visible region offsets are 0 in
@@ -136,7 +141,8 @@ void Camera::setPerspectiveView (const glm::mat4& view, const float fov) {
     glm::mat4 layerView = view;
     layerView[3][2] = -2000.0f;
     this->m_perspectiveLayer = kFlipY
-	* glm::perspective (2.0f * std::atan (std::tan (radians / 2.0f) / 2000.0f), aspect, 5.0f, 15000.0f) * layerView;
+	* DepthRange::perspective (2.0f * std::atan (std::tan (radians / 2.0f) / 2000.0f), aspect, 5.0f, 15000.0f)
+	* layerView;
 }
 
 void Camera::setVisibleRegion (const glm::vec4& margins, const float outputAspect) {
@@ -150,9 +156,11 @@ void Camera::setVisibleRegion (const glm::vec4& margins, const float outputAspec
     const float halfWidth = this->m_canvasWidth / 2.0f;
     const float halfHeight = this->m_canvasHeight / 2.0f;
 
-    this->m_orthogonal = glm::ortho<float> (
-	-halfWidth + margins.x, halfWidth - margins.y, -halfHeight + margins.z, halfHeight - margins.w, -2000.0f,
-	2000.0f
+    this->m_orthogonal = DepthRange::toClip (
+	glm::ortho<float> (
+	    -halfWidth + margins.x, halfWidth - margins.y, -halfHeight + margins.z, halfHeight - margins.w, -2000.0f,
+	    2000.0f
+	)
     );
     this->setZoom (this->m_zoom);
 }
@@ -186,7 +194,7 @@ void Camera::updatePerspectiveLayers () {
 
     const float aspect
 	= this->m_outputAspect > 0.0f ? this->m_outputAspect : this->m_canvasWidth / this->m_canvasHeight;
-    const glm::mat4 projection = glm::perspective (fov, aspect, 5.0f, farZ);
+    const glm::mat4 projection = DepthRange::perspective (fov, aspect, 5.0f, farZ);
 
     const glm::vec3 center (width / 2.0f, height / 2.0f, 0.0f);
     this->m_perspectiveLayer = kFlipY * projection * view * glm::translate (glm::mat4 (1.0f), center) * kFlipY;

+ 96 - 0
src/WallpaperEngine/Render/DepthRange.cpp

@@ -0,0 +1,96 @@
+#include "DepthRange.h"
+
+#include <cmath>
+#include <cstdlib>
+
+#include <glm/gtc/matrix_transform.hpp>
+
+namespace {
+int s_scopes = 0;
+}
+
+namespace WallpaperEngine::Render::DepthRange {
+bool supported () {
+    static const bool forward = std::getenv ("LWE_FORWARD_DEPTH") != nullptr;
+
+    return !forward && (GLEW_VERSION_4_5 || GLEW_ARB_clip_control);
+}
+
+Scope::Scope () {
+    if (!supported () || s_scopes++ > 0) {
+	return;
+    }
+
+    glClipControl (GL_LOWER_LEFT, GL_ZERO_TO_ONE);
+    glClearDepth (0.0);
+}
+
+Scope::~Scope () {
+    if (!supported () || --s_scopes > 0) {
+	return;
+    }
+
+    glClipControl (GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE);
+    glClearDepth (1.0);
+}
+
+glm::mat4 toClip (const glm::mat4& projection) {
+    if (!supported ()) {
+	return projection;
+    }
+
+    glm::mat4 result = projection;
+
+    for (int column = 0; column < 4; column++) {
+	result[column][2] = 0.5f * (projection[column][3] - projection[column][2]);
+    }
+
+    return result;
+}
+
+glm::mat4 perspective (const float fovY, const float aspect, const float near, const float far) {
+    if (!supported ()) {
+	return glm::perspective (fovY, aspect, near, far);
+    }
+
+    const double height = 1.0 / std::tan (static_cast<double> (fovY) * 0.5);
+    const double n = near;
+    const double f = far;
+    glm::mat4 projection (0.0f);
+
+    projection[0][0] = static_cast<float> (height / aspect);
+    projection[1][1] = static_cast<float> (height);
+    projection[2][2] = static_cast<float> (n / (f - n));
+    projection[2][3] = -1.0f;
+    projection[3][2] = static_cast<float> (n * f / (f - n));
+
+    return projection;
+}
+
+GLenum depthFunc (const GLenum forward) {
+    if (!supported ()) {
+	return forward;
+    }
+
+    switch (forward) {
+	case GL_LESS:
+	    return GL_GREATER;
+	case GL_LEQUAL:
+	    return GL_GEQUAL;
+	case GL_GREATER:
+	    return GL_LESS;
+	case GL_GEQUAL:
+	    return GL_LEQUAL;
+	default:
+	    return forward;
+    }
+}
+
+GLclampd farDepth () { return supported () ? 0.0 : 1.0; }
+
+float nearClip () { return supported () ? 1.0f : -1.0f; }
+
+float farClip () { return supported () ? 0.0f : 1.0f; }
+
+float middleClip () { return supported () ? 0.5f : 0.0f; }
+}

+ 34 - 0
src/WallpaperEngine/Render/DepthRange.h

@@ -0,0 +1,34 @@
+#pragma once
+
+#include <GL/glew.h>
+#include <glm/mat4x4.hpp>
+
+namespace WallpaperEngine::Render::DepthRange {
+/**
+ * WE renders its scene with a reversed float depth buffer (1 at the near plane, 0 at the far one, D32F cleared to 0,
+ * sub_14009A360). With ARB_clip_control that is what a scene is drawn with here: clip z is mapped to 0..1 while the
+ * scene renders (Scope), every matrix handed to a pass has its depth built or remapped that way, and depth tests
+ * are the mirrored ones. Without the extension everything stays forward, 0 at the near plane
+ */
+bool supported ();
+
+class Scope {
+public:
+    Scope ();
+    ~Scope ();
+    Scope (const Scope&) = delete;
+    Scope& operator= (const Scope&) = delete;
+};
+
+glm::mat4 toClip (const glm::mat4& projection);
+
+glm::mat4 perspective (float fovY, float aspect, float near, float far);
+
+GLenum depthFunc (GLenum forward);
+
+GLclampd farDepth ();
+
+float nearClip ();
+float farClip ();
+float middleClip ();
+}

+ 41 - 1
src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.cpp

@@ -2,6 +2,7 @@
 #include "WallpaperEngine/Logging/Log.h"
 
 #include <algorithm>
+#include <cstdlib>
 
 #include <X11/Xatom.h>
 #include <X11/Xlib.h>
@@ -50,6 +51,15 @@ X11FullScreenDetector::X11FullScreenDetector (Application::ApplicationContext& a
     XSetIOErrorHandler (CustomXIOErrorHandler);
 
     this->initialize ();
+
+    if (std::getenv ("LWE_XWAYLAND_FALLBACK") != nullptr && Desktop::isPantheonSession ()) {
+	this->m_gala = std::make_unique<Desktop::PantheonShell> ();
+
+	if (!this->m_gala->isAvailable ()) {
+	    sLog.error ("Native Wayland windows are not seen, ", this->m_gala->reason ());
+	    this->m_gala.reset ();
+	}
+    }
 }
 
 X11FullScreenDetector::~X11FullScreenDetector () { this->stop (); }
@@ -92,7 +102,37 @@ bool X11FullScreenDetector::anythingFullscreen () const {
 
     XFree (children);
 
-    return fullscreen || (render.pauseOnFocus && this->applicationFocused (ourWindow));
+    bool galaFocused = false;
+    const bool galaCovers = this->galaWindowCovers (galaFocused);
+
+    return fullscreen || (render.pauseOnFullscreen && galaCovers)
+	|| (render.pauseOnFocus && (this->applicationFocused (ourWindow) || galaFocused));
+}
+
+bool X11FullScreenDetector::galaWindowCovers (bool& focused) const {
+    if (this->m_gala == nullptr) {
+	return false;
+    }
+
+    this->m_gala->dispatch ();
+
+    bool covers = false;
+
+    for (const auto& window : this->m_gala->windows ()) {
+	// our own background window is a window of Gala's too
+	if (window.hidden || window.workspace != this->m_gala->activeWorkspace ()
+	    || window.wmClass == "linux-wallpaperengine") {
+	    continue;
+	}
+
+	focused = focused || window.focused;
+	covers = covers || std::ranges::any_of (this->m_screens, [&] (const auto& entry) {
+		     return window.width >= static_cast<uint32_t> (entry.second.z)
+			 && window.height >= static_cast<uint32_t> (entry.second.w);
+		 });
+    }
+
+    return covers;
 }
 
 bool X11FullScreenDetector::applicationFocused (Window ourWindow) const {

+ 4 - 0
src/WallpaperEngine/Render/Drivers/Detectors/X11FullScreenDetector.h

@@ -1,10 +1,12 @@
 #pragma once
 
 #include <glm/vec4.hpp>
+#include <memory>
 #include <string>
 #include <vector>
 
 #include "FullScreenDetector.h"
+#include "WallpaperEngine/Desktop/PantheonShell.h"
 #include "WallpaperEngine/Render/Drivers/VideoDriver.h"
 #include <X11/Xlib.h>
 
@@ -30,12 +32,14 @@ namespace Detectors {
 	[[nodiscard]] bool onCurrentDesktop (Window client) const;
 	[[nodiscard]] bool coversScreen (Window client) const;
 	[[nodiscard]] bool applicationFocused (Window ourWindow) const;
+	[[nodiscard]] bool galaWindowCovers (bool& focused) const;
 	void stop ();
 
 	Display* m_display = nullptr;
 	Window m_root;
 	std::map<std::string, glm::ivec4> m_screens = {};
 	VideoDriver& m_driver;
+	std::unique_ptr<Desktop::PantheonShell> m_gala;
     };
 }
 }

+ 0 - 1
src/WallpaperEngine/Render/Drivers/GLFWOpenGLDriver.cpp

@@ -22,7 +22,6 @@
 
 using namespace WallpaperEngine::Render::Drivers;
 
-// whether the wallpaper the engine starts with is a web one (project.json "type": "web")
 static bool isWebProject (const std::filesystem::path& background) {
     std::error_code error;
     const auto file = std::filesystem::is_directory (background, error) ? background / "project.json" : background;

+ 0 - 1
src/WallpaperEngine/Render/Drivers/Output/GLFWWindowOutput.cpp

@@ -29,7 +29,6 @@ GLFWWindowOutput::GLFWWindowOutput (ApplicationContext& context, VideoDriver& dr
 	sLog.error ("--window-background only works on X11, the window stays a normal one");
     }
 
-    // the GL window stays hidden for a background window, it only renders
     if (!background || driver.getX11Display () == nullptr) {
 	driver.showWindow ();
     }

+ 5 - 0
src/WallpaperEngine/Render/Drivers/Output/WaylandOutput.cpp

@@ -11,6 +11,11 @@ WaylandOutput::WaylandOutput (ApplicationContext& context, WaylandOpenGLDriver&
 void WaylandOutput::updateViewports () {
     m_viewports.clear ();
     const auto PDRIVER = dynamic_cast<WaylandOpenGLDriver*> (&m_driver);
+
+    if (PDRIVER == nullptr) {
+	return;
+    }
+
     glm::ivec2 fullw = { 0, 0 };
     for (const auto& o : PDRIVER->m_screens) {
 	if (!o->hasShellSurface ()) {

+ 1 - 1
src/WallpaperEngine/Render/Drivers/Output/WaylandOutputViewport.cpp

@@ -448,7 +448,7 @@ void WaylandOutputViewport::setupLS () {
 	ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT | ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT | ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP
 	    | ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM
     );
-    zwlr_layer_surface_v1_set_keyboard_interactivity (layerSurface, false);
+    zwlr_layer_surface_v1_set_keyboard_interactivity (layerSurface, 0);
     zwlr_layer_surface_v1_add_listener (layerSurface, &layerSurfaceListener, this);
     zwlr_layer_surface_v1_set_exclusive_zone (layerSurface, -1);
 

+ 203 - 60
src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.cpp

@@ -28,6 +28,7 @@ namespace {
 constexpr int KEY_TOLERANCE = 2;
 constexpr int OPAQUE_DISTANCE = 48;
 constexpr const char* XFCE_CHANNEL = "xfce4-desktop";
+constexpr const char* MATE_SCHEMA = "org.mate.background";
 
 bool runCapture (const std::vector<std::string>& argv, std::string* output = nullptr) {
     int fds[2];
@@ -121,10 +122,10 @@ int number (const std::string& text, size_t from) {
     return static_cast<int> (std::strtol (text.c_str () + from, nullptr, 10));
 }
 
-std::string restoreFilePath () {
+std::string restoreFilePath (const char* kind) {
     const char* runtime = std::getenv ("XDG_RUNTIME_DIR");
     std::string path = runtime != nullptr && *runtime != '\0' ? runtime : "/tmp";
-    path += "/lwe-xfdesktop-restore." + std::to_string (getuid ()) + ".sh";
+    path += std::string ("/lwe-") + kind + "-restore." + std::to_string (getuid ()) + ".sh";
     return path;
 }
 
@@ -180,20 +181,93 @@ std::string defaultWallpaper () {
     return {};
 }
 
-class XfceBackdrop {
+class Backdrop {
 public:
+    virtual ~Backdrop () = default;
+
     bool apply (const std::vector<std::string>& outputNames) {
-	const std::string path = restoreFilePath ();
+	const std::string path = restoreFilePath (this->kind ());
 
 	if (const pid_t owner = restoreOwner (path); owner != 0) {
 	    if (alive (owner) && owner != getpid ()) {
-		sLog.out ("Another engine already keys xfdesktop's background, sharing it");
+		sLog.out ("Another engine already keys the desktop's background, sharing it");
 		return true;
 	    }
 
 	    runRestore (path, owner);
 	}
 
+	std::ostringstream restore;
+	restore << "# " << getpid () << "\n";
+
+	if (!this->change (outputNames, restore)) {
+	    return false;
+	}
+
+	{
+	    std::ofstream file (path, std::ios::trunc);
+	    file << restore.str ();
+	}
+
+	chmod (path.c_str (), 0600);
+	this->m_path = path;
+	this->m_owner = getpid ();
+	this->watch ();
+	return true;
+    }
+
+    void restore () {
+	if (this->m_path.empty () || this->m_owner != getpid ()) {
+	    return;
+	}
+
+	runRestore (this->m_path, this->m_owner);
+	this->m_path.clear ();
+	this->m_owner = 0;
+    }
+
+protected:
+    virtual bool change (const std::vector<std::string>& outputNames, std::ostringstream& restore) = 0;
+    [[nodiscard]] virtual const char* kind () const = 0;
+
+private:
+    /** a SIGKILLed engine would leave the desktop with the key color, so a shell waits for it and puts the settings
+     * back */
+    void watch () const {
+	const std::string status = "/proc/" + std::to_string (this->m_owner) + "/status";
+	std::string script = "while [ -r " + status + " ] && ! grep -q '^State:.*Z' " + status + "; do sleep 1; done; ";
+	script
+	    += R"sh(f="$1"; [ "$(sed -n 1p "$f" 2>/dev/null)" = "# $2" ] || exit 0; t="$f.run.$$"; mv "$f" "$t" 2>/dev/null || exit 0; sh "$t"; rm -f "$t")sh";
+	const std::string path = this->m_path;
+	const std::string owner = std::to_string (this->m_owner);
+	const pid_t pid = fork ();
+
+	if (pid != 0) {
+	    return;
+	}
+
+	setsid ();
+	const int null = open ("/dev/null", O_RDWR);
+
+	if (null >= 0) {
+	    dup2 (null, STDIN_FILENO);
+	    dup2 (null, STDOUT_FILENO);
+	    dup2 (null, STDERR_FILENO);
+	}
+
+	execlp ("sh", "sh", "-c", script.c_str (), "sh", path.c_str (), owner.c_str (), static_cast<char*> (nullptr));
+	_exit (127);
+    }
+
+    std::string m_path;
+    pid_t m_owner = 0;
+};
+
+class XfceBackdrop : public Backdrop {
+protected:
+    [[nodiscard]] const char* kind () const override { return "xfdesktop"; }
+
+    bool change (const std::vector<std::string>& outputNames, std::ostringstream& restore) override {
 	std::string listing;
 
 	if (!runCapture ({ "xfconf-query", "-c", XFCE_CHANNEL, "-l" }, &listing)) {
@@ -231,8 +305,6 @@ public:
 	    }
 	}
 
-	std::ostringstream restore;
-	restore << "# " << getpid () << "\n";
 	bool changed = false;
 	const std::string fallback = defaultWallpaper ();
 
@@ -300,70 +372,125 @@ public:
 	    }
 	}
 
-	if (!changed) {
+	return changed;
+    }
+};
+
+class MateBackdrop : public Backdrop {
+protected:
+    [[nodiscard]] const char* kind () const override { return "caja"; }
+
+    bool change (const std::vector<std::string>&, std::ostringstream& restore) override {
+	// caja draws the desktop's background from these, no picture and a solid black is what the key color needs
+	bool changed = false;
+
+	for (const auto& [key, value] : { std::pair<const char*, const char*> { "picture-filename", "''" },
+					  { "primary-color", "'#000000'" },
+					  { "color-shading-type", "'solid'" } }) {
+	    std::string old;
+
+	    if (!runCapture ({ "gsettings", "get", MATE_SCHEMA, key }, &old)) {
+		continue;
+	    }
+
+	    const auto values = lines (old);
+
+	    if (values.empty () || !runCapture ({ "gsettings", "set", MATE_SCHEMA, key, value })) {
+		continue;
+	    }
+
+	    changed = true;
+	    restore << "gsettings set " << MATE_SCHEMA << " " << key << " " << quote (values.back ()) << "\n";
+	}
+
+	return changed;
+    }
+};
+
+class LxqtBackdrop : public Backdrop {
+protected:
+    [[nodiscard]] const char* kind () const override { return "pcmanfm-qt"; }
+
+    bool change (const std::vector<std::string>&, std::ostringstream& restore) override {
+	const std::string before = setting ("WallpaperMode");
+
+	if (before.empty ()) {
 	    return false;
 	}
 
-	{
-	    std::ofstream file (path, std::ios::trunc);
-	    file << restore.str ();
+	// pcmanfm-qt calls its plain color mode "none" in the settings file and "color" on the command line
+	const std::string old = before == "none" ? "color" : before;
+
+	if (old != "color" && !runCapture ({ "pcmanfm-qt", "--wallpaper-mode", "color" })) {
+	    return false;
 	}
 
-	chmod (path.c_str (), 0600);
-	this->m_path = path;
-	this->m_owner = getpid ();
-	this->watch ();
-	return true;
-    }
+	// the color can't be changed from outside, only a black desktop can be keyed; the file is written by the
+	// running desktop with the mode switch, so it shows the color that is really used
+	if (const std::string color = setting ("BgColor"); !isBlack (color)) {
+	    if (old != "color") {
+		runCapture ({ "pcmanfm-qt", "--wallpaper-mode", old });
+	    }
 
-    void restore () {
-	if (this->m_path.empty () || this->m_owner != getpid ()) {
-	    return;
+	    return false;
 	}
 
-	runRestore (this->m_path, this->m_owner);
-	this->m_path.clear ();
-	this->m_owner = 0;
+	if (old != "color") {
+	    restore << "pcmanfm-qt --wallpaper-mode " << quote (old) << "\n";
+	}
+
+	return true;
     }
 
 private:
-    /** a SIGKILLed engine would leave the desktop with the key color, so a shell waits for it and puts the settings
-     * back */
-    void watch () const {
-	const std::string status = "/proc/" + std::to_string (this->m_owner) + "/status";
-	std::string script = "while [ -r " + status + " ] && ! grep -q '^State:.*Z' " + status + "; do sleep 1; done; ";
-	script
-	    += R"sh(f="$1"; [ "$(sed -n 1p "$f" 2>/dev/null)" = "# $2" ] || exit 0; t="$f.run.$$"; mv "$f" "$t" 2>/dev/null || exit 0; sh "$t"; rm -f "$t")sh";
-	const std::string path = this->m_path;
-	const std::string owner = std::to_string (this->m_owner);
-	const pid_t pid = fork ();
+    static bool isBlack (const std::string& color) {
+	std::string text = color;
+	text.erase (std::remove (text.begin (), text.end (), '"'), text.end ());
+	return text == "#000000" || text == "#000";
+    }
 
-	if (pid != 0) {
-	    return;
+    static std::string setting (const char* key) {
+	const char* config = std::getenv ("XDG_CONFIG_HOME");
+	const char* home = std::getenv ("HOME");
+	std::string base = config != nullptr && *config != '\0' ? config
+	    : home != nullptr                                   ? std::string (home) + "/.config"
+								: "";
+
+	if (base.empty ()) {
+	    return {};
 	}
 
-	setsid ();
-	const int null = open ("/dev/null", O_RDWR);
+	for (const char* profile : { "lxqt", "default" }) {
+	    std::ifstream file (base + "/pcmanfm-qt/" + profile + "/settings.conf");
+	    std::string line;
+	    bool desktop = false;
 
-	if (null >= 0) {
-	    dup2 (null, STDIN_FILENO);
-	    dup2 (null, STDOUT_FILENO);
-	    dup2 (null, STDERR_FILENO);
+	    while (std::getline (file, line)) {
+		if (!line.empty () && line[0] == '[') {
+		    desktop = line == "[Desktop]";
+		} else if (desktop && line.rfind (std::string (key) + "=", 0) == 0) {
+		    return line.substr (std::strlen (key) + 1);
+		}
+	    }
 	}
 
-	execl (
-	    "/bin/sh", "sh", "-c", script.c_str (), "sh", path.c_str (), owner.c_str (), static_cast<char*> (nullptr)
-	);
-	_exit (127);
+	return {};
     }
-
-    std::string m_path;
-    pid_t m_owner = 0;
 };
 
-XfceBackdrop& backdrop () {
-    static XfceBackdrop instance;
-    return instance;
+Backdrop& backdropFor (int kind) {
+    static XfceBackdrop xfce;
+    static MateBackdrop mate;
+    static LxqtBackdrop lxqt;
+
+    switch (kind) {
+	case 1:
+	    return mate;
+	case 2:
+	    return lxqt;
+	default:
+	    return xfce;
+    }
 }
 
 bool classContains (Display* display, Window window, const char* needle) {
@@ -398,12 +525,26 @@ X11DesktopIcons::~X11DesktopIcons () {
     }
 
     if (this->m_active) {
-	backdrop ().restore ();
+	backdropFor (this->m_kind).restore ();
     }
 }
 
-bool X11DesktopIcons::supports (Display* display, Window window) {
-    return classContains (display, window, "xfdesktop");
+bool X11DesktopIcons::supports (Display* display, Window window) { return kindOf (display, window) >= 0; }
+
+int X11DesktopIcons::kindOf (Display* display, Window window) {
+    if (classContains (display, window, "xfdesktop")) {
+	return 0;
+    }
+
+    if (classContains (display, window, "caja")) {
+	return 1;
+    }
+
+    if (classContains (display, window, "pcmanfm")) {
+	return 2;
+    }
+
+    return -1;
 }
 
 bool X11DesktopIcons::start (const std::vector<Window>& windows, const std::vector<std::string>& outputNames) {
@@ -422,17 +563,19 @@ bool X11DesktopIcons::start (const std::vector<Window>& windows, const std::vect
 	return false;
     }
 
-    // following first: xfdesktop paints the key color as soon as the setting changes and that damage has to be seen
+    // following first: the desktop paints the key color as soon as the setting changes and that damage has to be seen
     this->follow (windows);
 
-    if (!backdrop ().apply (outputNames)) {
-	sLog.out ("xfdesktop's background could not be set to the key color, its icons stay under the wallpaper");
+    this->m_kind = windows.empty () ? 0 : std::max (kindOf (this->m_display, windows.front ()), 0);
+
+    if (!backdropFor (this->m_kind).apply (outputNames)) {
+	sLog.out ("The desktop's background could not be set to the key color, its icons stay under the wallpaper");
 	this->follow ({});
 	return false;
     }
 
     this->m_active = true;
-    sLog.out ("xfdesktop's icons are drawn over the wallpaper, its background is black while the engine runs");
+    sLog.out ("The desktop's icons are drawn over the wallpaper, its background is black while the engine runs");
     return true;
 }
 
@@ -544,8 +687,8 @@ void X11DesktopIcons::capture (Tracked& tracked) {
 	return;
     }
 
-    // the window only counts once it paints the key color: before xfdesktop took the setting up it still shows its own
-    // wallpaper, which would otherwise cover the real one
+    // the window only counts once it paints the key color: before the desktop took the setting up it still shows its
+    // own wallpaper, which would otherwise cover the real one
     size_t keyed = 0;
     size_t sampled = 0;
 

+ 6 - 4
src/WallpaperEngine/Render/Drivers/Output/X11DesktopIcons.h

@@ -9,10 +9,10 @@
 
 namespace WallpaperEngine::Render::Drivers::Output {
 /**
- * Keeps the icons of an opaque desktop window (xfdesktop) visible above the wallpaper. The window stays where it is and
- * keeps handling every click, its background is turned into a key colour, the window's pixels are read through the
- * Composite extension whenever it is damaged and every pixel that is not the key colour is drawn over the wallpaper
- * frame before it goes to the screen.
+ * Keeps the icons of an opaque desktop window (xfdesktop, caja, pcmanfm-qt) visible above the wallpaper. The window
+ * stays where it is and keeps handling every click, its background is turned into a key colour, the window's pixels are
+ * read through the Composite extension whenever it is damaged and every pixel that is not the key colour is drawn over
+ * the wallpaper frame before it goes to the screen.
  */
 class X11DesktopIcons {
 public:
@@ -23,6 +23,7 @@ public:
     X11DesktopIcons& operator= (const X11DesktopIcons&) = delete;
 
     [[nodiscard]] static bool supports (Display* display, Window window);
+    [[nodiscard]] static int kindOf (Display* display, Window window);
 
     bool start (const std::vector<Window>& windows, const std::vector<std::string>& outputNames);
 
@@ -65,6 +66,7 @@ private:
     int m_fullHeight;
     int m_damageEvent = 0;
     bool m_active = false;
+    int m_kind = 0;
     std::vector<Tracked> m_tracked;
 };
 }

+ 13 - 6
src/WallpaperEngine/Render/Drivers/Output/X11Output.cpp

@@ -21,7 +21,8 @@ void CustomXIOErrorExitHandler (Display* dsp, void* userdata) {
 
     sLog.debugerror ("Critical XServer error detected. Attempting to recover...");
 
-    context->reset ();
+    // Xlib is still inside the call that failed, the display can only go away once that has returned
+    context->requestReset ();
 }
 
 int CustomXErrorHandler (Display* dpy, XErrorEvent* event) {
@@ -111,6 +112,7 @@ bool X11Output::haveImageBuffer () const { return true; }
 uint32_t X11Output::getImageBufferSize () const { return this->m_imageSize; }
 
 void X11Output::loadScreenInfo () {
+    this->m_resetPending = false;
     this->m_display = XOpenDisplay (nullptr);
 #ifdef HAVE_XSETIOERROREXITHANDLER
     XSetIOErrorExitHandler (this->m_display, CustomXIOErrorExitHandler, this);
@@ -251,7 +253,14 @@ void X11Output::initX11Background () {
     this->m_driver.resizeWindow ({ this->m_fullWidth, this->m_fullHeight });
 }
 
+void X11Output::requestReset () const { this->m_resetPending = true; }
+
 void X11Output::updateRender () const {
+    if (this->m_resetPending) {
+	const_cast<X11Output*> (this)->reset ();
+	return;
+    }
+
     if (this->m_background != nullptr) {
 	this->m_background->present ();
 	return;
@@ -268,15 +277,13 @@ void X11Output::updateRender () const {
 	this->m_display, this->m_pixmap, this->m_gc, this->m_image, 0, 0, 0, 0, this->m_fullWidth, this->m_fullHeight
     );
 
-    // _XROOTPMAP_ID/ESETROOT_PMAP_ID tell compositors about the background pixmap and force a refresh (picom)
+    // _XROOTPMAP_ID tells compositors about the background pixmap and forces a refresh (picom). ESETROOT_PMAP_ID is
+    // left alone: whoever sets the next root background (mate-bg, feh, ...) calls XKillClient on the pixmap it names,
+    // which closes our whole connection to the server
     const Atom prop_root = XInternAtom (this->m_display, "_XROOTPMAP_ID", False);
-    const Atom prop_esetroot = XInternAtom (this->m_display, "ESETROOT_PMAP_ID", False);
     XChangeProperty (
 	this->m_display, this->m_root, prop_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char*)&this->m_pixmap, 1
     );
-    XChangeProperty (
-	this->m_display, this->m_root, prop_esetroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char*)&this->m_pixmap, 1
-    );
 
     XClearWindow (this->m_display, this->m_root);
     this->updateDesktopWindow ();

+ 3 - 0
src/WallpaperEngine/Render/Drivers/Output/X11Output.h

@@ -1,5 +1,6 @@
 #pragma once
 
+#include <atomic>
 #include <chrono>
 #include <glm/vec4.hpp>
 #include <map>
@@ -24,6 +25,7 @@ public:
     ~X11Output () override;
 
     void reset () override;
+    void requestReset () const;
 
     bool renderVFlip () const override;
     bool renderMultiple () const override;
@@ -68,5 +70,6 @@ private:
     mutable std::unique_ptr<X11DesktopIcons> m_icons;
     mutable bool m_iconsTried = false;
 #endif
+    mutable std::atomic<bool> m_resetPending = false;
 };
 }

+ 318 - 0
src/WallpaperEngine/Render/Fonts/SystemFonts.cpp

@@ -0,0 +1,318 @@
+#include "SystemFonts.h"
+
+#include <algorithm>
+#include <cstdio>
+#include <cstdlib>
+#include <fstream>
+#include <mutex>
+#include <sstream>
+#include <strings.h>
+#include <unordered_map>
+
+namespace WallpaperEngine::Render::Fonts {
+namespace {
+    std::string run (const std::string& command) {
+	FILE* pipe = popen (command.c_str (), "r");
+
+	if (pipe == nullptr) {
+	    return {};
+	}
+
+	std::string output;
+	char buffer[512];
+
+	while (fgets (buffer, sizeof (buffer), pipe) != nullptr) {
+	    output += buffer;
+	}
+
+	pclose (pipe);
+	return output;
+    }
+
+    // both ends of a command line, in single quotes: no quote, no line break (a backslash is fc-match's own escape)
+    bool shellSafe (const std::string& text) { return text.find_first_of ("'\n") == std::string::npos; }
+
+    std::string xmlEscape (const std::string& text) {
+	std::string result;
+
+	for (const char c : text) {
+	    switch (c) {
+		case '&':
+		    result += "&amp;";
+		    break;
+		case '<':
+		    result += "&lt;";
+		    break;
+		case '>':
+		    result += "&gt;";
+		    break;
+		default:
+		    result += c;
+	    }
+	}
+
+	return result;
+    }
+
+    std::string fontconfigFile () {
+	static std::string path;
+	static std::once_flag once;
+
+	std::call_once (once, [] {
+	    const std::filesystem::path directory = userFontDirectory ();
+	    std::error_code error;
+
+	    if (!std::filesystem::is_directory (directory, error) || !shellSafe (directory.string ())) {
+		return;
+	    }
+
+	    std::filesystem::path cache;
+
+	    if (const char* home = std::getenv ("XDG_CACHE_HOME"); home != nullptr && home[0] == '/') {
+		cache = home;
+	    } else if (const char* user = std::getenv ("HOME"); user != nullptr && user[0] == '/') {
+		cache = std::filesystem::path (user) / ".cache";
+	    } else {
+		return;
+	    }
+
+	    cache /= "linux-wallpaperengine";
+	    std::filesystem::create_directories (cache, error);
+
+	    const std::filesystem::path file = cache / "fonts.conf";
+	    // a configuration the environment already points at (Nix, Guix) is the one to extend
+	    std::string base = "/etc/fonts/fonts.conf";
+
+	    if (const char* env = std::getenv ("FONTCONFIG_FILE"); env != nullptr && env[0] == '/') {
+		base = env;
+	    }
+
+	    const std::string content
+		= "<?xml version=\"1.0\"?>\n<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n<fontconfig>\n"
+		  "  <include ignore_missing=\"yes\">"
+		+ xmlEscape (base) + "</include>\n  <dir>" + xmlEscape (directory.string ())
+		+ "</dir>\n</fontconfig>\n";
+
+	    std::string existing;
+
+	    if (std::ifstream in (file); in) {
+		std::stringstream buffer;
+		buffer << in.rdbuf ();
+		existing = buffer.str ();
+	    }
+
+	    if (existing != content) {
+		std::ofstream out (file, std::ios::trunc);
+		out << content;
+
+		if (!out) {
+		    return;
+		}
+	    }
+
+	    if (shellSafe (file.string ())) {
+		path = file.string ();
+	    }
+	});
+
+	return path;
+    }
+
+    bool sameFamily (const std::string& names, const std::string& family) {
+	std::stringstream list (names);
+	std::string name;
+
+	while (std::getline (list, name, ',')) {
+	    if (strcasecmp (name.c_str (), family.c_str ()) == 0) {
+		return true;
+	    }
+	}
+
+	return false;
+    }
+}
+
+std::filesystem::path userFontDirectory () {
+    if (const char* forced = std::getenv ("LWE_FONT_DIR"); forced != nullptr && forced[0] == '/') {
+	return forced;
+    }
+
+    if (const char* data = std::getenv ("XDG_DATA_HOME"); data != nullptr && data[0] == '/') {
+	return std::filesystem::path (data) / "linux-wallpaperengine" / "fonts";
+    }
+
+    if (const char* home = std::getenv ("HOME"); home != nullptr && home[0] == '/') {
+	return std::filesystem::path (home) / ".local/share/linux-wallpaperengine/fonts";
+    }
+
+    return {};
+}
+
+std::string fcMatch (const std::string& pattern, const std::string& format) {
+    if (!shellSafe (pattern) || !shellSafe (format)) {
+	return {};
+    }
+
+    const std::string config = fontconfigFile ();
+    const std::string prefix = config.empty () ? std::string () : "FONTCONFIG_FILE='" + config + "' ";
+
+    return run (prefix + "fc-match -f '" + format + "' '" + pattern + "' 2>/dev/null");
+}
+
+std::vector<std::string> systemFontFamilies (const std::string& font) {
+    static const std::vector<std::pair<std::string, std::vector<std::string>>> families = {
+	{ "systemfont_arial", { "Arial", "Liberation Sans", "Arimo" } },
+	{ "systemfont_calibri", { "Calibri", "Carlito" } },
+	{ "systemfont_cambria", { "Cambria", "Caladea" } },
+	{ "systemfont_comicsans", { "Comic Sans MS", "Comic Neue", "Comic Relief" } },
+	{ "systemfont_consolas", { "Consolas", "Inconsolata", "DejaVu Sans Mono" } },
+	{ "systemfont_sansserif", { "sans-serif" } },
+	{ "systemfont_segoe", { "Segoe UI", "Noto Sans", "Open Sans" } },
+	{ "systemfont_verdana", { "Verdana", "DejaVu Sans" } },
+    };
+
+    for (const auto& [name, list] : families) {
+	if (font == name) {
+	    return list;
+	}
+    }
+
+    return {};
+}
+
+std::string installedFamilyFile (const std::vector<std::string>& families) {
+    static std::unordered_map<std::string, std::string> cache;
+
+    for (const auto& family : families) {
+	auto it = cache.find (family);
+
+	if (it == cache.end ()) {
+	    const std::string output = fcMatch (family, "%{family}\\n%{file}");
+	    std::string path;
+
+	    if (const size_t newline = output.find ('\n');
+		newline != std::string::npos && sameFamily (output.substr (0, newline), family)) {
+		path = output.substr (newline + 1);
+	    }
+
+	    std::error_code error;
+
+	    if (!path.empty () && !std::filesystem::exists (path, error)) {
+		path.clear ();
+	    }
+
+	    it = cache.emplace (family, path).first;
+	}
+
+	if (!it->second.empty ()) {
+	    return it->second;
+	}
+    }
+
+    return {};
+}
+
+FontReport systemFontReport (const std::string& font) {
+    const auto families = systemFontFamilies (font);
+
+    if (families.empty ()) {
+	return {};
+    }
+
+    FontReport report;
+    report.family = families.front ();
+
+    if (families.front () == "sans-serif") {
+	report.using_ = families.front ();
+	return report;
+    }
+
+    static const std::vector<std::string> clones = { "Liberation Sans", "Arimo", "Carlito", "Caladea" };
+
+    for (size_t index = 0; index < families.size (); index++) {
+	if (installedFamilyFile ({ families[index] }).empty ()) {
+	    continue;
+	}
+
+	report.using_ = families[index];
+
+	if (index == 0) {
+	    report.status = FontStatus::Exact;
+	} else {
+	    report.status = std::find (clones.begin (), clones.end (), families[index]) != clones.end ()
+		? FontStatus::Compatible
+		: FontStatus::Substitute;
+	}
+
+	return report;
+    }
+
+    report.status = FontStatus::Substitute;
+    report.using_ = fcMatch (families.front (), "%{family[0]}");
+
+    if (report.using_.empty ()) {
+	report.using_ = "DejaVu Sans";
+    }
+
+    return report;
+}
+
+FontReport emojiReport () {
+    FontReport report;
+    report.family = "Segoe UI Emoji";
+
+    if (!installedFamilyFile ({ report.family }).empty ()) {
+	report.using_ = report.family;
+	return report;
+    }
+
+    report.status = FontStatus::Substitute;
+    report.using_ = "Twemoji";
+    return report;
+}
+
+bool containsEmoji (const std::string& utf8) {
+    // the characters Unicode draws as pictures by default (Emoji_Presentation) plus the markers that ask for one; the
+    // text symbols of the same blocks (stars, hearts, arrows) are plain glyphs in ordinary fonts and don't count
+    static constexpr std::pair<char32_t, char32_t> kRanges[] = {
+	{ 0x1F000, 0x1FAFF }, { 0x231A, 0x231B }, { 0x23E9, 0x23F3 }, { 0x23F8, 0x23FA }, { 0x25FD, 0x25FE },
+	{ 0x2614, 0x2615 },   { 0x2648, 0x2653 }, { 0x267F, 0x267F }, { 0x2693, 0x2693 }, { 0x26A1, 0x26A1 },
+	{ 0x26AA, 0x26AB },   { 0x26BD, 0x26BE }, { 0x26C4, 0x26C5 }, { 0x26CE, 0x26CE }, { 0x26D4, 0x26D4 },
+	{ 0x26EA, 0x26EA },   { 0x26F2, 0x26F3 }, { 0x26F5, 0x26F5 }, { 0x26FA, 0x26FA }, { 0x26FD, 0x26FD },
+	{ 0x2705, 0x2705 },   { 0x270A, 0x270B }, { 0x2728, 0x2728 }, { 0x274C, 0x274C }, { 0x274E, 0x274E },
+	{ 0x2753, 0x2755 },   { 0x2757, 0x2757 }, { 0x2795, 0x2797 }, { 0x27B0, 0x27B0 }, { 0x27BF, 0x27BF },
+	{ 0x2B1B, 0x2B1C },   { 0x2B50, 0x2B50 }, { 0x2B55, 0x2B55 }, { 0xFE0F, 0xFE0F }, { 0x20E3, 0x20E3 },
+    };
+
+    for (size_t index = 0; index < utf8.size ();) {
+	const auto lead = static_cast<unsigned char> (utf8[index]);
+	char32_t codepoint = lead;
+	size_t length = 1;
+
+	if (lead >= 0xF0) {
+	    length = 4;
+	    codepoint = lead & 0x07;
+	} else if (lead >= 0xE0) {
+	    length = 3;
+	    codepoint = lead & 0x0F;
+	} else if (lead >= 0xC0) {
+	    length = 2;
+	    codepoint = lead & 0x1F;
+	}
+
+	for (size_t part = 1; part < length && index + part < utf8.size (); part++) {
+	    codepoint = (codepoint << 6) | (static_cast<unsigned char> (utf8[index + part]) & 0x3F);
+	}
+
+	index += length;
+
+	for (const auto& [low, high] : kRanges) {
+	    if (codepoint >= low && codepoint <= high) {
+		return true;
+	    }
+	}
+    }
+
+    return false;
+}
+}

+ 33 - 0
src/WallpaperEngine/Render/Fonts/SystemFonts.h

@@ -0,0 +1,33 @@
+#pragma once
+
+#include <filesystem>
+#include <string>
+#include <vector>
+
+namespace WallpaperEngine::Render::Fonts {
+std::filesystem::path userFontDirectory ();
+
+std::string fcMatch (const std::string& pattern, const std::string& format);
+
+std::vector<std::string> systemFontFamilies (const std::string& font);
+
+std::string installedFamilyFile (const std::vector<std::string>& families);
+
+enum class FontStatus {
+    Exact,
+    Compatible,
+    Substitute,
+};
+
+struct FontReport {
+    std::string family;
+    FontStatus status = FontStatus::Exact;
+    std::string using_;
+};
+
+FontReport systemFontReport (const std::string& font);
+
+FontReport emojiReport ();
+
+bool containsEmoji (const std::string& utf8);
+}

+ 2 - 1
src/WallpaperEngine/Render/FrameMaterial.cpp

@@ -135,7 +135,8 @@ FrameMaterial::FrameMaterial (
     if (this->a_TexCoord != -1) {
 	glEnableVertexAttribArray (this->a_TexCoord);
 	glVertexAttribPointer (
-	    this->a_TexCoord, 2, GL_FLOAT, GL_FALSE, 5 * sizeof (float), reinterpret_cast<void*> (3 * sizeof (float))
+	    this->a_TexCoord, 2, GL_FLOAT, GL_FALSE, 5 * sizeof (float),
+	    std::bit_cast<void*> (static_cast<uintptr_t> (3 * sizeof (float)))
 	);
     }
 

+ 1 - 0
src/WallpaperEngine/Render/Helpers/ContextAware.h

@@ -8,6 +8,7 @@ namespace Helpers {
     public:
 	virtual ~ContextAware () = default;
 	ContextAware (const ContextAware& from);
+	ContextAware& operator= (const ContextAware& from) = delete;
 	explicit ContextAware (const ContextAware* from);
 	explicit ContextAware (RenderContext& context);
 

+ 7 - 2
src/WallpaperEngine/Render/ImageDecoder.cpp

@@ -143,8 +143,13 @@ stbi_uc* decodeImageRGBA (const void* data, size_t size, int& width, int& height
 
     const int srcWidth = width;
     const int srcHeight = height;
-    const int dstWidth = swapsAxes (orientation) ? srcHeight : srcWidth;
-    const int dstHeight = swapsAxes (orientation) ? srcWidth : srcHeight;
+    int dstWidth = srcWidth;
+    int dstHeight = srcHeight;
+
+    if (swapsAxes (orientation)) {
+	std::swap (dstWidth, dstHeight);
+    }
+
     auto* rotated = static_cast<stbi_uc*> (malloc (static_cast<size_t> (dstWidth) * dstHeight * 4));
 
     if (rotated == nullptr) {

+ 231 - 0
src/WallpaperEngine/Render/LedFrameGrabber.cpp

@@ -0,0 +1,231 @@
+#include "LedFrameGrabber.h"
+
+#include <cstring>
+
+#include "WallpaperEngine/Led/LedLayout.h"
+#include "WallpaperEngine/Logging/Log.h"
+
+namespace WallpaperEngine::Render {
+namespace {
+    const char* kVertex = R"(#version 330
+out vec2 v_TexCoord;
+
+void main () {
+    vec2 corner = vec2 ((gl_VertexID << 1) & 2, gl_VertexID & 2);
+    v_TexCoord = corner;
+    gl_Position = vec4 (corner * 2.0 - 1.0, 0.0, 1.0);
+}
+)";
+
+    const char* kFragment = R"(#version 330
+uniform sampler2D g_Texture0;
+uniform vec2 u_Texel;
+in vec2 v_TexCoord;
+out vec4 fragColor;
+
+void main () {
+    vec2 step = u_Texel * 2.0;
+    vec4 albedo = texture (g_Texture0, v_TexCoord - step) + texture (g_Texture0, v_TexCoord + step)
+	+ texture (g_Texture0, v_TexCoord + vec2 (-step.x, step.y)) + texture (g_Texture0, v_TexCoord + vec2 (step.x, -step.y));
+    fragColor = vec4 (albedo.rgb * 0.25, 1.0);
+}
+)";
+
+    GLuint compile (const GLenum type, const char* source) {
+	const GLuint shader = glCreateShader (type);
+	glShaderSource (shader, 1, &source, nullptr);
+	glCompileShader (shader);
+
+	GLint compiled = GL_FALSE;
+	glGetShaderiv (shader, GL_COMPILE_STATUS, &compiled);
+
+	if (compiled == GL_FALSE) {
+	    char log[1024] = {};
+	    glGetShaderInfoLog (shader, sizeof (log) - 1, nullptr, log);
+	    sLog.error ("LED frame shader failed to compile: ", log);
+	}
+
+	return shader;
+    }
+
+    struct SavedState {
+	GLint drawFramebuffer = 0, readFramebuffer = 0, program = 0, vao = 0, activeTexture = 0, texture = 0,
+	      sampler = 0;
+	GLint packBuffer = 0;
+	GLint viewport[4] = {};
+	GLboolean colorMask[4] = {};
+	GLboolean blend = GL_FALSE, depth = GL_FALSE, cull = GL_FALSE, scissor = GL_FALSE, stencil = GL_FALSE;
+	GLboolean framebufferSrgb = GL_FALSE;
+
+	SavedState () {
+	    glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &drawFramebuffer);
+	    glGetIntegerv (GL_READ_FRAMEBUFFER_BINDING, &readFramebuffer);
+	    glGetIntegerv (GL_CURRENT_PROGRAM, &program);
+	    glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &vao);
+	    glGetIntegerv (GL_ACTIVE_TEXTURE, &activeTexture);
+	    glActiveTexture (GL_TEXTURE0);
+	    glGetIntegerv (GL_TEXTURE_BINDING_2D, &texture);
+	    glGetIntegerv (GL_SAMPLER_BINDING, &sampler);
+	    glGetIntegerv (GL_PIXEL_PACK_BUFFER_BINDING, &packBuffer);
+	    glGetIntegerv (GL_VIEWPORT, viewport);
+	    glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
+	    blend = glIsEnabled (GL_BLEND);
+	    depth = glIsEnabled (GL_DEPTH_TEST);
+	    cull = glIsEnabled (GL_CULL_FACE);
+	    scissor = glIsEnabled (GL_SCISSOR_TEST);
+	    stencil = glIsEnabled (GL_STENCIL_TEST);
+	    framebufferSrgb = glIsEnabled (GL_FRAMEBUFFER_SRGB);
+	}
+
+	~SavedState () {
+	    const auto set = [] (const GLenum capability, const GLboolean on) {
+		if (on) {
+		    glEnable (capability);
+		} else {
+		    glDisable (capability);
+		}
+	    };
+
+	    glBindBuffer (GL_PIXEL_PACK_BUFFER, packBuffer);
+	    glBindFramebuffer (GL_DRAW_FRAMEBUFFER, drawFramebuffer);
+	    glBindFramebuffer (GL_READ_FRAMEBUFFER, readFramebuffer);
+	    glUseProgram (program);
+	    glBindVertexArray (vao);
+	    glActiveTexture (GL_TEXTURE0);
+	    glBindTexture (GL_TEXTURE_2D, texture);
+	    glBindSampler (0, sampler);
+	    glActiveTexture (activeTexture);
+	    glViewport (viewport[0], viewport[1], viewport[2], viewport[3]);
+	    glColorMask (colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
+	    set (GL_BLEND, blend);
+	    set (GL_DEPTH_TEST, depth);
+	    set (GL_CULL_FACE, cull);
+	    set (GL_SCISSOR_TEST, scissor);
+	    set (GL_STENCIL_TEST, stencil);
+	    set (GL_FRAMEBUFFER_SRGB, framebufferSrgb);
+	}
+    };
+}
+
+LedFrameGrabber::~LedFrameGrabber () {
+    if (!this->m_created) {
+	return;
+    }
+
+    glDeleteProgram (this->m_program);
+    glDeleteTextures (1, &this->m_target);
+    glDeleteFramebuffers (1, &this->m_framebuffer);
+    glDeleteSamplers (1, &this->m_sampler);
+    glDeleteVertexArrays (1, &this->m_vao);
+    glDeleteBuffers (2, this->m_buffers);
+}
+
+void LedFrameGrabber::create () {
+    this->m_created = true;
+
+    const GLuint vertex = compile (GL_VERTEX_SHADER, kVertex);
+    const GLuint fragment = compile (GL_FRAGMENT_SHADER, kFragment);
+
+    this->m_program = glCreateProgram ();
+    glAttachShader (this->m_program, vertex);
+    glAttachShader (this->m_program, fragment);
+    glLinkProgram (this->m_program);
+    glDeleteShader (vertex);
+    glDeleteShader (fragment);
+    glUseProgram (this->m_program);
+    glUniform1i (glGetUniformLocation (this->m_program, "g_Texture0"), 0);
+    this->m_texelLocation = glGetUniformLocation (this->m_program, "u_Texel");
+
+    glGenTextures (1, &this->m_target);
+    glBindTexture (GL_TEXTURE_2D, this->m_target);
+    glTexImage2D (
+	GL_TEXTURE_2D, 0, GL_RGBA8, Led::kFrameWidth, Led::kFrameHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr
+    );
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
+
+    glGenFramebuffers (1, &this->m_framebuffer);
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_framebuffer);
+    glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->m_target, 0);
+
+    glGenSamplers (1, &this->m_sampler);
+    glSamplerParameteri (this->m_sampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glSamplerParameteri (this->m_sampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glSamplerParameteri (this->m_sampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+    glSamplerParameteri (this->m_sampler, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+
+    glGenVertexArrays (1, &this->m_vao);
+    glGenBuffers (2, this->m_buffers);
+
+    for (const GLuint buffer : this->m_buffers) {
+	glBindBuffer (GL_PIXEL_PACK_BUFFER, buffer);
+	glBufferData (GL_PIXEL_PACK_BUFFER, Led::kFrameWidth * Led::kFrameHeight * 4, nullptr, GL_STREAM_READ);
+    }
+}
+
+bool LedFrameGrabber::grab (const GLuint texture, const int width, const int height, std::vector<uint8_t>& out) {
+    if (texture == 0 || width <= 0 || height <= 0) {
+	return false;
+    }
+
+    const SavedState saved;
+
+    if (!this->m_created) {
+	this->create ();
+    }
+
+    glDisable (GL_BLEND);
+    glDisable (GL_DEPTH_TEST);
+    glDisable (GL_CULL_FACE);
+    glDisable (GL_SCISSOR_TEST);
+    glDisable (GL_STENCIL_TEST);
+    glDisable (GL_FRAMEBUFFER_SRGB);
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_framebuffer);
+    glViewport (0, 0, Led::kFrameWidth, Led::kFrameHeight);
+    glUseProgram (this->m_program);
+    glUniform2f (this->m_texelLocation, 1.0f / static_cast<float> (width), 1.0f / static_cast<float> (height));
+    glActiveTexture (GL_TEXTURE0);
+    glBindTexture (GL_TEXTURE_2D, texture);
+    glBindSampler (0, this->m_sampler);
+    glBindVertexArray (this->m_vao);
+    glDrawArrays (GL_TRIANGLES, 0, 3);
+
+    const int current = this->m_slot;
+    const int previous = 1 - current;
+
+    glReadBuffer (GL_COLOR_ATTACHMENT0);
+    glBindBuffer (GL_PIXEL_PACK_BUFFER, this->m_buffers[current]);
+    glReadPixels (0, 0, Led::kFrameWidth, Led::kFrameHeight, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
+
+    bool produced = false;
+
+    if (this->m_pending) {
+	glBindBuffer (GL_PIXEL_PACK_BUFFER, this->m_buffers[previous]);
+
+	if (const auto* rgba = static_cast<const uint8_t*> (glMapBuffer (GL_PIXEL_PACK_BUFFER, GL_READ_ONLY));
+	    rgba != nullptr) {
+	    out.resize (Led::kFrameBytes);
+
+	    for (int row = 0; row < Led::kFrameHeight; row++) {
+		const uint8_t* from = rgba + static_cast<size_t> (row) * Led::kFrameWidth * 4;
+		uint8_t* to = out.data () + static_cast<size_t> (row) * Led::kFrameWidth * 3;
+
+		for (int column = 0; column < Led::kFrameWidth; column++) {
+		    to[column * 3] = from[column * 4];
+		    to[column * 3 + 1] = from[column * 4 + 1];
+		    to[column * 3 + 2] = from[column * 4 + 2];
+		}
+	    }
+
+	    glUnmapBuffer (GL_PIXEL_PACK_BUFFER);
+	    produced = true;
+	}
+    }
+
+    this->m_pending = true;
+    this->m_slot = previous;
+    return produced;
+}
+}

+ 35 - 0
src/WallpaperEngine/Render/LedFrameGrabber.h

@@ -0,0 +1,35 @@
+#pragma once
+
+#include <GL/glew.h>
+#include <cstdint>
+#include <vector>
+
+namespace WallpaperEngine::Render {
+/**
+ * What wallpaper64.exe 2.8.42 does for the LED plugin (sub_140110630): a single draw of
+ * materials/util/downsample_quarter from the source into an 80 x 10 target, read back one frame later. The shader takes
+ * four taps around each output pixel's center, two source texels away on the diagonals
+ */
+class LedFrameGrabber {
+public:
+    ~LedFrameGrabber ();
+
+    /** Starts the draw and read back of this source; true when the previous one's rgb (rows from the top, the scene's
+     * buffers run top down) landed in out */
+    bool grab (GLuint texture, int width, int height, std::vector<uint8_t>& out);
+
+private:
+    void create ();
+
+    bool m_created = false;
+    GLuint m_program = 0;
+    GLuint m_target = 0;
+    GLuint m_framebuffer = 0;
+    GLuint m_sampler = 0;
+    GLuint m_vao = 0;
+    GLuint m_buffers[2] = {};
+    GLint m_texelLocation = -1;
+    int m_slot = 0;
+    bool m_pending = false;
+};
+}

+ 2 - 2
src/WallpaperEngine/Render/MissingTexture.cpp

@@ -31,9 +31,9 @@ MissingTexture::~MissingTexture () { glDeleteTextures (1, &this->m_textureID); }
 
 GLuint MissingTexture::getTextureID (uint32_t imageIndex) const { return this->m_textureID; }
 uint32_t MissingTexture::getTextureWidth (uint32_t imageIndex) const { return SIZE; }
-uint32_t MissingTexture::getTextureHeight (uint32_t imageIndex) const { return SIZE; }
+uint32_t MissingTexture::getTextureHeight (uint32_t imageIndex) const { return this->getTextureWidth (imageIndex); }
 uint32_t MissingTexture::getRealWidth () const { return SIZE; }
-uint32_t MissingTexture::getRealHeight () const { return SIZE; }
+uint32_t MissingTexture::getRealHeight () const { return this->getRealWidth (); }
 TextureFormat MissingTexture::getFormat () const { return TextureFormat_ARGB8888; }
 uint32_t MissingTexture::getFlags () const { return TextureFlags_NoInterpolation; }
 const std::vector<FrameSharedPtr>& MissingTexture::getFrames () const { return this->m_frames; }

+ 3 - 3
src/WallpaperEngine/Render/Objects/CCamera.cpp

@@ -51,10 +51,10 @@ int CCamera::nextTimeline () {
 		this->m_bag.push_back (index);
 	    }
 	}
-    }
 
-    if (this->m_bag.empty ()) {
-	return -1;
+	if (this->m_bag.empty ()) {
+	    return -1;
+	}
     }
 
     const int size = static_cast<int> (this->m_bag.size ());

+ 19 - 12
src/WallpaperEngine/Render/Objects/CImage.cpp

@@ -1,6 +1,7 @@
 #include "CImage.h"
 #include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
+#include "WallpaperEngine/Render/DepthRange.h"
 
 #include "CMesh.h"
 #include "CRenderable.h"
@@ -509,10 +510,10 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
     if (this->getImage ().model->passthrough) {
 	this->m_modelViewProjectionCopy = this->m_modelViewProjectionScreen;
     } else {
-	this->m_modelViewProjectionCopy = glm::ortho<float> (0.0, size.x, 0.0, size.y);
+	this->m_modelViewProjectionCopy = DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y));
     }
     this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
-    this->m_modelMatrix = glm::ortho<float> (0.0, size.x, 0.0, size.y);
+    this->m_modelMatrix = DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y));
     this->m_viewProjectionMatrix = glm::mat4 (1.0);
 
     this->m_texture->incrementUsageCount ();
@@ -539,13 +540,18 @@ void CImage::renderPassthroughChildren (const std::shared_ptr<const CFBO>& buffe
 	    (this->m_pos.z - this->m_pos.x) / 2.0f, (this->m_pos.y - this->m_pos.w) / 2.0f, 1000.0f
 	);
 
-	transform = glm::inverse (glm::scale (glm::translate (this->m_modelViewProjectionScreen, center), halfExtent));
+	transform = DepthRange::toClip (
+	    glm::inverse (glm::scale (glm::translate (this->m_modelViewProjectionScreen, center), halfExtent))
+	);
 
 	// lights skip the model stack (volumetricsfront.vert only has g_ViewProjectionMatrix), so they see the bare
 	// ortho with the scene's y flip: their world position lands in the layer as if the layer sat at the origin
 	const glm::vec2 size = this->getSize ();
-	viewProjection = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
-	    * glm::ortho (-size.x / 2.0f, size.x / 2.0f, -size.y / 2.0f, size.y / 2.0f, -1000.0f, 1000.0f);
+	viewProjection
+	    = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f))
+	    * DepthRange::toClip (
+		  glm::ortho (-size.x / 2.0f, size.x / 2.0f, -size.y / 2.0f, size.y / 2.0f, -1000.0f, 1000.0f)
+	    );
     }
 
     this->getScene ().renderPassthroughChildren (
@@ -2070,7 +2076,7 @@ void CImage::setupPuppetBlendMap (bool offscreen) {
 
     const glm::vec2 albedoSize (texture->getTextureWidth (0), texture->getTextureHeight (0));
     // mesh is in texture pixels, y up
-    this->m_blendMap.projection = glm::ortho (0.0f, albedoSize.x, albedoSize.y, 0.0f, -1.0f, 1.0f);
+    this->m_blendMap.projection = DepthRange::toClip (glm::ortho (0.0f, albedoSize.x, albedoSize.y, 0.0f, -1.0f, 1.0f));
 
     constexpr GLfloat quad[] = { -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
 				 -1.0f, 1.0f,  0.0f, 0.0f, 1.0f, 1.0f, 1.0f,  0.0f, 1.0f, 1.0f };
@@ -2437,7 +2443,7 @@ void CImage::setup () {
     // passthrough without effects has nothing to draw unless another layer reads its _rt_imageLayerComposite or it
     // has children to draw into its buffer
     if (this->m_image.model->passthrough && this->m_image.effects.empty () && !this->m_readByOtherLayer
-	&& !this->m_hasPassthroughChildren) {
+	&& !this->m_hasPassthroughChildren && !this->m_image.renderable.ledSource->value->getBool ()) {
 	return;
     }
 
@@ -3112,7 +3118,7 @@ void CImage::render () {
     }
 
     if (this->m_image.model->passthrough && !this->m_hasActiveEffectPass && !this->m_readByOtherLayer
-	&& !this->m_hasPassthroughChildren) {
+	&& !this->m_hasPassthroughChildren && !this->m_image.renderable.ledSource->value->getBool ()) {
 	return;
     }
 
@@ -3316,14 +3322,14 @@ void CImage::uploadGeometryBuffers (const glm::vec2& size) {
 
     this->m_modelViewProjectionCopy = this->getImage ().model->passthrough
 	? this->m_modelViewProjectionScreen
-	: glm::ortho<float> (0.0, size.x, 0.0, size.y);
+	: DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y));
     this->m_modelViewProjectionCopyInverse = glm::inverse (this->m_modelViewProjectionCopy);
-    this->m_modelMatrix = glm::ortho<float> (0.0, size.x, 0.0, size.y);
+    this->m_modelMatrix = DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y));
     // WE's buffer ortho has near -1000 / far 1000 (sub_14009A630), so the mesh keeps its z
     const glm::mat4 placement = glm::translate (glm::mat4 (1.0f), glm::vec3 (size / 2.0f, 0.0f));
     this->m_puppetPrelight.projection = this->getImage ().model->passthrough
 	? this->m_modelViewProjectionCopy * glm::scale (placement, glm::vec3 (1.0f, -1.0f, 0.0f))
-	: glm::ortho<float> (0.0, size.x, 0.0, size.y, -1000.0f, 1000.0f)
+	: DepthRange::toClip (glm::ortho<float> (0.0, size.x, 0.0, size.y, -1000.0f, 1000.0f))
 	    * glm::scale (placement, glm::vec3 (1.0f, -1.0f, 1.0f));
 }
 
@@ -3604,7 +3610,8 @@ const Image& CImage::getImage () const { return this->m_image; }
 void CImage::markAsDependency () { this->m_isDependency = true; }
 
 bool CImage::copiesForReaders () const {
-    return this->m_readByOtherLayer && (this->getImage ().visible->value->getBool () || this->m_emitterImageSource);
+    return (this->m_readByOtherLayer || this->m_image.renderable.ledSource->value->getBool ())
+	&& (this->getImage ().visible->value->getBool () || this->m_emitterImageSource);
 }
 
 glm::vec2 CImage::getSize () const {

+ 6 - 5
src/WallpaperEngine/Render/Objects/CMesh.cpp

@@ -1,4 +1,5 @@
 #include "CMesh.h"
+#include "WallpaperEngine/Render/DepthRange.h"
 
 #include <bit>
 #include <map>
@@ -169,9 +170,9 @@ public:
 
     [[nodiscard]] GLuint getTextureID (uint32_t) const override { return this->m_texture; }
     [[nodiscard]] uint32_t getTextureWidth (uint32_t) const override { return this->m_side; }
-    [[nodiscard]] uint32_t getTextureHeight (uint32_t) const override { return this->m_side; }
+    [[nodiscard]] uint32_t getTextureHeight (uint32_t index) const override { return this->getTextureWidth (index); }
     [[nodiscard]] uint32_t getRealWidth () const override { return this->m_side; }
-    [[nodiscard]] uint32_t getRealHeight () const override { return this->m_side; }
+    [[nodiscard]] uint32_t getRealHeight () const override { return this->getRealWidth (); }
     [[nodiscard]] TextureFormat getFormat () const override { return TextureFormat_UNKNOWN; }
     [[nodiscard]] uint32_t getFlags () const override { return TextureFlags_ClampUVs; }
     [[nodiscard]] const std::vector<FrameSharedPtr>& getFrames () const override { return this->m_frames; }
@@ -567,7 +568,7 @@ public:
     [[nodiscard]] const float& getAlpha () const override { return this->m_one; }
     [[nodiscard]] const glm::vec3& getColor () const override { return this->m_white; }
     [[nodiscard]] const glm::vec4& getColor4 () const override { return this->m_white4; }
-    [[nodiscard]] const glm::vec3& getCompositeColor () const override { return this->m_white; }
+    [[nodiscard]] const glm::vec3& getCompositeColor () const override { return this->getColor (); }
 
 private:
     void uploadBones () {
@@ -1078,8 +1079,8 @@ std::optional<glm::vec3> CMesh::boxEntry (const glm::vec2& ndc) const {
 	scene.getWorldViewProjection (this->m_mesh.perspective->value->getBool ())
 	* scene.objectWorldMatrix (this->m_mesh)
     );
-    const glm::vec4 nearPoint = toModel * glm::vec4 (ndc, -1.0f, 1.0f);
-    const glm::vec4 farPoint = toModel * glm::vec4 (ndc, 1.0f, 1.0f);
+    const glm::vec4 nearPoint = toModel * glm::vec4 (ndc, DepthRange::nearClip (), 1.0f);
+    const glm::vec4 farPoint = toModel * glm::vec4 (ndc, DepthRange::farClip (), 1.0f);
     const glm::vec3 origin = glm::vec3 (nearPoint) / nearPoint.w;
     const glm::vec3 direction = glm::vec3 (farPoint) / farPoint.w - origin;
     const glm::vec3 extent = this->m_boundsMax - this->m_boundsMin;

+ 6 - 5
src/WallpaperEngine/Render/Objects/CParticle.h

@@ -6,6 +6,7 @@
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include <array>
 #include <deque>
 #include <functional>
@@ -70,7 +71,7 @@ struct ParticleInstance {
     float getLifetimePos () const { return lifetime > 0.0f ? (age / lifetime) : 1.0f; }
 
     // sub_140236CD0 kills a particle once lifetime < age, so it is still drawn on the frame it reaches its lifetime
-    bool isAlive () const { return alive && lifetime != 0.0f && !(lifetime < age); }
+    bool isAlive () const { return alive && WallpaperEngine::Data::Utils::isNonZero (lifetime) && !(lifetime < age); }
 };
 
 struct ControlPointData {
@@ -235,14 +236,14 @@ protected:
 
     /** A layerimage pixel: its colour and its place in layer units around the layer's center, y down */
     struct ImagePixel {
-	uint8_t r, g, b;
-	int16_t x, y;
+	uint8_t r = 0, g = 0, b = 0;
+	int16_t x = 0, y = 0;
 	/** puppet layers, 0xFF none */
 	uint8_t bone = 0xFF;
     };
     /** sub_1401D3AE0 */
     struct ImageEmitter {
-	int index;
+	int index = 0;
 	std::vector<ImagePixel> pixels;
 	/** first call only sets layer flags 0x1010 */
 	bool flagged { false };
@@ -435,7 +436,7 @@ private:
 
     /** Where a mapsequence initializer is in its sequence, WE keeps it in the initializer's record (+4, +8) */
     struct SequenceCounter {
-	float step;
+	float step = 0.0f;
 	float sequence { 0.0f };
 	/** Starts over with every new emitter period (mapsequencebetweencontrolpoints flag 0x20) */
 	bool periodReset { false };

+ 5 - 11
src/WallpaperEngine/Render/Objects/CSound.cpp

@@ -8,6 +8,7 @@
 #include <glm/gtc/constants.hpp>
 #include <glm/gtc/matrix_access.hpp>
 
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include <algorithm>
 #include <cfloat>
 #include <cmath>
@@ -237,7 +238,7 @@ void CSound::play () {
     if (!this->m_voices.empty ()) {
 	switch (this->m_sound.playbackmode) {
 	    case PlaybackMode_Random:
-		if (this->m_timer != 0.0f) {
+		if (WallpaperEngine::Data::Utils::isNonZero (this->m_timer)) {
 		    break;
 		}
 
@@ -286,15 +287,7 @@ void CSound::play () {
 
 void CSound::stop () {
     // sub_1401F6E60
-    this->m_paused = false;
-    this->m_stopped = true;
-    this->m_timer = 0.0f;
-
-    for (auto& voice : this->m_voices) {
-	if (voice.state != VoiceState::Stopped) {
-	    this->stopVoice (voice);
-	}
-    }
+    this->stopAllVoices ();
 }
 
 void CSound::pause () {
@@ -382,7 +375,8 @@ void CSound::update (float dt) {
 	this->m_startSilent = startSilent;
     }
 
-    if (volume != this->m_lastVolume || master != this->m_lastMaster) {
+    if (!WallpaperEngine::Data::Utils::sameFloat (volume, this->m_lastVolume)
+	|| !WallpaperEngine::Data::Utils::sameFloat (master, this->m_lastMaster)) {
 	this->m_lastVolume = volume;
 	this->m_lastMaster = master;
 	this->volumeChanged ();

+ 61 - 88
src/WallpaperEngine/Render/Objects/CText.cpp

@@ -1,10 +1,13 @@
 #include "CText.h"
+#include "WallpaperEngine/Render/DepthRange.h"
+#include "WallpaperEngine/Render/Fonts/SystemFonts.h"
 
 #include <algorithm>
 #include <array>
 #include <cstdio>
 #include <filesystem>
 #include <map>
+#include <set>
 #include <sstream>
 #include <strings.h>
 #include <unordered_map>
@@ -26,6 +29,7 @@
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 #include "WallpaperEngine/Scripting/ScriptEngine.h"
 
+using namespace WallpaperEngine::Render;
 using namespace WallpaperEngine::Render::Objects;
 using namespace WallpaperEngine::Render::Objects::Effects;
 using WallpaperEngine::Data::Parsers::MaterialParser;
@@ -38,100 +42,32 @@ const std::vector<std::string> kFontCandidates = {
     "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
 };
 
-std::string fontconfigMatch (const std::string& font) {
-    static const std::vector<std::pair<std::string, std::string>> families = {
-	{ "systemfont_arial", "Arial,Liberation Sans,Arimo" },
-	{ "systemfont_calibri", "Calibri,Carlito" },
-	{ "systemfont_cambria", "Cambria,Caladea" },
-	{ "systemfont_comicsans", "Comic Sans MS,Comic Neue,Comic Relief" },
-	{ "systemfont_consolas", "Consolas,Inconsolata,DejaVu Sans Mono" },
-	{ "systemfont_sansserif", "sans-serif" },
-	{ "systemfont_segoe", "Segoe UI,Noto Sans,Open Sans" },
-	{ "systemfont_verdana", "Verdana,DejaVu Sans" },
-    };
+struct FontMatch {
+    std::string path;
+    std::string families;
+};
 
-    std::string family = "sans-serif";
+FontMatch fontconfigMatch (const std::string& font) {
+    const auto list = Fonts::systemFontFamilies (font);
+    std::string family;
 
-    for (const auto& [name, list] : families) {
-	if (font == name) {
-	    family = list;
-	    break;
-	}
+    for (const auto& name : list) {
+	family += (family.empty () ? "" : ",") + name;
     }
 
-    const std::string command = "fc-match -f '%{file}' '" + family + "' 2>/dev/null";
-    FILE* pipe = popen (command.c_str (), "r");
+    const std::string output = Fonts::fcMatch (family.empty () ? "sans-serif" : family, "%{family}\\n%{file}");
+    const size_t newline = output.find ('\n');
 
-    if (pipe == nullptr) {
+    if (newline == std::string::npos) {
 	return {};
     }
 
-    std::string path;
-    char buffer[512];
-
-    while (fgets (buffer, sizeof (buffer), pipe) != nullptr) {
-	path += buffer;
-    }
+    FontMatch match { output.substr (newline + 1), output.substr (0, newline) };
 
-    pclose (pipe);
-
-    return !path.empty () && std::filesystem::exists (path) ? path : std::string ();
+    return !match.path.empty () && std::filesystem::exists (match.path) ? match : FontMatch {};
 }
 
-std::string installedFamily (const std::vector<std::string>& families) {
-    static std::unordered_map<std::string, std::string> cache;
-
-    for (const auto& family : families) {
-	if (const auto it = cache.find (family); it != cache.end ()) {
-	    if (!it->second.empty ()) {
-		return it->second;
-	    }
-
-	    continue;
-	}
-
-	const std::string command = "fc-match -f '%{family}\\n%{file}' '" + family + "' 2>/dev/null";
-	FILE* pipe = popen (command.c_str (), "r");
-	std::string output;
-
-	if (pipe != nullptr) {
-	    char buffer[512];
-
-	    while (fgets (buffer, sizeof (buffer), pipe) != nullptr) {
-		output += buffer;
-	    }
-
-	    pclose (pipe);
-	}
-
-	std::string path;
-	const size_t newline = output.find ('\n');
-
-	if (newline != std::string::npos) {
-	    std::stringstream names (output.substr (0, newline));
-	    std::string name;
-
-	    while (std::getline (names, name, ',')) {
-		if (strcasecmp (name.c_str (), family.c_str ()) == 0) {
-		    path = output.substr (newline + 1);
-		    break;
-		}
-	    }
-	}
-
-	if (!path.empty () && !std::filesystem::exists (path)) {
-	    path.clear ();
-	}
-
-	cache.emplace (family, path);
-
-	if (!path.empty ()) {
-	    return path;
-	}
-    }
-
-    return {};
-}
+std::string installedFamily (const std::vector<std::string>& families) { return Fonts::installedFamilyFile (families); }
 
 // WE's fallback fonts (off_140484C40, per character by sub_1401AD670): Windows fonts and the assets' Twemoji;
 // Windows fonts count when installed under their family (arial.ttf also via metric clones), CJK through the usual Linux
@@ -244,9 +180,9 @@ public:
 
     [[nodiscard]] GLuint getTextureID (uint32_t) const override { return m_textureID; }
     [[nodiscard]] uint32_t getTextureWidth (uint32_t) const override { return m_size; }
-    [[nodiscard]] uint32_t getTextureHeight (uint32_t) const override { return m_size; }
+    [[nodiscard]] uint32_t getTextureHeight (uint32_t index) const override { return getTextureWidth (index); }
     [[nodiscard]] uint32_t getRealWidth () const override { return m_size; }
-    [[nodiscard]] uint32_t getRealHeight () const override { return m_size; }
+    [[nodiscard]] uint32_t getRealHeight () const override { return getRealWidth (); }
     [[nodiscard]] TextureFormat getFormat () const override {
 	return m_channels == 4 ? TextureFormat_ARGB8888 : TextureFormat_R8;
     }
@@ -461,6 +397,37 @@ void CText::setup () {
     m_initialized = true;
 }
 
+namespace {
+void warnAboutSubstitute (const std::string& font, const std::string& matchedFamilies) {
+    static std::set<std::string> said;
+    static const std::set<std::string> clones = { "Liberation Sans", "Arimo", "Carlito", "Caladea" };
+    const auto wanted = Fonts::systemFontFamilies (font);
+
+    if (wanted.empty () || wanted.front () == "sans-serif" || !said.insert (font).second) {
+	return;
+    }
+
+    std::stringstream names (matchedFamilies);
+    std::string name;
+    std::string first;
+
+    while (std::getline (names, name, ',')) {
+	if (first.empty ()) {
+	    first = name;
+	}
+
+	if (strcasecmp (name.c_str (), wanted.front ().c_str ()) == 0 || clones.contains (name)) {
+	    return;
+	}
+    }
+
+    sLog.out (
+	"Warning: the font \"", wanted.front (), "\" is not installed, texts use \"", first,
+	"\" instead. Add the font in ", Fonts::userFontDirectory ().string (), " (we_manager: Add font)"
+    );
+}
+}
+
 bool CText::loadFont () {
     // wallpapers packed in .pkg don't expose physical paths, so the font is read into memory
     if (!m_loadedFont.empty () && m_loadedFont.rfind ("systemfont_", 0) != 0) {
@@ -475,7 +442,13 @@ bool CText::loadFont () {
 
     // a font WE can't load falls back to arial.ttf
     const bool systemFont = m_loadedFont.rfind ("systemfont_", 0) == 0;
-    std::string fontPath = fontconfigMatch (systemFont ? m_loadedFont : std::string ("systemfont_arial"));
+
+    const FontMatch match = fontconfigMatch (systemFont ? m_loadedFont : std::string ("systemfont_arial"));
+    std::string fontPath = match.path;
+
+    if (systemFont && !fontPath.empty ()) {
+	warnAboutSubstitute (m_loadedFont, match.families);
+    }
 
     if (fontPath.empty ()) {
 	for (const auto& candidate : kFontCandidates) {
@@ -1296,7 +1269,7 @@ void CText::updateBufferMatrix () {
 	const glm::vec2 size = m_passLayout.bufferSize;
 
 	m_glyphBufferMatrix = glm::translate (
-	    glm::ortho<float> (0.0f, size.x, size.y, 0.0f),
+	    DepthRange::toClip (glm::ortho<float> (0.0f, size.x, size.y, 0.0f)),
 	    glm::vec3 (padding.x - std::min (m_result.minX, 0.0f), padding.y - m_result.bottom, 0.0f)
 	);
 	m_glyphBufferMatrixInverse = glm::inverse (m_glyphBufferMatrix);
@@ -1344,7 +1317,7 @@ const float& CText::getBrightness () const {
     return kUnitBrightness;
 }
 
-const float& CText::getUserAlpha () const { return m_text.alpha->value->getFloat (); }
+const float& CText::getUserAlpha () const { return this->getAlpha (); }
 
 const float& CText::getAlpha () const { return m_text.alpha->value->getFloat (); }
 

+ 14 - 13
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -1,4 +1,5 @@
 #include "CPass.h"
+#include "WallpaperEngine/Render/DepthRange.h"
 
 #include <algorithm>
 #include <cctype>
@@ -398,7 +399,7 @@ void CPass::setupRenderFramebuffer () const {
     switch (depth.first) {
 	case DepthtestMode_Enabled:
 	    glEnable (GL_DEPTH_TEST);
-	    glDepthFunc (GL_LEQUAL);
+	    glDepthFunc (DepthRange::depthFunc (GL_LEQUAL));
 	    break;
 	case DepthtestMode_Disabled:
 	default:
@@ -562,7 +563,7 @@ void CPass::bindTextureUnit (int index, const std::shared_ptr<const TextureProvi
 }
 
 void CPass::bindTextureOverrides (uint32_t currentTexture, std::shared_ptr<const TextureProvider>& texture0) const {
-    for (auto [index, chain] : this->m_textures) {
+    for (auto [slot, chain] : this->m_textures) {
 	auto expectedTexture = chain->texture;
 
 	do {
@@ -592,9 +593,9 @@ void CPass::bindTextureOverrides (uint32_t currentTexture, std::shared_ptr<const
 	    expectedTexture = this->m_input;
 	}
 
-	this->bindTextureUnit (index, expectedTexture, index == 0 ? currentTexture : 0);
+	this->bindTextureUnit (slot, expectedTexture, slot == 0 ? currentTexture : 0);
 
-	if (index == 0) {
+	if (slot == 0) {
 	    texture0 = expectedTexture;
 	}
     }
@@ -1294,8 +1295,8 @@ std::shared_ptr<CPass::CompiledShader> CPass::compileShaderSources (
 	const ComboMap* comboMaps[] = { &this->m_combos, &this->m_override.combos };
 	for (const ComboMap* combos : comboMaps) {
 	    stream << '\1';
-	    for (const auto& [name, value] : *combos) {
-		stream << name << '=' << value << ';';
+	    for (const auto& [comboName, comboValue] : *combos) {
+		stream << comboName << '=' << comboValue << ';';
 	    }
 	}
 	for (const TextureMap* textures : { &passTextures, &overrideTextures }) {
@@ -1595,35 +1596,35 @@ void CPass::setupTextureUniforms () {
 	}
     }
 
-    for (const auto& [index, textureName] : this->m_override.textures) {
+    for (const auto& [slot, textureName] : this->m_override.textures) {
 	// WE writes every bound FBO into its slot on each draw (sub_1401EBF60), so overrides there are never sampled
-	if (const auto bind = this->m_binds.find (index); bind != this->m_binds.end () && bind->second != "previous") {
+	if (const auto bind = this->m_binds.find (slot); bind != this->m_binds.end () && bind->second != "previous") {
 	    continue;
 	}
 
 	// same for slot 0 of a pass without binds (3736099508)
-	if (index == 0 && this->m_binds.empty ()) {
+	if (slot == 0 && this->m_binds.empty ()) {
 	    continue;
 	}
 
 	try {
 	    auto texture = this->resolveNamedTexture (textureName);
 
-	    const auto it = this->m_textures.find (index);
+	    const auto it = this->m_textures.find (slot);
 	    const auto chain = std::make_shared<TextureChainEntry> (TextureChainEntry {
 		.texture = texture,
 		.next = it != this->m_textures.end () ? it->second : nullptr,
 	    });
 
-	    this->m_textures[index] = chain;
+	    this->m_textures[slot] = chain;
 
 	    if (textureName.find ("_rt_") != 0 && textureName.find ("_alias_") != 0) {
 		this->trackPlayback (texture);
 	    }
 	} catch (std::runtime_error& ex) {
 	    sLog.error (
-		"Cannot resolve texture '", textureName, "' (index=", index,
-		", object id=", this->m_renderable.getId (), ") for override ", ex.what ()
+		"Cannot resolve texture '", textureName, "' (slot=", slot, ", object id=", this->m_renderable.getId (),
+		") for override ", ex.what ()
 	    );
 	}
     }

+ 4 - 3
src/WallpaperEngine/Render/Objects/PuppetIK.cpp

@@ -8,6 +8,7 @@
 #include <bit>
 #include <cmath>
 
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include <glm/gtc/quaternion.hpp>
 #include <glm/gtc/type_ptr.hpp>
 
@@ -193,7 +194,7 @@ namespace {
 	const float c = (d2.x * d2.x + d2.y * d2.y) + d2.z * d2.z;
 	const float det = a * c - b * b;
 
-	if (det == 0.0f) {
+	if (WallpaperEngine::Data::Utils::isZero (det)) {
 	    return false;
 	}
 
@@ -371,12 +372,12 @@ void limitPuppetJointDirection (
     if (angle > settings.maxAngle) {
 	const float back = settings.maxAngle - angle;
 
-	if (turn == 0.0f || std::fabs (turn) > std::fabs (back)) {
+	if (WallpaperEngine::Data::Utils::isZero (turn) || std::fabs (turn) > std::fabs (back)) {
 	    turn = back;
 	}
     }
 
-    if (turn == 0.0f) {
+    if (WallpaperEngine::Data::Utils::isZero (turn)) {
 	return;
     }
 

+ 8 - 2
src/WallpaperEngine/Render/Objects/PuppetMeshFile.cpp

@@ -432,10 +432,16 @@ WallpaperEngine::Render::Objects::findMdlSection (const std::vector<char>& data,
 
 size_t WallpaperEngine::Render::Objects::findPuppetSkeleton (const std::vector<char>& data) {
     // sections start where the meshes end, so "MDLS" inside mesh data never counts
+    std::optional<size_t> section;
+
     try {
-	return findMdlSection (data, readMdlvMeshes (data).end, "MDLS").value_or (data.size ());
+	section = findMdlSection (data, readMdlvMeshes (data).end, "MDLS").value_or (data.size ());
     } catch (const std::exception&) {
-	// unknown mesh layout, search for the tag
+	section = std::nullopt;
+    }
+
+    if (section.has_value ()) {
+	return *section;
     }
 
     for (size_t offset = MARKER_SIZE; offset + strlen ("MDLS") < data.size (); offset++) {

+ 26 - 22
src/WallpaperEngine/Render/Objects/PuppetRig.cpp

@@ -16,6 +16,7 @@
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Data/Parsers/ObjectParser.h"
 #include "WallpaperEngine/Data/Utils/BinaryReader.h"
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include "WallpaperEngine/Data/Utils/MemoryStream.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Render/Objects/PuppetMeshFile.h"
@@ -246,7 +247,7 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
     };
 
     for (uint16_t i = 0; i < extraCount; i++) {
-	(void)reader.nextNullTerminatedString ();
+	reader.skipNullTerminatedString ();
 	PuppetExtra extra;
 	extra.bone = reader.nextUInt32 ();
 	extra.type = reader.nextUInt32 ();
@@ -499,9 +500,10 @@ void resolveBoneWorldTransform (
 
 std::vector<glm::mat4>
 composeBoneWorldTransforms (const std::vector<int>& parents, const std::vector<glm::mat4>& locals) {
-    std::vector<glm::mat4> world (locals.size ());
-    std::vector<bool> resolved (locals.size (), false);
-    std::vector<bool> visiting (locals.size (), false);
+    const size_t boneTotal = locals.size ();
+    std::vector<glm::mat4> world (boneTotal);
+    std::vector<bool> resolved (boneTotal);
+    std::vector<bool> visiting (boneTotal);
 
     for (size_t i = 0; i < locals.size (); i++) {
 	resolveBoneWorldTransform (i, parents, locals, world, resolved, visiting);
@@ -709,8 +711,8 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 		clip.blendTracks.resize (blendTracks);
 	    }
 
-	    for (uint32_t track = 0; track < blendTracks && valid; track++) {
-		(void)reader.nextUInt32 ();
+	    for (uint32_t track = 0; track < blendTracks; track++) {
+		reader.skipUInt32 ();
 
 		if (reader.nextUInt32 () != sampleCount * sizeof (float)) {
 		    valid = false;
@@ -728,8 +730,8 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 	    if (valid && reader.next () != 0) {
 		clip.boneAlphaTracks.resize (boneCount);
 
-		for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
-		    (void)reader.nextUInt32 ();
+		for (uint32_t boneIndex = 0; boneIndex < boneCount; boneIndex++) {
+		    reader.skipUInt32 ();
 		    const uint32_t trackBytes = reader.nextUInt32 ();
 
 		    if (trackBytes != sampleCount * sizeof (float)) {
@@ -763,11 +765,11 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 
 		auto& meshTracks = clip.morphTracks[mesh];
 		meshTracks.enabled = true;
-		(void)reader.nextUInt32 ();
+		reader.skipUInt32 ();
 		uint16_t count = 0;
 		reader.next (reinterpret_cast<char*> (&count), sizeof (count));
 
-		for (uint16_t i = 0; i < count && valid; i++) {
+		for (uint16_t i = 0; i < count; i++) {
 		    PuppetAnimationClip::MorphTrack track;
 		    reader.next (reinterpret_cast<char*> (&track.target), sizeof (track.target));
 		    const uint32_t trackBytes = reader.nextUInt32 ();
@@ -800,8 +802,8 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 	if (version >= 6 && valid && reader.next () != 0) {
 	    clip.drawOrderTracks.resize (boneCount);
 
-	    for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
-		(void)reader.nextUInt32 ();
+	    for (uint32_t boneIndex = 0; boneIndex < boneCount; boneIndex++) {
+		reader.skipUInt32 ();
 		const uint32_t trackBytes = reader.nextUInt32 ();
 
 		if (trackBytes != sampleCount * sizeof (float)) {
@@ -951,8 +953,9 @@ void PuppetRig::load (const std::vector<char>& data, size_t sections, uint32_t m
 
     auto boneSet = parsePuppetBones (reader, *mdlsOffset);
 
-    std::vector<int> bindParents (boneSet.bones.size ());
-    std::vector<glm::mat4> bindLocals (boneSet.bones.size ());
+    const size_t bindBoneCount = boneSet.bones.size ();
+    std::vector<int> bindParents (bindBoneCount);
+    std::vector<glm::mat4> bindLocals (bindBoneCount);
     for (size_t i = 0; i < boneSet.bones.size (); i++) {
 	bindParents[i] = boneSet.bones[i].parent;
 	bindLocals[i] = boneSet.bones[i].bindLocal;
@@ -1286,7 +1289,8 @@ size_t PuppetRig::removeLayers (const std::function<bool (const PuppetActiveAnim
 	}
     }
 
-    this->layers.erase (removed.begin (), removed.end ());
+    const auto firstRemoved = removed.begin ();
+    this->layers.erase (firstRemoved, this->layers.end ());
     return count;
 }
 
@@ -1318,11 +1322,11 @@ void PuppetRig::updateMorphWeights (const std::vector<PuppetLayerSample>& sample
     constexpr float epsilon = 1.1920929e-7f;
 
     for (const auto& sample : samples) {
-	if (sample.weight == 0.0f) {
+	if (WallpaperEngine::Data::Utils::isZero (sample.weight)) {
 	    continue;
 	}
 
-	const bool direct = sample.weight == 1.0f && !sample.additive;
+	const bool direct = WallpaperEngine::Data::Utils::sameFloat (sample.weight, 1.0f) && !sample.additive;
 	const auto& meshes = sample.clip->morphTracks;
 
 	if (this->morphWeights.size () < meshes.size ()) {
@@ -1569,7 +1573,7 @@ void PuppetRig::updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost*
 
 	samples.push_back (sample);
 
-	if (sample.weight == 0.0f) {
+	if (WallpaperEngine::Data::Utils::isZero (sample.weight)) {
 	    candidate.rootMotion.started = false;
 	    continue;
 	}
@@ -1645,7 +1649,7 @@ void PuppetRig::updateConstraintWeights (const std::vector<PuppetLayerSample>& s
     for (size_t layer = 0; layer < samples.size (); layer++) {
 	const auto& sample = samples[layer];
 	const auto& tracks = sample.clip->constraintTracks;
-	const bool direct = sample.weight == 1.0f && !sample.additive;
+	const bool direct = WallpaperEngine::Data::Utils::sameFloat (sample.weight, 1.0f) && !sample.additive;
 
 	if (layer == 0 && !direct) {
 	    std::ranges::fill (this->constraintWeights, 0.0f);
@@ -1675,7 +1679,7 @@ void PuppetRig::updateBlendMap (const std::vector<PuppetLayerSample>& samples) {
     // instance +848 persists across frames: set, lerp or add per layer (0x1401ff041..0x1401ffa18)
     for (const auto& sample : samples) {
 	const auto& tracks = sample.clip->blendTracks;
-	const bool direct = sample.weight == 1.0f && !sample.additive;
+	const bool direct = WallpaperEngine::Data::Utils::sameFloat (sample.weight, 1.0f) && !sample.additive;
 
 	for (size_t track = 0; track < tracks.size () && track < this->blendMap.size (); track++) {
 	    if (sample.frame1 >= tracks[track].size ()) {
@@ -1707,7 +1711,7 @@ void PuppetRig::updateBoneAlpha (const std::vector<PuppetLayerSample>& samples)
 
     for (const auto& sample : samples) {
 	const auto& tracks = sample.clip->boneAlphaTracks;
-	const bool direct = sample.weight == 1.0f && !sample.additive;
+	const bool direct = WallpaperEngine::Data::Utils::sameFloat (sample.weight, 1.0f) && !sample.additive;
 
 	for (size_t bone = 0; bone < tracks.size () && bone < this->boneAlpha.size (); bone++) {
 	    if (bone < sample.clip->boneFlags.size () && (sample.clip->boneFlags[bone] & 3) == 1) {
@@ -1753,7 +1757,7 @@ void PuppetRig::updateDrawOrder (const std::vector<PuppetLayerSample>& samples)
 
     for (const auto& sample : samples) {
 	const auto& tracks = sample.clip->drawOrderTracks;
-	const bool direct = sample.weight == 1.0f && !sample.additive;
+	const bool direct = WallpaperEngine::Data::Utils::sameFloat (sample.weight, 1.0f) && !sample.additive;
 
 	for (size_t bone = 0; bone < tracks.size () && bone < this->drawOrder.size (); bone++) {
 	    if (bone < sample.clip->boneFlags.size () && (sample.clip->boneFlags[bone] & 3) == 1) {

+ 9 - 19
src/WallpaperEngine/Render/Objects/TextLayout.cpp

@@ -1,4 +1,5 @@
 #include "TextLayout.h"
+#include "WallpaperEngine/Render/Fonts/SystemFonts.h"
 
 #include <algorithm>
 #include <cmath>
@@ -15,6 +16,7 @@
 
 #include <msdfgen.h>
 
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include "WallpaperEngine/Logging/Log.h"
 
 using namespace WallpaperEngine::Render::Objects;
@@ -108,21 +110,7 @@ std::string fontForCodepoint (char32_t codepoint) {
     char pattern[64];
     std::snprintf (pattern, sizeof (pattern), "sans-serif:scalable=true:charset=%x", static_cast<unsigned> (codepoint));
 
-    const std::string command = std::string ("fc-match -f '%{file}' '") + pattern + "' 2>/dev/null";
-    FILE* pipe = popen (command.c_str (), "r");
-
-    if (pipe == nullptr) {
-	return {};
-    }
-
-    std::string path;
-    char buffer[512];
-
-    while (fgets (buffer, sizeof (buffer), pipe) != nullptr) {
-	path += buffer;
-    }
-
-    pclose (pipe);
+    std::string path = WallpaperEngine::Render::Fonts::fcMatch (pattern, "%{file}");
 
     if (path.empty () || !std::filesystem::exists (path)) {
 	path.clear ();
@@ -132,7 +120,7 @@ std::string fontForCodepoint (char32_t codepoint) {
 }
 
 struct OutlineContext {
-    msdfgen::Shape* shape;
+    msdfgen::Shape* shape = nullptr;
     msdfgen::Contour* contour = nullptr;
     msdfgen::Point2 position;
 };
@@ -258,7 +246,9 @@ void distanceTransform2D (std::vector<float>& grid, int width, int height) {
     }
 
     for (int y = 0; y < height; y++) {
-	line.assign (grid.begin () + static_cast<long> (y) * width, grid.begin () + static_cast<long> (y + 1) * width);
+	line.assign (
+	    grid.begin () + static_cast<long> (y) * width, grid.begin () + (static_cast<long> (y) + 1) * width
+	);
 	scratch.resize (width);
 	distanceTransform1D (line, scratch, v, z);
 	std::ranges::copy (line, grid.begin () + static_cast<long> (y) * width);
@@ -384,7 +374,7 @@ bool TextLayout::addFace (std::shared_ptr<const std::vector<uint8_t>> data, cons
 }
 
 void TextLayout::applySize (float size) {
-    if (size == m_size) {
+    if (WallpaperEngine::Data::Utils::sameFloat (size, m_size)) {
 	return;
     }
 
@@ -989,7 +979,7 @@ bool TextLayout::pack (Atlas& atlas, uint64_t key, AtlasGlyph& glyph) {
     for (int row = 0; row < glyph.height; row++) {
 	std::copy_n (
 	    glyph.pixels.begin () + static_cast<long> (row) * glyph.width * channels, glyph.width * channels,
-	    atlas.pixels.begin () + (static_cast<long> (glyph.y + row) * atlas.size + glyph.x) * channels
+	    atlas.pixels.begin () + ((static_cast<long> (glyph.y) + row) * atlas.size + glyph.x) * channels
 	);
     }
 

+ 311 - 8
src/WallpaperEngine/Render/RenderContext.cpp

@@ -6,6 +6,7 @@
 #include "ImageDecoder.h"
 #include "RenderContext.h"
 #include "SplitLayout.h"
+#include "Transition.h"
 
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Logging/Log.h"
@@ -14,11 +15,14 @@
 #include <algorithm>
 #include <chrono>
 #include <cmath>
+#include <cstdio>
 #include <cstdlib>
 #include <numeric>
 #include <unordered_map>
 #include <vector>
 
+extern float g_RealTime;
+
 namespace {
 using Clock = std::chrono::steady_clock;
 
@@ -57,6 +61,18 @@ RenderContext::RenderContext (
     setMaxImageSide (maxTextureSize);
 }
 
+namespace {
+    // the test rigs wait for it: the same line on every desktop, unlike the driver specific ones
+    void noteFirstFrame (const std::string& output) {
+	static bool noted = false;
+
+	if (!noted) {
+	    noted = true;
+	    sLog.out ("First frame drawn on ", output);
+	}
+    }
+}
+
 void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
     if (frameStatsEnabled ()) {
 	this->renderWithStats (viewport);
@@ -73,6 +89,7 @@ void RenderContext::render (Drivers::Output::OutputViewport* viewport) {
 #endif
 
     this->drawWallpapers (*viewport);
+    noteFirstFrame (viewport->name);
 
 #if !NDEBUG
     glPopDebugGroup ();
@@ -102,6 +119,7 @@ void RenderContext::renderWithStats (Drivers::Output::OutputViewport* viewport)
     const auto sceneStart = Clock::now ();
 
     this->drawWallpapers (*viewport);
+    noteFirstFrame (viewport->name);
 
     glFinish ();
 
@@ -250,10 +268,10 @@ std::optional<RenderContext::DrawTarget> RenderContext::findDrawTarget (const st
 }
 
 void RenderContext::setWallpaper (
-    const std::string& display, std::shared_ptr<CWallpaper> wallpaper, const bool holdPrevious
+    const std::string& display, std::shared_ptr<CWallpaper> wallpaper, const bool holdPrevious, const bool animate
 ) {
     if (holdPrevious) {
-	this->holdFrame (display);
+	this->holdFrame (display, animate);
     } else {
 	this->releaseHeldFrame (display);
     }
@@ -263,7 +281,7 @@ void RenderContext::setWallpaper (
     this->pruneTextures ();
 }
 
-void RenderContext::holdFrame (const std::string& display) {
+void RenderContext::holdFrame (const std::string& display, const bool animate) {
     const auto current = this->m_wallpapers.find (display);
     const auto target = this->findDrawTarget (display);
 
@@ -273,7 +291,9 @@ void RenderContext::holdFrame (const std::string& display) {
     }
 
     // keep the older frame when switching again before content arrived
-    if (this->m_heldFrames.contains (display) && !current->second->hasContent ()) {
+    if (const auto older = this->m_heldFrames.find (display);
+	older != this->m_heldFrames.end () && !current->second->hasContent ()) {
+	older->second.animate = animate;
 	return;
     }
 
@@ -287,7 +307,7 @@ void RenderContext::holdFrame (const std::string& display) {
 
     target->viewport->makeCurrent ();
 
-    HeldFrame held { .viewport = rect };
+    HeldFrame held { .viewport = rect, .animate = animate };
 
     if (!allocateHeldFrame (held)) {
 	sLog.error ("Cannot keep the previous wallpaper on ", display, " while the new one loads");
@@ -320,6 +340,11 @@ void RenderContext::releaseHeldFrame (const std::string& display) {
     this->m_heldFrames.erase (held);
 }
 
+namespace {
+    void dumpTransitionFrame (GLuint framebuffer, const glm::ivec4& rect, float progress);
+    void dumpTransitionReferences (GLuint destination, GLuint held, const glm::ivec4& rect);
+}
+
 void RenderContext::drawHeldFrame (const std::string& display, const glm::ivec4& rect, const CWallpaper& wallpaper) {
     auto held = this->m_heldFrames.find (display);
 
@@ -327,14 +352,37 @@ void RenderContext::drawHeldFrame (const std::string& display, const glm::ivec4&
 	return;
     }
 
+    float progress = -1.0f;
+
     if (wallpaper.hasContent ()) {
-	this->releaseHeldFrame (display);
-	return;
+	const auto& render = this->m_app.getContext ().settings.render;
+	const auto kind = parseTransition (render.transition).value_or (TransitionKind::None);
+
+	if (!held->second.animate || kind == TransitionKind::None || !this->ensureTransitionProgram ()) {
+	    this->releaseHeldFrame (display);
+	    return;
+	}
+
+	if (held->second.transitionStart < 0.0) {
+	    held->second.transitionStart = g_RealTime;
+	}
+
+	const double seconds = std::max (render.transitionMs, TRANSITION_MIN_MS) / 1000.0;
+	const double t = (g_RealTime - held->second.transitionStart) / seconds;
+
+	if (t >= 1.0) {
+	    this->releaseHeldFrame (display);
+	    return;
+	}
+
+	progress = static_cast<float> (std::max (t, 0.0));
     }
 
     // the old frame is stretched over the new slot rect, via a copy since multisampled outputs only take 1:1 blits
     if (held->second.viewport.z != rect.z || held->second.viewport.w != rect.w) {
-	HeldFrame resized { .viewport = rect };
+	HeldFrame resized { .viewport = rect,
+			    .animate = held->second.animate,
+			    .transitionStart = held->second.transitionStart };
 
 	if (rect.z <= 0 || rect.w <= 0 || !allocateHeldFrame (resized)) {
 	    this->releaseHeldFrame (display);
@@ -351,6 +399,13 @@ void RenderContext::drawHeldFrame (const std::string& display, const glm::ivec4&
 	held = this->m_heldFrames.insert_or_assign (display, resized).first;
     }
 
+    if (progress >= 0.0f) {
+	dumpTransitionReferences (this->m_app.getDestinationFramebuffer (), held->second.framebuffer, rect);
+	this->drawTransition (held->second, rect, progress);
+	dumpTransitionFrame (this->m_app.getDestinationFramebuffer (), rect, progress);
+	return;
+    }
+
     glBindFramebuffer (GL_READ_FRAMEBUFFER, held->second.framebuffer);
     glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
     glBlitFramebuffer (
@@ -359,6 +414,254 @@ void RenderContext::drawHeldFrame (const std::string& display, const glm::ivec4&
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
 }
 
+namespace {
+    const char* TRANSITION_VERTEX_SHADER = R"(#version 330
+void main () {
+    vec2 corner = vec2 (float (gl_VertexID & 1), float ((gl_VertexID >> 1) & 1));
+    gl_Position = vec4 (corner * 2.0 - 1.0, 0.0, 1.0);
+}
+)";
+
+    // mode: 0 fade, 1 slide left, 2 slide right, 3 wipe left, 4 wipe right, 5 zoom
+    const char* TRANSITION_FRAGMENT_SHADER = R"(#version 330
+uniform sampler2D u_Old;
+uniform vec4 u_Rect;
+uniform float u_Progress;
+uniform int u_Mode;
+out vec4 outColor;
+
+void main () {
+    vec2 uv = (gl_FragCoord.xy - u_Rect.xy) / u_Rect.zw;
+    float p = u_Progress * u_Progress * (3.0 - 2.0 * u_Progress);
+    float alpha = 1.0;
+
+    if (u_Mode == 0) {
+	alpha = 1.0 - p;
+    } else if (u_Mode == 1) {
+	uv.x += p;
+	alpha = uv.x > 1.0 ? 0.0 : 1.0;
+    } else if (u_Mode == 2) {
+	uv.x -= p;
+	alpha = uv.x < 0.0 ? 0.0 : 1.0;
+    } else if (u_Mode == 3 || u_Mode == 4) {
+	float edge = p * 1.06 - 0.03;
+	float x = u_Mode == 3 ? 1.0 - uv.x : uv.x;
+	alpha = smoothstep (edge - 0.03, edge + 0.03, x);
+    } else {
+	uv = (uv - 0.5) / (1.0 + 0.5 * p) + 0.5;
+	alpha = 1.0 - p;
+    }
+
+    if (alpha <= 0.0) {
+	discard;
+    }
+
+    outColor = vec4 (texture (u_Old, clamp (uv, 0.0, 1.0)).rgb, alpha);
+}
+)";
+
+    void writePpm (const std::string& path, const GLuint framebuffer, const glm::ivec4& rect) {
+	std::vector<unsigned char> pixels (static_cast<std::size_t> (rect.z) * rect.w * 3);
+
+	glBindFramebuffer (GL_READ_FRAMEBUFFER, framebuffer);
+	glPixelStorei (GL_PACK_ALIGNMENT, 1);
+	glReadPixels (rect.x, rect.y, rect.z, rect.w, GL_RGB, GL_UNSIGNED_BYTE, pixels.data ());
+
+	if (std::FILE* file = std::fopen (path.c_str (), "wb"); file != nullptr) {
+	    std::fprintf (file, "P6\n%d %d\n255\n", rect.z, rect.w);
+	    std::fwrite (pixels.data (), 1, pixels.size (), file);
+	    std::fclose (file);
+	}
+    }
+
+    // LWE_TRANSITION_DUMP=<name>.ppm (tools/check_transition.sh, the VM matrix): screenshots never show a transition,
+    // they read the wallpaper's own buffer, so the output is written out instead, rows bottom up: the old frame
+    // (<name>-old.ppm) and the new wallpaper on its own (<name>-new.ppm) before the first transition frame is drawn,
+    // <name>.ppm for the first frame that is at least halfway
+    const char* transitionDumpPath () {
+	static const char* path = std::getenv ("LWE_TRANSITION_DUMP");
+	return path;
+    }
+
+    void dumpTransitionReferences (const GLuint destination, const GLuint held, const glm::ivec4& rect) {
+	static bool dumped = false;
+	const char* path = transitionDumpPath ();
+
+	if (path == nullptr || dumped) {
+	    return;
+	}
+
+	dumped = true;
+
+	std::string base = path;
+
+	if (base.ends_with (".ppm")) {
+	    base.resize (base.size () - 4);
+	}
+
+	writePpm (base + "-old.ppm", held, rect);
+	writePpm (base + "-new.ppm", destination, rect);
+    }
+
+    void dumpTransitionFrame (const GLuint framebuffer, const glm::ivec4& rect, const float progress) {
+	static bool dumped = false;
+	const char* path = transitionDumpPath ();
+
+	if (path == nullptr || dumped || progress < 0.5f) {
+	    return;
+	}
+
+	dumped = true;
+	writePpm (path, framebuffer, rect);
+    }
+
+    GLuint compileTransitionShader (const GLenum type, const char* source) {
+	const GLuint shader = glCreateShader (type);
+
+	glShaderSource (shader, 1, &source, nullptr);
+	glCompileShader (shader);
+
+	GLint ok = GL_FALSE;
+	glGetShaderiv (shader, GL_COMPILE_STATUS, &ok);
+
+	if (ok == GL_TRUE) {
+	    return shader;
+	}
+
+	char log[512] = {};
+	glGetShaderInfoLog (shader, sizeof (log) - 1, nullptr, log);
+	sLog.error ("Transition shader: ", log);
+	glDeleteShader (shader);
+	return GL_NONE;
+    }
+}
+
+bool RenderContext::ensureTransitionProgram () {
+    if (this->m_transitionProgram != GL_NONE) {
+	return true;
+    }
+
+    if (this->m_transitionProgramFailed) {
+	return false;
+    }
+
+    this->m_transitionProgramFailed = true;
+
+    const GLuint vertex = compileTransitionShader (GL_VERTEX_SHADER, TRANSITION_VERTEX_SHADER);
+    const GLuint fragment = compileTransitionShader (GL_FRAGMENT_SHADER, TRANSITION_FRAGMENT_SHADER);
+
+    if (vertex == GL_NONE || fragment == GL_NONE) {
+	glDeleteShader (vertex);
+	glDeleteShader (fragment);
+	return false;
+    }
+
+    const GLuint program = glCreateProgram ();
+    glAttachShader (program, vertex);
+    glAttachShader (program, fragment);
+    glLinkProgram (program);
+    glDeleteShader (vertex);
+    glDeleteShader (fragment);
+
+    GLint ok = GL_FALSE;
+    glGetProgramiv (program, GL_LINK_STATUS, &ok);
+
+    if (ok != GL_TRUE) {
+	sLog.error ("Transitions are not available: the shader does not link");
+	glDeleteProgram (program);
+	return false;
+    }
+
+    this->m_transitionProgram = program;
+    this->m_transitionProgramFailed = false;
+    return true;
+}
+
+void RenderContext::drawTransition (const HeldFrame& held, const glm::ivec4& rect, const float progress) {
+    const auto kind = parseTransition (this->m_app.getContext ().settings.render.transition);
+    int mode = 0;
+
+    switch (kind.value_or (TransitionKind::Fade)) {
+	case TransitionKind::SlideLeft:
+	    mode = 1;
+	    break;
+	case TransitionKind::SlideRight:
+	    mode = 2;
+	    break;
+	case TransitionKind::WipeLeft:
+	    mode = 3;
+	    break;
+	case TransitionKind::WipeRight:
+	    mode = 4;
+	    break;
+	case TransitionKind::Zoom:
+	    mode = 5;
+	    break;
+	default:
+	    break;
+    }
+
+    GLint viewport[4], scissorBox[4], program, texture, activeTexture, blendSrcRGB, blendSrcA, blendDstRGB, blendDstA;
+    GLboolean colorMask[4];
+    const GLboolean blend = glIsEnabled (GL_BLEND), scissor = glIsEnabled (GL_SCISSOR_TEST),
+		    depth = glIsEnabled (GL_DEPTH_TEST), cull = glIsEnabled (GL_CULL_FACE);
+
+    glGetIntegerv (GL_VIEWPORT, viewport);
+    glGetIntegerv (GL_SCISSOR_BOX, scissorBox);
+    glGetIntegerv (GL_CURRENT_PROGRAM, &program);
+    glGetIntegerv (GL_ACTIVE_TEXTURE, &activeTexture);
+    glActiveTexture (GL_TEXTURE0);
+    glGetIntegerv (GL_TEXTURE_BINDING_2D, &texture);
+    glGetIntegerv (GL_BLEND_SRC_RGB, &blendSrcRGB);
+    glGetIntegerv (GL_BLEND_SRC_ALPHA, &blendSrcA);
+    glGetIntegerv (GL_BLEND_DST_RGB, &blendDstRGB);
+    glGetIntegerv (GL_BLEND_DST_ALPHA, &blendDstA);
+    glGetBooleanv (GL_COLOR_WRITEMASK, colorMask);
+
+    GLuint vao = GL_NONE;
+    glGenVertexArrays (1, &vao);
+    glBindVertexArray (vao);
+
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_app.getDestinationFramebuffer ());
+    glViewport (rect.x, rect.y, rect.z, rect.w);
+    glEnable (GL_SCISSOR_TEST);
+    glScissor (rect.x, rect.y, rect.z, rect.w);
+    glDisable (GL_DEPTH_TEST);
+    glDisable (GL_CULL_FACE);
+    glEnable (GL_BLEND);
+    glBlendFuncSeparate (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
+
+    glUseProgram (this->m_transitionProgram);
+    glBindTexture (GL_TEXTURE_2D, held.texture);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+    glUniform1i (glGetUniformLocation (this->m_transitionProgram, "u_Old"), 0);
+    glUniform4f (
+	glGetUniformLocation (this->m_transitionProgram, "u_Rect"), static_cast<float> (rect.x),
+	static_cast<float> (rect.y), static_cast<float> (rect.z), static_cast<float> (rect.w)
+    );
+    glUniform1f (glGetUniformLocation (this->m_transitionProgram, "u_Progress"), progress);
+    glUniform1i (glGetUniformLocation (this->m_transitionProgram, "u_Mode"), mode);
+    glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
+
+    glBindTexture (GL_TEXTURE_2D, texture);
+    glActiveTexture (activeTexture);
+    glUseProgram (program);
+    glBindVertexArray (GL_NONE);
+    glDeleteVertexArrays (1, &vao);
+    glColorMask (colorMask[0], colorMask[1], colorMask[2], colorMask[3]);
+    glBlendFuncSeparate (blendSrcRGB, blendDstRGB, blendSrcA, blendDstA);
+    blend ? glEnable (GL_BLEND) : glDisable (GL_BLEND);
+    scissor ? glEnable (GL_SCISSOR_TEST) : glDisable (GL_SCISSOR_TEST);
+    depth ? glEnable (GL_DEPTH_TEST) : glDisable (GL_DEPTH_TEST);
+    cull ? glEnable (GL_CULL_FACE) : glDisable (GL_CULL_FACE);
+    glScissor (scissorBox[0], scissorBox[1], scissorBox[2], scissorBox[3]);
+    glViewport (viewport[0], viewport[1], viewport[2], viewport[3]);
+}
+
 bool RenderContext::allocateHeldFrame (HeldFrame& held) {
     glGenTextures (1, &held.texture);
     glBindTexture (GL_TEXTURE_2D, held.texture);

+ 14 - 4
src/WallpaperEngine/Render/RenderContext.h

@@ -39,9 +39,12 @@ namespace Render {
 	RenderContext (Drivers::VideoDriver& driver, WallpaperApplication& app, Media::MediaSource& mediaSource);
 
 	void render (Drivers::Output::OutputViewport* viewport);
-	/** holdPrevious keeps the old wallpaper's last frame on screen until the new one has content */
-	void
-	setWallpaper (const std::string& display, std::shared_ptr<CWallpaper> wallpaper, bool holdPrevious = false);
+	/** holdPrevious keeps the old wallpaper's last frame on screen until the new one has content, animate then
+	 *  plays the configured transition from that frame to the new wallpaper */
+	void setWallpaper (
+	    const std::string& display, std::shared_ptr<CWallpaper> wallpaper, bool holdPrevious = false,
+	    bool animate = false
+	);
 	void setPause (bool newState) const;
 	void pruneTextures () const;
 	[[nodiscard]] Input::InputContext& getInputContext () const;
@@ -63,7 +66,7 @@ namespace Render {
 	void drawSplitScreen (
 	    Drivers::Output::OutputViewport& viewport, const Application::ApplicationContext::SplitScreen& split
 	);
-	void holdFrame (const std::string& display);
+	void holdFrame (const std::string& display, bool animate);
 	void releaseHeldFrame (const std::string& display);
 	void drawHeldFrame (const std::string& display, const glm::ivec4& rect, const CWallpaper& wallpaper);
 
@@ -78,8 +81,13 @@ namespace Render {
 	    GLuint framebuffer = GL_NONE;
 	    GLuint texture = GL_NONE;
 	    glm::ivec4 viewport {};
+	    bool animate = false;
+	    /** g_RealTime of the first frame the new wallpaper had content, negative before that */
+	    double transitionStart = -1.0;
 	};
 	static bool allocateHeldFrame (HeldFrame& held);
+	void drawTransition (const HeldFrame& held, const glm::ivec4& rect, float progress);
+	bool ensureTransitionProgram ();
 
 	Drivers::VideoDriver& m_driver;
 	std::map<std::string, std::shared_ptr<CWallpaper>> m_wallpapers = {};
@@ -88,6 +96,8 @@ namespace Render {
 	std::unique_ptr<TextureCache> m_textureCache = nullptr;
 	std::map<std::string, HeldFrame> m_heldFrames = {};
 	std::map<std::string, glm::ivec4> m_slotRects = {};
+	GLuint m_transitionProgram = GL_NONE;
+	bool m_transitionProgramFailed = false;
     };
 }
 }

+ 0 - 1
src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp

@@ -1810,7 +1810,6 @@ const ComboMap& ShaderUnit::getCombos () const { return this->m_combos; }
 const ComboMap& ShaderUnit::getDiscoveredCombos () const { return this->m_discoveredCombos; }
 
 void ShaderUnit::releaseSources () {
-    // the identifiers asked about after the compile are looked up now
     for (const char* identifier : { "MORPHING" }) {
 	this->m_referenced.emplace (identifier, this->refersTo (identifier));
     }

+ 12 - 4
src/WallpaperEngine/Render/ShadowMapping.cpp

@@ -1,4 +1,5 @@
 #include "ShadowMapping.h"
+#include "WallpaperEngine/Render/DepthRange.h"
 
 #include <algorithm>
 #include <cmath>
@@ -128,12 +129,17 @@ GLuint compile (const GLenum type, const char* source) {
 }
 
 // WE's matrices put Direct3D's depth 0..1 into z and its viewport maps y = +1 to the first row of the target. The
-// same memory layout in GL: y flipped and z moved to -w..w, the window depth is then WE's depth value
+// same memory layout in GL: y flipped and, unless the scene draws with a 0..1 clip z, z moved to -w..w; the window
+// depth is then WE's depth value
 glm::mat4 toGL (const glm::mat4& direct3D) {
     glm::mat4 convert (1.0f);
     convert[1][1] = -1.0f;
-    convert[2][2] = 2.0f;
-    convert[3][2] = -1.0f;
+
+    if (!DepthRange::supported ()) {
+	convert[2][2] = 2.0f;
+	convert[3][2] = -1.0f;
+    }
+
     return convert * direct3D;
 }
 }
@@ -266,11 +272,13 @@ void ShadowMapping::render (std::vector<Entry>& entries) {
 
     // sub_140196530: clear to reversed far depth, draw GREATER with sub_140099050's shadow raster state: slope bias -4,
     // no culling (RenderDoc of live WE: NoCull, slope -4, D32)
+    GLdouble previousClearDepth = 1.0;
+    glGetDoublev (GL_DEPTH_CLEAR_VALUE, &previousClearDepth);
     glBindFramebuffer (GL_FRAMEBUFFER, atlas->getFramebuffer ());
     glDepthMask (GL_TRUE);
     glClearDepth (0.0);
     glClear (GL_DEPTH_BUFFER_BIT);
-    glClearDepth (1.0);
+    glClearDepth (previousClearDepth);
     glColorMask (GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
     glDisable (GL_BLEND);
     glEnable (GL_DEPTH_TEST);

+ 25 - 24
src/WallpaperEngine/Render/TextureCache.cpp

@@ -204,30 +204,30 @@ TextureUniquePtr buildIconTexture (const std::filesystem::path& path) {
     if (lowerExtension (path.string ()) == ".svg") {
 	NSVGimage* image = nsvgParseFromFile (path.c_str (), "px", 96.0f);
 
-	if (image == nullptr || image->width <= 0.0f || image->height <= 0.0f) {
+	if (image != nullptr && image->width > 0.0f && image->height > 0.0f) {
+	    const float scale = static_cast<float> (ICON_SIZE) / std::max (image->width, image->height);
+	    width = std::max (1, static_cast<int> (image->width * scale));
+	    height = std::max (1, static_cast<int> (image->height * scale));
+	    pixels.resize (static_cast<size_t> (width) * height * 4);
+
+	    NSVGrasterizer* rasterizer = nsvgCreateRasterizer ();
+	    nsvgRasterize (rasterizer, image, 0.0f, 0.0f, scale, pixels.data (), width, height, width * 4);
+	    nsvgDeleteRasterizer (rasterizer);
+	    nsvgDelete (image);
+	} else {
 	    nsvgDelete (image);
 	    sLog.exception ("Cannot parse icon ", path.string ());
 	}
-
-	const float scale = static_cast<float> (ICON_SIZE) / std::max (image->width, image->height);
-	width = std::max (1, static_cast<int> (image->width * scale));
-	height = std::max (1, static_cast<int> (image->height * scale));
-	pixels.resize (static_cast<size_t> (width) * height * 4);
-
-	NSVGrasterizer* rasterizer = nsvgCreateRasterizer ();
-	nsvgRasterize (rasterizer, image, 0.0f, 0.0f, scale, pixels.data (), width, height, width * 4);
-	nsvgDeleteRasterizer (rasterizer);
-	nsvgDelete (image);
     } else {
 	int channels = 0;
 	stbi_uc* data = stbi_load (path.c_str (), &width, &height, &channels, 4);
 
-	if (data == nullptr) {
+	if (data != nullptr) {
+	    pixels.assign (data, data + static_cast<size_t> (width) * height * 4);
+	    stbi_image_free (data);
+	} else {
 	    sLog.exception ("Cannot decode icon ", path.string (), ": ", stbi_failure_reason ());
 	}
-
-	pixels.assign (data, data + static_cast<size_t> (width) * height * 4);
-	stbi_image_free (data);
     }
 
     auto mipmap = std::make_shared<Mipmap> ();
@@ -643,20 +643,21 @@ std::shared_ptr<const TextureProvider> TextureCache::resolve (const std::string&
 	return texture;
     };
 
-    try {
-	return load (requester);
-    } catch (AssetLoadException&) {
-	// not shipped by the requesting project itself, it might still live in another loaded one
-    }
+    // not shipped by the requesting project itself, it might still live in another loaded one
+    std::vector<const Project*> candidates { &requester };
 
     for (const auto& project : this->getContext ().getApp ().getBackgrounds () | std::views::values) {
-	if (project.get () == &requester) {
-	    continue;
+	if (project.get () != &requester) {
+	    candidates.push_back (project.get ());
 	}
+    }
 
+    for (const Project* candidate : candidates) {
 	try {
-	    return load (*project);
-	} catch (AssetLoadException&) { }
+	    return load (*candidate);
+	} catch (AssetLoadException&) {
+	    continue;
+	}
     }
 
     throw AssetLoadException ("Cannot find file", filename, std::error_code ());

+ 1 - 1
src/WallpaperEngine/Render/TextureCache.h

@@ -46,7 +46,7 @@ public:
 private:
     struct ConditionalTexture {
 	std::weak_ptr<CTexture> texture;
-	const Data::Model::Project* project;
+	const Data::Model::Project* project = nullptr;
 	std::string filename;
 	std::vector<std::function<void ()>> listeners = {};
 	bool dirty = false;

+ 36 - 0
src/WallpaperEngine/Render/Transition.h

@@ -0,0 +1,36 @@
+#pragma once
+
+#include <optional>
+#include <string>
+
+namespace WallpaperEngine::Render {
+enum class TransitionKind { None, Fade, SlideLeft, SlideRight, WipeLeft, WipeRight, Zoom };
+
+inline std::optional<TransitionKind> parseTransition (const std::string& value) {
+    if (value == "none") {
+	return TransitionKind::None;
+    }
+    if (value == "fade") {
+	return TransitionKind::Fade;
+    }
+    if (value == "slide-left") {
+	return TransitionKind::SlideLeft;
+    }
+    if (value == "slide-right") {
+	return TransitionKind::SlideRight;
+    }
+    if (value == "wipe-left") {
+	return TransitionKind::WipeLeft;
+    }
+    if (value == "wipe-right") {
+	return TransitionKind::WipeRight;
+    }
+    if (value == "zoom") {
+	return TransitionKind::Zoom;
+    }
+    return std::nullopt;
+}
+
+constexpr int TRANSITION_MIN_MS = 100;
+constexpr int TRANSITION_MAX_MS = 5000;
+}

+ 27 - 41
src/WallpaperEngine/Render/Utils/NoiseUtils.h

@@ -1,6 +1,7 @@
 #pragma once
 
 #include <algorithm>
+#include <array>
 #include <cmath>
 #include <cstdint>
 #include <glm/glm.hpp>
@@ -34,42 +35,17 @@ static const unsigned char PERLIN_PERM[]
 	78,  66,  215, 61,  156, 180 };
 
 inline double perlinGrad (int hash, double x, double y, double z) {
-    switch (hash & 0xF) {
-	case 0x0:
-	    return x + y;
-	case 0x1:
-	    return -x + y;
-	case 0x2:
-	    return x - y;
-	case 0x3:
-	    return -x - y;
-	case 0x4:
-	    return x + z;
-	case 0x5:
-	    return -x + z;
-	case 0x6:
-	    return x - z;
-	case 0x7:
-	    return -x - z;
-	case 0x8:
-	    return y + z;
-	case 0x9:
-	    return -y + z;
-	case 0xA:
-	    return y - z;
-	case 0xB:
-	    return -y - z;
-	case 0xC:
-	    return y + x;
-	case 0xD:
-	    return -y + z;
-	case 0xE:
-	    return y - x;
-	case 0xF:
-	    return -y - z;
-	default:
-	    return 0;
-    }
+    struct Gradient {
+	int x, y, z;
+    };
+
+    static constexpr Gradient gradients[16] = {
+	{ 1, 1, 0 }, { -1, 1, 0 }, { 1, -1, 0 }, { -1, -1, 0 }, { 1, 0, 1 }, { -1, 0, 1 }, { 1, 0, -1 }, { -1, 0, -1 },
+	{ 0, 1, 1 }, { 0, -1, 1 }, { 0, 1, -1 }, { 0, -1, -1 }, { 1, 1, 0 }, { 0, -1, 1 }, { -1, 1, 0 }, { 0, -1, -1 },
+    };
+    const Gradient& gradient = gradients[hash & 0xF];
+
+    return gradient.x * x + gradient.y * y + gradient.z * z;
 }
 
 inline double perlinEase (double t) { return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); }
@@ -253,11 +229,21 @@ inline float hashedNoise2D (int32_t seed, float x, float y) {
     const uint32_t hashX = static_cast<uint32_t> (static_cast<int32_t> (i)) * primeX;
     const uint32_t hashY = static_cast<uint32_t> (static_cast<int32_t> (j)) * primeY;
 
-    const bool xFirst = y0 < x0;
-    const float x1 = (x0 - (xFirst ? 1.0f : 0.0f)) + G2;
-    const float y1 = (y0 - (xFirst ? 0.0f : 1.0f)) + G2;
-    const float x2 = x0 + cornerOffset;
-    const float y2 = y0 + cornerOffset;
+    const std::array<float, 2> origin = { x0, y0 };
+    const size_t steppedAxis = origin[0] > origin[1] ? 0 : 1;
+    const bool xFirst = steppedAxis == 0;
+    std::array<float, 2> middle {};
+    std::array<float, 2> last {};
+
+    for (size_t axis = 0; axis < 2; axis++) {
+	middle[axis] = (origin[axis] - (axis == steppedAxis ? 1.0f : 0.0f)) + G2;
+	last[axis] = origin[axis] + cornerOffset;
+    }
+
+    const float x1 = middle[0];
+    const float y1 = middle[1];
+    const float x2 = last[0];
+    const float y2 = last[1];
 
     float a0 = std::max (-(x0 * x0) + (-(y0 * y0) + 0.5f), 0.0f);
     float a1 = std::max (-(x1 * x1) + (-(y1 * y1) + 0.5f), 0.0f);

+ 36 - 12
src/WallpaperEngine/Render/Volumetrics.cpp

@@ -9,7 +9,9 @@
 #include "WallpaperEngine/Application/ApplicationContext.h"
 #include "WallpaperEngine/Application/WallpaperApplication.h"
 #include "WallpaperEngine/Data/Model/Object.h"
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/DepthRange.h"
 #include "WallpaperEngine/Render/RenderContext.h"
 #include "WallpaperEngine/Render/Wallpapers/CScene.h"
 
@@ -27,14 +29,19 @@ out vec2 v_HashPos;
 void main () {
     gl_Position = u_ViewProjection * u_Volume * vec4 (a_Position * u_MeshScale, 1.0);
 #if FULLSCREEN
+#if REVERSED
+    gl_Position = vec4 (a_Position.xy, 1.0, 1.0);
+#else
     gl_Position = vec4 (a_Position.xy, -1.0, 1.0);
+#endif
 #endif
     v_ScreenPos = gl_Position;
     v_HashPos = vec2 (gl_Position.x, -gl_Position.y);
 }
 )";
 
-// the far side of the volume, as normalized depth
+// the far side of the volume, as normalized depth (WE's reversed depth when REVERSED: the scene is drawn with a 0..1
+// clip z)
 const char* kBackFragment = R"(
 in vec4 v_ScreenPos;
 out vec4 fragColor;
@@ -228,6 +235,16 @@ float fogAlpha (float alpha, float viewLength, float height) {
 void main () {
     vec3 screenDepth = v_ScreenPos.xyz / v_ScreenPos.w;
     vec2 screenUV = gl_FragCoord.xy / u_BufferSize;
+#if REVERSED
+    float backDepth = texture (u_SceneDepth, screenUV).r;
+    float limitDepth = texture (u_Back, screenUV).r;
+
+    if (screenDepth.z - backDepth < 0.0) {
+	discard;
+    }
+
+    backDepth = max (backDepth, limitDepth);
+#else
     float backDepth = texture (u_SceneDepth, screenUV).r * 2.0 - 1.0;
     float limitDepth = texture (u_Back, screenUV).r;
 
@@ -236,6 +253,7 @@ void main () {
     }
 
     backDepth = min (backDepth, limitDepth);
+#endif
 
     vec4 worldStart = u_InverseViewProjection * vec4 (screenDepth, 1.0);
     vec4 worldEnd = u_InverseViewProjection * vec4 (screenDepth.xy, backDepth, 1.0);
@@ -360,7 +378,8 @@ void main () {
 )";
 
 GLuint compile (const std::string& defines, const char* vertex, const char* fragment) {
-    const std::string header = "#version 330\n" + defines;
+    const std::string header
+	= std::string ("#version 330\n") + (DepthRange::supported () ? "#define REVERSED 1\n" : "") + defines;
     const std::string vertexSource = header + vertex;
     const std::string fragmentSource = header + fragment;
     const char* sources[] = { vertexSource.c_str (), fragmentSource.c_str () };
@@ -527,7 +546,7 @@ void Volumetrics::setup () {
     for (int side = 0; side < 32; side++) {
 	const float angle = static_cast<float> (side) * 0.03125f * 6.2831855f;
 	const float next = angle + 0.19634955f;
-	const auto base = static_cast<GLushort> (vertices.size ());
+	const auto base = static_cast<GLushort> (vertices.size () & 0xFFFF);
 
 	vertices.emplace_back (std::sin (angle), -std::cos (angle), 1.0f);
 	vertices.emplace_back (std::sin (next), -std::cos (next), 1.0f);
@@ -618,7 +637,7 @@ void Volumetrics::allocate (const glm::ivec2 size) {
     // shared by the back pass and the light buffer
     glGenRenderbuffers (1, &this->m_backDepth);
     glBindRenderbuffer (GL_RENDERBUFFER, this->m_backDepth);
-    glRenderbufferStorage (GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, size.x, size.y);
+    glRenderbufferStorage (GL_RENDERBUFFER, GL_DEPTH_COMPONENT32F, size.x, size.y);
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_back.framebuffer);
     glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, this->m_backDepth);
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_light.framebuffer);
@@ -697,7 +716,7 @@ void Volumetrics::copySceneDepth (const GLint framebuffer) {
 	glGenTextures (1, &this->m_sceneDepth.texture);
 	glBindTexture (GL_TEXTURE_2D, this->m_sceneDepth.texture);
 	glTexImage2D (
-	    GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, size.x, size.y, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr
+	    GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32F, size.x, size.y, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr
 	);
 	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
 	glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
@@ -710,7 +729,7 @@ void Volumetrics::copySceneDepth (const GLint framebuffer) {
 	glReadBuffer (GL_NONE);
 	// passes leave their own depthwrite behind, and glClear honors it
 	glDepthMask (GL_TRUE);
-	glClearDepth (1.0);
+	glClearDepth (DepthRange::farDepth ());
 	glClear (GL_DEPTH_BUFFER_BIT);
 	glBindFramebuffer (GL_FRAMEBUFFER, framebuffer);
     }
@@ -770,9 +789,11 @@ void Volumetrics::renderLight (
     GLint previousFramebuffer = 0;
     GLint previousVao = 0;
     GLint previousViewport[4] = {};
+    GLdouble previousClearDepth = 1.0;
     glGetIntegerv (GL_FRAMEBUFFER_BINDING, &previousFramebuffer);
     glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &previousVao);
     glGetIntegerv (GL_VIEWPORT, previousViewport);
+    glGetDoublev (GL_DEPTH_CLEAR_VALUE, &previousClearDepth);
 
     this->copySceneDepth (previousFramebuffer);
 
@@ -827,7 +848,9 @@ void Volumetrics::renderLight (
     // volume and the front pass only the near one, so where the scene's depth range clips the far side off the ray
     // runs to the far plane. The near side faces the viewer when the mesh's outward winding, flipped by a mirroring
     // transform, comes out clockwise on screen
-    const bool nearIsFront = mesh.winding * glm::determinant (viewProjection * volume) < 0.0f;
+    // (the depth remap of a reversed projection turns the determinant's sign, the screen's winding stays)
+    const float depthSign = DepthRange::supported () ? -1.0f : 1.0f;
+    const bool nearIsFront = depthSign * mesh.winding * glm::determinant (viewProjection * volume) < 0.0f;
 
     glBindVertexArray (mesh.vao);
     glViewport (0, 0, size.x, size.y);
@@ -841,10 +864,10 @@ void Volumetrics::renderLight (
 
     // far side of the volume
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_back.framebuffer);
-    glClearColor (1.0f, 0.0f, 0.0f, 0.0f);
-    glClearDepth (0.0);
+    glClearColor (WallpaperEngine::Data::Utils::isZero (DepthRange::farDepth ()) ? 0.0f : 1.0f, 0.0f, 0.0f, 0.0f);
+    glClearDepth (1.0 - DepthRange::farDepth ());
     glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
-    glDepthFunc (GL_GREATER);
+    glDepthFunc (DepthRange::depthFunc (GL_GREATER));
     glUseProgram (this->m_backProgram);
     glUniformMatrix4fv (
 	glGetUniformLocation (this->m_backProgram, "u_ViewProjection"), 1, GL_FALSE, &viewProjection[0][0]
@@ -855,7 +878,7 @@ void Volumetrics::renderLight (
 
     // near side, added into the light buffer. Cleared by the first light since the last composite
     glBindFramebuffer (GL_FRAMEBUFFER, this->m_light.framebuffer);
-    glClearDepth (1.0);
+    glClearDepth (DepthRange::farDepth ());
 
     if (!this->m_pending) {
 	glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
@@ -865,7 +888,7 @@ void Volumetrics::renderLight (
 	glClear (GL_DEPTH_BUFFER_BIT);
     }
 
-    glDepthFunc (GL_LESS);
+    glDepthFunc (DepthRange::depthFunc (GL_LESS));
     glCullFace (nearIsFront ? GL_BACK : GL_FRONT);
     glEnable (GL_BLEND);
     glBlendEquation (GL_FUNC_ADD);
@@ -960,6 +983,7 @@ void Volumetrics::renderLight (
     glDisable (GL_DEPTH_TEST);
     glDepthFunc (GL_LESS);
     glDisable (GL_BLEND);
+    glClearDepth (previousClearDepth);
     glBindFramebuffer (GL_FRAMEBUFFER, previousFramebuffer);
     glBindVertexArray (previousVao);
     glViewport (previousViewport[0], previousViewport[1], previousViewport[2], previousViewport[3]);

+ 6 - 4
src/WallpaperEngine/Render/WallpaperState.cpp

@@ -1,5 +1,6 @@
 #include "WallpaperState.h"
 #include "TextureProvider.h"
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include <algorithm>
 #include <cmath>
@@ -196,7 +197,7 @@ float WallpaperState::getZoom () const { return this->m_zoom; }
 void WallpaperState::setZoom (float zoom) {
     zoom = std::clamp (zoom, 0.1f, 5.0f);
 
-    if (this->m_zoom == zoom) {
+    if (WallpaperEngine::Data::Utils::sameFloat (this->m_zoom, zoom)) {
 	return;
     }
 
@@ -217,7 +218,7 @@ void applyZoomToAxis (float& start, float& end, float zoom) {
 // Slides the UV window toward one edge without changing its size, offset in [-1, 1]; no-op when nothing is cropped on
 // the axis
 void applyOffsetToAxis (float& start, float& end, float offset) {
-    if (offset == 0.0f) {
+    if (WallpaperEngine::Data::Utils::isZero (offset)) {
 	return;
     }
 
@@ -253,7 +254,8 @@ void WallpaperState::setOffset (float offsetX, float offsetY) {
     offsetX = std::clamp (offsetX, -1.0f, 1.0f);
     offsetY = std::clamp (offsetY, -1.0f, 1.0f);
 
-    if (this->m_offsetX == offsetX && this->m_offsetY == offsetY) {
+    if (WallpaperEngine::Data::Utils::sameFloat (this->m_offsetX, offsetX)
+	&& WallpaperEngine::Data::Utils::sameFloat (this->m_offsetY, offsetY)) {
 	return;
     }
 
@@ -318,7 +320,7 @@ void WallpaperState::updateState (
 	    break;
     }
 
-    if (this->m_zoom != 1.0f) {
+    if (!WallpaperEngine::Data::Utils::sameFloat (this->m_zoom, 1.0f)) {
 	applyZoomToAxis (this->m_UVs.ustart, this->m_UVs.uend, this->m_zoom);
 	applyZoomToAxis (this->m_UVs.vstart, this->m_UVs.vend, this->m_zoom);
     }

+ 79 - 12
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -1,4 +1,5 @@
 #include "WallpaperEngine/Data/Model/Property.h"
+#include "WallpaperEngine/Render/DepthRange.h"
 #include "WallpaperEngine/Render/MissingTexture.h"
 #include "WallpaperEngine/Render/Objects/CCamera.h"
 #include "WallpaperEngine/Render/Objects/CImage.h"
@@ -13,7 +14,9 @@
 
 #include "CScene.h"
 #include "MouseMapping.h"
+#include "WallpaperEngine/Led/LedHub.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Render/LedFrameGrabber.h"
 #include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
 #include "WallpaperEngine/Scripting/ScriptableObject.h"
 #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
@@ -24,6 +27,7 @@
 #include "WallpaperEngine/Render/Shaders/GLSLContext.h"
 #include "WallpaperEngine/Render/Shaders/Shader.h"
 
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include <algorithm>
 #include <bit>
 #include <chrono>
@@ -295,6 +299,8 @@ CScene::CScene (
 }
 
 CScene::~CScene () {
+    Led::releaseFeed (this);
+
     if (this->m_nullTexture != GL_NONE) {
 	glDeleteTextures (1, &this->m_nullTexture);
     }
@@ -555,6 +561,9 @@ template <typename Step> void timeStep (const std::string& label, Step&& step) {
 }
 
 void CScene::renderFrame (const glm::ivec4& viewport) {
+    // WE draws its scenes with a reversed float depth buffer, so does this where the driver can map clip z to 0..1
+    const DepthRange::Scope depthRange;
+
     timeStep ("renderFrame total", [&] { this->renderFrameSteps (viewport); });
 }
 
@@ -678,6 +687,54 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
 
     // after every object (sub_14017FA70)
     timeStep ("post processing", [&] { this->renderPostProcessing (); });
+    this->feedLeds ();
+}
+
+void CScene::feedLeds () {
+    auto& output = Led::sharedOutput ();
+
+    if (!output.running () || !Led::claimFeed (this)) {
+	return;
+    }
+
+    using namespace std::chrono_literals;
+    const auto now = std::chrono::steady_clock::now ();
+
+    // wallpaper64.exe asks for a frame every 1/30 s
+    if (now < this->m_ledNext) {
+	return;
+    }
+
+    this->m_ledNext = now + 33ms;
+
+    std::shared_ptr<const CFBO> source = this->m_sceneFBO;
+
+    for (const auto& object : this->getScene ().objects) {
+	const bool led = object->is<Image> ()
+	    ? object->as<Image> ()->renderable.ledSource->value->getBool ()
+	    : object->is<Text> () && object->as<Text> ()->renderable.ledSource->value->getBool ();
+
+	if (!led) {
+	    continue;
+	}
+
+	if (auto layer = this->find ("_rt_imageLayerComposite_" + std::to_string (object->id) + "_a");
+	    layer != nullptr) {
+	    source = std::move (layer);
+	    break;
+	}
+    }
+
+    if (this->m_ledGrabber == nullptr) {
+	this->m_ledGrabber = std::make_unique<LedFrameGrabber> ();
+    }
+
+    if (this->m_ledGrabber->grab (
+	    source->getTextureID (0), static_cast<int> (source->getRealWidth ()),
+	    static_cast<int> (source->getRealHeight ()), this->m_ledFrame
+	)) {
+	output.submit (this->m_ledFrame);
+    }
 }
 
 void CScene::paintLetterbox () const {
@@ -1048,7 +1105,7 @@ bool CScene::prepareMultisample () {
     if (this->m_sceneFBO->getDepthbuffer () != GL_NONE) {
 	glGenRenderbuffers (1, &this->m_msaaDepth);
 	glBindRenderbuffer (GL_RENDERBUFFER, this->m_msaaDepth);
-	glRenderbufferStorageMultisample (GL_RENDERBUFFER, this->m_msaaSamples, GL_DEPTH_COMPONENT24, size.x, size.y);
+	glRenderbufferStorageMultisample (GL_RENDERBUFFER, this->m_msaaSamples, GL_DEPTH_COMPONENT32F, size.x, size.y);
     }
 
     glBindRenderbuffer (GL_RENDERBUFFER, 0);
@@ -1155,19 +1212,26 @@ void CScene::cursorLine (
     const glm::vec2& ndc, const bool perspectiveLayer, glm::vec3& origin, glm::vec3& direction
 ) const {
     const glm::mat4 toWorld = glm::inverse (this->getWorldViewProjection (perspectiveLayer));
-    const glm::vec4 nearPoint = toWorld * glm::vec4 (ndc, -1.0f, 1.0f);
-    const glm::vec4 farPoint = toWorld * glm::vec4 (ndc, 1.0f, 1.0f);
+    const glm::vec4 nearPoint = toWorld * glm::vec4 (ndc, DepthRange::nearClip (), 1.0f);
+    const glm::vec4 farPoint = toWorld * glm::vec4 (ndc, DepthRange::farClip (), 1.0f);
 
     origin = glm::vec3 (nearPoint) / nearPoint.w;
     direction = glm::vec3 (farPoint) / farPoint.w - origin;
 }
 
 glm::mat4 CScene::getCullViewProjection () const {
-    // GL clip z to WE's: perspective (z + w) / 2, 2D ortho (w - z) / 2
-    const float direction = this->getCamera ().isOrthogonal () ? -0.5f : 0.5f;
+    // the culling test wants WE's clip z: perspective 0 at the near plane and 1 at the far one, 2D ortho (w - z) / 2
+    // of GL's. Both come out of the scene matrices from a depth remap, which reversed ones already have for 2D ortho
+    const bool reversed = DepthRange::supported ();
+
+    if (reversed && this->getCamera ().isOrthogonal ()) {
+	return this->getWorldViewProjection ();
+    }
+
+    const float direction = reversed ? -1.0f : (this->getCamera ().isOrthogonal () ? -0.5f : 0.5f);
     glm::mat4 depth (1.0f);
     depth[2][2] = direction;
-    depth[3][2] = 0.5f;
+    depth[3][2] = reversed ? 1.0f : 0.5f;
 
     return depth * this->getWorldViewProjection ();
 }
@@ -1671,7 +1735,7 @@ bool CScene::setObjectParent (CObject& object, const CObject* parent, int attach
 
     this->detachChild (object);
 
-    if (loops || steps >= 1024) {
+    if (parent != nullptr && (loops || steps >= 1024)) {
 	sLog.error (
 	    "Cannot make object ", object.getId (), " a child of ", parent->getId (), ", the parents would loop"
 	);
@@ -1902,7 +1966,7 @@ void CScene::updateCamera () {
 	    amplitude *= static_cast<float> (this->getHeight ()) * 0.1f;
 	}
 
-	if (roughness > 0.001f && roughness != 1.0f) {
+	if (roughness > 0.001f && !WallpaperEngine::Data::Utils::sameFloat (roughness, 1.0f)) {
 	    const float length = glm::length (offset);
 
 	    if (length > 0.0f) {
@@ -2203,7 +2267,8 @@ void CScene::expandCanvasToContent (
     canvasWidth = std::min (std::ceil (extentX * 2.0f), std::max (width, maxCanvasSize));
     canvasHeight = std::min (std::ceil (extentY * 2.0f), std::max (height, maxCanvasSize));
 
-    if (canvasWidth != width || canvasHeight != height) {
+    if (!WallpaperEngine::Data::Utils::sameFloat (canvasWidth, width)
+	|| !WallpaperEngine::Data::Utils::sameFloat (canvasHeight, height)) {
 	sLog.out ("Expanded scene canvas from ", width, "x", height, " to ", canvasWidth, "x", canvasHeight);
     }
 }
@@ -2266,13 +2331,15 @@ glm::vec3 CScene::unprojectCursor () const {
     const auto& camera = this->getCamera ();
 
     if (camera.isPerspective ()) {
-	const glm::vec4 world
-	    = glm::inverse (camera.getPerspective () * camera.getView ()) * glm::vec4 (ndc, -1.0f, 1.0f);
+	const glm::vec4 world = glm::inverse (camera.getPerspective () * camera.getView ())
+	    * glm::vec4 (ndc, DepthRange::nearClip (), 1.0f);
 
 	return glm::vec3 (world) / world.w;
     }
 
-    return glm::vec3 (glm::inverse (camera.getProjection () * camera.getLookAt ()) * glm::vec4 (ndc, 0.0f, 1.0f));
+    return glm::vec3 (
+	glm::inverse (camera.getProjection () * camera.getLookAt ()) * glm::vec4 (ndc, DepthRange::middleClip (), 1.0f)
+    );
 }
 
 glm::vec3 CScene::getCursorWorldPosition () const {

+ 8 - 2
src/WallpaperEngine/Render/Wallpapers/CScene.h

@@ -6,10 +6,12 @@
 
 #include "WallpaperEngine/Render/CWallpaper.h"
 #include "WallpaperEngine/Render/FrameMaterial.h"
+#include "WallpaperEngine/Render/LedFrameGrabber.h"
 #include "WallpaperEngine/Render/ShadowMapping.h"
 #include "WallpaperEngine/Render/Volumetrics.h"
 #include "WallpaperEngine/Scripting/ScriptEngine.h"
 
+#include <chrono>
 #include <set>
 #include <unordered_map>
 
@@ -156,7 +158,7 @@ public:
 	std::shared_ptr<const CFBO> fbo;
 	glm::mat4 transform;
 	/** copybackground off: alpha blends with MAX (renderer state flag 0x10) */
-	bool alphaMax;
+	bool alphaMax = false;
 	glm::mat4 viewProjection;
 	/** WE only recomputes the cached view projection lights read once something marks the renderer dirty (+458);
 	 *  the layer doesn't, its first drawn child that isn't a light does */
@@ -271,6 +273,7 @@ protected:
     void loadStaticCamera ();
     void renderFrame (const glm::ivec4& viewport) override;
     void renderFrameSteps (const glm::ivec4& viewport);
+    void feedLeds ();
     void updateMouse (const glm::ivec4& viewport);
     void dispatchCursorEvents ();
 
@@ -353,6 +356,9 @@ private:
     float m_cameraFade = 0.0f;
     FogUniforms m_fog;
     std::unique_ptr<Volumetrics> m_volumetrics;
+    std::unique_ptr<LedFrameGrabber> m_ledGrabber;
+    std::vector<uint8_t> m_ledFrame;
+    std::chrono::steady_clock::time_point m_ledNext = {};
     bool m_fogDistance = false;
     bool m_fogHeight = false;
     bool m_hdr = false;
@@ -424,7 +430,7 @@ private:
     bool m_renderingReflection = false;
     struct OutputSizedBuffer {
 	std::weak_ptr<CFBO> fbo;
-	float divisor;
+	float divisor = 1.0f;
 	const FBO* base = nullptr;
 
 	[[nodiscard]] glm::uvec2 sizeFor (glm::ivec2 output) const;

+ 340 - 13
src/WallpaperEngine/Render/Wallpapers/CSplat.cpp

@@ -23,6 +23,7 @@
 #include "WallpaperEngine/Data/Model/Project.h"
 #include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Data/Model/Wallpaper.h"
+#include "WallpaperEngine/Data/Utils/FloatCompare.h"
 #include "WallpaperEngine/Logging/Log.h"
 #include "WallpaperEngine/Logging/ThreadGuard.h"
 #include "WallpaperEngine/Splat/SogLoader.h"
@@ -209,6 +210,9 @@ uniform vec4 u_ClockParams;
 uniform vec4 u_ClockBounds;
 uniform float u_ClockDistance;
 
+uniform sampler2D u_Ripple;
+uniform vec4 u_RippleParams;
+
 in vec2 a_Corner;
 in uint a_Index;
 
@@ -247,6 +251,22 @@ float clockField (vec2 screen, vec2 maskOffset) {
     return field;
 }
 
+vec4 rippleSample (vec2 uv) {
+    return textureLod (u_Ripple, clamp (uv, vec2 (0.0), vec2 (1.0)), 0.0);
+}
+
+// xy: the offset in screen height units, z and w: how much the splat is in the ripple
+vec4 rippleField (vec2 screen) {
+    vec2 texel = vec2 (u_RippleParams.z / max (1.0, u_RippleParams.w), u_RippleParams.z);
+    vec4 force = (rippleSample (screen) * 2.0 + rippleSample (screen - vec2 (texel.x, 0.0))
+        + rippleSample (screen + vec2 (texel.x, 0.0)) + rippleSample (screen - vec2 (0.0, texel.y))
+        + rippleSample (screen + vec2 (0.0, texel.y))) * 0.1666667;
+    vec2 direction = vec2 (force.r - force.b, force.g - force.a);
+    float amount = clamp (length (direction) * 1.75, 0.0, 1.0);
+
+    return vec4 (-direction * (0.024 * u_RippleParams.y), amount, amount);
+}
+
 void main () {
     ivec2 texel = ivec2 (int (a_Index) % u_TextureWidth, int (a_Index) / u_TextureWidth);
     uvec4 packedCenter = texelFetch (u_Centers, texel, 0);
@@ -307,6 +327,20 @@ void main () {
 
     vec2 screen = vec2 (centerNdc.x * 0.5 + 0.5, 0.5 - centerNdc.y * 0.5);
 
+    vec4 ripple = vec4 (0.0);
+    bool clockMoves = false;
+
+    if (u_RippleParams.x > 0.0) {
+        ripple = rippleField (screen);
+
+        if (ripple.z > 0.001) {
+            float amount = clamp (ripple.z * 0.58, 0.0, 0.74);
+
+            v_Color.rgb = mix (v_Color.rgb, v_Color.rgb * vec3 (1.18, 1.12, 1.04) + vec3 (0.05, 0.06, 0.08), amount);
+            v_Color.a = clamp (v_Color.a * (1.0 + ripple.z * 0.16), 0.0, 1.0);
+        }
+    }
+
     if (u_ClockParams.x > 0.0 && screen.x >= u_ClockBounds.x && screen.y >= u_ClockBounds.y
         && screen.x <= u_ClockBounds.z && screen.y <= u_ClockBounds.w) {
         float radius = u_ClockParams.z;
@@ -322,6 +356,7 @@ void main () {
         }
 
         if (abs (influence) > 0.001) {
+            clockMoves = true;
             float animation = abs (influence);
             float seed = fract (sin ((float (a_Index) * 29.29 + 7.7) * 12.9898) * 43758.5453);
             float liftPhase = smoothstep (0.0, 0.48, animation);
@@ -336,6 +371,10 @@ void main () {
         }
     }
 
+    if (ripple.z > 0.001 && !clockMoves) {
+        ndc += vec2 (ripple.x * 2.0, -ripple.y * 2.0);
+    }
+
     // the engine samples wallpaper textures with row 0 at the top, but a GL render target stores row
     // 0 at the bottom, so the whole frame is drawn upside down here
     gl_Position = vec4 (ndc.x, -ndc.y, clip.z / clip.w, 1.0);
@@ -440,6 +479,7 @@ CSplat::~CSplat () {
     glDeleteTextures (1, &this->m_centerTexture);
     glDeleteTextures (1, &this->m_rotationTexture);
     glDeleteTextures (1, &this->m_scaleTexture);
+    glDeleteTextures (1, &this->m_rippleTexture);
 }
 
 double CSplat::numberProperty (const std::string& name, double fallback) const {
@@ -616,8 +656,9 @@ void CSplat::loadCloud () {
 void CSplat::setupGL (
     const std::vector<float>& centers, const std::vector<float>& rotations, const std::vector<float>& scales
 ) {
+    const size_t rowCount = centers.size () / 4 / this->m_textureWidth;
     const GLsizei width = static_cast<GLsizei> (this->m_textureWidth);
-    const GLsizei height = static_cast<GLsizei> (centers.size () / 4 / this->m_textureWidth);
+    const GLsizei height = static_cast<GLsizei> (rowCount);
 
     const auto makeTexture = [] (GLuint& texture) {
 	glGenTextures (1, &texture);
@@ -677,6 +718,30 @@ void CSplat::setupGL (
     this->u_ClockParams = glGetUniformLocation (this->m_program, "u_ClockParams");
     this->u_ClockBounds = glGetUniformLocation (this->m_program, "u_ClockBounds");
     this->u_ClockDistance = glGetUniformLocation (this->m_program, "u_ClockDistance");
+    this->u_Ripple = glGetUniformLocation (this->m_program, "u_Ripple");
+    this->u_RippleParams = glGetUniformLocation (this->m_program, "u_RippleParams");
+
+    for (auto& field : this->m_rippleForces) {
+	field.assign (RIPPLE_SIZE * RIPPLE_SIZE, 0.0f);
+    }
+
+    for (auto& field : this->m_rippleNext) {
+	field.assign (RIPPLE_SIZE * RIPPLE_SIZE, 0.0f);
+    }
+
+    this->m_ripplePixels.assign (RIPPLE_SIZE * RIPPLE_SIZE * 4, 0);
+
+    // row 0 is the top of the screen, like the page's texture
+    glGenTextures (1, &this->m_rippleTexture);
+    glBindTexture (GL_TEXTURE_2D, this->m_rippleTexture);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+    glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+    glTexImage2D (
+	GL_TEXTURE_2D, 0, GL_RGBA8, RIPPLE_SIZE, RIPPLE_SIZE, 0, GL_RGBA, GL_UNSIGNED_BYTE, this->m_ripplePixels.data ()
+    );
+    glBindTexture (GL_TEXTURE_2D, 0);
 
     const GLint cornerAttribute = glGetAttribLocation (this->m_program, "a_Corner");
     const GLint indexAttribute = glGetAttribLocation (this->m_program, "a_Index");
@@ -708,9 +773,10 @@ void CSplat::resizeOutput (int width, int height) {
     this->m_hasBase = false;
     this->m_hasDrawn = false;
 
-    glBindTexture (GL_TEXTURE_2D, this->getWallpaperTexture ());
-    glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
-    glBindTexture (GL_TEXTURE_2D, 0);
+    // the frame buffer object keeps its own idea of its size (screenshots and the output pass read it)
+    if (const auto fbo = this->find ("_rt_FullFrameBuffer"); fbo != nullptr) {
+	fbo->resize (width, height);
+    }
 }
 
 std::vector<CSplat::ClockPoint> CSplat::buildClockPoints (
@@ -795,7 +861,7 @@ bool CSplat::updateClock (float aspect) {
     constexpr float TRANSITION_SECONDS = 0.82f;
     constexpr float BASE_RADIUS = 0.011f;
 
-    const bool enabled = this->numberProperty ("clockEnabled", 1.0) != 0.0;
+    const bool enabled = WallpaperEngine::Data::Utils::isNonZero (this->numberProperty ("clockEnabled", 1.0));
     const float size = std::clamp (static_cast<float> (this->numberProperty ("clockSize", 1.0)), 0.55f, 1.8f);
     const float x = std::clamp (static_cast<float> (this->numberProperty ("clockX", 50.0)), 8.0f, 92.0f);
     const float y = std::clamp (static_cast<float> (this->numberProperty ("clockY", 18.0)), 8.0f, 92.0f);
@@ -899,8 +965,8 @@ bool CSplat::updateClock (float aspect) {
     }
 
     const glm::vec4 params (active ? 1.0f : 0.0f, lift, radius, std::max (1.0f, aspect));
-    const bool changed
-	= points != this->m_clockPoints || params != this->m_clockParams || distance != this->m_clockDistance;
+    const bool changed = points != this->m_clockPoints || params != this->m_clockParams
+	|| !WallpaperEngine::Data::Utils::sameFloat (distance, this->m_clockDistance);
 
     this->m_clockPoints = points;
     this->m_clockParams = params;
@@ -910,6 +976,227 @@ bool CSplat::updateClock (float aspect) {
     return changed;
 }
 
+void CSplat::resetRipple () {
+    for (auto& field : this->m_rippleForces) {
+	std::fill (field.begin (), field.end (), 0.0f);
+    }
+
+    for (auto& field : this->m_rippleNext) {
+	std::fill (field.begin (), field.end (), 0.0f);
+    }
+
+    this->m_rippleEnergy = 0.0f;
+    this->m_ripplePhase = 0;
+    this->m_rippleActive = false;
+    this->m_trailLast.reset ();
+    this->m_trailCursor.reset ();
+    this->uploadRipple ();
+}
+
+void CSplat::uploadRipple () {
+    for (int index = 0; index < RIPPLE_SIZE * RIPPLE_SIZE; index++) {
+	for (int channel = 0; channel < 4; channel++) {
+	    this->m_ripplePixels[index * 4 + channel] = static_cast<uint8_t> (
+		std::lround (std::clamp (this->m_rippleForces[channel][index], 0.0f, 1.0f) * 255.0f)
+	    );
+	}
+    }
+
+    glBindTexture (GL_TEXTURE_2D, this->m_rippleTexture);
+    glTexSubImage2D (
+	GL_TEXTURE_2D, 0, 0, 0, RIPPLE_SIZE, RIPPLE_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, this->m_ripplePixels.data ()
+    );
+    glBindTexture (GL_TEXTURE_2D, 0);
+}
+
+void CSplat::addRippleImpulse (const TrailPoint& point, const TrailPoint& previous, float energy) {
+    constexpr float radius = 0.065f;
+    constexpr int size = RIPPLE_SIZE;
+
+    const float x0 = std::clamp (previous.x, 0.0f, 1.0f) * (size - 1);
+    const float y0 = std::clamp (previous.y, 0.0f, 1.0f) * (size - 1);
+    const float x1 = std::clamp (point.x, 0.0f, 1.0f) * (size - 1);
+    const float y1 = std::clamp (point.y, 0.0f, 1.0f) * (size - 1);
+    const float dx = x1 - x0;
+    const float dy = y1 - y0;
+    const float lengthSquared = std::max (0.0001f, dx * dx + dy * dy);
+    const float radiusPixels = std::max (2.0f, std::min (13.0f, std::clamp (radius, 0.02f, 0.12f) * size));
+    const float impulse = std::clamp (energy, 0.0f, 2.8f) * 0.72f;
+    const int minX = std::max (1, static_cast<int> (std::floor (std::min (x0, x1) - radiusPixels)));
+    const int maxX = std::min (size - 2, static_cast<int> (std::ceil (std::max (x0, x1) + radiusPixels)));
+    const int minY = std::max (1, static_cast<int> (std::floor (std::min (y0, y1) - radiusPixels)));
+    const int maxY = std::min (size - 2, static_cast<int> (std::ceil (std::max (y0, y1) + radiusPixels)));
+
+    for (int py = minY; py <= maxY; py++) {
+	const auto pointY = static_cast<float> (py);
+
+	for (int px = minX; px <= maxX; px++) {
+	    const auto pointX = static_cast<float> (px);
+	    const float t = std::clamp (((pointX - x0) * dx + (pointY - y0) * dy) / lengthSquared, 0.0f, 1.0f);
+	    const float closestX = x0 + dx * t;
+	    const float closestY = y0 + dy * t;
+	    const float distance = std::hypot (pointX - closestX, pointY - closestY);
+
+	    if (distance > radiusPixels) {
+		continue;
+	    }
+
+	    const float edge = 1.0f - distance / radiusPixels;
+	    const float radialX = (pointX - closestX) / radiusPixels;
+	    const float radialY = (pointY - closestY) / radiusPixels;
+	    const float radialLength = std::max (0.0001f, std::hypot (radialX, radialY));
+	    const float normalizedX = radialX / radialLength;
+	    const float normalizedY = radialY / radialLength;
+	    const float force = impulse * edge * std::min (1.0f, radialLength * 1.85f);
+	    const int index = py * size + px;
+
+	    this->m_rippleForces[0][index]
+		= std::min (1.0f, this->m_rippleForces[0][index] + std::max (0.0f, normalizedX) * force);
+	    this->m_rippleForces[1][index]
+		= std::min (1.0f, this->m_rippleForces[1][index] + std::max (0.0f, normalizedY) * force);
+	    this->m_rippleForces[2][index]
+		= std::min (1.0f, this->m_rippleForces[2][index] + std::max (0.0f, -normalizedX) * force);
+	    this->m_rippleForces[3][index]
+		= std::min (1.0f, this->m_rippleForces[3][index] + std::max (0.0f, -normalizedY) * force);
+	}
+    }
+
+    this->m_rippleEnergy = std::max (this->m_rippleEnergy, impulse);
+    this->m_rippleActive = true;
+}
+
+// the viewer's stepRippleField, once per drawn frame while there is energy: every force spreads to the three cells
+// next to it in its direction (a checkerboard of cells per step) and loses 0.0048
+void CSplat::stepRipple () {
+    constexpr int size = RIPPLE_SIZE;
+    constexpr float decay = 0.0048f;
+    float maxEnergy = 0.0f;
+
+    this->m_ripplePhase = 1 - this->m_ripplePhase;
+
+    const auto sampleMax = [] (const std::vector<float>& field, int a, int b, int c) {
+	return std::max ({ field[a], field[b], field[c] });
+    };
+
+    auto& [right, down, left, up] = this->m_rippleForces;
+    auto& [nextRight, nextDown, nextLeft, nextUp] = this->m_rippleNext;
+
+    for (int y = 1; y < size - 1; y++) {
+	const int row = y * size;
+
+	for (int x = 1; x < size - 1; x++) {
+	    const int index = row + x;
+
+	    if (((x + y) & 1) != this->m_ripplePhase) {
+		nextRight[index] = right[index];
+		nextDown[index] = down[index];
+		nextLeft[index] = left[index];
+		nextUp[index] = up[index];
+		maxEnergy = std::max (maxEnergy, right[index] + down[index] + left[index] + up[index]);
+		continue;
+	    }
+
+	    const int above = index - size;
+	    const int below = index + size;
+	    const int before = index - 1;
+	    const int after = index + 1;
+	    const int aboveBefore = above - 1;
+	    const int aboveAfter = above + 1;
+	    const int belowBefore = below - 1;
+	    const int belowAfter = below + 1;
+
+	    const float upR = sampleMax (right, above, aboveBefore, aboveAfter);
+	    const float upD = sampleMax (down, above, aboveBefore, aboveAfter);
+	    const float upL = sampleMax (left, above, aboveBefore, aboveAfter);
+	    const float downR = sampleMax (right, below, belowBefore, belowAfter);
+	    const float downL = sampleMax (left, below, belowBefore, belowAfter);
+	    const float downU = sampleMax (up, below, belowBefore, belowAfter);
+	    const float leftR = sampleMax (right, before, aboveBefore, belowBefore);
+	    const float leftD = sampleMax (down, before, aboveBefore, belowBefore);
+	    const float leftU = sampleMax (up, before, aboveBefore, belowBefore);
+	    const float rightD = sampleMax (down, after, aboveAfter, belowAfter);
+	    const float rightL = sampleMax (left, after, aboveAfter, belowAfter);
+	    const float rightU = sampleMax (up, after, aboveAfter, belowAfter);
+
+	    const float forceRight = std::clamp ((upR + downR + leftR) / 3.0f - decay, 0.0f, 1.0f);
+	    const float forceDown = std::clamp ((upD + leftD + rightD) / 3.0f - decay, 0.0f, 1.0f);
+	    const float forceLeft = std::clamp ((upL + downL + rightL) / 3.0f - decay, 0.0f, 1.0f);
+	    const float forceUp = std::clamp ((downU + leftU + rightU) / 3.0f - decay, 0.0f, 1.0f);
+
+	    nextRight[index] = forceRight;
+	    nextDown[index] = forceDown;
+	    nextLeft[index] = forceLeft;
+	    nextUp[index] = forceUp;
+	    maxEnergy = std::max (maxEnergy, forceRight + forceDown + forceLeft + forceUp);
+	}
+    }
+
+    for (auto& field : this->m_rippleNext) {
+	std::fill (field.begin (), field.begin () + size, 0.0f);
+	std::fill (field.begin () + (size - 1) * size, field.end (), 0.0f);
+
+	for (int y = 1; y < size - 1; y++) {
+	    field[y * size] = 0.0f;
+	    field[y * size + size - 1] = 0.0f;
+	}
+    }
+
+    for (size_t channel = 0; channel < this->m_rippleForces.size (); channel++) {
+	this->m_rippleForces[channel] = this->m_rippleNext[channel];
+    }
+
+    this->m_rippleEnergy = maxEnergy;
+    this->m_rippleActive = maxEnergy > 0.0012f;
+    this->uploadRipple ();
+}
+
+// the page's recordMouseTrail for one movement of the pointer: how fast and how suddenly it moved decides the
+// energy, only a sudden movement (acceleration over 15000 px/s^2) makes a ripple
+void CSplat::trackMouseTrail (const glm::dvec2& normalized, std::chrono::steady_clock::time_point now) {
+    constexpr float minimumDistance = 2.0f;
+    constexpr float accelerationThreshold = 15000.0f;
+
+    const auto width = static_cast<float> (std::max (this->m_width, 1));
+    const auto height = static_cast<float> (std::max (this->m_height, 1));
+    TrailPoint point;
+
+    point.x = static_cast<float> (std::clamp (normalized.x, 0.0, 1.0));
+    point.y = static_cast<float> (std::clamp (normalized.y, 0.0, 1.0));
+    point.time = now;
+
+    const std::optional<TrailPoint> previous
+	= this->m_trailLast && now - this->m_trailLast->time <= std::chrono::milliseconds (120) ? this->m_trailLast
+												: std::nullopt;
+    const float pixelDistance = previous
+	? std::hypot ((point.x - previous->x) * width, (point.y - previous->y) * height)
+	: std::numeric_limits<float>::infinity ();
+
+    if (previous && pixelDistance < minimumDistance && now - previous->time < std::chrono::milliseconds (24)) {
+	return;
+    }
+
+    const float dt = previous
+	? std::clamp (std::chrono::duration<float> (now - previous->time).count (), 1.0f / 120.0f, 0.12f)
+	: 1.0f / 60.0f;
+
+    point.velocityX = previous ? (point.x - previous->x) * width / dt : 0.0f;
+    point.velocityY = previous ? (point.y - previous->y) * height / dt : 0.0f;
+
+    const float speed = std::hypot (point.velocityX, point.velocityY);
+    const float acceleration = previous
+	? std::hypot (point.velocityX - previous->velocityX, point.velocityY - previous->velocityY) / dt
+	: 0.0f;
+    const float speedEnergy = std::min (1.0f, speed / 1400.0f);
+    const float accelerationEnergy = std::min (1.1f, acceleration / 16500.0f);
+    const float energy = std::clamp (speedEnergy + accelerationEnergy, previous ? 0.18f : 0.08f, 1.85f);
+
+    this->m_trailLast = point;
+
+    if (previous && acceleration >= accelerationThreshold) {
+	this->addRippleImpulse (point, *previous, energy);
+    }
+}
+
 CSplat::BaseCamera CSplat::buildBaseCamera (int width, int height, float focusDepth) const {
     const SceneProfile& profile = this->m_profile;
     BaseCamera base;
@@ -1080,16 +1367,29 @@ void CSplat::renderFrame (const glm::ivec4& viewport) {
 	return;
     }
 
-    if (viewport.z != this->m_width || viewport.w != this->m_height) {
-	this->resizeOutput (viewport.z, viewport.w);
+    const bool performanceMode
+	= WallpaperEngine::Data::Utils::isNonZero (this->numberProperty ("performanceMode", 1.0));
+    const int targetWidth = performanceMode ? (viewport.z + 1) / 2 : viewport.z;
+    const int targetHeight = performanceMode ? (viewport.w + 1) / 2 : viewport.w;
+
+    if (targetWidth != this->m_width || targetHeight != this->m_height) {
+	this->resizeOutput (targetWidth, targetHeight);
     }
 
-    const bool depthEnabled = this->numberProperty ("depthEnabled", 1.0) != 0.0;
+    const bool depthEnabled = WallpaperEngine::Data::Utils::isNonZero (this->numberProperty ("depthEnabled", 1.0));
     const float focusDepth = static_cast<float> (this->numberProperty ("focusDepth", 30.0));
+    const float fovProperty = static_cast<float> (this->numberProperty ("cameraFov", 60.0));
 
     if (!this->m_hasBase || this->m_base.viewport != glm::ivec2 (this->m_width, this->m_height)
-	|| this->m_base.focusDepth != focusDepth) {
+	|| !WallpaperEngine::Data::Utils::sameFloat (this->m_base.focusDepth, focusDepth)
+	|| !WallpaperEngine::Data::Utils::sameFloat (this->m_base.fovProperty, fovProperty)) {
 	this->m_base = this->buildBaseCamera (this->m_width, this->m_height, focusDepth);
+	this->m_base.fovProperty = fovProperty;
+
+	if (std::abs (fovProperty - 60.0f) > 1e-3f) {
+	    this->m_base.fov = std::clamp (fovProperty, 20.0f, 120.0f);
+	}
+
 	this->m_hasBase = true;
     }
 
@@ -1103,6 +1403,21 @@ void CSplat::renderFrame (const glm::ivec4& viewport) {
     glm::vec2 targetTilt (0.0f);
     const auto& settings = this->getContext ().getApp ().getContext ().settings;
 
+    if (WallpaperEngine::Data::Utils::isNonZero (this->numberProperty ("mouseTrailEnabled", 1.0))) {
+	const glm::dvec2 mouse = this->cursorPosition ();
+
+	if (!this->m_trailCursor.has_value () || *this->m_trailCursor != mouse) {
+	    this->m_trailCursor = mouse;
+	    this->trackMouseTrail ({ (mouse.x - viewport.x) / viewport.z, (mouse.y - viewport.y) / viewport.w }, now);
+	}
+
+	if (this->m_rippleActive) {
+	    this->stepRipple ();
+	}
+    } else if (this->m_rippleActive || this->m_trailLast.has_value ()) {
+	this->resetRipple ();
+    }
+
     if (depthEnabled && !settings.mouse.disableparallax) {
 	const glm::dvec2 mouse = this->cursorPosition ();
 	const float sensitivity = static_cast<float> (this->numberProperty ("sensorSensitivity", 4.0)) / 4.0f;
@@ -1133,7 +1448,7 @@ void CSplat::renderFrame (const glm::ivec4& viewport) {
 
     glm::vec2 orbit (0.0f);
 
-    if (depthEnabled && this->numberProperty ("orbitEnabled", 0.0) != 0.0) {
+    if (depthEnabled && WallpaperEngine::Data::Utils::isNonZero (this->numberProperty ("orbitEnabled", 0.0))) {
 	const float speed = static_cast<float> (this->numberProperty ("orbitSpeed", 0.12));
 	const float amount = static_cast<float> (this->numberProperty ("orbitAmount", 0.34));
 
@@ -1199,8 +1514,12 @@ void CSplat::renderFrame (const glm::ivec4& viewport) {
     const bool clockChanged
 	= this->updateClock (static_cast<float> (this->m_width) / static_cast<float> (this->m_height));
 
+    const bool rippleChanged = this->m_rippleActive || this->m_rippleWasActive;
+
+    this->m_rippleWasActive = this->m_rippleActive;
+
     // a still camera and clock produce the exact same frame, which is still sitting in the output texture
-    if (this->m_hasDrawn && !haveNewOrder && !clockChanged && view == this->m_drawnView
+    if (this->m_hasDrawn && !haveNewOrder && !clockChanged && !rippleChanged && view == this->m_drawnView
 	&& projection == this->m_drawnProjection) {
 	return;
     }
@@ -1236,6 +1555,14 @@ void CSplat::renderFrame (const glm::ivec4& viewport) {
     glUniform1i (this->u_Centers, 0);
     glUniform1i (this->u_Rotations, 1);
     glUniform1i (this->u_Scales, 2);
+    glActiveTexture (GL_TEXTURE3);
+    glBindTexture (GL_TEXTURE_2D, this->m_rippleTexture);
+    glUniform1i (this->u_Ripple, 3);
+    glUniform4f (
+	this->u_RippleParams, this->m_rippleActive ? 1.0f : 0.0f, 2.85f, 1.0f / RIPPLE_SIZE,
+	std::max (1.0f, static_cast<float> (viewport.z) / static_cast<float> (std::max (viewport.w, 1)))
+    );
+    glActiveTexture (GL_TEXTURE0);
     glUniformMatrix4fv (this->u_View, 1, GL_FALSE, glm::value_ptr (view));
     glUniformMatrix4fv (this->u_Projection, 1, GL_FALSE, glm::value_ptr (projection));
     glUniform2f (this->u_Viewport, static_cast<float> (this->m_width), static_cast<float> (this->m_height));

+ 32 - 0
src/WallpaperEngine/Render/Wallpapers/CSplat.h

@@ -3,6 +3,7 @@
 #include <array>
 #include <chrono>
 #include <memory>
+#include <optional>
 #include <string>
 #include <vector>
 
@@ -58,6 +59,7 @@ private:
 	float fov = 60.0f;
 	glm::ivec2 viewport = {};
 	float focusDepth = 0.0f;
+	float fovProperty = 60.0f;
     };
 
     struct Pose {
@@ -75,6 +77,15 @@ private:
     };
 
     static constexpr size_t CLOCK_POINT_CAPACITY = 32;
+    static constexpr int RIPPLE_SIZE = 96;
+
+    struct TrailPoint {
+	float x = 0.0f;
+	float y = 0.0f;
+	std::chrono::steady_clock::time_point time = {};
+	float velocityX = 0.0f;
+	float velocityY = 0.0f;
+    };
 
     void loadCloud ();
     void
@@ -85,6 +96,12 @@ private:
     buildClockPoints (const std::string& text, float aspect, float size, float originX, float originY) const;
     bool updateClock (float aspect);
 
+    void resetRipple ();
+    void addRippleImpulse (const TrailPoint& point, const TrailPoint& previous, float energy);
+    void stepRipple ();
+    void uploadRipple ();
+    void trackMouseTrail (const glm::dvec2& normalized, std::chrono::steady_clock::time_point now);
+
     BaseCamera buildBaseCamera (int width, int height, float focusDepth) const;
     Pose posePlacement (const BaseCamera& base, glm::vec2 tilt, glm::vec2 orbit, float parallaxStrength) const;
     bool viewFitsFrontFace (const glm::vec3& position, const glm::vec3& target, const BaseCamera& base) const;
@@ -123,6 +140,9 @@ private:
     GLint u_ClockParams = -1;
     GLint u_ClockBounds = -1;
     GLint u_ClockDistance = -1;
+    GLint u_Ripple = -1;
+    GLint u_RippleParams = -1;
+    GLuint m_rippleTexture = GL_NONE;
 
     int m_width = 16;
     int m_height = 17;
@@ -137,6 +157,18 @@ private:
     glm::vec4 m_clockBounds = {};
     float m_clockDistance = 0.0f;
 
+    std::array<std::vector<float>, 4> m_rippleForces;
+    std::array<std::vector<float>, 4> m_rippleNext;
+    std::vector<uint8_t> m_ripplePixels;
+    float m_rippleEnergy = 0.0f;
+    int m_ripplePhase = 0;
+    // the shader only looks at the field while this is set (WE page: tianyinRippleParams.x)
+    bool m_rippleActive = false;
+    // one more frame is needed after the field went quiet, to draw it without
+    bool m_rippleWasActive = false;
+    std::optional<TrailPoint> m_trailLast;
+    std::optional<glm::dvec2> m_trailCursor;
+
     glm::vec2 m_tilt = {};
     float m_orbitPhase = 0.0f;
     std::chrono::steady_clock::time_point m_lastFrame = {};

+ 246 - 25
src/WallpaperEngine/Render/Wallpapers/CVideo.cpp

@@ -7,6 +7,8 @@
 
 #include <algorithm>
 #include <cmath>
+#include <ranges>
+#include <vector>
 
 using namespace WallpaperEngine;
 using namespace WallpaperEngine::Render;
@@ -24,12 +26,26 @@ CVideo::CVideo (
     this->setupFramebuffers (false, hdr ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888);
     this->setLinearInput (hdr);
 
-    const std::filesystem::path videopath
-	= this->getVideo ().project.assetLocator->physicalPath (this->getVideo ().filename);
+    this->m_path = this->getVideo ().project.assetLocator->physicalPath (this->getVideo ().filename);
+    this->m_segments = normalizeSegments (this->getContext ().getApp ().getContext ().settings.render.videoSegments);
 
+    if (const auto it = s_sources.find (this->m_path); it != s_sources.end () && it->second->m_hdr == hdr
+	&& it->second->m_loop && it->second->m_segments == this->m_segments) {
+	this->m_source = it->second;
+	this->m_source->m_sharers.push_back (this);
+	this->m_source->m_player->setRenderOnlyNew (true);
+	sLog.out ("Video ", this->m_path.filename ().string (), " shares the decoder of another output");
+	return;
+    }
+
+    this->createPlayer ();
+    s_sources.emplace (this->m_path, this);
+}
+
+void CVideo::createPlayer () {
     // starts at a small framebuffer size; resized once mpv starts playback and reports the real resolution
     this->m_player = std::make_unique<GLPlayer> (
-	this->getContext (), this->CWallpaper::getWallpaperTexture (), videopath, 64, 64,
+	this->getContext (), this->CWallpaper::getWallpaperTexture (), this->m_path, 64, 64,
 	this->CWallpaper::getWallpaperFramebuffer ()
     );
     // --silent and a volume of 0 mute mpv too
@@ -37,21 +53,87 @@ CVideo::CVideo (
     this->m_player->setVolume (audioSettings.enabled ? audioSettings.volume * 100.0 / 128.0 : 0.0);
     const auto& renderSettings = this->getContext ().getApp ().getContext ().settings.render;
     this->m_player->setSpeed (renderSettings.playbackSpeed);
-    this->setSegments (renderSettings.videoSegments);
+    this->m_player->setSegments (this->m_segments);
+
+    if (!this->m_loop) {
+	this->m_player->setLoop (false);
+    }
 
-    if (hdr) {
+    if (this->m_hdr) {
 	this->m_player->setLinearOutput ();
     }
+
+    this->m_muted = false;
     // needs at least one usage marked for the video to actually start playing
     this->m_player->incrementUsageCount ();
+    this->applyPause ();
 }
 
-CVideo::~CVideo () { this->m_player->decrementUsageCount (); }
+CVideo::~CVideo () {
+    if (this->m_source != nullptr) {
+	std::erase (this->m_source->m_sharers, this);
 
-void CVideo::renderFrame (const glm::ivec4& viewport) {
-    this->updateMuteState ();
+	if (this->m_source->m_sharers.empty ()) {
+	    this->m_source->m_player->setRenderOnlyNew (false);
+	}
 
-    this->m_presentBackBuffer = false;
+	return;
+    }
+
+    if (const auto it = s_sources.find (this->m_path); it != s_sources.end () && it->second == this) {
+	s_sources.erase (it);
+    }
+
+    if (!this->m_sharers.empty ()) {
+	// the first sharer that can start a decoder takes the video over while this player still plays, so it starts at
+	// the same spot; one that can't is left without video rather than letting the exception out of a destructor
+	const std::vector<CVideo*> sharers = std::move (this->m_sharers);
+	this->m_sharers.clear ();
+	CVideo* heir = nullptr;
+	std::size_t next = 0;
+
+	for (CVideo* candidate : sharers) {
+	    next++;
+	    candidate->m_source = nullptr;
+
+	    try {
+		candidate->createPlayer ();
+		heir = candidate;
+		break;
+	    } catch (const std::exception& e) {
+		sLog.error (
+		    "Video ", this->m_path.filename ().string (), " could not take over the decoder: ", e.what ()
+		);
+		candidate->m_player.reset ();
+	    }
+	}
+
+	if (heir != nullptr) {
+	    for (CVideo* other : sharers | std::views::drop (next)) {
+		other->m_source = heir;
+		heir->m_sharers.push_back (other);
+	    }
+
+	    if (!heir->m_sharers.empty ()) {
+		heir->m_player->setRenderOnlyNew (true);
+	    }
+
+	    heir->applyPause ();
+	    s_sources[this->m_path] = heir;
+	}
+    }
+
+    if (this->m_player) {
+	this->m_player->decrementUsageCount ();
+    }
+}
+
+void CVideo::drivePlayer () {
+    if (!this->m_player) {
+	return;
+    }
+
+    this->updateMuteState ();
     // WE draws a video wallpaper as the texture of materials/background.json, shown every frame
     this->m_player->markUsed ();
     this->m_player->render ();
@@ -64,21 +146,108 @@ void CVideo::renderFrame (const glm::ivec4& viewport) {
 	this->m_player->requestRedraw ();
 	this->m_player->render ();
     }
+}
+
+void CVideo::copyFromSource () {
+    CVideo& source = *this->m_source;
+
+    source.drivePlayer ();
+
+    const int width = this->getWidth ();
+    const int height = this->getHeight ();
+
+    if (const auto fbo = this->find ("_rt_FullFrameBuffer"); fbo != nullptr
+	&& (static_cast<int> (fbo->getRealWidth ()) != width || static_cast<int> (fbo->getRealHeight ()) != height)) {
+	fbo->resize (width, height);
+    }
+
+    GLboolean mask[4] {};
+    const GLboolean scissor = glIsEnabled (GL_SCISSOR_TEST);
+
+    glGetBooleanv (GL_COLOR_WRITEMASK, mask);
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+    glDisable (GL_SCISSOR_TEST);
+    glBindFramebuffer (GL_READ_FRAMEBUFFER, source.CWallpaper::getWallpaperFramebuffer ());
+    glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->CWallpaper::getWallpaperFramebuffer ());
+    glBlitFramebuffer (0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
+    glBindFramebuffer (GL_FRAMEBUFFER, this->CWallpaper::getWallpaperFramebuffer ());
+    glColorMask (mask[0], mask[1], mask[2], mask[3]);
+
+    if (scissor) {
+	glEnable (GL_SCISSOR_TEST);
+    }
+}
+
+void CVideo::renderFrame (const glm::ivec4& viewport) {
+    this->m_presentBackBuffer = false;
+
+    if (this->m_source != nullptr) {
+	this->copyFromSource ();
+    } else {
+	this->drivePlayer ();
+    }
 
     if (!this->m_hdr) {
 	this->renderImageAdjustments ({ this->getWidth (), this->getHeight () }, GL_RGBA8);
     }
 }
 
+void CVideo::unshare () {
+    CVideo& source = *this->m_source;
+
+    this->m_source = nullptr;
+    this->createPlayer ();
+    std::erase (source.m_sharers, this);
+
+    if (source.m_sharers.empty ()) {
+	source.m_player->setRenderOnlyNew (false);
+    }
+
+    source.applyPause ();
+}
+
+void CVideo::applyPause () {
+    if (!this->m_player) {
+	return;
+    }
+
+    bool all = this->m_wantsPause;
+
+    for (const CVideo* sharer : this->m_sharers) {
+	all = all && sharer->m_wantsPause;
+    }
+
+    if (all) {
+	this->m_player->setPaused ();
+    } else {
+	this->m_player->clearPaused ();
+    }
+}
+
+void CVideo::reconcileSharers () {
+    const auto sharers = this->m_sharers;
+
+    for (CVideo* sharer : sharers) {
+	if (sharer->m_loop != this->m_loop || sharer->m_segments != this->m_segments) {
+	    sharer->unshare ();
+	}
+    }
+}
+
 void CVideo::updateMuteState () {
     if (!this->getContext ().getApp ().getContext ().settings.audio.enabled) {
 	return;
     }
 
-    const bool desiredMuted
-	= this->m_forceMuted || this->getAudioContext ().getDriver ().getAudioDetector ().anythingPlaying ();
+    bool forced = this->m_forceMuted;
+
+    for (const CVideo* sharer : this->m_sharers) {
+	forced = forced && sharer->m_forceMuted;
+    }
+
+    const bool desiredMuted = forced || this->getAudioContext ().getDriver ().getAudioDetector ().anythingPlaying ();
 
-    if (this->m_muted == desiredMuted) {
+    if (!this->m_player || this->m_muted == desiredMuted) {
 	return;
     }
 
@@ -93,28 +262,69 @@ void CVideo::updateMuteState () {
 
 void CVideo::setAudioPolicy (bool muted, std::optional<int> ambientVolume) {
     this->m_forceMuted = muted;
-    this->updateMuteState ();
+    this->root ().updateMuteState ();
 }
 
 const Data::Model::Video& CVideo::getVideo () const { return *this->getWallpaperData ().as<Data::Model::Video> (); }
 
-void CVideo::setVolume (double volume) { this->m_player->setVolume (volume); }
+void CVideo::setVolume (double volume) {
+    if (const auto& player = this->root ().m_player) {
+	player->setVolume (volume);
+    }
+}
 
-void CVideo::setSpeed (double speed) { this->m_player->setSpeed (speed); }
+void CVideo::setSpeed (double speed) {
+    if (const auto& player = this->root ().m_player) {
+	player->setSpeed (speed);
+    }
+}
 
 void CVideo::setLoop (const bool loop) {
-    if (this->m_player->isLooping () != loop) {
+    this->m_loop = loop;
+
+    if (this->m_source != nullptr) {
+	if (this->m_source->m_loop != loop) {
+	    this->unshare ();
+	}
+
+	return;
+    }
+
+    if (this->m_player && this->m_player->isLooping () != loop) {
 	this->m_player->setLoop (loop);
     }
+
+    this->reconcileSharers ();
 }
 
-bool CVideo::hasEnded () const { return this->m_player->hasEnded (); }
+bool CVideo::hasEnded () const {
+    const auto& player = this->root ().m_player;
+    return player && player->hasEnded ();
+}
 
 void CVideo::setSegments (const VideoPlayback::VideoSegments& segments) {
-    this->m_player->setSegments (normalizeSegments (segments));
+    this->m_segments = normalizeSegments (segments);
+
+    if (this->m_source != nullptr) {
+	if (this->m_source->m_segments != this->m_segments) {
+	    this->unshare ();
+	}
+
+	return;
+    }
+
+    if (this->m_player) {
+	this->m_player->setSegments (this->m_segments);
+    }
+
+    this->reconcileSharers ();
 }
 
-void CVideo::seek (const double seconds) { this->m_player->seek (seconds); }
+void CVideo::seek (const double seconds) {
+    if (const auto& player = this->root ().m_player) {
+	player->seek (seconds);
+    }
+}
 
 std::optional<double> CVideo::parseTime (const std::string& value) {
     double seconds = 0.0;
@@ -238,13 +448,24 @@ VideoPlayback::VideoSegments CVideo::normalizeSegments (VideoPlayback::VideoSegm
 }
 
 void CVideo::setPause (bool newState) {
-    if (newState) {
-	this->m_player->setPaused ();
-    } else {
-	this->m_player->clearPaused ();
+    this->m_wantsPause = newState;
+    this->root ().applyPause ();
+}
+
+int CVideo::getWidth () const {
+    if (this->m_player) {
+	return this->m_player->getWidth ();
     }
+
+    return this->m_source != nullptr ? this->m_source->getWidth () : 16;
 }
 
-int CVideo::getWidth () const { return this->m_player ? this->m_player->getWidth () : 16; }
+int CVideo::getHeight () const {
+    if (this->m_player) {
+	return this->m_player->getHeight ();
+    }
+
+    return this->m_source != nullptr ? this->m_source->getHeight () : 16;
+}
 
-int CVideo::getHeight () const { return this->m_player ? this->m_player->getHeight () : 16; }
+std::unordered_map<std::filesystem::path, CVideo*> CVideo::s_sources;

+ 20 - 0
src/WallpaperEngine/Render/Wallpapers/CVideo.h

@@ -4,6 +4,10 @@
 #include "WallpaperEngine/Render/CWallpaper.h"
 #include "WallpaperEngine/VideoPlayback/MPV/GLPlayer.h"
 
+#include <filesystem>
+#include <unordered_map>
+#include <vector>
+
 namespace WallpaperEngine::Render::Wallpapers {
 using namespace WallpaperEngine::VideoPlayback::MPV;
 
@@ -53,8 +57,24 @@ protected:
 
 private:
     void updateMuteState ();
+    CVideo& root () { return this->m_source != nullptr ? *this->m_source : *this; }
+    [[nodiscard]] const CVideo& root () const { return this->m_source != nullptr ? *this->m_source : *this; }
+    void drivePlayer ();
+    void unshare ();
+    void createPlayer ();
+    void applyPause ();
+    void reconcileSharers ();
+    void copyFromSource ();
 
     GLPlayerUniquePtr m_player;
+    std::filesystem::path m_path;
+    CVideo* m_source = nullptr;
+    std::vector<CVideo*> m_sharers;
+    bool m_loop = true;
+    bool m_wantsPause = false;
+    VideoPlayback::VideoSegments m_segments;
+
+    static std::unordered_map<std::filesystem::path, CVideo*> s_sources;
 
     bool m_hdr = false;
     bool m_muted = false;

Vissa filer visades inte eftersom för många filer har ändrats