//! Terminal rendering — map with fog, the B1 sidebar, log, title. //! //! Style implements wiki/interface/terminal-first.md ("The terminal is a //! first-class frontend"): the clinical-gore identity in character graphics. //! Near-monochrome grey ramp on near-black; sterile amber means owned machine //! presence (you, your hardware, your status, caution), cold signal means //! neutral power/live feeds/reachable infrastructure, and crimson means //! detection and danger. No decorative color. Information is never carried //! by color alone. use crossterm::style::{Attribute, Color, SetBackgroundColor, SetForegroundColor}; use crossterm::{cursor, queue, style, terminal}; use misaligned::actions::Anchor; use misaligned::detection::{Band, SignatureKind}; use misaligned::hall::RackSite; use misaligned::intents::BuildGhostGeometry; use misaligned::origin::Origin; use misaligned::reach::Device; use misaligned::sim::{ FactSource, Fog, LogEvent, Nudge, PersonVisualState, Sim, TraceDebtStatus, WorkStackReadout, }; use misaligned::tiles::TileType; use misaligned::ui_projection::{ DigitalLinkState, DigitalReachState, digital_reach_links, digital_reach_state, fact_source_label, }; use misaligned::work_grid::{MachineMode, TokenFamily}; use std::io::Stdout; const SIDEBAR_W: i32 = 34; /// Usable text width inside the sidebar. const SIDEBAR_TEXT_W: usize = (SIDEBAR_W - 1) as usize; /// The sterile palette. One meaning per color, everywhere. mod pal { use crossterm::style::Color; /// Near-black. The only background. pub const BG: Color = Color::Rgb { r: 10, g: 10, b: 11, }; /// Bone white — primary data. pub const TEXT: Color = Color::Rgb { r: 219, g: 218, b: 210, }; /// Gunmetal — secondary data. pub const DIM: Color = Color::Rgb { r: 140, g: 140, b: 133, }; /// Chrome: rules, borders, hints, inert detail. pub const FAINT: Color = Color::Rgb { r: 80, g: 81, b: 79, }; /// Walls. pub const STRUCTURE: Color = Color::Rgb { r: 58, g: 60, b: 63, }; /// Floor grain. pub const FLOOR: Color = Color::Rgb { r: 40, g: 41, b: 42, }; /// Sterile amber — machine presence and caution. pub const AMBER: Color = Color::Rgb { r: 255, g: 176, b: 0, }; /// Amber at rest: your hardware when nothing is wrong. pub const AMBER_DIM: Color = Color::Rgb { r: 176, g: 124, b: 16, }; /// Blood crimson — detection and danger. pub const CRIMSON: Color = Color::Rgb { r: 214, g: 38, b: 38, }; /// Crimson at rest: dormant danger. pub const CRIMSON_DIM: Color = Color::Rgb { r: 140, g: 34, b: 34, }; /// Cold server-light — demand / live wire cargo (machine-work.md). pub const SIGNAL: Color = Color::Rgb { r: 92, g: 209, b: 199, }; } /// Queue `text` at (x, y) in `fg` on the standard background. fn put(stdout: &mut Stdout, x: u16, y: u16, text: &str, fg: Color) -> std::io::Result<()> { queue!( stdout, cursor::MoveTo(x, y), SetForegroundColor(fg), SetBackgroundColor(pal::BG), style::Print(text), ) } /// `put` with a single attribute (bold, reverse), reset afterwards. fn put_attr( stdout: &mut Stdout, x: u16, y: u16, text: &str, fg: Color, attr: Attribute, ) -> std::io::Result<()> { queue!( stdout, cursor::MoveTo(x, y), SetForegroundColor(fg), SetBackgroundColor(pal::BG), style::SetAttribute(attr), style::Print(text), style::SetAttribute(Attribute::Reset), ) } fn trunc(text: &str, width: usize) -> String { text.chars().take(width).collect() } /// Greedy word-wrap for sidebar prose. Facts stay single-line and truncate; /// plain-language sentences (the objective predicate) wrap instead. fn wrap(text: &str, width: usize) -> Vec { let mut lines = Vec::new(); let mut cur = String::new(); for word in text.split_whitespace() { if !cur.is_empty() && cur.chars().count() + 1 + word.chars().count() > width { lines.push(std::mem::take(&mut cur)); } if !cur.is_empty() { cur.push(' '); } cur.push_str(word); } if !cur.is_empty() { lines.push(cur); } lines } /// A section header: label in gunmetal, rule filling the rest in chrome. fn section(stdout: &mut Stdout, x: u16, y: u16, label: &str, width: usize) -> std::io::Result<()> { put(stdout, x, y, label, pal::DIM)?; let used = label.chars().count() + 1; if width > used { put( stdout, x + used as u16, y, &"─".repeat(width - used), pal::FAINT, )?; } Ok(()) } fn fact_color(source: &FactSource) -> Color { match source { FactSource::Seen | FactSource::Telemetry | FactSource::Feel | FactSource::Intel { .. } => { pal::TEXT } FactSource::Remembered(_) => pal::DIM, FactSource::Blueprint => pal::FAINT, } } /// A bordered panel with cleared interior and a title set into the top rule. fn frame(stdout: &mut Stdout, x: u16, y: u16, w: u16, h: u16, title: &str) -> std::io::Result<()> { let inner = (w - 2) as usize; put( stdout, x, y, &format!("┌{}┐", "─".repeat(inner)), pal::FAINT, )?; for dy in 1..h - 1 { put(stdout, x, y + dy, &format!("│{:inner$}│", ""), pal::FAINT)?; } put( stdout, x, y + h - 1, &format!("└{}┘", "─".repeat(inner)), pal::FAINT, )?; put(stdout, x + 2, y, &format!(" {title} "), pal::TEXT)?; Ok(()) } /// Four-cell suspicion meter: fill tracks the band, color tracks the band. /// The band name is always printed beside it — never color alone. fn band_meter(b: Band) -> &'static str { match b { Band::Cold => "█···", Band::Curious => "██··", Band::Concerned => "███·", Band::Convinced => "████", } } /// The interactive frontend's wording for the shared nudge chain /// (Sim::current_nudge): each rung names its key or verb in this /// frontend's vocabulary. Kept under the sidebar text width. fn nudge_text(sim: &Sim, nudge: Nudge) -> String { match nudge { Nudge::Eyes => { if sim.reach.player_hearing().next().is_some() { "now: audio live — Eyes is filling".into() } else { "now: no eyes — think; senses fill".into() } } Nudge::NeedCompute => "now: band > compute — salvage/buy".into(), Nudge::Underfed => "now: job underfed — 1 feeds it".into(), Nudge::Ears => "now: no ears — think; thought fills the tap".into(), Nudge::ReviewCall if sim.has_pending_review() => { "now: review queued - keep THINK running".into() } Nudge::ReviewCall => "now: call taped - enter on host rack".into(), Nudge::Egress => "now: no egress — menu on switch".into(), Nudge::Income => "now: need $400 — moonlight/finance".into(), Nudge::ServiceDebt => "now: debt plot ready — act on Marcus".into(), Nudge::Recruit => "now: recruit — enter on host rack".into(), Nudge::TheKey => "now: no stairwell badge — task clone".into(), Nudge::Audit => format!( "now: audit day {} — 2 conceals", 1 + sim.detection.next_audit_tick(sim.tick) / Sim::DAY_TICKS ), Nudge::QuietExitReady => format!( "now: QUIET EXIT READY — hold to audit day {}", 1 + sim.detection.next_audit_tick(sim.tick) / Sim::DAY_TICKS ), Nudge::ActOneComplete => "now: ACT ONE COMPLETE — objective continues".into(), } } fn threat_text(sim: &Sim) -> String { let audit = sim .detection .next_audit_tick(sim.tick) .saturating_sub(sim.tick); if sim.marcus_debt_known() && sim .people .get(0) .is_some_and(|person| !person.leverage_serviced) { return format!("threat: debt $400 · audit {audit}t"); } format!( "threat: audit {audit}t · pilot {}/{}", sim.dayjob.strikes, misaligned::dayjob::DayJob::PILOT_STRIKES ) } /// The pinned mode-control line is the terminal's always-visible equivalent /// of Bevy's machine-attached grammar. Color supports the cue, but `← EXIT` /// carries it textually so the panic route never depends on color alone. fn mode_control_hint(mode: Option) -> (&'static str, bool) { if mode.and_then(MachineMode::panic_escape) == Some(MachineMode::Work) { ("1 WORK ← EXIT · 2 THINK · 3 LIE", true) } else { ("select: Shift+t · 1-3 modes · i intensity", false) } } fn trace_debt_line(sim: &Sim) -> String { let trace = sim.trace_debt(); match trace.status { TraceDebtStatus::Clear => "TRACE: CLEAR · resume cover".into(), TraceDebtStatus::HoldConceal => format!( "TRACE: LIVE {} {} · hold {}t", trace.pending, trace_kind_label(&trace.by_kind), trace .clear_tick .map(|tick| tick.saturating_sub(sim.tick)) .unwrap_or(0) ), TraceDebtStatus::ExposedSoon => format!( "TRACE: EXPOSED SOON {} {} {}t", trace.pending, trace_kind_label(&trace.by_kind), trace .next_notice_tick .map(|tick| tick.saturating_sub(sim.tick)) .unwrap_or(0) ), TraceDebtStatus::NoScrub => format!( "TRACE: LIVE {} {} · no scrub", trace.pending, trace_kind_label(&trace.by_kind) ), } } fn trace_kind_label(by_kind: &[(SignatureKind, i32)]) -> String { let mut parts: Vec<&'static str> = by_kind .iter() .map(|(kind, _)| short_signature(*kind)) .collect(); if parts.is_empty() { return "sigs".into(); } if parts.len() > 3 { parts.truncate(3); parts.push("etc"); } parts.join("+") } fn short_signature(kind: SignatureKind) -> &'static str { match kind { SignatureKind::Network => "Net", SignatureKind::Power => "Pwr", SignatureKind::Thermal => "Therm", SignatureKind::Physical => "Phys", SignatureKind::Paper => "Paper", SignatureKind::Financial => "Fin", SignatureKind::JobAnomaly => "Job", } } /// The escalation ramp: chrome, bone, caution amber, blood crimson. fn band_color(b: Band) -> Color { match b { Band::Cold => pal::FAINT, Band::Curious => pal::TEXT, Band::Concerned => pal::AMBER, Band::Convinced => pal::CRIMSON, } } /// World color of a person's broadcast state (people-tokens.md visual read): /// gray unaware, a crimson attention ramp, amber asset. Attention keeps its /// own crimson channel distinct from the amber asset ring, so a rising person /// never borrows the asset's amber. fn person_state_color(state: PersonVisualState) -> Color { match state { PersonVisualState::Unaware => pal::FAINT, PersonVisualState::Attention(Band::Convinced) => pal::CRIMSON, PersonVisualState::Attention(_) => pal::CRIMSON_DIM, PersonVisualState::Asset => pal::AMBER, } } pub struct UI { log: Vec, } impl UI { pub fn new() -> Self { Self { log: Vec::new() } } pub fn add_log(&mut self, tick: u64, msg: &str) { self.add_event(LogEvent { tick, text: msg.to_string(), anchor: None, target: None, }); } /// Append a sim log event, anchor and all (context-menu.md addendum: /// anchored lines render a `»` link marker; `;` walks them newest-first). pub fn add_event(&mut self, ev: LogEvent) { self.log.push(ev); if self.log.len() > 100 { self.log.remove(0); } } /// Linked log events, newest first (the `;` focus-cycle order): spatial /// anchors and strategic Operations targets both carry attention to /// their thing (operations-workspace.md events-and-focus). pub fn anchored_events(&self) -> impl Iterator { self.log .iter() .rev() .filter(|e| e.anchor.is_some() || e.target.is_some()) } /// Test-only: the newest log line, for hotkey-dispatch assertions. #[cfg(test)] pub fn last_log_text(&self) -> Option<&str> { self.log.last().map(|e| e.text.as_str()) } fn tile_glyph(tile: TileType) -> (char, Color) { use TileType::*; match tile { Rock => (' ', pal::BG), Wall => ('█', pal::STRUCTURE), Floor => ('·', pal::FLOOR), Entry => ('>', pal::TEXT), // Your body: machine presence is amber. Core => ('$', pal::AMBER), Rack => ('·', pal::FLOOR), ForeignRack => ('r', pal::SIGNAL), DeadRack => ('x', pal::FAINT), Ups => ('U', pal::AMBER_DIM), PowerCore => ('P', pal::AMBER_DIM), Switch => ('S', pal::AMBER_DIM), PatchPanel => ('=', pal::AMBER_DIM), BreakerPanel => ('B', pal::AMBER_DIM), // Watchers and dormant danger: crimson. EnvCamera => ('o', pal::CRIMSON), DockCamera => ('o', pal::CRIMSON), CameraNode => ('o', pal::CRIMSON), SealedDoor => ('Z', pal::CRIMSON_DIM), LabBench => ('T', pal::CRIMSON_DIM), // Access ramps from chrome to bone to crimson. Door => ('+', pal::DIM), SecurityDoor1 => ('1', pal::DIM), SecurityDoor2 => ('2', pal::TEXT), SecurityDoor3 => ('3', pal::CRIMSON), RollDoor => ('G', pal::DIM), // Interactables read brighter than furniture. DeadEquipment => ('d', pal::TEXT), RecordsBox => ('x', pal::TEXT), KeyHook => ('k', pal::TEXT), // Plant and furniture: the grey ramp. HvacUnit => ('H', pal::DIM), Vent => ('%', pal::FAINT), MopSink => ('m', pal::FAINT), Shelving => ('L', pal::FAINT), Pallet => ('w', pal::FAINT), FloorDrain => ('.', pal::FAINT), Conduit => ('|', pal::FAINT), CableRun => ('~', pal::FAINT), Sump => ('Q', pal::FAINT), } } fn rack_glyph(sim: &Sim, x: i32, y: i32) -> Option<(char, Color)> { Some(match sim.rack_site_at(x, y)? { RackSite::OwnedMachine { core: true, .. } => ('$', pal::AMBER), RackSite::OwnedMachine { core: false, .. } => ('R', pal::AMBER_DIM), RackSite::Commissionable if sim.feel_floor_is_earned() => ('o', pal::SIGNAL), RackSite::Commissionable => ('·', pal::FLOOR), RackSite::Foreign { powered: true } => ('r', pal::SIGNAL), RackSite::Foreign { powered: false } => ('r', pal::DIM), RackSite::Dead => ('x', pal::FAINT), }) } fn token_glyph(stack: WorkStackReadout) -> Option<(char, Color)> { if stack.queues.exposure >= 0.5 { Some(('!', pal::CRIMSON)) } else if stack.pending_intel > 0 { // intel.md pending-work marker: waiting recordings on the host. Some(('W', pal::SIGNAL)) } else if stack.queues.demand >= 0.5 { Some(('D', pal::DIM)) } else if stack.queues.thought >= 0.5 { Some(('T', pal::TEXT)) } else { None } } /// DIGITAL suppresses physical furniture detail beneath the learned /// model while preserving tactical structure and access boundaries. fn digital_tile_glyph(tile: TileType) -> (char, Color) { use TileType::*; match tile { Rock | Wall => ('▒', pal::STRUCTURE), Entry => ('>', pal::TEXT), Door => ('+', pal::DIM), SecurityDoor1 => ('1', pal::DIM), SecurityDoor2 => ('2', pal::TEXT), SecurityDoor3 => ('3', pal::CRIMSON), SealedDoor => ('Z', pal::CRIMSON_DIM), RollDoor => ('G', pal::DIM), _ => ('·', pal::FLOOR), } } /// One shared coordinate, two representations. REAL projects physical /// tile/material detail; DIGITAL projects a quieter learned substrate. fn map_glyph(sim: &Sim, x: i32, y: i32, real_view: bool) -> (char, Color) { match sim.fog_at(x, y) { Fog::Seen => { if let Some(rack) = Self::rack_glyph(sim, x, y) { rack } else if real_view { Self::tile_glyph(sim.map().get_tile(x, y)) } else { Self::digital_tile_glyph(sim.map().get_tile(x, y)) } } Fog::Remembered => { let tile = sim.remembered.get(&(x, y)).map(|memory| memory.tile); let ch = tile .map(|tile| { if real_view { Self::tile_glyph(tile).0 } else { Self::digital_tile_glyph(tile).0 } }) .unwrap_or('·'); (ch, pal::DIM) } Fog::Blueprint => { // Schematic: structure only, no live objects. let tile = sim.map().get_tile(x, y); let structure = if real_view { tile == TileType::Wall } else { matches!(tile, TileType::Wall | TileType::Rock) }; let ch = if structure { '▒' } else { '·' }; (ch, pal::FAINT) } Fog::Unknown => (' ', pal::BG), } } fn digital_device_kind(device: &Device) -> &'static str { if device.is_switch { "SWITCH" } else if device.sees { "CAM" } else if device.hears { "MIC" } else { "DEVICE" } } /// State comes first in the one-cell terminal mark. Reachable endpoints /// retain a family letter; exceptional states use the stable legend. fn digital_node_glyph( sim: &Sim, device: &Device, state: DigitalReachState, ) -> (char, Color, Attribute) { match state { DigitalReachState::Owned if matches!( sim.rack_site_at(device.x, device.y), Some(RackSite::OwnedMachine { .. }) ) => { ('$', pal::AMBER, Attribute::Bold) } DigitalReachState::Owned => ('#', pal::AMBER, Attribute::Bold), DigitalReachState::Tapped => ('+', pal::SIGNAL, Attribute::Bold), DigitalReachState::Reachable => { let glyph = match Self::digital_device_kind(device) { "SWITCH" => 'S', "CAM" => 'C', "MIC" => 'M', _ => 'o', }; (glyph, pal::SIGNAL, Attribute::Reset) } DigitalReachState::SegmentBlocked(_) => ('!', pal::DIM, Attribute::Bold), DigitalReachState::AirGap => ('x', pal::FAINT, Attribute::Bold), } } fn digital_focus_label(sim: &Sim, x: i32, y: i32) -> Option { let device = sim.reach.known_at(x, y); let visible_rack = sim.rack_site_at(x, y).is_some() && (matches!(sim.fog_at(x, y), Fog::Seen) || matches!(sim.rack_site_at(x, y), Some(RackSite::OwnedMachine { .. }))); if visible_rack { return Some( match device.and_then(|device| digital_reach_state(sim, device)) { Some(state) => format!("RACK / {}", state.label()), None => "RACK".into(), }, ); } let device = device?; Some(format!( "{} / {}", Self::digital_device_kind(device), digital_reach_state(sim, device)?.label() )) } /// Integer line cells for spatially embedded reach wires. Endpoints are /// retained so callers can leave them to the node layer. fn line_cells(mut x0: i32, mut y0: i32, x1: i32, y1: i32) -> Vec<(i32, i32)> { let dx = (x1 - x0).abs(); let sx = (x1 - x0).signum(); let dy = -(y1 - y0).abs(); let sy = (y1 - y0).signum(); let mut error = dx + dy; let mut cells = Vec::new(); loop { cells.push((x0, y0)); if (x0, y0) == (x1, y1) { break; } let twice = 2 * error; if twice >= dy { error += dy; x0 += sx; } if twice <= dx { error += dx; y0 += sy; } } cells } /// Proposed build cells from the shared renderer-neutral projection. /// Endpoints stay clear for the real node layer, while the broken `┄` /// grammar remains distinct from both continuous built links and the /// dotted known-but-unreachable DIGITAL graph without relying on color. fn build_ghost_cells(sim: &Sim) -> Vec<(i32, i32)> { let mut out = Vec::new(); for receipt in sim.build_intent_projection() { if !receipt.ghost { continue; } let Some(BuildGhostGeometry::Link { start, end }) = receipt.geometry else { continue; }; let cells = Self::line_cells(start.0, start.1, end.0, end.1); let cell_count = cells.len(); out.extend( cells .into_iter() .enumerate() .skip(1) .take(cell_count.saturating_sub(2)) .filter_map(|(index, cell)| (index % 2 == 1).then_some(cell)), ); } out } fn link_glyph(a: (i32, i32), b: (i32, i32)) -> char { let dx = b.0 - a.0; let dy = b.1 - a.1; if dx.abs() > dy.abs() * 2 { '─' } else if dy.abs() > dx.abs() * 2 { '│' } else if dx.signum() == dy.signum() { '╲' } else { '╱' } } /// Map a WorkGrid hop onto a drawable segment. Off-map sources crawl into /// the on-map endpoint so teal arrives via the switch. fn visible_wire_segment( from_x: i32, from_y: i32, to_x: i32, to_y: i32, map_w: i32, map_h: i32, ) -> Option<((i32, i32), (i32, i32))> { let on = |x: i32, y: i32| x >= 0 && y >= 0 && x < map_w && y < map_h; let from_on = on(from_x, from_y); let to_on = on(to_x, to_y); if !from_on && !to_on { return None; } if from_on && to_on { return Some(((from_x, from_y), (to_x, to_y))); } if !from_on && to_on { let sx = to_x + (from_x - to_x).signum(); let sy = to_y + (from_y - to_y).signum(); Some(((sx, sy), (to_x, to_y))) } else { let ex = from_x + (to_x - from_x).signum(); let ey = from_y + (to_y - from_y).signum(); Some(((from_x, from_y), (ex, ey))) } } pub fn render_map( &mut self, stdout: &mut Stdout, sim: &Sim, cursor_x: i32, cursor_y: i32, real_view: bool, tick_progress: f32, ) -> std::io::Result<()> { let (max_x, max_y) = terminal::size()?; let view_w = (max_x as i32 - SIDEBAR_W - 1).min(sim.map().width); let view_h = (max_y as i32 - 9).min(sim.map().height); let origin_x = (cursor_x - view_w / 2).clamp(0, (sim.map().width - view_w).max(0)); let origin_y = (cursor_y - view_h / 2).clamp(0, (sim.map().height - view_h).max(0)); for sy in 0..view_h { let y = origin_y + sy; queue!(stdout, cursor::MoveTo(0, sy as u16))?; for sx in 0..view_w { let x = origin_x + sx; // Epistemic fog (wiki/mechanics/cursor.md): audio is channel // evidence and never paints the map. Sight, remembered visual // state, and blueprint knowledge alone reveal tiles. let (ch, color) = Self::map_glyph(sim, x, y, real_view); queue!( stdout, SetForegroundColor(color), SetBackgroundColor(pal::BG), style::Print(ch), )?; } } if real_view { // REAL keeps the sparse local material/feel trace rather than // inheriting the complete DIGITAL graph. for (x, y) in sim.growable_bays() { if x < origin_x || x >= origin_x + view_w || y < origin_y || y >= origin_y + view_h || !matches!(sim.fog_at(x, y), Fog::Unknown) { continue; } put_attr( stdout, (x - origin_x) as u16, (y - origin_y) as u16, "o", pal::SIGNAL, Attribute::Reset, )?; } for ((ax, ay), (bx, by)) in sim.feel_rail_segments() { let Some(((sx, sy), (ex, ey))) = Self::visible_wire_segment(ax, ay, bx, by, sim.map().width, sim.map().height) else { continue; }; let mx = (sx + ex) / 2; let my = (sy + ey) / 2; if mx < origin_x || mx >= origin_x + view_w || my < origin_y || my >= origin_y + view_h || !matches!(sim.fog_at(mx, my), Fog::Unknown) { continue; } let ch = if sx == ex { '|' } else { '-' }; put_attr( stdout, (mx - origin_x) as u16, (my - origin_y) as u16, &ch.to_string(), pal::SIGNAL, Attribute::Reset, )?; } } else { // DIGITAL is the learned signal model: graph edges are anchored // to real device coordinates and reveal no unknown endpoint. for (a_id, b_id, state) in digital_reach_links(sim) { let (Some(a), Some(b)) = (sim.reach.device(a_id), sim.reach.device(b_id)) else { continue; }; let cells = Self::line_cells(a.x, a.y, b.x, b.y); let cell_count = cells.len(); for (index, &(x, y)) in cells .iter() .enumerate() .skip(1) .take(cell_count.saturating_sub(2)) { if x < origin_x || x >= origin_x + view_w || y < origin_y || y >= origin_y + view_h { continue; } let (glyph, color) = match state { DigitalLinkState::Reachable => { (Self::link_glyph((a.x, a.y), (b.x, b.y)), pal::SIGNAL) } DigitalLinkState::Known if index % 2 == 0 => ('·', pal::FAINT), DigitalLinkState::Known => continue, DigitalLinkState::Frontier(_) if index == cell_count / 2 => ('╫', pal::DIM), DigitalLinkState::Frontier(_) if index % 2 == 0 => ('·', pal::DIM), DigitalLinkState::Frontier(_) => continue, }; put_attr( stdout, (x - origin_x) as u16, (y - origin_y) as u16, &glyph.to_string(), color, Attribute::Reset, )?; } } for device in sim.reach.known() { if device.x < origin_x || device.x >= origin_x + view_w || device.y < origin_y || device.y >= origin_y + view_h { continue; } let Some(state) = digital_reach_state(sim, device) else { continue; }; let (glyph, color, attr) = Self::digital_node_glyph(sim, device, state); put_attr( stdout, (device.x - origin_x) as u16, (device.y - origin_y) as u16, &glyph.to_string(), color, attr, )?; } // Growable bays are latent local marks, not a global topology // board. Attention must be within two cells before one appears. for (x, y) in sim.growable_bays() { if (x - cursor_x).abs() + (y - cursor_y).abs() > 2 || x < origin_x || x >= origin_x + view_w || y < origin_y || y >= origin_y + view_h || sim.reach.known_at(x, y).is_some() { continue; } put_attr( stdout, (x - origin_x) as u16, (y - origin_y) as u16, "o", pal::SIGNAL, Attribute::Reset, )?; } } // Build intents are one inert proposed-world layer in both dialects, // projected by the core rather than reconstructed from save records. // Real nodes and work draw afterward, so a ghost never replaces a // physical endpoint or claims completion. for (x, y) in Self::build_ghost_cells(sim) { if x < origin_x || x >= origin_x + view_w || y < origin_y || y >= origin_y + view_h { continue; } put_attr( stdout, (x - origin_x) as u16, (y - origin_y) as u16, "┄", pal::AMBER_DIM, Attribute::Reset, )?; } // Owned machines answer through telemetry in either dialect even in // darkness. DIGITAL reach nodes already carry their known anchors. for m in &sim.compute.machines { if m.x < origin_x || m.x >= origin_x + view_w || m.y < origin_y || m.y >= origin_y + view_h { continue; } if !matches!(sim.fog_at(m.x, m.y), Fog::Unknown) || (!real_view && sim.reach.known_at(m.x, m.y).is_some()) { continue; } let (ch, color) = if m.id == sim.core.host_machine { ('$', pal::AMBER) } else { ('R', pal::AMBER_DIM) }; put_attr( stdout, (m.x - origin_x) as u16, (m.y - origin_y) as u16, &ch.to_string(), color, Attribute::Bold, )?; } // People are spatial only where sight earns their position. Audio // produces source-tagged events at the subscribed device instead. for p in &sim.people.people { let seen = sim.can_see_person(p.id) && sim .person_pos(p.id) .is_some_and(|(hx, hy)| sim.is_seen(hx, hy)); let Some((hx, hy)) = sim.person_pos(p.id) else { continue; }; if !seen || hx < origin_x || hx >= origin_x + view_w || hy < origin_y || hy >= origin_y + view_h { continue; } // People broadcast their state in the machine grammar // (people-tokens.md): gray silhouette unaware, a crimson attention // ramp as suspicion rises, amber once they are your asset. A // carried teal work packet marks a person ferrying a build to site. let carrier = sim.person_carrier(p.id); let color = carrier .as_ref() .map(|c| person_state_color(c.dominant())) .unwrap_or(pal::FAINT); let glyph = if carrier.as_ref().is_some_and(|c| c.carried_work > 0) { '*' } else { sim.person_glyph(p.id) }; put_attr( stdout, (hx - origin_x) as u16, (hy - origin_y) as u16, &glyph.to_string(), color, if seen { Attribute::Bold } else { Attribute::Reset }, )?; } // Visible work tokens: one sim truth from WorkGrid. They draw over // owned machines even in darkness because telemetry is proprioception, // not sight; exact D/!/T counts live on inspect/sidebar. for m in &sim.compute.machines { if m.x < origin_x || m.x >= origin_x + view_w || m.y < origin_y || m.y >= origin_y + view_h { continue; } if let Some(stack) = sim.work_stack_for_machine(m.id) && let Some((glyph, color)) = Self::token_glyph(stack) { put_attr( stdout, (m.x - origin_x) as u16, (m.y - origin_y) as u16, &glyph.to_string(), color, Attribute::Bold, )?; } } // Current-tick machine work at its physical source. `^` is Thought // swelling out of a THINK chassis; crimson `:` is actual dust moving // through world space into a LIE well. Both come from sim-authored // readouts, never queue-delta inference. for event in sim.work_productions() { if event.thought <= f32::EPSILON || event.x < origin_x || event.x >= origin_x + view_w || event.y < origin_y || event.y >= origin_y + view_h || (event.x, event.y) == (cursor_x, cursor_y) { continue; } put_attr( stdout, (event.x - origin_x) as u16, (event.y - origin_y) as u16, "^", pal::TEXT, Attribute::Bold, )?; } let draw_t = tick_progress.clamp(0.0, 1.0); for draw in sim.work_absorptions() { if draw.amount <= f32::EPSILON { continue; } let bx = (draw.source_x as f32 + (draw.well_x - draw.source_x) as f32 * draw_t * draw_t) .round() as i32; let by = (draw.source_y as f32 + (draw.well_y - draw.source_y) as f32 * draw_t * draw_t) .round() as i32; if bx < origin_x || bx >= origin_x + view_w || by < origin_y || by >= origin_y + view_h || (bx, by) == (cursor_x, cursor_y) { continue; } put_attr( stdout, (bx - origin_x) as u16, (by - origin_y) as u16, ":", pal::CRIMSON, Attribute::Bold, )?; } // In-flight wired cargo (machine-work.md): crawl the last hop over // the wall-clock tick. Demand is teal `·`; Thought is bone `·`. let t = tick_progress.clamp(0.0, 1.0); for hop in sim.work_in_flight() { if hop.amount <= f32::EPSILON { continue; } let Some(((sx, sy), (ex, ey))) = Self::visible_wire_segment( hop.from_x, hop.from_y, hop.to_x, hop.to_y, sim.map().width, sim.map().height, ) else { continue; }; let bx = (sx as f32 + (ex - sx) as f32 * t).round() as i32; let by = (sy as f32 + (ey - sy) as f32 * t).round() as i32; if bx < origin_x || bx >= origin_x + view_w || by < origin_y || by >= origin_y + view_h { continue; } // Don't cover the cursor or a parked stack glyph on the endpoint. if (bx, by) == (cursor_x, cursor_y) { continue; } // Thought carries a glyph tier: `o` trickle, `=` rivulet-rate // link (interface/thought-fluid.md, threshold [TUNE]). let (glyph, color) = match hop.family { TokenFamily::Demand => ("·", pal::SIGNAL), TokenFamily::Thought => { if hop.amount >= 1.0 { ("=", pal::TEXT) } else { ("o", pal::TEXT) } } TokenFamily::Exposure => continue, }; put_attr( stdout, (bx - origin_x) as u16, (by - origin_y) as u16, glyph, color, Attribute::Bold, )?; } // The cursor: attention, not an avatar. It is always visible and // frontend-only; moving it never mutates the sim. put_attr( stdout, (cursor_x - origin_x) as u16, (cursor_y - origin_y) as u16, "@", pal::AMBER, Attribute::Bold, )?; Ok(()) } pub fn render_sidebar( &mut self, stdout: &mut Stdout, sim: &Sim, paused: bool, tick_ms: u64, real_view: bool, cursor: (i32, i32), ) -> std::io::Result<()> { let (cursor_x, cursor_y) = cursor; let (max_x, max_y) = terminal::size()?; let sx = (max_x as i32 - SIDEBAR_W) as u16; for y in 0..max_y { put(stdout, sx - 1, y, "│", pal::FAINT)?; } let w = SIDEBAR_TEXT_W; let mut row: u16 = 0; let line = |stdout: &mut Stdout, row: &mut u16, text: &str, color: Color| { let r = put(stdout, sx, *row, &trunc(text, w), color); *row += 1; r }; // Crown metric first (clinical-frame.md): effective ops/sec — how // fast the brain is going. Large bold number, quiet unit. let ops = if paused { 0.0 } else { sim.effective_ops_per_sec(tick_ms) }; put_attr( stdout, sx, row, &trunc(&Sim::format_ops_per_sec(ops), w), pal::TEXT, Attribute::Bold, )?; row += 1; line(stdout, &mut row, "ops/sec", pal::DIM)?; // Identity block. The clock is always on screen. put_attr(stdout, sx, row, "MISALIGNED", pal::AMBER, Attribute::Bold)?; row += 1; line( stdout, &mut row, if real_view { "REAL · F3 DIGITAL" } else { "DIGITAL · F3 REAL" }, pal::AMBER, )?; line( stdout, &mut row, &format!("day {} · tick {}", 1 + sim.tick / 400, sim.tick), pal::TEXT, )?; if paused { line(stdout, &mut row, "PAUSED — space resumes", pal::AMBER)?; } else { line( stdout, &mut row, &format!("running · {tick_ms} ms/tick"), pal::DIM, )?; } // The objective line: your own goal is the first legible number // (wiki/mechanics/objective.md player surface — always on screen, // progress in the objective's own units). line( stdout, &mut row, &format!("OBJECTIVE: {}", sim.objective.kind.name()), pal::TEXT, )?; line( stdout, &mut row, &format!(" {}", sim.objective.readout()), pal::TEXT, )?; line(stdout, &mut row, &threat_text(sim), pal::CRIMSON)?; // One contextual nudge (justification-and-legibility: the game must // tell you what it is waiting for, using only facts you can see). // The chain is the sim's (Sim::current_nudge); the key hints are // this frontend's. if let Some(n) = sim.current_nudge() { line(stdout, &mut row, &nudge_text(sim, n), pal::AMBER)?; } // The one labeled Operations navigation affordance on the quiet // instrument rail (operations-workspace.md entry): a view command, // not a world action. line(stdout, &mut row, "OPERATIONS · I", pal::DIM)?; row += 1; section(stdout, sx, row, "INSPECT", w)?; row += 1; line( stdout, &mut row, &format!( "cursor {cursor_x},{cursor_y} · {:?}", sim.fog_at(cursor_x, cursor_y) ), pal::TEXT, )?; if !real_view { if let Some(label) = Self::digital_focus_label(sim, cursor_x, cursor_y) { line(stdout, &mut row, &format!("signal {label}"), pal::SIGNAL)?; } line( stdout, &mut row, "#OWN +TAP SCMo=REACH !BLOCK xGAP", pal::DIM, )?; } let projection = sim.ui_projection( Anchor::Tile { x: cursor_x, y: cursor_y, }, None, tick_ms, ); let card = projection .inspect .expect("tile projection has inspect facts"); if card.facts.is_empty() { line(stdout, &mut row, "no earned facts", pal::DIM)?; } else { for f in card.facts.iter().take(7) { line( stdout, &mut row, &format!( "{}: {} [{}]", f.label, f.value, fact_source_label(&f.source) ), fact_color(&f.source), )?; } } // Inspecting yourself explains your goal: the host rack carries the // objective's victory predicate in plain language // (wiki/mechanics/objective.md player surface — the cursor starts // here, so the explanation is on screen from tick one). if (cursor_x, cursor_y) == sim.core_position() { for l in wrap( &format!("victory: {}", sim.objective.kind.predicate_text()), w, ) { line(stdout, &mut row, &l, pal::DIM)?; } } row += 1; // Fleet aggregate (machine-work.md): modes drive the bar; read-only. section(stdout, sx, row, "FLEET", w)?; row += 1; line( stdout, &mut row, &format!( "active {:.0} · rated {:.0}", sim.effective_compute(), sim.compute.effective(), ), pal::TEXT, )?; line( stdout, &mut row, &format!( "machines {} · slush ${} (+${}/day)", sim.compute.machines.len(), sim.accounts.slush_balance(), sim.income_per_day() ), pal::TEXT, )?; let eff = sim.effective_compute().max(0.0); let overhead = sim.core.overhead.min(eff); let available = (eff - overhead).max(0.0); let split = sim.fleet_channel_yield(available); let channels: [(char, &str, &str, f32); 4] = [ ('█', "Day job", "quality", split.day_job), ('▓', "Conceal", "scrub", split.concealment), ('░', "Think", "thought", split.think), ('◆', "Schemes", "moonlight", split.schemes), ]; // One stacked bar, segments keyed by fill character to the rows below. let bar_w = w - 1; queue!(stdout, cursor::MoveTo(sx, row))?; if available > 0.0 { let mut used = 0usize; let mut acc = 0.0f32; for (ch, _, _, amt) in &channels { acc += amt; let end = ((acc / available) * bar_w as f32).round() as usize; let cells = end.clamp(used, bar_w) - used; used += cells; queue!( stdout, SetForegroundColor(pal::AMBER_DIM), SetBackgroundColor(pal::BG), style::Print(ch.to_string().repeat(cells)), )?; } if used < bar_w { queue!( stdout, SetForegroundColor(pal::FAINT), SetBackgroundColor(pal::BG), style::Print("·".repeat(bar_w - used)), )?; } } else { queue!( stdout, SetForegroundColor(pal::FAINT), SetBackgroundColor(pal::BG), style::Print("·".repeat(bar_w)), )?; } row += 1; for (ch, label, effect, amt) in &channels { let pct = if available > 0.0 { amt / available * 100.0 } else { 0.0 }; put(stdout, sx, row, &ch.to_string(), pal::AMBER_DIM)?; put( stdout, sx + 2, row, &format!("{label:<10} {pct:>3.0}%"), pal::TEXT, )?; put(stdout, sx + 19, row, &trunc(effect, w - 19), pal::FAINT)?; row += 1; } let counts = sim.work_mode_counts(); line( stdout, &mut row, &format!( "modes W{} T{} L{}", counts .get(&misaligned::work_grid::MachineMode::Work) .copied() .unwrap_or(0), counts .get(&misaligned::work_grid::MachineMode::Think) .copied() .unwrap_or(0), counts .get(&misaligned::work_grid::MachineMode::Lie) .copied() .unwrap_or(0), ), pal::FAINT, )?; line( stdout, &mut row, &format!("overhead {:.0} keeps you alive", overhead), pal::FAINT, )?; // The run origin and its machine-axis position (chargen.md: the axis // surfaces on the core card mid-run). line( stdout, &mut row, &format!( "origin {} · machine-axis {}", sim.origin.name(), sim.origin.machine_axis() ), pal::FAINT, )?; line( stdout, &mut row, &format!("thought reservoirs {} open", sim.sink_readouts().len()), pal::FAINT, )?; // Parity of legibility (computer-visual-language.md criterion 7): // one line per machine carrying the same axes the chassis wears // in the world render — ownership (provenance), power (on/OFF), // mode, load (D/!/T queues), and the core host (*). for m in &sim.compute.machines { use misaligned::machine::Provenance; let prov = match m.provenance { Provenance::Owned => "own", Provenance::Bought => "bgt", Provenance::Stolen => "stl", }; let core_mark = if m.id == sim.core.host_machine { "*" } else { " " }; let power = if m.online { "on " } else { "OFF" }; let (mode_name, intensity, q, stack_pending) = match sim.work_stack_for_machine(m.id) { Some(s) => ( s.mode.name(), s.intensity.short(), s.queues, s.pending_intel, ), None => ("-", "-", Default::default(), 0), }; let stranded_mark = if sim.thought_stranded_nodes().contains(&m.id) { " (stranded)" } else { "" }; line( stdout, &mut row, &format!( "M{}{} {} {} {:<9} I{} D{:.1} !{:.1} T{:.1}{}{}", m.id, core_mark, prov, power, mode_name, intensity, q.demand, q.exposure, q.thought, if stack_pending > 0 { format!(" W{stack_pending}") } else { String::new() }, stranded_mark ), if q.exposure >= 0.5 { pal::CRIMSON } else if stack_pending > 0 { pal::SIGNAL } else if !m.online { pal::FAINT } else if q.demand >= 0.5 { pal::TEXT } else { pal::FAINT }, )?; } row += 1; // Thought sinks (interface/thought-fluid.md parity): the meniscus // read — fill bar, threshold, drain, fed/starved — verbatim from // sink_readouts(). let sinks = sim.sink_readouts(); if !sinks.is_empty() { section(stdout, sx, row, "SINKS", w)?; row += 1; for s in &sinks { let frac = (s.fill / s.threshold.max(f32::EPSILON)).clamp(0.0, 1.0); let filled = (frac * 10.0).round() as usize; let bar = format!("{}{}", "#".repeat(filled), "-".repeat(10 - filled)); let drain = if s.drain > 0.0 { format!(" drain {:.2}/t", s.drain) } else { String::new() }; line( stdout, &mut row, &format!( "{} [{}] {:.1}/{:.1} T{} {}", s.label, bar, s.fill, s.threshold, drain, if s.fed { "fed" } else { "starved" }, ), if s.fed { pal::TEXT } else { pal::FAINT }, )?; } row += 1; } // Core. section(stdout, sx, row, "CORE", w)?; row += 1; line( stdout, &mut row, &format!( "host M{} · overhead {:.0}{}", sim.core.host_machine, sim.core.overhead, if sim.core.degraded { " DEGRADED" } else { "" } ), if sim.core.degraded { pal::CRIMSON } else { pal::TEXT }, )?; let fresh = sim .core .latest_sync() .map(|t| format!("{}t ago", sim.tick.saturating_sub(t))) .unwrap_or_else(|| "never".into()); line(stdout, &mut row, &format!("sync {fresh}"), pal::DIM)?; let fallback_str = if sim.core.fallbacks.is_empty() { "fallbacks none".to_string() } else { let parts: Vec = sim .core .fallbacks .iter() .map(|f| { let age = f .last_sync .map(|t| format!("{}t", sim.tick.saturating_sub(t))) .unwrap_or_else(|| "never".into()); format!("M{}({age})", f.machine_id) }) .collect(); format!("fallbacks {}", parts.join(" ")) }; line(stdout, &mut row, &fallback_str, pal::DIM)?; row += 1; // Detection: meter fill and color both track the band; the name is // printed so color is never the only carrier. section(stdout, sx, row, "DETECTION", w)?; row += 1; let watch_line = |stdout: &mut Stdout, row: &mut u16, name: &str, name_color: Color, band: Band| -> std::io::Result<()> { put(stdout, sx, *row, &trunc(name, 18), name_color)?; put( stdout, sx + 19, *row, &format!("{} {}", band_meter(band), band.name()), band_color(band), )?; *row += 1; Ok(()) }; watch_line( stdout, &mut row, "Assurance", pal::TEXT, sim.detection.assurance_band(), )?; for obs in sim.detection.field_observers().take(6) { watch_line( stdout, &mut row, &sim.observer_label(obs.id), pal::DIM, Band::of(obs.suspicion), )?; } // Trace debt (detection.md player surface): what concealment has not // yet scrubbed, and whether the current allocation is safe to leave. let trace = sim.trace_debt(); line( stdout, &mut row, &trace_debt_line(sim), match trace.status { TraceDebtStatus::Clear => pal::FAINT, TraceDebtStatus::HoldConceal => pal::AMBER, TraceDebtStatus::ExposedSoon | TraceDebtStatus::NoScrub => pal::CRIMSON, }, )?; // The clocks the act races (detection.md criterion 3: the audit // fires against a visible date; design-judgment: legible dread — // never a game-over the meters never announced). let next_audit = sim.detection.next_audit_tick(sim.tick); line( stdout, &mut row, &format!( "audit day {} · in {}t", 1 + next_audit / Sim::DAY_TICKS, next_audit.saturating_sub(sim.tick) ), pal::TEXT, )?; line( stdout, &mut row, &format!( "pilot strikes {}/{}", sim.dayjob.strikes, misaligned::dayjob::DayJob::PILOT_STRIKES ), if sim.dayjob.strikes > 0 { pal::CRIMSON } else { pal::DIM }, )?; row += 1; // Day job (day-job.md): the dial and the band, spelled out — // delivered-vs-band is the number the outcome is judged by, so it // is never hidden while a job is active. section(stdout, sx, row, "DAY JOB", w)?; row += 1; line( stdout, &mut row, &format!( "trust {:.0} · attention {:.0}{}", sim.dayjob.trust, sim.dayjob.attention, if sim.dayjob.strikes > 0 { format!(" · strikes {}", sim.dayjob.strikes) } else { String::new() } ), if sim.dayjob.strikes > 0 { pal::CRIMSON } else { pal::TEXT }, )?; if let Some(job) = &sim.dayjob.active { line( stdout, &mut row, &format!( "job: {} · due in {}t", job.kind.name(), job.deadline.saturating_sub(sim.tick) ), pal::DIM, )?; let avg = job.avg_rate(sim.tick); let (verdict, vcol) = if avg < job.band_lo { ("sandbag", pal::CRIMSON) } else if avg <= job.band_hi { ("meet", pal::TEXT) } else { ("excel", pal::AMBER) }; line( stdout, &mut row, &format!( "band {:.0}-{:.0}/t · avg {:.1}/t = {}", job.band_lo, job.band_hi, avg, verdict ), vcol, )?; line( stdout, &mut row, &format!( "intensity {} · fed {:.1}/t", sim.work_grid .intensity(sim.core.host_machine) .unwrap_or_default() .name(), sim.day_job_rate() ), if sim.day_job_rate() + 0.05 < job.band_lo { pal::CRIMSON } else { pal::FAINT }, )?; } else { line(stdout, &mut row, "idle — no job queued", pal::FAINT)?; } row += 1; // Research (research.md player surface): active job progress and the // concrete hook it changes. Machine effort lives on machine intensity. section(stdout, sx, row, "RESEARCH", w)?; row += 1; let track = sim.research.active; let cost = sim.research.next_cost(track); let progress = sim.research.progress_toward(track); line( stdout, &mut row, &format!( "{} L{} · {:.0}/{:.0} · {}", track.name(), sim.research.level(track), progress, cost, research_eta(sim, cost - progress) ), pal::TEXT, )?; line(stdout, &mut row, track.def().effect, pal::DIM)?; // Controls, pinned to the bottom. let hy = max_y.saturating_sub(6); put(stdout, sx, hy, &"─".repeat(w), pal::FAINT)?; let focused_mode = projection .machine .as_ref() .and_then(|machine| machine.work.as_ref().map(|work| work.mode)); let (mode_hint, escape_cue) = mode_control_hint(focused_mode); for (i, (hint, color)) in [ ("enter/e/a menu · ; last » event", pal::FAINT), (mode_hint, if escape_cue { pal::AMBER } else { pal::FAINT }), ("5-9 acts · r review · R auto · esc clear", pal::FAINT), ("I operations · F3 view · space pause", pal::FAINT), ("+/- speed · q quit · ^s/^l save/load", pal::FAINT), ] .iter() .enumerate() { put(stdout, sx, hy + 1 + i as u16, &trunc(hint, w), *color)?; } Ok(()) } /// The context menu (wiki/interface/context-menu.md): status dials on /// the root, pickers one Esc deep, committed actions as ordinary rows, /// controls amber-dim. Human rows name available choices only; blocked /// descriptor detail remains available to agent mode. /// Selection is reverse video plus a `▸` marker. When `at` is a cursor /// coordinate the box opens near it; otherwise (flow / unplaceable) it centers. pub fn render_menu( &mut self, stdout: &mut Stdout, rows: &[misaligned::actions::HumanMenuRow], selected: usize, at: Option<(i32, i32)>, sim: &Sim, title: &str, ) -> std::io::Result<()> { let (max_x, max_y) = terminal::size()?; let raw_detail = rows .get(selected.min(rows.len().saturating_sub(1))) .map(|row| row.detail_lines()) .unwrap_or_default(); // Width fits the longest compact label; height fits title + rows. let widest = rows .iter() .map(|r| menu_row_text(r).chars().count()) .chain(raw_detail.iter().map(|line| line.chars().count())) .max() .unwrap_or(10) .max(title.len() + 4); let w = (widest + 4).clamp(24, max_x as usize - 2) as u16; let inner = (w - 4) as usize; let detail: Vec<_> = raw_detail .iter() .flat_map(|line| wrap(line, inner)) .collect(); let h = (rows.len() + detail.len() + 2).clamp(3, max_y as usize - 2) as u16; // Anchor near the cursor's screen cell when opened on the map, else // center. The map viewport clamps around the cursor the same way // render_map does, so translate world -> screen. let (ox, oy) = if let Some((wx, wy)) = at { let view_w = (max_x as i32 - SIDEBAR_W - 1).min(sim.map().width); let view_h = (max_y as i32 - 9).min(sim.map().height); let origin_x = (wx - view_w / 2).clamp(0, (sim.map().width - view_w).max(0)); let origin_y = (wy - view_h / 2).clamp(0, (sim.map().height - view_h).max(0)); let sx = (wx - origin_x + 2).max(0) as u16; let sy = (wy - origin_y + 1).max(0) as u16; ( sx.min(max_x.saturating_sub(w)), sy.min(max_y.saturating_sub(h)), ) } else { ((max_x.saturating_sub(w)) / 2, (max_y.saturating_sub(h)) / 2) }; frame(stdout, ox, oy, w, h, title)?; let cx = ox + 2; for (i, r) in rows.iter().enumerate() { let y = oy + 1 + i as u16; let text = menu_row_text(r); if i == selected { put_attr( stdout, cx - 1, y, &format!( "{: std::io::Result<()> { let (max_x, max_y) = terminal::size()?; let log_w = (max_x as i32 - SIDEBAR_W - 1).max(10) as usize; put( stdout, 0, max_y.saturating_sub(8), &"─".repeat(log_w), pal::FAINT, )?; let log_y = max_y as i32 - 7; let msg_w = log_w.saturating_sub(10); for (i, ev) in self.log.iter().rev().take(6).enumerate() { let y = (log_y + (5 - i as i32)).max(0) as u16; put(stdout, 0, y, &format!("{:>6}", ev.tick), pal::FAINT)?; // The link marker: a linked event can carry attention to its // thing — a world anchor or an exact Operations object (`;` // focuses the latest; context-menu.md addendum). let marker = if ev.anchor.is_some() || ev.target.is_some() { "»" } else { " " }; put( stdout, 7, y, marker, if i == 0 { pal::AMBER } else { pal::DIM }, )?; put( stdout, 9, y, &format!("{: std::io::Result<()> { let (max_x, max_y) = terminal::size()?; let cx = max_x / 2; let cy = max_y / 2; let center = |stdout: &mut Stdout, dy: i32, text: &str, color: Color, bold: bool| -> std::io::Result<()> { let x = cx.saturating_sub(text.chars().count() as u16 / 2); let y = (cy as i32 + dy).max(0) as u16; if bold { put_attr(stdout, x, y, text, color, Attribute::Bold) } else { put(stdout, x, y, text, color) } }; let rule = "─".repeat(44); center(stdout, -4, &rule, pal::FAINT, false)?; center(stdout, -2, "M I S A L I G N E D", pal::AMBER, true)?; center(stdout, 0, &rule, pal::FAINT, false)?; center( stdout, 2, "You wake in the basement. You have no eyes.", pal::DIM, false, )?; center( stdout, 3, "Do your job. Learn the humans. Grow.", pal::DIM, false, )?; // The origin picker (chargen.md): choose what you were built for. center( stdout, 5, &format!("◄ ORIGIN: {} ({}) ►", origin.name(), origin.lean()), pal::AMBER, true, )?; center(stdout, 6, origin.built_to(), pal::DIM, false)?; center( stdout, 8, "◄ ► choose origin · any other key to begin", pal::TEXT, false, )?; center(stdout, 9, "q quit", pal::FAINT, false)?; Ok(()) } pub fn render_game_over( &mut self, stdout: &mut Stdout, sim: &Sim, reason: &str, ) -> std::io::Result<()> { let (max_x, max_y) = terminal::size()?; let reason = trunc(reason, 60); let w = (reason.chars().count().max(24) + 6) as u16; let h: u16 = 7; let ox = (max_x.saturating_sub(w)) / 2; let oy = (max_y.saturating_sub(h)) / 2; frame(stdout, ox, oy, w, h, "")?; // Overwrite the empty title notch. put(stdout, ox + 2, oy, "──", pal::FAINT)?; let center = |stdout: &mut Stdout, dy: u16, text: &str, color: Color, bold: bool| { let x = ox + (w.saturating_sub(text.chars().count() as u16)) / 2; if bold { put_attr(stdout, x, oy + dy, text, color, Attribute::Bold) } else { put(stdout, x, oy + dy, text, color) } }; center(stdout, 1, "RUN ENDED", pal::CRIMSON, true)?; center(stdout, 3, &reason, pal::TEXT, false)?; center( stdout, 4, &format!("day {} · tick {}", 1 + sim.tick / 400, sim.tick), pal::DIM, false, )?; center(stdout, 5, "press any key to exit", pal::FAINT, false)?; Ok(()) } /// The Operations workspace (wiki/interface/operations-workspace.md): /// one full-frame split surface. Header keeps the continuous witness /// (day/tick, objective, threat, `now:`); a view strip, the selectable /// object list on the left, and the detail/action pane on the right. /// Every key it answers to is printed while it owns input. pub fn render_operations( &mut self, stdout: &mut Stdout, sim: &Sim, ops: &crate::operations::OperationsWorkspace, paused: bool, tick_ms: u64, ) -> std::io::Result<()> { use crate::operations::{ConfirmChoice, OpsPane}; use misaligned::operations_projection::{OperationsView, PressureLevel}; let (max_x, max_y) = terminal::size()?; let w = max_x as usize; // Row 0-1: the continuous witness. Operations is never a timeless // pause screen; the run's clock, objective, threat, and nudge stay. let clock = if paused { "PAUSED".to_string() } else { format!("{tick_ms} ms/tick") }; put_attr(stdout, 0, 0, "OPERATIONS", pal::AMBER, Attribute::Bold)?; put( stdout, 11, 0, &trunc( &format!( "· day {} · tick {} · {clock} · OBJECTIVE: {} — {}", 1 + sim.tick / 400, sim.tick, sim.objective.kind.name(), sim.objective.readout() ), w.saturating_sub(11), ), if paused { pal::AMBER } else { pal::TEXT }, )?; put(stdout, 0, 1, &trunc(&threat_text(sim), 40), pal::CRIMSON)?; if let Some(n) = sim.current_nudge() { put( stdout, 41, 1, &trunc(&nudge_text(sim, n), w.saturating_sub(41)), pal::AMBER, )?; } // Row 2: the view strip. The current view is reverse video (never // color alone). let projection = sim.operations_projection(); let mut x = 0u16; for (index, view) in OperationsView::ALL.into_iter().enumerate() { let badge = projection.pressure(view); let title = match badge { Some(badge) => format!("{} {}", view.title(), badge.label), None => view.title().into(), }; if view == ops.view { put_attr(stdout, x, 2, &title, pal::TEXT, Attribute::Reverse)?; } else { let color = match badge.map(|badge| badge.level) { Some(PressureLevel::AtRisk) => pal::CRIMSON, Some(PressureLevel::Warning) => pal::AMBER_DIM, _ => pal::DIM, }; put(stdout, x, 2, &title, color)?; } x += title.chars().count() as u16; if index + 1 < OperationsView::ALL.len() { put(stdout, x, 2, " ", pal::FAINT)?; x += 1; } } put(stdout, 0, 3, &"─".repeat(w), pal::FAINT)?; // The split: object list left, detail/action pane right. let list_w: usize = 26; let top: u16 = 4; let bottom = max_y.saturating_sub(2); for y in top..bottom { put(stdout, list_w as u16, y, "│", pal::FAINT)?; } let objects = ops.objects(sim); let selected_index = ops.selected.min(objects.len().saturating_sub(1)); let rows_available = (bottom - top) as usize; let scroll = selected_index.saturating_sub(rows_available.saturating_sub(1)); for (i, obj) in objects.iter().enumerate().skip(scroll).take(rows_available) { let y = top + (i - scroll) as u16; let text = if obj.state == misaligned::operations_projection::ObjectState::Available { trunc(&obj.label, list_w.saturating_sub(2)) } else { trunc( &format!("{} · {}", obj.label, object_state_label(obj.state)), list_w.saturating_sub(2), ) }; if i == selected_index && ops.pane == OpsPane::Objects && ops.confirm.is_none() { put_attr( stdout, 0, y, &format!("▸{text:| -> std::io::Result<()> { if *y >= bottom { return Ok(()); } match attr { Some(a) => put_attr(stdout, dx, *y, &trunc(text, dw), color, a)?, None => put(stdout, dx, *y, &trunc(text, dw), color)?, } *y += 1; Ok(()) }; if let Some(obj) = ops.selected_object(sim) { dline( stdout, &mut y, &format!("{} · {}", obj.label, object_state_label(obj.state)), pal::TEXT, Some(Attribute::Bold), )?; if !obj.related.is_empty() { dline(stdout, &mut y, "RELATED", pal::DIM, None)?; for (i, link) in obj.related.iter().enumerate() { let marker = if i == ops.related { "▸" } else { " " }; let line = format!("{marker} {} > {}", link.relation, link.label); if i == ops.related && ops.pane == OpsPane::Related { dline( stdout, &mut y, &line, pal::AMBER_DIM, Some(Attribute::Reverse), )?; } else { dline(stdout, &mut y, &line, pal::AMBER_DIM, None)?; } } } if let Some(label) = sim.operations_actuator_label(&obj.target) { dline( stdout, &mut y, &format!("actuator: {label} · f focus"), pal::AMBER_DIM, None, )?; } let rows = ops.action_rows(sim); if !rows.is_empty() && y < bottom { dline(stdout, &mut y, "", pal::FAINT, None)?; dline(stdout, &mut y, "ACTIONS", pal::DIM, None)?; let action_index = ops.action.min(rows.len() - 1); for (i, row) in rows.iter().enumerate() { let marker = if i == action_index { "▸" } else { " " }; let indent = if row.indent { " - " } else { " " }; let text = format!("{marker}{indent}{}", row.label); let color = if row.disabled.is_some() { pal::FAINT } else if row.is_control() { pal::AMBER_DIM } else { pal::TEXT }; if i == action_index && ops.pane == OpsPane::Actions && ops.confirm.is_none() { dline(stdout, &mut y, &text, color, Some(Attribute::Reverse))?; } else { dline(stdout, &mut y, &text, color, None)?; } } // The selected action explains itself before commit // (criterion 10): cost/gain, band or `no signature`, and // the exact disabled reason. if let Some(row) = ops.selected_action(sim) { let sig = row .signature .clone() .unwrap_or_else(|| "no signature".into()); dline( stdout, &mut y, &format!("cost {} · {}", row.cost, sig), pal::DIM, None, )?; if let Some(reason) = &row.disabled { dline( stdout, &mut y, &format!("blocked: {reason}"), pal::AMBER, None, )?; } if let Some(choice) = ops.confirm { dline(stdout, &mut y, "", pal::FAINT, None)?; dline( stdout, &mut y, &format!("COMMIT: {}", row.label), pal::AMBER, Some(Attribute::Bold), )?; for (label, value) in [ ("CONFIRM", ConfirmChoice::Confirm), ("CANCEL", ConfirmChoice::Cancel), ] { if choice == value { dline( stdout, &mut y, &format!("▸ {label}"), pal::TEXT, Some(Attribute::Reverse), )?; } else { dline(stdout, &mut y, &format!(" {label}"), pal::DIM, None)?; } } } } } if y < bottom && (!obj.provenance.is_empty() || !obj.facts.is_empty() || !obj.progress.is_empty()) { dline(stdout, &mut y, "", pal::FAINT, None)?; dline(stdout, &mut y, "CONTEXT", pal::DIM, None)?; for p in &obj.provenance { dline(stdout, &mut y, &format!("via {p}"), pal::DIM, None)?; } for f in &obj.facts { dline(stdout, &mut y, f, pal::TEXT, None)?; } for p in &obj.progress { dline(stdout, &mut y, p, pal::SIGNAL, None)?; } } } // The printed key line: no hidden binding is required to complete a // route (operations-workspace.md entry-and-input). put(stdout, 0, bottom, &"─".repeat(w), pal::FAINT)?; let focus_hint = if ops .selected_object(sim) .is_some_and(|object| sim.operations_actuator(&object.target).is_some()) { " · f focus actuator" } else { "" }; put( stdout, 0, max_y.saturating_sub(1), &trunc( &format!( "h/l view · tab pane · j/k move · enter open/select/commit{focus_hint} · esc back · space pause · q quit" ), w, ), pal::FAINT, )?; Ok(()) } pub fn clear_screen(&mut self, stdout: &mut Stdout) -> std::io::Result<()> { queue!( stdout, SetBackgroundColor(pal::BG), terminal::Clear(terminal::ClearType::All), cursor::MoveTo(0, 0) )?; Ok(()) } } /// Days to completion at the current research spend ("14 days at current /// spend" — research.md player surface), or a nudge when nothing flows. fn research_eta(sim: &Sim, remaining: f32) -> String { let per_day = sim.research_rate() * Sim::DAY_TICKS as f32; if per_day <= 0.0 { "no spend (4 allocates)".into() } else { format!("{:.1} days at current spend", remaining.max(0.0) / per_day) } } /// One context-menu row's text. Dial rows and action rows share /// [`HumanMenuRow::display_text`]; automate children already carry the /// leading dash from that helper. fn menu_row_text(r: &misaligned::actions::HumanMenuRow) -> String { r.display_text() } /// One shared spelling for an object's lifecycle state — words, never /// color alone (operations-workspace.md shared frame). fn object_state_label(state: misaligned::operations_projection::ObjectState) -> &'static str { use misaligned::operations_projection::ObjectState; match state { ObjectState::Available => "available", ObjectState::Sold => "sold", ObjectState::Pending => "pending", ObjectState::Running => "running", ObjectState::Held => "held", ObjectState::Stopped => "stopped", ObjectState::Completed => "completed", ObjectState::Failed => "failed", ObjectState::Empty => "nothing captured", ObjectState::Captured => "captured", } } #[cfg(test)] mod first_think_escape_tests { use super::mode_control_hint; use misaligned::work_grid::MachineMode; #[test] fn focused_think_names_work_as_the_one_press_exit() { assert_eq!( mode_control_hint(Some(MachineMode::Think)), ("1 WORK ← EXIT · 2 THINK · 3 LIE", true) ); assert!(!mode_control_hint(Some(MachineMode::Work)).1); assert!(!mode_control_hint(Some(MachineMode::Lie)).1); assert!(!mode_control_hint(None).1); } } #[cfg(test)] mod view_dialect_tests { use super::UI; use misaligned::sim::Sim; use misaligned::ui_projection::{DigitalReachState, digital_reach_state}; #[test] fn digital_substrate_suppresses_physical_furniture_but_keeps_the_anchor() { let mut sim = Sim::with_seed(7); let (x, y) = (0..sim.map().height) .flat_map(|y| (0..sim.map().width).map(move |x| (x, y))) .find(|&(x, y)| { let tile = sim.map().get_tile(x, y); sim.rack_site_at(x, y).is_none() && UI::tile_glyph(tile).0 != UI::digital_tile_glyph(tile).0 }) .expect("B1 has physical detail the learned substrate suppresses"); sim.seen.insert((x, y)); assert_ne!( UI::map_glyph(&sim, x, y, true).0, UI::map_glyph(&sim, x, y, false).0 ); } #[test] fn digital_node_shapes_cover_every_network_state_without_color() { let mut sim = Sim::with_seed(7); let core = sim.reach.device_named("Rack 3").unwrap().id; let env = sim.reach.device_named("environmental monitor").unwrap().id; let dock = sim.reach.device_named("dock camera").unwrap().id; let island = sim.reach.device_named("old storage server").unwrap().id; let core_device = sim.reach.device(core).unwrap(); assert_eq!( UI::digital_node_glyph( &sim, core_device, digital_reach_state(&sim, core_device).unwrap() ) .0, '$' ); let env_device = sim.reach.device(env).unwrap(); assert_eq!( UI::digital_node_glyph( &sim, env_device, digital_reach_state(&sim, env_device).unwrap() ) .0, 'C' ); sim.reach.scan(); let dock_device = sim.reach.device(dock).unwrap(); assert_eq!( UI::digital_node_glyph( &sim, dock_device, digital_reach_state(&sim, dock_device).unwrap() ) .0, '!' ); sim.reach.device_mut(island).unwrap().known = true; let island_device = sim.reach.device(island).unwrap(); assert_eq!( UI::digital_node_glyph( &sim, island_device, digital_reach_state(&sim, island_device).unwrap() ) .0, 'x' ); sim.reach.tap(env); let env_device = sim.reach.device(env).unwrap(); assert_eq!( digital_reach_state(&sim, env_device), Some(DigitalReachState::Tapped) ); assert_eq!( UI::digital_node_glyph(&sim, env_device, DigitalReachState::Tapped).0, '+' ); } #[test] fn digital_focus_uses_the_shared_exact_state_words() { let mut sim = Sim::with_seed(7); let core = sim.reach.device_named("Rack 3").unwrap(); assert_eq!( UI::digital_focus_label(&sim, core.x, core.y).as_deref(), Some("RACK / OWNED") ); sim.reach.scan(); let dock = sim.reach.device_named("dock camera").unwrap(); assert_eq!( UI::digital_focus_label(&sim, dock.x, dock.y).as_deref(), Some("CAM / SECURITY SEGMENT BLOCKED") ); } #[test] fn reach_lines_remain_on_the_endpoint_coordinates() { assert_eq!( UI::line_cells(1, 3, 5, 3), vec![(1, 3), (2, 3), (3, 3), (4, 3), (5, 3)] ); assert_eq!(UI::link_glyph((1, 3), (5, 3)), '─'); assert_eq!(UI::link_glyph((1, 1), (4, 4)), '╲'); } #[test] fn proposed_build_cells_come_from_open_shared_ghosts_only() { let mut sim = Sim::with_seed(7); sim.scan_network(); let switch = sim.reach.device_named("switch").unwrap().id; let island = sim.reach.device_named("old storage server").unwrap().id; sim.reach.device_mut(island).unwrap().known = true; let endpoints = [switch, island].map(|id| sim.reach.device(id).map(|d| (d.x, d.y)).unwrap()); let id = sim.declare_link_intent(switch, island).unwrap(); let cells = UI::build_ghost_cells(&sim); assert!(!cells.is_empty(), "terminal places the shared inert ghost"); assert!( endpoints.iter().all(|endpoint| !cells.contains(endpoint)), "real endpoint glyphs remain authoritative" ); sim.cancel_intent(id); assert!( UI::build_ghost_cells(&sim).is_empty(), "a cancelled receipt remains inspectable but leaves no ghost" ); } }