From d4e9af567864de49c6f93f7e6747ba54c8150dcf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 5 Jun 2026 16:24:36 +0100 Subject: [PATCH] Make Gjallar the Nightwing compositor --- Cargo.lock | 12 - Cargo.toml | 1 - README.md | 21 +- crates/gjallar-daemon/Cargo.toml | 18 - crates/gjallar-daemon/src/main.rs | 310 ----- crates/odin-core/src/documents.rs | 56 - crates/odin-core/src/gjallar.rs | 245 ---- crates/odin-core/src/lib.rs | 2 - crates/odin-core/src/repository.rs | 11 +- docs/architecture.md | 44 +- docs/gjallar.md | 113 +- scripts/write-gjallar-persona-cc.mjs | 18 +- src/Gjallar/Gjallar.csproj | 14 + src/Gjallar/Program.cs | 1795 ++++++++++++++++++++++++++ 14 files changed, 1898 insertions(+), 762 deletions(-) delete mode 100644 crates/gjallar-daemon/Cargo.toml delete mode 100644 crates/gjallar-daemon/src/main.rs delete mode 100644 crates/odin-core/src/gjallar.rs create mode 100644 src/Gjallar/Gjallar.csproj create mode 100644 src/Gjallar/Program.cs diff --git a/Cargo.lock b/Cargo.lock index 2660cc4..5cae94a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -356,18 +356,6 @@ dependencies = [ "polyval", ] -[[package]] -name = "gjallar-daemon" -version = "0.1.0" -dependencies = [ - "anyhow", - "cultcache-rs", - "cultmesh-rs", - "odin-core", - "rmp-serde", - "serde_json", -] - [[package]] name = "hashbrown" version = "0.15.5" diff --git a/Cargo.toml b/Cargo.toml index c7d6575..71ad6fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,5 @@ [workspace] members = [ - "crates/gjallar-daemon", "crates/idunn-daemon", "crates/odin-core", ] diff --git a/README.md b/README.md index 66b7723..b9612b5 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Odin is the GameCult all-seer: the central CultMesh node every Verse can use to discover the other Verses, inspect schema catalogs, and find translation paths between local realities. -It is not the renderer. It is not Eve. It is not a Starfire utility script wearing a bigger coat. Odin owns discovery, schema awareness, translation planning, and accepted operator surfaces. Eve and the Nightwing compact TUI lower Odin's published CultUI surface into whatever body they have. +It is not the renderer. It is not Eve. It is not a Starfire utility script wearing a bigger coat. Odin owns discovery, schema awareness, translation planning, and accepted operator surfaces. Eve clients and Gjallar lower Odin's published CultUI surface into whatever body they have. Odin is also the compliance witness for the GameCult service architecture: durable service state in CultCache `.cc`, local Verse visibility through @@ -18,22 +18,23 @@ CultNet document registries, and lower interface state through Eve/CultUI. The first Rust core lives in `crates/odin-core` and already separates typed documents, ingest ports, normalization, and repository persistence so unit tests can use mocked inputs and pipeline smokes can prove typed handoff without -booting the whole daemon. Gjallar is part of that spine as the typed overview -composition lane: it reads Odin-owned sight and publishes the compact feed that -Nightwing lowers into terminal cells. +booting the whole daemon. Gjallar is not part of that Rust record spine: it is +the Nightwing-resident terminal compositor that consumes Odin's published +Eve/CultUI deck and renders the live display. ## Gjallar -Gjallar is Odin's herald display daemon: the package that turns Odin's gathered -sight into the overview Nightwing displays. Odin sees the Verses; Gjallar -decides how that sight is grouped, prioritized, and packed into a feed. -Nightwing stays a thin fast terminal lowerer. +Gjallar is the herald display daemon that runs on Nightwing. Odin sees the +Verses, accepts provider surfaces, and publishes the `odin.allseer` deck. +Gjallar talks to Odin, enumerates active providers, composes the multi-scale +tiled dashboard, owns the marquee and dense character-level update behavior, +and writes the visible framebuffer. Local package surfaces: - Organ contract: `docs/gjallar.md` - Branding Persona state: `personas/gjallar.persona_state.cc` -- Rust CultMesh organ: `crates/gjallar-daemon` +- Runtime source: `src/Gjallar` - Avatar asset: `assets/personas/gjallar-avatar.png` - Pixel avatar: `assets/personas/gjallar-avatar-pixel-256.png` @@ -62,7 +63,7 @@ Local package surfaces: - Owner: Odin owns the network-wide Verse registry, schema catalog index, translation map, and the accepted `odin.allseer` Eve surface. - Inputs: CultMesh/CultNet peer announcements, schema catalog responses, local host probes, Docker/ADB host facts, SSH-reachable ops hosts, Mimir's normalized Eve observation ledger, and later direct Verse subscriptions. - Outputs: CultCache-backed Odin state, CultMesh documents, CultNet schema/catalog messages, and an Eve-compatible `/eve/deck` surface for dashboards. -- Derived state: Nightwing's attached TUI, browser dashboards, and future Eve clients are projections of Odin state. +- Derived state: Gjallar's attached Nightwing display, browser dashboards, and future Eve clients are projections of Odin state and provider-owned Eve/CultUI surfaces. - Forbidden writers: renderers do not probe the network or decide Verse truth; individual projects do not maintain private incompatible discovery ledgers once Odin can see them. - Shared paths: human dashboards, worker schedulers, Verse bootstrap code, and compact TUI views consume the same registry and schema catalog. - Deletion line: old per-host coordinator scripts should be deleted or reduced to deployment wrappers that start Odin. diff --git a/crates/gjallar-daemon/Cargo.toml b/crates/gjallar-daemon/Cargo.toml deleted file mode 100644 index 5ca33bc..0000000 --- a/crates/gjallar-daemon/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "gjallar-daemon" -version = "0.1.0" -edition.workspace = true -license.workspace = true -publish.workspace = true - -[[bin]] -name = "gjallar" -path = "src/main.rs" - -[dependencies] -anyhow = "1" -cultcache-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultcache-rs" } -cultmesh-rs = { path = "E:/Projects/EpiphanyAgent/vendor/cultmesh-rs" } -odin-core = { path = "../odin-core" } -rmp-serde = "1" -serde_json = "1" diff --git a/crates/gjallar-daemon/src/main.rs b/crates/gjallar-daemon/src/main.rs deleted file mode 100644 index 3df35e2..0000000 --- a/crates/gjallar-daemon/src/main.rs +++ /dev/null @@ -1,310 +0,0 @@ -use anyhow::{Context, Result, anyhow}; -use cultmesh_rs::{CultMesh, CultMeshNode, CultMeshNodeOptions}; -use odin_core::{ - EveSurfaceStateRecord, GjallarComposition, GjallarCompositionInput, GjallarOverviewRecord, - GjallarOverviewTileRecord, OdinDocuments, OdinInterfaceRecord, OdinObservationStreamRecord, - OdinServiceRecord, OdinSnapshotRecord, OdinTranslationRouteRecord, OdinVerseRecord, - compose_gjallar_overview, -}; -use std::env; -use std::path::PathBuf; -use std::thread; -use std::time::Duration; -use std::time::{SystemTime, UNIX_EPOCH}; - -#[derive(Clone, Debug)] -struct Options { - odin_store_path: PathBuf, - gjallar_store_path: PathBuf, - overview_id: String, - surface_key: String, - target_columns: u32, - verse_keys: Vec, - service_keys: Vec, - interface_keys: Vec, - observation_stream_keys: Vec, - translation_route_keys: Vec, - interval_seconds: Option, -} - -fn main() -> Result<()> { - let options = Options::parse(env::args().skip(1))?; - - if let Some(parent) = options.gjallar_store_path.parent() { - std::fs::create_dir_all(parent) - .with_context(|| format!("creating {}", parent.display()))?; - } - - if let Some(interval_seconds) = options.interval_seconds { - loop { - run_cycle(&options)?; - thread::sleep(Duration::from_secs(interval_seconds)); - } - } - - run_cycle(&options) -} - -fn run_cycle(options: &Options) -> Result<()> { - if !options.odin_store_path.exists() { - return Err(anyhow!( - "Odin CultMesh store not found: {}", - options.odin_store_path.display() - )); - } - - let odin = CultMesh::create_node( - &options.odin_store_path, - OdinDocuments, - CultMeshNodeOptions { - runtime_id: "gjallar-odin-reader".to_string(), - pull_on_start: true, - }, - )?; - - let mut gjallar = CultMesh::create_node( - &options.gjallar_store_path, - OdinDocuments, - CultMeshNodeOptions { - runtime_id: "gjallar-daemon".to_string(), - pull_on_start: true, - }, - )?; - - let composition = match odin.get::("latest")? { - Some(snapshot) => compose_gjallar_overview(GjallarCompositionInput { - overview_id: options.overview_id.clone(), - composed_at: timestamp()?, - target_columns: options.target_columns, - snapshot, - verses: read_many::(&odin, &options.verse_keys)?, - services: read_many::(&odin, &options.service_keys)?, - interfaces: read_many::(&odin, &options.interface_keys)?, - observation_streams: read_many::( - &odin, - &options.observation_stream_keys, - )?, - translation_routes: read_many::( - &odin, - &options.translation_route_keys, - )?, - }), - None => compose_from_compat_surface( - &options.overview_id, - options.target_columns, - timestamp()?, - read_compat_surface(&odin, &options.surface_key)?, - ), - }; - - gjallar.put(&composition.overview.overview_id, &composition.overview)?; - for tile in &composition.tiles { - gjallar.put(&tile.tile_id, tile)?; - } - - println!( - "Gjallar composed {} tiles for {}", - composition.overview.tile_count, composition.overview.overview_id - ); - println!("Odin source: {}", options.odin_store_path.display()); - println!("Gjallar feed: {}", options.gjallar_store_path.display()); - Ok(()) -} - -fn read_many(node: &CultMeshNode, keys: &[String]) -> Result> -where - T: cultcache_rs::DatabaseEntry, -{ - let mut records = Vec::new(); - for key in keys { - if let Some(record) = node.get::(key)? { - records.push(record); - } - } - Ok(records) -} - -fn read_compat_surface(node: &CultMeshNode, key: &str) -> Result { - let envelope = node - .cache() - .get_required_envelope::(key)?; - rmp_serde::from_slice(&envelope.payload).with_context(|| { - format!("decoding CommonJS Odin surface payload at {key:?} as MessagePack map") - }) -} - -fn compose_from_compat_surface( - overview_id: &str, - target_columns: u32, - composed_at: String, - surface: serde_json::Value, -) -> GjallarComposition { - let provider_id = string_field(&surface, "providerId", "surface"); - let detail = surface - .get("surface") - .and_then(|surface| surface.get("root")) - .or_else(|| surface.get("root")) - .and_then(|root| root.get("props")) - .and_then(|props| props.get("summary")) - .and_then(|summary| summary.as_str()) - .unwrap_or("Odin CommonJS surface"); - let title = string_field(&surface, "title", &provider_id); - let updated_at = string_field(&surface, "updatedAt", "unknown"); - let tile = GjallarOverviewTileRecord { - tile_id: format!("{overview_id}:tile:0"), - overview_id: overview_id.to_string(), - source_record: format!("gamecult.eve.surface_state:{provider_id}"), - tile_kind: "compat-surface".to_string(), - title, - state: "active".to_string(), - detail: detail.to_string(), - priority: 0, - row_span: 1, - column_span: target_columns.max(1), - observed_at: updated_at.clone(), - }; - GjallarComposition { - overview: GjallarOverviewRecord { - overview_id: overview_id.to_string(), - source_snapshot_id: provider_id, - title: "Gjallar".to_string(), - status: "active".to_string(), - summary: "1 drawable tile from Odin compatibility surface".to_string(), - tile_count: 1, - target_columns: target_columns.max(1), - target_rows: 1, - source_observed_at: updated_at, - composed_at, - }, - tiles: vec![tile], - } -} - -fn string_field(value: &serde_json::Value, key: &str, fallback: &str) -> String { - value - .get(key) - .and_then(|entry| entry.as_str()) - .filter(|entry| !entry.trim().is_empty()) - .unwrap_or(fallback) - .to_string() -} - -impl Options { - fn parse(args: impl Iterator) -> Result { - let repo_root = find_repo_root(env::current_dir().context("reading current directory")?); - let mut options = Options { - odin_store_path: repo_root.join("scratch").join("odin").join("odin.ccmp"), - gjallar_store_path: repo_root - .join("scratch") - .join("gjallar") - .join("gjallar.overview.ccmp"), - overview_id: "gjallar.overview:nightwing".to_string(), - surface_key: "surface:gamecult.network.status".to_string(), - target_columns: 4, - verse_keys: split_keys( - "starfire.local,nightwing.local,periwinkle.local,yggdrasil.local", - ), - service_keys: split_keys("odin,cultcache,interfaces,gpu"), - interface_keys: split_keys("odin.allseer"), - observation_stream_keys: split_keys("periwinkle:motion:sensor,periwinkle:camera:media"), - translation_route_keys: Vec::new(), - interval_seconds: None, - }; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--odin-store" => { - options.odin_store_path = PathBuf::from(take_value(&mut args, "--odin-store")?) - } - "--store" | "--gjallar-store" => { - options.gjallar_store_path = - PathBuf::from(take_value(&mut args, "--gjallar-store")?) - } - "--overview" => options.overview_id = take_value(&mut args, "--overview")?, - "--surface-key" => options.surface_key = take_value(&mut args, "--surface-key")?, - "--columns" => { - options.target_columns = take_value(&mut args, "--columns")? - .parse() - .context("--columns must be a positive integer")? - } - "--verses" => options.verse_keys = split_keys(take_value(&mut args, "--verses")?), - "--services" => { - options.service_keys = split_keys(take_value(&mut args, "--services")?) - } - "--interfaces" => { - options.interface_keys = split_keys(take_value(&mut args, "--interfaces")?) - } - "--streams" => { - options.observation_stream_keys = - split_keys(take_value(&mut args, "--streams")?) - } - "--routes" => { - options.translation_route_keys = split_keys(take_value(&mut args, "--routes")?) - } - "--interval-seconds" => { - options.interval_seconds = Some( - take_value(&mut args, "--interval-seconds")? - .parse() - .context("--interval-seconds must be a positive integer")?, - ) - } - "--help" | "-h" => return Err(anyhow!(help_text())), - other => { - return Err(anyhow!( - "unknown Gjallar argument: {other}\n\n{}", - help_text() - )); - } - } - } - - if options.overview_id.trim().is_empty() { - return Err(anyhow!("--overview must not be empty")); - } - if options.target_columns == 0 { - return Err(anyhow!("--columns must be greater than zero")); - } - if options.interval_seconds == Some(0) { - return Err(anyhow!("--interval-seconds must be greater than zero")); - } - - Ok(options) - } -} - -fn take_value(args: &mut impl Iterator, name: &str) -> Result { - args.next() - .ok_or_else(|| anyhow!("{name} requires a value")) -} - -fn split_keys(value: impl AsRef) -> Vec { - value - .as_ref() - .split(',') - .map(str::trim) - .filter(|entry| !entry.is_empty()) - .map(ToString::to_string) - .collect() -} - -fn find_repo_root(start: PathBuf) -> PathBuf { - for candidate in start.ancestors() { - if candidate.join("Cargo.toml").exists() && candidate.join("personas").is_dir() { - return candidate.to_path_buf(); - } - } - start -} - -fn timestamp() -> Result { - let seconds = SystemTime::now() - .duration_since(UNIX_EPOCH) - .context("system clock is before Unix epoch")? - .as_secs(); - Ok(format!("unix:{seconds}")) -} - -fn help_text() -> &'static str { - "Usage: gjallar [--odin-store ] [--gjallar-store ] [--overview ] [--surface-key ] [--columns ] [--verses ] [--services ] [--interfaces ] [--streams ] [--routes ] [--interval-seconds ]\n\nGjallar reads Odin-owned typed records and publishes a compact typed overview feed for Nightwing." -} diff --git a/crates/odin-core/src/documents.rs b/crates/odin-core/src/documents.rs index 16c1c59..d9a6dff 100644 --- a/crates/odin-core/src/documents.rs +++ b/crates/odin-core/src/documents.rs @@ -7,8 +7,6 @@ pub const ODIN_SERVICE_SCHEMA: &str = "odin.service.v1"; pub const ODIN_INTERFACE_SCHEMA: &str = "odin.interface.v1"; pub const ODIN_OBSERVATION_STREAM_SCHEMA: &str = "odin.observation_stream.v1"; pub const ODIN_TRANSLATION_ROUTE_SCHEMA: &str = "odin.translation_route.v1"; -pub const GJALLAR_OVERVIEW_SCHEMA: &str = "gjallar.overview.v1"; -pub const GJALLAR_OVERVIEW_TILE_SCHEMA: &str = "gjallar.overview_tile.v1"; pub const EVE_SURFACE_STATE_SCHEMA: &str = "gamecult.eve.surface_state.v1"; pub const EVE_INTERFACE_BINDING_SCHEMA: &str = "gamecult.eve.interface_binding.v1"; pub const EVE_PROVIDER_ADVERTISEMENT_SCHEMA: &str = "gamecult.eve.provider_advertisement.v1"; @@ -137,58 +135,6 @@ pub struct OdinTranslationRouteRecord { pub notes: String, } -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "gjallar.overview", schema = "gjallar.overview.v1")] -pub struct GjallarOverviewRecord { - #[cultcache(key = 0)] - pub overview_id: String, - #[cultcache(key = 1)] - pub source_snapshot_id: String, - #[cultcache(key = 2)] - pub title: String, - #[cultcache(key = 3)] - pub status: String, - #[cultcache(key = 4)] - pub summary: String, - #[cultcache(key = 5)] - pub tile_count: u32, - #[cultcache(key = 6)] - pub target_columns: u32, - #[cultcache(key = 7)] - pub target_rows: u32, - #[cultcache(key = 8)] - pub source_observed_at: String, - #[cultcache(key = 9)] - pub composed_at: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "gjallar.overview_tile", schema = "gjallar.overview_tile.v1")] -pub struct GjallarOverviewTileRecord { - #[cultcache(key = 0)] - pub tile_id: String, - #[cultcache(key = 1)] - pub overview_id: String, - #[cultcache(key = 2)] - pub source_record: String, - #[cultcache(key = 3)] - pub tile_kind: String, - #[cultcache(key = 4)] - pub title: String, - #[cultcache(key = 5)] - pub state: String, - #[cultcache(key = 6)] - pub detail: String, - #[cultcache(key = 7)] - pub priority: i32, - #[cultcache(key = 8)] - pub row_span: u32, - #[cultcache(key = 9)] - pub column_span: u32, - #[cultcache(key = 10)] - pub observed_at: String, -} - #[derive(Clone, Debug, PartialEq, DatabaseEntry)] #[cultcache( type = "gamecult.eve.surface_state", @@ -349,8 +295,6 @@ cultmesh_rs::cultmesh_documents!(OdinDocuments { OdinInterfaceRecord => ODIN_INTERFACE_SCHEMA, OdinObservationStreamRecord => ODIN_OBSERVATION_STREAM_SCHEMA, OdinTranslationRouteRecord => ODIN_TRANSLATION_ROUTE_SCHEMA, - GjallarOverviewRecord => GJALLAR_OVERVIEW_SCHEMA, - GjallarOverviewTileRecord => GJALLAR_OVERVIEW_TILE_SCHEMA, EveSurfaceStateRecord => EVE_SURFACE_STATE_SCHEMA, EveInterfaceBindingCompatRecord => EVE_INTERFACE_BINDING_SCHEMA, EveProviderAdvertisementCompatRecord => EVE_PROVIDER_ADVERTISEMENT_SCHEMA, diff --git a/crates/odin-core/src/gjallar.rs b/crates/odin-core/src/gjallar.rs deleted file mode 100644 index e3ce0f2..0000000 --- a/crates/odin-core/src/gjallar.rs +++ /dev/null @@ -1,245 +0,0 @@ -use crate::documents::{ - GjallarOverviewRecord, GjallarOverviewTileRecord, OdinInterfaceRecord, - OdinObservationStreamRecord, OdinServiceRecord, OdinSnapshotRecord, OdinTranslationRouteRecord, - OdinVerseRecord, -}; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct GjallarCompositionInput { - pub overview_id: String, - pub composed_at: String, - pub target_columns: u32, - pub snapshot: OdinSnapshotRecord, - pub verses: Vec, - pub services: Vec, - pub interfaces: Vec, - pub observation_streams: Vec, - pub translation_routes: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct GjallarComposition { - pub overview: GjallarOverviewRecord, - pub tiles: Vec, -} - -pub fn compose_gjallar_overview(input: GjallarCompositionInput) -> GjallarComposition { - let mut tiles = Vec::new(); - let overview_id = input.overview_id; - let target_columns = input.target_columns.max(1); - - tiles.push(tile( - &overview_id, - 0, - "odin.snapshot:latest", - "summary", - "Odin", - snapshot_status(&input.snapshot), - format!( - "{} verses / {} services / {} interfaces / {} streams", - input.snapshot.verse_count, - input.snapshot.service_count, - input.snapshot.interface_count, - input.snapshot.observation_stream_count - ), - input.snapshot.observed_at.clone(), - )); - - for (index, interface) in input.interfaces.iter().enumerate() { - tiles.push(tile( - &overview_id, - 100 + index as i32, - format!("odin.interface:{}", interface.provider_id), - "interface", - interface.title.clone(), - interface.state.clone(), - interface.source.clone(), - interface.observed_at.clone(), - )); - } - - for (index, stream) in input.observation_streams.iter().enumerate() { - tiles.push(tile( - &overview_id, - 300 + index as i32, - format!("odin.observation_stream:{}", stream.stream_key), - "observation-stream", - format!("{} {}", stream.device_id, stream.stream_id), - stream.state.clone(), - stream.detail.clone(), - stream.observed_at.clone(), - )); - } - - for (index, service) in input.services.iter().enumerate() { - tiles.push(tile( - &overview_id, - 500 + index as i32, - format!("odin.service:{}", service.service_id), - "service", - service.name.clone(), - service.state.clone(), - service.detail.clone(), - service.observed_at.clone(), - )); - } - - for (index, verse) in input.verses.iter().enumerate() { - tiles.push(tile( - &overview_id, - 700 + index as i32, - format!("odin.verse:{}", verse.verse_id), - "verse", - verse.name.clone(), - verse.status.clone(), - verse.role.clone(), - verse.observed_at.clone(), - )); - } - - for (index, route) in input.translation_routes.iter().enumerate() { - tiles.push(tile( - &overview_id, - 900 + index as i32, - format!("odin.translation_route:{}", route.route_id), - "translation-route", - route.target_schema.clone(), - route.translation_kind.clone(), - route.owner.clone(), - input.snapshot.observed_at.clone(), - )); - } - - tiles.sort_by(|left, right| left.priority.cmp(&right.priority)); - let target_rows = (tiles.len() as u32).div_ceil(target_columns).max(1); - let status = if tiles.iter().any(|entry| entry.state == "failed") { - "degraded" - } else { - "active" - }; - - let overview = GjallarOverviewRecord { - overview_id: overview_id.clone(), - source_snapshot_id: input.snapshot.snapshot_id, - title: "Gjallar".to_string(), - status: status.to_string(), - summary: format!("{} drawable tiles from Odin sight", tiles.len()), - tile_count: tiles.len() as u32, - target_columns, - target_rows, - source_observed_at: input.snapshot.observed_at, - composed_at: input.composed_at, - }; - - GjallarComposition { overview, tiles } -} - -fn tile( - overview_id: &str, - priority: i32, - source_record: impl Into, - tile_kind: impl Into, - title: impl Into, - state: impl Into, - detail: impl Into, - observed_at: impl Into, -) -> GjallarOverviewTileRecord { - GjallarOverviewTileRecord { - tile_id: format!("{}:tile:{priority}", overview_id), - overview_id: overview_id.to_string(), - source_record: source_record.into(), - tile_kind: tile_kind.into(), - title: title.into(), - state: state.into(), - detail: detail.into(), - priority, - row_span: 1, - column_span: 1, - observed_at: observed_at.into(), - } -} - -fn snapshot_status(snapshot: &OdinSnapshotRecord) -> String { - if snapshot.service_count == 0 && snapshot.interface_count == 0 { - "waiting".to_string() - } else { - "active".to_string() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - - #[test] - fn compose_overview_orders_dashboard_tiles_for_nightwing() { - let composition = compose_gjallar_overview(GjallarCompositionInput { - overview_id: "gjallar.overview:nightwing".to_string(), - composed_at: "2026-06-05T00:00:00Z".to_string(), - target_columns: 2, - snapshot: OdinSnapshotRecord { - snapshot_id: "latest".to_string(), - observed_at: "2026-06-05T00:00:00Z".to_string(), - verse_count: 1, - service_count: 1, - interface_count: 1, - observation_stream_count: 1, - source: "unit-test".to_string(), - }, - verses: vec![OdinVerseRecord { - verse_id: "nightwing.local".to_string(), - name: "Nightwing".to_string(), - role: "terminal-lowerer".to_string(), - status: "active".to_string(), - capabilities: vec!["tui".to_string()], - observed_at: "2026-06-05T00:00:00Z".to_string(), - }], - services: vec![OdinServiceRecord { - service_id: "odin".to_string(), - verse_id: "starfire.local".to_string(), - name: "Odin".to_string(), - state: "active".to_string(), - detail: "all-seer".to_string(), - authority: "odin".to_string(), - observed_at: "2026-06-05T00:00:00Z".to_string(), - }], - interfaces: vec![OdinInterfaceRecord { - provider_id: "odin.allseer".to_string(), - title: "Odin All-Seer".to_string(), - state: "active".to_string(), - source: "cultmesh".to_string(), - version: Some("v1".to_string()), - updated_at: None, - observed_at: "2026-06-05T00:00:00Z".to_string(), - }], - observation_streams: vec![OdinObservationStreamRecord { - stream_key: "periwinkle:motion:sensor".to_string(), - device_id: "periwinkle".to_string(), - stream_id: "motion".to_string(), - kind: "sensor".to_string(), - state: "active".to_string(), - detail: "fresh".to_string(), - owner: "mimir".to_string(), - observed_at: "2026-06-05T00:00:00Z".to_string(), - }], - translation_routes: vec![OdinTranslationRouteRecord { - route_id: "source=>target".to_string(), - source_schema: "source".to_string(), - target_schema: "target".to_string(), - translation_kind: "projection".to_string(), - owner: "odin".to_string(), - version: "v1".to_string(), - notes: "test".to_string(), - }], - }); - - assert_eq!(composition.overview.tile_count, 6); - assert_eq!(composition.overview.target_rows, 3); - assert_eq!(composition.tiles[0].tile_kind, "summary"); - assert_eq!( - composition.tiles[1].source_record, - "odin.interface:odin.allseer" - ); - } -} diff --git a/crates/odin-core/src/lib.rs b/crates/odin-core/src/lib.rs index 35ab51f..4eb7729 100644 --- a/crates/odin-core/src/lib.rs +++ b/crates/odin-core/src/lib.rs @@ -1,12 +1,10 @@ pub mod documents; -pub mod gjallar; pub mod idunn; pub mod pipeline; pub mod ports; pub mod repository; pub use documents::*; -pub use gjallar::*; pub use idunn::*; pub use pipeline::*; pub use ports::*; diff --git a/crates/odin-core/src/repository.rs b/crates/odin-core/src/repository.rs index d58e951..334e8b0 100644 --- a/crates/odin-core/src/repository.rs +++ b/crates/odin-core/src/repository.rs @@ -1,6 +1,5 @@ use crate::documents::{ - GjallarOverviewRecord, GjallarOverviewTileRecord, OdinDocuments, OdinRecords, - OdinServiceRecord, OdinSnapshotRecord, OdinVerseRecord, + OdinDocuments, OdinRecords, OdinServiceRecord, OdinSnapshotRecord, OdinVerseRecord, }; use anyhow::Result; use cultmesh_rs::{CultMesh, CultMeshNode, CultMeshNodeOptions}; @@ -39,14 +38,6 @@ impl CultMeshOdinRepository { self.node.get::(verse_id) } - pub fn get_gjallar_overview(&self, overview_id: &str) -> Result> { - self.node.get::(overview_id) - } - - pub fn get_gjallar_tile(&self, tile_id: &str) -> Result> { - self.node.get::(tile_id) - } - pub fn document_binding_version(&self, document_type: &str) -> Option { self.node .documents() diff --git a/docs/architecture.md b/docs/architecture.md index 851a829..eb568b9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -35,9 +35,9 @@ Verse / host / device / provider inputs -> CultMesh node -> CultCache .cc persistence -> CultNet/CultMesh document registry - -> Gjallar overview composition - -> Nightwing terminal lowering - -> Eve/CultUI projection and compact display feeds + -> Odin Eve/CultUI deck projection + -> Gjallar Nightwing composition and framebuffer lowering + -> compact display feeds ``` The first Rust core lives in `crates/odin-core`: @@ -48,8 +48,6 @@ The first Rust core lives in `crates/odin-core`: Odin records. - `repository.rs`: `OdinRepository` abstraction, in-memory mock repository, and CultMesh-backed repository. -- `gjallar.rs`: pure overview composition from Odin records to typed Gjallar - overview/tile records. The Rust spine owns the future architecture. The CommonJS daemon remains the legacy operational body until each organ crosses this typed boundary. @@ -59,10 +57,9 @@ legacy operational body until each organ crosses this typed boundary. Odin's executable body is split by ownership: - `crates/odin-core`: Rust target core. Owns typed Odin documents, ingest - ports, Gjallar overview records, normalization, composition, and - CultMesh/CultCache repository boundaries. This is the replacement spine; - JavaScript remains legacy runtime/probe scaffolding until each organ has - crossed the typed boundary. + ports, normalization, and CultMesh/CultCache repository boundaries. This is + the replacement spine; JavaScript remains legacy runtime/probe scaffolding + until each organ has crossed the typed boundary. - `src/odin-coordinator.cjs`: process lifecycle, refresh loop, persistence, health, and transport wiring. - `src/odin/config.cjs`: runtime paths, seed deck URLs, intervals, and CultLib module path setup. - `src/odin/documents.cjs`: CultCache/CultMesh document definitions accepted by Odin. @@ -76,16 +73,12 @@ Odin's executable body is split by ownership: The entrypoint is not allowed to grow new probe, surface, provider, layout, or renderer policy. If a new owner is needed, name the owner and its invariant before adding code. -Gjallar is the named overview composition daemon for what Nightwing displays. -In the Rust spine, Gjallar has typed `gjallar.overview.v1` and -`gjallar.overview_tile.v1` records. Its package lives in -`crates/gjallar-daemon` and `docs/gjallar.md`. It runs as its own Rust CultMesh -entrypoint rather than being folded into Odin's coordinator or Nightwing's TUI. -Gjallar may read Odin-owned state and emit a packed overview feed. During the -CommonJS-to-Rust migration it may also read Odin's existing -`gamecult.eve.surface_state.v1` compatibility record and wrap it as a Gjallar -tile. It must not own the underlying registry, probe, provider truth, terminal -glyph rendering, or translation decisions. +Gjallar is the Nightwing-resident terminal compositor for what Odin can show. +Its runtime lives in `src/Gjallar` and consumes Odin's Eve deck directly. +Gjallar owns provider enumeration for display, panel packing, marquee behavior, +glyph/color/framebuffer lowering, frame stats, and the multi-scale terminal +product. It must not own the underlying registry, probe, provider truth, or +translation decisions. Idunn is the named keepalive organ for daemon continuity. Its current Rust body lives in `crates/idunn-daemon` and `crates/odin-core/src/idunn.rs`. Idunn may read @@ -145,8 +138,6 @@ Current Rust verification: - `pipeline_collects_from_injected_ports`: proves ingest ports and clock injection. - `memory_repository_supports_fast_unit_tests`: proves repository consumers can test without CultMesh. -- `compose_overview_orders_dashboard_tiles_for_nightwing`: proves Gjallar can - turn Odin records into an ordered overview feed without daemon boot. - `cultmesh_repository_round_trips_typed_records`: proves typed Odin records persist through CultMesh/CultCache and reload from `.cc`. @@ -188,11 +179,12 @@ Odin currently publishes service squares for: - Raven: SSH reachability. - Yggdrasil: SSH/HTTP/HTTPS reachability plus nginx, StreamPixels, Heimdall, Repixelizer, and Bifrost systemd state. -Gjallar composes these into the compact overview feed. The Nightwing TUI lowers -that feed into dense cells and fills surplus screen space according to -Gjallar's tile ordering, spans, and density hints. If Nightwing starts deriving -dashboard composition directly from Odin service records, the composition owner -has leaked out of Gjallar. +Gjallar consumes Odin's deck and composes these surfaces into the Nightwing +display. Nightwing is the host/body; Gjallar is the terminal product running +there. If Odin starts deciding framebuffer composition, the renderer owner has +leaked upward. If individual providers start tuning themselves for Nightwing +instead of emitting clean Eve/CultUI surfaces, provider truth has leaked +downward. ## Current Interface Surface diff --git a/docs/gjallar.md b/docs/gjallar.md index 659403b..4217b51 100644 --- a/docs/gjallar.md +++ b/docs/gjallar.md @@ -1,92 +1,79 @@ # Gjallar -Gjallar is the overview composition daemon for Odin. +Gjallar is the Nightwing-resident terminal compositor for Odin's domain. Odin is the all-seer: it accepts Verse discovery, schema catalogs, translation -routes, provider surfaces, and observation projections. Gjallar reads that -Odin-owned state and composes the dense overview feed that Nightwing displays. -Nightwing should not run a bespoke dashboard brain; it should ask Gjallar what -to draw and then lower that feed into fast terminal cells. +routes, provider surfaces, and observation projections. Gjallar talks to Odin, +enumerates the active provider surfaces Odin can show, and composes those +surfaces into the live multi-scale dashboard running on Nightwing. -Gjallar exists so Odin does not need to care how a pile of dashboards fits on -one screen, and Nightwing does not need to know how Odin's world model is built. +Gjallar exists so Odin does not need to care how a pile of provider-owned TUIs +fits on one fast display, and provider daemons do not need to know the terminal +body they are being lowered into. ## Authority Map -- Owner: Gjallar owns overview composition for Odin sight. -- Inputs: Odin's accepted snapshot, Verse records, service records, interface - records, observation stream records, translation route records, and explicit - operator/Nightwing display constraints. -- Outputs: typed `gjallar.overview.v1` and `gjallar.overview_tile.v1` records: - overview metadata, tile ordering, density hints, source pointers, status, - labels, and compact detail text for Nightwing. -- Derived state: tile priority, grouping, target rows/columns, row/column spans, - visual emphasis hints, and compact summaries are derived from Odin state. +- Owner: Gjallar owns Nightwing dashboard composition, tiling, marquee, visual + density, framebuffer presentation, and character-level refresh behavior. +- Inputs: Odin's Eve/CultUI deck endpoint, provider ids, provider-owned surface + graphs, display constraints, font choices, and operator runtime flags. +- Outputs: the visible Nightwing framebuffer and compact Gjallar frame/status + telemetry. +- Derived state: panel packing, visual weight, tile position, gutter cells, + marquee tape, glyph size, and frame timing are derived from Odin/provider + surfaces plus display constraints. - Forbidden writers: Gjallar does not probe hosts, accept Verse truth, mutate - provider-owned dashboards, own terminal glyph rendering, or invent schema - translation routes. -- Shared paths: Nightwing TUI, browser previews, future compact overlays, and - agent summaries consume the same Gjallar overview feed when they want the - "everything Odin sees" view. -- Deletion line: any Nightwing path that independently composes Odin dashboards - should move into Gjallar; any Gjallar path that decides discovery truth should - move back into Odin. + provider-owned dashboards, invent schema translation routes, or replace Odin's + provider registry. +- Shared paths: Nightwing's physical display, local frame dumps, future compact + overlays, and agent-facing TUI captures should all lower the same Gjallar + composition behavior when they want the "everything Odin can show" view. +- Deletion line: the old Rust `gjallar.overview` feed is not a runtime + authority. Any path that wants Nightwing composition belongs in `src/Gjallar`; + any path that decides discovery truth belongs in Odin. ## Body -- `crates/gjallar-daemon` is Gjallar's Rust CultMesh daemon. -- `crates/odin-core/src/gjallar.rs` owns the pure composition function so unit - tests can exercise packing decisions without booting a daemon. -- `gjallar.overview.v1` describes the feed Nightwing asks for. -- `gjallar.overview_tile.v1` describes each drawable tile and names its Odin - source record. +- `src/Gjallar` is Gjallar's executable C# runtime. +- `Gjallar.csproj` builds the Nightwing framebuffer compositor. +- Gjallar consumes Odin's deck over WebSocket, defaulting to + `ws://192.168.1.66:8797/eve/deck` and provider `odin.allseer`. +- The old Rust `crates/gjallar-daemon` and `gjallar.overview` records were cut + because they created an intermediate composition owner that did nothing Odin + and Gjallar's live renderer could not explain directly. - `assets/personas/gjallar-avatar.png` and `assets/personas/gjallar-avatar-pixel-256.png` remain branding assets for the view/persona surface. -Run one composition pass from the repo root: +Build from the repo root: ```powershell -cargo run -p gjallar-daemon -- +dotnet build .\src\Gjallar\Gjallar.csproj ``` -By default, Gjallar reads Odin's local CultMesh store at -`scratch/odin/odin.ccmp` and writes its feed to -`scratch/gjallar/gjallar.overview.ccmp`. +Publish for Nightwing: + +```powershell +dotnet publish .\src\Gjallar\Gjallar.csproj -c Release -r linux-x64 --self-contained true -o .\scratch\publish\gjallar +``` ## Runtime Contract ```text -Odin typed state - -> Gjallar overview composition - -> gjallar.overview / gjallar.overview_tile CultMesh records - -> Nightwing terminal lowerer +provider-owned Eve/CultUI surfaces + -> Odin discovery and allseer deck + -> Gjallar provider enumeration, packing, marquee, and framebuffer lowering + -> Nightwing visible display ``` -Nightwing owns terminal speed, key handling, glyph selection, color lowering, -and screen refresh. Gjallar owns what should be on the overview and how densely -it should be packed. Odin owns the facts being summarized. - -## Current Cut - -The current Rust daemon has two input paths: - -- Preferred: read Rust typed Odin records such as `odin.snapshot.v1`, - `odin.service.v1`, and `odin.interface.v1` from an Odin CultMesh store. -- Compatibility: read Odin's current CommonJS - `gamecult.eve.surface_state.v1` record as a raw MessagePack map, then wrap it - as a typed Gjallar overview tile. - -The compatibility path exists so Gjallar can talk to today's Odin without -pretending the migration is complete. The next improvement is for Odin to -publish a typed index/catalog document that Gjallar can read instead of carrying -configured key lists. +Nightwing is the host/body. Gjallar is the product that runs there. Odin owns +the accepted discovery/provider view. Each daemon owns its own surface truth. ## Invariants -- Odin remains the accepted owner of all-seer state. -- Gjallar owns overview composition, not discovery truth. -- Nightwing owns terminal lowering, not dashboard composition. -- Every tile names the Odin source record behind it. -- Missing Odin records disappear from the feed rather than becoming invented - truth. +- Odin remains the accepted owner of all-seer discovery and provider indexing. +- Gjallar owns display composition, not discovery truth. +- Provider surfaces are lowered, not rewritten into status summaries. +- Missing or invalid provider surfaces disappear or render as unavailable; they + do not become invented truth. +- Frame/status telemetry observes Gjallar's rendering behavior only. diff --git a/scripts/write-gjallar-persona-cc.mjs b/scripts/write-gjallar-persona-cc.mjs index 91e964c..333a51b 100644 --- a/scripts/write-gjallar-persona-cc.mjs +++ b/scripts/write-gjallar-persona-cc.mjs @@ -205,12 +205,12 @@ function buildPersonaState() { }), ], incubation: [ - thought("csharp-cultmesh-body", "Promote Gjallar from doc/persona package into an executable C# CultMesh daemon after Odin's runtime state read path and affordance packet schema are clear.", { + thought("csharp-cultmesh-body", "Gjallar now has an executable C# Nightwing body that consumes Odin's Eve deck and renders the live multi-scale terminal dashboard.", { status: "active", - question: "Which CultMesh document should carry Gjallar's first affordance packet?", - actionImplication: "Build the C# daemon around CultMesh node startup and typed Persona state, not a JSON sidecar.", + question: "Which native CultMesh subscription should replace the current Odin WebSocket deck bridge when the protocol is ready?", + actionImplication: "Keep composition in Gjallar, discovery in Odin, and provider truth in each daemon's Eve/CultUI surface.", intensity: 0.76, - tags: ["csharp", "cultmesh", "runtime"], + tags: ["csharp", "nightwing", "runtime"], }), ], }, @@ -233,19 +233,19 @@ function buildPersonaState() { candidateActions: { actions: [ { - id: "build-csharp-gjallar-daemon", + id: "promote-gjallar-native-cultmesh", status: "draft", actionType: "propose", readiness: "waiting", riskLevel: "medium", - target: target("runtime", "gjallar-csharp-daemon", "Gjallar C# CultMesh daemon"), - summary: "Implement Gjallar as its own C# CultMesh runtime once the packet schema and Odin state read path are named.", - rationale: "The Persona state is now a typed `.cc` record; the daemon body should use the same substrate instead of JSON.", + target: target("runtime", "gjallar-native-cultmesh", "Gjallar native CultMesh input path"), + summary: "Promote Gjallar's Odin input from the current WebSocket deck bridge to a native CultMesh subscription when the deck contract is ready.", + rationale: "Gjallar's C# Nightwing body exists; the remaining migration debt is the input transport, not the ownership model.", urgency: 0.62, confidence: 0.74, constraints: [ "Do not fold Gjallar into Odin's CommonJS coordinator.", - "Do not let Gjallar own discovery, probing, rendering, or schema truth.", + "Do not let Gjallar own discovery, probing, provider truth, or schema truth.", "Use CultMesh/CultCache typed state as the runtime substrate.", ], createdAt: updatedAt, diff --git a/src/Gjallar/Gjallar.csproj b/src/Gjallar/Gjallar.csproj new file mode 100644 index 0000000..830da2d --- /dev/null +++ b/src/Gjallar/Gjallar.csproj @@ -0,0 +1,14 @@ + + + Exe + net10.0 + enable + enable + true + Gjallar + Gjallar + + + + + diff --git a/src/Gjallar/Program.cs b/src/Gjallar/Program.cs new file mode 100644 index 0000000..2cbfd99 --- /dev/null +++ b/src/Gjallar/Program.cs @@ -0,0 +1,1795 @@ +using System.Buffers; +using System.Diagnostics; +using System.Globalization; +using System.IO.Compression; +using System.Net.WebSockets; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using CultMath; + +var config = GjallarConfig.Parse(args); +using var renderer = new GjallarRenderer(config); +await renderer.RunAsync(); + +internal sealed record GjallarConfig( + string FramebufferPath, + string Url, + string ProviderId, + int RefreshHz, + string StatusPath, + string FrameDumpPath, + int Frames, + int Width, + int Height, + string FontPath) +{ + public static GjallarConfig Parse(IReadOnlyList args) => new( + StringArg(args, "--fb", "/dev/fb0"), + StringArg(args, "--url", "ws://192.168.1.66:8797/eve/deck"), + StringArg(args, "--provider", "odin.allseer"), + IntArg(args, "--refresh-hz", 2), + StringArg(args, "--stats-path", "/var/log/gjallar.status"), + StringArg(args, "--frame-dump-path", ""), + IntArg(args, "--frames", 0), + IntArg(args, "--width", 0), + IntArg(args, "--height", 0), + StringArg(args, "--font", "")); + + private static string StringArg(IReadOnlyList args, string name, string fallback) + { + for (var i = 0; i < args.Count - 1; i++) + { + if (string.Equals(args[i], name, StringComparison.OrdinalIgnoreCase)) + { + return args[i + 1]; + } + } + + return fallback; + } + + private static int IntArg(IReadOnlyList args, string name, int fallback) => + int.TryParse(StringArg(args, name, ""), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ? value : fallback; +} + +internal sealed class GjallarRenderer : IDisposable +{ + private static readonly JsonSerializerOptions StatusJson = new() { WriteIndented = true }; + private readonly GjallarConfig config; + private readonly FramebufferDevice framebuffer; + private readonly FontAtlas fonts; + private readonly CancellationTokenSource stopping = new(); + private readonly PeriodicTimer timer; + private readonly TimeSpan frameInterval; + private byte[]? latestStateJson; + private int frameIndex; + private long lastStatusTick; + private int lastStatusFrame; + private SceneCache? sceneCache; + private FrameTimings lastTimings; + + public GjallarRenderer(GjallarConfig config) + { + this.config = config; + framebuffer = FramebufferDevice.Open(config.FramebufferPath, config.Width, config.Height); + fonts = FontAtlas.Load(config.FontPath); + frameInterval = TimeSpan.FromSeconds(1.0 / Math.Max(1, config.RefreshHz)); + timer = new PeriodicTimer(frameInterval); + lastStatusTick = Stopwatch.GetTimestamp(); + } + + public async Task RunAsync() + { + var receiveTask = Task.Run(() => ConnectReceiveLoopAsync(stopping.Token)); + var rendered = 0; + while (config.Frames <= 0 || rendered < config.Frames) + { + var started = DateTimeOffset.UtcNow; + var frameStarted = Stopwatch.GetTimestamp(); + lastTimings = RenderOnce(); + rendered++; + var paintMs = ElapsedMilliseconds(frameStarted, Stopwatch.GetTimestamp()); + WriteStatusIfDue("rendered", rendered, paintMs, lastTimings, started); + if (!string.IsNullOrWhiteSpace(config.FrameDumpPath)) + { + framebuffer.WritePpm(config.FrameDumpPath); + } + + if (config.Frames > 0 && rendered >= config.Frames) + { + break; + } + + await timer.WaitForNextTickAsync(stopping.Token).ConfigureAwait(false); + } + + stopping.Cancel(); + try + { + await receiveTask.ConfigureAwait(false); + } + catch (OperationCanceledException) when (stopping.IsCancellationRequested) + { + } + } + + private static Uri ProviderUri(string url, string providerId) + { + if (string.IsNullOrWhiteSpace(providerId)) + { + return new Uri(url); + } + + var trimmed = url.TrimEnd('/'); + if (trimmed.EndsWith("/" + providerId, StringComparison.Ordinal)) + { + return new Uri(trimmed); + } + + return new Uri($"{trimmed}/{Uri.EscapeDataString(providerId)}"); + } + + private async Task ConnectReceiveLoopAsync(CancellationToken token) + { + var target = ProviderUri(config.Url, config.ProviderId); + while (!token.IsCancellationRequested) + { + try + { + using var socket = new ClientWebSocket(); + await socket.ConnectAsync(target, token).ConfigureAwait(false); + await ReceiveLoopAsync(socket, token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + return; + } + catch when (!token.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromSeconds(2), token).ConfigureAwait(false); + } + } + } + + private async Task ReceiveLoopAsync(ClientWebSocket socket, CancellationToken token) + { + var buffer = ArrayPool.Shared.Rent(1024 * 1024); + try + { + while (socket.State == WebSocketState.Open) + { + using var body = new MemoryStream(); + WebSocketReceiveResult result; + do + { + result = await socket.ReceiveAsync(buffer, token).ConfigureAwait(false); + if (result.MessageType == WebSocketMessageType.Close) + { + return; + } + + body.Write(buffer, 0, result.Count); + } + while (!result.EndOfMessage); + + if (result.MessageType != WebSocketMessageType.Text) + { + continue; + } + + Interlocked.Exchange(ref latestStateJson, body.ToArray()); + } + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + private FrameTimings RenderOnce() + { + var stateJson = Volatile.Read(ref latestStateJson); + var frame = new FrameDocument(framebuffer.Width, framebuffer.Height, fonts); + var copyMs = 0.0; + var decorMs = 0.0; + var gutterMs = 0.0; + var presentMs = 0.0; + if (stateJson is null) + { + frame.Clear(ToBgra(Voronoi.SampleTone(0, 0, framebuffer.Height, frameIndex, CultMathTone.Background, Math.Max(framebuffer.Width, framebuffer.Height)))); + var statusFont = fonts.HeaderFor(framebuffer.Height); + frame.DrawText(fonts.IndexOf(statusFont), 16, 16, "Waiting for Odin Eve surface...", ToBgra(Voronoi.SampleTone(16, 16, framebuffer.Height, frameIndex, CultMathTone.Body, statusFont.Width))); + } + else + { + var scene = SceneFor(stateJson); + var step = Stopwatch.GetTimestamp(); + frame.Clear(ColorBgra.Black); + foreach (var panel in scene.Panels) + { + frame.DrawPanel(panel, frameIndex); + } + + copyMs = ElapsedMilliseconds(step, Stopwatch.GetTimestamp()); + step = Stopwatch.GetTimestamp(); + frame.DrawPanelDecorations(scene.Panels, frameIndex); + decorMs = ElapsedMilliseconds(step, Stopwatch.GetTimestamp()); + step = Stopwatch.GetTimestamp(); + frame.DrawGutterMaze(scene.GutterCells, frameIndex, scene.MarqueeTape); + gutterMs = ElapsedMilliseconds(step, Stopwatch.GetTimestamp()); + } + + var presentStarted = Stopwatch.GetTimestamp(); + framebuffer.Present(frame.Pixels); + presentMs = ElapsedMilliseconds(presentStarted, Stopwatch.GetTimestamp()); + frameIndex++; + return new FrameTimings(copyMs, decorMs, gutterMs, presentMs); + } + + private void WriteStatusIfDue(string status, int frames, double paintMs, FrameTimings timings, DateTimeOffset started) + { + var now = Stopwatch.GetTimestamp(); + if (frames > 1 && ElapsedMilliseconds(lastStatusTick, now) < 1000) + { + return; + } + + var elapsedSeconds = Math.Max(0.001, (now - lastStatusTick) / (double)Stopwatch.Frequency); + var measuredFps = (frames - lastStatusFrame) / elapsedSeconds; + lastStatusTick = now; + lastStatusFrame = frames; + WriteStatus(status, frames, paintMs, measuredFps, timings, started); + } + + private static double ElapsedMilliseconds(long started, long ended) => + (ended - started) * 1000.0 / Stopwatch.Frequency; + + private void WriteStatus(string status, int frames, double paintMs, double measuredFps, FrameTimings timings, DateTimeOffset started) + { + if (string.IsNullOrWhiteSpace(config.StatusPath)) + { + return; + } + + Directory.CreateDirectory(Path.GetDirectoryName(config.StatusPath) ?? "."); + var document = new + { + schema = "gamecult.gjallar.frame.v1", + service = "gjallar", + mode = "native-csharp-odin-eve-framebuffer", + presentMode = "single-contiguous-framebuffer-write", + status, + frames, + framebuffer = new { framebuffer.Width, framebuffer.Height, bytes = framebuffer.BufferBytes }, + refreshHz = config.RefreshHz, + measuredFps = Math.Round(measuredFps, 2), + cultMathNative = Voronoi.NativeAvailable, + paintMs = Math.Round(paintMs, 2), + timings = new + { + copyMs = Math.Round(timings.CopyMs, 2), + decorMs = Math.Round(timings.DecorMs, 2), + gutterMs = Math.Round(timings.GutterMs, 2), + presentMs = Math.Round(timings.PresentMs, 2), + }, + updatedAtUtc = started.ToString("O", CultureInfo.InvariantCulture), + }; + File.WriteAllText(config.StatusPath, JsonSerializer.Serialize(document, StatusJson), Encoding.UTF8); + } + + private static ColorBgra ToBgra(Color32 color) => new(color.r, color.g, color.b); + + private SceneCache SceneFor(byte[] stateJson) + { + if (sceneCache is { } existing && ReferenceEquals(existing.StateJson, stateJson)) + { + return existing; + } + + using var state = JsonDocument.Parse(stateJson); + if (!EveNode.TryRoot(state.RootElement, out var root)) + { + sceneCache = new SceneCache(stateJson, [], [], ""); + return sceneCache; + } + + var providers = root.PanelChildren().Where(node => !node.IsScaffoldOnly()).ToArray(); + var gutter = GutterSize(fonts.Edge); + var outerY = gutter; + var packed = AabbPacker.Pack(providers, new RectI(0, outerY, framebuffer.Width, framebuffer.Height - outerY * 2), gutter).ToArray(); + sceneCache = new SceneCache(stateJson, packed, FrameDocument.BuildGutterCells(framebuffer.Width, framebuffer.Height, fonts.Edge, packed, gutter), root.MarqueeText); + return sceneCache; + } + + private static int GutterSize(PsfFont font) => + Math.Max(28, Math.Max(font.LineHeight, font.Width) + 8); + + public void Dispose() + { + stopping.Cancel(); + stopping.Dispose(); + timer.Dispose(); + framebuffer.Dispose(); + } +} + +internal sealed record SceneCache(byte[] StateJson, IReadOnlyList Panels, IReadOnlyList GutterCells, string MarqueeTape); +internal readonly record struct FrameTimings(double CopyMs, double DecorMs, double GutterMs, double PresentMs); + +internal sealed class FrameDocument +{ + private readonly FontAtlas fonts; + public byte[] Pixels { get; } + public int Width { get; } + public int Height { get; } + public int PanelCount { get; private set; } + public int[] X { get; } + public int[] Y { get; } + public int[] W { get; } + public int[] H { get; } + public float[] Weight { get; } + public int[] FontIndex { get; } + + public FrameDocument(int width, int height, FontAtlas fonts, int panelCapacity = 256) + { + Width = width; + Height = height; + this.fonts = fonts; + Pixels = GC.AllocateUninitializedArray(width * height * 4); + X = new int[panelCapacity]; + Y = new int[panelCapacity]; + W = new int[panelCapacity]; + H = new int[panelCapacity]; + Weight = new float[panelCapacity]; + FontIndex = new int[panelCapacity]; + } + + public void Clear(ColorBgra color) + { + for (var i = 0; i < Pixels.Length; i += 4) + { + Pixels[i] = color.B; + Pixels[i + 1] = color.G; + Pixels[i + 2] = color.R; + Pixels[i + 3] = 255; + } + } + + public void CopyFrom(byte[] pixels) => Buffer.BlockCopy(pixels, 0, Pixels, 0, Math.Min(pixels.Length, Pixels.Length)); + + public void DrawPanel(PackedPanel panel, int frameIndex, int depth = 0) + { + var rect = panel.Rect; + var headerFont = fonts.HeaderFor(rect.Height); + var textItems = panel.Node.TextItems().ToArray(); + var headerPad = headerFont.Height <= 5 ? 2 : 8; + var headerBand = Math.Min(rect.Height, headerFont.Height + headerPad); + var headerTextY = rect.Y + (headerFont.Height <= 5 ? 1 : 6); + var contentW = Math.Max(1, rect.Width - 20); + var rowStart = rect.Y + headerBand + (headerFont.Height <= 5 ? 1 : 6); + var maxY = rect.Y + rect.Height - 8; + var contentH = Math.Max(1, maxY - rowStart); + _ = fonts.ForTextBox(contentW, contentH, textItems, panel.Weight, out var fontIndex); + var tones = new ToneBatch(Height, frameIndex); + var fills = new List(); + var texts = new List(); + var index = PanelCount++; + if (index < X.Length) + { + X[index] = rect.X; + Y[index] = rect.Y; + W[index] = rect.Width; + H[index] = rect.Height; + Weight[index] = panel.Weight; + FontIndex[index] = fontIndex; + } + + fills.Add(new FillCommand(rect, -1)); + fills.Add(new FillCommand( + new RectI(rect.X + 2, rect.Y + 2, Math.Max(1, rect.Width - 4), Math.Max(1, headerBand - 2)), + tones.Add(rect.X + 8, rect.Y + 8, CultMathTone.Background, headerFont.Height))); + AddBorderCommands(rect, tones, fills); + + var title = panel.Node.Title; + texts.Add(new TextCommand(headerFont, rect.X + 8, headerTextY, title, Math.Max(1, rect.Width - 16), tones.Add(rect.X + 8, headerTextY, CultMathTone.Header, headerFont.Width))); + + var contentX = rect.X + 10; + var colors = tones.Resolve(); + foreach (var fill in fills) + { + FillRect(fill.Rect, fill.ColorIndex < 0 ? ColorBgra.Black : colors[fill.ColorIndex]); + } + + foreach (var text in texts) + { + DrawText(text.Font, text.X, text.Y, text.Text, colors[text.ColorIndex], text.MaxWidth); + } + + if (depth >= 4 || !panel.Node.ShouldRenderNestedPanels() || rect.Width < 96 || contentH < 42) + { + DrawPanelText(panel, frameIndex, textItems, rowStart, maxY, contentW, contentX); + return; + } + + var children = panel.Node.RenderableChildren().ToArray(); + if (children.Length == 0) + { + DrawPanelText(panel, frameIndex, textItems, rowStart, maxY, contentW, contentX); + return; + } + + var childGap = Math.Max(4, Math.Max(fonts.Edge.LineHeight, fonts.Edge.Width) / 2); + var childRect = new RectI(contentX - 2, rowStart, Math.Max(1, rect.Width - 16), Math.Max(1, maxY - rowStart)); + var packedChildren = AabbPacker.Pack(children, childRect, childGap).ToArray(); + if (packedChildren.Length == 0) + { + DrawPanelText(panel, frameIndex, textItems, rowStart, maxY, contentW, contentX); + return; + } + + foreach (var child in packedChildren) + { + DrawPanel(child, frameIndex, depth + 1); + } + } + + private void DrawPanelText(PackedPanel panel, int frameIndex, IReadOnlyList textItems, int rowStart, int maxY, int contentW, int contentX) + { + var rect = panel.Rect; + var contentH = Math.Max(1, maxY - rowStart); + var font = fonts.ForTextBox(contentW, contentH, textItems, panel.Weight, out _); + var tones = new ToneBatch(Height, frameIndex); + var texts = new List(); + var row = rowStart; + var lineHeight = font.LineHeight; + foreach (var item in textItems) + { + if (row + font.Height > maxY) + { + texts.Add(new TextCommand(font, contentX, maxY - font.Height, "... more", contentW, tones.Add(contentX, maxY - font.Height, CultMathTone.Header, font.Width))); + break; + } + + foreach (var line in Wrap(item.RenderText, font, contentW, Math.Max(1, (maxY - row) / lineHeight))) + { + var tone = item.Prefix is "*" or "+" ? CultMathTone.Header : CultMathTone.Body; + texts.Add(new TextCommand(font, contentX, row, line, contentW, tones.Add(contentX, row, tone, font.Width))); + row += lineHeight; + if (row + font.Height > maxY) + { + break; + } + } + + row += font.BlockSpacing; + } + + var colors = tones.Resolve(); + foreach (var text in texts) + { + DrawText(text.Font, text.X, text.Y, text.Text, colors[text.ColorIndex], text.MaxWidth); + } + } + + public void DrawPanelDecorations(IReadOnlyList panels, int frameIndex) + { + var tones = new ToneBatch(Height, frameIndex); + var fills = new List(); + foreach (var panel in panels) + { + AddBorderCommands(panel.Rect, tones, fills); + } + + var colors = tones.Resolve(); + foreach (var fill in fills) + { + FillRect(fill.Rect, colors[fill.ColorIndex]); + } + } + + public void DrawGutterMaze(IReadOnlyList cells, int frameIndex, string marqueeTape) + { + var font = fonts.Edge; + var tones = new ToneBatch(Height, frameIndex); + var glyphs = BuildMazePoetry(font, cells, frameIndex, tones, marqueeTape); + var colors = tones.Resolve(); + foreach (var glyph in glyphs) + { + DrawGlyph(font, glyph.X, glyph.Y, glyph.Character, colors[glyph.ColorIndex]); + } + } + + public void DrawText(int fontIndex, int x, int y, string text, ColorBgra color) => DrawText(fonts[fontIndex], x, y, text, color, Width - x); + + private void DrawText(PsfFont font, int x, int y, string text, ColorBgra color, int maxWidth) + { + var cursor = x; + var limit = x + Math.Max(0, maxWidth); + foreach (var ch in text.Replace('\r', ' ').Replace('\n', ' ')) + { + if (cursor + font.Width > limit) + { + break; + } + + DrawGlyph(font, cursor, y, ch, color); + cursor += font.Width; + } + } + + private void DrawGlyph(PsfFont font, int x, int y, char ch, ColorBgra color) + { + var glyph = font.Glyph(ch); + for (var gy = 0; gy < font.Height; gy++) + { + var start = gy * font.BytesPerRow; + for (var gx = 0; gx < font.Width; gx++) + { + var b = glyph[start + gx / 8]; + var mask = 0x80 >> (gx % 8); + if ((b & mask) != 0) + { + SetPixel(x + gx, y + gy, color); + } + } + } + } + + public static IReadOnlyList BuildGutterCells(int width, int height, PsfFont font, IReadOnlyList panels, int edgeGutterHeight) + { + var columns = Math.Max(1, (width + Math.Max(1, font.Width) - 1) / Math.Max(1, font.Width)); + var spans = MergeVerticalSpans(panels.Select(panel => (Start: panel.Rect.Y, End: panel.Rect.Y + panel.Rect.Height))); + var cells = new List(); + var edge = Math.Clamp(edgeGutterHeight, font.Height, Math.Max(font.Height, height / 3)); + var lane = 0; + AddHorizontalGutterLane(cells, columns, font, width, lane++, 0, edge); + + var cursorY = edge; + var bottomStart = Math.Max(edge, height - edge); + foreach (var span in spans) + { + var start = Math.Clamp(span.Start, edge, bottomStart); + var end = Math.Clamp(span.End, edge, bottomStart); + AddHorizontalGutterLane(cells, columns, font, width, lane++, cursorY, Math.Max(0, start - cursorY)); + cursorY = Math.Max(cursorY, end); + } + + AddHorizontalGutterLane(cells, columns, font, width, lane++, cursorY, Math.Max(0, bottomStart - cursorY)); + AddHorizontalGutterLane(cells, columns, font, width, lane, bottomStart, Math.Max(0, height - bottomStart)); + return cells; + } + + private static IReadOnlyList<(int Start, int End)> MergeVerticalSpans(IEnumerable<(int Start, int End)> spans) + { + var sorted = spans + .Select(span => (Start: Math.Max(0, span.Start), End: Math.Max(0, span.End))) + .Where(span => span.End > span.Start) + .OrderBy(span => span.Start) + .ToArray(); + var merged = new List<(int Start, int End)>(); + foreach (var span in sorted) + { + if (merged.Count == 0 || span.Start > merged[^1].End) + { + merged.Add(span); + continue; + } + + var last = merged[^1]; + merged[^1] = (last.Start, Math.Max(last.End, span.End)); + } + + return merged; + } + + private static void AddHorizontalGutterLane(List cells, int columns, PsfFont font, int width, int lane, int y, int height) + { + if (height < font.Height) + { + return; + } + + var textY = y + Math.Max(0, (height - font.Height) / 2); + var forward = lane % 2 == 0; + for (var laneColumn = 0; laneColumn < columns; laneColumn++) + { + var x = laneColumn * font.Width; + if (x >= width) + { + continue; + } + + cells.Add(new GutterCell(x, textY, lane, laneColumn, forward)); + } + } + + private IReadOnlyList BuildMazePoetry(PsfFont font, IReadOnlyList cells, int frameIndex, ToneBatch tones, string marqueeTape) + { + const int framesPerScrollCell = 8; + var tape = MarketPoetryTape(marqueeTape); + var scroll = (frameIndex / framesPerScrollCell) % Math.Max(1, tape.Length); + var glyphs = new List(); + foreach (var cell in cells) + { + var tapeIndex = cell.Forward + ? cell.LaneColumn + scroll + cell.Row * 7 + : cell.LaneColumn - scroll + cell.Row * 7; + var character = tape[((tapeIndex % tape.Length) + tape.Length) % tape.Length]; + if (character == ' ') + { + continue; + } + + glyphs.Add(new GlyphCommand(cell.X, cell.Y, character, tones.Add(cell.X, cell.Y, CultMathTone.Edge, font.Width))); + } + + return glyphs; + } + + private static string MarketPoetryTape(string marqueeTape) + { + var market = string.IsNullOrWhiteSpace(marqueeTape) ? "" : marqueeTape.Trim(); + return string.IsNullOrWhiteSpace(market) + ? " wake the colossus / coherence over velocity / cultmesh carries signal / cultcache remembers / love is disciplined openness / no cache pretends to truth / " + : $" {market} / wake the colossus / "; + } + + private static void AddBorderCommands(RectI rect, ToneBatch tones, List fills) + { + const int chunk = 40; + for (var x = rect.X; x < rect.X + rect.Width; x += chunk) + { + var span = Math.Min(chunk, rect.X + rect.Width - x); + fills.Add(new FillCommand(new RectI(x, rect.Y, span, 2), tones.Add(x, rect.Y, CultMathTone.Edge, chunk))); + fills.Add(new FillCommand(new RectI(x, rect.Y + rect.Height - 2, span, 2), tones.Add(x, rect.Y + rect.Height - 2, CultMathTone.Edge, chunk))); + } + + for (var y = rect.Y; y < rect.Y + rect.Height; y += chunk) + { + var span = Math.Min(chunk, rect.Y + rect.Height - y); + fills.Add(new FillCommand(new RectI(rect.X, y, 2, span), tones.Add(rect.X, y, CultMathTone.Edge, chunk))); + fills.Add(new FillCommand(new RectI(rect.X + rect.Width - 2, y, 2, span), tones.Add(rect.X + rect.Width - 2, y, CultMathTone.Edge, chunk))); + } + } + + private void FillRect(RectI rect, ColorBgra color) + { + var x0 = Math.Clamp(rect.X, 0, Width); + var y0 = Math.Clamp(rect.Y, 0, Height); + var x1 = Math.Clamp(rect.X + rect.Width, 0, Width); + var y1 = Math.Clamp(rect.Y + rect.Height, 0, Height); + for (var y = y0; y < y1; y++) + { + var offset = (y * Width + x0) * 4; + for (var x = x0; x < x1; x++) + { + Pixels[offset++] = color.B; + Pixels[offset++] = color.G; + Pixels[offset++] = color.R; + Pixels[offset++] = 255; + } + } + } + + private void SetPixel(int x, int y, ColorBgra color) + { + if ((uint)x >= (uint)Width || (uint)y >= (uint)Height) + { + return; + } + + var offset = (y * Width + x) * 4; + Pixels[offset] = color.B; + Pixels[offset + 1] = color.G; + Pixels[offset + 2] = color.R; + Pixels[offset + 3] = 255; + } + + private static IEnumerable Wrap(string text, PsfFont font, int width, int maxLines) + { + var columns = Math.Max(1, width / Math.Max(1, font.Width)); + var current = ""; + var emitted = 0; + foreach (var word0 in text.Replace("\r", "").Replace("\n", " / ").Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + var word = word0; + var candidate = current.Length == 0 ? word : current + " " + word; + if (candidate.Length <= columns) + { + current = candidate; + continue; + } + + if (current.Length > 0) + { + yield return current; + emitted++; + if (emitted >= maxLines) + { + yield break; + } + } + + while (word.Length > columns) + { + yield return word[..columns]; + emitted++; + if (emitted >= maxLines) + { + yield break; + } + + word = word[columns..]; + } + + current = word; + } + + if (current.Length > 0 && emitted < maxLines) + { + yield return current; + } + } +} + +internal static class AabbPacker +{ + public static IReadOnlyList Pack(IReadOnlyList nodes, RectI rect, int gap) + { + var weighted = nodes + .Select(node => new PackedPanel(node, rect, Weight(node))) + .OrderByDescending(item => item.Weight) + .ToArray(); + var result = new List(); + var cursor = ReserveVerticalCollections(weighted, rect, gap, result, out var remaining); + Squarify(remaining, cursor, gap, result); + return result; + } + + private static RectI ReserveVerticalCollections(IReadOnlyList items, RectI rect, int gap, List output, out IReadOnlyList remaining) + { + var vertical = items.Where(static item => item.Node.PrefersVerticalPanel()).ToList(); + if (vertical.Count == 0 || items.Count < 2 || rect.Width < 240 || rect.Height < 96) + { + remaining = items; + return rect; + } + + var keep = items.Except(vertical).ToList(); + var cursor = rect; + var maxReserved = Math.Max(96, (int)MathF.Round(rect.Width * 0.45f)); + var reserved = 0; + foreach (var panel in vertical.OrderByDescending(static item => item.Weight)) + { + if (cursor.Width < 160 || reserved >= maxReserved) + { + keep.Add(panel); + continue; + } + + var desired = PreferredVerticalWidth(panel, rect); + var width = Math.Min(desired, Math.Min(cursor.Width - 96, maxReserved - reserved)); + if (width < 72) + { + keep.Add(panel); + continue; + } + + var x = cursor.X + cursor.Width - width; + output.Add(panel with { Rect = Inset(new RectI(x, cursor.Y, width, cursor.Height), gap) }); + cursor = new RectI(cursor.X, cursor.Y, Math.Max(0, cursor.Width - width), cursor.Height); + reserved += width; + } + + remaining = keep.OrderByDescending(static item => item.Weight).ToArray(); + return cursor; + } + + private static int PreferredVerticalWidth(PackedPanel panel, RectI rect) + { + var totalWeight = Math.Max(0.001f, panel.Weight); + var areaWidth = (int)MathF.Round(MathF.Sqrt(totalWeight) * 56.0f); + var childPressure = Math.Min(90, panel.Node.RenderableChildCount() * 6); + return Math.Clamp(Math.Max(areaWidth, 104 + childPressure), 112, Math.Max(112, rect.Width / 3)); + } + + private static void Squarify(IReadOnlyList items, RectI rect, int gap, List output) + { + if (items.Count == 0 || rect.Width <= 4 || rect.Height <= 4) + { + return; + } + + if (items.Count == 1) + { + output.Add(items[0] with { Rect = rect }); + return; + } + + var totalWeight = Math.Max(0.001f, items.Sum(item => item.Weight)); + var totalArea = Math.Max(1.0f, rect.Width * rect.Height); + var remaining = items + .Select(item => new TreemapItem(item, Math.Max(1.0f, item.Weight / totalWeight * totalArea))) + .ToList(); + var row = new List(); + var cursor = rect; + var sideIndex = 0; + while (remaining.Count > 0) + { + var next = remaining[0]; + var side = StripLength(cursor, sideIndex); + if (row.Count == 0 || + ShouldGrowMosaicBand(row, cursor, sideIndex) || + Worst(row.Append(next), side) <= Worst(row, side)) + { + row.Add(next); + remaining.RemoveAt(0); + continue; + } + + cursor = LayoutSpiralStrip(row, cursor, gap, sideIndex, output); + sideIndex++; + row.Clear(); + if (cursor.Width <= 4 || cursor.Height <= 4) + { + break; + } + } + + if (row.Count > 0 && cursor.Width > 4 && cursor.Height > 4) + { + _ = LayoutSpiralStrip(row, cursor, gap, sideIndex, output); + } + } + + private static bool ShouldGrowMosaicBand(IReadOnlyList row, RectI rect, int sideIndex) + { + if (row.Count == 0) + { + return false; + } + + var sum = row.Sum(item => item.Area); + var side = StripLength(rect, sideIndex); + var thickness = sum / Math.Max(1, side); + var target = sideIndex % 2 == 0 ? 56.0f : 72.0f; + return thickness < target; + } + + private static float Worst(IEnumerable row, float side) + { + var areas = row.Select(item => item.Area).ToArray(); + if (areas.Length == 0) + { + return float.MaxValue; + } + + var sum = areas.Sum(); + var max = areas.Max(); + var min = Math.Max(0.001f, areas.Min()); + var side2 = side * side; + return Math.Max(side2 * max / (sum * sum), (sum * sum) / (side2 * min)); + } + + private static float StripLength(RectI rect, int sideIndex) => sideIndex % 2 == 0 + ? Math.Max(1, rect.Width) + : Math.Max(1, rect.Height); + + private static RectI LayoutSpiralStrip(IReadOnlyList row, RectI rect, int gap, int sideIndex, List output) + { + var sum = row.Sum(item => item.Area); + switch (sideIndex % 4) + { + case 0: + return LayoutHorizontalStrip(row, rect, gap, output, sum, fromTop: true); + case 1: + return LayoutVerticalStrip(row, rect, gap, output, sum, fromLeft: false); + case 2: + return LayoutHorizontalStrip(row, rect, gap, output, sum, fromTop: false); + default: + return LayoutVerticalStrip(row, rect, gap, output, sum, fromLeft: true); + } + } + + private static RectI LayoutHorizontalStrip(IReadOnlyList row, RectI rect, int gap, List output, float sum, bool fromTop) + { + var rowHeight = ClampPreferred((int)MathF.Round(sum / Math.Max(1, rect.Width)), 24, rect.Height); + var x = rect.X; + var y = fromTop ? rect.Y : rect.Y + rect.Height - rowHeight; + for (var i = 0; i < row.Count; i++) + { + var width = i == row.Count - 1 + ? rect.X + rect.Width - x + : Math.Max(24, (int)MathF.Round(row[i].Area / Math.Max(1, rowHeight))); + output.Add(row[i].Panel with { Rect = Inset(new RectI(x, y, width, rowHeight), gap) }); + x += width; + } + + return fromTop + ? new RectI(rect.X, rect.Y + rowHeight, rect.Width, Math.Max(0, rect.Height - rowHeight)) + : new RectI(rect.X, rect.Y, rect.Width, Math.Max(0, rect.Height - rowHeight)); + } + + private static RectI LayoutVerticalStrip(IReadOnlyList row, RectI rect, int gap, List output, float sum, bool fromLeft) + { + var rowWidth = ClampPreferred((int)MathF.Round(sum / Math.Max(1, rect.Height)), 32, rect.Width); + var y = rect.Y; + var x = fromLeft ? rect.X : rect.X + rect.Width - rowWidth; + for (var i = 0; i < row.Count; i++) + { + var height = i == row.Count - 1 + ? rect.Y + rect.Height - y + : Math.Max(18, (int)MathF.Round(row[i].Area / Math.Max(1, rowWidth))); + output.Add(row[i].Panel with { Rect = Inset(new RectI(x, y, rowWidth, height), gap) }); + y += height; + } + + return fromLeft + ? new RectI(rect.X + rowWidth, rect.Y, Math.Max(0, rect.Width - rowWidth), rect.Height) + : new RectI(rect.X, rect.Y, Math.Max(0, rect.Width - rowWidth), rect.Height); + } + + private static int ClampPreferred(int value, int preferredMin, int max) + { + if (max <= 0) + { + return 0; + } + + return max < preferredMin ? max : Math.Clamp(value, preferredMin, max); + } + + private static RectI Inset(RectI rect, int gap) + { + var inset = Math.Max(1, gap / 2); + return new RectI(rect.X, rect.Y + inset, Math.Max(1, rect.Width), Math.Max(1, rect.Height - inset * 2)); + } + + private static float Weight(EveNode node) + { + var items = node.TextItems().Take(160).ToArray(); + var requestedRows = 1.0f; + var requestedCells = 0.0f; + foreach (var item in items) + { + var length = Math.Clamp(item.Prefix.Length + 1 + item.Text.Length, 8, 96); + var rows = MathF.Ceiling(length / 72.0f); + requestedRows += rows; + requestedCells += rows * Math.Min(72, length); + } + + if (items.Length == 160) + { + requestedRows += 8.0f; + requestedCells += 8.0f * 72.0f; + } + + var structuralWeight = node.Kind == "interface" ? 0.75f : 0.35f; + structuralWeight += MathF.Min(1.5f, node.Children.Count * 0.05f); + var cellWeight = MathF.Log2(Math.Max(2.0f, requestedCells)) * 0.62f; + var rowWeight = MathF.Sqrt(requestedRows) * 0.24f; + return Math.Clamp(structuralWeight + cellWeight + rowWeight, 0.45f, 9.0f); + } + + private sealed record TreemapItem(PackedPanel Panel, float Area); +} + +internal sealed record PackedPanel(EveNode Node, RectI Rect, float Weight); +internal readonly record struct RectI(int X, int Y, int Width, int Height) +{ + public float CenterX => X + Width * 0.5f; + public float CenterY => Y + Height * 0.5f; + public bool Contains(int x, int y) => x >= X && x < X + Width && y >= Y && y < Y + Height; + public bool Intersects(RectI other) => + X < other.X + other.Width && + X + Width > other.X && + Y < other.Y + other.Height && + Y + Height > other.Y; +} + +internal sealed class EveNode +{ + public string Kind { get; init; } = ""; + public string Title { get; init; } = ""; + public string ProviderId { get; init; } = ""; + public string Role { get; init; } = ""; + public string Text { get; init; } = ""; + public string MarqueeText { get; init; } = ""; + public IReadOnlyList Children { get; init; } = []; + + public static bool TryRoot(JsonElement element, out EveNode root) + { + root = new EveNode { Title = "root" }; + if (!element.TryGetProperty("surface", out var surface) || !surface.TryGetProperty("root", out var rootElement)) + { + return false; + } + + root = FromJson(rootElement); + return true; + } + + public IEnumerable PanelChildren() + { + var nodes = Children.Count > 0 ? Children : [this]; + foreach (var node in nodes) + { + yield return node.AsPanelNode(); + } + } + + private EveNode AsPanelNode() + { + if (Kind != "interface" || Children.Count != 1) + { + return this; + } + + var child = Children[0]; + return new EveNode + { + Title = Title, + Kind = child.Kind, + ProviderId = string.IsNullOrWhiteSpace(child.ProviderId) ? ProviderId : child.ProviderId, + Role = child.Role, + Text = child.Text, + MarqueeText = child.MarqueeText, + Children = child.Children, + }; + } + + public bool IsScaffoldOnly() + { + if (Kind == "verse" && Children.Count == 1 && Children[0].Kind == "service") + { + return true; + } + + if (Children.Count == 1 && Children[0].Children.Count == 0 && IsServiceReference(Children[0].Text)) + { + return true; + } + + if (Children.Count != 0) + { + return false; + } + + var text = Text.Trim(); + if (IsServiceReference(text)) + { + return true; + } + + if (!text.StartsWith("surface ", StringComparison.OrdinalIgnoreCase) || !text.EndsWith(" nodes", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + var countText = text["surface ".Length..^" nodes".Length].Trim(); + return int.TryParse(countText, NumberStyles.Integer, CultureInfo.InvariantCulture, out _); + } + + private static bool IsServiceReference(string text) + { + var trimmed = text.Trim(); + return trimmed.StartsWith("service-", StringComparison.OrdinalIgnoreCase) && !trimmed.Contains('\n'); + } + + public IEnumerable TextItems() + { + foreach (var child in Children.Count == 0 ? [this] : Children) + { + if (child.ShouldShowTitleInline(Title)) + { + yield return new TextItem("*", child.Title); + } + + foreach (var item in child.CollectTextItems(256)) + { + yield return item; + } + } + } + + public IEnumerable RenderableChildren() + { + foreach (var child in Children) + { + var panel = child.AsPanelNode(); + if (!panel.IsScaffoldOnly() && panel.HasPresentationSignal()) + { + yield return panel; + } + } + } + + public bool ShouldRenderNestedPanels() + { + if (Children.Count < 2) + { + return false; + } + + var meaningful = Children + .Select(static child => child.AsPanelNode()) + .Where(static child => !child.IsScaffoldOnly() && child.HasPresentationSignal()) + .ToArray(); + if (meaningful.Length < 2) + { + return false; + } + + if (meaningful.All(static child => child.IsTextLeaf())) + { + return false; + } + + if (meaningful.All(static child => child.IsCompactPresentationLeaf())) + { + return false; + } + + return meaningful.Any(static child => child.RenderableChildren().Any() || (!child.IsCompactPresentationLeaf() && IsStructuralKind(child.Kind))); + } + + public bool PrefersVerticalPanel() + { + if (!IsOrderedCollectionKind(Kind)) + { + return false; + } + + var renderableCount = RenderableChildCount(); + if (renderableCount >= 5) + { + return true; + } + + var textItems = TextItems().Take(16).ToArray(); + return textItems.Length >= 5 && textItems.Average(static item => item.Text.Length) <= 32.0; + } + + public int RenderableChildCount() => RenderableChildren().Count(); + + private bool IsTextLeaf() => + Children.Count == 0 && (Kind == "text" || Kind == "metric" || Kind == "avatar"); + + private bool ShouldShowTitleInline(string parentTitle) + { + if (Title == parentTitle || IsTextLeaf()) + { + return false; + } + + return ShouldShowInlineTitle(Title); + } + + private bool IsCompactPresentationLeaf() => + !RenderableChildren().Any() && !TextItems().Any(); + + private bool HasPresentationSignal() + { + if (!IsPresentationNoiseTitle(Title)) + { + return true; + } + + if (!string.IsNullOrWhiteSpace(Text) && !IsPresentationNoiseText(Text)) + { + return true; + } + + return Children.Any(static child => child.AsPanelNode().HasPresentationSignal()); + } + + private static bool IsStructuralKind(string kind) + { + var value = kind.Trim().ToLowerInvariant(); + return value is "dashboard" or "surface" or "stack" or "grid" or "dock" or "row" or "column" or "pane" or "panel" or "card" or "group" or "list" or "tree" or "cockpit" or "rail" or "interface"; + } + + private static bool IsOrderedCollectionKind(string kind) + { + var value = kind.Trim().ToLowerInvariant(); + return value is "list" or "rail" or "menu"; + } + + private static bool IsContentKind(string kind) + { + var value = kind.Trim().ToLowerInvariant(); + return value is "text" or "metric" or "avatar"; + } + + private IEnumerable CollectTextItems(int limit) + { + if (limit <= 0) + { + yield break; + } + + if (!string.IsNullOrWhiteSpace(Text) && !IsPresentationNoiseText(Text)) + { + yield return new TextItem(TextPrefixForLeaf(), Text); + limit--; + } + + foreach (var child in Children) + { + if (child.ShouldShowTitleInline(Title)) + { + yield return new TextItem("+", child.Title); + limit--; + } + + foreach (var item in child.CollectTextItems(limit)) + { + yield return item; + } + } + } + + private static EveNode FromJson(JsonElement element) + { + var props = element.TryGetProperty("props", out var propsElement) && propsElement.ValueKind == JsonValueKind.Object ? propsElement : default; + var title = StringProp(props, "title"); + var provider = StringProp(props, "providerId"); + var kind = StringProp(element, "kind"); + var role = StringProp(props, "role"); + if (string.IsNullOrWhiteSpace(role)) + { + role = StringProp(element, "role"); + } + + var text = StringProp(props, "text"); + var marqueeText = StringProp(props, "marqueeText"); + if (string.IsNullOrWhiteSpace(text)) + { + text = StringProp(element, "text"); + } + + if (string.IsNullOrWhiteSpace(title) && !IsContentKind(kind) && !string.IsNullOrWhiteSpace(text)) + { + title = text; + text = ""; + } + + var children = new List(); + if (element.TryGetProperty("children", out var childElements) && childElements.ValueKind == JsonValueKind.Array) + { + foreach (var child in childElements.EnumerateArray()) + { + children.Add(FromJson(child)); + } + } + + return new EveNode + { + Kind = kind, + Role = role, + Title = string.IsNullOrWhiteSpace(title) ? (IsContentKind(kind) ? "" : StringProp(element, "id")) : title, + ProviderId = provider, + Text = text, + MarqueeText = marqueeText, + Children = children, + }; + } + + private static string StringProp(JsonElement element, string name) => + element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) ? ValueString(value) : ""; + + private static bool ShouldShowInlineTitle(string title) => + !string.IsNullOrWhiteSpace(title) && !IsPresentationNoiseTitle(title); + + private static bool IsPresentationNoiseTitle(string title) + { + var value = title.Trim(); + if (value.Length == 0) + { + return true; + } + + if (value.StartsWith("fact-", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + return IsServiceReference(value); + } + + private static bool IsPresentationNoiseText(string text) + { + var value = text.Trim(); + if (value.Length == 0) + { + return true; + } + + if (IsServiceReference(value)) + { + return true; + } + + if (value.StartsWith("kind:", StringComparison.OrdinalIgnoreCase) || + value.StartsWith("health:", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + + if (value.StartsWith("surface ", StringComparison.OrdinalIgnoreCase) && + value.EndsWith(" nodes", StringComparison.OrdinalIgnoreCase) && + int.TryParse(value["surface ".Length..^" nodes".Length].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out _)) + { + return true; + } + + return false; + } + + private static string ValueString(JsonElement value) => value.ValueKind switch + { + JsonValueKind.String => value.GetString() ?? "", + JsonValueKind.Number => value.ToString(), + JsonValueKind.True => "true", + JsonValueKind.False => "false", + _ => "", + }; + + private string TextPrefixForLeaf() + { + if (string.Equals(Role, "mono", StringComparison.OrdinalIgnoreCase) && IsJustifiedRowText(Text)) + { + return ""; + } + + return "-"; + } + + private static bool IsJustifiedRowText(string text) + { + var value = text.TrimStart(); + if (value.Length < 4) + { + return false; + } + + var index = 0; + while (index < value.Length && char.IsDigit(value[index])) + { + index++; + } + + return index > 0 && index + 1 < value.Length && value[index] == '.' && char.IsWhiteSpace(value[index + 1]); + } +} + +internal sealed record TextItem(string Prefix, string Text) +{ + public string RenderText => string.IsNullOrWhiteSpace(Prefix) ? Text : $"{Prefix} {Text}"; +} +internal sealed record FillCommand(RectI Rect, int ColorIndex); +internal sealed record TextCommand(PsfFont Font, int X, int Y, string Text, int MaxWidth, int ColorIndex); +internal sealed record GlyphCommand(int X, int Y, char Character, int ColorIndex); +internal sealed record GutterCell(int X, int Y, int Row, int LaneColumn, bool Forward); + +internal sealed class ToneBatch(int resolutionY, int frameIndex) +{ + private readonly List xs = []; + private readonly List ys = []; + private readonly List tones = []; + private readonly List spans = []; + + public int Add(float x, float y, CultMathTone tone, float span) + { + var index = xs.Count; + xs.Add(x); + ys.Add(y); + tones.Add(tone); + spans.Add(span); + return index; + } + + public ColorBgra[] Resolve() + { + var nativeColors = new Color32[xs.Count]; + Voronoi.SampleTones( + CollectionsMarshal.AsSpan(xs), + CollectionsMarshal.AsSpan(ys), + CollectionsMarshal.AsSpan(tones), + CollectionsMarshal.AsSpan(spans), + resolutionY, + frameIndex, + nativeColors); + return nativeColors.Select(color => new ColorBgra(color.r, color.g, color.b)).ToArray(); + } +} + +internal readonly record struct ColorBgra(byte R, byte G, byte B) +{ + public static readonly ColorBgra Black = new(0, 0, 0); +} + +internal sealed class FramebufferDevice : IDisposable +{ + private const int OReadWrite = 2; + private const int ProtRead = 1; + private const int ProtWrite = 2; + private const int MapShared = 1; + private readonly FileStream? stream; + private readonly int fd = -1; + private readonly IntPtr mapped; + public int Width { get; } + public int Height { get; } + public int BufferBytes => Width * Height * 4; + + private FramebufferDevice(string path, int width, int height) + { + Width = width; + Height = height; + if (OperatingSystem.IsLinux()) + { + fd = open(path, OReadWrite); + if (fd >= 0) + { + mapped = mmap(IntPtr.Zero, (UIntPtr)BufferBytes, ProtRead | ProtWrite, MapShared, fd, IntPtr.Zero); + if (mapped != new IntPtr(-1)) + { + return; + } + + close(fd); + fd = -1; + } + } + + stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, BufferBytes); + } + + public static FramebufferDevice Open(string path, int width, int height) + { + if (width <= 0 || height <= 0) + { + (width, height) = ReadVirtualSize(path); + } + + return new FramebufferDevice(path, width, height); + } + + public void Present(byte[] pixels) + { + if (mapped != IntPtr.Zero && mapped != new IntPtr(-1)) + { + unsafe + { + pixels.AsSpan(0, Math.Min(pixels.Length, BufferBytes)).CopyTo(new Span((void*)mapped, BufferBytes)); + } + + return; + } + + if (stream is null) + { + return; + } + + stream.Position = 0; + stream.Write(pixels, 0, Math.Min(pixels.Length, BufferBytes)); + } + + public void WritePpm(string path) + { + Directory.CreateDirectory(Path.GetDirectoryName(path) ?? "."); + using var output = File.Create(path); + output.Write(Encoding.ASCII.GetBytes($"P6\n{Width} {Height}\n255\n")); + var rgb = new byte[Width * 3]; + for (var y = 0; y < Height; y++) + { + var row = new byte[Width * 4]; + ReadRow(y, row); + for (var x = 0; x < Width; x++) + { + rgb[x * 3] = row[x * 4 + 2]; + rgb[x * 3 + 1] = row[x * 4 + 1]; + rgb[x * 3 + 2] = row[x * 4]; + } + + output.Write(rgb); + } + } + + private static (int Width, int Height) ReadVirtualSize(string path) + { + var name = Path.GetFileName(path); + var sysfs = $"/sys/class/graphics/{name}/virtual_size"; + if (File.Exists(sysfs)) + { + var parts = File.ReadAllText(sysfs).Trim().Split(','); + if (parts.Length == 2 && + int.TryParse(parts[0], out var width) && + int.TryParse(parts[1], out var height)) + { + return (width, height); + } + } + + return (1920, 1080); + } + + private void ReadRow(int y, byte[] row) + { + if (mapped != IntPtr.Zero && mapped != new IntPtr(-1)) + { + unsafe + { + new ReadOnlySpan((void*)(mapped + y * Width * 4), row.Length).CopyTo(row); + } + + return; + } + + if (stream is null) + { + return; + } + + stream.Position = y * Width * 4; + _ = stream.Read(row); + } + + public void Dispose() + { + if (mapped != IntPtr.Zero && mapped != new IntPtr(-1)) + { + munmap(mapped, (UIntPtr)BufferBytes); + } + + if (fd >= 0) + { + close(fd); + } + + stream?.Dispose(); + } + + [DllImport("libc", SetLastError = true)] + private static extern int open(string pathname, int flags); + + [DllImport("libc", SetLastError = true)] + private static extern IntPtr mmap(IntPtr addr, UIntPtr length, int prot, int flags, int fd, IntPtr offset); + + [DllImport("libc", SetLastError = true)] + private static extern int munmap(IntPtr addr, UIntPtr length); + + [DllImport("libc", SetLastError = true)] + private static extern int close(int fd); +} + +internal sealed class FontAtlas +{ + private readonly PsfFont[] fonts; + public PsfFont Default => fonts[0]; + public PsfFont Edge => fonts.FirstOrDefault(font => font.Height >= 14 && font.Width >= 8) ?? fonts.FirstOrDefault(font => font.Height >= 10 && font.Width >= 6) ?? fonts.FirstOrDefault(font => font.Height >= 5 && font.Width >= 3) ?? Default; + public PsfFont this[int index] => fonts[Math.Clamp(index, 0, fonts.Length - 1)]; + public int IndexOf(PsfFont font) => Math.Max(0, Array.IndexOf(fonts, font)); + + private FontAtlas(PsfFont[] fonts) => this.fonts = fonts + .OrderBy(font => font.Width * font.Height) + .ThenBy(font => font.Height) + .ThenBy(font => font.Width) + .ToArray(); + + public static FontAtlas Load(string primary) + { + var candidates = new[] + { + primary, + "/usr/share/consolefonts/Lat2-Terminus12x6.psf.gz", + "/usr/share/consolefonts/Lat7-Terminus12x6.psf.gz", + "/usr/share/consolefonts/Lat2-Terminus14.psf.gz", + "/usr/share/consolefonts/Uni2-Fixed14.psf.gz", + "/usr/share/consolefonts/Lat2-TerminusBoldVGA16.psf.gz", + "/usr/share/consolefonts/UbuntuMono-R-8x16.psf", + "/usr/share/consolefonts/Uni3-TerminusBold18x10.psf.gz", + "/usr/share/consolefonts/Lat7-Terminus20x10.psf.gz", + "/usr/share/consolefonts/Uni3-TerminusBold22x11.psf.gz", + "/usr/share/consolefonts/Lat2-Terminus24x12.psf.gz", + "/usr/share/consolefonts/Uni2-Terminus28x14.psf.gz", + "/usr/share/consolefonts/Lat2-Terminus32x16.psf.gz", + }; + var loaded = candidates.Where(path => !string.IsNullOrWhiteSpace(path) && File.Exists(path)).Select(PsfFont.Load).GroupBy(font => (font.Width, font.Height)).Select(group => group.First()).ToArray(); + if (loaded.Length == 0) + { + throw new InvalidOperationException("No PSF console fonts found; pass --font."); + } + + var source = loaded.OrderBy(font => font.Width * font.Height).First(); + var generated = new[] + { + source.ShrinkTo(3, 3), + source.ShrinkTo(3, 5), + source.ShrinkTo(4, 5), + source.ShrinkTo(4, 6), + source.ShrinkTo(5, 7), + source.ShrinkTo(6, 8), + source.ShrinkTo(6, 10), + source.ShrinkTo(7, 11), + }; + return new FontAtlas(loaded.Concat(generated).GroupBy(font => (font.Width, font.Height)).Select(group => group.First()).ToArray()); + } + + public PsfFont ForTextBox(int width, int height, IReadOnlyList items, float weight, out int index) + { + var selected = fonts[0]; + var weightedPressure = Math.Clamp(weight / 4.0f, 0.0f, 5.0f); + foreach (var font in fonts.OrderByDescending(font => font.Width * font.Height)) + { + var columns = Math.Max(1, width / Math.Max(1, font.Width)); + var rows = Math.Max(1, height / Math.Max(1, font.LineHeight)); + var desiredRows = EstimateRows(items, columns) + weightedPressure; + if (desiredRows <= rows) + { + selected = font; + break; + } + } + + index = Array.IndexOf(fonts, selected); + return selected; + } + + public PsfFont HeaderFor(int height) + { + var target = height < 40 ? Math.Max(3, height / 3) : Math.Max(10, Math.Min(24, height / 7)); + return fonts.LastOrDefault(font => font.Height <= target) ?? Default; + } + + private static float EstimateRows(IReadOnlyList items, int columns) + { + if (items.Count == 0) + { + return 1.0f; + } + + var rows = 0.0f; + foreach (var item in items.Take(96)) + { + var length = Math.Max(1, item.Prefix.Length + 1 + item.Text.Length); + rows += MathF.Ceiling(length / (float)Math.Max(1, columns)); + rows += 0.18f; + } + + if (items.Count > 96) + { + rows += 1.0f; + } + + return rows; + } +} + +internal sealed class PsfFont +{ + private readonly byte[][] glyphs; + public int Width { get; } + public int Height { get; } + public int BytesPerRow { get; } + public int LineHeight => Height + (Height <= 5 ? 1 : 2); + public int BlockSpacing => Height <= 5 ? 0 : Math.Max(1, Height / 3); + + private PsfFont(int width, int height, byte[][] glyphs) + { + Width = width; + Height = height; + BytesPerRow = (width + 7) / 8; + this.glyphs = glyphs; + } + + public byte[] Glyph(char ch) => glyphs[Math.Clamp((int)ch, 0, glyphs.Length - 1)]; + + public PsfFont ShrinkTo(int width, int height) + { + var shrunk = new byte[glyphs.Length][]; + for (var glyphIndex = 0; glyphIndex < glyphs.Length; glyphIndex++) + { + shrunk[glyphIndex] = ShrinkGlyph(glyphs[glyphIndex], width, height); + } + + return new PsfFont(width, height, shrunk); + } + + public static PsfFont Load(string path) + { + var bytes = ReadBytes(path); + if (bytes.Length > 4 && bytes[0] == 0x36 && bytes[1] == 0x04) + { + var glyphCount = (bytes[2] & 0x01) != 0 ? 512 : 256; + var height = bytes[3]; + return new PsfFont(8, height, ReadGlyphs(bytes, 4, glyphCount, height, height)); + } + + if (bytes.Length > 32 && BitConverter.ToUInt32(bytes, 0) == 0x864ab572) + { + var headerSize = (int)BitConverter.ToUInt32(bytes, 8); + var glyphCount = (int)BitConverter.ToUInt32(bytes, 16); + var charSize = (int)BitConverter.ToUInt32(bytes, 20); + var height = (int)BitConverter.ToUInt32(bytes, 24); + var width = (int)BitConverter.ToUInt32(bytes, 28); + return new PsfFont(width, height, ReadGlyphs(bytes, headerSize, glyphCount, charSize, charSize)); + } + + throw new InvalidOperationException($"Unsupported PSF font: {path}"); + } + + private static byte[] ReadBytes(string path) + { + var bytes = File.ReadAllBytes(path); + if (!path.EndsWith(".gz", StringComparison.OrdinalIgnoreCase)) + { + return bytes; + } + + using var input = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress); + using var output = new MemoryStream(); + input.CopyTo(output); + return output.ToArray(); + } + + private static byte[][] ReadGlyphs(byte[] bytes, int offset, int count, int charSize, int stride) + { + var glyphs = new byte[count][]; + for (var i = 0; i < count; i++) + { + glyphs[i] = bytes.Skip(offset + i * stride).Take(charSize).ToArray(); + } + + return glyphs; + } + + private byte[] ShrinkGlyph(byte[] source, int width, int height) + { + var bytesPerRow = (width + 7) / 8; + var target = new byte[height * bytesPerRow]; + for (var y = 0; y < height; y++) + { + var sy0 = y * Height / height; + var sy1 = Math.Max(sy0 + 1, (y + 1) * Height / height); + for (var x = 0; x < width; x++) + { + var sx0 = x * Width / width; + var sx1 = Math.Max(sx0 + 1, (x + 1) * Width / width); + var lit = 0; + var total = 0; + for (var sy = sy0; sy < sy1; sy++) + { + for (var sx = sx0; sx < sx1; sx++) + { + total++; + if (IsSet(source, sx, sy)) + { + lit++; + } + } + } + + if (lit * 2 >= Math.Max(1, total)) + { + target[y * bytesPerRow + x / 8] |= (byte)(0x80 >> (x % 8)); + } + } + } + + return target; + } + + private bool IsSet(byte[] glyph, int x, int y) + { + if ((uint)x >= (uint)Width || (uint)y >= (uint)Height) + { + return false; + } + + var offset = y * BytesPerRow + x / 8; + return offset < glyph.Length && (glyph[offset] & (0x80 >> (x % 8))) != 0; + } +}