From 25fecb8daee77232333c6f289410d2fd3eb40bfc Mon Sep 17 00:00:00 2001 From: Tamas Csikel Date: Sun, 1 Nov 2026 19:14:11 +0100 Subject: [PATCH] sf-ui 0.1.1: GPU measurement at startup and a Material style for weak GPUs - GlassRenderer::choose_quality measures a typical TV frame offscreen at window size and picks Full, Light or the new Quality::Material; cached per GPU and size in ~/.cache/fennec-glass, SMARTFOX_GLASS overrides it. Glass picks it by default (set_auto_quality); set_quality fixes it. - Material: matte panes with a small shadow and a focus ring on a plain palette-coloured backdrop, in its own cheap shader, with no backdrop texture or full-screen pass. A still Material layer draws no frames while nothing changes. - Glass panes: a fast path for single panes, light/flat really skip the full lighting, and each pane's quad only covers its actual shadow. On a Raspberry Pi 4 at 1080p: full glass 50 ms, light 39 ms per frame, so Material is picked; the launcher animates at 55-60 fps (was 17). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 8 +- Cargo.toml | 2 +- docs/sf-ui.md | 17 +++ sf-ui/src/glass.rs | 86 +++++++++++- sf-ui/src/render/mod.rs | 19 +++ sf-ui/src/render/renderer.rs | 248 +++++++++++++++++++++++++++++++++-- sf-ui/src/render/shaders.rs | 96 ++++++++++++++ 7 files changed, 457 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 651f84e..0a0c20e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4810,7 +4810,7 @@ dependencies = [ [[package]] name = "sf-app" -version = "0.1.0" +version = "0.1.1" dependencies = [ "anyhow", "log", @@ -4820,7 +4820,7 @@ dependencies = [ [[package]] name = "sf-pack" -version = "0.1.0" +version = "0.1.1" dependencies = [ "anyhow", "ruzstd", @@ -4832,7 +4832,7 @@ dependencies = [ [[package]] name = "sf-ui" -version = "0.1.0" +version = "0.1.1" dependencies = [ "anyhow", "glow 0.16.0", @@ -4848,7 +4848,7 @@ dependencies = [ [[package]] name = "sf-ui-gallery" -version = "0.1.0" +version = "0.1.1" dependencies = [ "anyhow", "env_logger", diff --git a/Cargo.toml b/Cargo.toml index 1dd54ec..eb3c806 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["sf-app", "sf-ui", "sf-ui/gallery", "sf-pack"] exclude = ["templates/rust-app"] [workspace.package] -version = "0.1.0" +version = "0.1.1" edition = "2024" license = "MIT" repository = "https://gitea.bluefox.support/fennec/sdk" diff --git a/docs/sf-ui.md b/docs/sf-ui.md index d373908..336cea5 100644 --- a/docs/sf-ui.md +++ b/docs/sf-ui.md @@ -330,6 +330,23 @@ A `Glass` handle-lel (olcsón klónozható, a UI szálon használd): | `set_video(Some(source))` | videó a háttérben: az OSD üvege a filmet töri meg. `None`: kihalványul | | `set_light(rad)` | a fő fényforrás iránya (kis értékek, például ±0.3; követheti a fókuszt) | | `set_zoom(k)` | a gradient nagyítása (indítási „berepülés”) | +| `set_quality(Quality)` | rögzített megjelenés: `Full`, `Light`, `Flat` vagy `Material` (lásd lent) | +| `set_auto_quality()` | a réteg maga méri le a GPU-t, és választ (ez az alapértelmezés) | + +### Megjelenés gyengébb GPU-n + +Az első képkocka előtt a réteg ablakméretben, a képernyőn kívül lemér egy tipikus TV-képet (kártyasor, fókuszált kártya, sáv, nagy lap). Ha a teljes üveg belefér képkockánként kb. 7 ms-ba, `Full` marad. Ha a `Light` fér bele, azt választja, különben `Material`-t. +- Az eredmény GPU-nként és ablakméretenként a `~/.cache/fennec-glass` fájlba kerül, így csak egyszer mér. +- Felülírás: `SMARTFOX_GLASS=full|light|flat|material`. + +| Mód | Mit rajzol | Mire jó | +|---|---|---| +| `Full` | a teljes Liquid Glass: fénytörés, diszperzió, Fresnel | erős GPU (Intel N100 és fölötte) | +| `Light` | fagyasztott üveg a fényes peremmel, lencse nélkül | közepes GPU | +| `Flat` | színezett lapok peremmel, fagyasztás nélkül | kézi választás | +| `Material` | nem üveg: matt, kitöltött lapok kis árnyékkal és fókuszgyűrűvel, sima háttérszínen (a paletta sötét tónusa). A képek és a videó teljes felbontásban, közvetlenül kerülnek a háttérre. Ha semmi nem mozog, nem rajzol új képkockát | gyenge GPU (Raspberry Pi 4) | + +A Raspberry Pi 4-en (V3D 4.2, 1080p) mérve: `Full` kb. 50 ms, `Light` kb. 39 ms képkockánként, ezért ott `Material` jön ki, és a felület navigálás közben 55–60 FPS-sel fut. ```rust let px = images_pixels; // SharedPixelBuffer diff --git a/sf-ui/src/glass.rs b/sf-ui/src/glass.rs index 9bf591e..c1b3371 100644 --- a/sf-ui/src/glass.rs +++ b/sf-ui/src/glass.rs @@ -125,6 +125,12 @@ struct State { zoom: f32, last: f32, quality: Quality, + /// Pick the quality from a GPU measurement (the default). + auto: bool, + /// The window size the automatic quality was picked for. + chosen: Option<(u32, u32)>, + /// Asks the window for a frame (Material draws only when something changes). + redraw: Option>, } /// Handle to an installed glass layer (cheap to clone). @@ -160,8 +166,17 @@ impl Glass { zoom: 1.0, last: 0.0, quality: Quality::Full, + auto: true, + chosen: None, + redraw: None, })); let glass = Glass { state: state.clone() }; + let redraw_weak = ui.as_weak(); + state.borrow_mut().redraw = Some(Rc::new(move || { + if let Some(ui) = redraw_weak.upgrade() { + ui.window().request_redraw(); + } + })); let snapshot = crate::dev::setup(ui); let renderer: Rc>> = Rc::default(); let start = Instant::now(); @@ -189,6 +204,17 @@ impl Glass { panels(&ui, &mut list); let mut st = state.borrow_mut(); + // Picked again only when the window area changes a lot (not + // for a few pixels of a window manager's resize). + let area = |w: u32, h: u32| w as f32 * h as f32; + let stale = st.chosen.is_none_or(|(w, h)| { + (area(size.width, size.height) / area(w, h).max(1.0) - 1.0).abs() > 0.25 + }); + if st.auto && size.width > 0 && stale { + // SAFETY: the rendering notifier runs with the GL context current. + st.quality = unsafe { r.choose_quality(size.width, size.height) }; + st.chosen = Some((size.width, size.height)); + } let dt = (time - st.last).clamp(0.0, 0.25); st.last = time; st.step(dt); @@ -248,7 +274,12 @@ impl Glass { let _ = slint::quit_event_loop(); } } - ui.window().request_redraw(); + // The glass backdrop animates: keep frames coming. Material + // is still, so it only draws while something changes. + let st = state.borrow(); + if st.quality != Quality::Material || st.animating() || snapshot.path.borrow().is_some() { + ui.window().request_redraw(); + } } slint::RenderingState::RenderingTeardown => { if let Some(mut r) = renderer.borrow_mut().take() { @@ -268,12 +299,14 @@ impl Glass { /// The backdrop gradient's colours; eases over from the current ones. pub fn set_palette(&self, palette: Palette) { self.state.borrow_mut().palette_target = palette.to_floats(); + self.kick(); } /// Backdrop brightness, 0..1 (1 = full). Lower it to calm the backdrop /// behind dense content. pub fn set_brightness(&self, v: f32) { self.state.borrow_mut().brightness_target = v.clamp(0.0, 1.0); + self.kick(); } /// A picture over the gradient (crossfades from the previous one), or @@ -298,6 +331,8 @@ impl Glass { } } } + drop(st); + self.kick(); } /// Video as the backdrop (glass refracts the film), or `None` to fade it @@ -309,27 +344,70 @@ impl Glass { st.video = source; st.clear_video = true; } + drop(st); + self.kick(); } /// Turns the key light (radians, small values like ±0.3), e.g. to follow /// the focus across the screen. pub fn set_light(&self, offset: f32) { self.state.borrow_mut().light = offset; + self.kick(); } - /// How much of the glass effect to draw ([`Quality::Light`] or - /// [`Quality::Flat`] on weaker hardware). + /// How much of the glass effect to draw, fixed. By default the layer + /// measures the GPU and picks it itself ([`Glass::set_auto_quality`]). pub fn set_quality(&self, q: Quality) { - self.state.borrow_mut().quality = q; + { + let mut st = self.state.borrow_mut(); + st.quality = q; + st.auto = false; + } + self.kick(); + } + + /// Picks the quality from a short GPU measurement (cached per GPU and + /// window size): full glass, light glass, or [`Quality::Material`] on + /// GPUs too slow for glass. This is the default. + pub fn set_auto_quality(&self) { + { + let mut st = self.state.borrow_mut(); + st.auto = true; + st.chosen = None; + } + self.kick(); + } + + /// The quality in use (after the automatic pick, once the window drew). + pub fn quality(&self) -> Quality { + self.state.borrow().quality + } + + /// Asks for a frame: a still (Material) layer only draws on changes. + fn kick(&self) { + let redraw = self.state.borrow().redraw.clone(); + if let Some(f) = redraw { + f(); + } } /// Zooms the backdrop gradient (1 = none). pub fn set_zoom(&self, zoom: f32) { self.state.borrow_mut().zoom = zoom.max(0.1); + self.kick(); } } impl State { + /// Something is still easing (colours, pictures, video): frames needed. + fn animating(&self) -> bool { + self.palette.iter().zip(self.palette_target).any(|(c, t)| (c - t).abs() > 0.002) + || (self.brightness - self.brightness_target).abs() > 0.002 + || self.images.iter().any(|s| (s.alpha - s.target).abs() > 0.001 || s.id.is_none()) + || self.video_on + || self.video_alpha > 0.0 + } + fn step(&mut self, dt: f32) { let k = 1.0 - (-dt / EASE).exp(); for (c, t) in self.palette.iter_mut().zip(self.palette_target) { diff --git a/sf-ui/src/render/mod.rs b/sf-ui/src/render/mod.rs index ab929e2..2b431fb 100644 --- a/sf-ui/src/render/mod.rs +++ b/sf-ui/src/render/mod.rs @@ -122,6 +122,25 @@ pub enum Quality { Light, /// No frost: tinted panes with the rim only. Flat, + /// Not glass at all: matte, nearly opaque surfaces with a small shadow + /// and a focus ring, on a still backdrop. For GPUs that can't afford + /// glass (Raspberry Pi 4); [`GlassRenderer::choose_quality`] picks it. + Material, +} + +impl Quality { + pub fn name(self) -> &'static str { + match self { + Quality::Full => "full", + Quality::Light => "light", + Quality::Flat => "flat", + Quality::Material => "material", + } + } + + pub fn from_name(name: &str) -> Option { + [Quality::Full, Quality::Light, Quality::Flat, Quality::Material].into_iter().find(|q| q.name() == name.trim()) + } } /// Everything the renderer needs for one frame. diff --git a/sf-ui/src/render/renderer.rs b/sf-ui/src/render/renderer.rs index 2114a21..e53e29c 100644 --- a/sf-ui/src/render/renderer.rs +++ b/sf-ui/src/render/renderer.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; use glow::HasContext; use super::shaders; -use super::{Frame, ImageDraw, ImageId, MAX_GROUP, MAX_RECTS, Matrix, Nv12Frame, Panel}; +use super::{Frame, ImageDraw, ImageId, MAX_GROUP, MAX_RECTS, Matrix, Nv12Frame, Panel, Quality}; /// The backdrop is blurry by design, so it never needs more than this width. const SCENE_MAX_W: i32 = 640; @@ -68,6 +68,16 @@ struct GlassLocs { mode: Loc, } +struct MaterialLocs { + box_: Loc, + res: Loc, + scale: Loc, + rect: Loc, + param: Loc, + glow: Loc, + tint: Loc, +} + struct Image { tex: glow::Texture, w: i32, @@ -93,6 +103,8 @@ pub struct GlassRenderer { image_prog: glow::Program, video_prog: glow::Program, glass_prog: glow::Program, + material_prog: glow::Program, + material_locs: MaterialLocs, scene_locs: SceneLocs, blit_locs: BlitLocs, image_locs: ImageLocs, @@ -148,6 +160,7 @@ impl GlassRenderer { let image_prog = link(&gl, header, shaders::VERTEX, shaders::IMAGE)?; let video_prog = link(&gl, header, shaders::VERTEX, shaders::VIDEO)?; let glass_prog = link(&gl, header, shaders::QUAD_VERTEX, shaders::GLASS)?; + let material_prog = link(&gl, header, shaders::QUAD_VERTEX, shaders::MATERIAL)?; let loc = |p: glow::Program, name: &str| gl.get_uniform_location(p, name); let scene_locs = SceneLocs { res: loc(scene_prog, "uRes"), @@ -190,6 +203,15 @@ impl GlassRenderer { tint: loc(glass_prog, "uTint"), mode: loc(glass_prog, "uMode"), }; + let material_locs = MaterialLocs { + box_: loc(material_prog, "uBox"), + res: loc(material_prog, "uRes"), + scale: loc(material_prog, "uScale"), + rect: loc(material_prog, "uRect"), + param: loc(material_prog, "uParam"), + glow: loc(material_prog, "uGlow"), + tint: loc(material_prog, "uTint"), + }; let vao = gl.create_vertex_array().map_err(anyhow::Error::msg)?; let fbo = gl.create_framebuffer().map_err(anyhow::Error::msg)?; let tex = gl.create_texture().map_err(anyhow::Error::msg)?; @@ -202,6 +224,8 @@ impl GlassRenderer { image_prog, video_prog, glass_prog, + material_prog, + material_locs, scene_locs, blit_locs, image_locs, @@ -512,6 +536,11 @@ impl GlassRenderer { } let gl = &self.gl; gl.bind_vertex_array(Some(self.vao)); + if f.quality == Quality::Material { + self.render_material(f, &saved, video_alpha); + self.restore(saved); + return; + } // Pass 1: backdrop at low resolution (blurred by the glass anyway). let sw = (w / 4).clamp(1, SCENE_MAX_W); @@ -565,7 +594,7 @@ impl GlassRenderer { let mode = match f.quality { super::Quality::Full => 0, super::Quality::Light => 1, - super::Quality::Flat => 2, + super::Quality::Flat | super::Quality::Material => 2, }; gl.uniform_1_i32(l.mode.as_ref(), mode); @@ -576,8 +605,7 @@ impl GlassRenderer { let mut tint = [0f32; MAX_GROUP * 4]; for run in runs(rects) { let n = run.len(); - // Bounds plus room for the shadow (spread + downward offset). - let margin = 132.0 * f.scale; + let (side, top, bottom) = shadow_margins(run, f.quality, f.scale); let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN); for (i, r) in run.iter().enumerate() { rect[i * 4..i * 4 + 4].copy_from_slice(&[r.x, r.y, r.w, r.h]); @@ -589,12 +617,7 @@ impl GlassRenderer { x1 = x1.max(r.x + r.w); y1 = y1.max(r.y + r.h); } - let bx = [ - (x0 - margin).max(0.0), - (y0 - margin).max(0.0), - (x1 + margin).min(w as f32), - (y1 + margin + 46.0 * f.scale).min(h as f32), - ]; + let bx = [(x0 - side).max(0.0), (y0 - top).max(0.0), (x1 + side).min(w as f32), (y1 + bottom).min(h as f32)]; if bx[0] >= bx[2] || bx[1] >= bx[3] { continue; } @@ -615,6 +638,180 @@ impl GlassRenderer { /// /// # Safety /// Must be called with the context current, after Slint has rendered. + /// Material ([`Quality::Material`]): no backdrop texture and no extra + /// full-screen pass. The window is cleared to a dark colour of the + /// palette (one clear: nearly free on tile-based GPUs), pictures and + /// video go straight on it, then each pane is one cheap quad. + unsafe fn render_material(&self, f: &Frame, saved: &SavedState, video_alpha: f32) { + let (w, h) = (f.width as i32, f.height as i32); + let gl = &self.gl; + unsafe { + gl.bind_framebuffer( + glow::FRAMEBUFFER, + std::num::NonZeroU32::new(saved.framebuffer as u32).map(glow::NativeFramebuffer), + ); + gl.viewport(0, 0, w, h); + let [r, g, b] = material_background(&f.palette, f.brightness); + gl.clear_color(r, g, b, 1.0); + gl.clear(glow::COLOR_BUFFER_BIT); + // Every picture sharp: there is no soft (low resolution) copy. + self.draw_layers(f, w, h, true, video_alpha); + + let gl = &self.gl; + gl.enable(glow::BLEND); + gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD); + gl.blend_func_separate(glow::ONE, glow::SRC_ALPHA, glow::ZERO, glow::ONE); + let l = &self.material_locs; + gl.use_program(Some(self.material_prog)); + gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32); + gl.uniform_1_f32(l.scale.as_ref(), f.scale); + for p in f.rects.iter().take(MAX_RECTS) { + let (side, top, bottom) = shadow_margins(std::slice::from_ref(p), Quality::Material, f.scale); + let bx = [ + (p.x - side).max(0.0), + (p.y - top).max(0.0), + (p.x + p.w + side).min(w as f32), + (p.y + p.h + bottom).min(h as f32), + ]; + if bx[0] >= bx[2] || bx[1] >= bx[3] { + continue; + } + gl.uniform_4_f32(l.box_.as_ref(), bx[0], bx[1], bx[2], bx[3]); + gl.uniform_4_f32(l.rect.as_ref(), p.x, p.y, p.w, p.h); + gl.uniform_4_f32(l.param.as_ref(), p.radius, p.focus, p.alpha, p.blur); + gl.uniform_3_f32(l.glow.as_ref(), p.glow[0], p.glow[1], p.glow[2]); + gl.uniform_4_f32(l.tint.as_ref(), p.tint[0], p.tint[1], p.tint[2], p.tint[3]); + gl.draw_arrays(glow::TRIANGLE_STRIP, 0, 4); + } + } + } + + /// Milliseconds the GPU takes for one glass frame of `w` x `h` at + /// `quality`: a typical TV screen (a row of cards, a focused one, a + /// pill and a big pane) drawn offscreen a few times. + /// + /// # Safety + /// Must be called with the context current (inside the rendering notifier). + pub unsafe fn measure(&mut self, w: u32, h: u32, quality: Quality) -> Option { + let (wi, hi) = (w as i32, h as i32); + if wi <= 0 || hi <= 0 { + return None; + } + let s = h as f32 / 720.0; + let mut rects = Vec::new(); + for i in 0..5 { + rects.push(Panel { + x: (40.0 + 236.0 * i as f32) * s, + y: 470.0 * s, + w: 216.0 * s, + h: 128.0 * s, + radius: 22.0 * s, + focus: if i == 0 { 1.0 } else { 0.0 }, + alpha: 1.0, + blur: 3.0, + glow: [0.9, 0.3, 0.3], + group: 0.0, + tint: [0.8, 0.2, 0.2, 0.35], + }); + } + let pill = Panel { x: 880.0 * s, y: 26.0 * s, w: 340.0 * s, h: 44.0 * s, radius: 22.0 * s, alpha: 1.0, blur: 4.0, ..Default::default() }; + let pane = Panel { x: 60.0 * s, y: 120.0 * s, w: 560.0 * s, h: 300.0 * s, radius: 28.0 * s, alpha: 0.9, blur: 5.0, ..Default::default() }; + rects.push(pill); + rects.push(pane); + unsafe { + let gl = &self.gl; + let prev = gl.get_parameter_i32(glow::FRAMEBUFFER_BINDING); + let tex = gl.create_texture().ok()?; + let fbo = gl.create_framebuffer().ok()?; + gl.bind_texture(glow::TEXTURE_2D, Some(tex)); + gl.tex_image_2d( + glow::TEXTURE_2D, + 0, + glow::RGBA8 as i32, + wi, + hi, + 0, + glow::RGBA, + glow::UNSIGNED_BYTE, + glow::PixelUnpackData::Slice(None), + ); + set_filter(gl, false); + gl.bind_framebuffer(glow::FRAMEBUFFER, Some(fbo)); + gl.framebuffer_texture_2d(glow::FRAMEBUFFER, glow::COLOR_ATTACHMENT0, glow::TEXTURE_2D, Some(tex), 0); + let complete = gl.check_framebuffer_status(glow::FRAMEBUFFER) == glow::FRAMEBUFFER_COMPLETE; + let mut ms = None; + if complete { + let frame = |t: f32| Frame { width: w, height: h, scale: s, time: t, rects: rects.clone(), quality, ..Default::default() }; + for i in 0..2 { + self.render(&frame(i as f32 * 0.016)); + } + self.gl.finish(); + const RUNS: u32 = 6; + let start = std::time::Instant::now(); + for i in 0..RUNS { + self.render(&frame(0.1 + i as f32 * 0.016)); + } + self.gl.finish(); + ms = Some(start.elapsed().as_secs_f32() * 1000.0 / RUNS as f32); + } + let gl = &self.gl; + gl.bind_framebuffer(glow::FRAMEBUFFER, std::num::NonZeroU32::new(prev as u32).map(glow::NativeFramebuffer)); + gl.delete_framebuffer(fbo); + gl.delete_texture(tex); + ms + } + } + + /// The richest look this GPU draws at `w` x `h` with time to spare: + /// full glass, light glass, or the matte Material style. Measured once + /// per GPU and size, then cached (`~/.cache/fennec-glass`). + /// `SMARTFOX_GLASS=full|light|flat|material` overrides it. + /// + /// # Safety + /// Must be called with the context current (inside the rendering notifier). + pub unsafe fn choose_quality(&mut self, w: u32, h: u32) -> Quality { + if let Some(q) = std::env::var("SMARTFOX_GLASS").ok().and_then(|v| Quality::from_name(&v)) { + return q; + } + let gpu = unsafe { self.gl.get_parameter_string(glow::RENDERER) }; + let key = format!("v1 {w}x{h} {}", gpu.replace('=', " ")); + let path = std::env::var_os("XDG_CACHE_HOME") + .map(std::path::PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cache"))) + .map(|d| d.join("fennec-glass")); + let cached = path.as_ref().and_then(|p| std::fs::read_to_string(p).ok()).unwrap_or_default(); + let hit = cached + .lines() + .filter_map(|l| l.split_once(" = ")) + .find(|(k, _)| *k == key) + .and_then(|(_, v)| Quality::from_name(v)); + if let Some(q) = hit { + return q; + } + // Glass gets this much of a 60 Hz frame; Slint and the compositor need the rest. + const BUDGET_MS: f32 = 7.0; + let mut pick = Quality::Material; + for q in [Quality::Full, Quality::Light] { + let ms = unsafe { self.measure(w, h, q) }; + log::info!("glass: {} at {w}x{h}: {:.1} ms per frame", q.name(), ms.unwrap_or(f32::NAN)); + if ms.is_some_and(|ms| ms <= BUDGET_MS) { + pick = q; + break; + } + } + log::info!("glass: using {} on {gpu}", pick.name()); + if let Some(p) = path { + let prefix = format!("{key} = "); + let mut text: String = cached.lines().filter(|l| !l.starts_with(&prefix)).map(|l| format!("{l}\n")).collect(); + text.push_str(&format!("{prefix}{}\n", pick.name())); + if let Some(dir) = p.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(&p, text); + } + pick + } + pub unsafe fn read_pixels(&self, w: u32, h: u32) -> Vec { let mut buf = vec![0u8; (w * h * 4) as usize]; unsafe { @@ -653,6 +850,7 @@ impl GlassRenderer { self.gl.delete_program(self.image_prog); self.gl.delete_program(self.video_prog); self.gl.delete_program(self.glass_prog); + self.gl.delete_program(self.material_prog); self.gl.delete_vertex_array(self.vao); self.gl.delete_framebuffer(self.fbo); self.gl.delete_texture(self.tex); @@ -660,6 +858,36 @@ impl GlassRenderer { } } +/// Material's window colour: the palette's deep tone, a little of the mid +/// one, dimmed with the backdrop brightness. Always dark (text is white). +fn material_background(palette: &[f32; 9], brightness: f32) -> [f32; 3] { + let k = 0.6 + 0.4 * brightness.clamp(0.0, 1.0); + let c = |i: usize| ((palette[6 + i] * 0.85 + palette[3 + i] * 0.15) * k).clamp(0.0, 0.16); + [c(0), c(1), c(2)] +} + +/// Room around a run of panels for its shadow and accent light (px): sides, +/// top, bottom. Matches the GLASS shader's shadow (offset down, spread) so +/// the quad covers no pixel that would be discarded anyway: on a weak GPU +/// the shadow area is most of the glass cost. +fn shadow_margins(run: &[Panel], quality: Quality, s: f32) -> (f32, f32, f32) { + let focus = run.iter().map(|p| p.focus).fold(0.0, f32::max); + let min_half = run.iter().map(|p| p.w.min(p.h) * 0.5).fold(f32::MAX, f32::min); + let nested = run.iter().all(|p| p.blur < 0.0); + if quality == Quality::Material { + let spread = (6.0 + 10.0 * focus) * s; + let off = (2.0 + 4.0 * focus) * s; + return (spread + 2.0 * s, spread + 2.0 * s, spread + off + 2.0 * s); + } + let size_k = (min_half / (240.0 * s)).clamp(0.0, 1.0); + let spread = (34.0 + 34.0 * focus + 50.0 * size_k) * s * if nested { 0.5 } else { 1.0 }; + let off = (10.0 + 18.0 * focus + 14.0 * size_k) * s; + // Focused panes spill accent light up to ~100 px (exp(-d / 22) * 0.16). + let glow = if focus > 0.01 { 100.0 * s } else { 8.0 * s }; + let side = spread.max(glow); + (side, (spread - off).max(glow), (spread + off).max(glow)) +} + /// Linear filtering on the bound texture, with mipmaps for minification. unsafe fn set_filter(gl: &glow::Context, mipmaps: bool) { let min = if mipmaps { glow::LINEAR_MIPMAP_LINEAR } else { glow::LINEAR }; diff --git a/sf-ui/src/render/shaders.rs b/sf-ui/src/render/shaders.rs index e6778a6..46c1bb8 100644 --- a/sf-ui/src/render/shaders.rs +++ b/sf-ui/src/render/shaders.rs @@ -303,6 +303,18 @@ void main() { vec4 tint = vec4(0.0); vec2 center = vec2(0.0); vec2 halfSize = vec2(0.0); + if (!merged) { + // One pane (nearly every draw): constant indices, no loop. Uniform + // arrays indexed by a loop variable are very slow on some GPUs + // (Raspberry Pi's V3D reads them from memory per pixel). + if (uParam[0].z <= 0.001) discard; + d = sdPanel(0, p); + P = uParam[0]; + accent = uGlow[0].rgb; + tint = uTint[0]; + center = uRect[0].xy + uRect[0].zw * 0.5; + halfSize = uRect[0].zw * 0.5; + } else { for (int k = 0; k < MAX_GROUP; k++) { if (k >= uCount) break; float a = uParam[k].z; @@ -320,6 +332,7 @@ void main() { } if (wsum <= 0.0) discard; P /= wsum; accent /= wsum; tint /= wsum; center /= wsum; halfSize /= wsum; + } float focus = P.y; float alpha = P.z; @@ -352,6 +365,41 @@ void main() { } } + // ---- light and flat: frost (or tint) and the lit rim only ---- + // Weak GPUs (Raspberry Pi 4) can't afford the full surface below on + // every pixel of every pane; this keeps the look's essentials. + if (uMode != 0) { + float inside = max(-d, 0.0); + float mat = smoothstep(0.0, 1.0, alpha); + float A = 1.0; + vec3 B = vec3(0.0); + if (uMode == 1 && !nested) { + A = 0.0; + B = sceneAt(p / uRes, abs(P.w) * mix(0.35, 1.0, mat)); + } + float kb = 1.02 + 0.10 * focus; + A *= kb; + B = B * kb + 0.03 + (nested ? 0.025 : 0.0); + A *= 1.0 - tint.a; + B = mix(B, tint.rgb, tint.a); + vec2 qn = (p - center) / max(halfSize, vec2(1.0)); + B += mix(vec3(1.0), accent, 0.45) * focus * (0.06 + 0.12 * exp(-dot(qn, qn) * 1.3)); + float vy = clamp((p.y - (center.y - halfSize.y)) / (2.0 * halfSize.y), 0.0, 1.0); + B += vec3(0.06 + 0.05 * focus) * (1.0 - vy) * (1.0 - vy); + vec2 n2 = gradRoundRect(p - center, halfSize, min(P.x, minHalf)); + float facing = max(dot(n2, uLight), 0.0); + float away = max(dot(n2, -uLight), 0.0); + float rimLine = exp(-inside / (1.0 * s)); + float rimGlow = exp(-inside / (6.0 * s)); + B += rimLine * (0.22 + 0.80 * facing * facing + 0.55 * away * away + 0.22 * focus) * mat; + B += rimGlow * (0.06 + 0.10 * facing + 0.06 * away + 0.08 * focus) * mat; + B += accent * rimGlow * focus * 0.10 * mat; + float cov = clamp(0.5 - d, 0.0, 1.0) * clamp(alpha * 2.0, 0.0, 1.0); + float keep = 1.0 - cov + cov * A; + fragColor = vec4(add * keep + cov * B, mul * keep); + return; + } + // ---- surface geometry ---- vec2 n2; if (merged) { @@ -469,3 +517,51 @@ void main() { fragColor = vec4(add * keep + cov * B, mul * keep); } "#; + +/// Material panes ([`super::Quality::Material`]): a matte surface, lighter +/// and accent-tinted when focused, with a focus ring and a small elevation +/// shadow. One pane per draw, nothing sampled: cheap enough for GPUs that +/// can't afford glass. Output is dst * a + rgb, like GLASS. +pub const MATERIAL: &str = r#" +out vec4 fragColor; +uniform vec2 uRes; +uniform float uScale; +uniform vec4 uRect; // x, y, w, h (px, top-left origin) +uniform vec4 uParam; // radius, focus, alpha, frost (< 0 = nested on another pane) +uniform vec3 uGlow; // accent +uniform vec4 uTint; // rgb, amount + +float sdRoundRect(vec2 p, vec2 b, float r) { + vec2 q = abs(p) - b + r; + return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r; +} + +void main() { + vec2 p = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y); + float s = uScale; + float focus = uParam.y; + float alpha = uParam.z; + vec2 hs = uRect.zw * 0.5; + vec2 c = uRect.xy + hs; + float r = min(uParam.x, min(hs.x, hs.y)); + float d = sdRoundRect(p - c, hs, r); + + float spread = (6.0 + 10.0 * focus) * s; + float ds = sdRoundRect(p - c - vec2(0.0, (2.0 + 4.0 * focus) * s), hs, r); + float mul = 1.0 - (1.0 - smoothstep(-spread * 0.5, spread, ds)) * (0.30 + 0.10 * focus) * alpha; + if (d > 0.5) { + if (mul > 0.997) discard; + fragColor = vec4(0.0, 0.0, 0.0, mul); + return; + } + + vec3 col = uParam.w < 0.0 ? vec3(0.20, 0.21, 0.24) : vec3(0.135, 0.14, 0.16); + col = mix(col, uTint.rgb, uTint.a); + col = mix(col, uGlow, 0.22 * focus) + 0.05 * focus; + float ring = (1.0 - smoothstep(2.0 * s, 3.5 * s, -d)) * focus; + col = mix(col, mix(vec3(1.0), uGlow, 0.35), ring * 0.9); + float cov = clamp(0.5 - d, 0.0, 1.0) * clamp(alpha * 2.0, 0.0, 1.0); + float keep = 1.0 - cov * 0.94; + fragColor = vec4(cov * col, mul * keep); +} +"#;