From 6a540541b3fbb1271615207ce2a2909a5948d48c Mon Sep 17 00:00:00 2001 From: arcu1tus Date: Sun, 29 Nov 2026 18:28:53 +0100 Subject: [PATCH 1/2] feat(glass): add on/off resource benchmark and baseline results `just glass bench` toggles only the fluctusglass effect (stock Blur stays loaded), drives idle / window drag / video / pointer scenarios with mpv and KWin scripts, and records kwin and plasmashell CPU time, memory and NVIDIA board power. Results from before and after the audit fixes are in glass/docs/performance.md, raw data under glass/tools/bench/results/. Co-Authored-By: Claude Opus 5.5 --- glass/docs/README.md | 2 + glass/docs/performance.md | 86 +++++ glass/justfile | 4 + glass/tools/bench/Cover.qml | 31 ++ glass/tools/bench/Drag.qml | 53 ++++ glass/tools/bench/bench.py | 297 ++++++++++++++++++ glass/tools/bench/probe.js | 13 + .../results/2026-11-29-after-fixes/main.json | 194 ++++++++++++ .../tools/bench/results/2026-11-29/main.json | 194 ++++++++++++ .../results/2026-11-29/video-behind-dock.json | 50 +++ 10 files changed, 924 insertions(+) create mode 100644 glass/docs/performance.md create mode 100644 glass/tools/bench/Cover.qml create mode 100644 glass/tools/bench/Drag.qml create mode 100755 glass/tools/bench/bench.py create mode 100644 glass/tools/bench/probe.js create mode 100644 glass/tools/bench/results/2026-11-29-after-fixes/main.json create mode 100644 glass/tools/bench/results/2026-11-29/main.json create mode 100644 glass/tools/bench/results/2026-11-29/video-behind-dock.json diff --git a/glass/docs/README.md b/glass/docs/README.md index d91cd54..353f285 100644 --- a/glass/docs/README.md +++ b/glass/docs/README.md @@ -8,6 +8,8 @@ The deep material behind [Fluctus Glass](../README.md) (KWin effect id `fluctusg 2. [apple-liquid-glass-re.md](apple-liquid-glass-re.md): what is known about Apple's Liquid Glass (iOS 26 / macOS 26). It separates verified findings from documentation, observation and guesswork. +3. [performance.md](performance.md): measured CPU, GPU power and memory cost of the effect + versus stock blur (`just glass bench`), with the raw results. ## How the pieces fit diff --git a/glass/docs/performance.md b/glass/docs/performance.md new file mode 100644 index 0000000..e27bdc8 --- /dev/null +++ b/glass/docs/performance.md @@ -0,0 +1,86 @@ +# Fluctus Glass: performance measurements + +How much Liquid Glass costs compared to KWin's stock Blur, measured in a real session with +[`tools/bench/bench.py`](../tools/bench/bench.py) (`just glass bench`). Add new runs at the top. + +## Method + +`bench.py` switches only the `fluctusglass` effect. KWin's Blur effect stays loaded, so "off" means +plain blur where the glass would be. Each scenario runs for a fixed window and records: + +- **CPU**: cumulative CPU time of `kwin_wayland` and `plasmashell` over the window, as % of one core. +- **GPU power**: mean NVIDIA board power from `nvidia-smi` (every 500 ms). +- **Memory**: PSS of plasmashell, RSS of kwin_wayland (its smaps are root-only), mean VRAM in use. + +| Scenario | What happens | +|---|---| +| idle | nothing | +| drag | a throwaway mpv window sweeps behind the dock (moving backdrop) | +| video | an mpv test pattern animates on screen (see the notes per run for its placement) | +| pointer | the effect's debug hook replays a pointer path over the dock pill | + +On/off order alternates every repetition to cancel drift. Results are medians, with min..max in +brackets. Ignore `nvidia-smi`'s GPU utilization column: the GPU's power-state clock changes make it +noisier than the differences being measured (it read *higher* with glass off). Board power is the +reliable GPU number. + +## 2026-11-29: after the audit fixes + +Same machine, setup and method as the baseline below (2 × 30 s per scenario), with the fixed effect +and dock installed. The video scenario now covers the whole output, so it plays *behind* the dock. +Raw data: [`tools/bench/results/2026-11-29-after-fixes/`](../tools/bench/results/2026-11-29-after-fixes/). + +Compare the **on − off** columns, not absolute values between runs: this run's glass-off baseline +was noisier (idle kwin 1.9–3.0% against 0.5–0.6% in the baseline run). + +| Scenario | kwin CPU on − off: before → after | GPU power on − off: before → after | +|---|---|---| +| idle | +1.1 → −0.8 (noise) | +0.2 → −0.8 W (noise) | +| drag behind dock | +4.8 → +4.2 | +2.0 → +0.4 W | +| video behind the dock | +2.6 → +3.2 | +0.5 → +0.7 W | +| pointer over the pill | +3.2 → +1.1 | +1.2 → −1.6 W (noise) | + +### Reading + +- Idle stays free. Pointer response got cheaper (+3.2 → +1.1 points of one core). +- Dragging a window behind the dock costs about the same CPU, but far less GPU power + (+2.0 → +0.4 W): the capture and blur textures are no longer reallocated while the backdrop moves. +- Video behind the dock is unchanged within noise: there KWin repaints the dock area every frame + anyway, and the glass must follow the video. +- No scenario here isolates the biggest structural fix (damage *far* from the glass, such as a + blinking cursor in a maximized window, no longer repaints it), nor the dock-side savings during + window drags (TasksModel geometry updates are now skipped). Plasmashell CPU in the drag scenario + is 2.5–2.9% here against 3.6–4.7% in the baseline run, but that comparison crosses runs. +- With 2 runs per scenario, differences under about 1 point of CPU or 1 W are within noise. + +## 2026-11-29: baseline before the audit fixes + +- **Machine**: AMD Ryzen 7 7700, NVIDIA RTX 5060 Ti (driver 620.73.04, KWin on OpenGL ES), + 2 × 1920×1080 outputs, CachyOS kernel 7.3.6, KWin / Plasma 6.8.3. +- **Setup**: global mode; one glass shape on screen (the Fluctus Dock pill, about 290×54 px). +- **Runs**: 2 repetitions × 30 s per scenario (video behind the dock: a separate 2 × 30 s run). +- **Raw data**: [`tools/bench/results/2026-11-29/`](../tools/bench/results/2026-11-29/). + +| Scenario | kwin CPU, off → on | plasmashell CPU, off → on | GPU power, off → on | +|---|---|---|---| +| idle | 0.6% → 1.6% (+1.1) | 0.4% → 0.4% | 13.5 → 13.7 W | +| drag behind dock | 4.5% → 9.3% (+4.8) | 3.9% → 4.2% | 15.8 → 17.8 W | +| video **next to** the dock (maximized, ends at the dock's strut) | 3.1% → 8.3% (+5.2) | 0.4% → 1.0% | 19.0 → 21.1 W | +| video **behind** the dock (covers the whole output) | 3.4% → 6.1% (+2.6) | 0.4% → 0.4% | 19.6 → 20.1 W | +| pointer over the pill | 0.9% → 4.1% (+3.2) | 0.4% → 0.4% | 13.8 → 15.0 W | + +Memory did not move beyond noise (kwin ±1 MB, plasmashell ±8 MB, VRAM +6..35 MB). + +### Reading + +- At rest glass is nearly free: about 1% of one core in KWin and no measurable power. +- Anything moving under or near the glass roughly doubles KWin's CPU (+3–5% of one core) and adds + up to 2 W of GPU power. Each change in the area the refraction samples redraws the whole effect: + backdrop copy, blur chain and glass pass. +- Video *next to* the dock costs twice as much as video *behind* it. Behind the dock, KWin repaints + that area anyway. Next to it, the video sits in the margin the refraction samples beyond the + dock's window, so the effect repaints the dock glass on every video frame. That part is needed + (the refraction must show the moving video). What was wasted: the effect repainted on *any* damage + of a window overlapping that margin, wherever in the window it was. It now checks the frame's real + repaint region instead. +- The pointer response costs about 3% of one core while the pointer moves over glass. diff --git a/glass/justfile b/glass/justfile index 63f1b06..de8cdfd 100644 --- a/glass/justfile +++ b/glass/justfile @@ -56,6 +56,10 @@ nested *args: build parity out=(build_dir / "parity") *args: build python3 tools/verify-glass-parity.py --build "{{ build_dir }}" --out "{{ out }}" {{ args }} +# A/B resource benchmark of the loaded effect vs stock blur in this session (~20 min; see tools/bench/bench.py) +bench *args: + python3 tools/bench/bench.py --out "{{ build_dir }}/bench.json" {{ args }} + [private] disable-if-installed: @[ ! -f "{{ state_dir }}/glass.manifest" ] || just disable diff --git a/glass/tools/bench/Cover.qml b/glass/tools/bench/Cover.qml new file mode 100644 index 0000000..706d8a3 --- /dev/null +++ b/glass/tools/bench/Cover.qml @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2026 Kogical +// SPDX-License-Identifier: GPL-3.0-or-later +// +// KWin declarative script for bench.py: stretches the "fluctusbench-video" window over the whole +// output, including the area reserved by panels, so the test pattern animates behind the dock. +// (Maximizing stops at the dock's strut, which only puts the video next to the glass.) +import QtQuick +import org.kde.kwin + +Item { + Timer { + interval: 500 + repeat: true + running: true + onTriggered: { + const windows = Workspace.windows; + for (let i = 0; i < windows.length; ++i) { + const w = windows[i]; + if (w.caption.indexOf("fluctusbench-video") < 0) { + continue; + } + const area = Workspace.clientArea(KWin.FullScreenArea, w); + const g = w.frameGeometry; + if (g.x !== area.x || g.y !== area.y || g.width !== area.width || g.height !== area.height) { + w.noBorder = true; + w.frameGeometry = area; + } + } + } + } +} diff --git a/glass/tools/bench/Drag.qml b/glass/tools/bench/Drag.qml new file mode 100644 index 0000000..23051af --- /dev/null +++ b/glass/tools/bench/Drag.qml @@ -0,0 +1,53 @@ +// SPDX-FileCopyrightText: 2026 Kogical +// SPDX-License-Identifier: GPL-3.0-or-later +// +// KWin declarative script for bench.py: sweeps the "fluctusbench-drag" window in a Lissajous path +// that passes behind the dock, so the glass has to follow a moving backdrop every frame. +import QtQuick +import org.kde.kwin + +Item { + id: root + + property var target: null + property var dock: null + property real t: 0 + + function find() { + const windows = Workspace.windows; + for (let i = 0; i < windows.length; ++i) { + const w = windows[i]; + if (!root.target && w.caption.indexOf("fluctusbench-drag") >= 0) { + root.target = w; + } + // The widest dock on the same output wins (the Fluctus Dock rather than a thin top bar). + if (w.dock && (!root.dock || w.frameGeometry.height > root.dock.frameGeometry.height)) { + root.dock = w; + } + } + } + + Timer { + interval: 16 + repeat: true + running: true + onTriggered: { + if (!root.target || !root.dock) { + root.find(); + if (!root.target || !root.dock) { + return; + } + } + root.t += 0.016; + const d = root.dock.frameGeometry; + const g = root.target.frameGeometry; + const cx = d.x + d.width / 2 - g.width / 2; + const bottom = d.y + d.height - g.height; + root.target.frameGeometry = Qt.rect( + cx + 420 * Math.sin(root.t), + bottom - 120 + 120 * Math.sin(root.t * 1.37), + g.width, + g.height); + } + } +} diff --git a/glass/tools/bench/bench.py b/glass/tools/bench/bench.py new file mode 100755 index 0000000..4a26fbc --- /dev/null +++ b/glass/tools/bench/bench.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2026 Kogical +# SPDX-License-Identifier: GPL-3.0-or-later +"""A/B resource benchmark for Fluctus Glass in the running session. + +Toggles only the `fluctusglass` KWin effect (stock Blur stays loaded, so "off" means plain blur +where glass would be), runs scripted scenarios, and records: + + * CPU time of kwin_wayland and plasmashell (cumulative /proc ticks over the window, not samples) + * memory: PSS where readable, else RSS (kwin_wayland's smaps are root-only) + * NVIDIA GPU utilization, board power and VRAM (nvidia-smi, if present) + +Scenarios (each runs --seconds): + idle nothing happens + drag a throwaway mpv window sweeps behind the dock (moving backdrop) + video an mpv test pattern covering the whole output animates behind the dock + pointer the effect's debug hook replays a pointer path over the dock pill + +Configurations alternate order every repetition to cancel drift. The effect is always reloaded at +the end, even on error or Ctrl+C. Only windows this script opens are touched. + +Usage: just glass bench (or: python3 glass/tools/bench/bench.py --reps 3 --seconds 40) +""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import signal +import statistics +import subprocess +import sys +import tempfile +import time +import uuid +from pathlib import Path + +HERE = Path(__file__).resolve().parent +HZ = os.sysconf("SC_CLK_TCK") +SCENARIOS = ("idle", "drag", "video", "pointer") +METRICS = ( + ("kwin_cpu_pct", "kwin CPU %"), + ("shell_cpu_pct", "plasmashell CPU %"), + ("gpu_util_pct", "GPU util %"), + ("gpu_power_w", "GPU power W"), + ("vram_mb", "VRAM MB"), + ("kwin_mem_mb", "kwin mem MB"), + ("shell_mem_mb", "plasmashell mem MB"), +) + + +def kwin(*args: str) -> str: + return subprocess.run(["qdbus6", "org.kde.KWin", *args], capture_output=True, text=True).stdout.strip() + + +def pid_of(name: str) -> int: + out = subprocess.run(["pgrep", "-x", name], capture_output=True, text=True).stdout.split() + if not out: + sys.exit(f"{name} is not running") + return int(out[0]) + + +def cpu_ticks(pid: int) -> int: + fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split() + return int(fields[11]) + int(fields[12]) # utime + stime + + +def mem_mb(pid: int) -> float: + for path, key in ((f"/proc/{pid}/smaps_rollup", "Pss:"), (f"/proc/{pid}/status", "VmRSS:")): + try: + for line in Path(path).read_text().splitlines(): + if line.startswith(key): + return int(line.split()[1]) / 1024 + except PermissionError: + continue + return 0.0 + + +def glass_loaded() -> bool: + return kwin("/Effects", "org.kde.kwin.Effects.isEffectLoaded", "fluctusglass") == "true" + + +def set_glass(on: bool) -> None: + kwin("/Effects", "org.kde.kwin.Effects." + ("loadEffect" if on else "unloadEffect"), "fluctusglass") + for _ in range(50): + if glass_loaded() == on: + return + time.sleep(0.1) + raise RuntimeError(f"could not set fluctusglass loaded={on}") + + +def find_pointer_path() -> tuple[float, float, float] | None: + """Global logical (x0, x1, y) across the dock pill, from KWin's dock geometry + the effect's shapes.""" + token = f"FLUCTUSBENCH-{uuid.uuid4().hex[:8]}" + with tempfile.TemporaryDirectory() as tmp: + script = Path(tmp) / "probe.js" + script.write_text((HERE / "probe.js").read_text().replace("__TOKEN__", token)) + name = token.lower() + sid = kwin("/Scripting", "org.kde.kwin.Scripting.loadScript", str(script), name) + kwin(f"/Scripting/Script{sid}", "org.kde.kwin.Script.run") + time.sleep(0.5) + kwin("/Scripting", "org.kde.kwin.Scripting.unloadScript", name) + log = subprocess.run(["journalctl", "--user", "--since", "-30s", "-o", "cat"], capture_output=True, text=True).stdout + docks = [tuple(map(float, line.split()[1:5])) for line in log.splitlines() if line.startswith(token)] + + state = kwin("/Effects", "org.kde.kwin.Effects.debug", "fluctusglass", "state") + rects = [] + for line in state.splitlines(): + line = line.strip() + if line.startswith("rect="): + pos, size = line.split()[0][5:], line.split()[1] + x, y = map(float, pos.split(",")) + w, h = map(float, size.split("x")) + rects.append((x, y, w, h)) + # A shape belongs to a dock when it fits inside that dock window; prefer the largest one. + best = None + for dx, dy, dw, dh in docks: + for x, y, w, h in rects: + if x >= 0 and y >= 0 and x + w <= dw + 1 and y + h <= dh + 1 and (best is None or w * h > best[2] * best[3]): + best = (dx + x, dy + y, w, h) + if best is None: + return None + x, y, w, h = best + return (x + 8, x + w - 8, y + h / 2) + + +class Scenario: + def __init__(self, name: str, qml_dir: Path, pointer: tuple[float, float, float] | None): + self.name, self.qml_dir, self.pointer = name, qml_dir, pointer + self.procs: list[subprocess.Popen] = [] + self.scripts: list[str] = [] + + def _mpv(self, title: str, *extra: str) -> None: + self.procs.append(subprocess.Popen( + ["mpv", "--no-config", "--no-terminal", "--no-audio", f"--title={title}", *extra], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)) + time.sleep(1.5) + + def _script(self, qml: str) -> None: + name = f"fluctusbench-{qml.lower()}" + kwin("/Scripting", "org.kde.kwin.Scripting.loadDeclarativeScript", str(self.qml_dir / f"{qml}.qml"), name) + kwin("/Scripting", "org.kde.kwin.Scripting.start") + self.scripts.append(name) + + def setup(self) -> None: + if self.name == "drag": + self._mpv("fluctusbench-drag", "--idle", "--force-window=immediate", "--geometry=600x400") + self._script("Drag") + elif self.name == "video": + self._mpv("fluctusbench-video", "--loop=inf", "av://lavfi:testsrc2=size=1280x720:rate=60") + self._script("Cover") + + def tick(self, t: float) -> float: + if self.name == "pointer" and self.pointer: + x0, x1, y = self.pointer + phase = (t * 0.5) % 2.0 + frac = phase if phase <= 1.0 else 2.0 - phase + kwin("/Effects", "org.kde.kwin.Effects.debug", "fluctusglass", f"pointer {x0 + (x1 - x0) * frac:.0f} {y:.0f}") + return 1 / 30 + return 0.25 + + def teardown(self) -> None: + for name in self.scripts: + kwin("/Scripting", "org.kde.kwin.Scripting.unloadScript", name) + for proc in self.procs: + proc.terminate() + try: + proc.wait(3) + except subprocess.TimeoutExpired: + proc.kill() + self.procs.clear() + self.scripts.clear() + + +def measure(scenario: Scenario, seconds: float, kwin_pid: int, shell_pid: int) -> dict: + scenario.setup() + try: + time.sleep(3) # let window mapping / effect setup settle out of the window + smi = None + if shutil.which("nvidia-smi"): + smi = subprocess.Popen(["nvidia-smi", "--query-gpu=utilization.gpu,power.draw,memory.used", + "--format=csv,noheader,nounits", "-lms", "500"], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + k0, s0, t0 = cpu_ticks(kwin_pid), cpu_ticks(shell_pid), time.monotonic() + while (t := time.monotonic() - t0) < seconds: + time.sleep(scenario.tick(t)) + k1, s1, dt = cpu_ticks(kwin_pid), cpu_ticks(shell_pid), time.monotonic() - t0 + rows = [] + if smi: + smi.terminate() + rows = [line.split(",") for line in smi.communicate()[0].splitlines() if line.count(",") == 2] + finally: + scenario.teardown() + + def avg(i: int) -> float | None: + values = [] + for row in rows: + try: + values.append(float(row[i])) + except ValueError: + pass + return statistics.fmean(values) if values else None + + return { + "kwin_cpu_pct": 100 * (k1 - k0) / HZ / dt, + "shell_cpu_pct": 100 * (s1 - s0) / HZ / dt, + "gpu_util_pct": avg(0), + "gpu_power_w": avg(1), + "vram_mb": avg(2), + "kwin_mem_mb": mem_mb(kwin_pid), + "shell_mem_mb": mem_mb(shell_pid), + } + + +def summarize(results: list[dict]) -> str: + lines = [] + for scenario in SCENARIOS: + rows = [r for r in results if r["scenario"] == scenario] + if not rows: + continue + lines.append(f"\n{scenario} (median of {len(rows) // 2} runs each; spread = min..max)") + lines.append(f" {'metric':<20}{'glass off':>18}{'glass on':>18}{'on - off':>12}") + for key, label in METRICS: + off = [r[key] for r in rows if not r["glass"] and r[key] is not None] + on = [r[key] for r in rows if r["glass"] and r[key] is not None] + if not off or not on: + continue + fmt = lambda v: f"{statistics.median(v):.1f} ({min(v):.1f}..{max(v):.1f})" + delta = statistics.median(on) - statistics.median(off) + lines.append(f" {label:<20}{fmt(off):>18}{fmt(on):>18}{delta:>+12.1f}") + return "\n".join(lines) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--reps", type=int, default=3, help="repetitions of each configuration (default 3)") + parser.add_argument("--seconds", type=float, default=40, help="measurement window per scenario (default 40)") + parser.add_argument("--scenarios", default=",".join(SCENARIOS), help="comma-separated subset to run") + parser.add_argument("--out", type=Path, default=Path("fluctusbench-results.json"), help="raw results JSON") + args = parser.parse_args() + # Treat SIGTERM like Ctrl+C so the effect is always reloaded. + signal.signal(signal.SIGTERM, signal.default_int_handler) + + for tool in ("qdbus6", "mpv", "journalctl"): + if not shutil.which(tool): + sys.exit(f"{tool} is required") + if not glass_loaded(): + sys.exit("fluctusglass is not loaded; enable it first (just glass enable)") + + args.out.parent.mkdir(parents=True, exist_ok=True) + # Scripts left loaded by an interrupted run would shadow the ones this run loads. + for name in ("fluctusbench-drag", "fluctusbench-cover"): + kwin("/Scripting", "org.kde.kwin.Scripting.unloadScript", name) + + scenarios = [s for s in args.scenarios.split(",") if s in SCENARIOS] + kwin_pid, shell_pid = pid_of("kwin_wayland"), pid_of("plasmashell") + pointer = find_pointer_path() if "pointer" in scenarios else None + if "pointer" in scenarios and pointer is None: + print("No dock glass shape found: skipping the pointer scenario.", file=sys.stderr) + scenarios.remove("pointer") + + total = 2 * args.reps * len(scenarios) * (args.seconds + 6) + print(f"Running ~{total / 60:.0f} min: {args.reps} reps x on/off x {scenarios}", flush=True) + + results: list[dict] = [] + # KWin's QML engine caches directory listings, so load scripts from a fresh copy of this folder. + with tempfile.TemporaryDirectory(prefix="fluctusbench-") as tmp: + qml_dir = Path(tmp) + for qml in HERE.glob("*.qml"): + shutil.copy(qml, qml_dir / qml.name) + try: + for rep in range(args.reps): + for on in ((True, False) if rep % 2 == 0 else (False, True)): + set_glass(on) + time.sleep(5) + for name in scenarios: + row = measure(Scenario(name, qml_dir, pointer), args.seconds, kwin_pid, shell_pid) + row.update(rep=rep, glass=on, scenario=name) + results.append(row) + print(f"rep {rep} glass={'on ' if on else 'off'} {name:<8} " + f"kwin {row['kwin_cpu_pct']:5.1f}% shell {row['shell_cpu_pct']:5.1f}% " + f"gpu {row['gpu_util_pct'] or 0:4.1f}% {row['gpu_power_w'] or 0:5.1f} W", flush=True) + args.out.write_text(json.dumps(results, indent=1)) + except KeyboardInterrupt: + print("Interrupted.", file=sys.stderr) + finally: + set_glass(True) + print(f"fluctusglass restored: {glass_loaded()}", flush=True) + + print(summarize(results)) + print(f"\nRaw results: {args.out}") + + +if __name__ == "__main__": + main() diff --git a/glass/tools/bench/probe.js b/glass/tools/bench/probe.js new file mode 100644 index 0000000..a3d2e9d --- /dev/null +++ b/glass/tools/bench/probe.js @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: 2026 Kogical +// SPDX-License-Identifier: GPL-3.0-or-later +// +// KWin script for bench.py: prints every dock window's frame geometry to KWin's journal. +// bench.py replaces __TOKEN__ with a per-run marker before loading it. +var windows = workspace.windowList(); +for (var i = 0; i < windows.length; ++i) { + var w = windows[i]; + if (w.dock) { + var g = w.frameGeometry; + print("__TOKEN__ " + g.x + " " + g.y + " " + g.width + " " + g.height); + } +} diff --git a/glass/tools/bench/results/2026-11-29-after-fixes/main.json b/glass/tools/bench/results/2026-11-29-after-fixes/main.json new file mode 100644 index 0000000..a087d3c --- /dev/null +++ b/glass/tools/bench/results/2026-11-29-after-fixes/main.json @@ -0,0 +1,194 @@ +[ + { + "kwin_cpu_pct": 1.1996239424463135, + "shell_cpu_pct": 0.36655176019192914, + "gpu_util_pct": 0.11666666666666667, + "gpu_power_w": 13.3575, + "vram_mb": 1460.3, + "kwin_mem_mb": 328.94140625, + "shell_mem_mb": 393.4111328125, + "rep": 0, + "glass": true, + "scenario": "idle" + }, + { + "kwin_cpu_pct": 9.530641419231731, + "shell_cpu_pct": 2.5326179995161247, + "gpu_util_pct": 2.183333333333333, + "gpu_power_w": 16.231666666666666, + "vram_mb": 1607.3166666666666, + "kwin_mem_mb": 330.8125, + "shell_mem_mb": 395.6923828125, + "rep": 0, + "glass": true, + "scenario": "drag" + }, + { + "kwin_cpu_pct": 7.497875787807315, + "shell_cpu_pct": 0.9663928793173873, + "gpu_util_pct": 4.166666666666667, + "gpu_power_w": 20.046499999999998, + "vram_mb": 1653.2333333333333, + "kwin_mem_mb": 332.11328125, + "shell_mem_mb": 397.79296875, + "rep": 0, + "glass": true, + "scenario": "video" + }, + { + "kwin_cpu_pct": 6.499482787624579, + "shell_cpu_pct": 0.43329885250830524, + "gpu_util_pct": 1.85, + "gpu_power_w": 17.487333333333332, + "vram_mb": 1872.35, + "kwin_mem_mb": 330.62109375, + "shell_mem_mb": 403.7158203125, + "rep": 0, + "glass": true, + "scenario": "pointer" + }, + { + "kwin_cpu_pct": 1.932791993086321, + "shell_cpu_pct": 0.3998879985695837, + "gpu_util_pct": 1.0, + "gpu_power_w": 14.863833333333334, + "vram_mb": 1820.0166666666667, + "kwin_mem_mb": 488.2109375, + "shell_mem_mb": 404.345703125, + "rep": 0, + "glass": false, + "scenario": "idle" + }, + { + "kwin_cpu_pct": 4.198811006731417, + "shell_cpu_pct": 2.6325878534268408, + "gpu_util_pct": 1.9833333333333334, + "gpu_power_w": 15.350833333333332, + "vram_mb": 1857.2166666666667, + "kwin_mem_mb": 489.2109375, + "shell_mem_mb": 406.0458984375, + "rep": 0, + "glass": false, + "scenario": "drag" + }, + { + "kwin_cpu_pct": 3.499017366753996, + "shell_cpu_pct": 0.3998876990575995, + "gpu_util_pct": 3.1666666666666665, + "gpu_power_w": 19.177666666666667, + "vram_mb": 1745.6833333333334, + "kwin_mem_mb": 489.72265625, + "shell_mem_mb": 406.25, + "rep": 0, + "glass": false, + "scenario": "video" + }, + { + "kwin_cpu_pct": 5.1985396226102365, + "shell_cpu_pct": 1.732846540870079, + "gpu_util_pct": 2.1666666666666665, + "gpu_power_w": 18.041166666666665, + "vram_mb": 1511.35, + "kwin_mem_mb": 487.98046875, + "shell_mem_mb": 411.087890625, + "rep": 0, + "glass": false, + "scenario": "pointer" + }, + { + "kwin_cpu_pct": 3.0324683431680923, + "shell_cpu_pct": 0.9663910104601613, + "gpu_util_pct": 2.6666666666666665, + "gpu_power_w": 14.876666666666667, + "vram_mb": 1992.2, + "kwin_mem_mb": 487.953125, + "shell_mem_mb": 411.5185546875, + "rep": 1, + "glass": false, + "scenario": "idle" + }, + { + "kwin_cpu_pct": 5.664958800930308, + "shell_cpu_pct": 2.8991259745937463, + "gpu_util_pct": 2.65, + "gpu_power_w": 16.762333333333334, + "vram_mb": 1999.6333333333334, + "kwin_mem_mb": 489.01171875, + "shell_mem_mb": 413.4130859375, + "rep": 1, + "glass": false, + "scenario": "drag" + }, + { + "kwin_cpu_pct": 4.165550456186124, + "shell_cpu_pct": 0.7331368802887579, + "gpu_util_pct": 3.533333333333333, + "gpu_power_w": 19.31116666666667, + "vram_mb": 1780.4833333333333, + "kwin_mem_mb": 491.71875, + "shell_mem_mb": 414.703125, + "rep": 1, + "glass": false, + "scenario": "video" + }, + { + "kwin_cpu_pct": 4.3322293379009515, + "shell_cpu_pct": 1.332993642431062, + "gpu_util_pct": 1.55, + "gpu_power_w": 16.732, + "vram_mb": 1748.2, + "kwin_mem_mb": 490.25, + "shell_mem_mb": 414.5234375, + "rep": 1, + "glass": false, + "scenario": "pointer" + }, + { + "kwin_cpu_pct": 2.0993428546725066, + "shell_cpu_pct": 0.3998748294614298, + "gpu_util_pct": 5.616666666666666, + "gpu_power_w": 14.779333333333334, + "vram_mb": 1752.5333333333333, + "kwin_mem_mb": 490.9609375, + "shell_mem_mb": 415.1669921875, + "rep": 1, + "glass": true, + "scenario": "idle" + }, + { + "kwin_cpu_pct": 8.830863473871746, + "shell_cpu_pct": 2.4993009831712487, + "gpu_util_pct": 4.916666666666667, + "gpu_power_w": 16.719666666666665, + "vram_mb": 1853.0333333333333, + "kwin_mem_mb": 491.79296875, + "shell_mem_mb": 415.11328125, + "rep": 1, + "glass": true, + "scenario": "drag" + }, + { + "kwin_cpu_pct": 6.5647713718744996, + "shell_cpu_pct": 0.46653197566620813, + "gpu_util_pct": 4.216666666666667, + "gpu_power_w": 19.93883333333333, + "vram_mb": 1701.4833333333333, + "kwin_mem_mb": 492.26171875, + "shell_mem_mb": 415.2568359375, + "rep": 1, + "glass": true, + "scenario": "video" + }, + { + "kwin_cpu_pct": 5.2972917902965015, + "shell_cpu_pct": 0.39979560681483034, + "gpu_util_pct": 0.5833333333333334, + "gpu_power_w": 14.139000000000001, + "vram_mb": 1425.35, + "kwin_mem_mb": 492.265625, + "shell_mem_mb": 415.29296875, + "rep": 1, + "glass": true, + "scenario": "pointer" + } +] \ No newline at end of file diff --git a/glass/tools/bench/results/2026-11-29/main.json b/glass/tools/bench/results/2026-11-29/main.json new file mode 100644 index 0000000..8df75a1 --- /dev/null +++ b/glass/tools/bench/results/2026-11-29/main.json @@ -0,0 +1,194 @@ +[ + { + "kwin_cpu_pct": 1.0996846829754514, + "shell_cpu_pct": 0.43320911753578384, + "gpu_util_pct": 0.55, + "gpu_power_w": 14.029833333333332, + "vram_mb": 1374.5833333333333, + "kwin_mem_mb": 419.15625, + "shell_mem_mb": 468.7294921875, + "rep": 0, + "glass": true, + "scenario": "idle" + }, + { + "kwin_cpu_pct": 10.99683180579262, + "shell_cpu_pct": 4.698646317020484, + "gpu_util_pct": 2.85, + "gpu_power_w": 19.2775, + "vram_mb": 1564.4, + "kwin_mem_mb": 417.66015625, + "shell_mem_mb": 461.5185546875, + "rep": 0, + "glass": true, + "scenario": "drag" + }, + { + "kwin_cpu_pct": 10.430433947015521, + "shell_cpu_pct": 1.5995553656765016, + "gpu_util_pct": 5.533333333333333, + "gpu_power_w": 22.168166666666664, + "vram_mb": 1662.4166666666667, + "kwin_mem_mb": 417.796875, + "shell_mem_mb": 472.7216796875, + "rep": 0, + "glass": true, + "scenario": "video" + }, + { + "kwin_cpu_pct": 4.132545008496192, + "shell_cpu_pct": 0.46657766224957, + "gpu_util_pct": 1.0666666666666667, + "gpu_power_w": 15.084, + "vram_mb": 1377.0833333333333, + "kwin_mem_mb": 417.796875, + "shell_mem_mb": 478.0263671875, + "rep": 0, + "glass": true, + "scenario": "pointer" + }, + { + "kwin_cpu_pct": 0.5331937892139564, + "shell_cpu_pct": 0.4665445655622119, + "gpu_util_pct": 5.5, + "gpu_power_w": 13.653666666666668, + "vram_mb": 1366.7166666666667, + "kwin_mem_mb": 417.80078125, + "shell_mem_mb": 476.912109375, + "rep": 0, + "glass": false, + "scenario": "idle" + }, + { + "kwin_cpu_pct": 4.232171956787527, + "shell_cpu_pct": 3.7323091272456925, + "gpu_util_pct": 11.1, + "gpu_power_w": 15.6655, + "vram_mb": 1519.8833333333334, + "kwin_mem_mb": 418.04296875, + "shell_mem_mb": 476.9716796875, + "rep": 0, + "glass": false, + "scenario": "drag" + }, + { + "kwin_cpu_pct": 2.9991157474113064, + "shell_cpu_pct": 0.4332056079594109, + "gpu_util_pct": 4.0, + "gpu_power_w": 19.06566666666667, + "vram_mb": 1594.2166666666667, + "kwin_mem_mb": 418.39453125, + "shell_mem_mb": 477.0517578125, + "rep": 0, + "glass": false, + "scenario": "video" + }, + { + "kwin_cpu_pct": 0.8664043823495001, + "shell_cpu_pct": 0.3332324547498077, + "gpu_util_pct": 1.0, + "gpu_power_w": 13.871, + "vram_mb": 1343.1333333333334, + "kwin_mem_mb": 418.39453125, + "shell_mem_mb": 477.0546875, + "rep": 0, + "glass": false, + "scenario": "pointer" + }, + { + "kwin_cpu_pct": 0.5998185637018393, + "shell_cpu_pct": 0.39987904246789285, + "gpu_util_pct": 9.7, + "gpu_power_w": 13.445, + "vram_mb": 1348.1333333333334, + "kwin_mem_mb": 418.39453125, + "shell_mem_mb": 477.0361328125, + "rep": 1, + "glass": false, + "scenario": "idle" + }, + { + "kwin_cpu_pct": 4.765326409559789, + "shell_cpu_pct": 4.0321992696275135, + "gpu_util_pct": 7.2, + "gpu_power_w": 16.021833333333333, + "vram_mb": 1523.5333333333333, + "kwin_mem_mb": 418.39453125, + "shell_mem_mb": 477.177734375, + "rep": 1, + "glass": false, + "scenario": "drag" + }, + { + "kwin_cpu_pct": 3.299050689256651, + "shell_cpu_pct": 0.4665324207029608, + "gpu_util_pct": 3.1, + "gpu_power_w": 18.997, + "vram_mb": 1592.9833333333333, + "kwin_mem_mb": 418.3984375, + "shell_mem_mb": 477.2412109375, + "rep": 1, + "glass": false, + "scenario": "video" + }, + { + "kwin_cpu_pct": 0.9329036152586039, + "shell_cpu_pct": 0.46645180762930194, + "gpu_util_pct": 0.0, + "gpu_power_w": 13.634333333333334, + "vram_mb": 1344.8333333333333, + "kwin_mem_mb": 418.3984375, + "shell_mem_mb": 477.3779296875, + "rep": 1, + "glass": false, + "scenario": "pointer" + }, + { + "kwin_cpu_pct": 2.199302185682014, + "shell_cpu_pct": 0.39987312466945707, + "gpu_util_pct": 0.11666666666666667, + "gpu_power_w": 13.442666666666668, + "vram_mb": 1345.0666666666666, + "kwin_mem_mb": 418.41015625, + "shell_mem_mb": 478.1357421875, + "rep": 1, + "glass": true, + "scenario": "idle" + }, + { + "kwin_cpu_pct": 7.531127830749987, + "shell_cpu_pct": 3.6322696174856133, + "gpu_util_pct": 1.5166666666666666, + "gpu_power_w": 16.37, + "vram_mb": 1525.1833333333334, + "kwin_mem_mb": 418.53515625, + "shell_mem_mb": 478.3115234375, + "rep": 1, + "glass": true, + "scenario": "drag" + }, + { + "kwin_cpu_pct": 6.23152356761197, + "shell_cpu_pct": 0.4998548316266286, + "gpu_util_pct": 3.9166666666666665, + "gpu_power_w": 19.948500000000003, + "vram_mb": 1592.75, + "kwin_mem_mb": 418.45703125, + "shell_mem_mb": 478.3779296875, + "rep": 1, + "glass": true, + "scenario": "video" + }, + { + "kwin_cpu_pct": 4.129542073023106, + "shell_cpu_pct": 0.39963310384094575, + "gpu_util_pct": 0.03278688524590164, + "gpu_power_w": 14.880491803278689, + "vram_mb": 1348.295081967213, + "kwin_mem_mb": 420.45703125, + "shell_mem_mb": 478.3837890625, + "rep": 1, + "glass": true, + "scenario": "pointer" + } +] \ No newline at end of file diff --git a/glass/tools/bench/results/2026-11-29/video-behind-dock.json b/glass/tools/bench/results/2026-11-29/video-behind-dock.json new file mode 100644 index 0000000..e987211 --- /dev/null +++ b/glass/tools/bench/results/2026-11-29/video-behind-dock.json @@ -0,0 +1,50 @@ +[ + { + "kwin_cpu_pct": 6.231158019659787, + "shell_cpu_pct": 0.3998604076787029, + "gpu_util_pct": 3.9833333333333334, + "gpu_power_w": 20.129666666666665, + "vram_mb": 1625.1333333333334, + "kwin_mem_mb": 420.49609375, + "shell_mem_mb": 478.4541015625, + "rep": 0, + "glass": true, + "scenario": "video" + }, + { + "kwin_cpu_pct": 3.4988776222223974, + "shell_cpu_pct": 0.3998717282539883, + "gpu_util_pct": 3.1666666666666665, + "gpu_power_w": 19.5365, + "vram_mb": 1615.9, + "kwin_mem_mb": 420.5, + "shell_mem_mb": 478.4873046875, + "rep": 0, + "glass": false, + "scenario": "video" + }, + { + "kwin_cpu_pct": 3.332179393722344, + "shell_cpu_pct": 0.3665397333094579, + "gpu_util_pct": 3.533333333333333, + "gpu_power_w": 19.642833333333332, + "vram_mb": 1599.0833333333333, + "kwin_mem_mb": 420.5, + "shell_mem_mb": 478.556640625, + "rep": 1, + "glass": false, + "scenario": "video" + }, + { + "kwin_cpu_pct": 5.89824032468336, + "shell_cpu_pct": 0.36655730831365513, + "gpu_util_pct": 3.933333333333333, + "gpu_power_w": 20.039833333333334, + "vram_mb": 1601.55, + "kwin_mem_mb": 420.5, + "shell_mem_mb": 478.630859375, + "rep": 1, + "glass": true, + "scenario": "video" + } +] \ No newline at end of file From 47222c3a20e2022480eaf5dc8e224958fbbdec62 Mon Sep 17 00:00:00 2001 From: arcu1tus Date: Sun, 29 Nov 2026 18:28:53 +0100 Subject: [PATCH 2/2] perf(glass,dock): fix audit findings in the effect, renderer and dock Glass effect / liquidglass: - Keep the backdrop capture registered to screen coordinates with slack, and carry overlapping pixels over on reallocation: no per-frame texture churn while the dock pill grows or a window moves, no black edge refraction. - Cache blur chains by size/format/iterations in the GL renderer instead of one shared chain thrashed by every differently sized draw. - Finish the Kawase chain with a full-resolution upsample so the glass shader reads the blur with one level-0 tap instead of an 8-tap filter per sample. - Repaint glass for another window's damage only where the frame really repainted its sampling margin, not on any damage of an overlapping window. - Blur only frosted shapes; skip no-op Set() calls; free idle capture textures; cache color-mapped materials; restore UBO binding 0 and avoid reading a host PBO when allocating. - Catch Rust panics at the FFI boundary (new release-ffi profile unwinds) and take Kawase/margin math from the renderer instead of duplicating it in C++. - Global mode: pointer response off on application windows by default (new PointerEffectsOnWindows setting). Dock: - Cache role ids and ignore dataChanged for roles the dock does not use (window drags no longer resync delegates every frame). - Publish minimize geometry only when it changes; cache per-frame property handles; send the glass region over D-Bus only once animations settle. - Settle check uses the resolved (auto-scaled) metrics like step(), so the hover spring always reaches rest (new regression test). - Higher-resolution icon sources with mipmapping; non-blocking startup glass detection. Co-Authored-By: Claude Opus 5.5 --- Cargo.toml | 6 + crates/liquidglass/include/liquidglass.h | 28 ++ crates/liquidglass/shaders/liquidglass.wgsl | 20 +- crates/liquidglass/src/core.rs | 10 + crates/liquidglass/src/ffi.rs | 80 ++++-- crates/liquidglass/src/gl_backend.rs | 291 +++++++++++++------- crates/liquidglass/src/wgpu_backend.rs | 57 ++-- dock/src/backend/FluctusApplet.cpp | 17 +- dock/src/core/DockPhysicsEngine.cpp | 7 +- dock/src/core/DockPhysicsEngine.hpp | 4 + dock/src/quick/DockIconItem.cpp | 18 +- dock/src/quick/DockLayoutItem.cpp | 113 +++++++- dock/src/quick/DockLayoutItem.hpp | 21 ++ dock/tests/test_dock_physics.cpp | 36 +++ docs/development.md | 4 +- glass/CMakeLists.txt | 9 +- glass/kcm/glassconfig.cpp | 2 + glass/src/fluctusglass.kcfg | 2 + glass/src/glasseffect.cpp | 289 +++++++++++++------ glass/src/glasseffect.hpp | 35 ++- glass/src/glassservice.cpp | 13 +- glass/src/material.cpp | 25 +- 22 files changed, 793 insertions(+), 294 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index cbd6874..1e813f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,3 +21,9 @@ repository = "https://github.com/kogical/fluctus" lto = "thin" codegen-units = 1 panic = "abort" + +# The KWin effect links liquidglass as a staticlib. Its FFI catches Rust panics and returns an +# error instead; with panic = "abort" a panic would take down KWin (and the session) instead. +[profile.release-ffi] +inherits = "release" +panic = "unwind" diff --git a/crates/liquidglass/include/liquidglass.h b/crates/liquidglass/include/liquidglass.h index 0acedf5..09b1ac3 100644 --- a/crates/liquidglass/include/liquidglass.h +++ b/crates/liquidglass/include/liquidglass.h @@ -20,6 +20,10 @@ typedef enum LgStatus { LG_STATUS_GL_COMPILE_ERROR = 3, LG_STATUS_GL_FRAMEBUFFER_ERROR = 4, LG_STATUS_UNSUPPORTED = 5, + /** + * The renderer hit an internal error (a Rust panic caught at the FFI boundary). + */ + LG_STATUS_INTERNAL = 6, } LgStatus; /** @@ -167,6 +171,14 @@ typedef struct LgMaterial { float pointer_radius; } LgMaterial; +/** + * C ABI form of [`KawaseStep`]: Dual Kawase iteration count and sample offset. + */ +typedef struct LgKawaseStep { + uint32_t iterations; + float offset; +} LgKawaseStep; + /** * Host callback resolving OpenGL function pointers by null-terminated symbol name * (e.g. `eglGetProcAddress` or `glXGetProcAddress`). @@ -369,6 +381,22 @@ float lg_material_draw_margin(const struct LgMaterial *material); uint32_t lg_kawase_expand_for_frost(float frost, float scale); +/** + * Maps `frost` (`0..1`) to a KWin blur strength (`0` = sharp, `1..=15`). + */ +uint32_t lg_strength_for_frost(float frost); + +/** + * Resolves a KWin blur strength (`0..=15`) at a HiDPI `scale` into Dual Kawase iterations + offset + * (KWin Blur's own table; `strength == 0` gives zero iterations). + */ +struct LgKawaseStep lg_kawase_for_strength(uint32_t strength, float scale); + +/** + * Minimum backdrop expansion (device px) that `iterations` Dual Kawase passes sample beyond a rect. + */ +uint32_t lg_kawase_expand_for_iterations(uint32_t iterations); + /** * Creates a zero-copy OpenGL / GLES Liquid Glass renderer on the currently active GL context. * diff --git a/crates/liquidglass/shaders/liquidglass.wgsl b/crates/liquidglass/shaders/liquidglass.wgsl index 65deae9..e767252 100644 --- a/crates/liquidglass/shaders/liquidglass.wgsl +++ b/crates/liquidglass/shaders/liquidglass.wgsl @@ -23,7 +23,7 @@ struct GlassUniforms { inner_border: vec4, // straight-alpha RGBA outer_border: vec4, // straight-alpha RGBA shadow_color: vec4, // straight-alpha RGBA - tex_and_blur: vec4, // (tex_w, tex_h, blur_half_x, blur_half_y) + tex_and_blur: vec4, // (tex_w, tex_h, blur_half_x, blur_half_y); blur half-pixels unused since the full-res upsample optics_a: vec4, // (radius, bezel, refraction, dispersion) optics_b: vec4, // (magnify, edge_bend, saturation, brightness) rim_params: vec4, // (rim_light, rim_width, light_dir_x, light_dir_y) @@ -136,21 +136,15 @@ fn to_uv(p: vec2) -> vec2 { return clamp(uv, u.uv_clamp.xy, u.uv_clamp.zw); } +// The host's blur chain ends with a full-resolution Kawase upsample, so the blurred backdrop is a +// single tap here (the 5 dispersion samples used to re-run the 8-tap upsample each). Every lookup uses +// level 0 explicitly: they sit in non-uniform control flow, where implicit derivatives are undefined. fn sample_backdrop_blur(p: vec2) -> vec4 { let uv = to_uv(p); if (u.pointer_b.w < 0.5) { - return textureSample(sharp_tex, sharp_samp, uv); + return textureSampleLevel(sharp_tex, sharp_samp, uv, 0.0); } - let h = u.tex_and_blur.zw * u.misc.x; - var sum = textureSample(blur_tex, blur_samp, uv + vec2(-h.x * 2.0, 0.0)); - sum += textureSample(blur_tex, blur_samp, uv + vec2(-h.x, h.y)) * 2.0; - sum += textureSample(blur_tex, blur_samp, uv + vec2(0.0, h.y * 2.0)); - sum += textureSample(blur_tex, blur_samp, uv + vec2(h.x, h.y)) * 2.0; - sum += textureSample(blur_tex, blur_samp, uv + vec2(h.x * 2.0, 0.0)); - sum += textureSample(blur_tex, blur_samp, uv + vec2(h.x, -h.y)) * 2.0; - sum += textureSample(blur_tex, blur_samp, uv + vec2(0.0, -h.y * 2.0)); - sum += textureSample(blur_tex, blur_samp, uv + vec2(-h.x, -h.y)) * 2.0; - return sum / 12.0; + return textureSampleLevel(blur_tex, blur_samp, uv, 0.0); } fn sample_backdrop(p: vec2, clarity: f32) -> vec4 { @@ -158,7 +152,7 @@ fn sample_backdrop(p: vec2, clarity: f32) -> vec4 { if (u.pointer_b.w < 0.5 || clarity <= 0.001) { return blurred; } - let sharp = textureSample(sharp_tex, sharp_samp, to_uv(p)); + let sharp = textureSampleLevel(sharp_tex, sharp_samp, to_uv(p), 0.0); return mix(blurred, sharp, clarity); } diff --git a/crates/liquidglass/src/core.rs b/crates/liquidglass/src/core.rs index 605786e..91f80d3 100644 --- a/crates/liquidglass/src/core.rs +++ b/crates/liquidglass/src/core.rs @@ -39,6 +39,8 @@ pub enum LgStatus { GlCompileError = 3, GlFramebufferError = 4, Unsupported = 5, + /// The renderer hit an internal error (a Rust panic caught at the FFI boundary). + Internal = 6, } /// Straight-alpha RGBA color in the output color space (SDR `0..1`, or HDR linear/mapped). @@ -426,6 +428,14 @@ pub struct KawaseStep { pub offset: f32, } +/// C ABI form of [`KawaseStep`]: Dual Kawase iteration count and sample offset. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct LgKawaseStep { + pub iterations: u32, + pub offset: f32, +} + #[derive(Debug, Clone, Copy)] struct KawaseLevel { min_offset: f32, diff --git a/crates/liquidglass/src/ffi.rs b/crates/liquidglass/src/ffi.rs index 0434910..7d470e6 100644 --- a/crates/liquidglass/src/ffi.rs +++ b/crates/liquidglass/src/ffi.rs @@ -7,10 +7,21 @@ use core::ffi::{c_char, c_void}; +#[cfg(feature = "gl")] +use std::panic::{catch_unwind, AssertUnwindSafe}; + use crate::core::{ - expand_for_iterations, kawase_for_strength, strength_for_frost, LgMaterial, LgRenderParams, - LgStatus, + expand_for_iterations, kawase_for_strength, strength_for_frost, LgKawaseStep, LgMaterial, }; +#[cfg(feature = "gl")] +use crate::core::{LgRenderParams, LgStatus}; + +/// Runs `f`, turning a Rust panic into `LgStatus::Internal`: unwinding across `extern "C"` would +/// abort the host process (for KWin, the whole session). +#[cfg(feature = "gl")] +fn guarded(f: impl FnOnce() -> LgStatus) -> LgStatus { + catch_unwind(AssertUnwindSafe(f)).unwrap_or(LgStatus::Internal) +} /// Opaque handle to a zero-copy OpenGL / OpenGL ES Liquid Glass renderer. #[repr(C)] @@ -65,6 +76,26 @@ pub extern "C" fn lg_kawase_expand_for_frost(frost: f32, scale: f32) -> u32 { expand_for_iterations(step.iterations) } +/// Maps `frost` (`0..1`) to a KWin blur strength (`0` = sharp, `1..=15`). +#[unsafe(no_mangle)] +pub extern "C" fn lg_strength_for_frost(frost: f32) -> u32 { + strength_for_frost(frost) +} + +/// Resolves a KWin blur strength (`0..=15`) at a HiDPI `scale` into Dual Kawase iterations + offset +/// (KWin Blur's own table; `strength == 0` gives zero iterations). +#[unsafe(no_mangle)] +pub extern "C" fn lg_kawase_for_strength(strength: u32, scale: f32) -> LgKawaseStep { + let step = kawase_for_strength(strength, scale); + LgKawaseStep { iterations: step.iterations as u32, offset: step.offset } +} + +/// Minimum backdrop expansion (device px) that `iterations` Dual Kawase passes sample beyond a rect. +#[unsafe(no_mangle)] +pub extern "C" fn lg_kawase_expand_for_iterations(iterations: u32) -> u32 { + expand_for_iterations(iterations as usize) +} + /// Creates a zero-copy OpenGL / GLES Liquid Glass renderer on the currently active GL context. /// /// # Safety @@ -87,23 +118,24 @@ pub unsafe extern "C" fn lg_gl_create( return LgStatus::NullPointer; }; - let res = unsafe { - crate::gl_backend::GlRenderer::new(|symbol: &str| { - let Ok(cstr) = CString::new(symbol) else { - return core::ptr::null(); - }; - loader_fn(cstr.as_ptr(), user_data) - }) - }; - - match res { - Ok(renderer) => { - let boxed = Box::new(renderer); - unsafe { *out_renderer = Box::into_raw(boxed).cast::() }; - LgStatus::Ok + guarded(|| { + let res = unsafe { + crate::gl_backend::GlRenderer::new(|symbol: &str| { + let Ok(cstr) = CString::new(symbol) else { + return core::ptr::null(); + }; + loader_fn(cstr.as_ptr(), user_data) + }) + }; + match res { + Ok(renderer) => { + let boxed = Box::new(renderer); + unsafe { *out_renderer = Box::into_raw(boxed).cast::() }; + LgStatus::Ok + } + Err(status) => status, } - Err(status) => status, - } + }) } /// Renders one frame of Liquid Glass shapes from a borrowed backdrop texture into a borrowed target FBO. @@ -123,7 +155,7 @@ pub unsafe extern "C" fn lg_gl_render( } let r = unsafe { &mut *renderer.cast::() }; let p = unsafe { &*params }; - unsafe { r.render(p) } + guarded(|| unsafe { r.render(p) }) } /// Releases pooled internal scratch blur textures/FBOs without destroying compiled shaders. @@ -137,7 +169,10 @@ pub unsafe extern "C" fn lg_gl_invalidate_caches(renderer: *mut LgGlRenderer) { return; } let r = unsafe { &mut *renderer.cast::() }; - unsafe { r.invalidate_caches() }; + let _ = guarded(|| { + unsafe { r.invalidate_caches() }; + LgStatus::Ok + }); } /// Destroys all owned GL resources and frees the renderer handle. @@ -152,5 +187,8 @@ pub unsafe extern "C" fn lg_gl_destroy(renderer: *mut LgGlRenderer) { return; } let boxed = unsafe { Box::from_raw(renderer.cast::()) }; - unsafe { boxed.destroy() }; + let _ = guarded(|| { + unsafe { boxed.destroy() }; + LgStatus::Ok + }); } diff --git a/crates/liquidglass/src/gl_backend.rs b/crates/liquidglass/src/gl_backend.rs index bc46e77..9b367b3 100644 --- a/crates/liquidglass/src/gl_backend.rs +++ b/crates/liquidglass/src/gl_backend.rs @@ -3,7 +3,7 @@ // // Zero-copy raw OpenGL / OpenGL ES 3.0 backend (`glow`). // Borrows the host's active GL context, takes a borrowed `GLuint` backdrop texture and caller FBO, -// reuses pooled internal scratch Dual-Kawase blur textures (zero per-frame allocations), and +// reuses cached internal scratch Dual-Kawase blur textures (zero per-frame allocations), and // strictly saves & restores EVERY touched GL state via RAII so host compositors (KWin, Qt, GTK, // Flutter) never observe leaked GL state. @@ -31,87 +31,160 @@ struct GlBlurLevel { height: u32, } -struct GlBlurPool { +impl GlBlurLevel { + /// Allocates one linear, edge-clamped render target. A host pixel-unpack buffer is unbound + /// around the allocation so `glTexImage2D(.., NULL)` never reads from it. + unsafe fn new(gl: &glow::Context, width: u32, height: u32, format: LgPixelFormat) -> Result { + let (internal_fmt, data_fmt, data_ty) = gl_format_tuple(format); + unsafe { + let unpack = gl.get_parameter_i32(glow::PIXEL_UNPACK_BUFFER_BINDING); + if unpack != 0 { + gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, None); + } + let texture = gl.create_texture().map_err(|_| LgStatus::GlFramebufferError)?; + gl.bind_texture(glow::TEXTURE_2D, Some(texture)); + gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR as i32); + gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32); + gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32); + gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32); + gl.tex_image_2d( + glow::TEXTURE_2D, + 0, + internal_fmt as i32, + width as i32, + height as i32, + 0, + data_fmt, + data_ty, + glow::PixelUnpackData::Slice(None), + ); + if unpack != 0 { + gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, NonZeroU32::new(unpack as u32).map(glow::NativeBuffer)); + } + let fbo = match gl.create_framebuffer() { + Ok(fbo) => fbo, + Err(_) => { + gl.delete_texture(texture); + return Err(LgStatus::GlFramebufferError); + } + }; + gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fbo)); + gl.framebuffer_texture_2d(glow::FRAMEBUFFER, glow::COLOR_ATTACHMENT0, glow::TEXTURE_2D, Some(texture), 0); + if gl.check_framebuffer_status(glow::FRAMEBUFFER) != glow::FRAMEBUFFER_COMPLETE { + gl.delete_framebuffer(fbo); + gl.delete_texture(texture); + return Err(LgStatus::GlFramebufferError); + } + Ok(Self { texture, fbo, width, height }) + } + } + + unsafe fn delete(self, gl: &glow::Context) { + unsafe { + gl.delete_framebuffer(self.fbo); + gl.delete_texture(self.texture); + } + } +} + +/// One Dual Kawase chain for a given backdrop size, format and iteration count: `levels[i]` is +/// 1/2^(i+1) of the backdrop, `full` is the final upsample back to backdrop resolution (so the glass +/// shader reads the blur with a single tap instead of re-running the 8-tap upsample per sample). +struct GlBlurChain { base_size: [u32; 2], format: LgPixelFormat, levels: Vec, + full: GlBlurLevel, + last_used: u64, +} + +impl GlBlurChain { + unsafe fn new(gl: &glow::Context, base_size: [u32; 2], iterations: usize, format: LgPixelFormat) -> Result { + let full = unsafe { GlBlurLevel::new(gl, base_size[0].max(1), base_size[1].max(1), format)? }; + let mut levels: Vec = Vec::with_capacity(iterations); + for i in 1..=iterations { + let w = (base_size[0] >> i).max(1); + let h = (base_size[1] >> i).max(1); + match unsafe { GlBlurLevel::new(gl, w, h, format) } { + Ok(level) => levels.push(level), + Err(err) => { + unsafe { + full.delete(gl); + for level in levels { + level.delete(gl); + } + } + return Err(err); + } + } + } + Ok(Self { base_size, format, levels, full, last_used: 0 }) + } + + unsafe fn delete(self, gl: &glow::Context) { + unsafe { + self.full.delete(gl); + for level in self.levels { + level.delete(gl); + } + } + } +} + +/// Small LRU cache of blur chains. Hosts draw several glass surfaces per frame (windows of different +/// sizes, outputs with different formats); a single shared chain would be torn down and reallocated +/// on every draw that differs from the previous one. +struct GlBlurPool { + chains: Vec, + clock: u64, } impl GlBlurPool { + const MAX_CHAINS: usize = 6; + fn new() -> Self { - Self { base_size: [0, 0], format: LgPixelFormat::Rgba8Unorm, levels: Vec::new() } + Self { chains: Vec::new(), clock: 0 } } unsafe fn clear(&mut self, gl: &glow::Context) { - for lvl in self.levels.drain(..) { - unsafe { - gl.delete_framebuffer(lvl.fbo); - gl.delete_texture(lvl.texture); - } + for chain in self.chains.drain(..) { + unsafe { chain.delete(gl) }; } - self.base_size = [0, 0]; } + /// Returns the index of a chain matching the request, allocating (and evicting the least + /// recently used chain) only on a miss. unsafe fn ensure( &mut self, gl: &glow::Context, base_size: [u32; 2], iterations: usize, format: LgPixelFormat, - ) -> Result<(), LgStatus> { - if self.base_size == base_size && self.format == format && self.levels.len() == iterations { - return Ok(()); + ) -> Result { + self.clock += 1; + if let Some(idx) = self + .chains + .iter() + .position(|c| c.base_size == base_size && c.format == format && c.levels.len() == iterations) + { + self.chains[idx].last_used = self.clock; + return Ok(idx); } - unsafe { self.clear(gl) }; - self.base_size = base_size; - self.format = format; - let (internal_fmt, data_fmt, data_ty) = gl_format_tuple(format); - for i in 1..=iterations { - let w = (base_size[0] >> i).max(1); - let h = (base_size[1] >> i).max(1); - let texture = unsafe { gl.create_texture() }.map_err(|_| LgStatus::GlFramebufferError)?; - unsafe { - gl.bind_texture(glow::TEXTURE_2D, Some(texture)); - gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR as i32); - gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32); - gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32); - gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32); - gl.tex_image_2d( - glow::TEXTURE_2D, - 0, - internal_fmt as i32, - w as i32, - h as i32, - 0, - data_fmt, - data_ty, - glow::PixelUnpackData::Slice(None), - ); - } - let fbo = unsafe { gl.create_framebuffer() }.map_err(|_| { - unsafe { gl.delete_texture(texture) }; - LgStatus::GlFramebufferError - })?; - unsafe { - gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fbo)); - gl.framebuffer_texture_2d( - glow::FRAMEBUFFER, - glow::COLOR_ATTACHMENT0, - glow::TEXTURE_2D, - Some(texture), - 0, - ); - let status = gl.check_framebuffer_status(glow::FRAMEBUFFER); - if status != glow::FRAMEBUFFER_COMPLETE { - gl.delete_framebuffer(fbo); - gl.delete_texture(texture); - self.clear(gl); - return Err(LgStatus::GlFramebufferError); - } - } - self.levels.push(GlBlurLevel { texture, fbo, width: w, height: h }); + if self.chains.len() >= Self::MAX_CHAINS { + let lru = self + .chains + .iter() + .enumerate() + .min_by_key(|(_, c)| c.last_used) + .map(|(i, _)| i) + .unwrap_or(0); + let evicted = self.chains.swap_remove(lru); + unsafe { evicted.delete(gl) }; } - Ok(()) + let mut chain = unsafe { GlBlurChain::new(gl, base_size, iterations, format)? }; + chain.last_used = self.clock; + self.chains.push(chain); + Ok(self.chains.len() - 1) } } @@ -150,6 +223,8 @@ struct SavedGlState { vao: i32, array_buf: i32, ubo_binding: i32, + /// Indexed binding point 0, which the passes rebind with `glBindBufferBase`. + ubo_binding0: i32, active_tex: i32, tex0: i32, tex1: i32, @@ -185,6 +260,7 @@ impl SavedGlState { let vao = gl.get_parameter_i32(glow::VERTEX_ARRAY_BINDING); let array_buf = gl.get_parameter_i32(glow::ARRAY_BUFFER_BINDING); let ubo_binding = gl.get_parameter_i32(glow::UNIFORM_BUFFER_BINDING); + let ubo_binding0 = gl.get_parameter_indexed_i32(glow::UNIFORM_BUFFER_BINDING, 0); let active_tex = gl.get_parameter_i32(glow::ACTIVE_TEXTURE); gl.active_texture(glow::TEXTURE0); let tex0 = gl.get_parameter_i32(glow::TEXTURE_BINDING_2D); @@ -217,6 +293,7 @@ impl SavedGlState { vao, array_buf, ubo_binding, + ubo_binding0, active_tex, tex0, tex1, @@ -251,6 +328,8 @@ impl SavedGlState { gl.use_program(NonZeroU32::new(self.program as u32).map(glow::NativeProgram)); gl.bind_vertex_array(NonZeroU32::new(self.vao as u32).map(glow::NativeVertexArray)); gl.bind_buffer(glow::ARRAY_BUFFER, NonZeroU32::new(self.array_buf as u32).map(glow::NativeBuffer)); + // Indexed first: glBindBufferBase also rebinds the generic UNIFORM_BUFFER target. + gl.bind_buffer_base(glow::UNIFORM_BUFFER, 0, NonZeroU32::new(self.ubo_binding0 as u32).map(glow::NativeBuffer)); gl.bind_buffer(glow::UNIFORM_BUFFER, NonZeroU32::new(self.ubo_binding as u32).map(glow::NativeBuffer)); gl.active_texture(glow::TEXTURE0); gl.bind_texture(glow::TEXTURE_2D, NonZeroU32::new(self.tex0 as u32).map(glow::NativeTexture)); @@ -628,17 +707,34 @@ impl GlRenderer { max_scale = max_scale.max(s.scale); } let step = kawase_for_strength(max_strength, max_scale); - if let Err(err) = unsafe { - self.blur_pool.ensure(gl, [backdrop.width, backdrop.height], step.iterations, backdrop.format) - } { - return err; - } + let chain_idx = if step.iterations > 0 { + match unsafe { self.blur_pool.ensure(gl, [backdrop.width, backdrop.height], step.iterations, backdrop.format) } { + Ok(idx) => Some(idx), + Err(err) => return err, + } + } else { + None + }; let sharp_tex = to_native_tex(backdrop.texture_id); - let use_blur = !self.blur_pool.levels.is_empty(); - // 1. Dual Kawase blur chain into pooled internal FBOs (no blending, fullscreen triangle). - if use_blur { + // 1. Dual Kawase blur chain into cached internal FBOs (no blending, fullscreen triangle), + // finishing with one upsample back to backdrop resolution. + if let Some(idx) = chain_idx { + let chain = &self.blur_pool.chains[idx]; + let kawase_pass = |src: Option, src_size: [u32; 2], dst: &GlBlurLevel, flip_y: bool| unsafe { + let ubo = KawaseUniforms { + halfpixel: [0.5 / src_size[0].max(1) as f32, 0.5 / src_size[1].max(1) as f32], + offset: step.offset, + flip_y: if flip_y { 1.0 } else { 0.0 }, + }; + gl.bind_buffer(glow::UNIFORM_BUFFER, Some(self.kawase_ubo)); + gl.buffer_sub_data_u8_slice(glow::UNIFORM_BUFFER, 0, bytemuck::bytes_of(&ubo)); + gl.bind_texture(glow::TEXTURE_2D, src); + gl.bind_framebuffer(glow::FRAMEBUFFER, Some(dst.fbo)); + gl.viewport(0, 0, dst.width as i32, dst.height as i32); + gl.draw_arrays(glow::TRIANGLES, 0, 3); + }; unsafe { gl.disable(glow::BLEND); gl.bind_vertex_array(Some(self.empty_vao)); @@ -647,54 +743,35 @@ impl GlRenderer { // Downsample chain gl.use_program(Some(self.prog_down.program)); - let n = self.blur_pool.levels.len(); + let n = chain.levels.len(); for i in 0..n { - let (src_tex, sw, sh) = if i == 0 { - (sharp_tex, backdrop.width, backdrop.height) + let (src_tex, src_size) = if i == 0 { + (sharp_tex, [backdrop.width, backdrop.height]) } else { - let prev = &self.blur_pool.levels[i - 1]; - (Some(prev.texture), prev.width, prev.height) + let prev = &chain.levels[i - 1]; + (Some(prev.texture), [prev.width, prev.height]) }; - let dst = &self.blur_pool.levels[i]; - let ubo = KawaseUniforms { - halfpixel: [0.5 / sw.max(1) as f32, 0.5 / sh.max(1) as f32], - offset: step.offset, - flip_y: if i == 0 && backdrop.y_origin == LgYOrigin::TopLeft { 1.0 } else { 0.0 }, - }; - gl.bind_buffer(glow::UNIFORM_BUFFER, Some(self.kawase_ubo)); - gl.buffer_sub_data_u8_slice(glow::UNIFORM_BUFFER, 0, bytemuck::bytes_of(&ubo)); - gl.bind_texture(glow::TEXTURE_2D, src_tex); - gl.bind_framebuffer(glow::FRAMEBUFFER, Some(dst.fbo)); - gl.viewport(0, 0, dst.width as i32, dst.height as i32); - gl.draw_arrays(glow::TRIANGLES, 0, 3); + kawase_pass(src_tex, src_size, &chain.levels[i], i == 0 && backdrop.y_origin == LgYOrigin::TopLeft); } - // Upsample chain back to level 0 (half-resolution) + // Upsample chain back to level 0 (half resolution), then to full resolution. gl.use_program(Some(self.prog_up.program)); for i in (1..n).rev() { - let src = &self.blur_pool.levels[i]; - let dst = &self.blur_pool.levels[i - 1]; - let ubo = KawaseUniforms { - halfpixel: [0.5 / src.width.max(1) as f32, 0.5 / src.height.max(1) as f32], - offset: step.offset, - flip_y: 0.0, - }; - gl.bind_buffer(glow::UNIFORM_BUFFER, Some(self.kawase_ubo)); - gl.buffer_sub_data_u8_slice(glow::UNIFORM_BUFFER, 0, bytemuck::bytes_of(&ubo)); - gl.bind_texture(glow::TEXTURE_2D, Some(src.texture)); - gl.bind_framebuffer(glow::FRAMEBUFFER, Some(dst.fbo)); - gl.viewport(0, 0, dst.width as i32, dst.height as i32); - gl.draw_arrays(glow::TRIANGLES, 0, 3); + let src = &chain.levels[i]; + kawase_pass(Some(src.texture), [src.width, src.height], &chain.levels[i - 1], false); } + let l0 = &chain.levels[0]; + kawase_pass(Some(l0.texture), [l0.width, l0.height], &chain.full, false); } } // 2. Liquid Glass composite pass directly into caller-provided target FBO. - let (blur_tex, blur_size) = if use_blur { - let l0 = &self.blur_pool.levels[0]; - (Some(l0.texture), [l0.width, l0.height]) - } else { - (sharp_tex, [backdrop.width, backdrop.height]) + let (blur_tex, blur_size) = match chain_idx { + Some(idx) => { + let full = &self.blur_pool.chains[idx].full; + (Some(full.texture), [full.width, full.height]) + } + None => (sharp_tex, [backdrop.width, backdrop.height]), }; unsafe { @@ -751,7 +828,9 @@ impl GlRenderer { bytemuck::cast_slice(&self.scratch_verts), ); - let ubo = GlassUniforms::pack(shape, backdrop, target, use_blur, blur_size, step.offset); + // Only frosted shapes read the blur; a frost-0 shape next to a frosted one stays sharp. + let shape_blur = chain_idx.is_some() && strength_for_frost(shape.material.frost) > 0; + let ubo = GlassUniforms::pack(shape, backdrop, target, shape_blur, blur_size, step.offset); gl.bind_buffer(glow::UNIFORM_BUFFER, Some(self.glass_ubo)); gl.buffer_sub_data_u8_slice(glow::UNIFORM_BUFFER, 0, bytemuck::bytes_of(&ubo)); diff --git a/crates/liquidglass/src/wgpu_backend.rs b/crates/liquidglass/src/wgpu_backend.rs index 16ef31f..796a123 100644 --- a/crates/liquidglass/src/wgpu_backend.rs +++ b/crates/liquidglass/src/wgpu_backend.rs @@ -31,10 +31,28 @@ struct BlurLevel { height: u32, } +/// Dual Kawase chain: `levels[i]` is 1/2^(i+1) of the backdrop; `full` is the final upsample back to +/// backdrop resolution, so the glass shader reads the blur with a single tap. struct BlurPool { base_size: [u32; 2], format: wgpu::TextureFormat, levels: Vec, + full: Option, +} + +fn blur_level(device: &wgpu::Device, width: u32, height: u32, format: wgpu::TextureFormat) -> BlurLevel { + let tex = device.create_texture(&wgpu::TextureDescriptor { + label: Some("lg_kawase_level"), + size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); + BlurLevel { _texture: tex, view, width, height } } impl BlurPool { @@ -43,6 +61,7 @@ impl BlurPool { base_size: [0, 0], format: wgpu::TextureFormat::Rgba8Unorm, levels: Vec::new(), + full: None, } } @@ -57,24 +76,18 @@ impl BlurPool { return; } self.levels.clear(); + self.full = None; self.base_size = base_size; self.format = format; + if iterations == 0 { + return; + } for i in 1..=iterations { let w = (base_size[0] >> i).max(1); let h = (base_size[1] >> i).max(1); - let tex = device.create_texture(&wgpu::TextureDescriptor { - label: Some("lg_kawase_level"), - size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, - view_formats: &[], - }); - let view = tex.create_view(&wgpu::TextureViewDescriptor::default()); - self.levels.push(BlurLevel { _texture: tex, view, width: w, height: h }); + self.levels.push(blur_level(device, w, h, format)); } + self.full = Some(blur_level(device, base_size[0].max(1), base_size[1].max(1), format)); } } @@ -457,14 +470,18 @@ impl WgpuRenderer { self.run_kawase_step(&mut enc, up_pipe, &src.view, &dst.view, src.width, src.height, step.offset); self.queue.submit(Some(enc.finish())); } + // Final upsample from half to full resolution. + if let Some(full) = self.blur_pool.full.as_ref() { + let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + let l0 = &self.blur_pool.levels[0]; + self.run_kawase_step(&mut enc, up_pipe, &l0.view, &full.view, l0.width, l0.height, step.offset); + self.queue.submit(Some(enc.finish())); + } } - let blur_view = if use_blur { &self.blur_pool.levels[0].view } else { backdrop_view }; - let blur_size = if use_blur { - [self.blur_pool.levels[0].width, self.blur_pool.levels[0].height] - } else { - [backdrop.width, backdrop.height] - }; + let full = self.blur_pool.full.as_ref().filter(|_| use_blur); + let blur_view = full.map_or(backdrop_view, |f| &f.view); + let blur_size = full.map_or([backdrop.width, backdrop.height], |f| [f.width, f.height]); let glass_pipe = self.glass_pipeline.as_ref().unwrap(); let bounds = LgRect::new(0.0, 0.0, backdrop.width as f32, backdrop.height as f32); @@ -488,7 +505,9 @@ impl WgpuRenderer { } self.queue.write_buffer(&self.vertex_buf, 0, bytemuck::cast_slice(&self.scratch_verts)); - let ubo = GlassUniforms::pack(shape, backdrop, target, use_blur, blur_size, step.offset); + // Only frosted shapes read the blur; a frost-0 shape next to a frosted one stays sharp. + let shape_blur = use_blur && strength_for_frost(shape.material.frost) > 0; + let ubo = GlassUniforms::pack(shape, backdrop, target, shape_blur, blur_size, step.offset); self.queue.write_buffer(&self.glass_uniform_buf, 0, bytemuck::bytes_of(&ubo)); let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { diff --git a/dock/src/backend/FluctusApplet.cpp b/dock/src/backend/FluctusApplet.cpp index 03c4a23..ccc1ed1 100644 --- a/dock/src/backend/FluctusApplet.cpp +++ b/dock/src/backend/FluctusApplet.cpp @@ -67,12 +67,6 @@ QDBusMessage effectsCall(const QString &method, const QString &id) { return message; } -bool effectLoaded(const QString &id) { - constexpr int kTimeoutMs = 500; - const QDBusReply reply = QDBusConnection::sessionBus().call(effectsCall(QStringLiteral("isEffectLoaded"), id), QDBus::Block, kTimeoutMs); - return reply.isValid() && reply.value(); -} - /// (state, provider) from what is installed and loaded, in detection order. std::pair detectGlass(bool fluctusLoaded, bool thirdPartyLoaded) { if (fluctusLoaded) { @@ -166,12 +160,15 @@ void FluctusApplet::init() { QDBusConnection::sessionBus(), QDBusServiceWatcher::WatchForOwnerChange); connect(m_fluctusGlassWatcher.get(), &QDBusServiceWatcher::serviceOwnerChanged, this, &FluctusApplet::refreshGlassEffectState); - // First check is synchronous (bounded) so a Liquid Glass dock never starts as Frosted. - const auto [state, provider] = detectGlass( - fluctus::glass::GlassRequest::serviceRegistered(), - effectInstalled(kThirdPartyGlassId) && effectLoaded(kThirdPartyGlassId)); + // Seed from what is answered locally (Fluctus Glass owns a bus name, so a Fluctus Glass dock never + // starts as Frosted), then ask KWin about third-party glass asynchronously: a blocking call here + // stalled plasmashell's startup for up to half a second. + const auto [state, provider] = detectGlass(fluctus::glass::GlassRequest::serviceRegistered(), false); m_glassEffectState = state; m_glassProvider = provider; + if (state != 2) { + refreshGlassEffectState(); + } // The containment can finish wiring its applets after init(); re-check once settled. QTimer::singleShot(0, this, &FluctusApplet::attachContainment); } diff --git a/dock/src/core/DockPhysicsEngine.cpp b/dock/src/core/DockPhysicsEngine.cpp index 7aeac34..743042e 100644 --- a/dock/src/core/DockPhysicsEngine.cpp +++ b/dock/src/core/DockPhysicsEngine.cpp @@ -687,6 +687,8 @@ double DockPhysicsEngine::mapCanonicalCoordinate( } bool DockPhysicsEngine::step(double dt, double containerWidth, double containerHeight) { + m_lastContainerWidth = containerWidth; + m_lastContainerHeight = containerHeight; const ResolvedMetrics metrics = resolveMetrics(containerWidth, containerHeight); const double dpr = std::max(1.0, m_config.devicePixelRatio); const double scaleSpan = std::max(1.0, metrics.baseIconSize * (metrics.maxScale - 1.0)); @@ -774,15 +776,16 @@ bool DockPhysicsEngine::isSettled() const noexcept { if (m_dirty) { return false; } + const ResolvedMetrics metrics = resolveMetrics(m_lastContainerWidth, m_lastContainerHeight); const double dpr = std::max(1.0, m_config.devicePixelRatio); - const double scaleSpan = std::max(1.0, m_config.baseIconSize * (m_config.effectiveMaxScale() - 1.0)); + const double scaleSpan = std::max(1.0, metrics.baseIconSize * (metrics.maxScale - 1.0)); const double alphaPosEps = 0.25 / (scaleSpan * dpr); const double alphaVelEps = alphaPosEps * 4.0; if (!m_hoverSpring.isSettled(alphaPosEps, alphaVelEps)) { return false; } - const double weightPosEps = 0.25 / (std::max(1.0, m_config.baseIconSize) * dpr); + const double weightPosEps = 0.25 / (std::max(1.0, metrics.baseIconSize) * dpr); const double weightVelEps = weightPosEps * 4.0; const double reorderPosEps = 0.25 / dpr; const double reorderVelEps = reorderPosEps * 4.0; diff --git a/dock/src/core/DockPhysicsEngine.hpp b/dock/src/core/DockPhysicsEngine.hpp index 754cdc0..898373d 100644 --- a/dock/src/core/DockPhysicsEngine.hpp +++ b/dock/src/core/DockPhysicsEngine.hpp @@ -221,6 +221,10 @@ class DockPhysicsEngine { double m_pointerCanonical{0.0}; bool m_hasPointerCanonical{false}; bool m_dirty{true}; + // Container of the last step(): isSettled() resolves the same metrics (and so the same settle + // thresholds) as step(), or the driver could stop with the hover spring just short of rest. + double m_lastContainerWidth{0.0}; + double m_lastContainerHeight{0.0}; }; } // namespace fluctus::core diff --git a/dock/src/quick/DockIconItem.cpp b/dock/src/quick/DockIconItem.cpp index a4730d8..ca1f499 100644 --- a/dock/src/quick/DockIconItem.cpp +++ b/dock/src/quick/DockIconItem.cpp @@ -3,7 +3,7 @@ #include #include #include -#include +#include #include #include @@ -263,9 +263,10 @@ QImage DockIconItem::resampleLanczos3(const QImage &src, int targetWidth, int ta QImage DockIconItem::loadHighResSource(int targetPhysicalPx) const { const QIcon::Mode mode = m_active ? QIcon::Active : QIcon::Normal; - // Always request high-resolution artwork (at least 128 px, up to 256 px) so QIcon - // never hands back a small pre-downscaled 22 px bitmap when higher-res art or SVG exists. - const int requestPx = std::clamp(std::max(128, targetPhysicalPx * 4), 128, 256); + // Request high-resolution artwork so QIcon never hands back a small pre-downscaled 22 px + // bitmap when higher-res art or SVG exists: up to 4x oversampling for small icons, and never + // less than the target itself (large icons on HiDPI were upscaled from 256 px and looked soft). + const int requestPx = std::clamp(std::max(std::min(targetPhysicalPx * 4, 256), targetPhysicalPx), 128, 1024); auto fromQIcon = [&](const QIcon &icon) -> QImage { if (icon.isNull()) { @@ -340,23 +341,26 @@ QSGNode *DockIconItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *da return nullptr; } - auto *node = static_cast(oldNode); + auto *node = static_cast(oldNode); if (!node) { - node = new QSGSimpleTextureNode(); + node = window()->createImageNode(); node->setOwnsTexture(true); m_textureDirty = true; } if (m_textureDirty || !node->texture()) { + // The image is rendered at the magnified size and drawn scaled down at rest (delegates have + // a fixed size and are scaled per frame), so mipmaps keep resting icons from aliasing. QSGTexture *tex = window()->createTextureFromImage( m_cachedImage, - QQuickWindow::TextureHasAlphaChannel + QQuickWindow::CreateTextureOptions(QQuickWindow::TextureHasAlphaChannel) | QQuickWindow::TextureHasMipmaps ); node->setTexture(tex); m_textureDirty = false; } node->setFiltering(m_exactPixelSampling ? QSGTexture::Nearest : QSGTexture::Linear); + node->setMipmapFiltering(m_exactPixelSampling ? QSGTexture::None : QSGTexture::Linear); node->setRect(QRectF(0.0, 0.0, width(), height())); return node; } diff --git a/dock/src/quick/DockLayoutItem.cpp b/dock/src/quick/DockLayoutItem.cpp index 0944146..da15791 100644 --- a/dock/src/quick/DockLayoutItem.cpp +++ b/dock/src/quick/DockLayoutItem.cpp @@ -7,6 +7,7 @@ #include #include +#include #include namespace fluctus::quick { @@ -41,12 +42,23 @@ namespace { // Writing an unchanged value to a QML `var` property still emits its change signal // (QIcon has no QVariant equality), which makes every Kirigami.Icon reload its source and // flicker whenever the task model changes (e.g. while an app is starting). Only write deltas. -void setPropertyIfChanged(QObject *obj, const char *name, const QVariant &value) { +bool setPropertyIfChanged(QObject *obj, const char *name, const QVariant &value) { if (!sameVariant(obj->property(name), value)) { obj->setProperty(name, value); + return true; } + return false; } +// Every role syncDelegateProperties(), readTaskIdentity() and the bounce/attention checks read. +constexpr std::array kUsedRoleNames{ + "IsActive", "IsLauncher", "IsWindow", "IsStartup", "IsDemandingAttention", "IsMinimized", + "IsMaximized", "IsFullScreen", "IsKeepAbove", "IsKeepBelow", "IsClosable", "IsMinimizable", + "IsMaximizable", "IsMovable", "IsResizable", "IsFullScreenable", "IsOnAllVirtualDesktops", + "VirtualDesktops", "WinIdList", "IsGroupParent", "ChildCount", "AppId", "AppName", "AppPid", + "LauncherUrlWithoutIcon", "LauncherUrl", "StorageId", +}; + } // namespace DockLayoutItem::DockLayoutItem(QQuickItem *parent) @@ -105,6 +117,7 @@ DockLayoutItem::DockLayoutItem(QQuickItem *parent) const bool settled = m_engine.isSettled(); if (settled) { + flushGlassRegion(false); publishDelegateGeometries(); } return active && !settled; @@ -127,6 +140,7 @@ void DockLayoutItem::setModel(QAbstractItemModel *model) { } m_model = model; + rebuildRoleCache(); if (m_model) { connect(m_model, &QAbstractItemModel::modelReset, this, &DockLayoutItem::onModelReset); @@ -568,7 +582,7 @@ void DockLayoutItem::publishDelegateGeometries() { } const core::DockFrame frame = m_engine.computeFrame(width(), height()); - for (const auto &entry : m_delegates) { + for (auto &entry : m_delegates) { if (entry.ghost || !entry.modelIndex.isValid() || !entry.item) { continue; } @@ -587,6 +601,11 @@ void DockLayoutItem::publishDelegateGeometries() { static_cast(std::round(it->restingRect.width)), static_cast(std::round(it->restingRect.height)) ); + // Every hover settles here; only tell the window manager what actually moved. + if (globalRect == entry.publishedGeometry) { + continue; + } + entry.publishedGeometry = globalRect; QMetaObject::invokeMethod( m_model, @@ -641,6 +660,7 @@ void DockLayoutItem::updatePolish() { } void DockLayoutItem::onModelReset() { + rebuildRoleCache(); m_reconcileTimer.stop(); m_suppressNextLayoutReorder = false; rebuildAllDelegates(); @@ -1160,10 +1180,14 @@ void DockLayoutItem::onDataChanged( const QModelIndex &bottomRight, const QList &roles ) { - Q_UNUSED(roles); if (!m_model || topLeft.parent().isValid() || m_reconcileTimer.isActive()) { return; } + // TasksModel reports geometry, title and screen changes of every window here (per frame while + // one is dragged); most of them change nothing the dock shows. + if (!touchesUsedRoles(roles)) { + return; + } const int first = topLeft.row(); const int last = bottomRight.row(); @@ -1177,7 +1201,9 @@ void DockLayoutItem::onDataChanged( } } - updateAttentionState(); + if (roles.isEmpty() || roles.contains(m_attentionRole)) { + updateAttentionState(); + } if (!m_engine.isSettled()) { m_driver->ensureRunning(); } @@ -1274,6 +1300,14 @@ QQuickItem *DockLayoutItem::createDelegateForRow(int row, std::uint64_t slotId, return item; } +namespace { +QMetaProperty findProperty(const QObject *item, const char *name) { + const QMetaObject *mo = item->metaObject(); + const int index = mo->indexOfProperty(name); + return index >= 0 ? mo->property(index) : QMetaProperty(); +} +} // namespace + void DockLayoutItem::syncDelegateProperties(ManagedDelegate &entry, int activeIndex) { if (!entry.item || !m_model || !entry.modelIndex.isValid()) { return; @@ -1289,8 +1323,14 @@ void DockLayoutItem::syncDelegateProperties(ManagedDelegate &entry, int activeIn return v.isValid() ? v : fallback; }; + if (!entry.slotScaleProperty.isValid()) { + entry.slotScaleProperty = findProperty(entry.item, "slotScale"); + entry.bounceOffsetProperty = findProperty(entry.item, "bounceOffset"); + } setPropertyIfChanged(entry.item, "taskIndex", activeIndex); - setPropertyIfChanged(entry.item, "modelIndex", QVariant::fromValue(idx)); + if (setPropertyIfChanged(entry.item, "modelIndex", QVariant::fromValue(idx))) { + entry.publishedGeometry = {}; // another task in this slot: publish its geometry afresh + } setPropertyIfChanged(entry.item, "displayTitle", m_model->data(idx, Qt::DisplayRole).toString()); setPropertyIfChanged(entry.item, "decorationIcon", m_model->data(idx, Qt::DecorationRole)); setPropertyIfChanged(entry.item, "isActive", readRole(QByteArrayLiteral("IsActive"), false).toBool()); @@ -1315,7 +1355,9 @@ void DockLayoutItem::syncDelegateProperties(ManagedDelegate &entry, int activeIn setPropertyIfChanged(entry.item, "isFullScreenable", readRole(QByteArrayLiteral("IsFullScreenable"), true).toBool()); setPropertyIfChanged(entry.item, "isOnAllVirtualDesktops", readRole(QByteArrayLiteral("IsOnAllVirtualDesktops"), false).toBool()); setPropertyIfChanged(entry.item, "virtualDesktops", readRole(QByteArrayLiteral("VirtualDesktops"), QVariantList())); - setPropertyIfChanged(entry.item, "winIdList", readRole(QByteArrayLiteral("WinIdList"), QVariantList())); + if (setPropertyIfChanged(entry.item, "winIdList", readRole(QByteArrayLiteral("WinIdList"), QVariantList()))) { + entry.publishedGeometry = {}; // new windows in the group need the geometry too + } setPropertyIfChanged(entry.item, "isGroupParent", readRole(QByteArrayLiteral("IsGroupParent"), false).toBool()); setPropertyIfChanged(entry.item, "childCount", readRole(QByteArrayLiteral("ChildCount"), 0).toInt()); const QString appId = readRole(QByteArrayLiteral("AppId"), QString()).toString(); @@ -1391,8 +1433,16 @@ void DockLayoutItem::applyCurrentFrame(const core::DockFrame &frame) { ? std::clamp(slot.weight * slot.weight, 0.0, 1.0) : std::clamp(slot.weight * 1.35, 0.0, 1.0); item->setOpacity(visualOpacity); - item->setProperty("slotScale", slot.scale); - item->setProperty("bounceOffset", slot.bounceOffset); + if (!it->slotScaleProperty.isValid()) { + it->slotScaleProperty = findProperty(item, "slotScale"); + it->bounceOffsetProperty = findProperty(item, "bounceOffset"); + } + if (it->slotScaleProperty.isValid()) { + it->slotScaleProperty.write(item, slot.scale); + } + if (it->bounceOffsetProperty.isValid()) { + it->bounceOffsetProperty.write(item, slot.bounceOffset); + } } const QRectF nextPill = toQRectF(frame.pillRect); @@ -1438,13 +1488,17 @@ void DockLayoutItem::updateBlurRegion() { if (!window() || m_pillRect.isEmpty()) { m_blurController->setWindowPillRect({}); m_blurController->setCustomRegion({}); - m_glass->setRegion({}, 0.0); + m_glassRegion = {}; + m_glassRadius = 0.0; + flushGlassRegion(true); return; } const QPointF topLeftInWindow = mapToScene(m_pillRect.topLeft()); const QRectF rectInWindow(topLeftInWindow, m_pillRect.size()); m_blurController->setWindowPillRect(rectInWindow); - m_glass->setRegion(rectInWindow, m_pillCornerRadius); + m_glassRegion = rectInWindow; + m_glassRadius = m_pillCornerRadius; + flushGlassRegion(false); m_blurController->setCustomRegion( m_blurMask.isEmpty() ? QRegion() : m_blurMask.translated(topLeftInWindow.toPoint()) ); @@ -1465,16 +1519,47 @@ QQuickItem::TransformOrigin DockLayoutItem::transformOriginForEdge() const noexc } int DockLayoutItem::roleIdByName(const QByteArray &name) const { + return m_roleIds.value(name, -1); +} + +void DockLayoutItem::rebuildRoleCache() { + m_roleIds.clear(); + m_usedRoles.clear(); + m_attentionRole = -1; if (!m_model) { - return -1; + return; } const auto roles = m_model->roleNames(); for (auto it = roles.cbegin(); it != roles.cend(); ++it) { - if (it.value() == name) { - return it.key(); + m_roleIds.insert(it.value(), it.key()); + } + m_usedRoles = {Qt::DisplayRole, Qt::DecorationRole}; + for (const char *name : kUsedRoleNames) { + if (const int role = roleIdByName(QByteArray(name)); role >= 0) { + m_usedRoles.insert(role); } } - return -1; + m_attentionRole = roleIdByName(QByteArrayLiteral("IsDemandingAttention")); +} + +bool DockLayoutItem::touchesUsedRoles(const QList &roles) const { + if (roles.isEmpty()) { + return true; // "everything may have changed" + } + return std::ranges::any_of(roles, [this](int role) { + return m_usedRoles.contains(role); + }); +} + +void DockLayoutItem::flushGlassRegion(bool force) { + // The effect takes the pill's geometry from the window's blur region, which follows every + // frame; the request only has to pick that piece out. Sending it over D-Bus on every animation + // frame cost a round trip and a full rebuild in KWin per frame, so mid-animation it waits. + if (!force && m_glassRegionSent && !m_engine.isSettled()) { + return; + } + m_glass->setRegion(m_glassRegion, m_glassRadius); + m_glassRegionSent = true; } bool DockLayoutItem::isRowBouncing(int row) const { diff --git a/dock/src/quick/DockLayoutItem.hpp b/dock/src/quick/DockLayoutItem.hpp index 1f62dfb..b970f71 100644 --- a/dock/src/quick/DockLayoutItem.hpp +++ b/dock/src/quick/DockLayoutItem.hpp @@ -7,11 +7,14 @@ #include "FluctusGlass/GlassRequest.hpp" #include +#include +#include #include #include #include #include #include +#include #include #include #include @@ -254,6 +257,9 @@ private Q_SLOTS: bool isStartup{false}; bool isLauncher{false}; TaskIdentity identity{}; + QRect publishedGeometry; ///< last minimize geometry sent to the window manager + QMetaProperty slotScaleProperty; ///< per-frame properties, resolved once per delegate + QMetaProperty bounceOffsetProperty; }; void scheduleReconcile(); @@ -274,6 +280,11 @@ private Q_SLOTS: [[nodiscard]] static bool matchesTaskIdentity(const TaskIdentity &a, const TaskIdentity &b) noexcept; [[nodiscard]] QQuickItem::TransformOrigin transformOriginForEdge() const noexcept; [[nodiscard]] int roleIdByName(const QByteArray &name) const; + void rebuildRoleCache(); + /// True when `roles` (from dataChanged) may change anything a delegate shows. + [[nodiscard]] bool touchesUsedRoles(const QList &roles) const; + /// Sends the pill to the glass effect (D-Bus). During animations only once settled. + void flushGlassRegion(bool force); [[nodiscard]] bool isRowBouncing(int row) const; [[nodiscard]] bool isRowDemandingAttention(int row) const; @@ -299,6 +310,16 @@ private Q_SLOTS: bool m_hasAttentionTask{false}; bool m_suppressNextLayoutReorder{false}; double m_lastDelegateLogicalSize{0.0}; + + // Role ids of m_model by name. libtaskmanager builds roleNames() afresh on every call, and a + // delegate sync reads ~35 roles, so the lookup is cached per model. + QHash m_roleIds; + QSet m_usedRoles; + int m_attentionRole{-1}; + + QRectF m_glassRegion; + qreal m_glassRadius{0.0}; + bool m_glassRegionSent{false}; }; } // namespace fluctus::quick diff --git a/dock/tests/test_dock_physics.cpp b/dock/tests/test_dock_physics.cpp index 79f60e1..e874ba4 100644 --- a/dock/tests/test_dock_physics.cpp +++ b/dock/tests/test_dock_physics.cpp @@ -203,6 +203,42 @@ private Q_SLOTS: QCOMPARE(engine.computeFrame(W, H).hoverAlpha, 0.0); } + void testSettlesAtRestWithAutoScaledMetrics() { + // With auto-scale the resolved icon size / zoom differ from the configured ones. The settle + // check must use the resolved values (as step() does), or the driver stops with the hover + // spring a hair above 0 and the icons never get pixel-snapped at rest. + DockConfig cfg{}; + cfg.autoScaleToPanel = true; + cfg.baseIconSize = 16.0; // configured values the auto-scale overrides + cfg.maxScale = 1.1; + cfg.devicePixelRatio = 1.0; + DockPhysicsEngine engine{}; + engine.setConfig(cfg); + for (std::size_t i = 0; i < 6; ++i) { + engine.insertSlot(i, false); + } + const double W = 1600.0; + const double H = 220.0; // thick panel: resolved icons far larger than 16 px + const DockFrame rest = engine.computeFrame(W, H); + engine.updatePointer(Vec2{W * 0.5, H - 20.0}, W, H); + QVERIFY(engine.isPointerEngaged()); + for (int i = 0; i < 60; ++i) { + engine.step(1.0 / 60.0, W, H); + } + engine.clearPointer(); + int steps = 0; + while (steps < 600) { + const bool changed = engine.step(1.0 / 60.0, W, H); + ++steps; + if (!changed || engine.isSettled()) { + break; + } + } + QVERIFY(engine.isSettled()); + QCOMPARE(engine.computeFrame(W, H).hoverAlpha, 0.0); + QVERIFY(rest.restingLength > 0.0); + } + void testGhostSlotRemovalAndRestingInsertionIndex() { DockPhysicsEngine engine{}; for (std::size_t i = 0; i < 5; ++i) { diff --git a/docs/development.md b/docs/development.md index 58f1966..18dddd5 100644 --- a/docs/development.md +++ b/docs/development.md @@ -33,7 +33,9 @@ Shared things live at the root and nowhere else. (`cmake/FluctusSettings.cmake`). - **Rust.** The root `Cargo.toml` is a workspace with one `Cargo.lock` and one `target/`. `cargo test`, CI and the CMake build of the KWin effect all share it. CMake asks for - `target/release/libliquidglass.a`, so the release and sanitizer presets link the same Rust build. + `target/release-ffi/libliquidglass.a`, so the release and sanitizer presets link the same Rust + build. `release-ffi` is the release profile with `panic = "unwind"`, so the FFI can turn a Rust + panic into an error code instead of aborting KWin. Packagers can move it with `-DFLUCTUS_CARGO_TARGET_DIR=…`. - **CI** caches `ccache`, the CMake trees, Cargo's registry and `target/`. diff --git a/glass/CMakeLists.txt b/glass/CMakeLists.txt index 31092bd..eb3c6b1 100644 --- a/glass/CMakeLists.txt +++ b/glass/CMakeLists.txt @@ -34,7 +34,7 @@ set(FLUCTUS_GLASS_KWIN_VERSION "${KWin_VERSION}" CACHE INTERNAL "KWin version Fl # and CI reuse one compiled copy. Packagers can point FLUCTUS_CARGO_TARGET_DIR elsewhere. set(FLUCTUS_CARGO_TARGET_DIR "${PROJECT_SOURCE_DIR}/target" CACHE PATH "Cargo target directory for Rust crates") set(LG_CRATE_DIR "${PROJECT_SOURCE_DIR}/crates/liquidglass") -set(LG_RUST_LIB "${FLUCTUS_CARGO_TARGET_DIR}/release/libliquidglass.a") +set(LG_RUST_LIB "${FLUCTUS_CARGO_TARGET_DIR}/release-ffi/libliquidglass.a") set(LG_RUST_HEADER "${LG_CRATE_DIR}/include/liquidglass.h") file(GLOB LG_RUST_SOURCES CONFIGURE_DEPENDS @@ -51,7 +51,7 @@ add_custom_command( OUTPUT "${LG_RUST_LIB}" "${LG_RUST_HEADER}" COMMAND "${CARGO_EXECUTABLE}" build --manifest-path "${LG_CRATE_DIR}/Cargo.toml" - --release + --profile release-ffi --locked --no-default-features --features "gl,ffi" @@ -63,10 +63,13 @@ add_custom_command( add_custom_target(fluctus_liquidglass_rust DEPENDS "${LG_RUST_LIB}" "${LG_RUST_HEADER}") +find_package(Threads REQUIRED) add_library(Fluctus::LiquidGlassRust STATIC IMPORTED GLOBAL) set_target_properties(Fluctus::LiquidGlassRust PROPERTIES IMPORTED_LOCATION "${LG_RUST_LIB}" INTERFACE_INCLUDE_DIRECTORIES "${LG_CRATE_DIR}/include" + # What the Rust standard library inside the staticlib needs from the final link. + INTERFACE_LINK_LIBRARIES "Threads::Threads;${CMAKE_DL_LIBS};m" ) add_dependencies(Fluctus::LiquidGlassRust fluctus_liquidglass_rust) @@ -82,7 +85,7 @@ add_library(fluctus_glass_logic STATIC set_target_properties(fluctus_glass_logic PROPERTIES AUTOMOC ON POSITION_INDEPENDENT_CODE ON) target_include_directories(fluctus_glass_logic PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src) target_link_libraries(fluctus_glass_logic - PUBLIC Qt6::Core Qt6::Gui Qt6::DBus Fluctus::GlassProtocol + PUBLIC Qt6::Core Qt6::Gui Qt6::DBus Fluctus::GlassProtocol Fluctus::LiquidGlassRust PRIVATE fluctus_warnings ) diff --git a/glass/kcm/glassconfig.cpp b/glass/kcm/glassconfig.cpp index 6822051..49aa73e 100644 --- a/glass/kcm/glassconfig.cpp +++ b/glass/kcm/glassconfig.cpp @@ -114,6 +114,8 @@ GlassEffectConfig::GlassEffectConfig(QObject *parent, const KPluginMetaData &dat globalForm->addRow(checkBox("kcfg_GlobalMenus", i18n("Menus, popups and tooltips"), global)); globalForm->addRow(checkBox("kcfg_GlobalPanels", i18n("Panels and docks"), global)); globalForm->addRow(checkBox("kcfg_GlobalNotifications", i18n("Notifications and on-screen displays"), global)); + globalForm->addRow(checkBox("kcfg_PointerEffectsOnWindows", + i18n("Pointer light and lens on application windows (uses more power)"), global)); globalForm->addRow(i18n("Never use glass for:"), classList("kcfg_ExcludedClasses", global)); globalForm->addRow(i18n("Always use glass for:"), classList("kcfg_ForcedClasses", global)); layout->addWidget(global); diff --git a/glass/src/fluctusglass.kcfg b/glass/src/fluctusglass.kcfg index b4d2474..30b4e2e 100644 --- a/glass/src/fluctusglass.kcfg +++ b/glass/src/fluctusglass.kcfg @@ -40,6 +40,8 @@ true + + false 6032 diff --git a/glass/src/glasseffect.cpp b/glass/src/glasseffect.cpp index 2395628..c9df5fe 100644 --- a/glass/src/glasseffect.cpp +++ b/glass/src/glasseffect.cpp @@ -64,71 +64,42 @@ constexpr std::chrono::milliseconds kPointerFade{140}; constexpr qreal kPointerHitMargin = 24.0; constexpr qreal kShapeInsetLimit = 64.0; -/// KWin blur's strength table (1..15 → Dual Kawase iterations + offset) and the minimum -/// expansion each iteration needs so it never samples past the captured backdrop. +/// KWin Blur's strength table (strength 1..15 -> Dual Kawase iterations + offset) and the minimum +/// expansion each iteration needs, from the renderer (crates/liquidglass) so both sides agree. struct KawaseStep { std::size_t iterations; float offset; }; -struct KawaseLevel { - float minOffset; - float maxOffset; - int expandSize; -}; -constexpr std::array kKawaseLevels{{ - {1.0F, 2.0F, 10}, - {2.0F, 3.0F, 20}, - {2.0F, 5.0F, 50}, - {3.0F, 8.0F, 150}, -}}; - -const std::vector &kawaseSteps() { - static const std::vector steps = [] { - std::vector out; - constexpr int kSteps = 15; - float sum = 0.0F; - for (const KawaseLevel &level : kKawaseLevels) { - sum += level.maxOffset - level.minOffset; - } - int remaining = kSteps; - for (std::size_t i = 0; i < kKawaseLevels.size(); ++i) { - const float span = kKawaseLevels[i].maxOffset - kKawaseLevels[i].minOffset; - int count = static_cast(std::ceil(span / sum * static_cast(kSteps))); - remaining -= count; - if (remaining < 0) { - count += remaining; - } - for (int j = 1; j <= count; ++j) { - out.push_back({i + 1, kKawaseLevels[i].minOffset + span / static_cast(count) * static_cast(j)}); - } - } - return out; - }(); - return steps; -} -/// strength 1..15 (KWin units). Device-resolution captures need one more iteration on HiDPI -/// to blur as far as KWin's logical-resolution blur does. +/// strength 1..15 (KWin units; 0 = no blur). Device-resolution captures get one more iteration on +/// HiDPI to blur as far as KWin's logical-resolution blur does. KawaseStep kawaseForStrength(int strength, qreal scale) { - const auto &steps = kawaseSteps(); - KawaseStep step = steps[static_cast(std::clamp(strength, 1, static_cast(steps.size())) - 1)]; - if (scale >= 1.5 && step.iterations < kKawaseLevels.size()) { - ++step.iterations; - } - return step; + const LgKawaseStep step = lg_kawase_for_strength(static_cast(std::max(strength, 0)), static_cast(scale)); + return {.iterations = step.iterations, .offset = step.offset}; } -/// Frost 0..1 → KWin strength (0 = sharp, no blur). Eased so the light frost of Liquid Glass -/// (~0.15) stays a soft veil while Frosted / Acrylic (0.75+) reach stock blur strength. +/// Frost 0..1 -> KWin strength (0 = sharp, no blur), eased so the light frost of Liquid Glass stays +/// a soft veil while Frosted / Acrylic (0.75+) reach stock blur strength. int strengthForFrost(qreal frost) { - if (frost < 0.01) { - return 0; - } - return std::clamp(static_cast(std::lround(15.0 * std::pow(frost, 1.5))), 1, 15); + return static_cast(lg_strength_for_frost(static_cast(frost))); } int expandForIterations(std::size_t iterations) { - return iterations == 0 ? 0 : kKawaseLevels[std::min(iterations, kKawaseLevels.size()) - 1].expandSize; + return static_cast(lg_kawase_expand_for_iterations(static_cast(iterations))); +} + +/// Capture slack: grow the captured area by this fraction per side (at least kCaptureSlackMin +/// logical px) so it can follow a growing or moving shape for a while without reallocating. +constexpr qreal kCaptureSlack = 0.125; +constexpr qreal kCaptureSlackMin = 32.0; +/// A capture this many times larger than needed is reallocated smaller. +constexpr qreal kCaptureMaxOversize = 2.5; +/// Capture textures of windows not drawn for this long are freed. +constexpr std::chrono::seconds kRenderDataIdle{5}; + +bool isAppWindow(const EffectWindow *w) { + return !(w->isDock() || w->isMenu() || w->isPopupMenu() || w->isDropdownMenu() || w->isTooltip() + || w->isPopupWindow() || w->isNotification() || w->isCriticalNotification() || w->isOnScreenDisplay()); } QMatrix4x4 saturationMatrix(qreal saturation) { @@ -390,6 +361,7 @@ void GlassEffect::reconfigure(ReconfigureFlags) { m_menuRadius = config->menuRadius(); m_panelRadius = config->panelRadius(); m_pointerEffects = config->pointerEffects(); + m_pointerEffectsOnWindows = config->pointerEffectsOnWindows(); Material m; m.refraction = config->refraction(); @@ -451,9 +423,13 @@ void GlassEffect::slotWindowAdded(EffectWindow *w) { if (QWindow *internal = w->internalWindow()) { internal->installEventFilter(this); } - // Refraction samples beyond our own window: changes there must repaint the glass too. + // Refraction samples beyond our own window: changes there must repaint the glass too. The + // signal carries no region, so only note the window; refreshBackdrops() checks what it really + // repainted once the frame's damage is known. connections.push_back(connect(w, &EffectWindow::windowDamaged, this, [this, w]() { - backdropChanged(w); + if (!m_windows.empty()) { + m_damagedWindows[w] = ++m_damageSerial; + } })); auto watchDecoration = [this, w, &connections]() { if (KDecoration3::Decoration *decoration = w->decoration()) { @@ -490,6 +466,7 @@ void GlassEffect::slotWindowDeleted(EffectWindow *w) { m_windowConnections.erase(it); } const QUuid id = w->internalId(); + m_damagedWindows.erase(w); releaseWindow(w); backdropChanged(w); m_service.unbindWindow(id); @@ -504,6 +481,7 @@ void GlassEffect::slotViewRemoved(RenderView *view) { for (auto &[window, state] : m_windows) { state.render.erase(view); } + m_viewDamageSerial.erase(view); } bool GlassEffect::eventFilter(QObject *watched, QEvent *event) { @@ -647,6 +625,7 @@ void GlassEffect::rebuildShapes(EffectWindow *w, WindowState &state) { const QRectF oldBounds = state.effectBounds; state.shapes.clear(); state.plainRects.clear(); + state.lgMaterials.clear(); const RegionF content = blurRegion(w, state); std::vector contentRects; @@ -723,12 +702,19 @@ void GlassEffect::rebuildShapes(EffectWindow *w, WindowState &state) { } } - // Global mode: every remaining blur island becomes glass. + // Global mode: every remaining blur island becomes glass. The pointer response redraws the + // whole shape on every pointer move, so by default it is kept to docks, panels, menus and + // notifications rather than (often large) application windows. + Material globalMaterial = m_globalMaterial; + if (!m_pointerEffectsOnWindows && isAppWindow(w)) { + globalMaterial.pointerLight = 0.0; + globalMaterial.pointerBulge = 0.0; + } if (state.global || state.forced) { for (std::size_t i = 0; i < islands.size(); ++i) { if (!claimed[i]) { claimed[i] = true; - addShape(islands[i].rect, globalRadius(w, islands[i]), m_globalMaterial); + addShape(islands[i].rect, globalRadius(w, islands[i]), globalMaterial); } } } @@ -736,7 +722,7 @@ void GlassEffect::rebuildShapes(EffectWindow *w, WindowState &state) { // Decoration blur. if (state.frame.has_value() && !state.frame->isEmpty()) { if ((state.global || state.forced) && m_globalDecorations) { - Material material = m_globalMaterial; + Material material = globalMaterial; material.pointerBulge = 0.0; std::vector frameRects; for (const RectF &rect : state.frame->rects()) { @@ -973,7 +959,77 @@ void GlassEffect::prePaintScreen(ScreenPrePaintData &data) { bool GlassEffect::paintScreen(const RenderTarget &renderTarget, const RenderViewport &viewport, int mask, const Region &deviceRegion, LogicalOutput *screen) { m_frameDamage = deviceRegion; - return effects->paintScreen(renderTarget, viewport, mask, deviceRegion, screen); + const bool painted = effects->paintScreen(renderTarget, viewport, mask, deviceRegion, screen); + refreshBackdrops(viewport, deviceRegion); + return painted; +} + +void GlassEffect::refreshBackdrops(const RenderViewport &viewport, const Region &deviceRegion) { + quint64 &seen = m_viewDamageSerial[m_currentView]; + const quint64 since = seen; + seen = m_damageSerial; + if (m_windows.empty() || m_damagedWindows.empty()) { + m_damagedWindows.clear(); + return; + } + + // What this output really repainted, in logical px. A window's damage signal says nothing about + // where it changed, so a blinking cursor at the far end of a maximized window used to repaint + // every glass surface whose margin the window overlaps. The glass is redrawn on the next frame: + // one frame of lag on content seen only through the refraction margin. + const Region damage = deviceRegion == Region::infinite() + ? Region(viewport.renderRect().roundedOut()) + : viewport.mapFromDeviceCoordinatesAligned(deviceRegion); + for (const auto &[other, serial] : m_damagedWindows) { + if (serial <= since) { + continue; + } + const Region changed = damage & other->expandedGeometry().roundedOut(); + if (changed.isEmpty()) { + continue; + } + for (auto &[w, state] : m_windows) { + if (w == other || state.sampleBounds.isEmpty()) { + continue; + } + // Only the margin beyond our own window: inside it KWin repaints us anyway. + const Rect sample = toRectF(state.sampleBounds.translated(w->pos())).roundedOut(); + const Region margin = Region(sample) - w->frameGeometry().roundedIn(); + if (changed.intersects(margin)) { + repaintShapes(w, state); + } + } + } + + // Forget damage every view has seen. + quint64 oldest = m_damageSerial; + for (const auto &[view, serial] : m_viewDamageSerial) { + oldest = std::min(oldest, serial); + } + std::erase_if(m_damagedWindows, [oldest](const auto &entry) { + return entry.second <= oldest; + }); +} + +void GlassEffect::releaseIdleRenderData() { + const auto now = std::chrono::steady_clock::now(); + if (now - m_lastIdleSweep < std::chrono::seconds(1)) { + return; + } + m_lastIdleSweep = now; + bool current = false; + for (auto &[w, state] : m_windows) { + std::erase_if(state.render, [&](auto &entry) { + if (now - entry.second.lastUsed < kRenderDataIdle) { + return false; + } + if (!current) { + effects->makeOpenGLContextCurrent(); // the textures are deleted below + current = true; + } + return true; + }); + } } void GlassEffect::backdropChanged(EffectWindow *other, const QRectF &extraArea) { @@ -1007,6 +1063,7 @@ void GlassEffect::postPaintScreen() { // Idle: forget the clock so the next fade starts from a fresh timestamp. m_lastFrame = {}; } + releaseIdleRenderData(); effects->postPaintScreen(); } @@ -1036,28 +1093,52 @@ bool GlassEffect::drawWindow(const RenderTarget &renderTarget, const RenderViewp return effects->drawWindow(renderTarget, viewport, w, mask, deviceRegion, data); } -bool GlassEffect::ensureCapture(RenderData &data, const QSize &size, unsigned int format) { - if (data.capture && data.capture->size() == size && data.capture->internalFormat() == format) { +bool GlassEffect::ensureCapture(RenderData &data, const Rect &rect, const Rect &scaledRect, unsigned int format, Region &uncached) { + const QSize size(scaledRect.width(), scaledRect.height()); + if (data.capture && data.captureRect == rect && data.capture->size() == size && data.capture->internalFormat() == format) { + uncached = Region(); return true; } - data.plain = {}; - data.captureFramebuffer.reset(); - data.capture = GLTexture::allocate(format, size); - if (!data.capture) { + auto capture = GLTexture::allocate(format, size); + if (!capture) { return false; } - data.capture->setFilter(GL_LINEAR); - data.capture->setWrapMode(GL_CLAMP_TO_EDGE); - data.captureFramebuffer = std::make_unique(data.capture.get()); - if (!data.captureFramebuffer->valid()) { - data.captureFramebuffer.reset(); - data.capture.reset(); + capture->setFilter(GL_LINEAR); + capture->setWrapMode(GL_CLAMP_TO_EDGE); + auto framebuffer = std::make_unique(capture.get()); + if (!framebuffer->valid()) { return false; } - EglContext::currentContext()->pushFramebuffer(data.captureFramebuffer.get()); + EglContext::currentContext()->pushFramebuffer(framebuffer.get()); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); EglContext::currentContext()->popFramebuffer(); + + // The capture is registered to the screen, so whatever the old one held where the two overlap is + // still the backdrop there: carry it over instead of starting from transparent black. + uncached = Region(rect); + if (data.captureFramebuffer && data.capture && data.capture->internalFormat() == format) { + const Rect overlap = data.captureRect.intersected(rect); + const qreal sx = static_cast(data.capture->width()) / std::max(1, data.captureRect.width()); + const qreal sy = static_cast(data.capture->height()) / std::max(1, data.captureRect.height()); + const qreal dx = static_cast(size.width()) / std::max(1, rect.width()); + const qreal dy = static_cast(size.height()) / std::max(1, rect.height()); + if (!overlap.isEmpty() && qFuzzyCompare(sx, dx) && qFuzzyCompare(sy, dy)) { + const Rect source = RectF((overlap.x() - data.captureRect.x()) * sx, (overlap.y() - data.captureRect.y()) * sy, + overlap.width() * sx, overlap.height() * sy).rounded(); + const Rect destination = RectF((overlap.x() - rect.x()) * dx, (overlap.y() - rect.y()) * dy, + overlap.width() * dx, overlap.height() * dy).rounded(); + GLFramebuffer::pushFramebuffer(data.captureFramebuffer.get()); + framebuffer->blitFromFramebuffer(source, destination, GL_NEAREST); + GLFramebuffer::popFramebuffer(); + uncached = uncached - overlap; + } + } + + data.plain = {}; + data.captureFramebuffer = std::move(framebuffer); + data.capture = std::move(capture); + data.captureRect = rect; return true; } @@ -1153,11 +1234,30 @@ bool GlassEffect::render(const RenderTarget &renderTarget, const RenderViewport const QRectF grown = rect.translated(origin).adjusted(-margin, -margin, margin, margin); wanted = wanted.isNull() ? grown : wanted.united(grown); } - // Capture beyond our window too (deep refraction); backdropChanged() keeps that area fresh. - const Rect captureRect = toRectF(wanted.intersected(toQRectF(viewport.renderRect()))).roundedOut(); - if (captureRect.isEmpty()) { + // Capture beyond our window too (deep refraction); refreshBackdrops() keeps that area fresh. + const RectF renderRect = viewport.renderRect(); + const Rect needed = toRectF(wanted.intersected(toQRectF(renderRect))).roundedOut(); + if (needed.isEmpty()) { return false; } + RenderData &rd = state.render[m_currentView]; + rd.lastUsed = std::chrono::steady_clock::now(); + // Keep the current capture while it still covers what the shaders need and is not much larger: + // a growing dock pill or a moving window then reuses its textures instead of reallocating them + // (and the Rust blur chain sized from them) on every frame. + Rect captureRect = rd.captureRect; + const auto area = [](const Rect &r) { + return static_cast(r.width()) * static_cast(r.height()); + }; + if (!rd.capture || !captureRect.contains(needed) || !renderRect.contains(RectF(captureRect)) + || area(captureRect) > kCaptureMaxOversize * area(needed)) { + const qreal mx = std::max(kCaptureSlackMin, needed.width() * kCaptureSlack); + const qreal my = std::max(kCaptureSlackMin, needed.height() * kCaptureSlack); + captureRect = RectF(needed.x() - mx, needed.y() - my, needed.width() + 2 * mx, needed.height() + 2 * my) + .intersected(renderRect) + .roundedIn(); + captureRect = captureRect.united(needed); // roundedIn() must never cut into what is needed + } const Rect scaledCapture = captureRect.scaled(scale).rounded(); const Rect deviceCapture = viewport.mapToDeviceCoordinates(RectF(captureRect)).rounded(); const QSize texSize = scaledCapture.size(); @@ -1167,7 +1267,8 @@ bool GlassEffect::render(const RenderTarget &renderTarget, const RenderViewport // Paint-region clip in capture-local device px (same convention as KWin's blur). const bool infinite = deviceRegion == Region::infinite(); - std::vector clips; + std::vector &clips = m_scratchDeviceClips; + clips.clear(); if (!infinite) { for (const Rect &clip : deviceRegion.rects()) { const RectF local = RectF(clip).translated(-deviceCapture.x(), -deviceCapture.y()); @@ -1184,8 +1285,8 @@ bool GlassEffect::render(const RenderTarget &renderTarget, const RenderViewport if (renderTarget.texture()) { format = renderTarget.texture()->internalFormat(); } - RenderData &rd = state.render[m_currentView]; - if (!ensureCapture(rd, texSize, format) + Region uncached; + if (!ensureCapture(rd, captureRect, scaledCapture, format, uncached) || !ensureChain(rd.plain, texSize, state.plainRects.empty() ? 0 : plainStep.iterations, format)) { qCWarning(FLUCTUS_GLASS) << "Failed to allocate offscreen textures"; state.render.erase(m_currentView); @@ -1194,12 +1295,22 @@ bool GlassEffect::render(const RenderTarget &renderTarget, const RenderViewport // Fetch the backdrop behind us. Everything repainted this frame (not just our own paint // region) already holds the windows below us; the rest of the capture is the cache from - // earlier frames, kept fresh by BackgroundEffectItem (inside the window) and backdropChanged(). - const Region dirty = viewport.mapFromDeviceCoordinatesContained(m_frameDamage) & captureRect; + // earlier frames, kept fresh by BackgroundEffectItem (inside the window) and refreshBackdrops(). + const Region frameDirty = viewport.mapFromDeviceCoordinatesContained(m_frameDamage); + const Region dirty = frameDirty & captureRect; for (const Rect &dirtyRect : dirty.rects()) { const Rect destination = dirtyRect.scaled(scale).rounded().translated(-scaledCapture.x(), -scaledCapture.y()); rd.captureFramebuffer->blitFromRenderTarget(renderTarget, viewport, dirtyRect, destination); } + // Pixels the cache cannot vouch for: a fresh capture's area without carried-over pixels, and + // spare capture area the shaders start sampling now (it was not kept fresh while unused). + // Repaint them so the next frame captures them; this frame uses what the cache has. + Region stale = uncached | (Region(needed) - rd.lastNeeded); + stale = stale - frameDirty; + rd.lastNeeded = needed; + if (!stale.isEmpty()) { + effects->addRepaint(stale); + } const QSizeF texSizeF(texSize); const QPointF captureOrigin(scaledCapture.x(), scaledCapture.y()); @@ -1215,7 +1326,8 @@ bool GlassEffect::render(const RenderTarget &renderTarget, const RenderViewport // Plain frosted blur (stock look) for the rest of the blur region. if (!state.plainRects.empty() && !rd.plain.textures.empty()) { - std::vector vertices; + std::vector &vertices = m_scratchVertices; + vertices.clear(); appendQuad(vertices, RectF(0, 0, texSize.width(), texSize.height()), texSizeF); const int plainStart = static_cast(vertices.size()); for (const QRectF &rect : state.plainRects) { @@ -1260,9 +1372,20 @@ bool GlassEffect::render(const RenderTarget &renderTarget, const RenderViewport const QVector3D white = mappedColor(Qt::white, targetDesc).toVector3D(); const auto s = static_cast(scale); + // Color-space mapping of the material colors only changes with the shapes or the output. + if (state.lgMaterials.size() != state.shapes.size() || !(state.lgSpace == renderTarget.colorDescription())) { + state.lgMaterials.clear(); + state.lgMaterials.reserve(state.shapes.size()); + for (const ResolvedShape &shape : state.shapes) { + state.lgMaterials.push_back(toLgMaterial(shape.material, targetDesc)); + } + state.lgSpace = renderTarget.colorDescription(); + } + m_scratchShapes.clear(); m_scratchShapes.reserve(state.shapes.size()); - for (const ResolvedShape &shape : state.shapes) { + for (std::size_t i = 0; i < state.shapes.size(); ++i) { + const ResolvedShape &shape = state.shapes[i]; const QRectF global = shape.rect.translated(origin); const QRectF local(global.x() * scale - captureOrigin.x(), global.y() * scale - captureOrigin.y(), global.width() * scale, global.height() * scale); @@ -1277,7 +1400,7 @@ bool GlassEffect::render(const RenderTarget &renderTarget, const RenderViewport .radius = static_cast(shape.radius) * s, .opacity = opacity, .scale = s, - .material = toLgMaterial(shape.material, targetDesc), + .material = state.lgMaterials[i], .pointer = LgPointerState{ .x = static_cast(pointer.x()), .y = static_cast(pointer.y()), diff --git a/glass/src/glasseffect.hpp b/glass/src/glasseffect.hpp index 3c9b049..48ce7d4 100644 --- a/glass/src/glasseffect.hpp +++ b/glass/src/glasseffect.hpp @@ -15,8 +15,10 @@ #include +#include "core/colorspace.h" #include "core/region.h" #include "effect/effect.h" +#include "opengl/glvertexbuffer.h" #include #include @@ -47,11 +49,18 @@ struct BlurChain { /// Per render view (output): the sharp backdrop capture, cached between frames like KWin's blur, /// plus the stock-strength blur chain for plain blur regions (Liquid Glass blur textures are -/// pooled inside the Rust `LgGlRenderer`). +/// cached inside the Rust `LgGlRenderer`). +/// +/// The capture is registered to screen coordinates (`captureRect`) and only re-allocated when the +/// area the shaders need leaves it, so a growing dock pill or a moving window does not reallocate +/// textures every frame, and the cached pixels never shift relative to the screen. struct RenderData { std::unique_ptr capture; std::unique_ptr captureFramebuffer; + KWin::Rect captureRect; ///< logical screen rect held by `capture` + KWin::Rect lastNeeded; ///< part of it the shaders sampled last frame BlurChain plain; + std::chrono::steady_clock::time_point lastUsed{}; ///< freed after a few idle seconds }; /// One glass shape of a window, resolved for rendering (window-local logical px). @@ -77,6 +86,10 @@ struct WindowState { std::unique_ptr item; std::unordered_map render; + // Renderer materials for `shapes`, converted to the color space they were last drawn in. + std::shared_ptr lgSpace; + std::vector lgMaterials; + // Pointer QPointF pointer; ///< window-local logical px qreal pointerStrength{0}; @@ -122,8 +135,13 @@ class GlassEffect : public KWin::Effect { void slotWindowDeleted(KWin::EffectWindow *w); void slotViewRemoved(KWin::RenderView *view); void slotMouseChanged(const QPointF &pos); - /// Another window changed: repaint glass whose refraction samples where it is. + /// Another window moved or closed: repaint glass whose refraction samples where it is. void backdropChanged(KWin::EffectWindow *other, const QRectF &extraArea = {}); + /// After a frame: repaint glass whose sampling margin (outside its own window) intersects + /// what other, damaged windows actually repainted in it. + void refreshBackdrops(const KWin::RenderViewport &viewport, const KWin::Region &deviceRegion); + /// Drops capture textures of windows that have not been drawn for a while. + void releaseIdleRenderData(); void onRegistrationChanged(const QString &handle); /// Re-reads the blur region of `w` and recomputes its shapes. @@ -142,7 +160,10 @@ class GlassEffect : public KWin::Effect { bool render(const KWin::RenderTarget &renderTarget, const KWin::RenderViewport &viewport, KWin::EffectWindow *w, WindowState &state, const KWin::Region &deviceRegion, KWin::WindowPaintData &data); - bool ensureCapture(RenderData &data, const QSize &size, unsigned int format); + /// Makes `data.capture` hold `rect` (logical) at `size` (device px), keeping the pixels of the + /// previous capture that still overlap. Returns the part of `rect` with no cached pixels. + bool ensureCapture(RenderData &data, const KWin::Rect &rect, const KWin::Rect &scaledRect, unsigned int format, + KWin::Region &uncached); bool ensureChain(BlurChain &chain, const QSize &size, std::size_t iterations, unsigned int format); void runDualKawase(RenderData &data, BlurChain &chain, KWin::GLVertexBuffer *vbo, float offset); @@ -150,6 +171,13 @@ class GlassEffect : public KWin::Effect { LgGlRenderer *m_rustRenderer{nullptr}; std::vector m_scratchShapes; std::vector m_scratchClips; + std::vector m_scratchDeviceClips; + std::vector m_scratchVertices; + // Windows damaged since each view last checked them (refreshBackdrops()). + std::unordered_map m_damagedWindows; + std::unordered_map m_viewDamageSerial; + quint64 m_damageSerial{0}; + std::chrono::steady_clock::time_point m_lastIdleSweep{}; GlassService m_service; Material m_globalMaterial; std::unordered_map m_windows; @@ -172,6 +200,7 @@ class GlassEffect : public KWin::Effect { bool m_globalPanels{true}; bool m_globalNotifications{true}; bool m_pointerEffects{true}; + bool m_pointerEffectsOnWindows{false}; ///< global mode: pointer response on app windows too bool m_advertisedBlur{false}; bool m_valid{false}; }; diff --git a/glass/src/glassservice.cpp b/glass/src/glassservice.cpp index 62457f4..0599c0e 100644 --- a/glass/src/glassservice.cpp +++ b/glass/src/glassservice.cpp @@ -233,10 +233,15 @@ QString GlassService::Set(const QString &handle, const QVariantMap &match, const if (!reg) { return {}; } - reg->match = match; - reg->params = normalised(params); - reg->material = resolveMaterial(reg->params, reg->followGlobal); - notify(handle); + QVariantMap normParams = normalised(params); + // Clients may resend unchanged state (e.g. every animation frame); only real changes reach the + // effect, which rebuilds and repaints the window for each one. + if (reg->match != match || reg->params != normParams) { + reg->match = match; + reg->params = std::move(normParams); + reg->material = resolveMaterial(reg->params, reg->followGlobal); + notify(handle); + } // notify() may have bound or rebound the window. if (Registration *now = find(handle); now && !now->window.isNull()) { return now->window.toString(QUuid::WithoutBraces); diff --git a/glass/src/material.cpp b/glass/src/material.cpp index 3e3e260..074b254 100644 --- a/glass/src/material.cpp +++ b/glass/src/material.cpp @@ -5,6 +5,8 @@ #include "FluctusGlass/GlassProtocol.hpp" +#include + #include #include @@ -239,18 +241,25 @@ Material Material::scaled() const { return m; } +// The margins come from the renderer itself (crates/liquidglass), so the capture and draw bounds can +// never drift from what its shader samples and draws. qreal Material::sampleMargin() const { - // Two-zone bezel refraction (including outer lip fold), dispersion spread, and pointer bulge - // can all sample outside the shape silhouette. - return std::ceil(refraction * (1.75 + 0.70 * edgeBend) * (1.0 + dispersion) + pointerBulge * 1.5 + 8.0); + LgMaterial m = lg_material_default(); + m.refraction = static_cast(refraction); + m.edge_bend = static_cast(edgeBend); + m.dispersion = static_cast(dispersion); + m.pointer_bulge = static_cast(pointerBulge); + return lg_material_sample_margin(&m); } qreal Material::drawMargin() const { - qreal margin = borderWidth + 2.0; - if (shadowColor.alphaF() > 0.001F) { - margin = std::max(margin, shadowBlur + std::max(std::abs(shadowOffsetX), std::abs(shadowOffsetY))); - } - return std::ceil(margin); + LgMaterial m = lg_material_default(); + m.border_width = static_cast(borderWidth); + m.shadow_color.a = shadowColor.alphaF(); + m.shadow_blur = static_cast(shadowBlur); + m.shadow_offset_x = static_cast(shadowOffsetX); + m.shadow_offset_y = static_cast(shadowOffsetY); + return lg_material_draw_margin(&m); } bool Material::reactsToPointer() const {