//! The design system's widgets drawn in the game (`crates/horizon-theme`: //! palette, type scale, radii, control sizes, motion and the bundled fonts; //! `docs/design-system.md`). Every menu is vanilla's (`ui`); what is left //! here draws Horizon's own overlays that vanilla has no screen for: the //! on-screen keyboard a controller types with (`osk`), plus the //! `horizon.txt` preferences. //! //! Build a [`Ui`] over the frame's `HudBatch` with [`Ui::new`], lay out in dp //! (the launcher's logical pixels) and give every interactive widget a stable //! `id`. Clicks run the same layout with [`Ui::dry`] and read [`Ui::hit`]: one //! function draws and hit-tests, so they never disagree. use crate::hud::{HudAtlas, HudBatch, Rect}; use ab_glyph::{Font as _, FontRef, PxScale, ScaleFont as _}; use std::{cell::RefCell, collections::HashMap, path::Path}; /// A Horizon-only preference from `horizon.txt` beside `options.txt` /// (`key:value` lines), so vanilla's options file stays exactly as vanilla /// writes it. pub fn preference(dir: &Path, key: &str) -> Option { let text = std::fs::read_to_string(dir.join("horizon.txt")).ok()?; text.lines().find_map(|l| { let (k, v) = l.split_once(':')?; (k.trim() == key).then(|| v.trim().to_owned()) }) } /// Set (or with None remove) one preference, keeping the others. pub(crate) fn set_preference(dir: &Path, key: &str, value: Option<&str>) { let text = std::fs::read_to_string(dir.join("horizon.txt")).unwrap_or_default(); let mut lines: Vec = text .lines() .filter(|l| l.split_once(':').is_none_or(|(k, _)| k.trim() != key)) .map(str::to_owned) .collect(); if let Some(v) = value { lines.push(format!("{key}:{v}")); } let mut out = lines.join("\n"); out.push('\n'); let _ = std::fs::write(dir.join("horizon.txt"), out); } /// The dark palette (`horizon_theme::DARK`) in the HUD's colour encoding, plus the /// translucent plates the overlays draw over the game. pub(crate) mod color { use horizon_theme::DARK as P; pub const fn hex(c: u32, a: u8) -> u32 { (a as u32) << 24 | (c & 0xff) << 16 | (c >> 8 & 0xff) << 8 | (c >> 16 & 0xff) } /// The page, under every veil. pub const BG: u32 = hex(P.page, 255); /// Hover plates, secondary buttons, fields, the segmented track: the /// dark palette's soft plate, as ink over the veil so the plates read the /// same over any backdrop (over the page colour they are `plate_soft`). pub const RAISED: u32 = hex(P.ink, 20); /// Pressed plates and a switch that is off (`plate`, the same way). pub const HOVER: u32 = hex(P.ink, 36); /// One-pixel rules between rows, slider tracks. pub const BORDER: u32 = hex(P.rule, 255); /// Text and selection (`ink`). pub const TEXT: u32 = hex(P.ink, 255); /// Values and secondary text (`ink_soft`). pub const MUTED: u32 = hex(P.ink_soft, 255); pub const ACCENT: u32 = hex(P.accent, 255); pub const ON_ACCENT: u32 = hex(P.on_accent, 255); pub(crate) fn with_alpha(c: u32, a: f32) -> u32 { let base = (c >> 24) as f32; (c & 0x00ff_ffff) | ((base * a.clamp(0.0, 1.0)).round() as u32) << 24 } } /// The launcher's type scale and shapes (`horizon_theme`), in dp. pub(crate) const SMALL: f32 = horizon_theme::CAPTION.px; pub(crate) const BODY: f32 = horizon_theme::LABEL.px; /// Fields; plates (hover rows, selection); pills (buttons, segments). pub(crate) const RADIUS: f32 = horizon_theme::RADIUS; pub(crate) const RADIUS_PLATE: f32 = horizon_theme::RADIUS_PLATE; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) enum Face { Regular, Medium, } struct Fonts { faces: [FontRef<'static>; 2], } impl Fonts { fn load() -> Self { let f = |b: &'static [u8]| FontRef::try_from_slice(b).expect("bundled font"); Self { faces: [ f(horizon_theme::fonts::GEIST_REGULAR), f(horizon_theme::fonts::GEIST_MEDIUM), ], } } fn face(&self, f: Face) -> &FontRef<'static> { &self.faces[f as usize] } /// The ab_glyph scale for an em size in pixels. fn scale(&self, f: Face, px: f32) -> PxScale { let font = self.face(f); let upem = font.units_per_em().unwrap_or(1000.0); PxScale::from(px * font.height_unscaled() / upem) } } #[derive(Clone, Copy, PartialEq, Eq, Hash)] enum Key { Glyph(Face, u16, u16), /// A quarter disc (`false`) or a 1px quarter ring of this radius in pixels. Corner(u16, bool), } #[derive(Clone, Copy)] struct Cached { rect: Option, /// Offset of the bitmap from the pen (glyphs) in pixels. left: f32, top: f32, } /// Glyphs and corner masks rasterized into the atlas region `horizon/ui-text`. struct Cache { fonts: Fonts, entries: HashMap, shelf: (u32, u32, u32), pending: Vec, /// The atlas the entries were uploaded to (a new atlas starts over). atlas: usize, } thread_local! { static CACHE: RefCell> = const { RefCell::new(None) }; } /// Reloaded atlases can occupy the same address with empty run-time slots. pub fn reset_atlas() { CACHE.with(|cache| *cache.borrow_mut() = None); } fn with_cache(atlas: &HudAtlas, f: impl FnOnce(&mut Cache) -> R) -> R { CACHE.with(|c| { let mut c = c.borrow_mut(); let id = atlas as *const HudAtlas as usize; let cache = c.get_or_insert_with(|| Cache { fonts: Fonts::load(), entries: HashMap::new(), shelf: (0, 0, 0), pending: Vec::new(), atlas: id, }); if cache.atlas != id { cache.atlas = id; cache.entries.clear(); cache.shelf = (0, 0, 0); cache.pending.clear(); } f(cache) }) } impl Cache { fn region(atlas: &HudAtlas) -> Option { atlas.sprites.get("horizon/ui-text").copied() } /// Reserve `w x h` pixels; on overflow forget everything and start over. fn place(&mut self, atlas: &HudAtlas, w: u32, h: u32) -> Option<(u32, u32, Rect)> { let region = Self::region(atlas)?; let (mut x, mut y, mut row) = self.shelf; if x + w + 1 > region.w { x = 0; y += row + 1; row = 0; } if y + h > region.h || w > region.w { self.entries.clear(); self.shelf = (0, 0, 0); return None; } self.shelf = (x + w + 1, y, row.max(h)); Some((x, y, region)) } fn upload(&mut self, atlas: &HudAtlas, w: u32, h: u32, alpha: &[f32]) -> Option { let (x, y, region) = self.place(atlas, w, h)?; let (ax, ay) = ( (region.u0 * atlas.width as f32).round() as u32 + x, (region.v0 * atlas.height as f32).round() as u32 + y, ); let rgba = alpha .iter() .flat_map(|a| [255, 255, 255, (a.clamp(0.0, 1.0) * 255.0).round() as u8]) .collect(); self.pending.push(crate::font::Patch { x: ax, y: ay, width: w, height: h, rgba, }); let (aw, ah) = (atlas.width as f32, atlas.height as f32); Some(Rect { u0: ax as f32 / aw, v0: ay as f32 / ah, u1: (ax + w) as f32 / aw, v1: (ay + h) as f32 / ah, w, h, }) } fn glyph(&mut self, atlas: &HudAtlas, face: Face, id: ab_glyph::GlyphId, px: f32) -> Cached { let size = (px * 4.0).round() as u16; let key = Key::Glyph(face, id.0, size); if let Some(c) = self.entries.get(&key) { return *c; } let scale = self.fonts.scale(face, f32::from(size) / 4.0); let glyph = id.with_scale_and_position(scale, ab_glyph::point(0.0, 0.0)); let made = match self.fonts.face(face).outline_glyph(glyph) { Some(outline) => { let b = outline.px_bounds(); let (w, h) = (b.width() as u32, b.height() as u32); let mut alpha = vec![0.0; (w * h) as usize]; outline.draw(|x, y, c| { if x < w && y < h { alpha[(y * w + x) as usize] = c; } }); // Light text on dark backgrounds reads thin: a gentle boost. for a in &mut alpha { *a = a.powf(0.85); } Cached { rect: self.upload(atlas, w, h, &alpha), left: b.min.x, top: b.min.y, } } None => Cached { rect: None, left: 0.0, top: 0.0, }, }; if made.rect.is_some() || made.left == 0.0 { self.entries.insert(key, made); } made } fn corner(&mut self, atlas: &HudAtlas, r: u16, ring: bool) -> Option { let key = Key::Corner(r, ring); if let Some(c) = self.entries.get(&key) { return c.rect; } // The top-left quadrant of a circle centred at (r, r), 4x4 supersampled. let n = u32::from(r); let rf = f32::from(r); let mut alpha = vec![0.0; (n * n) as usize]; for y in 0..n { for x in 0..n { let mut hits = 0; for sy in 0..4 { for sx in 0..4 { let px = x as f32 + (sx as f32 + 0.5) / 4.0; let py = y as f32 + (sy as f32 + 0.5) / 4.0; let d = ((px - rf).powi(2) + (py - rf).powi(2)).sqrt(); if d <= rf && (!ring || d >= rf - 1.0) { hits += 1; } } } alpha[(y * n + x) as usize] = hits as f32 / 16.0; } } let rect = self.upload(atlas, n, n, &alpha); if rect.is_some() { self.entries.insert( key, Cached { rect, left: 0.0, top: 0.0, }, ); } rect } } /// One frame of design-system drawing, in dp: the /// launcher's logical pixels, scaled so the screen reads like the launcher's /// 1040x700 window at any size. pub struct Ui<'a> { pub atlas: &'a HudAtlas, pub batch: &'a mut HudBatch, /// The screen in dp. pub w: f32, pub h: f32, /// The cursor in dp. pub cursor: (f32, f32), /// Physical pixels per dp. pub density: f32, scale: f32, } impl<'a> Ui<'a> { /// `cursor` is in GUI pixels, like every screen's input. pub fn new(atlas: &'a HudAtlas, batch: &'a mut HudBatch, cursor: (f32, f32)) -> Self { let scale = batch.scale; let (pw, ph) = (batch.width * scale, batch.height * scale); let density = (pw / 1040.0).min(ph / 700.0).clamp(1.0, 4.0); Self { atlas, w: pw / density, h: ph / density, cursor: (cursor.0 * scale / density, cursor.1 * scale / density), density, scale, batch, } } /// Move rasterized glyphs into the batch's atlas uploads (real frames only). pub fn finish(self) { let pending = with_cache(self.atlas, |c| std::mem::take(&mut c.pending)); self.batch.patches.extend(pending); } // ---- geometry, snapped to physical pixels ---- fn px_x(&self, v: f32) -> f32 { (v * self.density).round() } fn px_y(&self, v: f32) -> f32 { (v * self.density).round() } fn raw_fill(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, color: u32) { if x1 > x0 && y1 > y0 { let s = self.scale; self.batch.fill( self.atlas, x0 / s, y0 / s, (x1 - x0) / s, (y1 - y0) / s, color, ); } } fn corner_quad(&mut self, rect: Rect, x: f32, y: f32, r: f32, flip: (bool, bool), color: u32) { let (u0, u1) = if flip.0 { (rect.u1, rect.u0) } else { (rect.u0, rect.u1) }; let (v0, v1) = if flip.1 { (rect.v1, rect.v0) } else { (rect.v0, rect.v1) }; let s = self.scale; let (gx, gy, gr) = (x / s, y / s, r / s); self.batch.quad( [[gx, gy], [gx + gr, gy], [gx + gr, gy + gr], [gx, gy + gr]], [[u0, v0], [u1, v0], [u1, v1], [u0, v1]], color, ); } fn corners(&mut self, x0: f32, y0: f32, x1: f32, y1: f32, r: f32, ring: bool, color: u32) { if r < 1.0 { return; } let atlas = self.atlas; if let Some(rect) = with_cache(atlas, |c| c.corner(atlas, r as u16, ring)) { self.corner_quad(rect, x0, y0, r, (false, false), color); self.corner_quad(rect, x1 - r, y0, r, (true, false), color); self.corner_quad(rect, x1 - r, y1 - r, r, (true, true), color); self.corner_quad(rect, x0, y1 - r, r, (false, true), color); } } /// A filled rectangle with rounded corners. pub(crate) fn rounded(&mut self, x: f32, y: f32, w: f32, h: f32, radius: f32, color: u32) { if color >> 24 == 0 { return; } let (x0, y0, x1, y1) = ( self.px_x(x), self.px_y(y), self.px_x(x + w), self.px_y(y + h), ); let r = (radius * self.density) .round() .min(((x1 - x0) / 2.0).floor()) .min(((y1 - y0) / 2.0).floor()) .max(0.0); if r < 1.0 { self.raw_fill(x0, y0, x1, y1, color); return; } self.raw_fill(x0 + r, y0, x1 - r, y1, color); self.raw_fill(x0, y0 + r, x0 + r, y1 - r, color); self.raw_fill(x1 - r, y0 + r, x1, y1 - r, color); self.corners(x0, y0, x1, y1, r, false, color); } /// A 1px rounded border. pub(crate) fn border(&mut self, x: f32, y: f32, w: f32, h: f32, radius: f32, color: u32) { if color >> 24 == 0 { return; } let (x0, y0, x1, y1) = ( self.px_x(x), self.px_y(y), self.px_x(x + w), self.px_y(y + h), ); let r = (radius * self.density) .round() .min(((x1 - x0) / 2.0).floor()) .min(((y1 - y0) / 2.0).floor()) .max(0.0); self.raw_fill(x0 + r, y0, x1 - r, y0 + 1.0, color); self.raw_fill(x0 + r, y1 - 1.0, x1 - r, y1, color); self.raw_fill(x0, y0 + r, x0 + 1.0, y1 - r, color); self.raw_fill(x1 - 1.0, y0 + r, x1, y1 - r, color); self.corners(x0, y0, x1, y1, r, true, color); } // ---- text ---- /// The advance of `text` in dp. pub(crate) fn measure(&self, face: Face, size: f32, text: &str) -> f32 { let px = (size * self.density * 4.0).round() / 4.0; with_cache(self.atlas, |c| { let font = c.fonts.face(face); let scaled = font.as_scaled(c.fonts.scale(face, px)); let mut w = 0.0; let mut prev = None; for ch in text.chars() { let id = font.glyph_id(ch); if let Some(p) = prev { w += scaled.kern(p, id); } w += scaled.h_advance(id); prev = Some(id); } w / self.density }) } /// Draw a line of text in a `line`-tall box whose top is `y` (the /// launcher's line heights: about 1.45 × size for the interface); /// returns its width in dp. pub(crate) fn text_line( &mut self, face: Face, size: f32, line: f32, x: f32, y: f32, color: u32, text: &str, ) -> f32 { let px = (size * self.density * 4.0).round() / 4.0; let real = color >> 24 != 0; let (x0, y0) = (self.px_x(x), self.px_y(y)); let box_px = line * self.density; let atlas = self.atlas; let density = self.density; let mut quads = Vec::new(); let width = with_cache(atlas, |c| { let scale = c.fonts.scale(face, px); let (ascent, descent) = { let f = c.fonts.face(face).as_scaled(scale); (f.ascent(), f.descent()) }; let baseline = y0 + ((box_px - (ascent - descent)) / 2.0 + ascent).round(); let mut pen = x0; let mut prev = None; for ch in text.chars() { let (id, advance, kern) = { let font = c.fonts.face(face); let id = font.glyph_id(ch); let f = font.as_scaled(scale); (id, f.h_advance(id), prev.map_or(0.0, |p| f.kern(p, id))) }; pen += kern; if real && !ch.is_whitespace() { let g = c.glyph(atlas, face, id, px); if let Some(rect) = g.rect { quads.push(((pen + g.left).round(), baseline + g.top, rect)); } } pen += advance; prev = Some(id); } (pen - x0) / density }); let s = self.scale; for (gx, gy, rect) in quads { self.batch.rect_uv( gx / s, gy / s, rect.w as f32 / s, rect.h as f32 / s, rect, color, ); } width } /// Text in a `1.45 × size` line box whose top is `y`. pub(crate) fn text( &mut self, face: Face, size: f32, x: f32, y: f32, color: u32, text: &str, ) -> f32 { self.text_line(face, size, (size * 1.45).round(), x, y, color, text) } pub(crate) fn text_centered( &mut self, face: Face, size: f32, cx: f32, y: f32, color: u32, text: &str, ) { let w = self.measure(face, size, text); self.text(face, size, cx - w / 2.0, y, color, text); } // ---- the launcher's components ---- } #[cfg(test)] mod tests { use super::*; #[test] fn atlas_reload_regenerates_text_and_corners_at_the_same_address() { let atlas = HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap(); reset_atlas(); let draw = |cache: &mut Cache| { let glyph = cache.fonts.face(Face::Regular).glyph_id('A'); assert!( cache .glyph(&atlas, Face::Regular, glyph, 16.0) .rect .is_some() ); assert!(cache.corner(&atlas, 8, false).is_some()); std::mem::take(&mut cache.pending) }; let before = with_cache(&atlas, draw); assert_eq!(before.len(), 2); assert!(with_cache(&atlas, draw).is_empty()); reset_atlas(); let after = with_cache(&atlas, draw); assert_eq!(after.len(), 2); for (a, b) in before.iter().zip(&after) { assert_eq!((a.x, a.y, a.width, a.height), (b.x, b.y, b.width, b.height)); assert_eq!(a.rgba, b.rgba); } reset_atlas(); } }