From 2243518e3bd4f8c8794de8281c34013f3af38e17 Mon Sep 17 00:00:00 2001 From: Antigravity Date: Tue, 24 Nov 2026 19:49:06 +0000 Subject: [PATCH 1/4] feat(frontend-sync): add zero-allocation offline RGB888 showcase GIF sync on RPi - Resolve local `/showcase//.gif` (YOKO) and `/showcase_tate//.gif` (TATE) via `DmdCache::resolve_offline_showcase_gif_path` with `0` network traffic when present on SD/DATA - Decode multi-frame 24-bit `RGB888` GIFs off-thread into `PreloadedRgb888Gif` and render on H-Core via `SyncOfflineGifRenderer` (`once`, `alternating`, `loop` cycles, `V1.6-FinalLocked` parity with ESP32) - Prove `0` H-Core heap allocations across 10,000 frames via `TrackingAllocator` in `tests/test_v16_final_locked.rs` plus full MQTT TATE E2E tests and trilingual (`EN`/`FR`/`ES`) Online/Offline/Hybrid guides --- README.md | 3 +- README_ES.md | 3 +- README_FR.md | 3 +- docs/QUICKSTART.md | 7 +- docs/QUICKSTART_ES.md | 7 +- docs/QUICKSTART_FR.md | 7 +- src/core/dmd_cache.rs | 131 +++++++++ src/core/types.rs | 79 ++++- src/engines/frontend_sync.rs | 434 ++++++++++++++++++++++++++-- src/engines/gif.rs | 2 +- src/engines/renderers/sync_cards.rs | 16 + tests/test_v16_final_locked.rs | 95 ++++++ 12 files changed, 741 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index 52a7847b..fd1b501e 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,8 @@ ArcadeMatrix supports instant **Pixelcade-style** marquees while browsing menus, 1. **Menu Browsing (`0 ms` Instant Marquee)**: As you browse your game lists, the Raspberry Pi downloads official Pixelcade marquees in the background, caches them on your SD card, and displays them instantly on your LED matrix. 2. **Launching a Game (Seamless In-Game Showcase)**: - The moment you launch a game, the **classic marquee appears immediately** (zero black screen or `"Waiting for content"` screen). - - If **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** is enabled on your network and **In-Game Showcase** is turned on, `FrontendSync` requests the game's presentation on a dedicated `{dmd_id}_sync` slot (sending both the ROM basename and console display title as `fallback_query` without disturbing Showcase rotation queues), prepares the **Animated Info Card** + **Boxart/Marquee/Screenshot Panoramas** + **Gameplay Video** in the background, and smoothly takes over the screen once ready. + - **Offline In-Game Showcase (`0 ms`, Zero Server Needed)**: If you placed an Offline Recalbox/Batocera pack generated by **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** Tab #7 into `data/showcase//.gif` (`data/showcase_tate//.gif` in TATE), `FrontendSync` decodes and plays the 24-bit `RGB888` `.gif` presentation locally with **`0` network calls** — even without a running Showcase server! + - **Live Remote Fallback**: Otherwise, if **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** is enabled on your network and **In-Game Showcase** is turned on, `FrontendSync` requests the game's presentation on a dedicated `{dmd_id}_sync` slot (sending both the ROM basename and console display title as `fallback_query` without disturbing Showcase rotation queues), prepares the **Animated Info Card** + **Boxart/Marquee/Screenshot Panoramas** + **Gameplay Video** in the background, and smoothly takes over the screen once ready. - Configurable **Playback Cycle** while playing: - **Alternate Marquee & Showcase** *(default)*: Alternates between the Showcase presentation and a configurable pause on the classic marquee (e.g. `45s`). - **Play Once then Keep Marquee**: Plays the Showcase presentation once, then leaves the game's marquee on screen. diff --git a/README_ES.md b/README_ES.md index cb9c215b..1cf57143 100644 --- a/README_ES.md +++ b/README_ES.md @@ -265,7 +265,8 @@ ArcadeMatrix es compatible con marquees instantáneos **estilo Pixelcade** al na 1. **Navegación por Menús (`0 ms` — Marquesina Instantánea)**: Mientras navegas por tus listas de juegos, la Raspberry Pi descarga las marquees oficiales de Pixelcade en segundo plano, las almacena en caché en la tarjeta SD y las muestra al instante en tu matriz LED. 2. **Al Iniciar un Juego (Showcase en Juego Fluido)**: - En cuanto lanzas un juego, la **marquesina clásica aparece de inmediato** (sin pantalla negra ni mensaje de espera). - - Si **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** está activo en tu red local y **Showcase en Juego** está habilitado, `FrontendSync` solicita la secuencia en una ranura dedicada `{dmd_id}_sync` (enviando tanto el nombre de la ROM como el título de consola como `fallback_query`, sin alterar las colas de rotación de Showcase), prepara en segundo plano la **Ficha Informativa Animada** + **Panoramas de Carátula/Marquee/Capturas** + **Vídeo de Gameplay** y toma el relevo suavemente cuando está lista. + - **Showcase en Juego Offline (`0 ms`, Sin Servidor)**: Si colocaste un paquete Offline de Recalbox/Batocera generado desde la pestaña #7 de **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** en `data/showcase//.gif` (`data/showcase_tate//.gif` en TATE), `FrontendSync` decodifica y reproduce directamente el `.gif` `RGB888` de 24 bits en local con **`0` llamadas de red**, ¡incluso sin servidor Showcase encendido! + - **Respaldo en Vivo por Red**: En caso contrario, si **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** está activo en tu red local y **Showcase en Juego** está habilitado, `FrontendSync` solicita la secuencia en una ranura dedicada `{dmd_id}_sync` (enviando tanto el nombre de la ROM como el título de consola como `fallback_query`, sin alterar las colas de rotación de Showcase), prepara en segundo plano la **Ficha Informativa Animada** + **Panoramas de Carátula/Marquee/Capturas** + **Vídeo de Gameplay** y toma el relevo suavemente cuando está lista. - **Ciclo de Reproducción** configurable durante la partida: - **Alternar Marquesina y Showcase** *(por defecto)*: alterna entre la secuencia Showcase y una pausa configurable en la marquesina clásica (ej. `45s`). - **Reproducir una vez y mantener Marquesina**: reproduce Showcase una vez y mantiene la marquesina fija del juego. diff --git a/README_FR.md b/README_FR.md index e7d08cb6..2d66fdf0 100644 --- a/README_FR.md +++ b/README_FR.md @@ -262,7 +262,8 @@ ArcadeMatrix prend en charge les marquees instantanés **style Pixelcade** penda 1. **Navigation dans les Menus (`0 ms` — Marquee Instantané)** : Quand vous parcourez vos listes de jeux, le Raspberry Pi télécharge les marquees officielles Pixelcade en arrière-plan, les met en cache sur votre carte SD et les affiche instantanément sur votre matrice LED. 2. **Lancement d'un Jeu (Showcase en Jeu Transparent)** : - Dès le lancement d'un jeu, le **marquee classique s'affiche immédiatement** (aucun écran noir ni message d'attente). - - Si **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** est actif sur votre réseau et que **Showcase en Jeu** est activé, `FrontendSync` demande la séquence sur un slot dédié `{dmd_id}_sync` (en transmettant le nom de la ROM ainsi que le titre console en `fallback_query`, sans perturber les files de rotation Showcase), prépare en tâche de fond la **Fiche Info Animée** + **Panoramas Jaquette/Marquee/Screenshots** + **Vidéo de Gameplay**, et prend la main en douceur dès qu'elle est prête. + - **Showcase en Jeu Offline (`0 ms`, Sans Serveur)** : Si vous avez déposé un pack Offline Recalbox/Batocera généré depuis l'onglet #7 de **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** dans `data/showcase//.gif` (`data/showcase_tate//.gif` en TATE), `FrontendSync` décode et lit directement le `.gif` `RGB888` 24 bits en local avec **`0` appel réseau** — même sans serveur Showcase actif ! + - **Repli Serveur Live** : Sinon, si **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** est actif sur votre réseau et que **Showcase en Jeu** est activé, `FrontendSync` demande la séquence sur un slot dédié `{dmd_id}_sync` (en transmettant le nom de la ROM ainsi que le titre console en `fallback_query`, sans perturber les files de rotation Showcase), prépare en tâche de fond la **Fiche Info Animée** + **Panoramas Jaquette/Marquee/Screenshots** + **Vidéo de Gameplay**, et prend la main en douceur dès qu'elle est prête. - Choix du **Cycle d'Affichage** pendant la partie : - **Alterner Marquee & Showcase** *(par défaut)* : alterne entre la présentation Showcase et une pause configurable sur le marquee classique (ex. `45s`). - **Lire une fois puis garder le Marquee** : joue la séquence Showcase une fois, puis laisse le marquee du jeu affiché. diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index 6c435dd2..c0107145 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -46,9 +46,10 @@ We recommend using an Adafruit RGB Matrix HAT or Bonnet connected to a Raspberry 1. **1-Click Console Setup**: Open **System → MQTT & API → 🎮 FrontendSync**, enter your Recalbox, Batocera, or RetroPie IP and SSH credentials, and click **Install Sync Script** (your console stores only your DMD's IP and discovers the active MQTT broker automatically — you never have to reinstall the script later). 2. **Instant Marquees**: Set **Enable MQTT** to **Enabled**. Scrolling menus on your console displays Pixelcade marquees immediately (`0 ms`). -3. **In-Game Info Cards & Gameplay Videos** (with **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** on your LAN): - - In **🎬 DMD Media Showcase**, toggle **Enable DMD Media Showcase** ON (`🟢 Communication OK`). - - In **🎮 FrontendSync**, enable **Share Showcase MQTT Broker** (frees local RAM) and **In-Game Showcase (Card + Gameplay Video)**, pick your **Playback Cycle** (`Alternate Marquee & Showcase`, `Play Once`, or `Loop`) and **Card Style** (`Inherit from Showcase Studio` or `Custom Override on DMD`), and click **Save MQTT Settings**. +3. **In-Game Info Cards & Gameplay Videos: Online, Offline, or Hybrid Mode** (with **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)**): + - 🌐 **100% Online Mode (Live Stream, zero files to copy)**: In **🎬 DMD Media Showcase**, toggle **Enable DMD Media Showcase** ON (`🟢 Communication OK`), then in **🎮 FrontendSync**, enable **Share Showcase MQTT Broker** and **In-Game Showcase (Card + Gameplay Video)** (`Alternate Marquee & Showcase`, `Play Once`, or `Loop`). + - 💾 **100% Offline Mode (No PC running & No Internet)**: In Showcase's **Tab `7. Batch Scraper & Offline Packs`** (from a PC, NAS, or smartphone), import your Recalbox/Batocera `gamelist.xml` file(s) and copy **`showcase/`** (or `showcase_tate/` on vertical panels) + **`pixelcade/`** onto your **DATA** USB partition (plus any Clock playlists like `snes_platformer` into `DATA:/gifs/`). Keep **In-Game Showcase** enabled in **🎮 FrontendSync**: your `RGB888` `.gif` packs play in **`0 ms`** even with Showcase Server turned OFF! + - ⚡ **Hybrid Mode (Automatic)**: When both `DATA:/showcase/` and Showcase Server are enabled, your Raspberry Pi always plays local `.gif` packs first (`0` network traffic) and queries the Online server only for new games missing from the SD card ([Complete Beginner Tutorial](https://github.com/red77290/dmd_media_showcase/blob/main/docs/TUTORIAL_ONLINE_OFFLINE_SCRAPING.md)). ## 6. Appendix: PC & Console Companion Tools (`ArcadeMatrix-tools.zip`) diff --git a/docs/QUICKSTART_ES.md b/docs/QUICKSTART_ES.md index 184d3e5c..93d93b2c 100644 --- a/docs/QUICKSTART_ES.md +++ b/docs/QUICKSTART_ES.md @@ -46,9 +46,10 @@ Recomendamos usar un Adafruit RGB Matrix HAT o Bonnet conectado a una Raspberry 1. **Instalación en Consola en 1 Clic**: Abre **Sistema → MQTT & API → 🎮 FrontendSync**, introduce la IP y credenciales SSH de tu consola Recalbox, Batocera o RetroPie y pulsa **Install Sync Script** (la consola solo guarda la IP del DMD y descubre automáticamente el broker MQTT activo — nunca tendrás que reinstalar el script). 2. **Marquesinas Instantáneas**: Pon **Activar MQTT** en **Activado**. Al navegar por los menús de tu consola se mostrarán las marquesinas Pixelcade al instante (`0 ms`). -3. **Fichas y Vídeos de Gameplay en Juego** (con **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** en tu red local): - - En **🎬 DMD Media Showcase**, activa el servidor Showcase (`🟢 Comunicación OK`). - - En **🎮 FrontendSync**, activa **Usar Broker MQTT de Showcase si está activo** (libera RAM local) y **Showcase en Juego (Tarjeta + Vídeo Gameplay)**, elige tu **Ciclo** (`Alternar Marquesina y Showcase`, `Una vez` o `Bucle`) y el **Estilo de Tarjeta** (`Heredar de Showcase Studio` o `Personalizado en el DMD`), y guarda los ajustes. +3. **Fichas y Vídeos de Gameplay en Juego: Modo Online, Offline o Híbrido** (con **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)**): + - 🌐 **Modo 100 % Online (Streaming directo sin copiar archivos)**: En **🎬 DMD Media Showcase**, activa el servidor Showcase (`🟢 Comunicación OK`), y en **🎮 FrontendSync**, activa **Usar Broker MQTT de Showcase si está activo** y **Showcase en Juego (Tarjeta + Vídeo Gameplay)** (`Alternar Marquesina y Showcase`, `Una vez` o `Bucle`). + - 💾 **Modo 100 % Offline (Sin PC encendido ni Internet)**: En la pestaña **`7. Batch Scraper & Packs Offline`** de Showcase (desde un PC, NAS o móvil), importa tus `gamelist.xml` de Recalbox/Batocera y copia **`showcase/`** (o `showcase_tate/` en vertical) + **`pixelcade/`** en la unidad USB **DATA** (así como playlists de reloj `snes_platformer`... en `DATA:/gifs/`). Con **Showcase en Juego** activo en **🎮 FrontendSync**, tus `.gif` `RGB888` arrancan en **`0 ms`** incluso con Showcase Server apagado. + - ⚡ **Modo Híbrido (Automático)**: Si `DATA:/showcase/` existe **y** Showcase Server está activo, la Raspberry Pi reproduce siempre primero el `.gif` local (`0` tráfico de red) y consulta al servidor Online solo para juegos nuevos que no estén en la tarjeta SD ([Tutorial Completo para Principiantes](https://github.com/red77290/dmd_media_showcase/blob/main/docs/TUTORIAL_ONLINE_OFFLINE_SCRAPING_ES.md)). ## 6. Anexo: Uso de las Herramientas para PC y Consolas (`ArcadeMatrix-tools.zip`) diff --git a/docs/QUICKSTART_FR.md b/docs/QUICKSTART_FR.md index 9cd4c843..9b76ea5b 100644 --- a/docs/QUICKSTART_FR.md +++ b/docs/QUICKSTART_FR.md @@ -46,9 +46,10 @@ Nous recommandons d'utiliser un Adafruit RGB Matrix HAT ou Bonnet connecté à u 1. **Installation Console en 1 Clic** : Ouvrez **Système → MQTT & API → 🎮 FrontendSync**, renseignez l'IP et les identifiants SSH de votre console Recalbox, Batocera ou RetroPie, puis cliquez sur **Install Sync Script** (la console ne mémorise que l'IP du DMD et découvre automatiquement le broker MQTT actif — aucune réinstallation ultérieure requise). 2. **Marquees Instantanés** : Passez **Activer MQTT** sur **Activé**. Parcourir vos menus affiche immédiatement les marquees Pixelcade (`0 ms`). -3. **Fiches & Vidéos de Gameplay en Jeu** (avec **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)** sur votre réseau) : - - Dans **🎬 DMD Media Showcase**, activez le serveur Showcase (`🟢 Communication OK`). - - Dans **🎮 FrontendSync**, activez **Utiliser le Broker MQTT Showcase si actif** (libère la RAM locale) et **Showcase en Jeu (Carte + Vidéo Gameplay)**, choisissez votre **Cycle** (`Alterner Marquee & Showcase`, `Une fois` ou `Boucle`) et votre **Style de Carte** (`Hériter de Showcase Studio` ou `Personnalisé sur le DMD`), puis enregistrez. +3. **Fiches & Vidéos de Gameplay en Jeu : Mode Online, Mode Offline ou Hybride** (avec **[dmd_media_showcase](https://github.com/red77290/dmd_media_showcase)**) : + - 🌐 **Mode 100 % Online (Streaming Direct sans copier de fichiers)** : Dans **🎬 DMD Media Showcase**, activez le serveur Showcase (`🟢 Communication OK`), puis dans **🎮 FrontendSync**, activez **Utiliser le Broker MQTT Showcase si actif** et **Showcase en Jeu (Carte + Vidéo Gameplay)** (`Alterner Marquee & Showcase`, `Une fois` ou `Boucle`). + - 💾 **Mode 100 % Offline (Sans PC allumé ni Internet)** : Dans l'onglet **`7. Batch Scraper & Packs Offline`** de Showcase (depuis un PC, NAS ou smartphone), importez vos `gamelist.xml` Recalbox/Batocera et copiez les dossiers **`showcase/`** (ou `showcase_tate/` en vertical) + **`pixelcade/`** sur votre lecteur USB **DATA** (ainsi que vos playlists horloge `snes_platformer`... dans `DATA:/gifs/`). Activez simplement **Showcase en Jeu** dans **🎮 FrontendSync** : vos `.gif` `RGB888` démarrent en **`0 ms`** même avec Showcase Server désactivé ! + - ⚡ **Mode Hybride (Automatique)** : Si `DATA:/showcase/` est présent **et** que Showcase Server est activé, le Raspberry Pi joue toujours le `.gif` local en priorité instantanée (`0` trafic réseau) et n'interroge le serveur Online que pour les nouveaux jeux absents de la carte SD ([Tutoriel complet Débutant](https://github.com/red77290/dmd_media_showcase/blob/main/docs/TUTORIAL_ONLINE_OFFLINE_SCRAPING_FR.md)). ## 6. Annexe : Utiliser les Outils Compagnons PC & Consoles (`ArcadeMatrix-tools.zip`) diff --git a/src/core/dmd_cache.rs b/src/core/dmd_cache.rs index 3fc9fde8..f4973b30 100644 --- a/src/core/dmd_cache.rs +++ b/src/core/dmd_cache.rs @@ -187,9 +187,97 @@ impl DmdCache { return Some(local_path); } } + + // Also check pre-synced companion marquees under `/pixelcade//.{png,gif}` + let folders = build_offline_folder_candidates(system); + let stems = build_offline_stem_candidates(game); + for root in self.offline_pack_search_roots() { + let px_root = root.join("pixelcade"); + if !px_root.is_dir() { + continue; + } + for folder in &folders { + let f_dir = px_root.join(folder); + if !f_dir.is_dir() { + continue; + } + for stem in &stems { + for ext in &[".png", ".gif"] { + let cand = f_dir.join(format!("{}{}", stem, ext)); + if cand.is_file() { + return Some(cand); + } + } + } + } + } None } + /// Resolves a local 24-bit `RGB888` Offline In-Game Showcase `.gif` (`showcase[_tate]//.gif`) + /// generated by `dmd_media_showcase` Batch Scraper (`0` network calls). + pub fn resolve_offline_showcase_gif_path( + &self, + system: &str, + game: &str, + is_tate: bool, + ) -> Option { + let folders = build_offline_folder_candidates(system); + let stems = build_offline_stem_candidates(game); + if folders.is_empty() || stems.is_empty() { + return None; + } + + let sub_roots: &[&str] = if is_tate { + &["showcase_tate", "showcase"] + } else { + &["showcase"] + }; + + for base_root in self.offline_pack_search_roots() { + for sub in sub_roots { + let sc_root = base_root.join(sub); + if !sc_root.is_dir() { + continue; + } + for folder in &folders { + let sys_dir = sc_root.join(folder); + if !sys_dir.is_dir() { + continue; + } + for stem in &stems { + let cand = sys_dir.join(format!("{}.gif", stem)); + if cand.is_file() { + return Some(cand); + } + } + } + } + } + None + } + + fn offline_pack_search_roots(&self) -> Vec { + let mut roots: Vec = Vec::with_capacity(6); + if let Some(parent) = self.cache_dir.parent() { + roots.push(parent.to_path_buf()); + } + roots.push(self.cache_dir.clone()); + for fixed in &[ + "data", + ".", + "/arcade", + "/opt/arcadematrix/data", + "/opt/arcadematrix", + ] { + let pb = PathBuf::from(fixed); + if !roots.iter().any(|r| r == &pb) { + roots.push(pb); + } + } + roots + } + pub fn download_marquee(&self, system: &str, game: &str) -> Option { self.download_marquee_with_title(system, game, None) } @@ -644,6 +732,49 @@ pub fn clean_system_name(system: &str) -> String { s.trim().to_string() } +pub fn build_offline_folder_candidates(system_id: &str) -> Vec { + let cleaned = clean_system_name(system_id); + let primary = map_system_to_pixelcade_folder(system_id); + let secondary = get_secondary_pixelcade_folder(system_id); + + let mut out: Vec = Vec::with_capacity(3); + for cand in [Some(cleaned.as_str()), Some(primary.as_str()), secondary] + .into_iter() + .flatten() + { + let trimmed = cand.trim(); + if trimmed.is_empty() { + continue; + } + let safe = sanitize_cache_component(trimmed); + if safe != "_" && !out.iter().any(|x| x.eq_ignore_ascii_case(&safe)) { + out.push(safe); + } + } + out +} + +pub fn build_offline_stem_candidates(raw_game: &str) -> Vec { + let leaf = raw_game + .rsplit(['/', '\\']) + .next() + .unwrap_or(raw_game) + .trim(); + let base_no_ext = strip_known_rom_or_image_ext(leaf).trim(); + let safe_leaf = sanitize_cache_component(base_no_ext); + let stripped = strip_rom_or_art_extension_and_tags(leaf); + let safe_stripped = sanitize_cache_component(stripped.trim()); + + let mut out: Vec = Vec::with_capacity(3); + for cand in [&safe_leaf, &safe_stripped, &base_no_ext.to_string()] { + let t = cand.trim(); + if !t.is_empty() && t != "_" && !out.iter().any(|x| x.eq_ignore_ascii_case(t)) { + out.push(t.to_string()); + } + } + out +} + fn compact_system_key(s: &str) -> String { s.chars() .filter(|c| c.is_ascii_alphanumeric()) diff --git a/src/core/types.rs b/src/core/types.rs index a0faa7f0..3c7716f9 100644 --- a/src/core/types.rs +++ b/src/core/types.rs @@ -18,19 +18,92 @@ pub enum InGameCycleMode { Alternating { marquee_interval_sec: u32 }, } -/// Preloaded in-game Showcase stream published from the FrontendSync worker to the render loop +/// Pre-decoded 24-bit `RGB888` (`RgbImage`) frames for Offline In-Game Showcase `.gif` playback (0 H-Core alloc). +#[derive(Clone)] +pub struct PreloadedRgb888Gif { + pub frames: Arc>, + pub width: u32, + pub height: u32, +} + +/// Preloaded in-game Showcase sequence published from the FrontendSync worker to the render loop #[derive(Clone)] pub struct InGameShowcasePayload { pub session_token: u64, - pub stream: Arc, + pub stream: Option>, + pub offline_gif: Option, pub cycle_mode: InGameCycleMode, } +impl InGameShowcasePayload { + #[inline] + pub fn from_stream( + session_token: u64, + stream: Arc, + cycle_mode: InGameCycleMode, + ) -> Self { + Self { + session_token, + stream: Some(stream), + offline_gif: None, + cycle_mode, + } + } + + #[inline] + pub fn from_offline_gif( + session_token: u64, + frames: Arc>, + width: u32, + height: u32, + cycle_mode: InGameCycleMode, + ) -> Self { + Self { + session_token, + stream: None, + offline_gif: Some(PreloadedRgb888Gif { + frames, + width, + height, + }), + cycle_mode, + } + } + + #[inline] + pub fn is_empty(&self) -> bool { + let stream_ok = self.stream.as_ref().is_some_and(|s| !s.is_empty()); + let gif_ok = self + .offline_gif + .as_ref() + .is_some_and(|g| !g.frames.is_empty()); + !stream_ok && !gif_ok + } + + #[inline] + pub fn dimensions(&self) -> (u32, u32) { + if let Some(ref s) = self.stream { + (s.width, s.height) + } else if let Some(ref g) = self.offline_gif { + (g.width, g.height) + } else { + (0, 0) + } + } +} + impl std::fmt::Debug for InGameShowcasePayload { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let frames = self + .stream + .as_ref() + .map(|s| s.frame_count as usize) + .or_else(|| self.offline_gif.as_ref().map(|g| g.frames.len())) + .unwrap_or(0); f.debug_struct("InGameShowcasePayload") .field("session_token", &self.session_token) - .field("frame_count", &self.stream.frame_count) + .field("frame_count", &frames) + .field("is_offline_gif", &self.offline_gif.is_some()) .field("cycle_mode", &self.cycle_mode) .finish() } diff --git a/src/engines/frontend_sync.rs b/src/engines/frontend_sync.rs index af057c77..510069c0 100644 --- a/src/engines/frontend_sync.rs +++ b/src/engines/frontend_sync.rs @@ -11,7 +11,7 @@ use crate::engines::renderers::media_showcase::{ resolve_showcase_server_url, rpi_hardware_short_id, }; pub use crate::engines::renderers::sync_cards::{ - HallOfFameCard, RetroAchievementsCard, SyncCelebrationRenderer, + HallOfFameCard, RetroAchievementsCard, SyncCelebrationRenderer, SyncOfflineGifRenderer, }; use parking_lot::Mutex; use rumqttc::{Client, Event, MqttOptions, Packet, QoS}; @@ -523,12 +523,15 @@ fn take_ready_signal(sync_client_id: &str, queue_id: &str) -> Option { fn spawn_ingame_showcase_request( config: Arc, + dmd_cache: Arc, req_id: u64, system: String, game: String, fallback_title: String, + offline_dwell_ms: u64, ) { std::thread::spawn(move || { + let launch_started = Instant::now(); let (showcase_enabled, raw_server_url, mqtt_cfg, width, height, lang) = { let s = config.settings.read(); let phys_w = s.matrix.width.saturating_mul(s.matrix.chain_length.max(1)); @@ -552,10 +555,57 @@ fn spawn_ingame_showcase_request( ) }; - if !showcase_enabled - || !mqtt_cfg.ingame_showcase_enabled - || raw_server_url.trim().is_empty() + if !mqtt_cfg.ingame_showcase_enabled { + return; + } + if MQTT_REQUEST_ID.load(Ordering::Acquire) != req_id { + return; + } + + // 1. Offline-First Fast Path: check local `showcase[_tate]//.gif` (0 network calls, + // works even when remote `showcase.enabled` is false or Wi-Fi is disconnected). + if let Some(offline_gif_path) = + dmd_cache.resolve_offline_showcase_gif_path(&system, &game, height > width) { + if let Some(frames) = crate::engines::gif::GifEngine::decode_gif_frames( + &offline_gif_path, + width.max(1), + height.max(1), + ) { + let cycle_mode = parse_cycle_mode(&mqtt_cfg); + let target_dwell = Duration::from_millis(offline_dwell_ms); + while launch_started.elapsed() < target_dwell { + if MQTT_REQUEST_ID.load(Ordering::Acquire) != req_id { + return; + } + let rem = target_dwell.saturating_sub(launch_started.elapsed()); + std::thread::sleep(rem.min(Duration::from_millis(50))); + } + if MQTT_REQUEST_ID.load(Ordering::Acquire) != req_id { + return; + } + info!( + "[FrontendSync] Offline In-Game Showcase RGB888 GIF ready for {}/{} -> {} ({} frames, {:?})", + system, + game, + offline_gif_path.display(), + frames.len(), + cycle_mode + ); + crate::core::matrix::reset_mock_distinct_crcs(); + e2e_telemetry().lock().showcase_streams_loaded += 1; + config.set_ingame_showcase(Some(InGameShowcasePayload::from_offline_gif( + req_id, + Arc::new(frames), + width.max(1), + height.max(1), + cycle_mode, + ))); + return; + } + } + + if !showcase_enabled || raw_server_url.trim().is_empty() { return; } if MQTT_REQUEST_ID.load(Ordering::Acquire) != req_id { @@ -801,11 +851,9 @@ fn spawn_ingame_showcase_request( ); crate::core::matrix::reset_mock_distinct_crcs(); e2e_telemetry().lock().showcase_streams_loaded += 1; - config.set_ingame_showcase(Some(InGameShowcasePayload { - session_token: req_id, - stream, - cycle_mode, - })); + config.set_ingame_showcase(Some(InGameShowcasePayload::from_stream( + req_id, stream, cycle_mode, + ))); }); } @@ -1218,10 +1266,12 @@ pub fn handle_frontend_sync_payload( } spawn_ingame_showcase_request( Arc::clone(config), + Arc::clone(dmd_cache), req_id, system, - game_clean, + game, raw_title, + 3500, ); } } @@ -1633,7 +1683,7 @@ enum InGameSubStage { ShowcaseStream, } -/// Zero-reallocation realtime playback engine for In-Game Showcase sequences (`DMDZ` v2 & `DMDS`) +/// Zero-reallocation realtime playback engine for In-Game Showcase sequences (`DMDZ` v2, `DMDS`, & Offline `RGB888` `.gif`) /// and opportunistic `HallOfFameCard` / `RetroAchievementsCard` views. /// /// Shares [`crate::core::dmd_stream::ShowcaseStreamPlayer`] 1:1 with [`MediaShowcaseRunner`] and @@ -1648,6 +1698,10 @@ pub struct InGameShowcaseEngine { pending_draw: bool, finished: bool, player: crate::core::dmd_stream::ShowcaseStreamPlayer, + gif_frame_idx: usize, + gif_frame_elapsed: Duration, + gif_last_drawn_idx: Option, + gif_last_tick: Option, sub_stage: InGameSubStage, stage_started_at: Option, stage_paused_at: Option, @@ -1669,6 +1723,10 @@ impl InGameShowcaseEngine { pending_draw: false, finished: false, player: crate::core::dmd_stream::ShowcaseStreamPlayer::new(), + gif_frame_idx: 0, + gif_frame_elapsed: Duration::ZERO, + gif_last_drawn_idx: None, + gif_last_tick: None, sub_stage: InGameSubStage::ShowcaseStream, stage_started_at: None, stage_paused_at: None, @@ -1679,6 +1737,14 @@ impl InGameShowcaseEngine { } } + #[inline] + fn reset_gif_cursor(&mut self, now: Instant) { + self.gif_frame_idx = 0; + self.gif_frame_elapsed = Duration::ZERO; + self.gif_last_drawn_idx = None; + self.gif_last_tick = Some(now); + } + fn select_initial_stage( meta: Option<&Arc>, has_stream: bool, @@ -1726,6 +1792,7 @@ impl Engine for InGameShowcaseEngine { self.stage_paused_ms = 0; self.stage_elapsed_ms = 0; self.last_card_tick = u32::MAX; + self.reset_gif_cursor(now); self.player.start(now); } @@ -1735,6 +1802,7 @@ impl Engine for InGameShowcaseEngine { if self.stage_paused_at.is_none() { self.stage_paused_at = Some(now); } + self.gif_last_tick = None; self.player.pause(now); } @@ -1745,6 +1813,8 @@ impl Engine for InGameShowcaseEngine { .stage_paused_ms .saturating_add(now.duration_since(p).as_millis() as u64); } + self.gif_last_tick = Some(now); + self.gif_last_drawn_idx = None; self.player.resume(now); self.pending_draw = !self.finished; } @@ -1761,12 +1831,17 @@ impl Engine for InGameShowcaseEngine { self.stage_paused_ms = 0; self.stage_elapsed_ms = 0; self.last_card_tick = u32::MAX; + self.gif_frame_idx = 0; + self.gif_frame_elapsed = Duration::ZERO; + self.gif_last_drawn_idx = None; + self.gif_last_tick = None; self.player.reset(); } fn on_display_geometry_changed(&mut self, geometry: &DisplayGeometry) { self.surface_width = geometry.width(); self.surface_height = geometry.height(); + self.gif_last_drawn_idx = None; self.player.invalidate_drawn_frame(); if !self.finished && self.stage_paused_at.is_none() { self.pending_draw = true; @@ -1787,10 +1862,7 @@ impl Engine for InGameShowcaseEngine { } let snap = context.config.producer_snapshot.load(); - let ig_opt = snap - .ingame_showcase - .as_ref() - .filter(|ig| !ig.stream.is_empty()); + let ig_opt = snap.ingame_showcase.as_ref().filter(|ig| !ig.is_empty()); let meta_opt = snap.sync_meta.as_ref().filter(|m| m.has_any_card()); if ig_opt.is_none() && meta_opt.is_none() { @@ -1817,6 +1889,7 @@ impl Engine for InGameShowcaseEngine { self.stage_paused_ms = 0; self.stage_elapsed_ms = 0; self.last_card_tick = u32::MAX; + self.reset_gif_cursor(now); if prev_token != 0 || !self.player.is_started() { self.player.start(now); } @@ -1849,6 +1922,7 @@ impl Engine for InGameShowcaseEngine { return; } else if ig_opt.is_some() { self.sub_stage = InGameSubStage::ShowcaseStream; + self.reset_gif_cursor(now); self.player.start(now); } else { self.finished = true; @@ -1875,6 +1949,7 @@ impl Engine for InGameShowcaseEngine { if !has_ra || elapsed >= card_dur_ms { if ig_opt.is_some() { self.sub_stage = InGameSubStage::ShowcaseStream; + self.reset_gif_cursor(now); self.player.start(now); } else { self.finished = true; @@ -1903,12 +1978,67 @@ impl Engine for InGameShowcaseEngine { }; self.has_stream = true; - self.stream_width = ig.stream.width; - self.stream_height = ig.stream.height; + let (dim_w, dim_h) = ig.dimensions(); + self.stream_width = dim_w; + self.stream_height = dim_h; let has_cards = meta_opt.is_some(); let loop_playback = matches!(ig.cycle_mode, InGameCycleMode::Loop) && !has_cards; - let stream_done = self.player.advance(&ig.stream, now, loop_playback, None); + + if let Some(ref gif_data) = ig.offline_gif { + let frames = gif_data.frames.as_slice(); + if frames.is_empty() { + self.finished = true; + self.pending_draw = false; + return; + } + if let Some(prev) = self.gif_last_tick { + self.gif_frame_elapsed = self + .gif_frame_elapsed + .saturating_add(now.duration_since(prev)); + } + self.gif_last_tick = Some(now); + + let mut gif_done = false; + while !frames.is_empty() && self.gif_frame_elapsed >= frames[self.gif_frame_idx].1 { + let delay = frames[self.gif_frame_idx].1; + self.gif_frame_elapsed = self.gif_frame_elapsed.saturating_sub(delay); + self.gif_frame_idx += 1; + if self.gif_frame_idx >= frames.len() { + if loop_playback { + self.gif_frame_idx = 0; + } else { + self.gif_frame_idx = frames.len() - 1; + gif_done = true; + break; + } + } + } + + if gif_done && matches!(ig.cycle_mode, InGameCycleMode::Loop) && has_cards { + if let Some(first_stage) = Self::select_initial_stage(meta_opt, true) { + self.sub_stage = first_stage; + self.stage_started_at = Some(now); + self.stage_paused_ms = 0; + self.stage_elapsed_ms = 0; + self.last_card_tick = u32::MAX; + self.pending_draw = true; + return; + } + } + + self.finished = gif_done; + self.pending_draw = !gif_done && self.gif_last_drawn_idx != Some(self.gif_frame_idx); + return; + } + + let Some(ref stream) = ig.stream else { + self.finished = true; + self.pending_draw = false; + return; + }; + + let stream_done = self.player.advance(stream, now, loop_playback, None); if stream_done && matches!(ig.cycle_mode, InGameCycleMode::Loop) && has_cards { if let Some(first_stage) = Self::select_initial_stage(meta_opt, true) { self.sub_stage = first_stage; @@ -1921,7 +2051,7 @@ impl Engine for InGameShowcaseEngine { } } self.finished = stream_done; - self.pending_draw = self.player.has_new_frame(&ig.stream); + self.pending_draw = self.player.has_new_frame(stream); } fn render(&mut self, context: &mut EngineContext) { @@ -1951,8 +2081,16 @@ impl Engine for InGameShowcaseEngine { } InGameSubStage::ShowcaseStream => { if let Some(ref ig) = snap.ingame_showcase { - self.player - .render_to_surface(&ig.stream, &mut *context.surface); + if let Some(ref gif_data) = ig.offline_gif { + SyncOfflineGifRenderer::render( + &mut *context.surface, + gif_data.frames.as_slice(), + self.gif_frame_idx, + ); + self.gif_last_drawn_idx = Some(self.gif_frame_idx); + } else if let Some(ref stream) = ig.stream { + self.player.render_to_surface(stream, &mut *context.surface); + } } } } @@ -2273,11 +2411,11 @@ mod tests { let config = Config::new(tmp_dir.join("config.json")); let stream = build_sample_dmdz_v2_stream(30); - config.set_ingame_showcase(Some(InGameShowcasePayload { - session_token: 42, - stream: Arc::clone(&stream), - cycle_mode: InGameCycleMode::Once, - })); + config.set_ingame_showcase(Some(InGameShowcasePayload::from_stream( + 42, + Arc::clone(&stream), + InGameCycleMode::Once, + ))); let mut engine = InGameShowcaseEngine::new(); assert!(!engine.allows_overlay()); @@ -2330,11 +2468,11 @@ mod tests { } // Switch to `Loop` mode on a new session token -> wraps around cleanly without finishing - config.set_ingame_showcase(Some(InGameShowcasePayload { - session_token: 43, + config.set_ingame_showcase(Some(InGameShowcasePayload::from_stream( + 43, stream, - cycle_mode: InGameCycleMode::Loop, - })); + InGameCycleMode::Loop, + ))); { let mut ctx = EngineContext { surface: &mut surface, @@ -2351,6 +2489,141 @@ mod tests { let _ = std::fs::remove_dir_all(&tmp_dir); } + #[test] + fn test_offline_showcase_rgb888_gif_sync_without_remote_server_and_cycle_modes() { + use image::codecs::gif::GifEncoder; + use image::{Delay, Frame, Rgba, RgbaImage}; + + let tmp_dir = std::env::temp_dir().join(format!( + "arcadematrix_offline_rgb888_gif_test_{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + let marquee_dir = tmp_dir.join("marquees"); + let showcase_snes_dir = tmp_dir.join("showcase").join("snes"); + let pixelcade_snes_dir = tmp_dir.join("pixelcade").join("snes"); + std::fs::create_dir_all(&marquee_dir).unwrap(); + std::fs::create_dir_all(&showcase_snes_dir).unwrap(); + std::fs::create_dir_all(&pixelcade_snes_dir).unwrap(); + + // 1. Write companion non-interlaced marquee PNG (`pixelcade/snes/smw.png`) + let mut mq_img = image::RgbImage::new(4, 2); + mq_img.put_pixel(0, 0, image::Rgb([12, 234, 56])); + mq_img.save(pixelcade_snes_dir.join("smw.png")).unwrap(); + + // 2. Write 2-frame pure 24-bit RGB888 animated GIF (`showcase/snes/smw.gif`) + // using non-RGB565-quantized channels `(123, 45, 211)` and `(19, 207, 131)`! + let gif_path = showcase_snes_dir.join("smw.gif"); + { + let f_out = std::fs::File::create(&gif_path).unwrap(); + let mut enc = GifEncoder::new(f_out); + let f0_img = RgbaImage::from_pixel(4, 2, Rgba([123, 45, 211, 255])); + let f1_img = RgbaImage::from_pixel(4, 2, Rgba([19, 207, 131, 255])); + enc.encode_frame(Frame::from_parts( + f0_img, + 0, + 0, + Delay::from_numer_denom_ms(30, 1), + )) + .unwrap(); + enc.encode_frame(Frame::from_parts( + f1_img, + 0, + 0, + Delay::from_numer_denom_ms(30, 1), + )) + .unwrap(); + } + + let config = Arc::new(Config::new(tmp_dir.join("config.json"))); + { + let mut s = config.settings.write(); + s.matrix.width = 4; + s.matrix.height = 2; + s.matrix.chain_length = 1; + s.matrix.parallel = 1; + s.showcase.enabled = false; // Remote Showcase server explicitly DISABLED! + s.showcase.server_url.clear(); + s.mqtt.ingame_showcase_enabled = true; + s.mqtt.ingame_cycle_mode = "once".to_string(); + } + let dmd_cache = Arc::new(crate::core::dmd_cache::DmdCache::new(&marquee_dir)); + + // Verify companion `pixelcade/snes/smw.png` & offline `showcase/snes/smw.gif` both resolve + assert!(dmd_cache.get_cached_path("snes", "./smw.sfc").is_some()); + assert_eq!( + dmd_cache.resolve_offline_showcase_gif_path("snes", "./smw.sfc", false), + Some(gif_path.clone()) + ); + + let req_id = MQTT_REQUEST_ID.fetch_add(1, Ordering::AcqRel) + 1; + spawn_ingame_showcase_request( + Arc::clone(&config), + Arc::clone(&dmd_cache), + req_id, + "snes".to_string(), + "./smw.sfc".to_string(), + "Super Mario World".to_string(), + 10, + ); + + // Wait briefly for off-thread GIF decode (`<= 250 ms`, 0 network calls) + let wait_t0 = Instant::now(); + while config.producer_snapshot.load().ingame_showcase.is_none() + && wait_t0.elapsed() < Duration::from_millis(500) + { + std::thread::sleep(Duration::from_millis(10)); + } + let published = config + .producer_snapshot + .load() + .ingame_showcase + .clone() + .expect("offline RGB888 GIF payload published without remote server"); + assert!(published.offline_gif.is_some()); + + // Render Frame 0 & Frame 1 on `InGameShowcaseEngine` -> exact 24-bit RGB888 channels preserved! + let mut engine = InGameShowcaseEngine::new(); + let mut surface = MockSurface::new(4, 2); + engine.activate(); + { + let mut ctx = EngineContext { + surface: &mut surface, + config: &config, + }; + engine.update(&mut ctx); + assert!(engine.has_new_frame()); + engine.render(&mut ctx); + } + assert_eq!(surface.canvas.get_pixel(0, 0).0, [123, 45, 211]); + + std::thread::sleep(Duration::from_millis(38)); + { + let mut ctx = EngineContext { + surface: &mut surface, + config: &config, + }; + engine.update(&mut ctx); + assert!(!engine.is_finished()); + assert!(engine.has_new_frame()); + engine.render(&mut ctx); + } + assert_eq!(surface.canvas.get_pixel(0, 0).0, [19, 207, 131]); + + std::thread::sleep(Duration::from_millis(38)); + { + let mut ctx = EngineContext { + surface: &mut surface, + config: &config, + }; + engine.update(&mut ctx); + assert!(engine.is_finished()); + } + + engine.deactivate(); + let _ = std::fs::remove_dir_all(&tmp_dir); + } + #[test] fn test_registry_recycle_preserves_frontend_sync_ingame_engine() { let tmp_dir = std::env::temp_dir().join(format!( @@ -2454,4 +2727,105 @@ mod tests { let _ = std::fs::remove_dir_all(&tmp_dir); } + + #[test] + fn test_handle_frontend_sync_payload_e2e_offline_tate_preemption_and_stopped() { + let tmp_dir = std::env::temp_dir().join(format!( + "arcadematrix_e2e_mqtt_offline_tate_{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&tmp_dir); + let marquee_dir = tmp_dir.join("marquees"); + let tate_showcase_dir = tmp_dir.join("showcase_tate").join("neogeo"); + let px_dir = tmp_dir.join("pixelcade").join("neogeo"); + std::fs::create_dir_all(&marquee_dir).unwrap(); + std::fs::create_dir_all(&tate_showcase_dir).unwrap(); + std::fs::create_dir_all(&px_dir).unwrap(); + + // Write valid 2-frame RGB888 TATE GIF (`showcase_tate/neogeo/mslugx.gif`) + companion marquee `.png` + { + use image::{Delay, Frame, RgbaImage}; + let gif_file = std::fs::File::create(tate_showcase_dir.join("mslugx.gif")).unwrap(); + let mut enc = image::codecs::gif::GifEncoder::new(gif_file); + enc.set_repeat(image::codecs::gif::Repeat::Infinite) + .unwrap(); + let f0 = Frame::from_parts( + RgbaImage::from_pixel(4, 8, image::Rgba([250, 90, 20, 255])), + 0, + 0, + Delay::from_numer_denom_ms(40, 1), + ); + let f1 = Frame::from_parts( + RgbaImage::from_pixel(4, 8, image::Rgba([30, 220, 140, 255])), + 0, + 0, + Delay::from_numer_denom_ms(40, 1), + ); + enc.encode_frames(vec![f0, f1].into_iter()).unwrap(); + + let marquee_img = image::RgbImage::from_pixel(4, 8, image::Rgb([15, 80, 210])); + marquee_img.save(px_dir.join("mslugx.png")).unwrap(); + } + + let config = Arc::new(Config::new(tmp_dir.join("config.json"))); + { + let mut s = config.settings.write(); + // TATE 64x128 (`rotation = 90` on 128x64 panel -> effective width=64, height=128) + s.matrix.width = 128; + s.matrix.height = 64; + s.matrix.chain_length = 1; + s.matrix.parallel = 1; + s.matrix.rotation = 90; + s.mqtt.ingame_showcase_enabled = true; + s.mqtt.ingame_cycle_mode = "once".to_string(); + s.mqtt.sync_celebrate_events = true; + // Showcase server disabled -> proves 100% autonomous local offline resolution! + s.showcase.enabled = false; + s.showcase.server_url.clear(); + } + let dmd_cache = Arc::new(crate::core::dmd_cache::DmdCache::new(&marquee_dir)); + assert!(dmd_cache + .resolve_offline_showcase_gif_path("neogeo", "mslugx.zip", true) + .is_some()); + + // 1. Virtual collection `favorites` + `/recalbox/share/roms/neogeo/mslugx.zip` in `playing` state: + // must immediately display companion marquee `pixelcade/neogeo/mslugx.png` AND spawn TATE offline GIF! + handle_frontend_sync_payload( + &config, + &dmd_cache, + r#"{"status":"playing","system":"favorites","game":"mslugx.zip","title":"Metal Slug X","rom_path":"/recalbox/share/roms/neogeo/mslugx.zip"}"#, + ); + assert_eq!( + config.producer_snapshot.load().forced_mode, + ForcedEngineMode::Marquee + ); + assert!(e2e_telemetry() + .lock() + .active_marquee_path + .contains("pixelcade")); + + // 2. Inject `sync_meta` & `celebrate` while in-game -> both atomic snapshots populated + handle_frontend_sync_payload( + &config, + &dmd_cache, + r#"{"status":"sync_meta","system":"neogeo","game":"mslugx","hiscores":[{"rank":1,"tag":"SNK","score":"1,500,000"}]}"#, + ); + assert!(config.producer_snapshot.load().sync_meta.is_some()); + + handle_frontend_sync_payload( + &config, + &dmd_cache, + r#"{"status":"celebrate","kind":"highscore","system":"neogeo","game":"mslugx","rank":1,"tag":"SNK","score":"2,000,000"}"#, + ); + assert!(config.producer_snapshot.load().sync_celebration.is_some()); + + // 3. `stopped` event immediately cancels in-game Showcase & SyncMeta while keeping last marquee displayed! + handle_frontend_sync_payload(&config, &dmd_cache, r#"{"status":"stopped"}"#); + let snap_after_stop = config.producer_snapshot.load(); + assert!(snap_after_stop.ingame_showcase.is_none()); + assert!(snap_after_stop.sync_meta.is_none()); + assert_eq!(snap_after_stop.forced_mode, ForcedEngineMode::Marquee); + + let _ = std::fs::remove_dir_all(&tmp_dir); + } } diff --git a/src/engines/gif.rs b/src/engines/gif.rs index a31f1f38..3f752c22 100644 --- a/src/engines/gif.rs +++ b/src/engines/gif.rs @@ -83,7 +83,7 @@ impl GifEngine { } } - fn decode_gif_frames( + pub fn decode_gif_frames( path: &Path, target_width: u32, target_height: u32, diff --git a/src/engines/renderers/sync_cards.rs b/src/engines/renderers/sync_cards.rs index ac6ac0b8..bf0a365d 100644 --- a/src/engines/renderers/sync_cards.rs +++ b/src/engines/renderers/sync_cards.rs @@ -973,3 +973,19 @@ impl SyncCelebrationRenderer { } } } + +/// Pure zero-allocation renderer for pre-decoded 24-bit `RGB888` Offline In-Game Showcase `.gif` frames (ADR-0004). +pub struct SyncOfflineGifRenderer; + +impl SyncOfflineGifRenderer { + #[inline] + pub fn render( + surface: &mut dyn IDrawingSurface, + frames: &[(image::RgbImage, std::time::Duration)], + frame_index: usize, + ) { + if let Some((ref img, _)) = frames.get(frame_index) { + surface.draw_image(img, 0, 0); + } + } +} diff --git a/tests/test_v16_final_locked.rs b/tests/test_v16_final_locked.rs index 8237f7f5..a830e8f1 100644 --- a/tests/test_v16_final_locked.rs +++ b/tests/test_v16_final_locked.rs @@ -1569,3 +1569,98 @@ fn test_frontend_sync_cards_and_ota_telemetry_helpers() { assert_eq!(cel.score_or_pts_str(), "+25 PTS"); assert!(cel.hardcore); } + +#[test] +fn test_ingame_offline_rgb888_gif_10000_frames_zero_allocation_proof() { + use arcadematrix::core::types::{InGameCycleMode, InGameShowcasePayload}; + use std::sync::Arc; + use std::time::Duration; + + let mut arbiter = DisplayArbiter::new(); + let mut runtime = DisplayRuntime::new(); + let mut engine_runtime = EngineRuntime::new(); + let mut matrix = MockSurface::new(128, 32); + let temp_dir = tempfile::tempdir().expect("failed to create temp dir"); + let temp_cfg_path = temp_dir.path().join("config.json"); + let _ = std::fs::copy("config.json", &temp_cfg_path); + let config = arcadematrix::core::config::Config::new(&temp_cfg_path); + { + let mut s = config.settings.write(); + s.matrix.width = 128; + s.matrix.height = 32; + s.matrix.chain_length = 1; + s.matrix.parallel = 1; + s.mqtt.ingame_showcase_enabled = true; + s.mqtt.ingame_cycle_mode = "loop".to_string(); + } + + // Build a pre-decoded 24-bit RGB888 offline GIF payload on the cold path + let f0 = image::RgbImage::from_fn(128, 32, |x, y| { + image::Rgb([(x as u8).wrapping_mul(2), (y as u8).wrapping_mul(7), 180]) + }); + let f1 = image::RgbImage::from_fn(128, 32, |x, y| { + image::Rgb([40, (x as u8).wrapping_add(11), (y as u8).wrapping_mul(5)]) + }); + let frames = Arc::new(vec![ + (f0, Duration::from_millis(16)), + (f1, Duration::from_millis(16)), + ]); + config.set_ingame_showcase(Some(InGameShowcasePayload::from_offline_gif( + 101, + frames, + 128, + 32, + InGameCycleMode::Loop, + ))); + + let mut ctx = EngineContext { + surface: &mut matrix, + config: &config, + }; + let empty_cfg = HashMap::new(); + let h_ingame = engine_runtime.register_instance_handle("__ingame_showcase", "frontend_sync"); + assert!(engine_runtime.init_instance(h_ingame, &mut ctx, &empty_cfg)); + + arbiter.submit_request(DisplayRequest::new( + DisplaySourceId::InGameShowcase, + 101, + h_ingame, + 45, + RequestLifecycle::Persistent, + true, + 0, + )); + + // Warmup cycle to enter steady-state offline RGB888 GIF playback + let d0 = arbiter.evaluate(Instant::now()); + let _ = runtime.transition_session(d0, &arbiter, &mut engine_runtime); + runtime.update(&mut engine_runtime, &mut ctx); + runtime.render(&mut engine_runtime, &mut ctx); + + // Arm TrackingAllocator and execute 10,000 H-Core frames — MUST allocate strictly 0 bytes! + THREAD_ALLOC_COUNT.with(|c| c.set(0)); + THREAD_DEALLOC_COUNT.with(|c| c.set(0)); + THREAD_TRACKING.with(|t| t.set(true)); + + for _ in 0..10_000 { + let now = Instant::now(); + let dec = arbiter.evaluate(now); + let _ = runtime.transition_session(dec, &arbiter, &mut engine_runtime); + runtime.update(&mut engine_runtime, &mut ctx); + runtime.render(&mut engine_runtime, &mut ctx); + } + + THREAD_TRACKING.with(|t| t.set(false)); + let allocs = THREAD_ALLOC_COUNT.with(|c| c.get()); + let deallocs = THREAD_DEALLOC_COUNT.with(|c| c.get()); + assert_eq!( + allocs, 0, + "Offline RGB888 GIF H-Core hot-path performed {} heap allocations across 10,000 frames!", + allocs + ); + assert_eq!( + deallocs, 0, + "Offline RGB888 GIF H-Core hot-path performed {} heap deallocations across 10,000 frames!", + deallocs + ); +} From 5f131e9895c6e5baf12978c463772039146ea52d Mon Sep 17 00:00:00 2001 From: red77290 <23342613+red77290@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:19:35 +0000 Subject: [PATCH 2/4] feat(matrix): add integer ui_scale for giant LED walls and pixel_mapper support - Add matrix.ui_scale ('auto', '1', '2', '3', '4') and zero-allocation ScaledDrawingSurface Nearest-Neighbor wrapper around IDrawingSurface preserving DirtyBounds and CanvasView. - Guarantee strict 1x zero-impact behavior in 'auto' mode for 64x32, 32x64, 64x64, 128x32, 32x128, 128x64, 64x128, 256x64, and 64x256, only activating 2x/3x/4x when min(w,h) >= 128 and max(w,h) >= 192 (e.g. 256x192, 512x384). - Preserve native 1x full-screen rendering via surface.unscaled() for gifs, DMD Media Showcase Phase 2 LiveStream video/panoramas, and FrontendSync ShowcaseStream while upscaling Phase 1 Intro Cards. - Add matrix.pixel_mapper (e.g. 'U-mapper', 'V-mapper') forwarded to hzeller LedMatrixOptions::set_pixel_mapper_config and mirrored in effective_physical_dimensions(). - Update WebUI Hardware tab, OpenAPI schema, EN/FR/ES i18n & docs, and unit + H-Core 10,000-frame zero-allocation tests. --- api/www/index.html | 24 ++ api/www/js/app.js | 5 + api/www/js/i18n.js | 30 ++ config.json | 4 +- docs/ARCHITECTURE.md | 14 + docs/ARCHITECTURE_ES.md | 14 + docs/ARCHITECTURE_FR.md | 14 + docs/CONFIGURATION.md | 2 + docs/CONFIGURATION_ES.md | 2 + docs/CONFIGURATION_FR.md | 2 + docs/DEVELOPER.md | 7 + docs/DEVELOPER_ES.md | 7 + docs/DEVELOPER_FR.md | 7 + docs/openapi.yaml | 28 ++ scripts/validate_docs.py | 11 +- src/api/server.rs | 54 +-- src/app.rs | 48 ++- src/core/config.rs | 216 ++++++++++++ src/core/matrix.rs | 349 ++++++++++++++++++- src/core/orientation.rs | 54 ++- src/core/types.rs | 43 ++- src/engines/anime_showcase.rs | 8 +- src/engines/frontend_sync.rs | 50 +-- src/engines/gif.rs | 18 +- src/engines/movie_showcase.rs | 8 +- src/engines/renderers/media_showcase.rs | 103 ++++-- src/engines/renderers/weather_page.rs | 3 + src/engines/retro_games.rs | 8 +- src/engines/series_showcase.rs | 8 +- tests/test_matrix.rs | 434 ++++++++++++++++++++++++ tests/test_v16_final_locked.rs | 68 ++++ 31 files changed, 1520 insertions(+), 123 deletions(-) diff --git a/api/www/index.html b/api/www/index.html index e85dad51..69ea21ae 100644 --- a/api/www/index.html +++ b/api/www/index.html @@ -512,6 +512,30 @@

Matrix Hardware Configuration

+
+
+ + + + + + + + + + +
+
+ + +
+
diff --git a/api/www/js/app.js b/api/www/js/app.js index ec5caf37..f3fb2079 100644 --- a/api/www/js/app.js +++ b/api/www/js/app.js @@ -1346,6 +1346,9 @@ async function initSettings() { setVal('hw-pwm-lsb', matrix.pwm_lsb_nanoseconds ?? 130); setVal('hw-limit-refresh', matrix.limit_refresh_rate_hz ?? 0); setChk('hw-disable-pulsing', matrix.disable_hardware_pulsing ?? false); + setVal('hw-pixel-mapper', matrix.pixel_mapper || ''); + const normUiScale = String(matrix.ui_scale ?? 'auto').trim().toLowerCase().replace(/x$/, ''); + setVal('hw-ui-scale', ['1', '2', '3', '4'].includes(normUiScale) ? normUiScale : 'auto'); setVal('hw-render-pipeline', matrix.render_pipeline || 'canvas_single'); // MQTT (nested mqtt.*) @@ -1520,6 +1523,7 @@ async function initSettings() { parallel: numOr('hw-parallel', 1), driver_chip: document.getElementById('hw-driver-chip')?.value || 'SHIFTREG', mapping: document.getElementById('hw-mapping')?.value || 'regular', + pixel_mapper: (document.getElementById('hw-pixel-mapper')?.value || '').trim(), rgb_sequence: document.getElementById('hw-rgb')?.value || 'RGB', row_address_mode: numOr('hw-row-addr-type', 0), multiplexing: numOr('hw-multiplexing', 0), @@ -1529,6 +1533,7 @@ async function initSettings() { limit_refresh_rate_hz: numOr('hw-limit-refresh', 0), disable_hardware_pulsing: document.getElementById('hw-disable-pulsing')?.checked || false, render_pipeline: document.getElementById('hw-render-pipeline')?.value || 'canvas_single', + ui_scale: document.getElementById('hw-ui-scale')?.value || 'auto', }; try { diff --git a/api/www/js/i18n.js b/api/www/js/i18n.js index c05c9783..3968765f 100644 --- a/api/www/js/i18n.js +++ b/api/www/js/i18n.js @@ -406,6 +406,16 @@ export const translations = { hw_pipeline_canvas_double: "🚀 Canvas + Double Buffer (Max Smoothness)", hw_pipeline_direct_double: "⚙️ Direct Double Buffer (No Canvas)", hw_pipeline_direct_single: "🪶 Direct Single Buffer (Ultra-Low RAM)", + hw_pixel_mapper: "Pixel Mapper (Multi-Panel)", + ph_hw_pixel_mapper: "None (e.g. U-mapper)", + tt_hw_pixel_mapper: "Optional hzeller pixel-mapper chain for folded multi-panel walls (e.g. 'U-mapper', 'V-mapper', 'V-mapper:Z', 'U-mapper;Rotate:180'). Leave empty for a linear chain.", + hw_ui_scale: "UI Integer Scale (Giant Walls)", + tt_hw_ui_scale: "Auto keeps 1x on all standard YOKO/TATE panels (64x32 to 256x64) and applies 2x/3x/4x Nearest-Neighbor upscaling on giant walls (256x192, 512x384), while keeping GIFs and Showcase videos/panoramas at native 1x.", + hw_ui_scale_auto: "✨ Auto (1x up to 256x64, 2x–4x on Giant Walls)", + hw_ui_scale_1x: "1x — Native Pixel-Perfect (No Upscaling)", + hw_ui_scale_2x: "2x — Nearest-Neighbor (256x192 → 128x96)", + hw_ui_scale_3x: "3x — Nearest-Neighbor (384x288 → 128x96)", + hw_ui_scale_4x: "4x — Nearest-Neighbor (512x384 → 128x96)", hw_trans_vortex: "✨ Particle Vortex", hw_trans_glitch: "⚡ Cyberpunk Glitch", hw_trans_slide: "💫 Smooth Slide", @@ -1381,6 +1391,16 @@ export const translations = { hw_pipeline_canvas_double: "🚀 Canevas + Double Buffer (Fluidité maximale)", hw_pipeline_direct_double: "⚙️ Double Buffer Direct (Sans canevas)", hw_pipeline_direct_single: "🪶 Simple Buffer Direct (RAM ultra-basse)", + hw_pixel_mapper: "Pixel Mapper (Multi-Panneaux)", + ph_hw_pixel_mapper: "Aucun (ex. U-mapper)", + tt_hw_pixel_mapper: "Chaîne pixel-mapper hzeller optionnelle pour murs multi-panneaux repliés (ex. 'U-mapper', 'V-mapper', 'V-mapper:Z', 'U-mapper;Rotate:180'). Laisser vide pour une chaîne linéaire.", + hw_ui_scale: "Échelle Entière UI (Murs Géants)", + tt_hw_ui_scale: "Auto conserve 1x sur toutes les dalles YOKO/TATE standard (64x32 à 256x64) et active l'upscaling entier Nearest-Neighbor 2x/3x/4x sur les très grands murs (256x192, 512x384), tout en gardant les GIFs et vidéos/panoramas Showcase en 1x natif.", + hw_ui_scale_auto: "✨ Auto (1x jusqu'à 256x64, 2x–4x sur Murs Géants)", + hw_ui_scale_1x: "1x — Natif Pixel-Perfect (Sans Upscaling)", + hw_ui_scale_2x: "2x — Nearest-Neighbor (256x192 → 128x96)", + hw_ui_scale_3x: "3x — Nearest-Neighbor (384x288 → 128x96)", + hw_ui_scale_4x: "4x — Nearest-Neighbor (512x384 → 128x96)", hw_trans_vortex: "✨ Vortex de Particules", hw_trans_glitch: "⚡ Glitch Cyberpunk", hw_trans_slide: "💫 Glissement Fluide", @@ -2356,6 +2376,16 @@ export const translations = { hw_pipeline_canvas_double: "🚀 Lienzo + Doble Buffer (Máxima fluidez)", hw_pipeline_direct_double: "⚙️ Doble Buffer Directo (Sin lienzo)", hw_pipeline_direct_single: "🪶 Buffer Simple Directo (RAM ultra-baja)", + hw_pixel_mapper: "Pixel Mapper (Multi-Panel)", + ph_hw_pixel_mapper: "Ninguno (ej. U-mapper)", + tt_hw_pixel_mapper: "Cadena opcional pixel-mapper de hzeller para muros multipanel plegados (ej. 'U-mapper', 'V-mapper', 'V-mapper:Z', 'U-mapper;Rotate:180'). Dejar vacío para cadena lineal.", + hw_ui_scale: "Escala Entera UI (Muros Gigantes)", + tt_hw_ui_scale: "Auto mantiene 1x en todos los paneles YOKO/TATE estándar (64x32 a 256x64) y aplica escalado entero Nearest-Neighbor 2x/3x/4x en muros gigantes (256x192, 512x384), manteniendo los GIFs y vídeos/panoramas de Showcase en 1x nativo.", + hw_ui_scale_auto: "✨ Auto (1x hasta 256x64, 2x–4x en Muros Gigantes)", + hw_ui_scale_1x: "1x — Nativo Pixel-Perfect (Sin Escalado)", + hw_ui_scale_2x: "2x — Nearest-Neighbor (256x192 → 128x96)", + hw_ui_scale_3x: "3x — Nearest-Neighbor (384x288 → 128x96)", + hw_ui_scale_4x: "4x — Nearest-Neighbor (512x384 → 128x96)", hw_trans_vortex: "✨ Vórtice de Partículas", hw_trans_glitch: "⚡ Glitch Cyberpunk", hw_trans_slide: "💫 Deslizamiento Suave", diff --git a/config.json b/config.json index fd9f5142..d0ffd048 100644 --- a/config.json +++ b/config.json @@ -22,12 +22,14 @@ "pwm_lsb_nanoseconds": 130, "disable_hardware_pulsing": false, "mapping": "regular", + "pixel_mapper": "", "rotation": 0, "transition_effect": "vortex", "transition_duration_ms": 400, "slot_transition": "none", "slot_transition_duration_ms": 500, - "render_pipeline": "canvas_single" + "render_pipeline": "canvas_single", + "ui_scale": "auto" }, "wifi": { "ssid": "", diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 734e32b3..1c3bb8a6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -653,9 +653,14 @@ pub trait IDrawingSurface: Send + Sync { fn height(&self) -> u32; fn physical_width(&self) -> u32; fn physical_height(&self) -> u32; + fn native_width(&self) -> u32 { self.width() } + fn native_height(&self) -> u32 { self.height() } + fn ui_scale(&self) -> u32 { 1 } + fn set_ui_scale(&mut self, _scale: u32) {} fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); @@ -664,6 +669,7 @@ pub trait IDrawingSurface: Send + Sync { fn draw_image(&mut self, img: &RgbImage, offset_x: i32, offset_y: i32); fn blit565(&mut self, src: &[u16], x: i32, y: i32, w: u32, h: u32, stride_pixels: Option); fn acquire_canvas(&mut self) -> Option>; + fn unscaled(&mut self) -> &mut dyn IDrawingSurface; } ``` @@ -687,6 +693,14 @@ Under `canvas_single`, the `DirtyBounds` tracker monitors which scanlines have a 2. `present()` completes in $O(1)$ without calling the C FFI or writing to the physical LED matrix memory. 3. The Broadcom memory bus and CPU remain completely free for Wi-Fi, MQTT, and HTTP traffic. +### 13.3 Multi-Panel Pixel Mapping (`pixel_mapper`) & Integer UI Upscaling (`ScaledDrawingSurface`) + +- **Hardware Pixel Mapper (`matrix.pixel_mapper`)**: Forwarded to hzeller `LedMatrixOptions::set_pixel_mapper_config` (e.g. `"U-mapper"`, `"V-mapper"`, `"U-mapper;Rotate:180"`), allowing multi-panel HUB75 chains to fold into tall multi-row physical walls (such as `256×192` or `512×384`). Off-hardware surfaces (`MockSurface`, E2E inspection, and API layout previews) compute identical folded physical dimensions via `MatrixConfig::effective_physical_dimensions()`. +- **Zero-Allocation `ScaledDrawingSurface` (`matrix.ui_scale`)**: Wraps the hardware or mock `IDrawingSurface` transparently with zero heap allocations on the H-Core hot path: + - In `"auto"` mode (default), `UiScale::resolve` returns **`1x`** strictly across all standard and TATE resolutions (`64×32`, `32×64`, `64×64`, `128×32`, `32×128`, `128×64`, `64×128`, `256×64`, `64×256`), acting as a pure 1:1 passthrough (preserving `acquire_canvas()` and `DirtyBounds` untouched). + - Only when `min(width, height) >= 128` and `max(width, height) >= 192` does `"auto"` engage `2x`/`3x`/`4x` Nearest-Neighbor integer block expansion (`256×192` → `2x` `128×96`, `512×384` → `4x` `128×96`), expanding each logical pixel into an exact `N×N` sharp LED block while propagating exact scanline `DirtyBounds` to the inner surface. + - Full-screen media streams (`gifs`, plus `DMD Media Showcase` Phase 2 `LiveStream` video/panoramas and `FrontendSync` `ShowcaseStream`) bypass UI scaling via `surface.unscaled()` (`native_width()` × `native_height()`), while UI engines and Showcase Phase 1 Intro Cards render crisply on the upscaled logical grid. + --- ## 14. Runtime Isolation & Threading Model diff --git a/docs/ARCHITECTURE_ES.md b/docs/ARCHITECTURE_ES.md index 16cf7e88..abbe3104 100644 --- a/docs/ARCHITECTURE_ES.md +++ b/docs/ARCHITECTURE_ES.md @@ -653,9 +653,14 @@ pub trait IDrawingSurface: Send + Sync { fn height(&self) -> u32; fn physical_width(&self) -> u32; fn physical_height(&self) -> u32; + fn native_width(&self) -> u32 { self.width() } + fn native_height(&self) -> u32 { self.height() } + fn ui_scale(&self) -> u32 { 1 } + fn set_ui_scale(&mut self, _scale: u32) {} fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); @@ -664,6 +669,7 @@ pub trait IDrawingSurface: Send + Sync { fn draw_image(&mut self, img: &RgbImage, offset_x: i32, offset_y: i32); fn blit565(&mut self, src: &[u16], x: i32, y: i32, w: u32, h: u32, stride_pixels: Option); fn acquire_canvas(&mut self) -> Option>; + fn unscaled(&mut self) -> &mut dyn IDrawingSurface; } ``` @@ -687,6 +693,14 @@ Bajo `canvas_single`, el rastreador `DirtyBounds` monitoriza qué líneas han si 2. `present()` se completa en $O(1)$ sin llamar a la FFI C ni escribir en la memoria física del panel LED. 3. El bus de memoria Broadcom y la CPU quedan completamente libres para el tráfico Wi-Fi, MQTT y HTTP. +### 13.3 Mapeo Multipanel (`pixel_mapper`) y Escalado Entero (`ScaledDrawingSurface`) + +- **Pixel Mapper de Hardware (`matrix.pixel_mapper`)**: Se envía a hzeller `LedMatrixOptions::set_pixel_mapper_config` (p. ej. `"U-mapper"`, `"V-mapper"`, `"U-mapper;Rotate:180"`), plegando largas cadenas HUB75 en grandes muros LED multifila (como `256×192` o `512×384`). Fuera de hardware (`MockSurface`, inspección E2E y vistas previas de API), `MatrixConfig::effective_physical_dimensions()` calcula exactamente las mismas dimensiones físicas plegadas. +- **Wrapper Cero-Asignación `ScaledDrawingSurface` (`matrix.ui_scale`)**: Envuelve de forma transparente la superficie física o simulada con **cero asignaciones dinámicas** en la ruta crítica H-Core: + - En modo `"auto"` (por defecto), `UiScale::resolve` permanece **estrictamente en `1x`** en todas las resoluciones estándar y TATE (`64×32`, `32×64`, `64×64`, `128×32`, `32×128`, `128×64`, `64×128`, `256×64`, `64×256`), actuando como passthrough 1:1 directo (`acquire_canvas()` y `DirtyBounds` intactos). + - Solo cuando `min(width, height) >= 128` y `max(width, height) >= 192`, `"auto"` activa un escalado entero Nearest-Neighbor `2x`/`3x`/`4x` (`256×192` → `2x` `128×96`, `512×384` → `4x` `128×96`), expandiendo cada píxel lógico en un bloque LED nítido `N×N` y propagando las filas `DirtyBounds` exactas a la superficie interna. + - Los flujos multimedia a pantalla completa (`gifs`, la Fase 2 `LiveStream` de vídeo/panoramas de `DMD Media Showcase` y `ShowcaseStream` de `FrontendSync`) omiten el escalado mediante `surface.unscaled()` (`native_width()` × `native_height()`), mientras que los motores UI y la Tarjeta de Intro Fase 1 de Showcase aprovechan la cuadrícula lógica escalada. + --- ## 14. Aislamiento del runtime y modelo de hilos diff --git a/docs/ARCHITECTURE_FR.md b/docs/ARCHITECTURE_FR.md index 87aac919..addd7b62 100644 --- a/docs/ARCHITECTURE_FR.md +++ b/docs/ARCHITECTURE_FR.md @@ -653,9 +653,14 @@ pub trait IDrawingSurface: Send + Sync { fn height(&self) -> u32; fn physical_width(&self) -> u32; fn physical_height(&self) -> u32; + fn native_width(&self) -> u32 { self.width() } + fn native_height(&self) -> u32 { self.height() } + fn ui_scale(&self) -> u32 { 1 } + fn set_ui_scale(&mut self, _scale: u32) {} fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); @@ -664,6 +669,7 @@ pub trait IDrawingSurface: Send + Sync { fn draw_image(&mut self, img: &RgbImage, offset_x: i32, offset_y: i32); fn blit565(&mut self, src: &[u16], x: i32, y: i32, w: u32, h: u32, stride_pixels: Option); fn acquire_canvas(&mut self) -> Option>; + fn unscaled(&mut self) -> &mut dyn IDrawingSurface; } ``` @@ -687,6 +693,14 @@ Sous `canvas_single`, le tracker `DirtyBounds` surveille quelles lignes ont effe 2. `present()` se termine en $O(1)$ sans appeler le C FFI ni écrire dans la mémoire physique du panneau LED. 3. Le bus mémoire Broadcom et le CPU restent totalement libres pour le trafic Wi-Fi, MQTT et HTTP. +### 13.3 Mapping Multi-Dalles (`pixel_mapper`) & Mise à l'Échelle Entière (`ScaledDrawingSurface`) + +- **Pixel Mapper Matériel (`matrix.pixel_mapper`)** : Transmis à hzeller `LedMatrixOptions::set_pixel_mapper_config` (ex. `"U-mapper"`, `"V-mapper"`, `"U-mapper;Rotate:180"`), permettant de replier de longues chaînes HUB75 en murs LED multi-rangées (comme `256×192` ou `512×384`). Hors matériel (`MockSurface`, inspection E2E et aperçus d'API), `MatrixConfig::effective_physical_dimensions()` reproduit exactement les mêmes dimensions physiques repliées. +- **Wrapper Zéro-Allocation `ScaledDrawingSurface` (`matrix.ui_scale`)** : Enveloppe de façon transparente la surface matérielle ou simulée avec **zéro allocation dynamique** sur le chemin critique H-Core : + - En mode `"auto"` (défaut), `UiScale::resolve` reste **strictement à `1x`** sur toutes les résolutions standard et TATE (`64×32`, `32×64`, `64×64`, `128×32`, `32×128`, `128×64`, `64×128`, `256×64`, `64×256`) en passe-plat 1:1 intégral (`acquire_canvas()` et `DirtyBounds` inchangés). + - Uniquement lorsque `min(width, height) >= 128` et `max(width, height) >= 192`, le mode `"auto"` active un upscaling entier Nearest-Neighbor `2x`/`3x`/`4x` (`256×192` → `2x` `128×96`, `512×384` → `4x` `128×96`), transformant chaque pixel logique en bloc `N×N` net tout en propageant exactement les lignes `DirtyBounds` à la surface interne. + - Les flux médias plein écran (`gifs`, ainsi que la Phase 2 `LiveStream` vidéo/panoramas de `DMD Media Showcase` et `ShowcaseStream` de `FrontendSync`) contournent la mise à l'échelle via `surface.unscaled()` (`native_width()` × `native_height()`), tandis que les moteurs UI et la Carte d'Intro Phase 1 de Showcase profitent de la grille logique mise à l'échelle. + --- ## 14. Isolation runtime et modèle de threads diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index e3d02ebc..e95a3917 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -41,6 +41,8 @@ This block configures the DMA parameters for the hzeller `rpi-rgb-led-matrix` li | `force_single_buffer` | `bool` | Force single-buffer mode when true (default `false`). | | `color_depth` | `int` | Logical color depth in bits (`24` default). | | `mapping` | `String` | GPIO wiring/mapping (`regular`, `adafruit-hat`, `adafruit-hat-pwm`, ...). | +| `pixel_mapper` | `String` | Optional hzeller pixel-mapper chain (`""` default, `"U-mapper"`, `"V-mapper"`, `"U-mapper;Rotate:180"`, ...). Folds long horizontal HUB75 chains into multi-row physical surfaces (e.g. `8` panels of `64×32` with `"U-mapper"` and `parallel: 3` → `256×192`). | +| `ui_scale` | `String` | Integer Nearest-Neighbor UI upscaling for giant multi-panel LED walls (`"auto"` default, `"1"`, `"2"`, `"3"`, `"4"`). In `"auto"` mode, stays **strictly `1x`** across all standard & TATE panels (`64×32`, `32×64`, `64×64`, `128×32`, `32×128`, `128×64`, `64×128`, `256×64`, `64×256`) and only triggers `2x`/`3x`/`4x` when `min(width, height) >= 128` and `max(width, height) >= 192` (e.g. `256×192` → `2x` `128×96`, `512×384` → `4x` `128×96`). Native `1x` full-screen rendering is preserved for `gifs` and for `DMD Media Showcase` video/panorama streams while the Phase 1 Intro Card benefits from upscaling. | | `driver_chip` | `String` | Controller chip (`SHIFTREG`, `FM6126A`). | | `rgb_sequence` | `String` | Color order (`RGB`, `RBG`, `BGR`, ...). Fix swapped colors here. | | `clk_phase` | `bool` | Clock phase inversion (`false` default). | diff --git a/docs/CONFIGURATION_ES.md b/docs/CONFIGURATION_ES.md index 18e0f40d..adca1d17 100644 --- a/docs/CONFIGURATION_ES.md +++ b/docs/CONFIGURATION_ES.md @@ -41,6 +41,8 @@ Este bloque configura los parámetros DMA para la biblioteca hzeller `rpi-rgb-le | `force_single_buffer` | `bool` | Fuerza el modo de buffer único cuando es `true` (por defecto `false`). | | `color_depth` | `int` | Profundidad de color lógica en bits (`24` por defecto). | | `mapping` | `String` | Cableado/mapeo GPIO (`regular`, `adafruit-hat`, `adafruit-hat-pwm`, ...). | +| `pixel_mapper` | `String` | Cadena opcional de pixel-mapper hzeller (`""` por defecto, `"U-mapper"`, `"V-mapper"`, `"U-mapper;Rotate:180"`, ...). Pliega largas cadenas HUB75 horizontales en superficies físicas multifila (ej. `8` paneles `64×32` con `"U-mapper"` y `parallel: 3` → `256×192`). | +| `ui_scale` | `String` | Escalado entero Nearest-Neighbor de la interfaz para grandes muros LED multipanel (`"auto"` por defecto, `"1"`, `"2"`, `"3"`, `"4"`). En modo `"auto"`, permanece **estrictamente en `1x`** en todas las resoluciones estándar y TATE (`64×32`, `32×64`, `64×64`, `128×32`, `32×128`, `128×64`, `64×128`, `256×64`, `64×256`) y solo activa `2x`/`3x`/`4x` cuando `min(width, height) >= 128` y `max(width, height) >= 192` (ej. `256×192` → `2x` `128×96`, `512×384` → `4x` `128×96`). El reproductor `gifs` y los flujos de vídeo/panoramas de `DMD Media Showcase` mantienen el renderizado nativo `1x` a pantalla completa mientras que la Tarjeta de Intro Fase 1 aprovecha el escalado. | | `driver_chip` | `String` | Chip controlador (`SHIFTREG`, `FM6126A`). | | `rgb_sequence` | `String` | Orden de colores (`RGB`, `RBG`, `BGR`, ...). Corrige aquí colores intercambiados. | | `clk_phase` | `bool` | Inversión de fase de reloj (`false` por defecto). | diff --git a/docs/CONFIGURATION_FR.md b/docs/CONFIGURATION_FR.md index 49d8787a..0ea27d98 100644 --- a/docs/CONFIGURATION_FR.md +++ b/docs/CONFIGURATION_FR.md @@ -41,6 +41,8 @@ Ce bloc configure les paramètres DMA de la bibliothèque hzeller `rpi-rgb-led-m | `force_single_buffer` | `bool` | Force le mode simple buffer lorsque défini à `true` (défaut `false`). | | `color_depth` | `int` | Profondeur de couleur logique en bits (`24` par défaut). | | `mapping` | `String` | Câblage/mapping GPIO (`regular`, `adafruit-hat`, `adafruit-hat-pwm`, ...). | +| `pixel_mapper` | `String` | Chaîne optionnelle de pixel-mapper hzeller (`""` par défaut, `"U-mapper"`, `"V-mapper"`, `"U-mapper;Rotate:180"`, ...). Replie de longues chaînes HUB75 horizontales en surfaces physiques multi-rangées (ex. `8` dalles `64×32` avec `"U-mapper"` et `parallel: 3` → `256×192`). | +| `ui_scale` | `String` | Mise à l'échelle entière Nearest-Neighbor de l'interface pour les très grands murs LED multi-panneaux (`"auto"` par défaut, `"1"`, `"2"`, `"3"`, `"4"`). En mode `"auto"`, le facteur reste **strictement à `1x`** sur toutes les résolutions standard et TATE (`64×32`, `32×64`, `64×64`, `128×32`, `32×128`, `128×64`, `64×128`, `256×64`, `64×256`) et ne déclenche `2x`/`3x`/`4x` que lorsque `min(width, height) >= 128` et `max(width, height) >= 192` (ex. `256×192` → `2x` `128×96`, `512×384` → `4x` `128×96`). Le lecteur `gifs` et les flux vidéo/panoramas de `DMD Media Showcase` conservent leur rendu natif `1x` plein écran tandis que la Carte d'Intro Phase 1 profite de l'upscaling. | | `driver_chip` | `String` | Puce contrôleur (`SHIFTREG`, `FM6126A`). | | `rgb_sequence` | `String` | Ordre des couleurs (`RGB`, `RBG`, `BGR`, ...). Corrigez ici les couleurs inversées. | | `clk_phase` | `bool` | Inversion de phase d'horloge (`false` par défaut). | diff --git a/docs/DEVELOPER.md b/docs/DEVELOPER.md index 44b83e7e..205238fb 100644 --- a/docs/DEVELOPER.md +++ b/docs/DEVELOPER.md @@ -629,9 +629,14 @@ pub trait IDrawingSurface: Send + Sync { fn height(&self) -> u32; fn physical_width(&self) -> u32; fn physical_height(&self) -> u32; + fn native_width(&self) -> u32 { self.width() } + fn native_height(&self) -> u32 { self.height() } + fn ui_scale(&self) -> u32 { 1 } + fn set_ui_scale(&mut self, _scale: u32) {} fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); @@ -642,6 +647,7 @@ pub trait IDrawingSurface: Send + Sync { fn acquire_canvas(&mut self) -> Option>; fn release_canvas(&mut self); fn has_canvas(&self) -> bool; + fn unscaled(&mut self) -> &mut dyn IDrawingSurface; } ``` @@ -671,6 +677,7 @@ fn render(&mut self, ctx: &mut EngineContext) { 2. **Take advantage of dirty tracking**: With `RenderPipeline::CanvasSingle` (the default, see [ARCHITECTURE.md §13](ARCHITECTURE.md#13-hardware-render-pipeline--the-idrawingsurface-abstraction)), `IDrawingSurface` tracks exact scanline bounds (`DirtyBounds`). If nothing changes (`has_new_frame() == false`), `present()` completes in $O(1)$ with **zero** memory bus traffic, guaranteeing protection for Broadcom SDIO Wi-Fi (`brcmfmac`). 3. **Control full-screen clearing**: If your engine paints the entire display every tick (e.g. streaming GIF or video), override `wants_clear(&self) -> bool { false }` to avoid an unnecessary full-screen black clear before your `render()` call. 4. **Overlay Pass**: After your `render()` returns, the render loop may run the additive **Fighter overlay** pass on top of your frame (see [ARCHITECTURE.md §12](ARCHITECTURE.md#12-the-transverse-overlay-architecture--overlaymanager)). If your engine cannot support overlays, return `allows_overlay(&self) -> bool { false }`. +5. **UI Scaling vs. Native `1x` Full-Screen Media**: Standard UI engines draw to `ctx.surface.width()` × `ctx.surface.height()`, automatically gaining crisp integer Nearest-Neighbor upscaling (`2x`/`3x`/`4x`) on giant multi-panel LED walls (`256×192`, `512×384`). Only full-screen native media streams (`gifs`, `DMD Media Showcase` Phase 2 `LiveStream`) query `native_width()` / `native_height()` and blit via `ctx.surface.unscaled()`. --- diff --git a/docs/DEVELOPER_ES.md b/docs/DEVELOPER_ES.md index 0f194513..f7be63ee 100644 --- a/docs/DEVELOPER_ES.md +++ b/docs/DEVELOPER_ES.md @@ -621,9 +621,14 @@ pub trait IDrawingSurface: Send + Sync { fn height(&self) -> u32; fn physical_width(&self) -> u32; fn physical_height(&self) -> u32; + fn native_width(&self) -> u32 { self.width() } + fn native_height(&self) -> u32 { self.height() } + fn ui_scale(&self) -> u32 { 1 } + fn set_ui_scale(&mut self, _scale: u32) {} fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); @@ -634,6 +639,7 @@ pub trait IDrawingSurface: Send + Sync { fn acquire_canvas(&mut self) -> Option>; fn release_canvas(&mut self); fn has_canvas(&self) -> bool; + fn unscaled(&mut self) -> &mut dyn IDrawingSurface; } ``` @@ -663,6 +669,7 @@ fn render(&mut self, ctx: &mut EngineContext) { 2. **Aprovecha el dirty tracking**: Con `RenderPipeline::CanvasSingle` (por defecto recomendado, ver [ARCHITECTURE_ES.md §13](ARCHITECTURE_ES.md#13-pipeline-de-renderizado-por-hardware-y-abstracción-idrawingsurface)), `IDrawingSurface` rastrea las áreas modificadas (`DirtyBounds`). Si la frame es idéntica (`has_new_frame() == false`), `present()` termina en $O(1)$ con **cero tráfico en el bus de memoria**, garantizando la protección del Wi-Fi SDIO Broadcom (`brcmfmac`). 3. **Controla el borrado de pantalla completa**: Si tu motor repinta toda la pantalla en cada tick (p. ej. streaming de GIF o vídeo), sobrescribe `wants_clear(&self) -> bool { false }` para evitar una pasada innecesaria de borrado en negro. 4. **Pasada de Overlay**: Tras finalizar `render()`, el bucle puede aplicar la pasada aditiva del **overlay Fighter** (ver [ARCHITECTURE_ES.md §12](ARCHITECTURE_ES.md#12-la-arquitectura-de-overlay-transversal-y-overlaymanager)). Si tu motor no admite overlays, devuelve `allows_overlay(&self) -> bool { false }`. +5. **Escalado UI vs. Multimedia Nativo `1x` a Pantalla Completa**: Los motores UI estándar dibujan sobre `ctx.surface.width()` × `ctx.surface.height()`, beneficiándose automáticamente del escalado entero Nearest-Neighbor (`2x`/`3x`/`4x`) en grandes muros LED (`256×192`, `512×384`). Solo los flujos multimedia a pantalla completa (`gifs`, Fase 2 `LiveStream` de `DMD Media Showcase`) consultan `native_width()` / `native_height()` y dibujan mediante `ctx.surface.unscaled()`. --- diff --git a/docs/DEVELOPER_FR.md b/docs/DEVELOPER_FR.md index 6659d732..591e117b 100644 --- a/docs/DEVELOPER_FR.md +++ b/docs/DEVELOPER_FR.md @@ -629,9 +629,14 @@ pub trait IDrawingSurface: Send + Sync { fn height(&self) -> u32; fn physical_width(&self) -> u32; fn physical_height(&self) -> u32; + fn native_width(&self) -> u32 { self.width() } + fn native_height(&self) -> u32 { self.height() } + fn ui_scale(&self) -> u32 { 1 } + fn set_ui_scale(&mut self, _scale: u32) {} fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); @@ -642,6 +647,7 @@ pub trait IDrawingSurface: Send + Sync { fn acquire_canvas(&mut self) -> Option>; fn release_canvas(&mut self); fn has_canvas(&self) -> bool; + fn unscaled(&mut self) -> &mut dyn IDrawingSurface; } ``` @@ -671,6 +677,7 @@ fn render(&mut self, ctx: &mut EngineContext) { 2. **Profiter du dirty tracking** : Avec `RenderPipeline::CanvasSingle` (le mode par défaut recommandé, voir [ARCHITECTURE_FR.md §13](ARCHITECTURE_FR.md#13-pipeline-de-rendu-matériel--abstraction-idrawingsurface)), `IDrawingSurface` suit les tranches de lignes modifiées (`DirtyBounds`). Si rien ne change visuellement (`has_new_frame() == false`), `present()` se termine en $O(1)$ avec **zéro trafic sur le bus mémoire**, garantissant la protection du contrôleur Wi-Fi Broadcom SDIO (`brcmfmac`). 3. **Contrôler l'effacement plein écran** : Si ton moteur redessine l'intégralité de l'écran à chaque tick (ex. flux GIF ou vidéo streaming), surcharge `wants_clear(&self) -> bool { false }` pour éviter une passe d'effacement noir redondante avant l'appel à ton `render()`. 4. **Passe Overlay** : Après le retour de ton `render()`, la boucle de rendu peut exécuter la passe additive de **l'overlay Fighter** par-dessus ta frame (voir [ARCHITECTURE_FR.md §12](ARCHITECTURE_FR.md#12-larchitecture-doverlay-transverse--overlaymanager)). Si ton moteur n'admet pas d'overlay, retourne `allows_overlay(&self) -> bool { false }`. +5. **Mise à l'échelle UI vs. Médias Natifs `1x` Plein Écran** : Les moteurs UI standard dessinent sur `ctx.surface.width()` × `ctx.surface.height()`, profitant automatiquement de l'upscaling entier Nearest-Neighbor (`2x`/`3x`/`4x`) sur les très grands murs LED (`256×192`, `512×384`). Seuls les flux médias plein écran (`gifs`, Phase 2 `LiveStream` de `DMD Media Showcase`) lisent `native_width()` / `native_height()` et dessinent via `ctx.surface.unscaled()`. --- diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 735257c2..e390e14e 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -252,6 +252,18 @@ paths: type: string slot_transition_duration_ms: type: integer + pixel_mapper: + type: string + description: >- + Optional hzeller pixel-mapper chain (e.g. "", "U-mapper", "V-mapper", + "U-mapper;Rotate:180"). Changing it flags a hardware render-loop reload. + ui_scale: + type: string + enum: [auto, "1", "2", "3", "4"] + default: auto + description: >- + Integer UI upscaling mode for giant multi-panel LED walls ("auto", "1", "2", + "3", "4"). Applied live on the next rotation refresh without restarting. responses: '200': description: Settings applied or reload scheduled @@ -1853,6 +1865,22 @@ components: type: boolean mapping: type: string + pixel_mapper: + type: string + default: "" + description: >- + Optional hzeller --led-pixel-mapper chain (e.g. "", "U-mapper", "V-mapper", + "U-mapper;Rotate:180") folding chained panels into multi-row surfaces. + ui_scale: + type: string + enum: [auto, "1", "2", "3", "4"] + default: auto + description: >- + Integer Nearest-Neighbor UI scale factor ("auto", "1", "2", "3", "4"). In "auto" + mode, stays strictly 1x for all standard & TATE panels (64x32..256x64, 32x64..64x256) + and only activates 2x/3x/4x when min(width, height) >= 128 and max(width, height) >= 192 + (e.g. 256x192 -> 2x 128x96, 512x384 -> 4x 128x96), while preserving native 1x full-screen + playback for gifs and DMD Media Showcase video/panoramas. rotation: type: integer enum: [0, 90, 180, 270] diff --git a/scripts/validate_docs.py b/scripts/validate_docs.py index a37392f2..a829ed35 100644 --- a/scripts/validate_docs.py +++ b/scripts/validate_docs.py @@ -29,7 +29,16 @@ ) EXPECTED_CONFIG_SCHEMA = { - "matrix": ["width", "height", "chain_length", "pwm_bits", "rotation", "transition_effect"], + "matrix": [ + "width", + "height", + "chain_length", + "pwm_bits", + "pixel_mapper", + "rotation", + "transition_effect", + "ui_scale", + ], "system": ["timezone", "format_24h", "lang", "temp_unit", "night_mode_enabled", "idle_fighter_enabled"], "wifi": ["ssid", "password", "hostname"], "mqtt": ["enabled", "broker", "port"], diff --git a/src/api/server.rs b/src/api/server.rs index 48029bea..4fee473d 100644 --- a/src/api/server.rs +++ b/src/api/server.rs @@ -298,6 +298,16 @@ async fn post_system( { s.matrix.slot_transition_duration_ms = v as u32; } + if let Some(v) = body.get("ui_scale") { + if let Some(sv) = v.as_str() { + s.matrix.ui_scale = crate::core::config::UiScale::from_str_lossy(sv); + } else if let Some(iv) = v.as_u64() { + s.matrix.ui_scale = crate::core::config::UiScale::from_int_lossy(iv); + } + } + if let Some(v) = body.get("pixel_mapper").and_then(|v| v.as_str()) { + s.matrix.pixel_mapper = v.trim().to_string(); + } // Hardware & MQTT-affecting settings only take effect after a restart of the // render/network loops, so flag it when physical matrix params, MQTT broker, or Wi-Fi state change. let prev_matrix_cfg: Option = @@ -306,8 +316,10 @@ async fn post_system( p.width != s.matrix.width || p.height != s.matrix.height || p.chain_length != s.matrix.chain_length + || p.parallel != s.matrix.parallel || p.driver_chip != s.matrix.driver_chip || p.mapping != s.matrix.mapping + || p.pixel_mapper != s.matrix.pixel_mapper || p.rgb_sequence != s.matrix.rgb_sequence || p.row_address_mode != s.matrix.row_address_mode || p.multiplexing != s.matrix.multiplexing @@ -1349,19 +1361,14 @@ async fn get_themes(req: HttpRequest, data: web::Data) -> impl Respond } let (w, h) = { let mat = &data.config.settings.read().matrix; - let phys_w = (mat.width * mat.chain_length).max(32) as i32; - let phys_h = (mat.height * mat.parallel.max(1)).max(32) as i32; - if mat.rotation == 90 || mat.rotation == 270 { - (phys_h, phys_w) - } else { - (phys_w, phys_h) - } + let (lw, lh) = mat.effective_logical_dimensions(); + (lw.max(32), lh.max(32)) }; // Built automatically from the single theme source of truth, filtering out // themes whose declarative resolution constraints are not met by the panel. let themes: Vec<_> = crate::core::theme::all_themes() .iter() - .filter(|t| t.is_compatible(w as u32, h as u32)) + .filter(|t| t.is_compatible(w, h)) .map(|t| json!({"value": t.id.to_string(), "label": t.name})) .collect(); HttpResponse::Ok().json(themes) @@ -1692,23 +1699,31 @@ async fn get_e2e_state(data: web::Data) -> impl Responder { let sync_tel = crate::engines::frontend_sync::read_e2e_sync_telemetry(); let fb_snap = crate::core::matrix::read_mock_framebuffer_snapshot(); let prod_snap = cfg.producer_snapshot.load(); - let (w, h) = { + let (w, h, nat_w, nat_h, ui_scale, pixel_mapper) = { let s = cfg.settings.read(); + let (pw, ph) = s.matrix.effective_physical_dimensions(); + let (nw, nh) = s.matrix.effective_native_dimensions(); ( - s.matrix.width * s.matrix.chain_length, - s.matrix.height * s.matrix.parallel.clamp(1, 3), + pw, + ph, + nw, + nh, + s.matrix.resolve_ui_scale(), + s.matrix.pixel_mapper.clone(), ) }; let sync_client_id = format!( "rpi_{}_games_{}x{}_sync", crate::engines::renderers::media_showcase::rpi_hardware_short_id(), - w, - h + nat_w, + nat_h ); HttpResponse::Ok().json(json!({ "target": "arcadematrix_rpi", "width": w, "height": h, + "ui_scale": ui_scale, + "pixel_mapper": pixel_mapper, "sync_client_id": sync_client_id, "forced_mode": format!("{:?}", prod_snap.forced_mode), "ingame_showcase_active": prod_snap.ingame_showcase.is_some(), @@ -1742,13 +1757,12 @@ async fn get_e2e_framebuffer(data: web::Data) -> impl Responder { .content_type("application/octet-stream") .body(fb_snap.rgb565_le); } - let (w, h) = { - let s = data.config.settings.read(); - ( - s.matrix.width * s.matrix.chain_length, - s.matrix.height * s.matrix.parallel.clamp(1, 3), - ) - }; + let (w, h) = data + .config + .settings + .read() + .matrix + .effective_physical_dimensions(); HttpResponse::Ok() .content_type("application/octet-stream") .body(vec![0u8; (w * h * 2) as usize]) diff --git a/src/app.rs b/src/app.rs index 2cdfe842..479bb1ce 100644 --- a/src/app.rs +++ b/src/app.rs @@ -293,6 +293,7 @@ struct RuntimeSnapshot { system: crate::core::config::SystemConfig, mqtt: crate::core::config::MqttConfig, display_rotation: u8, + resolved_ui_scale: u32, slot_transition: String, slot_transition_duration_ms: u32, mqtt_handle: EngineHandle, @@ -317,6 +318,13 @@ fn build_runtime_snapshot( surface: &mut dyn IDrawingSurface, ) -> RuntimeSnapshot { let settings = config.settings.read(); + let display_rotation = normalize_rotation(settings.matrix.rotation); + let resolved_ui_scale = settings + .matrix + .ui_scale + .resolve(surface.physical_width(), surface.physical_height()); + surface.set_rotation(display_rotation); + surface.set_ui_scale(resolved_ui_scale); let mut ctx = crate::core::engine_contract::EngineContext { surface, config }; let active_instance_ids: std::collections::HashSet<&str> = settings @@ -382,7 +390,8 @@ fn build_runtime_snapshot( rotation, system: settings.system.clone(), mqtt: settings.mqtt.clone(), - display_rotation: normalize_rotation(settings.matrix.rotation), + display_rotation, + resolved_ui_scale, slot_transition: settings.matrix.slot_transition.clone(), slot_transition_duration_ms: settings.matrix.slot_transition_duration_ms, mqtt_handle, @@ -414,9 +423,13 @@ impl ArcadeMatrixApp { attempt, e ); - break Box::new(MockSurface::new( - matrix_cfg.width * matrix_cfg.chain_length, - matrix_cfg.height * matrix_cfg.parallel.clamp(1, 3), + let (fb_w, fb_h) = matrix_cfg.effective_physical_dimensions(); + let mut mock = MockSurface::new(fb_w, fb_h); + mock.set_rotation(normalize_rotation(matrix_cfg.rotation)); + let fb_scale = matrix_cfg.ui_scale.resolve(fb_w, fb_h); + break Box::new(crate::core::matrix::ScaledDrawingSurface::new( + Box::new(mock), + fb_scale, )); } tracing::warn!( @@ -439,10 +452,21 @@ impl ArcadeMatrixApp { let mut engine_runtime = EngineRuntime::new(); let mut rotation_manager = RotationManager::new(); let mut slot_transition = crate::core::slot_transition::SlotTransition::default(); - let initial_rot = normalize_rotation(config.settings.read().matrix.rotation); + let (initial_rot, initial_scale) = { + let mat = &config.settings.read().matrix; + ( + normalize_rotation(mat.rotation), + mat.ui_scale.resolve(phys_width, phys_height), + ) + }; surface.set_rotation(initial_rot); - let mut orientation_manager = - crate::core::orientation::OrientationManager::new(phys_width, phys_height, initial_rot); + surface.set_ui_scale(initial_scale); + let mut orientation_manager = crate::core::orientation::OrientationManager::new_with_scale( + phys_width, + phys_height, + initial_rot, + initial_scale, + ); let mut overlay_manager = crate::core::overlay_manager::OverlayManager::new( orientation_manager.geometry().width(), orientation_manager.geometry().height(), @@ -543,7 +567,10 @@ impl ArcadeMatrixApp { .set_instance_rotation_budget(rot_entry.handle, rot_entry.duration_sec); } surface.set_rotation(snapshot.display_rotation); - if orientation_manager.set_rotation(snapshot.display_rotation) { + surface.set_ui_scale(snapshot.resolved_ui_scale); + let rot_changed = orientation_manager.set_rotation(snapshot.display_rotation); + let scale_changed = orientation_manager.set_ui_scale(snapshot.resolved_ui_scale); + if rot_changed || scale_changed { runtime.on_display_geometry_changed( orientation_manager.geometry(), &mut engine_runtime, @@ -551,8 +578,9 @@ impl ArcadeMatrixApp { overlay_manager.on_display_geometry_changed(orientation_manager.geometry()); } tracing::info!( - "Display orientation/rotation updated to {}° in real-time.", - (snapshot.display_rotation as u32) * 90 + "Display orientation/rotation updated to {}° (ui_scale={}x) in real-time.", + (snapshot.display_rotation as u32) * 90, + snapshot.resolved_ui_scale ); } diff --git a/src/core/config.rs b/src/core/config.rs index c6764d3b..ed67d793 100644 --- a/src/core/config.rs +++ b/src/core/config.rs @@ -103,6 +103,138 @@ impl Default for RenderPipeline { } } +/// Integer UI upscaling policy for multi-panel HUB75 LED walls (`matrix.ui_scale`). +/// +/// In `Auto` mode (default), strictly preserves `1x` native rendering for all standard YOKO and +/// TATE panels (`64x32`, `32x64`, `64x64`, `128x32`, `32x128`, `128x64`, `64x128`, `256x64`, +/// `64x256`, `128x128`), and engages `2x`/`3x`/`4x` Nearest-Neighbor integer upscaling only when +/// `min(width, height) >= 128 && max(width, height) >= 192` (e.g. `256x192` -> `2x` `128x96`, +/// `384x288` -> `3x` `128x96`, `512x384` -> `4x` `128x96`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UiScale { + Auto, + Scale1x, + Scale2x, + Scale3x, + Scale4x, +} + +impl Default for UiScale { + fn default() -> Self { + UiScale::Auto + } +} + +impl UiScale { + #[inline] + pub const fn as_str(self) -> &'static str { + match self { + UiScale::Auto => "auto", + UiScale::Scale1x => "1", + UiScale::Scale2x => "2", + UiScale::Scale3x => "3", + UiScale::Scale4x => "4", + } + } + + pub fn from_str_lossy(raw: &str) -> Self { + match raw.trim().to_ascii_lowercase().as_str() { + "" | "auto" | "0" | "0x" => UiScale::Auto, + "1" | "1x" => UiScale::Scale1x, + "2" | "2x" => UiScale::Scale2x, + "3" | "3x" => UiScale::Scale3x, + "4" | "4x" => UiScale::Scale4x, + _ => UiScale::Auto, + } + } + + #[inline] + pub const fn from_int_lossy(val: u64) -> Self { + match val { + 1 => UiScale::Scale1x, + 2 => UiScale::Scale2x, + 3 => UiScale::Scale3x, + 4 => UiScale::Scale4x, + _ => UiScale::Auto, + } + } + + /// Resolves the active integer Nearest-Neighbor UI scale factor (`1..=4`) for `(width, height)`. + /// + /// Symmetric across YOKO and TATE orientations (`resolve(w, h) == resolve(h, w)`). + #[inline] + pub const fn resolve(self, width: u32, height: u32) -> u32 { + match self { + UiScale::Scale1x => 1, + UiScale::Scale2x => { + if width >= 2 && height >= 2 { + 2 + } else { + 1 + } + } + UiScale::Scale3x => { + if width >= 3 && height >= 3 { + 3 + } else { + 1 + } + } + UiScale::Scale4x => { + if width >= 4 && height >= 4 { + 4 + } else { + 1 + } + } + UiScale::Auto => { + let min_dim = if width < height { width } else { height }; + let max_dim = if width > height { width } else { height }; + if min_dim < 128 || max_dim < 192 { + return 1; + } + let by_max = max_dim / 128; + let by_min = min_dim / 64; + let raw = if by_max < by_min { by_max } else { by_min }; + if raw < 2 { + 2 + } else if raw > 4 { + 4 + } else { + raw + } + } + } + } +} + +impl Serialize for UiScale { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + serializer.serialize_str(self.as_str()) + } +} + +impl<'de> Deserialize<'de> for UiScale { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let val = Value::deserialize(deserializer)?; + let parsed = match val { + Value::String(s) => Self::from_str_lossy(&s), + Value::Number(n) => n + .as_u64() + .map(Self::from_int_lossy) + .unwrap_or(UiScale::Auto), + _ => UiScale::Auto, + }; + Ok(parsed) + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct MatrixConfig { @@ -130,6 +262,9 @@ pub struct MatrixConfig { pub pwm_lsb_nanoseconds: u32, pub disable_hardware_pulsing: bool, pub mapping: String, + /// Optional hzeller `pixel_mapper_config` chain (e.g. `"U-mapper"`, `"V-mapper"`, `"U-mapper;Rotate:90"`). + #[serde(default)] + pub pixel_mapper: String, pub rotation: u32, pub transition_effect: String, pub transition_duration_ms: u32, @@ -140,6 +275,9 @@ pub struct MatrixConfig { pub slot_transition_duration_ms: u32, #[serde(default)] pub render_pipeline: RenderPipeline, + /// Integer Nearest-Neighbor UI scale policy (`"auto"`, `"1"`, `"2"`, `"3"`, `"4"`). + #[serde(default)] + pub ui_scale: UiScale, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -407,16 +545,94 @@ impl Default for MatrixConfig { pwm_lsb_nanoseconds: 130, disable_hardware_pulsing: false, mapping: "regular".to_string(), + pixel_mapper: String::new(), rotation: 0, transition_effect: "vortex".to_string(), transition_duration_ms: 400, slot_transition: default_slot_transition(), slot_transition_duration_ms: default_slot_transition_ms(), render_pipeline: RenderPipeline::CanvasSingle, + ui_scale: UiScale::Auto, } } } +impl MatrixConfig { + /// Computes the visible physical canvas `(width, height)` after applying `chain_length`, + /// `parallel`, and any semicolon-separated `pixel_mapper` (`U-mapper`, `V-mapper`, `Rotate`), + /// matching `hzeller/rpi-rgb-led-matrix` `pixel-mapper.cc` 1:1. + pub fn effective_physical_dimensions(&self) -> (u32, u32) { + let chain = self.chain_length.max(1); + let par = self.parallel.clamp(1, 3); + let mut w = self.width.max(1).saturating_mul(chain); + let mut h = self.height.max(1).saturating_mul(par); + + for raw_stage in self.pixel_mapper.split(';') { + let stage = raw_stage.trim(); + if stage.is_empty() { + continue; + } + let (name, param) = match stage.split_once(':') { + Some((n, p)) => (n.trim(), p.trim()), + None => (stage, ""), + }; + if name.eq_ignore_ascii_case("u-mapper") { + if chain >= 2 && chain % 2 == 0 { + w = if w >= 64 { + (w / 64).saturating_mul(32) + } else { + (w / 2).max(1) + }; + h = h.saturating_mul(2); + } + } else if name.eq_ignore_ascii_case("v-mapper") { + let next_w = w.saturating_mul(par) / chain; + let next_h = h.saturating_mul(chain) / par; + if next_w > 0 && next_h > 0 { + w = next_w; + h = next_h; + } + } else if name.eq_ignore_ascii_case("rotate") { + if let Ok(angle) = param.parse::() { + let norm = angle.rem_euclid(360); + if norm == 90 || norm == 270 { + std::mem::swap(&mut w, &mut h); + } + } + } + } + (w.max(1), h.max(1)) + } + + /// Computes the native 1x logical `(width, height)` after applying `pixel_mapper` and `rotation` + /// (`0°/180°` vs `90°/270°` TATE), before any `ui_scale` integer division. + #[inline] + pub fn effective_native_dimensions(&self) -> (u32, u32) { + let (pw, ph) = self.effective_physical_dimensions(); + if matches!(self.rotation, 90 | 1 | 270 | 3) { + (ph, pw) + } else { + (pw, ph) + } + } + + /// Resolves the active integer `ui_scale` factor (`1..=4`) for this matrix configuration. + #[inline] + pub fn resolve_ui_scale(&self) -> u32 { + let (nw, nh) = self.effective_native_dimensions(); + self.ui_scale.resolve(nw, nh) + } + + /// Computes the UI logical `(width, height)` seen by scaled UI engines after `pixel_mapper`, + /// `rotation`, and `ui_scale` resolution. + #[inline] + pub fn effective_logical_dimensions(&self) -> (u32, u32) { + let (nw, nh) = self.effective_native_dimensions(); + let s = self.ui_scale.resolve(nw, nh).max(1); + ((nw / s).max(1), (nh / s).max(1)) + } +} + impl Default for WifiConfig { fn default() -> Self { Self { diff --git a/src/core/matrix.rs b/src/core/matrix.rs index b3ec5d92..ac1e5713 100644 --- a/src/core/matrix.rs +++ b/src/core/matrix.rs @@ -355,6 +355,266 @@ pub trait IDrawingSurface: Send + Sync { fn has_canvas(&self) -> bool { false } + + /// Active integer Nearest-Neighbor UI scale factor (`1` = native 1:1, `2..=4` = upscaled). + #[inline] + fn ui_scale(&self) -> u32 { + 1 + } + + /// Updates the active integer UI scale factor in real time (`1..=4`). + fn set_ui_scale(&mut self, _scale: u32) {} + + /// Native 1x logical width after rotation (ignoring `ui_scale`). + #[inline] + fn native_width(&self) -> u32 { + if self.rotation() % 2 == 1 { + self.physical_height() + } else { + self.physical_width() + } + } + + /// Native 1x logical height after rotation (ignoring `ui_scale`). + #[inline] + fn native_height(&self) -> u32 { + if self.rotation() % 2 == 1 { + self.physical_width() + } else { + self.physical_height() + } + } + + /// Returns `Some((min_y, max_y))` when row-span `DirtyBounds` tracking is active and dirty. + #[inline] + fn dirty_row_span(&self) -> Option<(u32, u32)> { + None + } + + /// Returns a mutable reference to the underlying native 1x surface (bypassing `ui_scale` + /// Nearest-Neighbor expansion for full-screen 1x GIFs, panoramas, and video streams). + /// Zero heap allocation, zero copy, preserves `DirtyBounds`. + fn unscaled(&mut self) -> &mut dyn IDrawingSurface; +} + +/// Zero-allocation Nearest-Neighbor integer upscaling wrapper around `IDrawingSurface`. +/// +/// - When `scale == 1` (default `"auto"` for all standard panels `64x32..256x64` YOKO & TATE), +/// operates as a 1:1 passthrough with zero coordinate alteration and full `CanvasView` support. +/// - When `scale` is `2..=4` (e.g. `256x192` -> `2x` `128x96`, `512x384` -> `4x` `128x96`), +/// expands each logical UI pixel into an exact `scale x scale` Nearest-Neighbor block in `0` +/// heap allocations while preserving `DirtyBounds` row span tracking on the inner surface. +pub struct ScaledDrawingSurface { + inner: Box, + scale: u32, +} + +impl ScaledDrawingSurface { + #[inline] + fn clamp_scale_for_dims(scale: u32, phys_w: u32, phys_h: u32) -> u32 { + let s = scale.clamp(1, 4); + if phys_w >= s && phys_h >= s { + s + } else { + 1 + } + } + + pub fn new(inner: Box, scale: u32) -> Self { + let clamped = + Self::clamp_scale_for_dims(scale, inner.physical_width(), inner.physical_height()); + Self { + inner, + scale: clamped, + } + } + + #[inline] + pub fn inner(&self) -> &dyn IDrawingSurface { + &*self.inner + } + + #[inline] + pub fn inner_mut(&mut self) -> &mut dyn IDrawingSurface { + &mut *self.inner + } + + #[inline] + pub fn into_inner(self) -> Box { + self.inner + } +} + +impl IDrawingSurface for ScaledDrawingSurface { + #[inline] + fn width(&self) -> u32 { + if self.scale <= 1 { + self.inner.width() + } else { + (self.inner.width() / self.scale).max(1) + } + } + + #[inline] + fn height(&self) -> u32 { + if self.scale <= 1 { + self.inner.height() + } else { + (self.inner.height() / self.scale).max(1) + } + } + + #[inline] + fn physical_width(&self) -> u32 { + self.inner.physical_width() + } + + #[inline] + fn physical_height(&self) -> u32 { + self.inner.physical_height() + } + + #[inline] + fn native_width(&self) -> u32 { + self.inner.native_width() + } + + #[inline] + fn native_height(&self) -> u32 { + self.inner.native_height() + } + + #[inline] + fn ui_scale(&self) -> u32 { + self.scale + } + + #[inline] + fn set_ui_scale(&mut self, scale: u32) { + let next = Self::clamp_scale_for_dims( + scale, + self.inner.physical_width(), + self.inner.physical_height(), + ); + if self.scale != next { + self.scale = next; + self.inner.mark_dirty(); + } + } + + #[inline] + fn unscaled(&mut self) -> &mut dyn IDrawingSurface { + self.inner.unscaled() + } + + #[inline] + fn set_rotation(&mut self, rotation: u8) { + self.inner.set_rotation(rotation); + } + + #[inline] + fn rotation(&self) -> u8 { + self.inner.rotation() + } + + #[inline] + fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8) { + if self.scale <= 1 { + self.inner.set_pixel(x, y, red, green, blue); + return; + } + let log_w = self.width() as i32; + let log_h = self.height() as i32; + if x < 0 || y < 0 || x >= log_w || y >= log_h { + return; + } + let s = self.scale as i32; + let bx = x * s; + let by = y * s; + for dy in 0..s { + for dx in 0..s { + self.inner.set_pixel(bx + dx, by + dy, red, green, blue); + } + } + } + + #[inline] + fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, r: u8, g: u8, b: u8) { + if self.scale <= 1 { + self.inner.fill_rect(x, y, w, h, r, g, b); + return; + } + if w <= 0 || h <= 0 { + return; + } + let max_w = self.width() as i32; + let max_h = self.height() as i32; + let x0 = x.max(0); + let y0 = y.max(0); + let x1 = (x + w).min(max_w); + let y1 = (y + h).min(max_h); + if x0 >= x1 || y0 >= y1 { + return; + } + let s = self.scale as i32; + self.inner + .fill_rect(x0 * s, y0 * s, (x1 - x0) * s, (y1 - y0) * s, r, g, b); + } + + #[inline] + fn clear(&mut self) { + self.inner.clear(); + } + + #[inline] + fn present(&mut self) { + self.inner.present(); + } + + #[inline] + fn set_brightness(&mut self, brightness: u8) { + self.inner.set_brightness(brightness); + } + + #[inline] + fn mark_dirty(&mut self) { + self.inner.mark_dirty(); + } + + #[inline] + fn is_dirty(&self) -> bool { + self.inner.is_dirty() + } + + #[inline] + fn dirty_row_span(&self) -> Option<(u32, u32)> { + self.inner.dirty_row_span() + } + + #[inline] + fn acquire_canvas(&mut self) -> Option> { + if self.scale <= 1 { + self.inner.acquire_canvas() + } else { + None + } + } + + #[inline] + fn release_canvas(&mut self) { + if self.scale <= 1 { + self.inner.release_canvas(); + } + } + + #[inline] + fn has_canvas(&self) -> bool { + if self.scale <= 1 { + self.inner.has_canvas() + } else { + false + } + } } /// Move-only RAII guard strictly enforcing the scoped per-frame lifetime of a borrowed CanvasView. @@ -537,6 +797,14 @@ impl IDrawingSurface for MockSurface { self.dirty_bounds.dirty } + fn dirty_row_span(&self) -> Option<(u32, u32)> { + if self.dirty_bounds.dirty { + Some((self.dirty_bounds.min_y, self.dirty_bounds.max_y)) + } else { + None + } + } + fn acquire_canvas(&mut self) -> Option> { let w = self.physical_width; let h = self.physical_height; @@ -556,6 +824,11 @@ impl IDrawingSurface for MockSurface { fn has_canvas(&self) -> bool { true } + + #[inline] + fn unscaled(&mut self) -> &mut dyn IDrawingSurface { + self + } } #[cfg(all(target_os = "linux", any(target_arch = "arm", target_arch = "aarch64")))] @@ -620,7 +893,7 @@ impl CanvasBufferedSurface { brightness: 100, physical_width, physical_height, - rotation: (cfg.rotation % 4) as u8, + rotation: normalize_rotation_code(cfg.rotation), buffer: RgbImage::new(physical_width, physical_height), scaled_buffer: vec![0u8; scaled_len], dirty_bounds: DirtyBounds::new(physical_height), @@ -800,6 +1073,14 @@ impl IDrawingSurface for CanvasBufferedSurface { self.dirty_bounds.dirty } + fn dirty_row_span(&self) -> Option<(u32, u32)> { + if self.dirty_bounds.dirty { + Some((self.dirty_bounds.min_y, self.dirty_bounds.max_y)) + } else { + None + } + } + fn acquire_canvas(&mut self) -> Option> { let w = self.physical_width; let h = self.physical_height; @@ -819,6 +1100,11 @@ impl IDrawingSurface for CanvasBufferedSurface { fn has_canvas(&self) -> bool { true } + + #[inline] + fn unscaled(&mut self) -> &mut dyn IDrawingSurface { + self + } } /// Direct Surface rendering directly to hardware LedCanvas. @@ -851,7 +1137,7 @@ impl DirectSurface { brightness: 100, physical_width: w as u32, physical_height: h as u32, - rotation: (cfg.rotation % 4) as u8, + rotation: normalize_rotation_code(cfg.rotation), pipeline, dirty: true, }) @@ -959,6 +1245,21 @@ impl IDrawingSurface for DirectSurface { fn is_dirty(&self) -> bool { self.dirty } + + #[inline] + fn unscaled(&mut self) -> &mut dyn IDrawingSurface { + self + } +} + +#[inline] +pub fn normalize_rotation_code(val: u32) -> u8 { + match val { + 90 | 1 => 1, + 180 | 2 => 2, + 270 | 3 => 3, + _ => 0, + } } #[cfg(all(target_os = "linux", any(target_arch = "arm", target_arch = "aarch64")))] @@ -976,10 +1277,22 @@ fn init_led_matrix( options.set_scan_mode(cfg.scan_mode); options.set_brightness(100).unwrap_or(()); if !cfg.mapping.is_empty() { - options.set_hardware_mapping(&cfg.mapping); + let clean_mapping: String = cfg.mapping.chars().filter(|&c| c != '\0').collect(); + if !clean_mapping.trim().is_empty() { + options.set_hardware_mapping(clean_mapping.trim()); + } } if !cfg.rgb_sequence.is_empty() { - options.set_led_rgb_sequence(&cfg.rgb_sequence); + let clean_rgb: String = cfg.rgb_sequence.chars().filter(|&c| c != '\0').collect(); + if !clean_rgb.trim().is_empty() { + options.set_led_rgb_sequence(clean_rgb.trim()); + } + } + if !cfg.pixel_mapper.is_empty() { + let clean_mapper: String = cfg.pixel_mapper.chars().filter(|&c| c != '\0').collect(); + if !clean_mapper.trim().is_empty() { + options.set_pixel_mapper_config(clean_mapper.trim()); + } } let _ = options.set_pwm_bits(cfg.pwm_bits as u8); options.set_pwm_lsb_nanoseconds(cfg.pwm_lsb_nanoseconds); @@ -1031,11 +1344,11 @@ fn init_led_matrix( /// Factory creating the canonical IDrawingSurface according to configuration. pub fn create_surface(cfg: &MatrixConfig) -> Result, String> { if is_mock_matrix_mode() { - let w = cfg.width * cfg.chain_length; - let h = cfg.height * cfg.parallel.clamp(1, 3); + let (w, h) = cfg.effective_physical_dimensions(); let mut mock = MockSurface::new(w, h); - mock.set_rotation((cfg.rotation % 4) as u8); - return Ok(Box::new(mock)); + mock.set_rotation(normalize_rotation_code(cfg.rotation)); + let scale = cfg.ui_scale.resolve(w, h); + return Ok(Box::new(ScaledDrawingSurface::new(Box::new(mock), scale))); } #[cfg(all(target_os = "linux", any(target_arch = "arm", target_arch = "aarch64")))] @@ -1054,24 +1367,28 @@ pub fn create_surface(cfg: &MatrixConfig) -> Result, St } }; - match pipeline { + let base: Box = match pipeline { RenderPipeline::DirectSingle | RenderPipeline::DirectDouble => { let surf = DirectSurface::new(cfg, pipeline)?; - Ok(Box::new(surf)) + Box::new(surf) } RenderPipeline::CanvasSingle | RenderPipeline::CanvasDouble | RenderPipeline::Auto => { let surf = CanvasBufferedSurface::new(cfg, pipeline)?; - Ok(Box::new(surf)) + Box::new(surf) } - } + }; + let scale = cfg + .ui_scale + .resolve(base.physical_width(), base.physical_height()); + Ok(Box::new(ScaledDrawingSurface::new(base, scale))) } #[cfg(not(all(target_os = "linux", any(target_arch = "arm", target_arch = "aarch64"))))] { - let w = cfg.width * cfg.chain_length; - let h = cfg.height * cfg.parallel.clamp(1, 3); + let (w, h) = cfg.effective_physical_dimensions(); let mut mock = MockSurface::new(w, h); - mock.set_rotation((cfg.rotation % 4) as u8); - Ok(Box::new(mock)) + mock.set_rotation(normalize_rotation_code(cfg.rotation)); + let scale = cfg.ui_scale.resolve(w, h); + Ok(Box::new(ScaledDrawingSurface::new(Box::new(mock), scale))) } } diff --git a/src/core/orientation.rs b/src/core/orientation.rs index 1a222fa4..f48719f4 100644 --- a/src/core/orientation.rs +++ b/src/core/orientation.rs @@ -6,12 +6,32 @@ use crate::core::types::DisplayGeometry; /// Both emit the identical DisplayGeometry contract with monotonic versioning. pub struct OrientationManager { geometry: DisplayGeometry, + ui_scale: u32, } impl OrientationManager { pub fn new(physical_width: u32, physical_height: u32, initial_rotation: u8) -> Self { - let geometry = DisplayGeometry::new(physical_width, physical_height, initial_rotation, 1); - Self { geometry } + Self::new_with_scale(physical_width, physical_height, initial_rotation, 1) + } + + pub fn new_with_scale( + physical_width: u32, + physical_height: u32, + initial_rotation: u8, + ui_scale: u32, + ) -> Self { + let scale = ui_scale.clamp(1, 4); + let geometry = DisplayGeometry::new_scaled( + physical_width, + physical_height, + initial_rotation % 4, + scale, + 1, + ); + Self { + geometry, + ui_scale: scale, + } } #[inline] @@ -19,16 +39,41 @@ impl OrientationManager { &self.geometry } + #[inline] + pub fn ui_scale(&self) -> u32 { + self.ui_scale + } + + /// Updates active integer `ui_scale` factor (`1..=4`). Increments geometry version on change. + pub fn set_ui_scale(&mut self, ui_scale: u32) -> bool { + let scale = ui_scale.clamp(1, 4); + if self.ui_scale != scale { + self.ui_scale = scale; + let next_version = self.geometry.version.wrapping_add(1); + self.geometry = DisplayGeometry::new_scaled( + self.geometry.physical_width, + self.geometry.physical_height, + self.geometry.rotation, + scale, + if next_version == 0 { 1 } else { next_version }, + ); + true + } else { + false + } + } + /// Updates manual rotation setting (0: 0°, 1: 90°, 2: 180°, 3: 270°). /// Increments geometry version on change and returns true. pub fn set_rotation(&mut self, rotation: u8) -> bool { let normalized = rotation % 4; if self.geometry.rotation != normalized { let next_version = self.geometry.version.wrapping_add(1); - self.geometry = DisplayGeometry::new( + self.geometry = DisplayGeometry::new_scaled( self.geometry.physical_width, self.geometry.physical_height, normalized, + self.ui_scale, if next_version == 0 { 1 } else { next_version }, ); true @@ -41,10 +86,11 @@ impl OrientationManager { pub fn set_physical_dimensions(&mut self, width: u32, height: u32) -> bool { if self.geometry.physical_width != width || self.geometry.physical_height != height { let next_version = self.geometry.version.wrapping_add(1); - self.geometry = DisplayGeometry::new( + self.geometry = DisplayGeometry::new_scaled( width, height, self.geometry.rotation, + self.ui_scale, if next_version == 0 { 1 } else { next_version }, ); true diff --git a/src/core/types.rs b/src/core/types.rs index 3c7716f9..c83f20b7 100644 --- a/src/core/types.rs +++ b/src/core/types.rs @@ -576,11 +576,32 @@ pub struct DisplayGeometry { impl DisplayGeometry { pub fn new(physical_width: u32, physical_height: u32, rotation: u8, version: u64) -> Self { - let (logical_width, logical_height) = if rotation == 1 || rotation == 3 { + Self::new_scaled(physical_width, physical_height, rotation, 1, version) + } + + pub fn new_scaled( + physical_width: u32, + physical_height: u32, + rotation: u8, + ui_scale: u32, + version: u64, + ) -> Self { + let (nat_w, nat_h) = if rotation == 1 || rotation == 3 { (physical_height, physical_width) } else { (physical_width, physical_height) }; + let scale = ui_scale.max(1); + let logical_width = if scale <= 1 { + nat_w + } else { + (nat_w / scale).max(1) + }; + let logical_height = if scale <= 1 { + nat_h + } else { + (nat_h / scale).max(1) + }; let layout_class = Self::classify(logical_width, logical_height); @@ -605,6 +626,26 @@ impl DisplayGeometry { self.logical_height } + /// Native 1x rotated width (ignoring `ui_scale` division). + #[inline] + pub fn native_width(&self) -> u32 { + if self.rotation == 1 || self.rotation == 3 { + self.physical_height + } else { + self.physical_width + } + } + + /// Native 1x rotated height (ignoring `ui_scale` division). + #[inline] + pub fn native_height(&self) -> u32 { + if self.rotation == 1 || self.rotation == 3 { + self.physical_width + } else { + self.physical_height + } + } + #[inline] pub fn classify(width: u32, height: u32) -> LayoutClass { if width == height { diff --git a/src/engines/anime_showcase.rs b/src/engines/anime_showcase.rs index 986de86a..b8a1ae9c 100644 --- a/src/engines/anime_showcase.rs +++ b/src/engines/anime_showcase.rs @@ -62,8 +62,12 @@ impl Engine for AnimeShowcaseEngine { } fn on_display_geometry_changed(&mut self, geometry: &crate::core::types::DisplayGeometry) { - self.runner - .on_display_geometry_changed(geometry.width(), geometry.height()); + self.runner.on_display_geometry_changed_scaled( + geometry.native_width(), + geometry.native_height(), + geometry.width(), + geometry.height(), + ); } fn has_new_frame(&self) -> bool { diff --git a/src/engines/frontend_sync.rs b/src/engines/frontend_sync.rs index 510069c0..ead55035 100644 --- a/src/engines/frontend_sync.rs +++ b/src/engines/frontend_sync.rs @@ -534,19 +534,13 @@ fn spawn_ingame_showcase_request( let launch_started = Instant::now(); let (showcase_enabled, raw_server_url, mqtt_cfg, width, height, lang) = { let s = config.settings.read(); - let phys_w = s.matrix.width.saturating_mul(s.matrix.chain_length.max(1)); - let phys_h = s - .matrix - .height - .saturating_mul(s.matrix.parallel.clamp(1, 3)); - let rot = crate::app::normalize_rotation(s.matrix.rotation); - let geom = DisplayGeometry::new(phys_w, phys_h, rot, 0); + let (nat_w, nat_h) = s.matrix.effective_native_dimensions(); ( s.showcase.enabled, s.showcase.server_url.clone(), s.mqtt.clone(), - geom.width(), - geom.height(), + nat_w, + nat_h, if s.system.lang.is_empty() { "en".to_string() } else { @@ -1283,14 +1277,7 @@ pub fn build_cyan_sync_banner( ) -> crate::engines::message::MessagePayload { let (eff_w, eff_h) = { let s = config.settings.read(); - let phys_w = s.matrix.width.saturating_mul(s.matrix.chain_length.max(1)); - let phys_h = s - .matrix - .height - .saturating_mul(s.matrix.parallel.clamp(1, 3)); - let rot = crate::app::normalize_rotation(s.matrix.rotation); - let geom = DisplayGeometry::new(phys_w, phys_h, rot, 0); - (geom.width(), geom.height()) + s.matrix.effective_logical_dimensions() }; let char_count = clean_name.chars().count(); if eff_w >= 192 && eff_h >= 48 { @@ -1694,6 +1681,8 @@ pub struct InGameShowcaseEngine { stream_height: u32, surface_width: u32, surface_height: u32, + native_surface_width: u32, + native_surface_height: u32, has_stream: bool, pending_draw: bool, finished: bool, @@ -1719,6 +1708,8 @@ impl InGameShowcaseEngine { stream_height: 0, surface_width: 0, surface_height: 0, + native_surface_width: 0, + native_surface_height: 0, has_stream: false, pending_draw: false, finished: false, @@ -1841,6 +1832,8 @@ impl Engine for InGameShowcaseEngine { fn on_display_geometry_changed(&mut self, geometry: &DisplayGeometry) { self.surface_width = geometry.width(); self.surface_height = geometry.height(); + self.native_surface_width = geometry.native_width(); + self.native_surface_height = geometry.native_height(); self.gif_last_drawn_idx = None; self.player.invalidate_drawn_frame(); if !self.finished && self.stage_paused_at.is_none() { @@ -1856,6 +1849,8 @@ impl Engine for InGameShowcaseEngine { } self.surface_width = context.surface.width(); self.surface_height = context.surface.height(); + self.native_surface_width = context.surface.native_width(); + self.native_surface_height = context.surface.native_height(); if self.stage_paused_at.is_some() || self.player.is_paused() { self.pending_draw = false; return; @@ -2057,6 +2052,8 @@ impl Engine for InGameShowcaseEngine { fn render(&mut self, context: &mut EngineContext) { self.surface_width = context.surface.width(); self.surface_height = context.surface.height(); + self.native_surface_width = context.surface.native_width(); + self.native_surface_height = context.surface.native_height(); let snap = context.config.producer_snapshot.load(); match self.sub_stage { InGameSubStage::HallOfFame => { @@ -2081,15 +2078,16 @@ impl Engine for InGameShowcaseEngine { } InGameSubStage::ShowcaseStream => { if let Some(ref ig) = snap.ingame_showcase { + let native_surface = context.surface.unscaled(); if let Some(ref gif_data) = ig.offline_gif { SyncOfflineGifRenderer::render( - &mut *context.surface, + native_surface, gif_data.frames.as_slice(), self.gif_frame_idx, ); self.gif_last_drawn_idx = Some(self.gif_frame_idx); } else if let Some(ref stream) = ig.stream { - self.player.render_to_surface(stream, &mut *context.surface); + self.player.render_to_surface(stream, native_surface); } } } @@ -2101,12 +2099,20 @@ impl Engine for InGameShowcaseEngine { if self.sub_stage != InGameSubStage::ShowcaseStream { return true; } + let target_w = if self.native_surface_width > 0 { + self.native_surface_width + } else { + self.surface_width + }; + let target_h = if self.native_surface_height > 0 { + self.native_surface_height + } else { + self.surface_height + }; !self.has_stream || self.stream_width == 0 || self.stream_height == 0 - || (self.surface_width > 0 - && (self.stream_width != self.surface_width - || self.stream_height != self.surface_height)) + || (target_w > 0 && (self.stream_width != target_w || self.stream_height != target_h)) } fn has_new_frame(&self) -> bool { diff --git a/src/engines/gif.rs b/src/engines/gif.rs index 3f752c22..429edacd 100644 --- a/src/engines/gif.rs +++ b/src/engines/gif.rs @@ -521,7 +521,7 @@ impl GifEngine { } let (ref img, _) = self.frames[self.frame_index]; - matrix.draw_image(img, 0, 0); + matrix.unscaled().draw_image(img, 0, 0); self.last_drawn_index = Some(self.frame_index); true } @@ -532,7 +532,7 @@ impl GifEngine { pub fn redraw_current(&mut self, matrix: &mut dyn IDrawingSurface) { if let Some((ref img, _)) = self.frames.get(self.frame_index) { - matrix.draw_image(img, 0, 0); + matrix.unscaled().draw_image(img, 0, 0); self.last_drawn_index = Some(self.frame_index); } } @@ -544,8 +544,8 @@ impl Engine for GifEngine { context: &mut EngineContext, config: &dyn EngineConfig, ) -> Result<(), EngineError> { - self.target_width = context.surface.width(); - self.target_height = context.surface.height(); + self.target_width = context.surface.native_width(); + self.target_height = context.surface.native_height(); self.geometry = DisplayGeometry::new(self.target_width, self.target_height, 0, 0); self.apply_config(config); let playlists = self.playlists.clone(); @@ -574,8 +574,8 @@ impl Engine for GifEngine { } fn update(&mut self, context: &mut EngineContext) { - let w = context.surface.width(); - let h = context.surface.height(); + let w = context.surface.native_width(); + let h = context.surface.native_height(); if self.target_width != w || self.target_height != h { self.target_width = w; self.target_height = h; @@ -619,7 +619,7 @@ impl Engine for GifEngine { return; } let (ref img, _) = self.frames[self.frame_index]; - context.surface.draw_image(img, 0, 0); + context.surface.unscaled().draw_image(img, 0, 0); self.last_drawn_index = Some(self.frame_index); } @@ -634,8 +634,8 @@ impl Engine for GifEngine { fn on_display_geometry_changed(&mut self, geometry: &crate::core::types::DisplayGeometry) { let prev_tate = self.is_tate(); - self.target_width = geometry.logical_width; - self.target_height = geometry.logical_height; + self.target_width = geometry.native_width(); + self.target_height = geometry.native_height(); self.geometry = *geometry; if self.is_tate() != prev_tate { self.cached_scan_key = None; diff --git a/src/engines/movie_showcase.rs b/src/engines/movie_showcase.rs index 97351d37..aebe42ca 100644 --- a/src/engines/movie_showcase.rs +++ b/src/engines/movie_showcase.rs @@ -62,8 +62,12 @@ impl Engine for MovieShowcaseEngine { } fn on_display_geometry_changed(&mut self, geometry: &crate::core::types::DisplayGeometry) { - self.runner - .on_display_geometry_changed(geometry.width(), geometry.height()); + self.runner.on_display_geometry_changed_scaled( + geometry.native_width(), + geometry.native_height(), + geometry.width(), + geometry.height(), + ); } fn has_new_frame(&self) -> bool { diff --git a/src/engines/renderers/media_showcase.rs b/src/engines/renderers/media_showcase.rs index 041f262a..031ac07b 100644 --- a/src/engines/renderers/media_showcase.rs +++ b/src/engines/renderers/media_showcase.rs @@ -1933,6 +1933,8 @@ pub struct MediaShowcaseRunner { pub global_mqtt_port: u16, pub width: u32, pub height: u32, + pub card_width: u32, + pub card_height: u32, pub shared: Arc>, pub worker_busy: Arc, pub worker_gen: Arc, @@ -1975,14 +1977,18 @@ impl Drop for MediaShowcaseRunner { impl MediaShowcaseRunner { pub fn new(domain: ShowcaseDomain, width: u32, height: u32) -> Self { let now = Instant::now(); + let w = width.max(32); + let h = height.max(32); Self { domain, cfg: ShowcaseConfig::default(), system_lang: "fr".to_string(), global_mqtt_host: String::new(), global_mqtt_port: 1883, - width: width.max(32), - height: height.max(32), + width: w, + height: h, + card_width: w, + card_height: h, shared: Arc::new(Mutex::new(SharedShowcaseState::default())), worker_busy: Arc::new(AtomicBool::new(false)), worker_gen: Arc::new(AtomicU64::new(0)), @@ -2044,9 +2050,9 @@ impl MediaShowcaseRunner { if !self.cfg.show_synopsis || item.synopsis.is_empty() { return base_dur; } - let w = self.width as i32; - let h = self.height as i32; - let (pw, _) = compute_card_poster_dims(self.width, self.height); + let w = self.card_width as i32; + let h = self.card_height as i32; + let (pw, _) = compute_card_poster_dims(self.card_width, self.card_height); let box_w = if h > w || w == h { (w - 4).max(24) } else if self.cfg.show_poster && item.poster.is_some() { @@ -2094,6 +2100,8 @@ impl MediaShowcaseRunner { let lang = cfg.effective_lang(&self.system_lang).to_string(); let width = self.width; let height = self.height; + let card_width = self.card_width; + let card_height = self.card_height; let shared = Arc::clone(&self.shared); let busy = Arc::clone(&self.worker_busy); let worker_gen_arc = Arc::clone(&self.worker_gen); @@ -2110,6 +2118,8 @@ impl MediaShowcaseRunner { lang, width, height, + card_width, + card_height, global_host, global_port, shared, @@ -2123,6 +2133,8 @@ impl MediaShowcaseRunner { lang, width, height, + card_width, + card_height, shared, config_gen_arc, my_gen, @@ -2138,6 +2150,8 @@ impl MediaShowcaseRunner { lang: String, width: u32, height: u32, + card_width: u32, + card_height: u32, global_host: String, global_port: u16, shared: Arc>, @@ -2214,11 +2228,14 @@ impl MediaShowcaseRunner { let stream_state_topic = format!("dmd_showcase/clients/{}/stream_state", dmd_id); let config_topic = format!("dmd_showcase/clients/{}/config", dmd_id); + let (default_pw, default_ph) = compute_card_poster_dims(card_width, card_height); let mut domain_cfg = serde_json::Map::new(); domain_cfg.insert( slug.to_string(), serde_json::json!({ "lang": lang, + "poster_width": default_pw, + "poster_height": default_ph, "show_poster": cfg.show_poster, "show_synopsis": cfg.show_synopsis, "text_scroll_speed": cfg.text_scroll_speed, @@ -2261,7 +2278,6 @@ impl MediaShowcaseRunner { let http_client = crate::core::memory::stream_http_client(); let preload_in_flight = Arc::new(AtomicBool::new(false)); let pending_preload: Arc>> = Arc::new(Mutex::new(None)); - let (default_pw, default_ph) = compute_card_poster_dims(width, height); // Spawn a dedicated fast 4ms I/O pump thread for UDP `DMDF` packet reception and // immediate (< 4ms) outbound `start_card` / `start_stream` MQTT event dispatching. @@ -2676,6 +2692,8 @@ impl MediaShowcaseRunner { lang, width, height, + card_width, + card_height, shared, config_gen_arc, my_gen, @@ -2687,12 +2705,15 @@ impl MediaShowcaseRunner { worker_alive.store(false, Ordering::SeqCst); } + #[allow(clippy::too_many_arguments)] fn run_http_poll_worker( domain: ShowcaseDomain, cfg: ShowcaseConfig, lang: String, width: u32, height: u32, + card_width: u32, + card_height: u32, shared: Arc>, config_gen_arc: Arc, my_gen: u64, @@ -2703,7 +2724,7 @@ impl MediaShowcaseRunner { let base = resolved_base.trim_end_matches('/'); let slug = domain.as_api_slug(); let dmd_id = format_rpi_dmd_client_id(slug, width, height); - let (default_pw, default_ph) = compute_card_poster_dims(width, height); + let (default_pw, default_ph) = compute_card_poster_dims(card_width, card_height); // 1. Register client config (`POST /api/v1/{domain}/config`) let cfg_url = format!("{}/api/v1/{}/config", base, slug); @@ -2852,8 +2873,10 @@ impl MediaShowcaseRunner { } pub fn initialize(&mut self, context: &mut EngineContext, config: &dyn EngineConfig) { - self.width = context.surface.width().max(32); - self.height = context.surface.height().max(32); + self.width = context.surface.native_width().max(32); + self.height = context.surface.native_height().max(32); + self.card_width = context.surface.width().max(32); + self.card_height = context.surface.height().max(32); let showcase_settings = { let settings = context.config.settings.read(); self.system_lang = settings.system.lang.clone(); @@ -2899,12 +2922,30 @@ impl MediaShowcaseRunner { } pub fn on_display_geometry_changed(&mut self, width: u32, height: u32) { - let new_w = width.max(32); - let new_h = height.max(32); - if new_w != self.width || new_h != self.height { + self.on_display_geometry_changed_scaled(width, height, width, height); + } + + pub fn on_display_geometry_changed_scaled( + &mut self, + native_width: u32, + native_height: u32, + card_width: u32, + card_height: u32, + ) { + let new_w = native_width.max(32); + let new_h = native_height.max(32); + let new_cw = card_width.max(32); + let new_ch = card_height.max(32); + if new_w != self.width + || new_h != self.height + || new_cw != self.card_width + || new_ch != self.card_height + { let now = Instant::now(); self.width = new_w; self.height = new_h; + self.card_width = new_cw; + self.card_height = new_ch; let stopped_id = self.active_item.take().map(|it| it.id); self.phase = PlaybackPhase::Card; self.phase_started_at = now; @@ -3113,10 +3154,16 @@ impl MediaShowcaseRunner { self.spawn_background_sync(); } - let new_w = context.surface.width().max(32); - let new_h = context.surface.height().max(32); - if new_w != self.width || new_h != self.height { - self.on_display_geometry_changed(new_w, new_h); + let new_w = context.surface.native_width().max(32); + let new_h = context.surface.native_height().max(32); + let new_cw = context.surface.width().max(32); + let new_ch = context.surface.height().max(32); + if new_w != self.width + || new_h != self.height + || new_cw != self.card_width + || new_ch != self.card_height + { + self.on_display_geometry_changed_scaled(new_w, new_h, new_cw, new_ch); } if !self.turn_evaluated { @@ -3664,22 +3711,14 @@ impl MediaShowcaseRunner { let h = matrix.height() as i32; let phase_ms = self.phase_started_at.elapsed().as_millis(); - let eff_lang = self.cfg.effective_lang(&self.system_lang).to_string(); + let eff_lang = self.cfg.effective_lang(&self.system_lang); if self.active_item.is_none() { let effective_url = if self.cfg.enabled { self.cfg.server_url.as_str() } else { "" }; - render_waiting_pixel_art( - self.domain, - matrix, - w, - h, - phase_ms, - effective_url, - &eff_lang, - ); + render_waiting_pixel_art(self.domain, matrix, w, h, phase_ms, effective_url, eff_lang); self.dirty = false; return; } @@ -3698,7 +3737,8 @@ impl MediaShowcaseRunner { .cloned(); if let Some(stream) = stream_opt { if !stream.is_empty() { - self.stream_player.render_to_surface(&stream, matrix); + self.stream_player + .render_to_surface(&stream, matrix.unscaled()); } } else { let live_frame = { @@ -3706,12 +3746,13 @@ impl MediaShowcaseRunner { guard.live_udp_frame.clone() }; if let Some(frame) = live_frame { - let fw = (frame.width() as i32).min(w); - let fh = (frame.height() as i32).min(h); + let native_matrix = matrix.unscaled(); + let fw = (frame.width() as i32).min(native_matrix.width() as i32); + let fh = (frame.height() as i32).min(native_matrix.height() as i32); for py in 0..fh { for px in 0..fw { let p = frame.get_pixel(px as u32, py as u32).0; - matrix.set_pixel(px, py, p[0], p[1], p[2]); + native_matrix.set_pixel(px, py, p[0], p[1], p[2]); } } } else { @@ -3723,7 +3764,7 @@ impl MediaShowcaseRunner { h, phase_ms, &self.cfg.server_url, - &eff_lang, + eff_lang, ); } } diff --git a/src/engines/renderers/weather_page.rs b/src/engines/renderers/weather_page.rs index 40df6c30..6c245708 100644 --- a/src/engines/renderers/weather_page.rs +++ b/src/engines/renderers/weather_page.rs @@ -345,4 +345,7 @@ impl crate::core::matrix::IDrawingSurface for SlideCanvas<'_> { fn is_dirty(&self) -> bool { true } + fn unscaled(&mut self) -> &mut dyn crate::core::matrix::IDrawingSurface { + self + } } diff --git a/src/engines/retro_games.rs b/src/engines/retro_games.rs index 17e6501e..a9e12418 100644 --- a/src/engines/retro_games.rs +++ b/src/engines/retro_games.rs @@ -63,8 +63,12 @@ impl Engine for RetroGamesEngine { } fn on_display_geometry_changed(&mut self, geometry: &crate::core::types::DisplayGeometry) { - self.runner - .on_display_geometry_changed(geometry.width(), geometry.height()); + self.runner.on_display_geometry_changed_scaled( + geometry.native_width(), + geometry.native_height(), + geometry.width(), + geometry.height(), + ); } fn has_new_frame(&self) -> bool { diff --git a/src/engines/series_showcase.rs b/src/engines/series_showcase.rs index 0a1f6cb4..9180e726 100644 --- a/src/engines/series_showcase.rs +++ b/src/engines/series_showcase.rs @@ -62,8 +62,12 @@ impl Engine for SeriesShowcaseEngine { } fn on_display_geometry_changed(&mut self, geometry: &crate::core::types::DisplayGeometry) { - self.runner - .on_display_geometry_changed(geometry.width(), geometry.height()); + self.runner.on_display_geometry_changed_scaled( + geometry.native_width(), + geometry.native_height(), + geometry.width(), + geometry.height(), + ); } fn has_new_frame(&self) -> bool { diff --git a/tests/test_matrix.rs b/tests/test_matrix.rs index 95b4fa2b..adbcb121 100644 --- a/tests/test_matrix.rs +++ b/tests/test_matrix.rs @@ -76,3 +76,437 @@ fn test_mock_matrix_rotations() { let px3 = matrix.canvas.get_pixel(10, 26); assert_eq!(px3[0], 50); } + +fn phys_pixel(surface: &mut dyn IDrawingSurface, x: u32, y: u32) -> [u8; 3] { + let cv = surface + .unscaled() + .acquire_canvas() + .expect("MockSurface always provides CanvasView"); + let idx = (y as usize) * cv.stride_bytes + (x as usize) * 3; + [cv.data[idx], cv.data[idx + 1], cv.data[idx + 2]] +} + +#[test] +fn test_ui_scale_auto_preserves_strict_1x_across_all_standard_and_tate_resolutions() { + use arcadematrix::core::config::{MatrixConfig, UiScale}; + use arcadematrix::core::matrix::{normalize_rotation_code, ScaledDrawingSurface}; + use arcadematrix::core::orientation::OrientationManager; + + let standard_and_tate = [ + (64, 32), + (32, 64), + (64, 64), + (128, 32), + (32, 128), + (128, 64), + (64, 128), + (256, 64), + (64, 256), + (128, 128), + ]; + + for &(w, h) in &standard_and_tate { + assert_eq!( + UiScale::Auto.resolve(w, h), + 1, + "UiScale::Auto MUST remain strictly 1x for {}x{}", + w, + h + ); + + let mut cfg = MatrixConfig::default(); + cfg.width = w; + cfg.height = h; + cfg.chain_length = 1; + cfg.parallel = 1; + cfg.ui_scale = UiScale::Auto; + + assert_eq!(cfg.resolve_ui_scale(), 1); + assert_eq!(cfg.effective_native_dimensions(), (w, h)); + assert_eq!(cfg.effective_logical_dimensions(), (w, h)); + + let om = OrientationManager::new_with_scale(w, h, 0, cfg.resolve_ui_scale()); + assert_eq!(om.geometry().width(), w); + assert_eq!(om.geometry().height(), h); + assert_eq!(om.geometry().native_width(), w); + assert_eq!(om.geometry().native_height(), h); + + // Compare ScaledDrawingSurface(scale=1) pixel-for-pixel against bare MockSurface + let mut bare = MockSurface::new(w, h); + let mut scaled = ScaledDrawingSurface::new(Box::new(MockSurface::new(w, h)), 1); + + assert_eq!(scaled.ui_scale(), 1); + assert_eq!(scaled.width(), w); + assert_eq!(scaled.height(), h); + assert_eq!(scaled.native_width(), w); + assert_eq!(scaled.native_height(), h); + assert!( + scaled.has_canvas(), + "1x ScaledDrawingSurface must expose underlying CanvasView for {}x{}", + w, + h + ); + { + let cv = scaled + .acquire_canvas() + .expect("1x ScaledDrawingSurface must provide CanvasView"); + assert_eq!(cv.width, w); + assert_eq!(cv.height, h); + } + bare.present(); + scaled.present(); + assert!(!scaled.is_dirty()); + assert_eq!(scaled.dirty_row_span(), None); + + let probes = [ + (0, 0, 255, 10, 20), + ((w as i32) - 1, 0, 30, 240, 50), + (0, (h as i32) - 1, 60, 70, 250), + ((w as i32) - 1, (h as i32) - 1, 200, 180, 90), + ((w as i32) / 2, (h as i32) / 2, 123, 222, 45), + ]; + for &(px, py, r, g, b) in &probes { + bare.set_pixel(px, py, r, g, b); + scaled.set_pixel(px, py, r, g, b); + } + bare.fill_rect(3, 2, 5, 4, 17, 88, 199); + scaled.fill_rect(3, 2, 5, 4, 17, 88, 199); + assert!(scaled.is_dirty()); + assert_eq!(scaled.dirty_row_span(), bare.dirty_row_span()); + + let scaled_bytes = scaled.acquire_canvas().unwrap().data.to_vec(); + assert_eq!( + scaled_bytes.as_slice(), + bare.canvas.as_raw().as_slice(), + "1x ScaledDrawingSurface altered pixels on {}x{}", + w, + h + ); + } + + // Also verify rotated TATE configurations (rotation = 90 and 270) on 128x32 and 256x64 + for &(phys_w, phys_h, rot_deg, exp_w, exp_h) in &[ + (128u32, 32u32, 90u32, 32u32, 128u32), + (128u32, 32u32, 270u32, 32u32, 128u32), + (256u32, 64u32, 90u32, 64u32, 256u32), + (256u32, 64u32, 270u32, 64u32, 256u32), + ] { + let mut cfg = MatrixConfig::default(); + cfg.width = phys_w; + cfg.height = phys_h; + cfg.chain_length = 1; + cfg.parallel = 1; + cfg.rotation = rot_deg; + cfg.ui_scale = UiScale::Auto; + + assert_eq!(cfg.resolve_ui_scale(), 1); + assert_eq!(cfg.effective_native_dimensions(), (exp_w, exp_h)); + assert_eq!(cfg.effective_logical_dimensions(), (exp_w, exp_h)); + + let mut mock = MockSurface::new(phys_w, phys_h); + mock.set_rotation(normalize_rotation_code(rot_deg)); + let mut surf = ScaledDrawingSurface::new(Box::new(mock), cfg.resolve_ui_scale()); + assert_eq!(surf.ui_scale(), 1); + assert_eq!(surf.width(), exp_w); + assert_eq!(surf.height(), exp_h); + surf.present(); + surf.set_pixel(4, 9, 210, 110, 55); + assert!(surf.is_dirty()); + surf.present(); + assert!(!surf.is_dirty()); + } +} + +#[test] +fn test_ui_scale_giant_led_walls_nearest_neighbor_and_dirty_bounds() { + use arcadematrix::core::config::UiScale; + use arcadematrix::core::matrix::ScaledDrawingSurface; + + // Auto scaling thresholds: triggers ONLY when min >= 128 && max >= 192 + assert_eq!(UiScale::Auto.resolve(256, 192), 2); + assert_eq!(UiScale::Auto.resolve(192, 256), 2); + assert_eq!(UiScale::Auto.resolve(384, 288), 3); + assert_eq!(UiScale::Auto.resolve(288, 384), 3); + assert_eq!(UiScale::Auto.resolve(512, 384), 4); + assert_eq!(UiScale::Auto.resolve(384, 512), 4); + + // 256x192 at Auto (2x -> logical 128x96) + let mut surf = ScaledDrawingSurface::new( + Box::new(MockSurface::new(256, 192)), + UiScale::Auto.resolve(256, 192), + ); + assert_eq!(surf.ui_scale(), 2); + assert_eq!(surf.width(), 128); + assert_eq!(surf.height(), 96); + assert_eq!(surf.native_width(), 256); + assert_eq!(surf.native_height(), 192); + assert!(!surf.has_canvas()); + + surf.present(); + assert!(!surf.is_dirty()); + assert_eq!(surf.dirty_row_span(), None); + + // Single logical pixel (10, 7) -> exact 2x2 block at physical [20..22, 14..16] + surf.set_pixel(10, 7, 250, 120, 40); + assert!(surf.is_dirty()); + assert_eq!(surf.dirty_row_span(), Some((14, 15))); + + for py in 14..16 { + for px in 20..22 { + assert_eq!(phys_pixel(&mut surf, px, py), [250, 120, 40]); + } + } + assert_eq!(phys_pixel(&mut surf, 19, 14), [0, 0, 0]); + assert_eq!(phys_pixel(&mut surf, 22, 15), [0, 0, 0]); + assert_eq!(phys_pixel(&mut surf, 20, 13), [0, 0, 0]); + assert_eq!(phys_pixel(&mut surf, 20, 16), [0, 0, 0]); + + surf.present(); + assert!(!surf.is_dirty()); + assert_eq!(surf.dirty_row_span(), None); + + // Manual 3x on 256x192 -> logical 85x64 + surf.set_ui_scale(3); + assert_eq!(surf.ui_scale(), 3); + assert_eq!(surf.width(), 85); + assert_eq!(surf.height(), 64); + + // 512x384 at Auto (4x -> logical 128x96) + let mut wall_4x = ScaledDrawingSurface::new( + Box::new(MockSurface::new(512, 384)), + UiScale::Auto.resolve(512, 384), + ); + assert_eq!(wall_4x.ui_scale(), 4); + assert_eq!(wall_4x.width(), 128); + assert_eq!(wall_4x.height(), 96); + wall_4x.present(); + wall_4x.fill_rect(2, 3, 2, 1, 12, 234, 56); + assert_eq!(wall_4x.dirty_row_span(), Some((12, 15))); + for py in 12..16 { + for px in 8..16 { + assert_eq!(phys_pixel(&mut wall_4x, px, py), [12, 234, 56]); + } + } + assert_eq!(phys_pixel(&mut wall_4x, 7, 12), [0, 0, 0]); + assert_eq!(phys_pixel(&mut wall_4x, 16, 15), [0, 0, 0]); +} + +#[test] +fn test_pixel_mapper_folding_and_config_serde() { + use arcadematrix::core::config::{MatrixConfig, UiScale}; + + // 1. 8 chained 64x32 panels with U-mapper (parallel=1) -> 256x64 physical -> stays 1x! + let cfg_256x64: MatrixConfig = serde_json::from_str( + r#"{ + "width": 64, + "height": 32, + "chain_length": 8, + "parallel": 1, + "pixel_mapper": "U-mapper", + "ui_scale": "auto" + }"#, + ) + .expect("valid MatrixConfig JSON"); + assert_eq!(cfg_256x64.effective_physical_dimensions(), (256, 64)); + assert_eq!(cfg_256x64.resolve_ui_scale(), 1); + assert_eq!(cfg_256x64.effective_logical_dimensions(), (256, 64)); + + // 2. 8x3 = 24 panels of 64x32 with U-mapper (chain=8, parallel=3) -> 256x192 -> Auto 2x (128x96) + let cfg_256x192: MatrixConfig = serde_json::from_str( + r#"{ + "width": 64, + "height": 32, + "chain_length": 8, + "parallel": 3, + "pixel_mapper": "U-mapper", + "ui_scale": "auto" + }"#, + ) + .expect("valid MatrixConfig JSON"); + assert_eq!(cfg_256x192.effective_physical_dimensions(), (256, 192)); + assert_eq!(cfg_256x192.resolve_ui_scale(), 2); + assert_eq!(cfg_256x192.effective_logical_dimensions(), (128, 96)); + + // 3. V-mapper on 4 chained 64x32 panels (parallel=1) -> 64x128 TATE -> stays 1x! + let cfg_vmapper: MatrixConfig = serde_json::from_str( + r#"{ + "width": 64, + "height": 32, + "chain_length": 4, + "parallel": 1, + "pixel_mapper": "V-mapper" + }"#, + ) + .expect("valid MatrixConfig JSON"); + assert_eq!(cfg_vmapper.effective_physical_dimensions(), (64, 128)); + assert_eq!(cfg_vmapper.resolve_ui_scale(), 1); + assert_eq!(cfg_vmapper.effective_logical_dimensions(), (64, 128)); + + // 4. Flexible UiScale deserialization ("2", "2x", integer 2, unknown -> Auto) + let s_num: UiScale = serde_json::from_str("2").unwrap(); + let s_str: UiScale = serde_json::from_str(r#""2x""#).unwrap(); + let s_fallback: UiScale = serde_json::from_str(r#""invalid""#).unwrap(); + assert_eq!(s_num, UiScale::Scale2x); + assert_eq!(s_str, UiScale::Scale2x); + assert_eq!(s_fallback, UiScale::Auto); + assert_eq!(serde_json::to_string(&s_num).unwrap(), r#""2""#); +} + +#[test] +fn test_gif_and_showcase_stream_stay_native_1x_while_showcase_card_upscales() { + use arcadematrix::core::config::Config; + use arcadematrix::core::dmd_stream::PreloadedDmdStream; + use arcadematrix::core::engine_contract::{Engine, EngineContext, HashConfig}; + use arcadematrix::core::matrix::ScaledDrawingSurface; + use arcadematrix::engines::gif::GifEngine; + use arcadematrix::engines::renderers::media_showcase::{ + MediaShowcaseRunner, PlaybackPhase, PreparedShowcaseItem, ShowcaseDomain, + }; + use image::codecs::gif::{GifEncoder, Repeat}; + use image::{Delay, Frame, Rgba, RgbaImage}; + use std::collections::HashMap; + use std::sync::Arc; + use std::time::{Duration, Instant}; + + let temp_dir = tempfile::tempdir().expect("tempdir"); + let cfg_path = temp_dir.path().join("config.json"); + let _ = std::fs::copy("config.json", &cfg_path); + let config = Config::new(&cfg_path); + + // Giant 256x192 LED wall with 2x UI scale (logical 128x96, native 256x192) + let mut scaled_surface = ScaledDrawingSurface::new(Box::new(MockSurface::new(256, 192)), 2); + assert_eq!(scaled_surface.width(), 128); + assert_eq!(scaled_surface.height(), 96); + assert_eq!(scaled_surface.native_width(), 256); + assert_eq!(scaled_surface.native_height(), 192); + + // Part A: GifEngine MUST decode & render at native 1x full-screen (256x192) + let gif_path = temp_dir.path().join("native_wall.gif"); + { + let mut rgba = RgbaImage::from_pixel(256, 192, Rgba([0, 0, 0, 255])); + // Put distinct fine-grained 1px neighbors at (0, 0) = Red and (1, 0) = Blue + rgba.put_pixel(0, 0, Rgba([255, 0, 0, 255])); + rgba.put_pixel(1, 0, Rgba([0, 0, 255, 255])); + rgba.put_pixel(255, 191, Rgba([0, 255, 0, 255])); + let file = std::fs::File::create(&gif_path).expect("create gif"); + let mut encoder = GifEncoder::new(file); + encoder.set_repeat(Repeat::Infinite).unwrap(); + let frame = Frame::from_parts(rgba, 0, 0, Delay::from_numer_denom_ms(100, 1)); + encoder.encode_frame(frame).unwrap(); + } + + let empty_map = HashMap::new(); + let hash_cfg = HashConfig { data: &empty_map }; + let mut gif_engine = GifEngine::new(64, 32); + { + let mut ctx = EngineContext { + surface: &mut scaled_surface, + config: &config, + }; + gif_engine.initialize(&mut ctx, &hash_cfg).unwrap(); + assert!(gif_engine.load_gif(&gif_path)); + gif_engine.render(&mut ctx); + } + assert_eq!(phys_pixel(&mut scaled_surface, 0, 0), [255, 0, 0]); + assert_eq!( + phys_pixel(&mut scaled_surface, 1, 0), + [0, 0, 255], + "GifEngine must render at native 1x (1px precision), not 2x block-upscaled" + ); + assert_eq!(phys_pixel(&mut scaled_surface, 255, 191), [0, 255, 0]); + + // Part B: MediaShowcaseRunner Phase 1 Card upscales (2x) while Phase 2 LiveStream stays native 1x! + scaled_surface.clear(); + let mut runner = MediaShowcaseRunner::new(ShowcaseDomain::Games, 128, 32); + { + let mut ctx = EngineContext { + surface: &mut scaled_surface, + config: &config, + }; + let mut showcase_map = HashMap::new(); + showcase_map.insert("enabled".to_string(), "false".to_string()); + let sc_cfg = HashConfig { + data: &showcase_map, + }; + runner.initialize(&mut ctx, &sc_cfg); + } + assert_eq!(runner.width, 256); + assert_eq!(runner.height, 192); + assert_eq!(runner.card_width, 128); + assert_eq!(runner.card_height, 96); + assert!( + runner.dmd_client_id().ends_with("_games_256x192"), + "Showcase client_id must advertise native 256x192 stream resolution, got {}", + runner.dmd_client_id() + ); + + // Prepare an item with a 4x96 poster (green at (0, 0)) + a 256x192 native stream + let mut poster = RgbImage::new(4, 96); + poster.put_pixel(0, 0, Rgb([0, 255, 0])); + let mut raw_stream = vec![0u8; 256 * 192 * 2]; + // Native pixel (0, 0) = Pure Red RGB565 (0xF800), (1, 0) = Pure Blue RGB565 (0x001F) + raw_stream[0..2].copy_from_slice(&0xF800u16.to_le_bytes()); + raw_stream[2..4].copy_from_slice(&0x001Fu16.to_le_bytes()); + let stream_arc = Arc::new(PreloadedDmdStream::from_raw_rgb565_le( + 256, + 192, + 1, + Duration::from_millis(66), + raw_stream, + )); + + runner.turn_evaluated = true; + runner.phase = PlaybackPhase::Card; + runner.phase_started_at = Instant::now(); + runner.active_item = Some(PreparedShowcaseItem { + id: "pkg_games_testwall".to_string(), + title: "METAL SLUG".to_string(), + year: "1996".to_string(), + badge: "NEOGEO".to_string(), + badge_rgb: (255, 80, 0), + subtitle: "SNK".to_string(), + rating: "9.5".to_string(), + synopsis: "Run and gun classic.".to_string(), + poster: Some(poster), + has_stream: true, + stream_duration_s: 4.0, + stream_fps: 15, + http_stream: Some(Arc::clone(&stream_arc)), + http_frame_delay: Duration::from_millis(66), + }); + + // Render Phase 1 Card -> logical (0, 0) green pixel MUST expand to a 2x2 block at [0..2, 0..2] + { + let mut ctx = EngineContext { + surface: &mut scaled_surface, + config: &config, + }; + runner.render(&mut ctx); + } + assert_eq!(phys_pixel(&mut scaled_surface, 0, 0), [0, 255, 0]); + assert_eq!( + phys_pixel(&mut scaled_surface, 1, 0), + [0, 255, 0], + "Phase 1 Intro Card must benefit from 2x Nearest-Neighbor upscaling on 256x192" + ); + assert_eq!(phys_pixel(&mut scaled_surface, 0, 1), [0, 255, 0]); + assert_eq!(phys_pixel(&mut scaled_surface, 1, 1), [0, 255, 0]); + + // Switch to Phase 2 LiveStream -> native 256x192 stream MUST render 1:1 without 2x expansion + scaled_surface.clear(); + runner.phase = PlaybackPhase::LiveStream; + runner.stream_player.start(Instant::now()); + { + let mut ctx = EngineContext { + surface: &mut scaled_surface, + config: &config, + }; + runner.render(&mut ctx); + } + assert_eq!(phys_pixel(&mut scaled_surface, 0, 0), [255, 0, 0]); + assert_eq!( + phys_pixel(&mut scaled_surface, 1, 0), + [0, 0, 255], + "Phase 2 LiveStream video/panoramas must render at native 1x full-screen on 256x192" + ); +} diff --git a/tests/test_v16_final_locked.rs b/tests/test_v16_final_locked.rs index a830e8f1..d482d5c0 100644 --- a/tests/test_v16_final_locked.rs +++ b/tests/test_v16_final_locked.rs @@ -1664,3 +1664,71 @@ fn test_ingame_offline_rgb888_gif_10000_frames_zero_allocation_proof() { deallocs ); } + +#[test] +fn test_scaled_drawing_surface_10000_frames_zero_allocation_proof() { + use arcadematrix::core::config::UiScale; + use arcadematrix::core::matrix::{IDrawingSurface, ScaledDrawingSurface}; + + let mut wall_2x = ScaledDrawingSurface::new( + Box::new(MockSurface::new(256, 192)), + UiScale::Auto.resolve(256, 192), + ); + let mut wall_4x = ScaledDrawingSurface::new( + Box::new(MockSurface::new(512, 384)), + UiScale::Auto.resolve(512, 384), + ); + assert_eq!(wall_2x.ui_scale(), 2); + assert_eq!(wall_4x.ui_scale(), 4); + + let native_strip = [0xF800u16, 0x07E0u16, 0x001Fu16, 0xFFFFu16]; + + // Warmup before arming allocator tracker + wall_2x.clear(); + wall_2x.set_pixel(10, 10, 255, 128, 0); + wall_2x.fill_rect(4, 4, 8, 6, 20, 180, 240); + wall_2x.unscaled().blit565(&native_strip, 0, 0, 4, 1, None); + wall_2x.present(); + + wall_4x.clear(); + wall_4x.set_pixel(20, 15, 0, 255, 128); + wall_4x.fill_rect(2, 2, 6, 4, 240, 60, 120); + wall_4x.unscaled().blit565(&native_strip, 0, 0, 4, 1, None); + wall_4x.present(); + + THREAD_ALLOC_COUNT.with(|c| c.set(0)); + THREAD_DEALLOC_COUNT.with(|c| c.set(0)); + THREAD_TRACKING.with(|t| t.set(true)); + + for i in 0..10_000i32 { + let lx = i % 120; + let ly = (i / 120) % 90; + wall_2x.set_pixel(lx, ly, 200, 100, 50); + wall_2x.fill_rect(lx, ly, 3, 2, 40, 160, 250); + wall_2x + .unscaled() + .blit565(&native_strip, lx * 2, ly * 2, 4, 1, None); + wall_2x.present(); + + wall_4x.set_pixel(lx, ly, 50, 220, 140); + wall_4x.fill_rect(lx, ly, 2, 2, 255, 90, 30); + wall_4x + .unscaled() + .blit565(&native_strip, lx * 4, ly * 4, 4, 1, None); + wall_4x.present(); + } + + THREAD_TRACKING.with(|t| t.set(false)); + let allocs = THREAD_ALLOC_COUNT.with(|c| c.get()); + let deallocs = THREAD_DEALLOC_COUNT.with(|c| c.get()); + assert_eq!( + allocs, 0, + "ScaledDrawingSurface H-Core hot-path performed {} heap allocations across 10,000 frames!", + allocs + ); + assert_eq!( + deallocs, 0, + "ScaledDrawingSurface H-Core hot-path performed {} heap deallocations across 10,000 frames!", + deallocs + ); +} From d207562dc725ea4349b685a13fd0597d21c1ccd6 Mon Sep 17 00:00:00 2001 From: red77290 <23342613+red77290@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:09:48 +0000 Subject: [PATCH 3/4] fix(frontend-sync,matrix): harden offline marquee cache, streaming gif memory, and native marquee scaling --- api/www/js/app.js | 8 +++- docs/ARCHITECTURE.md | 2 +- docs/ARCHITECTURE_ES.md | 2 +- docs/ARCHITECTURE_FR.md | 2 +- docs/DEVELOPER.md | 2 +- docs/DEVELOPER_ES.md | 2 +- docs/DEVELOPER_FR.md | 2 +- src/core/config.rs | 6 +-- src/core/dmd_cache.rs | 63 +++++++++++++++++++------- src/core/registry.rs | 15 +++++++ src/core/runtime.rs | 10 +---- src/engines/frontend_sync.rs | 8 ++++ src/engines/gif.rs | 87 +++++++++++++++++++++++++----------- src/engines/marquee.rs | 43 +++++++++++------- 14 files changed, 174 insertions(+), 78 deletions(-) diff --git a/api/www/js/app.js b/api/www/js/app.js index f3fb2079..d71876cc 100644 --- a/api/www/js/app.js +++ b/api/www/js/app.js @@ -1537,10 +1537,14 @@ async function initSettings() { }; try { - await API.post('/api/system', { matrix }); + const res = await API.post('/api/system', { matrix }); if (window.__sysConfig) window.__sysConfig.matrix = matrix; window.invalidateCachedEndpoint?.('/api/themes'); - window.showToast('Hardware settings saved! The panel will restart to apply physical bus changes.', 'success'); + if (res && res.status === 'rebooting') { + window.showToast('Hardware settings saved! The panel will restart to apply physical bus changes.', 'success'); + } else { + window.showToast('Display settings saved and applied live!', 'success'); + } } catch (e) { window.showToast('Failed to save HW settings', 'error'); } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1c3bb8a6..db01400a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -660,7 +660,7 @@ pub trait IDrawingSurface: Send + Sync { fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); - fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); diff --git a/docs/ARCHITECTURE_ES.md b/docs/ARCHITECTURE_ES.md index abbe3104..f167c2ff 100644 --- a/docs/ARCHITECTURE_ES.md +++ b/docs/ARCHITECTURE_ES.md @@ -660,7 +660,7 @@ pub trait IDrawingSurface: Send + Sync { fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); - fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); diff --git a/docs/ARCHITECTURE_FR.md b/docs/ARCHITECTURE_FR.md index addd7b62..f8e57186 100644 --- a/docs/ARCHITECTURE_FR.md +++ b/docs/ARCHITECTURE_FR.md @@ -660,7 +660,7 @@ pub trait IDrawingSurface: Send + Sync { fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); - fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); diff --git a/docs/DEVELOPER.md b/docs/DEVELOPER.md index 205238fb..72f1ac02 100644 --- a/docs/DEVELOPER.md +++ b/docs/DEVELOPER.md @@ -636,7 +636,7 @@ pub trait IDrawingSurface: Send + Sync { fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); - fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); diff --git a/docs/DEVELOPER_ES.md b/docs/DEVELOPER_ES.md index f7be63ee..fc1922b6 100644 --- a/docs/DEVELOPER_ES.md +++ b/docs/DEVELOPER_ES.md @@ -628,7 +628,7 @@ pub trait IDrawingSurface: Send + Sync { fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); - fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); diff --git a/docs/DEVELOPER_FR.md b/docs/DEVELOPER_FR.md index 591e117b..0a2054bf 100644 --- a/docs/DEVELOPER_FR.md +++ b/docs/DEVELOPER_FR.md @@ -636,7 +636,7 @@ pub trait IDrawingSurface: Send + Sync { fn set_rotation(&mut self, rotation: u8); fn rotation(&self) -> u8; fn set_pixel(&mut self, x: i32, y: i32, red: u8, green: u8, blue: u8); - fn fill_rect(&mut self, x: i32, y: i32, w: u32, h: u32, red: u8, green: u8, blue: u8); + fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32, red: u8, green: u8, blue: u8); fn clear(&mut self); fn present(&mut self); fn set_brightness(&mut self, brightness: u8); diff --git a/src/core/config.rs b/src/core/config.rs index ed67d793..31f01bf8 100644 --- a/src/core/config.rs +++ b/src/core/config.rs @@ -578,11 +578,7 @@ impl MatrixConfig { }; if name.eq_ignore_ascii_case("u-mapper") { if chain >= 2 && chain % 2 == 0 { - w = if w >= 64 { - (w / 64).saturating_mul(32) - } else { - (w / 2).max(1) - }; + w = (w / 2).max(1); h = h.saturating_mul(2); } } else if name.eq_ignore_ascii_case("v-mapper") { diff --git a/src/core/dmd_cache.rs b/src/core/dmd_cache.rs index f4973b30..c21447c3 100644 --- a/src/core/dmd_cache.rs +++ b/src/core/dmd_cache.rs @@ -175,10 +175,6 @@ impl DmdCache { pub fn get_cached_path(&self, system: &str, game: &str) -> Option { let safe_sys = sanitize_cache_component(system); let safe_game = sanitize_cache_component(game); - let key = format!("{}/{}", safe_sys, safe_game); - if self.negative_cache.lock().contains(&key) { - return None; - } for ext in &[".png", ".gif", ".bmp"] { let local_filename = format!("{}_{}{}", safe_sys, safe_game, ext); @@ -288,6 +284,10 @@ impl DmdCache { game: &str, title: Option<&str>, ) -> Option { + if let Some(existing) = self.get_cached_path(system, game) { + return Some(existing); + } + let safe_sys = sanitize_cache_component(system); let safe_game = sanitize_cache_component(game); let key = format!("{}/{}", safe_sys, safe_game); @@ -295,10 +295,6 @@ impl DmdCache { return None; } - if let Some(existing) = self.get_cached_path(system, game) { - return Some(existing); - } - let primary_folder = map_system_to_pixelcade_folder(system); let secondary_folder = get_secondary_pixelcade_folder(system); @@ -418,10 +414,6 @@ impl DmdCache { pub fn get_cached_system_path(&self, system: &str) -> Option { let safe_sys = sanitize_cache_component(system); - let key = format!("system/{}", safe_sys); - if self.negative_cache.lock().contains(&key) { - return None; - } for ext in &[".png", ".gif", ".bmp"] { let candidate = self.cache_dir.join(format!("system_{}{}", safe_sys, ext)); @@ -433,16 +425,16 @@ impl DmdCache { } pub fn download_system_marquee(&self, system: &str) -> Option { + if let Some(path) = self.get_cached_system_path(system) { + return Some(path); + } + let safe_sys = sanitize_cache_component(system); let key = format!("system/{}", safe_sys); if self.negative_cache.lock().contains(&key) { return None; } - if let Some(path) = self.get_cached_system_path(system) { - return Some(path); - } - let variants = get_system_name_variants_mapped(&self.system_mappings, system); let local_prefix = format!("system_{}", safe_sys); @@ -2135,4 +2127,43 @@ mod tests { let _ = fs::remove_dir_all(&tmp_dir); } + + #[test] + fn test_offline_pixelcade_marquee_overrides_stale_negative_cache() { + let tmp_root = std::env::temp_dir().join(format!( + "arcadematrix_dmd_cache_offline_override_{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&tmp_root); + let marquees_dir = tmp_root.join("marquees"); + let cat_dir = marquees_dir.join("_catalog"); + fs::create_dir_all(&cat_dir).unwrap(); + fs::write(cat_dir.join("snes.txt"), "Chrono Trigger (USA).png\n").unwrap(); + fs::write(cat_dir.join("nintendo_super_famicom.txt"), "").unwrap(); + + let cache = DmdCache::new(&marquees_dir); + // 1. First lookup misses catalog and records key in `.negative_cache_v2` + assert!(cache + .download_marquee_with_title("snes", "smw_hack", None) + .is_none()); + assert!(cache.is_negative_cached("snes", "smw_hack")); + + // 2. User later copies an Offline Showcase/Pixelcade pack onto SD (`pixelcade/snes/smw_hack.png`) + let px_dir = tmp_root.join("pixelcade").join("snes"); + fs::create_dir_all(&px_dir).unwrap(); + let offline_png = px_dir.join("smw_hack.png"); + fs::write(&offline_png, b"PNG_STUB").unwrap(); + + // Both `get_cached_path` and `download_marquee_with_title` must immediately resolve the local file! + assert_eq!( + cache.get_cached_path("snes", "smw_hack"), + Some(offline_png.clone()) + ); + assert_eq!( + cache.download_marquee_with_title("snes", "smw_hack", None), + Some(offline_png) + ); + + let _ = fs::remove_dir_all(&tmp_root); + } } diff --git a/src/core/registry.rs b/src/core/registry.rs index d8e80ce4..f645a060 100644 --- a/src/core/registry.rs +++ b/src/core/registry.rs @@ -247,6 +247,21 @@ impl EngineRuntime { entry.engine.as_mut() } + /// Broadcasts display geometry updates (`ui_scale` or TATE orientation) to all initialized + /// engine instances (both active and cached `KeepWarm` off-screen instances) with zero heap allocation. + pub fn broadcast_display_geometry_changed( + &mut self, + geometry: &crate::core::types::DisplayGeometry, + ) { + for slot in self.id_to_registered.iter_mut().flatten() { + if slot.ready { + if let Some(engine) = slot.engine.as_mut() { + engine.on_display_geometry_changed(geometry); + } + } + } + } + /// Activates an instance and records its pre-activation RSS baseline. /// If the instance was previously recycled via `Drop` (`!entry.ready`), defers `activate()` /// until `ensure_ready_and_get_active()` runs `initialize()` on the current frame. diff --git a/src/core/runtime.rs b/src/core/runtime.rs index d029a2bf..1a737eaf 100644 --- a/src/core/runtime.rs +++ b/src/core/runtime.rs @@ -383,7 +383,7 @@ impl DisplayRuntime { } } - /// Synchronously notifies the active engine of geometric display changes (Tate mode, etc.) + /// Synchronously notifies all initialized engines of geometric display changes (`ui_scale`, TATE mode, etc.) pub fn on_display_geometry_changed( &mut self, geometry: &DisplayGeometry, @@ -391,13 +391,7 @@ impl DisplayRuntime { ) { if self.geometry_version != geometry.version { self.geometry_version = geometry.version; - if self.active_session.is_active { - if let Some(engine) = - engine_runtime.get_active_instance(self.active_session.engine_handle) - { - engine.on_display_geometry_changed(geometry); - } - } + engine_runtime.broadcast_display_geometry_changed(geometry); } } } diff --git a/src/engines/frontend_sync.rs b/src/engines/frontend_sync.rs index ead55035..5f117380 100644 --- a/src/engines/frontend_sync.rs +++ b/src/engines/frontend_sync.rs @@ -447,8 +447,12 @@ fn take_dirty_remote_sync_target(matching_req_id: Option) -> Option<(String } pub fn cancel_active_ingame_showcase(config: &Config) { + let had_showcase = config.producer_snapshot.load().ingame_showcase.is_some(); config.set_ingame_showcase(None); config.set_sync_meta(None); + if had_showcase { + crate::core::memory::trim_heap(); + } if let Some((server_url, sync_client_id)) = take_dirty_remote_sync_target(None) { delete_showcase_client_queue_async(server_url, sync_client_id); } @@ -570,12 +574,16 @@ fn spawn_ingame_showcase_request( let target_dwell = Duration::from_millis(offline_dwell_ms); while launch_started.elapsed() < target_dwell { if MQTT_REQUEST_ID.load(Ordering::Acquire) != req_id { + drop(frames); + crate::core::memory::trim_heap(); return; } let rem = target_dwell.saturating_sub(launch_started.elapsed()); std::thread::sleep(rem.min(Duration::from_millis(50))); } if MQTT_REQUEST_ID.load(Ordering::Acquire) != req_id { + drop(frames); + crate::core::memory::trim_heap(); return; } info!( diff --git a/src/engines/gif.rs b/src/engines/gif.rs index 429edacd..22484580 100644 --- a/src/engines/gif.rs +++ b/src/engines/gif.rs @@ -88,22 +88,36 @@ impl GifEngine { target_width: u32, target_height: u32, ) -> Option> { + const MAX_DECODED_GIF_BYTES: usize = 64 * 1024 * 1024; + let file = File::open(path).ok()?; let reader = std::io::BufReader::new(file); let decoder = image::codecs::gif::GifDecoder::new(reader).ok()?; let mut frames = Vec::new(); - use image::AnimationDecoder; - if let Ok(decoded_frames) = decoder.into_frames().collect_frames() { - for frame in decoded_frames { - // `frame.into_buffer()` returns an RgbaImage; composite over black so transparent - // pixels with white RGB backing never bleed as solid white. - let rgba_img = frame.clone().into_buffer(); - let rgb_img = crate::engines::marquee::rgba_to_rgb_on_black(&rgba_img); - - let src_w = rgb_img.width(); - let src_h = rgb_img.height(); + let mut total_bytes: usize = 0; + let bytes_per_frame = (target_width as usize) + .saturating_mul(target_height as usize) + .saturating_mul(3); + use image::AnimationDecoder; + for frame_res in decoder.into_frames() { + let Ok(frame) = frame_res else { + break; + }; + let (num, den) = frame.delay().numer_denom_ms(); + // `frame.into_buffer()` consumes the frame in-place without cloning the RgbaImage; + // composite over black so transparent pixels with white RGB backing never bleed. + let rgba_img = frame.into_buffer(); + let rgb_img = crate::engines::marquee::rgba_to_rgb_on_black(&rgba_img); + drop(rgba_img); + + let src_w = rgb_img.width(); + let src_h = rgb_img.height(); + + let canvas = if src_w == target_width && src_h == target_height { + rgb_img + } else { // Compute uniform scaling preserving aspect ratio (zero distortion/stretching) let (new_w, new_h) = if src_w > 0 && src_h > 0 { let scale_x = target_width as f32 / src_w as f32; @@ -122,25 +136,46 @@ impl GifEngine { new_h, image::imageops::FilterType::Nearest, ); + drop(rgb_img); - // Create a canvas filled with black and center the resized frame (letterboxed) - let mut canvas = RgbImage::new(target_width, target_height); - let offset_x = (target_width.saturating_sub(new_w)) / 2; - let offset_y = (target_height.saturating_sub(new_h)) / 2; - image::imageops::overlay(&mut canvas, &resized, offset_x as i64, offset_y as i64); - - let (num, den) = frame.delay().numer_denom_ms(); - let ms = if den == 0 { 0 } else { num / den }; - let ms_clamped = if ms == 0 { - 100 // Standard GIF fallback for 0ms delay headers - } else if ms < 20 { - 20 // Cap at 50fps max to avoid stuttering + if new_w == target_width && new_h == target_height { + resized } else { - ms - }; - let delay = Duration::from_millis(ms_clamped as u64); + // Create a canvas filled with black and center the resized frame (letterboxed) + let mut boxed = RgbImage::new(target_width, target_height); + let offset_x = (target_width.saturating_sub(new_w)) / 2; + let offset_y = (target_height.saturating_sub(new_h)) / 2; + image::imageops::overlay( + &mut boxed, + &resized, + offset_x as i64, + offset_y as i64, + ); + boxed + } + }; - frames.push((canvas, delay)); + let ms = if den == 0 { 0 } else { num / den }; + let ms_clamped = if ms == 0 { + 100 // Standard GIF fallback for 0ms delay headers + } else if ms < 20 { + 20 // Cap at 50fps max to avoid stuttering + } else { + ms + }; + let delay = Duration::from_millis(ms_clamped as u64); + + total_bytes = total_bytes.saturating_add(bytes_per_frame); + frames.push((canvas, delay)); + + if total_bytes >= MAX_DECODED_GIF_BYTES { + tracing::warn!( + "[GifEngine] Truncated oversized GIF {} at {} frames ({} MB cap)", + path.display(), + frames.len(), + MAX_DECODED_GIF_BYTES / (1024 * 1024) + ); + break; } } diff --git a/src/engines/marquee.rs b/src/engines/marquee.rs index 182560f5..885253ee 100644 --- a/src/engines/marquee.rs +++ b/src/engines/marquee.rs @@ -146,42 +146,55 @@ impl MarqueeEngine { } pub fn render_image(&self, matrix: &mut dyn IDrawingSurface, image: &RgbImage) { - let mw = matrix.width() as u32; - let mh = matrix.height() as u32; + let mw = matrix.native_width(); + let mh = matrix.native_height(); + let target = matrix.unscaled(); let iw = image.width(); let ih = image.height(); - if iw == 0 || ih == 0 { + if iw == 0 || ih == 0 || mw == 0 || mh == 0 { return; } match self.fit_mode.to_lowercase().as_str() { "stretch" => { - let scaled = - image::imageops::resize(image, mw, mh, image::imageops::FilterType::Nearest); - matrix.draw_image(&scaled, 0, 0); + if iw == mw && ih == mh { + target.draw_image(image, 0, 0); + } else { + let scaled = image::imageops::resize( + image, + mw, + mh, + image::imageops::FilterType::Nearest, + ); + target.draw_image(&scaled, 0, 0); + } } "center" => { let offset_x = (mw as i32 - iw as i32) / 2; let offset_y = (mh as i32 - ih as i32) / 2; - matrix.draw_image(image, offset_x, offset_y); + target.draw_image(image, offset_x, offset_y); } _ => { - // "fit" (default): scale to fit within (mw, mh) preserving aspect ratio + // "fit" (default): scale to fit within native (mw, mh) preserving aspect ratio let ratio_w = mw as f32 / iw as f32; let ratio_h = mh as f32 / ih as f32; let ratio = ratio_w.min(ratio_h); let new_w = ((iw as f32 * ratio).round() as u32).clamp(1, mw); let new_h = ((ih as f32 * ratio).round() as u32).clamp(1, mh); - let scaled = image::imageops::resize( - image, - new_w, - new_h, - image::imageops::FilterType::Nearest, - ); let offset_x = (mw as i32 - new_w as i32) / 2; let offset_y = (mh as i32 - new_h as i32) / 2; - matrix.draw_image(&scaled, offset_x, offset_y); + if new_w == iw && new_h == ih { + target.draw_image(image, offset_x, offset_y); + } else { + let scaled = image::imageops::resize( + image, + new_w, + new_h, + image::imageops::FilterType::Nearest, + ); + target.draw_image(&scaled, offset_x, offset_y); + } } } } From dff55982066a21fb99d0bb428ae3924ab957d384 Mon Sep 17 00:00:00 2001 From: red77290 <23342613+red77290@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:09:48 +0000 Subject: [PATCH 4/4] feat(clocks,finance): adapt animated clocks, crypto, and stock to custom aspect ratios --- src/core/theme.rs | 8 +- src/engines/clocks/binary_clock.rs | 109 +++++- src/engines/clocks/castle_clock.rs | 148 +++++-- src/engines/clocks/mario_clock.rs | 216 ++++++++--- src/engines/clocks/megaman_clock.rs | 72 +++- src/engines/clocks/metal_slug_clock.rs | 249 ++++++++---- src/engines/clocks/pokedex_clock.rs | 141 ++++++- src/engines/clocks/sonic_clock.rs | 170 +++++++-- src/engines/clocks/words_clock.rs | 41 +- src/engines/clocks/worldmap_clock.rs | 13 +- src/engines/crypto.rs | 356 ++++++++++++++++- src/engines/stock.rs | 361 +++++++++++++++++- .../test_base_resolutions_zero_regression.rs | 256 +++++++++++++ 13 files changed, 1878 insertions(+), 262 deletions(-) create mode 100644 tests/test_base_resolutions_zero_regression.rs diff --git a/src/core/theme.rs b/src/core/theme.rs index a05a6025..e698aa6a 100644 --- a/src/core/theme.rs +++ b/src/core/theme.rs @@ -296,7 +296,7 @@ pub static THEMES: &[ThemeInfo] = &[ ThemeGroup::GameClock, (255, 255, 255), (0, 0, 0), - (192, 64), + (192, 32), Some((64, 128)), ), theme_with_bounds( @@ -305,7 +305,7 @@ pub static THEMES: &[ThemeInfo] = &[ ThemeGroup::GameClock, (255, 255, 255), (0, 0, 0), - (192, 64), + (192, 32), Some((64, 128)), ), theme( @@ -328,7 +328,7 @@ pub static THEMES: &[ThemeInfo] = &[ ThemeGroup::GameClock, (255, 255, 255), (72, 176, 200), - (192, 64), + (192, 32), None, ), theme( @@ -344,7 +344,7 @@ pub static THEMES: &[ThemeInfo] = &[ ThemeGroup::GameClock, (255, 140, 0), (0, 100, 0), - (192, 64), + (192, 32), Some((32, 128)), ), ]; diff --git a/src/engines/clocks/binary_clock.rs b/src/engines/clocks/binary_clock.rs index e1a4134f..6aff4ffd 100644 --- a/src/engines/clocks/binary_clock.rs +++ b/src/engines/clocks/binary_clock.rs @@ -36,22 +36,83 @@ impl BinaryClock { let colors: [(u8, u8, u8); 3] = [(0, 220, 255), (255, 0, 180), (200, 200, 200)]; let dim_color: (u8, u8, u8) = (25, 25, 25); - let dot_r = ((w / 20).max(2)).min(h / 12) as i32; - let spacing_x = w / 8; - let spacing_y = h / 6; + let is_base_4x1 = (w == 128 && h == 32) || (w == 256 && h == 64); - // Center the 6 columns (with gap after col 1 and col 3) - // Extra gap between H/M and M/S pairs - let mut start_x = (w - 5 * spacing_x) / 2; - let start_y = h - h / 6; + if is_base_4x1 { + let dot_r = ((w / 20).max(2)).min(h / 12) as i32; + let spacing_x = w / 8; + let spacing_y = h / 6; - for (col, &val) in digits.iter().enumerate() { - // Extra horizontal gap between pairs (H|M and M|S) + let mut start_x = (w - 5 * spacing_x) / 2; + let start_y = h - h / 6; + + for (col, &val) in digits.iter().enumerate() { + if col == 2 || col == 4 { + start_x += spacing_x / 2; + } + let x = start_x + col as i32 * spacing_x; + let color_idx = col / 2; // 0=H, 1=M, 2=S + let fg = colors[color_idx]; + + for bit in 0..max_bits[col] { + let y = start_y - bit as i32 * spacing_y; + let is_on = (val >> bit) & 1 == 1; + + if is_on { + for dy in -dot_r..=dot_r { + for dx in -dot_r..=dot_r { + if dx * dx + dy * dy <= dot_r * dot_r { + matrix.set_pixel(x + dx, y + dy, fg.0, fg.1, fg.2); + } + } + } + } else { + for dy in -dot_r..=dot_r { + for dx in -dot_r..=dot_r { + let dist_sq = dx * dx + dy * dy; + if dist_sq <= dot_r * dot_r && dist_sq >= (dot_r - 1) * (dot_r - 1) + { + matrix.set_pixel( + x + dx, + y + dy, + dim_color.0, + dim_color.1, + dim_color.2, + ); + } + } + } + } + } + } + return; + } + + // Custom aspect ratios (e.g. 192x32, 256x32, 192x64, 384x64, 64x32, 128x64, TATE): + // Bound horizontal column pitch proportionally to height so ultra-wide ribbons stay cohesive, + // and account for both inter-pair gaps (`2 * pair_gap`) when centering on `w`. + let dot_r = ((w / 24).max(2)).min((h / 11).max(1)); + let spacing_x = (w / 8).min((h * 5) / 8).max(dot_r * 2 + 2); + let pair_gap = (spacing_x / 2).max(2); + let spacing_y = (h / 5).min(dot_r * 3 + 2).max(dot_r * 2 + 1); + + let total_span_x = 5 * spacing_x + 2 * pair_gap; + let base_x = (w - total_span_x) / 2; + let total_span_y = 3 * spacing_y; + let start_y = (h + total_span_y) / 2 - if w >= 160 && h >= 28 { 1 } else { 0 }; + + let mut col_xs = [0i32; 6]; + let mut extra_x = 0; + for (col, slot) in col_xs.iter_mut().enumerate() { if col == 2 || col == 4 { - start_x += spacing_x / 2; + extra_x += pair_gap; } - let x = start_x + col as i32 * spacing_x; - let color_idx = col / 2; // 0=H, 1=M, 2=S + *slot = base_x + col as i32 * spacing_x + extra_x; + } + + for (col, &val) in digits.iter().enumerate() { + let x = col_xs[col]; + let color_idx = col / 2; let fg = colors[color_idx]; for bit in 0..max_bits[col] { @@ -59,7 +120,6 @@ impl BinaryClock { let is_on = (val >> bit) & 1 == 1; if is_on { - // Filled circle for "on" bit for dy in -dot_r..=dot_r { for dx in -dot_r..=dot_r { if dx * dx + dy * dy <= dot_r * dot_r { @@ -68,7 +128,6 @@ impl BinaryClock { } } } else { - // Dim outline circle for "off" bit for dy in -dot_r..=dot_r { for dx in -dot_r..=dot_r { let dist_sq = dx * dx + dy * dy; @@ -86,5 +145,27 @@ impl BinaryClock { } } } + + // On ultra-wide custom ribbons (e.g. 192x32, 256x32, 192x64+), frame HH : MM : SS groups + // with subtle pair underline bars and blinking colon separators. + if w >= 160 && h >= 28 { + let bar_y = (start_y + dot_r + 3).min(h - 2); + for grp in 0..3 { + let c = colors[grp]; + let x0 = col_xs[grp * 2] - dot_r; + let x1 = col_xs[grp * 2 + 1] + dot_r; + for px in x0..=x1 { + matrix.set_pixel(px, bar_y, c.0 / 3, c.1 / 3, c.2 / 3); + } + } + if seconds % 2 == 0 { + let sep_y1 = start_y - spacing_y; + let sep_y2 = start_y - 2 * spacing_y; + for &sep_x in &[(col_xs[1] + col_xs[2]) / 2, (col_xs[3] + col_xs[4]) / 2] { + matrix.set_pixel(sep_x, sep_y1, 90, 90, 110); + matrix.set_pixel(sep_x, sep_y2, 90, 90, 110); + } + } + } } } diff --git a/src/engines/clocks/castle_clock.rs b/src/engines/clocks/castle_clock.rs index caae3d8d..8ece0eca 100644 --- a/src/engines/clocks/castle_clock.rs +++ b/src/engines/clocks/castle_clock.rs @@ -317,24 +317,34 @@ impl CastleClock { false, ); } else if h >= 48 { - // --- 256x64 Dracula's Castle Parapets --- - matrix.fill_rect(0, 0, w, 48, 16, 0, 24); + // --- Tall Dracula's Castle Parapets (256x64 base, adapts to 128x64, 192x64, 384x64) --- + let parapet_y = h - 16; + matrix.fill_rect(0, 0, w, parapet_y, 16, 0, 24); - // Blood Moon on right - matrix.fill_circle(216, 22, 18, 220, 40, 20); - matrix.fill_circle(214, 20, 15, 240, 80, 40); + // Blood Moon on right (`216, 22` on 256x64) + let moon_x = w - 40; + matrix.fill_circle(moon_x, 22, 18, 220, 40, 20); + matrix.fill_circle(moon_x - 2, 20, 15, 240, 80, 40); - // Parapets at y=48..63 + // Parapets at y=(h-16)..(h-1) let stone_base = (80u8, 80u8, 96u8); let stone_light = (140u8, 140u8, 160u8); let stone_dark = (36u8, 36u8, 48u8); - matrix.fill_rect(0, 48, w, h - 48, stone_base.0, stone_base.1, stone_base.2); + matrix.fill_rect( + 0, + parapet_y, + w, + h - parapet_y, + stone_base.0, + stone_base.1, + stone_base.2, + ); matrix.draw_line( 0, - 48, + parapet_y, w - 1, - 48, + parapet_y, stone_light.0, stone_light.1, stone_light.2, @@ -342,10 +352,18 @@ impl CastleClock { let mut x = 0; while x < w { - matrix.draw_line(x, 48, x, h - 1, stone_dark.0, stone_dark.1, stone_dark.2); + matrix.draw_line( + x, + parapet_y, + x, + h - 1, + stone_dark.0, + stone_dark.1, + stone_dark.2, + ); matrix.draw_line( x + 1, - 48, + parapet_y, x + 1, h - 1, stone_light.0, @@ -355,16 +373,40 @@ impl CastleClock { x += 16; } - // Candle Torch Stand on right (x=240, y=26..47) - matrix.fill_rect(240, 34, 4, 14, 140, 100, 50); - matrix.fill_rect(238, 30, 8, 4, 140, 100, 50); + // Candle Torch Stand on right (`240` on 256x64) + let stand_x = w - 16; + matrix.fill_rect(stand_x, parapet_y - 14, 4, 14, 140, 100, 50); + matrix.fill_rect(stand_x - 2, parapet_y - 18, 8, 4, 140, 100, 50); let flame_pal = FLAME_PALS[self.flame_frame % 3]; let flame_pix = FLAME_PIXELS[self.flame_frame % 3]; Self::blit_sprite( - matrix, flame_pal, flame_pix, FLAME_F0_W, FLAME_F0_H, 238, 20, false, + matrix, + flame_pal, + flame_pix, + FLAME_F0_W, + FLAME_F0_H, + stand_x - 2, + parapet_y - 28, + false, ); + if w >= 320 { + // Symmetrical left parapet torch stand on giant ultra-wide 64px+ walls + matrix.fill_rect(12, parapet_y - 14, 4, 14, 140, 100, 50); + matrix.fill_rect(10, parapet_y - 18, 8, 4, 140, 100, 50); + Self::blit_sprite( + matrix, + flame_pal, + flame_pix, + FLAME_F0_W, + FLAME_F0_H, + 10, + parapet_y - 28, + false, + ); + } + let bat_pal = BAT_PALS[self.bat_frame % 2]; let bat_pix = BAT_PIXELS[self.bat_frame % 2]; Self::blit_sprite( @@ -378,31 +420,70 @@ impl CastleClock { false, ); } else { - // --- 128x32 Dungeon Floor --- - matrix.fill_rect(0, 0, w, 26, 0, 0, 0); + // --- 32px Dungeon Floor (128x32 base, adapts to 192x32, 256x32, 64x32) --- + let floor_y = h - 6; + matrix.fill_rect(0, 0, w, floor_y, 0, 0, 0); // Blood Moon in upper-left sky matrix.fill_circle(14, 10, 8, 220, 40, 20); matrix.fill_circle(13, 9, 6, 240, 80, 40); - // Brick floor at y=26..31 - matrix.fill_rect(0, 26, w, h - 26, 116, 40, 12); - matrix.draw_line(0, 26, w - 1, 26, 180, 70, 20); + // Brick floor at y=(h-6)..(h-1) + matrix.fill_rect(0, floor_y, w, h - floor_y, 116, 40, 12); + matrix.draw_line(0, floor_y, w - 1, floor_y, 180, 70, 20); let mut x = 0; while x < w { - matrix.draw_line(x, 26, x, h - 1, 40, 16, 8); + matrix.draw_line(x, floor_y, x, h - 1, 40, 16, 8); x += 8; } - // Candle Torch on right - matrix.fill_rect(116, 20, 2, 6, 140, 100, 50); + // Candle Torch on right (`116` on 128x32, `180` on 192x32) + let torch_x = w - 12; + matrix.fill_rect(torch_x, floor_y - 6, 2, 6, 140, 100, 50); let flame_pal = FLAME_PALS[self.flame_frame % 3]; let flame_pix = FLAME_PIXELS[self.flame_frame % 3]; Self::blit_sprite( - matrix, flame_pal, flame_pix, FLAME_F0_W, FLAME_F0_H, 113, 10, false, + matrix, + flame_pal, + flame_pix, + FLAME_F0_W, + FLAME_F0_H, + torch_x - 3, + floor_y - 16, + false, ); + // On ultra-wide 32px ribbons (e.g. 192x32, 256x32), frame the centered clock with twin inner sconces + if w >= 160 { + let left_sconce_x = (w - 66) / 2 - 18; + let right_sconce_x = (w + 66) / 2 + 16; + matrix.fill_rect(left_sconce_x, floor_y - 6, 2, 6, 140, 100, 50); + Self::blit_sprite( + matrix, + flame_pal, + flame_pix, + FLAME_F0_W, + FLAME_F0_H, + left_sconce_x - 3, + floor_y - 16, + false, + ); + if right_sconce_x + 8 < torch_x { + matrix.fill_rect(right_sconce_x, floor_y - 6, 2, 6, 140, 100, 50); + Self::blit_sprite( + matrix, + flame_pal, + flame_pix, + FLAME_F0_W, + FLAME_F0_H, + right_sconce_x - 3, + floor_y - 16, + false, + ); + } + } + let bat_pal = BAT_PALS[self.bat_frame % 2]; let bat_pix = BAT_PIXELS[self.bat_frame % 2]; Self::blit_sprite( @@ -645,7 +726,11 @@ impl CastleClock { } } } else { - let target_x = if h >= 48 { 20.0 } else { 6.0 }; + let target_x = if h >= 48 { + ((w - 88) / 2 - 64).max(2) as f32 + } else { + ((w - 66) / 2 - 25).max(0) as f32 + }; self.simon_x += 65.0 * dt; if self.simon_x >= target_x { self.simon_x = target_x; @@ -807,8 +892,11 @@ impl CastleClock { } } } else if h >= 48 { - // --- 256x64 Layout: Blood Red Gothic Digits Centered (scale 4 = 88px wide) --- - Self::draw_gothic_time(matrix, 84, 16, &time_buf, crimson, 4); + // --- Tall Layout: Blood Red Gothic Digits Centered (`84` on 256x64) --- + let (scale, tw) = if w < 96 { (2, 44) } else { (4, 88) }; + let time_x = (w - tw) / 2; + let time_y = (h - 16 - 5 * scale) / 2 + 2; + Self::draw_gothic_time(matrix, time_x, time_y, &time_buf, crimson, scale); if self.phase != Phase::Idle { if self.phase == Phase::WhipWindup { @@ -867,8 +955,10 @@ impl CastleClock { } } } else { - // --- 128x32 Layout: Blood Red Gothic Digits Centered (scale 3 = 66px wide) --- - Self::draw_gothic_time(matrix, 31, 8, &time_buf, crimson, 3); + // --- 32px Layout: Blood Red Gothic Digits Centered (`31` on 128x32, `63` on 192x32) --- + let (scale, tw, ty) = if w < 80 { (2, 44, 9) } else { (3, 66, 8) }; + let time_x = (w - tw) / 2; + Self::draw_gothic_time(matrix, time_x, ty, &time_buf, crimson, scale); if self.phase != Phase::Idle { if self.phase == Phase::WhipWindup { diff --git a/src/engines/clocks/mario_clock.rs b/src/engines/clocks/mario_clock.rs index ba7d9d89..d26a1da6 100644 --- a/src/engines/clocks/mario_clock.rs +++ b/src/engines/clocks/mario_clock.rs @@ -331,6 +331,55 @@ impl MarioClock { ); } + let is_base_4x1 = (w == 128 && h == 32) || (w == 256 && h == 64); + + if h >= 48 { + Self::blit_sprite( + matrix, + &HILL, + HILL_W, + HILL_H, + 0, + ground_top - HILL_H + 2, + true, + false, + ); + Self::blit_sprite( + matrix, + &BUSH, + BUSH_W, + BUSH_H, + w - BUSH_W, + ground_top - BUSH_H, + true, + false, + ); + } else if !is_base_4x1 && w >= 160 { + // Custom ultra-wide 32px ribbon (e.g. 192x32, 256x32): dress both flanks like World 1-1 + Self::blit_sprite( + matrix, + &HILL, + HILL_W, + HILL_H, + 2, + ground_top - HILL_H + 2, + true, + false, + ); + Self::blit_sprite( + matrix, + &BUSH, + BUSH_W, + BUSH_H, + w - BUSH_W - 4, + ground_top - BUSH_H, + true, + false, + ); + Self::blit_sprite(matrix, &CLOUD1, CLOUD_W, CLOUD_H, 28, 3, true, false); + Self::blit_sprite(matrix, &CLOUD2, CLOUD_W, CLOUD_H, w - 46, 4, true, false); + } + Self::blit_sprite( matrix, &CLOUD1, @@ -353,48 +402,84 @@ impl MarioClock { ); if w >= 128 && h >= 48 { - Self::blit_sprite( - matrix, - &CLOUD_FULL, - CLOUD_FULL_W, - CLOUD_FULL_H, - 40, - 6, - true, - false, - ); - Self::blit_sprite( - matrix, - &CLOUD_FULL, - CLOUD_FULL_W, - CLOUD_FULL_H, - 72, - 14, - true, - false, - ); - } - if w >= 256 && h >= 48 { - Self::blit_sprite( - matrix, - &CLOUD_FULL, - CLOUD_FULL_W, - CLOUD_FULL_H, - 165, - 6, - true, - false, - ); - Self::blit_sprite( - matrix, - &CLOUD_FULL, - CLOUD_FULL_W, - CLOUD_FULL_H, - 198, - 14, - true, - false, - ); + if is_base_4x1 || w == 128 { + Self::blit_sprite( + matrix, + &CLOUD_FULL, + CLOUD_FULL_W, + CLOUD_FULL_H, + 40, + 6, + true, + false, + ); + Self::blit_sprite( + matrix, + &CLOUD_FULL, + CLOUD_FULL_W, + CLOUD_FULL_H, + 72, + 14, + true, + false, + ); + if w >= 256 { + Self::blit_sprite( + matrix, + &CLOUD_FULL, + CLOUD_FULL_W, + CLOUD_FULL_H, + 165, + 6, + true, + false, + ); + Self::blit_sprite( + matrix, + &CLOUD_FULL, + CLOUD_FULL_W, + CLOUD_FULL_H, + 198, + 14, + true, + false, + ); + } + } else { + // Custom tall widths (192x64, 384x64, etc.): distribute clouds outside the centered blocks + let scene_left = (w - SCENE) / 2; + let mut cx = 28; + let mut row_toggle = false; + while cx + CLOUD_FULL_W < scene_left - 8 { + Self::blit_sprite( + matrix, + &CLOUD_FULL, + CLOUD_FULL_W, + CLOUD_FULL_H, + cx, + if row_toggle { 14 } else { 6 }, + true, + false, + ); + row_toggle = !row_toggle; + cx += 34; + } + let mut rx = scene_left + SCENE + 8; + while rx + CLOUD_FULL_W < w - CLOUD_W - 6 { + Self::blit_sprite( + matrix, + &CLOUD_FULL, + CLOUD_FULL_W, + CLOUD_FULL_H, + rx, + if row_toggle { 14 } else { 6 }, + true, + false, + ); + row_toggle = !row_toggle; + rx += 34; + } + } } } @@ -420,6 +505,7 @@ impl MarioClock { let h = matrix.height() as i32; let is_portrait = h > w; let is_wide_tall = h >= 48 && !is_portrait; + let is_base_4x1 = (w == 128 && h == 32) || (w == 256 && h == 64); let ground_top = if is_portrait { 70 } else { h - GROUND_H }; let (hour_x, minute_x, block_y) = if is_portrait { @@ -431,6 +517,11 @@ impl MarioClock { } else if is_wide_tall { let scene_left = (w - SCENE) / 2; (scene_left + 13, scene_left + 32, 8) + } else if !is_base_4x1 && w >= 160 { + let hx = (w * 52) / 100; + (hx, hx + 22, 3) + } else if !is_base_4x1 && w < 96 { + ((w - 41).max(2), (w - 20).max(22), 3) } else { (w - 46, w - 24, 3) }; @@ -746,7 +837,7 @@ impl MarioClock { } } } else { - // 128x32 compact mode shell physics + // Compact 32px shell physics (128x32 base, adapts to 192x32, 256x32, 64x32) let target_x = ((if self.jump_target == 0 { hour_x } else { @@ -754,16 +845,32 @@ impl MarioClock { }) + BLOCK_W / 2 - KOOPA_SHELL_W / 2) as f32; let pace = 75.0 * speed_scale; + let (shell_min, shell_max, run_jump_limit, shell_retreat) = if is_base_4x1 { + (20.0f32, 65.0f32, 25.0f32, 55.0f32) + } else if w >= 160 { + let s_max = (hour_x - 17) as f32; + let s_min = (hour_x - 62).max(26) as f32; + (s_min, s_max, s_min + 5.0, s_max - 10.0) + } else { + let s_max = (hour_x - 10).max(12) as f32; + let s_min = 4.0f32; + ( + s_min, + s_max, + (s_min + 4.0).min(s_max), + (s_max - 4.0).max(s_min), + ) + }; match self.phase { Phase::Waiting => { let patrol_speed = 22.0 * speed_scale; self.shell_x += self.shell_dir * patrol_speed * dt; - if self.shell_x >= 65.0 { - self.shell_x = 65.0; + if self.shell_x >= shell_max { + self.shell_x = shell_max; self.shell_dir = -1.0; - } else if self.shell_x <= 20.0 { - self.shell_x = 20.0; + } else if self.shell_x <= shell_min { + self.shell_x = shell_min; self.shell_dir = 1.0; } self.runner_x = -40.0; @@ -771,18 +878,19 @@ impl MarioClock { Phase::RunIn => { let patrol_speed = 22.0 * speed_scale; self.shell_x += self.shell_dir * patrol_speed * dt; - if self.shell_x >= 65.0 { - self.shell_x = 65.0; + if self.shell_x >= shell_max { + self.shell_x = shell_max; self.shell_dir = -1.0; - } else if self.shell_x <= 20.0 { - self.shell_x = 20.0; + } else if self.shell_x <= shell_min { + self.shell_x = shell_min; self.shell_dir = 1.0; } self.runner_x += pace * dt; self.runner_y = (ground_top - MARIO_H) as f32; - if (self.runner_x >= 10.0 && (self.shell_x - self.runner_x) <= 35.0) - || self.runner_x >= 25.0 + if (self.runner_x >= (shell_min - 10.0).max(2.0) + && (self.shell_x - self.runner_x) <= 35.0) + || self.runner_x >= run_jump_limit { self.jump_start_x = self.runner_x; self.jump_target_x = self.shell_x; @@ -825,7 +933,7 @@ impl MarioClock { Phase::RunOut => { self.runner_x += pace * dt; self.runner_y = (ground_top - MARIO_H) as f32; - if self.shell_x > 55.0 { + if self.shell_x > shell_retreat { self.shell_x -= 40.0 * speed_scale * dt; } if self.runner_x > (w + MARIO_JUMP_W + 16) as f32 { diff --git a/src/engines/clocks/megaman_clock.rs b/src/engines/clocks/megaman_clock.rs index ff22fe9b..5f70bc24 100644 --- a/src/engines/clocks/megaman_clock.rs +++ b/src/engines/clocks/megaman_clock.rs @@ -334,28 +334,33 @@ impl MegamanClock { surface.fill_rect(0, y, w, 1, 6, 10, grad); } - // Skyline silhouettes - for &(bx, bh, bw_raw) in &SKYLINE_BUILDINGS { - if bx >= w { - continue; - } - let bw = if bx + bw_raw > w { w - bx } else { bw_raw }; - let by = (h - bh).max(0); - surface.fill_rect(bx, by, bw, h - by, 16, 24, 40); - - let mut wx = bx + 3; - while wx < bx + bw - 3 { - let mut wy = by + 4; - while wy < h - 8 { - if (wx + wy) % 7 == 0 { - surface.draw_pixel(wx, wy, 252, 224, 0); - } else if (wx + wy) % 11 == 0 { - surface.draw_pixel(wx, wy, 0, 232, 216); + // Skyline silhouettes (tiles seamlessly every 256px on ultra-wide walls) + let mut sky_off = 0; + while sky_off < w { + for &(bx_rel, bh, bw_raw) in &SKYLINE_BUILDINGS { + let bx = sky_off + bx_rel; + if bx >= w { + continue; + } + let bw = if bx + bw_raw > w { w - bx } else { bw_raw }; + let by = (h - bh).max(0); + surface.fill_rect(bx, by, bw, h - by, 16, 24, 40); + + let mut wx = bx + 3; + while wx < bx + bw - 3 { + let mut wy = by + 4; + while wy < h - 8 { + if (wx + wy) % 7 == 0 { + surface.draw_pixel(wx, wy, 252, 224, 0); + } else if (wx + wy) % 11 == 0 { + surface.draw_pixel(wx, wy, 0, 232, 216); + } + wy += 6; } - wy += 6; + wx += 5; } - wx += 5; } + sky_off += 256; } if is_portrait { @@ -495,6 +500,7 @@ impl MegamanClock { let is_portrait = h > w; let is_wide_tall = h >= 48; + let is_base_128x32 = w == 128 && h == 32; let ground_top = h - if is_wide_tall { GROUND_TILE_H } else { 6 }; let (hour_x, min_x, pod_y) = if is_portrait { @@ -506,6 +512,11 @@ impl MegamanClock { } else if is_wide_tall { let mid_x = w / 2; (mid_x - 28, mid_x + 4, 10) + } else if !is_base_128x32 && w >= 160 { + let mid_x = (w * 52) / 100; + (mid_x - 27, mid_x, 6) + } else if !is_base_128x32 && w < 96 { + ((w - 49).max(2), (w - 24).max(26), 6) } else { (w - 54, w - 27, 6) }; @@ -649,7 +660,13 @@ impl MegamanClock { } else { self.megaman_x += 85.0 * dt; self.megaman_y = (ground_top - MEGAMAN_RUN1_H) as f32; - let shoot_start_x = 18.0; + let shoot_start_x = if !is_base_128x32 && w >= 160 { + (hour_x - 42).max(18) as f32 + } else if !is_base_128x32 && w < 96 { + 2.0 + } else { + 18.0 + }; if self.megaman_x >= shoot_start_x { self.megaman_x = shoot_start_x; self.phase = Phase::HeroJump; @@ -708,7 +725,7 @@ impl MegamanClock { self.phase_timer = 0.0; } } else { - // 128x32 horizontal: Mega Man advances straight without jumping, stops and fires Buster lemon + // 128x32 / 192x32 horizontal: Mega Man stops and fires Buster lemon self.megaman_y = (ground_top - MEGAMAN_SHOOT_H) as f32; if self.phase_timer >= 0.06 && !self.bullet_active && !self.spark_active { @@ -822,6 +839,19 @@ impl MegamanClock { } } else { Self::draw_mini_energy_gauge(surface, 6, 2, seconds as i32); + if !is_base_128x32 && w >= 160 { + let metool_x = w - METOOL_W - 8; + Self::blit_sprite( + surface, + &METOOL_SLEEP, + METOOL_W, + METOOL_H, + metool_x, + ground_top - METOOL_H, + true, + false, + ); + } } // Mega Man rendering (appears only during minute sequence) diff --git a/src/engines/clocks/metal_slug_clock.rs b/src/engines/clocks/metal_slug_clock.rs index 08a6d088..d7953fd1 100644 --- a/src/engines/clocks/metal_slug_clock.rs +++ b/src/engines/clocks/metal_slug_clock.rs @@ -135,7 +135,8 @@ impl MetalSlugClock { self.snap_to_now = true; } - fn blit_sprite( + #[allow(clippy::too_many_arguments)] + fn blit_sprite_div( surface: &mut dyn IDrawingSurface, palette: &[u16], pixels: &[u8], @@ -144,34 +145,49 @@ impl MetalSlugClock { x: i32, y: i32, flip_h: bool, + div: i32, ) { + let d = div.max(1); let panel_w = surface.width() as i32; let panel_h = surface.height() as i32; - for row in 0..h { - let py = y + row; - if py < 0 || py >= panel_h { - continue; - } - for col in 0..w { - let px = x + col; - if px < 0 || px >= panel_w { - continue; - } - let src_col = if flip_h { w - 1 - col } else { col }; - let Some(&idx) = pixels.get((row * w + src_col) as usize) else { - continue; - }; - if idx == 0 { - continue; - } - if let Some(&col565) = palette.get(idx as usize) { - let (r, g, b) = rgb565_to_rgb888(col565); - surface.draw_pixel(px, py, r, g, b); + let mut row = 0; + while row < h { + let py = y + row / d; + if py >= 0 && py < panel_h { + let mut col = 0; + while col < w { + let px = x + col / d; + if px >= 0 && px < panel_w { + let src_col = if flip_h { w - 1 - col } else { col }; + if let Some(&idx) = pixels.get((row * w + src_col) as usize) { + if idx != 0 { + if let Some(&col565) = palette.get(idx as usize) { + let (r, g, b) = rgb565_to_rgb888(col565); + surface.draw_pixel(px, py, r, g, b); + } + } + } + } + col += d; } } + row += d; } } + fn blit_sprite( + surface: &mut dyn IDrawingSurface, + palette: &[u16], + pixels: &[u8], + w: i32, + h: i32, + x: i32, + y: i32, + flip_h: bool, + ) { + Self::blit_sprite_div(surface, palette, pixels, w, h, x, y, flip_h, 1); + } + fn blit_backdrop( surface: &mut dyn IDrawingSurface, palette: &[u16], @@ -182,7 +198,7 @@ impl MetalSlugClock { let panel_w = surface.width() as i32; let panel_h = surface.height() as i32; - if panel_w < w && panel_h < h && panel_w > 0 && panel_h > 0 { + if (panel_w != w || panel_h != h) && panel_w > 0 && panel_h > 0 { let row_stride_bytes = (w * 3 / 4) as usize; for py in 0..panel_h { let sy = (py * h / panel_h).clamp(0, h - 1) as usize; @@ -363,6 +379,7 @@ impl MetalSlugClock { fn draw_scene(&self, surface: &mut dyn IDrawingSurface, w: i32, h: i32) { let is_portrait = h > w; + let div = if !is_portrait && h < 48 { 2 } else { 1 }; let ground_top = if is_portrait { if h < 192 { h - 13 @@ -370,7 +387,7 @@ impl MetalSlugClock { h - 26 } } else { - 64 + h }; if is_portrait { @@ -387,14 +404,22 @@ impl MetalSlugClock { } // 2. Flying Helicopter in upper sky - let heli_max = if is_portrait { w as f32 + 50.0 } else { 270.0 }; + let heli_max = if is_portrait { + w as f32 + 50.0 + } else if w == 256 && h == 64 { + 270.0 + } else { + w as f32 + 14.0 + }; if self.heli_x > -50.0 && self.heli_x < heli_max { let hy = if is_portrait { 46 + ((self.phase_timer * 3.0).sin() * 3.0) as i32 + } else if h < 48 { + 9 + ((self.phase_timer * 3.0).sin() * 1.5) as i32 } else { 8 + ((self.phase_timer * 3.0).sin() * 3.0) as i32 }; - Self::blit_sprite( + Self::blit_sprite_div( surface, &ENEMY_HELI_PAL, &ENEMY_HELI_PIXELS, @@ -403,24 +428,26 @@ impl MetalSlugClock { self.heli_x as i32, hy, false, + div, ); } // 3. Rebel Army Di-Cokka Tank - let tank_y = ground_top - TANK_ALIVE_H; + let tank_y = ground_top - TANK_ALIVE_H / div; if self.phase == Phase::Explosion || self.phase == Phase::HeroExit { - Self::blit_sprite( + Self::blit_sprite_div( surface, &TANK_DEAD_PAL, &TANK_DEAD_PIXELS, TANK_DEAD_W, TANK_DEAD_H, self.tank_x as i32, - ground_top - TANK_DEAD_H, + ground_top - TANK_DEAD_H / div, false, + div, ); } else { - Self::blit_sprite( + Self::blit_sprite_div( surface, &TANK_ALIVE_PAL, &TANK_ALIVE_PIXELS, @@ -429,52 +456,56 @@ impl MetalSlugClock { self.tank_x as i32, tank_y, false, + div, ); } // 4. Tank Cannon Shell if self.tank_bullet_active && self.tank_bullet_x > self.marco_x { - Self::blit_sprite( + Self::blit_sprite_div( surface, &TANK_BULLET_PAL, &TANK_BULLET_PIXELS, TANK_BULLET_W, TANK_BULLET_H, self.tank_bullet_x as i32, - ground_top - 22, + ground_top - 22 / div, false, + div, ); } // 5. Marco Rossi animation (appears only during minute sequence, hidden in Idle) if self.phase == Phase::HeroEnter || self.phase == Phase::HeroExit { if self.walk_frame % 2 == 0 { - Self::blit_sprite( + Self::blit_sprite_div( surface, &MARCO_WALK_0_PAL, &MARCO_WALK_0_PIXELS, MARCO_WALK_0_W, MARCO_WALK_0_H, self.marco_x as i32, - ground_top - MARCO_WALK_0_H, + ground_top - MARCO_WALK_0_H / div, false, + div, ); } else { - Self::blit_sprite( + Self::blit_sprite_div( surface, &MARCO_WALK_1_PAL, &MARCO_WALK_1_PIXELS, MARCO_WALK_1_W, MARCO_WALK_1_H, self.marco_x as i32, - ground_top - MARCO_WALK_1_H, + ground_top - MARCO_WALK_1_H / div, false, + div, ); } } else if self.phase == Phase::Firefight { - let marco_y = ground_top - MARCO_SHOOT_0_H; + let marco_y = ground_top - MARCO_SHOOT_0_H / div; if self.anim_frame % 2 == 0 { - Self::blit_sprite( + Self::blit_sprite_div( surface, &MARCO_SHOOT_0_PAL, &MARCO_SHOOT_0_PIXELS, @@ -483,9 +514,10 @@ impl MetalSlugClock { self.marco_x as i32, marco_y, false, + div, ); } else { - Self::blit_sprite( + Self::blit_sprite_div( surface, &MARCO_SHOOT_1_PAL, &MARCO_SHOOT_1_PIXELS, @@ -494,47 +526,53 @@ impl MetalSlugClock { self.marco_x as i32, marco_y, false, + div, ); } - let muzzle_x = self.marco_x as i32 + MARCO_SHOOT_0_W; - let muzzle_y = marco_y + 10; + let muzzle_x = self.marco_x as i32 + MARCO_SHOOT_0_W / div; + let muzzle_y = marco_y + 10 / div; if self.anim_frame % 2 == 1 { - let tracer_len = if is_portrait { 18 } else { 40 }; + let tracer_len = if is_portrait { 18 } else { 40 / div }; surface.fill_rect(muzzle_x + 2, muzzle_y, tracer_len, 1, 255, 240, 60); - surface.fill_rect(muzzle_x + 4, muzzle_y + 1, tracer_len - 6, 1, 255, 120, 20); + if div == 1 { + surface.fill_rect(muzzle_x + 4, muzzle_y + 1, tracer_len - 6, 1, 255, 120, 20); + } } } else if self.phase == Phase::GrenadeAssault { - Self::blit_sprite( + Self::blit_sprite_div( surface, &MARCO_GRENADE_PAL, &MARCO_GRENADE_PIXELS, MARCO_GRENADE_W, MARCO_GRENADE_H, self.marco_x as i32, - ground_top - MARCO_GRENADE_H, + ground_top - MARCO_GRENADE_H / div, false, + div, ); } else if self.phase == Phase::Explosion { - Self::blit_sprite( + Self::blit_sprite_div( surface, &MARCO_VICTORY_PAL, &MARCO_VICTORY_PIXELS, MARCO_VICTORY_W, MARCO_VICTORY_H, self.marco_x as i32, - ground_top - MARCO_VICTORY_H, + ground_top - MARCO_VICTORY_H / div, false, + div, ); } // 6. Flying Grenade Arc if self.grenade_active { + let gsz = if div == 2 { 2 } else { 3 }; surface.fill_rect( self.grenade_x as i32, self.grenade_y as i32, - 3, - 3, + gsz, + gsz, 180, 160, 40, @@ -555,9 +593,19 @@ impl MetalSlugClock { let exp_x = if is_portrait { self.tank_x as i32 + 4 } else { - self.tank_x as i32 + 15 + self.tank_x as i32 + 15 / div }; - Self::blit_sprite(surface, pal, pix, ew, eh, exp_x, ground_top - eh - 4, false); + Self::blit_sprite_div( + surface, + pal, + pix, + ew, + eh, + exp_x, + ground_top - eh / div - 4 / div, + false, + div, + ); } // 8. Authentic SNK Neo Geo Arcade HUD @@ -609,6 +657,42 @@ impl MetalSlugClock { Self::draw_arcade_digit(surface, time_x + 8, 28, mm_bytes[1], hud_yellow, 2); } } + } else if h < 48 { + // Compact 32px Neo-Geo HUD bar (`192x32` / `256x32` custom ribbons) + surface.fill_rect(0, 0, w, 9, 8, 8, 16); + surface.fill_rect(0, 9, w, 1, 40, 40, 70); + + Self::draw_arcade_digit(surface, 4, 2, b'1', hud_red, 1); + surface.fill_rect(9, 2, 1, 5, hud_red.0, hud_red.1, hud_red.2); + surface.fill_rect(11, 2, 1, 5, hud_red.0, hud_red.1, hud_red.2); + surface.fill_rect(9, 6, 3, 1, hud_red.0, hud_red.1, hud_red.2); + surface.fill_rect(14, 2, 1, 5, hud_red.0, hud_red.1, hud_red.2); + surface.fill_rect(14, 2, 3, 1, hud_red.0, hud_red.1, hud_red.2); + surface.fill_rect(16, 2, 1, 3, hud_red.0, hud_red.1, hud_red.2); + surface.fill_rect(14, 4, 3, 1, hud_red.0, hud_red.1, hud_red.2); + + let score_str = format!("00{}{}", self.shown_hh, self.shown_mm); + let mut sx = 20; + for b in score_str.bytes() { + Self::draw_arcade_digit(surface, sx, 2, b, hud_white, 1); + sx += 4; + } + + // Prominent scale-2 yellow Neo-Geo clock centered in upper sky + let time_x = (w - 44) / 2; + Self::draw_arcade_time(surface, time_x, 1, &time_str, hud_yellow, 2); + + let r_base = w - 64; + surface.fill_rect(r_base, 1, 7, 7, 220, 160, 20); + surface.draw_rect(r_base, 1, 7, 7, 255, 240, 80); + let mut ax = r_base + 10; + for b in self.shown_mm.bytes() { + Self::draw_arcade_digit(surface, ax, 2, b, hud_yellow, 1); + ax += 4; + } + surface.fill_circle(w - 18, 4, 2, 240, 80, 20); + Self::draw_arcade_digit(surface, w - 12, 2, b'1', hud_white, 1); + Self::draw_arcade_digit(surface, w - 7, 2, b'0', hud_white, 1); } else { surface.fill_rect(0, 0, w, 12, 8, 8, 16); surface.fill_rect(0, 12, w, 1, 40, 40, 70); @@ -629,25 +713,27 @@ impl MetalSlugClock { sx += 4; } - Self::draw_arcade_time(surface, 106, 1, &time_str, hud_yellow, 2); + let time_x = (w - 44) / 2; + Self::draw_arcade_time(surface, time_x, 1, &time_str, hud_yellow, 2); - Self::draw_arcade_digit(surface, 185, 3, b'4', hud_cyan, 1); - surface.fill_rect(195, 2, 7, 7, 220, 160, 20); - surface.draw_rect(195, 2, 7, 7, 255, 240, 80); - surface.fill_rect(197, 4, 1, 3, 0, 0, 0); - surface.fill_rect(199, 4, 1, 3, 0, 0, 0); - surface.fill_rect(197, 5, 3, 1, 0, 0, 0); + let r_off = w - 71; + Self::draw_arcade_digit(surface, r_off, 3, b'4', hud_cyan, 1); + surface.fill_rect(r_off + 10, 2, 7, 7, 220, 160, 20); + surface.draw_rect(r_off + 10, 2, 7, 7, 255, 240, 80); + surface.fill_rect(r_off + 12, 4, 1, 3, 0, 0, 0); + surface.fill_rect(r_off + 14, 4, 1, 3, 0, 0, 0); + surface.fill_rect(r_off + 12, 5, 3, 1, 0, 0, 0); - let mut ax = 205; + let mut ax = r_off + 20; for b in self.shown_mm.bytes() { Self::draw_arcade_digit(surface, ax, 3, b, hud_yellow, 1); ax += 4; } - surface.fill_circle(235, 5, 2, 240, 80, 20); - surface.draw_pixel(236, 3, 255, 255, 0); - Self::draw_arcade_digit(surface, 241, 3, b'1', hud_white, 1); - Self::draw_arcade_digit(surface, 246, 3, b'0', hud_white, 1); + surface.fill_circle(w - 21, 5, 2, 240, 80, 20); + surface.draw_pixel(w - 20, 3, 255, 255, 0); + Self::draw_arcade_digit(surface, w - 15, 3, b'1', hud_white, 1); + Self::draw_arcade_digit(surface, w - 10, 3, b'0', hud_white, 1); } } @@ -678,6 +764,7 @@ impl MetalSlugClock { let w = surface.width() as i32; let h = surface.height() as i32; let is_portrait = h > w; + let div = if !is_portrait && h < 48 { 2 } else { 1 }; let ground_top = if is_portrait { if h < 192 { h - 13 @@ -685,7 +772,7 @@ impl MetalSlugClock { h - 26 } } else { - 64 + h }; let target_tank_x = if is_portrait { if w < 64 { @@ -693,8 +780,10 @@ impl MetalSlugClock { } else { w as f32 - 34.0 } + } else if h < 48 { + (w - 42).max(90) as f32 } else { - 185.0 + (w - 71).max(96) as f32 }; let target_fire_x = if is_portrait { if w < 64 { @@ -702,6 +791,8 @@ impl MetalSlugClock { } else { 2.0 } + } else if h < 48 { + 28.0 } else { 42.0 }; @@ -750,8 +841,14 @@ impl MetalSlugClock { let current_min = minutes as i32; - let heli_max = if is_portrait { w as f32 + 50.0 } else { 280.0 }; - self.heli_x += 22.0 * dt; + let heli_max = if is_portrait { + w as f32 + 50.0 + } else if w == 256 && h == 64 { + 280.0 + } else { + w as f32 + 24.0 + }; + self.heli_x += (22.0 / div as f32) * dt; if self.heli_x > heli_max { self.heli_x = -60.0; } @@ -787,21 +884,25 @@ impl MetalSlugClock { self.phase = Phase::GrenadeAssault; self.phase_timer = 0.0; self.grenade_active = true; - self.grenade_x = self.marco_x + 18.0; - self.grenade_y = ground_top as f32 - 28.0; - self.grenade_vx = - (self.tank_x + 10.0 - self.grenade_x) / if is_portrait { 0.5 } else { 0.7 }; - self.grenade_vy = if is_portrait { -70.0 } else { -95.0 }; + self.grenade_x = self.marco_x + (18 / div) as f32; + self.grenade_y = ground_top as f32 - (28 / div) as f32; + self.grenade_vx = (self.tank_x + (10 / div) as f32 - self.grenade_x) + / if is_portrait { 0.5 } else { 0.7 }; + self.grenade_vy = if is_portrait { + -70.0 + } else { + -95.0 / div as f32 + }; } } Phase::GrenadeAssault => { if self.grenade_active { self.grenade_x += self.grenade_vx * dt; - self.grenade_vy += 220.0 * dt; + self.grenade_vy += (220.0 / div as f32) * dt; self.grenade_y += self.grenade_vy * dt; - if self.grenade_x >= self.tank_x + 8.0 - || self.grenade_y >= ground_top as f32 - 16.0 + if self.grenade_x >= self.tank_x + (8 / div) as f32 + || self.grenade_y >= ground_top as f32 - (16 / div) as f32 || self.phase_timer >= 0.9 { self.grenade_active = false; diff --git a/src/engines/clocks/pokedex_clock.rs b/src/engines/clocks/pokedex_clock.rs index b43f361e..b15f85a0 100644 --- a/src/engines/clocks/pokedex_clock.rs +++ b/src/engines/clocks/pokedex_clock.rs @@ -45,22 +45,155 @@ impl PokedexClock { ) { let w = matrix.width() as i32; let h = matrix.height() as i32; - if w < 64 || h < 64 || (w >= h && w < 192) { + let valid_tall = w >= 64 && h >= 64 && (h > w || w >= 192); + let valid_ribbon = w >= 192 && h >= 32 && h < 64; + if !valid_tall && !valid_ribbon { super::wide_only_notice(matrix, font, scale); return; } - let d = cwscene::divisor(h); if minutes != self.last_minute { self.last_minute = minutes; self.sprite = (self.sprite + 1) % 7; } - cwscene::draw_background(matrix, &POKEDEX_BG, w, h); - let creatures: [&[u16]; 7] = [ &POKEMON1, &POKEMON2, &POKEMON3, &POKEMON4, &POKEMON5, &POKEMON6, &POKEMON7, ]; + + if valid_ribbon { + // Widescreen Pokédex ribbon (e.g. 192x32): crimson chassis, blinking sensor lens, + // un-shrunk 16x16 creature screen, central HH:MM digital readout, and weekday/seconds telemetry. + matrix.fill_rect(0, 0, w, h, 180, 24, 36); + matrix.fill_rect(0, 0, w, 2, 225, 60, 72); + matrix.fill_rect(0, h - 2, w, 2, 110, 10, 18); + + // Blinking blue sensor lens + R/Y/G indicator LEDs on left + let lamp_on = seconds % 2 == 0; + let (lr, lg, lb) = if lamp_on { + (40, 235, 255) + } else { + (16, 110, 180) + }; + matrix.fill_rect(6, 5, 8, 8, 230, 235, 245); + matrix.fill_rect(7, 6, 6, 6, lr, lg, lb); + matrix.set_pixel(8, 7, 255, 255, 255); + matrix.fill_rect(6, 17, 2, 2, 255, 60, 60); + matrix.fill_rect(10, 17, 2, 2, 255, 215, 0); + matrix.fill_rect(14, 17, 2, 2, 50, 220, 90); + + // Native 16x16 Pokémon display bezel + let scr_x = 22; + let scr_y = (h - 22) / 2; + matrix.fill_rect(scr_x, scr_y, 24, 22, 210, 215, 220); + matrix.fill_rect(scr_x + 2, scr_y + 2, 20, 18, 18, 38, 32); + let spr = creatures[self.sprite]; + for row in 0..16i32 { + for col in 0..16i32 { + let c = spr[(row * 16 + col) as usize]; + if c != 0x0000 { + cwscene::put(matrix, scr_x + 4 + col, scr_y + 3 + row, c); + } + } + } + + // Central dark telemetry screen for HH:MM + let mid_x = 52; + let mid_w = w - 52 - 48; + matrix.fill_rect(mid_x, 4, mid_w, h - 8, 14, 26, 36); + matrix.draw_rect(mid_x, 4, mid_w, h - 8, 70, 140, 165); + let time_txt = format!("{:02}:{:02}", hours, minutes); + let mut t_scale = 2.0f32; + let (_, mut tw, mut th) = font.get_pixel_map(&time_txt, t_scale); + if tw > mid_w - 6 || th > h - 10 { + t_scale = 1.0; + let (_, w1, h1) = font.get_pixel_map(&time_txt, t_scale); + tw = w1; + th = h1; + } + BaseRenderer::draw_text_at( + matrix, + &time_txt, + font, + t_scale, + mid_x + (mid_w - tw) / 2, + (h - th) / 2, + (150, 255, 210), + (0, 0, 0), + ); + + // Right telemetry module: 7-day grid + animated seconds bar + let rx = w - 42; + matrix.fill_rect(rx, 4, 36, 12, 12, 28, 48); + let wd = Local::now().weekday().num_days_from_sunday() as i32; + for d_idx in 0..7i32 { + let col_x = rx + 2 + (d_idx % 4) * 8; + let row_y = 6 + (d_idx / 4) * 5; + let c = if d_idx == wd { 0x07FF } else { DARK_BLUE }; + fill(matrix, col_x, row_y, 6, 3, c); + } + + matrix.fill_rect(rx, 19, 36, 8, 10, 32, 22); + let bar_len = if seconds == 0 { + 32 + } else { + ((32 * seconds as i32) / 59).clamp(1, 32) + }; + fill( + matrix, + rx + 2, + 21, + bar_len, + 4, + if seconds == 0 { + LIGHT_GREEN + } else { + DARK_GREEN + }, + ); + return; + } + + let d = cwscene::divisor(h); + cwscene::draw_background(matrix, &POKEDEX_BG, w, h); + if w > 64 && !(w == 256 && h == 64) { + let ox = cwscene::origin_x(w, h); + let scene_w = cwscene::scaled_size(h); + for &(wx, ww) in &[(0, ox), (ox + scene_w, w - (ox + scene_w))] { + if ww <= 2 { + continue; + } + matrix.fill_rect(wx, 0, ww, h, 180, 24, 36); + matrix.fill_rect(wx, 0, ww, 2, 225, 60, 72); + matrix.fill_rect(wx, h - 2, ww, 2, 110, 10, 18); + matrix.fill_rect(wx, 2, 1, h - 4, 120, 14, 22); + matrix.fill_rect(wx + ww - 1, 2, 1, h - 4, 120, 14, 22); + if ww >= 20 && h >= 24 { + let cx = wx + ww / 2; + let cy = h / 2; + let r = 7i32; + for dy in -r..=r { + for dx in -r..=r { + let d2 = dx * dx + dy * dy; + if d2 <= r * r { + let (pr, pg, pb) = if d2 >= (r - 1) * (r - 1) { + (25, 25, 32) + } else if d2 <= 4 { + (245, 250, 255) + } else if d2 <= 9 || dy.abs() <= 1 { + (30, 30, 38) + } else if dy < 0 { + (240, 42, 48) + } else { + (235, 240, 248) + }; + matrix.set_pixel(cx + dx, cy + dy, pr, pg, pb); + } + } + } + } + } + } cwscene::draw_sprite(matrix, creatures[self.sprite], 16, 16, 8, 21, w, h, 0x0000); BaseRenderer::draw_text_at( diff --git a/src/engines/clocks/sonic_clock.rs b/src/engines/clocks/sonic_clock.rs index bef79445..9e459514 100644 --- a/src/engines/clocks/sonic_clock.rs +++ b/src/engines/clocks/sonic_clock.rs @@ -313,18 +313,19 @@ impl SonicClock { Self::draw_green_hill_ground(matrix, w, h, 12); } else if h >= 48 { - matrix.fill_rect(0, 0, w, 48, sky_blue.0, sky_blue.1, sky_blue.2); + let sky_h = h - 16; + matrix.fill_rect(0, 0, w, sky_h, sky_blue.0, sky_blue.1, sky_blue.2); let mountain_col = (32, 144, 96); let mut x = 0; while x < w { matrix.fill_triangle( x, - 48, + sky_h, x + 20, - 24, + sky_h - 24, x + 40, - 48, + sky_h, mountain_col.0, mountain_col.1, mountain_col.2, @@ -334,13 +335,65 @@ impl SonicClock { Self::draw_green_hill_ground(matrix, w, h, 16); } else { - matrix.fill_rect(0, 0, w, 23, sky_blue.0, sky_blue.1, sky_blue.2); + let sky_h = h - 9; + matrix.fill_rect(0, 0, w, sky_h, sky_blue.0, sky_blue.1, sky_blue.2); Self::draw_green_hill_ground(matrix, w, h, 9); - matrix.draw_line(120, 10, 118, 23, 160, 112, 48); - matrix.draw_line(121, 10, 119, 23, 160, 112, 48); - matrix.fill_triangle(114, 8, 120, 6, 126, 8, 0, 180, 0); - matrix.fill_triangle(114, 8, 120, 11, 126, 8, 0, 180, 0); + // Right Green Hill palm tree (`120` on 128x32, `184` on 192x32) + let palm_x = w - 8; + matrix.draw_line(palm_x, sky_h - 13, palm_x - 2, sky_h, 160, 112, 48); + matrix.draw_line(palm_x + 1, sky_h - 13, palm_x - 1, sky_h, 160, 112, 48); + matrix.fill_triangle( + palm_x - 6, + sky_h - 15, + palm_x, + sky_h - 17, + palm_x + 6, + sky_h - 15, + 0, + 180, + 0, + ); + matrix.fill_triangle( + palm_x - 6, + sky_h - 15, + palm_x, + sky_h - 12, + palm_x + 6, + sky_h - 15, + 0, + 180, + 0, + ); + + // Symmetrical left Green Hill palm + hills on ultra-wide custom ribbons (192x32, 256x32) + if w >= 160 { + let lp = 8; + matrix.draw_line(lp, sky_h - 13, lp + 2, sky_h, 160, 112, 48); + matrix.draw_line(lp + 1, sky_h - 13, lp + 3, sky_h, 160, 112, 48); + matrix.fill_triangle( + lp - 6, + sky_h - 15, + lp, + sky_h - 17, + lp + 6, + sky_h - 15, + 0, + 180, + 0, + ); + matrix.fill_triangle( + lp - 6, + sky_h - 15, + lp, + sky_h - 12, + lp + 6, + sky_h - 15, + 0, + 180, + 0, + ); + } } } @@ -570,7 +623,11 @@ impl SonicClock { } } } else { - let target_x = if h >= 48 { 36.0 } else { 10.0 }; + let target_x = if h >= 48 { + ((w - 88) / 2 - 48).max(2) as f32 + } else { + ((w - 66) / 2 - 21).max(2) as f32 + }; self.sonic_x += 130.0 * dt; if self.sonic_x >= target_x { self.sonic_x = target_x; @@ -710,29 +767,50 @@ impl SonicClock { } } } else if h >= 48 { - Self::blit_sprite( - matrix, - &SONIC_ITEM_BOX_PAL, - &SONIC_ITEM_BOX_PIXELS, - SONIC_ITEM_BOX_W, - SONIC_ITEM_BOX_H, - 52, - 16, - false, - ); - Self::draw_arcade_time(matrix, 84, 15, &time_buf, yellow_time, 4); - Self::blit_sprite(matrix, ring_pal, ring_pix, 16, 16, 178, 22, false); - let moto_x = 208 + moto_offset as i32; - Self::blit_sprite( - matrix, - &SONIC_MOTOBUG_PAL, - &SONIC_MOTOBUG_PIXELS, - SONIC_MOTOBUG_W, - SONIC_MOTOBUG_H, - moto_x, - 64 - 16 - 29, - moto_flip, - ); + let (scale, tw) = if w < 96 { (2, 44) } else { (4, 88) }; + let time_x = (w - tw) / 2; + let sky_h = h - 16; + let time_y = (sky_h - 5 * scale) / 2 + 1; + let box_x = (time_x - 32).max(2); + let box_y = sky_h - 32; + if w >= 128 { + Self::blit_sprite( + matrix, + &SONIC_ITEM_BOX_PAL, + &SONIC_ITEM_BOX_PIXELS, + SONIC_ITEM_BOX_W, + SONIC_ITEM_BOX_H, + box_x, + box_y, + false, + ); + } + Self::draw_arcade_time(matrix, time_x, time_y, &time_buf, yellow_time, scale); + if time_x + tw + 22 <= w { + Self::blit_sprite( + matrix, + ring_pal, + ring_pix, + 16, + 16, + time_x + tw + 6, + sky_h - 26, + false, + ); + } + if w >= 176 { + let moto_x = (w - 48) + moto_offset as i32; + Self::blit_sprite( + matrix, + &SONIC_MOTOBUG_PAL, + &SONIC_MOTOBUG_PIXELS, + SONIC_MOTOBUG_W, + SONIC_MOTOBUG_H, + moto_x, + sky_h - 29, + moto_flip, + ); + } if self.phase != Phase::Idle { if self.phase == Phase::JumpStrike || self.phase == Phase::Impact { @@ -747,7 +825,7 @@ impl SonicClock { false, ); if self.phase == Phase::Impact { - matrix.fill_circle(52 + 16, 16 + 16, 5, 255, 255, 255); + matrix.fill_circle(box_x + 16, box_y + 16, 5, 255, 255, 255); } } else { Self::blit_sprite( @@ -763,8 +841,26 @@ impl SonicClock { } } } else { - Self::blit_sprite(matrix, ring_pal, ring_pix, 16, 16, 10, 6, false); - Self::draw_arcade_time(matrix, 31, 6, &time_buf, yellow_time, 3); + let (scale, tw) = if w < 80 { (2, 44) } else { (3, 66) }; + let time_x = (w - tw) / 2; + let ring_x = (time_x - 21).max(2); + if w >= 96 { + Self::blit_sprite(matrix, ring_pal, ring_pix, 16, 16, ring_x, 6, false); + } + Self::draw_arcade_time(matrix, time_x, 6, &time_buf, yellow_time, scale); + // Symmetrical right Golden Ring on ultra-wide 32px ribbons (e.g. 192x32, 256x32) + if w >= 160 { + Self::blit_sprite( + matrix, + ring_pal, + ring_pix, + 16, + 16, + time_x + tw + 5, + 6, + false, + ); + } if self.phase != Phase::Idle { if self.phase == Phase::JumpStrike || self.phase == Phase::Impact { @@ -779,7 +875,7 @@ impl SonicClock { false, ); if self.phase == Phase::Impact { - matrix.fill_circle(20, 14, 3, 255, 255, 255); + matrix.fill_circle(ring_x + 10, 14, 3, 255, 255, 255); } } else { Self::blit_sprite( diff --git a/src/engines/clocks/words_clock.rs b/src/engines/clocks/words_clock.rs index 277d70e4..a60a5aae 100644 --- a/src/engines/clocks/words_clock.rs +++ b/src/engines/clocks/words_clock.rs @@ -29,13 +29,45 @@ impl WordsClock { ) { let w = matrix.width() as i32; let h = matrix.height() as i32; - if w < 192 || h < 64 { + if w < 192 || h < 32 { super::wide_only_notice(matrix, font, scale); return; } matrix.clear(); let (hour_words, minute_words) = spoken_time(hours, minutes, lang); + let now = Local::now(); + let date = date_line( + now.weekday().num_days_from_sunday() as usize, + now.month0() as usize, + now.day() as i32, + lang, + ); + + if h < 64 { + let full_words = if minute_words.is_empty() { + hour_words + } else { + format!("{} {}", hour_words, minute_words) + }; + centre( + matrix, + &full_words, + font, + 1.0, + h * 26 / 100, + (255, 255, 255), + w, + ); + let rule_w = w * 3 / 4; + let rule_y = h / 2; + for x in ((w - rule_w) / 2)..((w - rule_w) / 2 + rule_w) { + matrix.set_pixel(x, rule_y, ACCENT.0, ACCENT.1, ACCENT.2); + } + centre(matrix, &date, font, 1.0, h * 77 / 100, ACCENT, w); + return; + } + let s = scale.max(1) as f32; centre(matrix, &hour_words, font, s, h * 22 / 100, ACCENT, w); @@ -55,13 +87,6 @@ impl WordsClock { matrix.set_pixel(x, rule_y, 255, 255, 255); } - let now = Local::now(); - let date = date_line( - now.weekday().num_days_from_sunday() as usize, - now.month0() as usize, - now.day() as i32, - lang, - ); centre(matrix, &date, font, s, h * 80 / 100, ACCENT, w); } } diff --git a/src/engines/clocks/worldmap_clock.rs b/src/engines/clocks/worldmap_clock.rs index 3ce54437..95065b5e 100644 --- a/src/engines/clocks/worldmap_clock.rs +++ b/src/engines/clocks/worldmap_clock.rs @@ -85,13 +85,20 @@ impl WorldMapClock { } let text = format!("{}:{:02}", hours, minutes); + let (tx, ty) = if h < 64 { + let (_, _, th) = font.get_pixel_map(&text, 1.0); + (4, (h - th - 1).max(0)) + } else { + (cwscene::map_x(1, w, h), cwscene::map_y(58, h)) + }; + let eff_scale = if h < 64 { 1.0 } else { scale.max(1) as f32 }; BaseRenderer::draw_text_at( matrix, &text, font, - scale.max(1) as f32, - cwscene::map_x(1, w, h), - cwscene::map_y(58, h), + eff_scale, + tx, + ty, (255, 255, 255), (0, 0, 0), ); diff --git a/src/engines/crypto.rs b/src/engines/crypto.rs index 279457b0..388797aa 100644 --- a/src/engines/crypto.rs +++ b/src/engines/crypto.rs @@ -140,7 +140,12 @@ impl CryptoEngine { } } - fn advance_page_if_due(&mut self, height: u32) { + #[inline] + fn is_unified_ultrawide_32(width: u32, height: u32) -> bool { + width >= 160 && (32..64).contains(&height) + } + + fn advance_page_if_due(&mut self, width: u32, height: u32) { if self.symbols.is_empty() { return; } @@ -157,7 +162,7 @@ impl CryptoEngine { return; } - if height >= 64 || !self.show_chart { + if height >= 64 || Self::is_unified_ultrawide_32(width, height) || !self.show_chart { self.current_page = CryptoPage::Info; self.symbols_shown_this_cycle += 1; if self.symbols_shown_this_cycle < self.symbols.len() { @@ -789,6 +794,176 @@ impl CryptoEngine { } } + #[allow(clippy::too_many_arguments)] + fn render_unified_ultrawide_32( + &self, + matrix: &mut dyn IDrawingSurface, + symbol: &str, + price_str: &str, + pct_str: &str, + badge_color: (u8, u8, u8), + success: bool, + price: f64, + change: f64, + cached_img: Option<&image::RgbaImage>, + history_opt: Option<&PriceHistory>, + elapsed_ms: u128, + lang: &str, + ) { + matrix.clear(); + let m_w = matrix.width() as i32; + let m_h = matrix.height() as i32; + let tf_label = self.chart_timeframe.label(); + + let div_x = ((m_w * 46) / 100).clamp(84, 116); + let icon_y = ((m_h - 16) / 2).max(0); + draw_crypto_icon(matrix, symbol, 2, icon_y, 16, cached_img); + draw_fast_vline(matrix, div_x, 3, m_h - 6, (50, 50, 50)); + + let tf_w = tf_label.len() as i32 * 6; + let sym_end = (div_x - tf_w - 4).max(26); + draw_scrolling_text( + matrix, + symbol, + 20, + sym_end, + 2, + 1, + (255, 255, 255), + elapsed_ms, + false, + ); + draw_glcd_text(matrix, tf_label, div_x - tf_w - 2, 2, (130, 130, 130)); + + draw_scrolling_text( + matrix, + price_str, + 20, + div_x - 3, + 12, + 1, + (255, 215, 0), + elapsed_ms, + false, + ); + + let pct_text = if success && price > 0.0 { + format!("{} {}", if change >= 0.0 { "^" } else { "v" }, pct_str) + } else { + pct_str.to_string() + }; + draw_scrolling_text( + matrix, + &pct_text, + 20, + div_x - 3, + 22, + 1, + badge_color, + elapsed_ms, + false, + ); + + let spark_x = div_x + 4; + let spark_y = 4; + let spark_w = (m_w - spark_x - 3).max(8) as u32; + let spark_h = (m_h - 8).max(8) as u32; + + if let Some(hist) = history_opt { + if hist.points.len() > 1 { + let is_up = + hist.points.last().unwrap_or(&0.0) >= hist.points.first().unwrap_or(&0.0); + let line_color = if is_up { (0, 255, 120) } else { (255, 60, 60) }; + let fill_color = if is_up { + Some((0, 35, 12)) + } else { + Some((40, 12, 12)) + }; + draw_sparkline( + matrix, hist, spark_x, spark_y, spark_w, spark_h, line_color, fill_color, + ); + return; + } + } + draw_glcd_text( + matrix, + crate::core::i18n::t(lang, "loading_chart"), + spark_x + 4, + spark_y + (spark_h as i32 / 2) - 3, + (120, 120, 120), + ); + } + + #[allow(clippy::too_many_arguments)] + fn render_ultrawide_quote_32( + &self, + matrix: &mut dyn IDrawingSurface, + symbol: &str, + price_str: &str, + pct_str: &str, + badge_color: (u8, u8, u8), + success: bool, + price: f64, + change: f64, + cached_img: Option<&image::RgbaImage>, + elapsed_ms: u128, + ) { + matrix.clear(); + let m_w = matrix.width() as i32; + let m_h = matrix.height() as i32; + let icon_y = ((m_h - 16) / 2).max(0); + draw_crypto_icon(matrix, symbol, 4, icon_y, 16, cached_img); + + draw_glcd_text(matrix, symbol, 24, 5, (255, 255, 255)); + draw_glcd_text(matrix, "24h", 24, 18, (130, 130, 130)); + + let badge_text = if success && price > 0.0 { + format!("{} {}", if change >= 0.0 { "^" } else { "v" }, pct_str) + } else { + pct_str.to_string() + }; + let badge_w = badge_text.len() as i32 * 6 + 6; + let badge_x = m_w - badge_w - 4; + let badge_y = (m_h - 11) / 2; + let (pill_bg, pill_border) = if !success || price <= 0.0 { + ((28, 28, 28), (70, 70, 70)) + } else if change >= 0.0 { + ((0, 36, 16), (0, 130, 65)) + } else { + ((42, 10, 10), (150, 40, 40)) + }; + fill_round_rect(matrix, badge_x, badge_y, badge_w, 11, 2, pill_bg); + draw_round_rect(matrix, badge_x, badge_y, badge_w, 11, 2, pill_border); + draw_glcd_text(matrix, &badge_text, badge_x + 3, badge_y + 2, badge_color); + + let price_left = 24 + (symbol.len() as i32).max(3) * 6 + 8; + let price_right = (badge_x - 6).max(price_left + 18); + let avail_w = price_right - price_left; + let big_w = price_str.len() as i32 * 12; + if big_w <= avail_w && m_h >= 28 { + let px = price_left + (avail_w - big_w) / 2; + draw_glcd_text_scaled(matrix, price_str, px, (m_h - 14) / 2, 2, (255, 215, 0)); + } else { + let small_w = price_str.len() as i32 * 6; + if small_w <= avail_w { + let px = price_left + (avail_w - small_w) / 2; + draw_glcd_text(matrix, price_str, px, (m_h - 7) / 2, (255, 215, 0)); + } else { + draw_scrolling_text( + matrix, + price_str, + price_left, + price_right, + (m_h - 7) / 2, + 1, + (255, 215, 0), + elapsed_ms, + false, + ); + } + } + } + fn render_unified_wide( &self, matrix: &mut dyn IDrawingSurface, @@ -811,7 +986,11 @@ impl CryptoEngine { draw_crypto_icon(matrix, symbol, 4, 4, 16, cached_img); - let div_x = 58; + let div_x = if m_w >= 320 { + ((m_w * 26) / 100).clamp(72, 112) + } else { + 58 + }; draw_fast_vline(matrix, div_x, 4, m_h - 8, (50, 50, 50)); draw_scrolling_text( @@ -855,9 +1034,9 @@ impl CryptoEngine { false, ); - let spark_x = 62; + let spark_x = div_x + 4; let spark_y = 6; - let spark_w = matrix.width().saturating_sub(66); + let spark_w = matrix.width().saturating_sub((div_x + 8) as u32); let spark_h = matrix.height().saturating_sub(12); if let Some(hist) = history_opt { @@ -1151,8 +1330,9 @@ impl Engine for CryptoEngine { } fn update(&mut self, context: &mut EngineContext) { + let width = context.surface.width(); let height = context.surface.height(); - self.advance_page_if_due(height); + self.advance_page_if_due(width, height); } fn self_paced(&self) -> bool { @@ -1179,8 +1359,9 @@ impl Engine for CryptoEngine { sys_lang.as_str() }; + let width = context.surface.width(); let height = context.surface.height(); - self.advance_page_if_due(height); + self.advance_page_if_due(width, height); let matrix = &mut *context.surface; let width = matrix.width(); @@ -1232,6 +1413,19 @@ impl Engine for CryptoEngine { loaded_icon.as_ref(), elapsed_ms, ); + } else if Self::is_unified_ultrawide_32(width, height) { + self.render_ultrawide_quote_32( + matrix, + &symbol, + &price_str, + &pct_str, + badge_color, + success, + price, + change, + loaded_icon.as_ref(), + elapsed_ms, + ); } else { self.render_quote( matrix, @@ -1275,6 +1469,21 @@ impl Engine for CryptoEngine { lang, ); } + } else if Self::is_unified_ultrawide_32(width, height) { + self.render_unified_ultrawide_32( + matrix, + &symbol, + &price_str, + &pct_str, + badge_color, + success, + price, + change, + loaded_icon.as_ref(), + history_opt.as_ref(), + elapsed_ms, + lang, + ); } else if self.current_page == CryptoPage::Info { self.render_quote( matrix, @@ -1623,4 +1832,137 @@ mod tests { assert_eq!(engine.current_index, 0); assert!(!engine.is_finished()); } + + #[test] + fn test_crypto_128x32_and_256x64_zero_regression() { + fn fnv1a(s: &MockSurface) -> u64 { + let mut h: u64 = 0xcbf29ce484222325; + for &b in s.canvas.as_raw() { + h ^= b as u64; + h = h.wrapping_mul(0x100000001b3); + } + h + } + + let hist = PriceHistory { + points: vec![91000.0, 92400.0, 91800.0, 94500.0, 96200.0, 98450.0], + min: 91000.0, + max: 98450.0, + }; + let engine = CryptoEngine::new(128, 32); + + let mut s128_q = MockSurface::new(128, 32); + engine.render_quote( + &mut s128_q, + "BTC", + "$98450", + "+3.42%", + (0, 255, 120), + None, + 0, + ); + + let mut s128_c = MockSurface::new(128, 32); + engine.render_chart(&mut s128_c, "BTC", "$98450", Some(&hist), 0, "en"); + + let mut s256_u = MockSurface::new(256, 64); + engine.render_unified_wide( + &mut s256_u, + "BTC", + "$98450", + "+3.42%", + (0, 255, 120), + true, + 98450.0, + 3.42, + None, + Some(&hist), + 0, + "en", + ); + + let mut s256_fs = MockSurface::new(256, 64); + engine.render_fullscreen_quote( + &mut s256_fs, + "BTC", + "$98450", + "+3.42%", + (0, 255, 120), + true, + 98450.0, + 3.42, + None, + 0, + ); + + assert_eq!(fnv1a(&s128_q), 0xa86d4120ac8b6e0d); + assert_eq!(fnv1a(&s128_c), 0x78c9f18f0cbde2db); + assert_eq!(fnv1a(&s256_u), 0x545a059cc040040c); + assert_eq!(fnv1a(&s256_fs), 0xc5165d47097bdf49); + + // Verify custom 192x32 renders both quote on left AND sparkline chart on right + let mut s192 = MockSurface::new(192, 32); + engine.render_unified_ultrawide_32( + &mut s192, + "BTC", + "$98450", + "+3.42%", + (0, 255, 120), + true, + 98450.0, + 3.42, + None, + Some(&hist), + 0, + "en", + ); + let mut left_lit = 0usize; + let mut right_lit = 0usize; + for y in 0..32 { + for x in 0..88 { + let p = s192.canvas.get_pixel(x, y); + if p[0] > 0 || p[1] > 0 || p[2] > 0 { + left_lit += 1; + } + } + for x in 92..192 { + let p = s192.canvas.get_pixel(x, y); + if p[0] > 0 || p[1] > 0 || p[2] > 0 { + right_lit += 1; + } + } + } + assert!(left_lit > 60, "expected left quote pane lit on 192x32"); + assert!( + right_lit > 80, + "expected right sparkline pane lit on 192x32" + ); + + let mut s192_nochart = MockSurface::new(192, 32); + engine.render_ultrawide_quote_32( + &mut s192_nochart, + "BTC", + "$98450", + "+3.42%", + (0, 255, 120), + true, + 98450.0, + 3.42, + None, + 0, + ); + let mut badge_lit = 0usize; + for y in 0..32 { + for x in 120..192 { + let p = s192_nochart.canvas.get_pixel(x, y); + if p[0] > 0 || p[1] > 0 || p[2] > 0 { + badge_lit += 1; + } + } + } + assert!( + badge_lit > 40, + "expected right pill badge lit on 192x32 quote" + ); + } } diff --git a/src/engines/stock.rs b/src/engines/stock.rs index ff29a7f8..2f758f90 100644 --- a/src/engines/stock.rs +++ b/src/engines/stock.rs @@ -140,7 +140,12 @@ impl StockEngine { } } - fn advance_page_if_due(&mut self, height: u32) { + #[inline] + fn is_unified_ultrawide_32(width: u32, height: u32) -> bool { + width >= 160 && (32..64).contains(&height) + } + + fn advance_page_if_due(&mut self, width: u32, height: u32) { if self.symbols.is_empty() { return; } @@ -157,7 +162,7 @@ impl StockEngine { return; } - if height >= 64 || !self.show_chart { + if height >= 64 || Self::is_unified_ultrawide_32(width, height) || !self.show_chart { self.current_page = StockPage::Info; self.symbols_shown_this_cycle += 1; if self.symbols_shown_this_cycle < self.symbols.len() { @@ -785,6 +790,182 @@ impl StockEngine { } } + #[allow(clippy::too_many_arguments)] + fn render_unified_ultrawide_32( + &self, + matrix: &mut dyn IDrawingSurface, + symbol: &str, + price_str: &str, + pct_str: &str, + badge_color: (u8, u8, u8), + success: bool, + price: f64, + change: f64, + cached_img: Option<&image::RgbaImage>, + history_opt: Option<&PriceHistory>, + elapsed_ms: u128, + lang: &str, + ) { + matrix.clear(); + let m_w = matrix.width() as i32; + let m_h = matrix.height() as i32; + let tf_label = self.chart_timeframe.label(); + + let div_x = ((m_w * 46) / 100).clamp(84, 116); + let icon_y = ((m_h - 16) / 2).max(0); + draw_stock_icon(matrix, symbol, 2, icon_y, 16, cached_img); + draw_fast_vline(matrix, div_x, 3, m_h - 6, (50, 50, 50)); + + let tf_w = tf_label.len() as i32 * 6; + let sym_end = (div_x - tf_w - 4).max(26); + draw_scrolling_text( + matrix, + symbol, + 20, + sym_end, + 2, + 1, + (255, 255, 255), + elapsed_ms, + false, + ); + draw_glcd_text(matrix, tf_label, div_x - tf_w - 2, 2, (130, 130, 130)); + + draw_scrolling_text( + matrix, + price_str, + 20, + div_x - 3, + 12, + 1, + (0, 220, 255), + elapsed_ms, + false, + ); + + let pct_text = if success && price > 0.0 { + format!("{} {}", if change >= 0.0 { "^" } else { "v" }, pct_str) + } else { + pct_str.to_string() + }; + draw_scrolling_text( + matrix, + &pct_text, + 20, + div_x - 3, + 22, + 1, + badge_color, + elapsed_ms, + false, + ); + + let spark_x = div_x + 4; + let spark_y = 4; + let spark_w = (m_w - spark_x - 3).max(8) as u32; + let spark_h = (m_h - 8).max(8) as u32; + + if let Some(hist) = history_opt { + if hist.points.len() > 1 { + let is_up = + hist.points.last().unwrap_or(&0.0) >= hist.points.first().unwrap_or(&0.0); + let line_color = if is_up { (0, 255, 120) } else { (255, 60, 60) }; + let fill_color = if is_up { + Some((0, 35, 12)) + } else { + Some((40, 12, 12)) + }; + draw_sparkline( + matrix, hist, spark_x, spark_y, spark_w, spark_h, line_color, fill_color, + ); + return; + } + } + draw_glcd_text( + matrix, + crate::core::i18n::t(lang, "loading_chart"), + spark_x + 4, + spark_y + (spark_h as i32 / 2) - 3, + (120, 120, 120), + ); + } + + #[allow(clippy::too_many_arguments)] + fn render_ultrawide_quote_32( + &self, + matrix: &mut dyn IDrawingSurface, + symbol: &str, + price_str: &str, + pct_str: &str, + badge_color: (u8, u8, u8), + success: bool, + price: f64, + change: f64, + cached_img: Option<&image::RgbaImage>, + elapsed_ms: u128, + ) { + matrix.clear(); + let m_w = matrix.width() as i32; + let m_h = matrix.height() as i32; + let icon_y = ((m_h - 16) / 2).max(0); + draw_stock_icon(matrix, symbol, 4, icon_y, 16, cached_img); + + draw_glcd_text(matrix, symbol, 24, 5, (255, 255, 255)); + draw_glcd_text( + matrix, + self.chart_timeframe.label(), + 24, + 18, + (130, 130, 130), + ); + + let badge_text = if success && price > 0.0 { + format!("{} {}", if change >= 0.0 { "^" } else { "v" }, pct_str) + } else { + pct_str.to_string() + }; + let badge_w = badge_text.len() as i32 * 6 + 6; + let badge_x = m_w - badge_w - 4; + let badge_y = (m_h - 11) / 2; + let (pill_bg, pill_border) = if !success || price <= 0.0 { + ((28, 28, 28), (70, 70, 70)) + } else if change >= 0.0 { + ((0, 36, 16), (0, 130, 65)) + } else { + ((42, 10, 10), (150, 40, 40)) + }; + fill_round_rect(matrix, badge_x, badge_y, badge_w, 11, 2, pill_bg); + draw_round_rect(matrix, badge_x, badge_y, badge_w, 11, 2, pill_border); + draw_glcd_text(matrix, &badge_text, badge_x + 3, badge_y + 2, badge_color); + + let price_left = 24 + (symbol.len() as i32).max(4) * 6 + 8; + let price_right = (badge_x - 6).max(price_left + 18); + let avail_w = price_right - price_left; + let big_w = price_str.len() as i32 * 12; + if big_w <= avail_w && m_h >= 28 { + let px = price_left + (avail_w - big_w) / 2; + draw_glcd_text_scaled(matrix, price_str, px, (m_h - 14) / 2, 2, (0, 220, 255)); + } else { + let small_w = price_str.len() as i32 * 6; + if small_w <= avail_w { + let px = price_left + (avail_w - small_w) / 2; + draw_glcd_text(matrix, price_str, px, (m_h - 7) / 2, (0, 220, 255)); + } else { + draw_scrolling_text( + matrix, + price_str, + price_left, + price_right, + (m_h - 7) / 2, + 1, + (0, 220, 255), + elapsed_ms, + false, + ); + } + } + } + fn render_unified_wide( &self, matrix: &mut dyn IDrawingSurface, @@ -807,7 +988,11 @@ impl StockEngine { draw_stock_icon(matrix, symbol, 4, 4, 16, cached_img); - let div_x = 58; + let div_x = if m_w >= 320 { + ((m_w * 26) / 100).clamp(72, 112) + } else { + 58 + }; draw_fast_vline(matrix, div_x, 4, m_h - 8, (50, 50, 50)); draw_scrolling_text( @@ -851,9 +1036,9 @@ impl StockEngine { false, ); - let spark_x = 62; + let spark_x = div_x + 4; let spark_y = 6; - let spark_w = matrix.width().saturating_sub(66); + let spark_w = matrix.width().saturating_sub((div_x + 8) as u32); let spark_h = matrix.height().saturating_sub(12); if let Some(hist) = history_opt { @@ -1147,8 +1332,9 @@ impl Engine for StockEngine { } fn update(&mut self, context: &mut EngineContext) { + let width = context.surface.width(); let height = context.surface.height(); - self.advance_page_if_due(height); + self.advance_page_if_due(width, height); } fn self_paced(&self) -> bool { @@ -1175,8 +1361,9 @@ impl Engine for StockEngine { sys_lang.as_str() }; + let width = context.surface.width(); let height = context.surface.height(); - self.advance_page_if_due(height); + self.advance_page_if_due(width, height); let matrix = &mut *context.surface; let width = matrix.width(); @@ -1228,6 +1415,19 @@ impl Engine for StockEngine { loaded_icon.as_ref(), elapsed_ms, ); + } else if Self::is_unified_ultrawide_32(width, height) { + self.render_ultrawide_quote_32( + matrix, + &symbol, + &price_str, + &pct_str, + badge_color, + success, + price, + change, + loaded_icon.as_ref(), + elapsed_ms, + ); } else { self.render_quote( matrix, @@ -1271,6 +1471,21 @@ impl Engine for StockEngine { lang, ); } + } else if Self::is_unified_ultrawide_32(width, height) { + self.render_unified_ultrawide_32( + matrix, + &symbol, + &price_str, + &pct_str, + badge_color, + success, + price, + change, + loaded_icon.as_ref(), + history_opt.as_ref(), + elapsed_ms, + lang, + ); } else if self.current_page == StockPage::Info { self.render_quote( matrix, @@ -1609,4 +1824,136 @@ mod tests { assert_eq!(engine.current_index, 0); assert!(!engine.is_finished()); } + + #[test] + fn test_stock_128x32_and_256x64_zero_regression() { + fn fnv1a(s: &MockSurface) -> u64 { + let mut h: u64 = 0xcbf29ce484222325; + for &b in s.canvas.as_raw() { + h ^= b as u64; + h = h.wrapping_mul(0x100000001b3); + } + h + } + + let hist = PriceHistory { + points: vec![218.5, 221.0, 219.8, 224.2, 226.9, 229.40], + min: 218.5, + max: 229.40, + }; + let engine = StockEngine::new(128, 32); + + let mut s128_q = MockSurface::new(128, 32); + engine.render_quote( + &mut s128_q, + "AAPL", + "$229.40", + "+1.85%", + (0, 255, 120), + None, + 0, + ); + + let mut s128_c = MockSurface::new(128, 32); + engine.render_chart(&mut s128_c, "AAPL", "$229.40", Some(&hist), 0, "en"); + + let mut s256_u = MockSurface::new(256, 64); + engine.render_unified_wide( + &mut s256_u, + "AAPL", + "$229.40", + "+1.85%", + (0, 255, 120), + true, + 229.40, + 1.85, + None, + Some(&hist), + 0, + "en", + ); + + let mut s256_fs = MockSurface::new(256, 64); + engine.render_fullscreen_quote( + &mut s256_fs, + "AAPL", + "$229.40", + "+1.85%", + (0, 255, 120), + true, + 229.40, + 1.85, + None, + 0, + ); + + assert_eq!(fnv1a(&s128_q), 0xa680b170354407ee); + assert_eq!(fnv1a(&s128_c), 0x15e1aed1313f5c5b); + assert_eq!(fnv1a(&s256_u), 0x06e6daa013701906); + assert_eq!(fnv1a(&s256_fs), 0x83f5bdf02725aadd); + + let mut s192 = MockSurface::new(192, 32); + engine.render_unified_ultrawide_32( + &mut s192, + "AAPL", + "$229.40", + "+1.85%", + (0, 255, 120), + true, + 229.40, + 1.85, + None, + Some(&hist), + 0, + "en", + ); + let mut left_lit = 0usize; + let mut right_lit = 0usize; + for y in 0..32 { + for x in 0..88 { + let p = s192.canvas.get_pixel(x, y); + if p[0] > 0 || p[1] > 0 || p[2] > 0 { + left_lit += 1; + } + } + for x in 92..192 { + let p = s192.canvas.get_pixel(x, y); + if p[0] > 0 || p[1] > 0 || p[2] > 0 { + right_lit += 1; + } + } + } + assert!(left_lit > 60, "expected left quote pane lit on 192x32"); + assert!( + right_lit > 80, + "expected right sparkline pane lit on 192x32" + ); + + let mut s192_nochart = MockSurface::new(192, 32); + engine.render_ultrawide_quote_32( + &mut s192_nochart, + "AAPL", + "$229.40", + "+1.85%", + (0, 255, 120), + true, + 229.40, + 1.85, + None, + 0, + ); + let mut badge_lit = 0usize; + for y in 0..32 { + for x in 120..192 { + let p = s192_nochart.canvas.get_pixel(x, y); + if p[0] > 0 || p[1] > 0 || p[2] > 0 { + badge_lit += 1; + } + } + } + assert!( + badge_lit > 40, + "expected right pill badge lit on 192x32 quote" + ); + } } diff --git a/tests/test_base_resolutions_zero_regression.rs b/tests/test_base_resolutions_zero_regression.rs new file mode 100644 index 00000000..b3f70edf --- /dev/null +++ b/tests/test_base_resolutions_zero_regression.rs @@ -0,0 +1,256 @@ +//! Mathematical zero-regression framebuffer hash verification for base 4:1 panels (`128x32` and +//! `256x64`) alongside custom aspect-ratio (`192x32`, `256x32`, `192x64`, `384x64`) coverage tests +//! across all animated clock faces. + +use arcadematrix::core::matrix::MockSurface; +use arcadematrix::core::theme::is_theme_compatible; +use arcadematrix::engines::clocks::{ + BinaryClock, CastleClock, MarioClock, MegamanClock, MetalSlugClock, PokedexClock, PongClock, + SlotMachineClock, SonicClock, TetrisClock, VersusClock, WordClock, WordsClock, WorldMapClock, +}; +use arcadematrix::engines::renderers::BaseRenderer; + +fn fnv1a_surface(surface: &MockSurface) -> u64 { + let mut hash: u64 = 0xcbf29ce484222325; + for &b in surface.canvas.as_raw() { + hash ^= b as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + hash +} + +fn count_lit_in_x_range(surface: &MockSurface, x0: u32, x1: u32) -> usize { + let mut lit = 0usize; + for y in 0..surface.canvas.height() { + for x in x0..x1.min(surface.canvas.width()) { + let p = surface.canvas.get_pixel(x, y); + if p[0] > 0 || p[1] > 0 || p[2] > 0 { + lit += 1; + } + } + } + lit +} + +fn capture_clock_hashes(w: u32, h: u32) -> Vec<(&'static str, u64)> { + let renderer = BaseRenderer::new(); + let font = renderer.font(); + let mut out = Vec::new(); + + { + let mut s = MockSurface::new(w, h); + let c = BinaryClock::new(); + c.render(&mut s, 14, 37, 45, &font, 1); + out.push(("binary", fnv1a_surface(&s))); + } + { + let mut s = MockSurface::new(w, h); + let mut c = MarioClock::new(); + c.draw(&mut s, 14, 37, 0.016); + out.push(("mario_idle", fnv1a_surface(&s))); + for _ in 0..35 { + s.canvas.fill(0); + c.draw(&mut s, 14, 38, 0.025); + } + out.push(("mario_action", fnv1a_surface(&s))); + } + { + let mut s = MockSurface::new(w, h); + let mut c = CastleClock::new(); + c.draw(&mut s, 14, 37, 45, 0.016); + out.push(("castle_idle", fnv1a_surface(&s))); + for _ in 0..30 { + s.canvas.fill(0); + c.draw(&mut s, 14, 38, 0, 0.025); + } + out.push(("castle_action", fnv1a_surface(&s))); + } + { + let mut s = MockSurface::new(w, h); + let mut c = MegamanClock::new(); + c.draw(&mut s, 14, 37, 45, 0.016); + out.push(("megaman_idle", fnv1a_surface(&s))); + for _ in 0..30 { + s.canvas.fill(0); + c.draw(&mut s, 14, 38, 0, 0.025); + } + out.push(("megaman_action", fnv1a_surface(&s))); + } + { + let mut s = MockSurface::new(w, h); + let mut c = SonicClock::new(); + c.draw(&mut s, 14, 37, 45, 0.016); + out.push(("sonic_idle", fnv1a_surface(&s))); + for _ in 0..25 { + s.canvas.fill(0); + c.draw(&mut s, 14, 38, 0, 0.025); + } + out.push(("sonic_action", fnv1a_surface(&s))); + } + if w >= 192 && h >= 64 { + let mut s = MockSurface::new(w, h); + let mut c = MetalSlugClock::new(); + c.draw(&mut s, 14, 37, 45, 0.033); + out.push(("metal_slug_idle", fnv1a_surface(&s))); + for _ in 0..40 { + s.canvas.fill(0); + c.draw(&mut s, 14, 38, 0, 0.033); + } + out.push(("metal_slug_action", fnv1a_surface(&s))); + } + { + let mut s = MockSurface::new(w, h); + let mut c = VersusClock::new(); + c.render(&mut s, 14, 37, &font, 1); + out.push(("versus", fnv1a_surface(&s))); + } + { + let mut s = MockSurface::new(w, h); + let mut c = SlotMachineClock::new(); + c.render(&mut s, "14:37", 14, 37, &font, 1); + out.push(("slot_machine", fnv1a_surface(&s))); + } + { + let mut s = MockSurface::new(w, h); + let c = WordClock::new(); + c.render(&mut s, 14, 35, &font, 1, "en"); + out.push(("word_en", fnv1a_surface(&s))); + } + + out +} + +#[test] +fn test_base_128x32_and_256x64_bit_exact_zero_regression() { + let expected_128x32: &[(&str, u64)] = &[ + ("binary", 0x8c0e7f41bffcc84a), + ("mario_idle", 0x11b3ef3e3a3fff86), + ("mario_action", 0xcf40af9263b0de72), + ("castle_idle", 0x488f98566a4ad997), + ("castle_action", 0xe0789957bbcf9446), + ("megaman_idle", 0xc276f6afab875f0d), + ("megaman_action", 0xf030573d52a0958d), + ("sonic_idle", 0xeac99ab66ecf628b), + ("sonic_action", 0xe3e55111c87d0add), + ("versus", 0x31f02bce82974ef4), + ("slot_machine", 0x6f49940b6e293e36), + ("word_en", 0xe801df8a88db90ac), + ]; + + let expected_256x64: &[(&str, u64)] = &[ + ("binary", 0x0eaa362d766694ba), + ("mario_idle", 0x6f8c58740cdeb7f9), + ("mario_action", 0xda1ace27b0952966), + ("castle_idle", 0xe58f43911c70696b), + ("castle_action", 0x03cbb4c0fda96fe5), + ("megaman_idle", 0xe2453533bfb28cbd), + ("megaman_action", 0x98689dd183ea64d3), + ("sonic_idle", 0xbaa0d02f22df6ac3), + ("sonic_action", 0xe398c26c7aa4e6ed), + ("metal_slug_idle", 0x56571018fbf90064), + ("metal_slug_action", 0x70ef48a3b04b0103), + ("versus", 0xbbca94e51c981971), + ("slot_machine", 0x409edc84a1875f36), + ("word_en", 0xaaff1b7f59d883ac), + ]; + + let actual_128 = capture_clock_hashes(128, 32); + assert_eq!(actual_128.len(), expected_128x32.len()); + for ((name, got), (exp_name, exp)) in actual_128.iter().zip(expected_128x32.iter()) { + assert_eq!(name, exp_name); + assert_eq!( + got, exp, + "128x32 pixel regression on '{}': got 0x{:016x}, expected 0x{:016x}", + name, got, exp + ); + } + + let actual_256 = capture_clock_hashes(256, 64); + assert_eq!(actual_256.len(), expected_256x64.len()); + for ((name, got), (exp_name, exp)) in actual_256.iter().zip(expected_256x64.iter()) { + assert_eq!(name, exp_name); + assert_eq!( + got, exp, + "256x64 pixel regression on '{}': got 0x{:016x}, expected 0x{:016x}", + name, got, exp + ); + } + + // Theme compatibility on 128x32 and 256x64 must also remain 100% unchanged + for id in [32, 33, 37, 41] { + assert!(!is_theme_compatible(id, 128, 32)); + assert!(is_theme_compatible(id, 256, 64)); + assert!(is_theme_compatible(id, 192, 32)); + } +} + +#[test] +fn test_custom_192x32_and_ultrawide_clocks_balanced_coverage() { + let renderer = BaseRenderer::new(); + let font = renderer.font(); + + for &(w, h) in &[(192u32, 32u32), (256, 32), (192, 64), (384, 64)] { + // BinaryClock: symmetrical left/right halves + let mut s_bin = MockSurface::new(w, h); + BinaryClock::new().render(&mut s_bin, 23, 59, 58, &font, 1); + assert!(count_lit_in_x_range(&s_bin, 0, w / 2) > 20); + assert!(count_lit_in_x_range(&s_bin, w / 2, w) > 20); + + // MarioClock: scenery + blocks populate left, middle, and right thirds + let mut s_mario = MockSurface::new(w, h); + let mut mario = MarioClock::new(); + mario.draw(&mut s_mario, 14, 37, 0.016); + assert!(count_lit_in_x_range(&s_mario, 0, w / 3) > 30); + assert!(count_lit_in_x_range(&s_mario, w / 3, 2 * w / 3) > 30); + assert!(count_lit_in_x_range(&s_mario, 2 * w / 3, w) > 30); + + // CastleClock, MegamanClock, SonicClock, MetalSlugClock, Pokedex, WorldMap, Words, Pong, Tetris + let mut s_castle = MockSurface::new(w, h); + CastleClock::new().draw(&mut s_castle, 14, 37, 45, 0.016); + assert!(count_lit_in_x_range(&s_castle, w / 3, 2 * w / 3) > 40); + assert!(count_lit_in_x_range(&s_castle, 2 * w / 3, w) > 20); + + let mut s_mm = MockSurface::new(w, h); + MegamanClock::new().draw(&mut s_mm, 14, 37, 45, 0.016); + assert!(count_lit_in_x_range(&s_mm, w / 3, 2 * w / 3) > 40); + assert!(count_lit_in_x_range(&s_mm, 2 * w / 3, w) > 40); + + let mut s_sonic = MockSurface::new(w, h); + SonicClock::new().draw(&mut s_sonic, 14, 37, 45, 0.016); + assert!(count_lit_in_x_range(&s_sonic, w / 3, 2 * w / 3) > 40); + assert!(count_lit_in_x_range(&s_sonic, 2 * w / 3, w) > 40); + + let mut s_ms = MockSurface::new(w, h); + let mut ms = MetalSlugClock::new(); + ms.draw(&mut s_ms, 14, 37, 45, 0.033); + for _ in 0..35 { + ms.draw(&mut s_ms, 14, 38, 0, 0.033); + } + assert!(count_lit_in_x_range(&s_ms, 0, w / 3) > 50); + assert!(count_lit_in_x_range(&s_ms, w / 3, 2 * w / 3) > 50); + assert!(count_lit_in_x_range(&s_ms, 2 * w / 3, w) > 50); + + let mut s_pdx = MockSurface::new(w, h); + PokedexClock::new().render(&mut s_pdx, 14, 37, 45, &font, 1); + assert!(count_lit_in_x_range(&s_pdx, 0, w / 3) > 40); + assert!(count_lit_in_x_range(&s_pdx, w / 3, 2 * w / 3) > 40); + assert!(count_lit_in_x_range(&s_pdx, 2 * w / 3, w) > 40); + + let mut s_wm = MockSurface::new(w, h); + WorldMapClock::new().render(&mut s_wm, 14, 37, &font, 1); + assert!(count_lit_in_x_range(&s_wm, 0, w / 2) > 40); + assert!(count_lit_in_x_range(&s_wm, w / 2, w) > 40); + + let mut s_words = MockSurface::new(w, h); + WordsClock::new().render(&mut s_words, 14, 35, &font, 1, "en"); + assert!(count_lit_in_x_range(&s_words, w / 4, 3 * w / 4) > 30); + + let mut s_pong = MockSurface::new(w, h); + PongClock::new(w, h).update_and_render(&mut s_pong, 14, 37, &font, 1); + assert!(count_lit_in_x_range(&s_pong, 0, w / 2) > 15); + assert!(count_lit_in_x_range(&s_pong, w / 2, w) > 15); + + let mut s_tet = MockSurface::new(w, h); + TetrisClock::new(false).render(&mut s_tet, "14:37", &font, 2); + } +}