Skip to main content

hypergraph_rs/raster/
mod.rs

1//! Deterministic 3D-scene → terminal-text rasterizer (Phase R, PHASE-R-MAP §3/§4).
2//!
3//! Pipeline: `state → SceneGraph3D → CellGrid` (glyph text). Every public
4//! type here is `Debug + Clone + PartialEq + Serialize + Deserialize` (the
5//! JSON golden-artifact contract) and every `Cell` is Tier-0 fully
6//! informative (`ch + fg + bg` unconditionally — no `Option`).
7
8use serde::{Deserialize, Serialize};
9
10use crate::viz::NodeStyle;
11
12pub mod algebra;
13pub mod camera;
14pub mod color;
15pub mod deck;
16pub mod fmt;
17mod grid;
18#[cfg(feature = "cells3d")]
19pub mod h3;
20pub mod ingest;
21#[cfg(feature = "cells3d")]
22pub mod instruments;
23#[cfg(feature = "raster-png")]
24pub mod png;
25
26pub use camera::{
27    depth_sort, depth_sort_nodes, face_is_clipped, node_is_clipped, project, strut_is_clipped,
28    Camera, Projected,
29};
30pub use color::{heat, to_ansi256, Palette};
31
32/// A truecolor RGB triple. No alpha — the glyph floor composes fg/bg
33/// unconditionally (Task 4 fills the quantization/heat-ramp logic).
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Rgb(pub u8, pub u8, pub u8);
36
37/// A single terminal cell: glyph + foreground + background, always all
38/// three present (the glyph floor — PHASE-R-MAP §4 Tier-0 contract).
39#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
40pub struct Cell {
41    pub ch: char,
42    pub fg: Rgb,
43    pub bg: Rgb,
44}
45
46/// A row-major grid of `Cell`s (`cells.len() == cols*rows`).
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48pub struct CellGrid {
49    pub cols: u16,
50    pub rows: u16,
51    pub cells: Vec<Cell>,
52}
53
54impl CellGrid {
55    /// A grid of `cols * rows` cells, all set to `fill`.
56    pub fn filled(cols: u16, rows: u16, fill: Cell) -> Self {
57        let n = cols as usize * rows as usize;
58        Self {
59            cols,
60            rows,
61            cells: vec![fill; n],
62        }
63    }
64
65    /// Render `text` as a single-row banner of literal glyph `Cell`s (Task
66    /// 13 Property 3 hook: the labeled-scalar text path, independent of the
67    /// pixel `rasterize()` path — it never touches a frame golden). Every
68    /// cell still carries `ch+fg+bg` unconditionally (glyph floor). Bounded:
69    /// `text.chars().count()`.
70    pub fn from_banner_text(text: &str) -> Self {
71        let cells: Vec<Cell> = text
72            .chars()
73            .map(|ch| Cell {
74                ch,
75                fg: Rgb(255, 255, 255),
76                bg: Rgb(0, 0, 0),
77            })
78            .collect();
79        let cols = cells.len() as u16;
80        Self {
81            cols,
82            rows: u16::from(!cells.is_empty()),
83            cells,
84        }
85    }
86
87    /// Overwrite cells with the literal glyphs of `text`, starting at
88    /// `(row, col)` and wrapping onto the following rows, clipped at the
89    /// grid's last row (review MAJOR 5: the glyph-floor information-parity
90    /// constraint is met by stamping labeled scalars into the REAL frame,
91    /// not by building a separate banner grid nothing renders). Every
92    /// stamped cell still carries `ch+fg+bg` unconditionally. Bounded:
93    /// `text.chars().count()`, and never writes past `cells.len()`.
94    pub fn stamp_text(&mut self, row: u16, col: u16, text: &str, fg: Rgb, bg: Rgb) {
95        let cols = self.cols as usize;
96        if cols == 0 {
97            return;
98        }
99        let start = row as usize * cols + col as usize;
100        for (cell, ch) in self.cells.iter_mut().skip(start).zip(text.chars()) {
101            *cell = Cell { ch, fg, bg };
102        }
103    }
104
105    /// Glyphs only, newline-joined — the diffable byte-exact golden form.
106    pub fn to_text(&self) -> String {
107        let cols = self.cols as usize;
108        self.cells
109            .chunks(cols.max(1))
110            .map(|row| row.iter().map(|c| c.ch).collect::<String>())
111            .collect::<Vec<_>>()
112            .join("\n")
113    }
114
115    /// Glyphs with fg/bg ANSI escapes under `palette` (Task 4): `\x1b[0m`
116    /// reset, then per-cell `\x1b[38;2;r;g;bm`/`\x1b[48;2;r;g;bm` (truecolor)
117    /// or `\x1b[38;5;{n}m`/`\x1b[48;5;{n}m` (256, via `color::to_ansi256`,
118    /// quantized after the fg/bg pick — pick in truecolor, degrade last),
119    /// followed by the glyph.
120    pub fn to_ansi(&self, palette: Palette) -> String {
121        let cols = self.cols as usize;
122        let mut out = String::from("\x1b[0m");
123        for (i, cell) in self.cells.iter().enumerate() {
124            if i > 0 && i % cols.max(1) == 0 {
125                out.push('\n');
126            }
127            match palette {
128                Palette::TrueColor => {
129                    out.push_str(&format!(
130                        "\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m",
131                        cell.fg.0, cell.fg.1, cell.fg.2, cell.bg.0, cell.bg.1, cell.bg.2
132                    ));
133                }
134                Palette::Ansi256 => {
135                    out.push_str(&format!(
136                        "\x1b[38;5;{}m\x1b[48;5;{}m",
137                        to_ansi256(cell.fg),
138                        to_ansi256(cell.bg)
139                    ));
140                }
141            }
142            out.push(cell.ch);
143        }
144        out
145    }
146}
147
148/// A point in the 3D scene, prior to camera projection.
149#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
150pub struct Vertex3 {
151    pub x: f64,
152    pub y: f64,
153    pub z: f64,
154}
155
156/// A rendered node lifted into 3D (mirrors `viz::NodeGlyph`, `viz/mod.rs:52-61`).
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
158pub struct Node3 {
159    pub id: String,
160    pub pos: Vertex3,
161    pub radius: f64,
162    pub color: Rgb,
163    pub style: NodeStyle,
164    pub attrs: serde_json::Value,
165}
166
167/// A triangle face for the scanline fill (Task 3).
168#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
169pub struct Face {
170    pub verts: [Vertex3; 3],
171    pub fill: Rgb,
172    pub opacity: f64,
173}
174
175/// A line strut for the Bresenham line walk (Task 3).
176#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
177pub struct Strut {
178    pub a: Vertex3,
179    pub b: Vertex3,
180    pub color: Rgb,
181}
182
183/// The 3D scene graph — mirrors `viz::SceneGraph` (`viz/mod.rs:74-80`) lifted
184/// to `(x,y,z)` with triangle faces and line struts.
185#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
186pub struct SceneGraph3D {
187    pub nodes: Vec<Node3>,
188    pub faces: Vec<Face>,
189    pub struts: Vec<Strut>,
190    pub bounding_box: (f64, f64, f64, f64, f64, f64),
191    pub metadata: serde_json::Map<String, serde_json::Value>,
192}
193
194impl SceneGraph3D {
195    /// An empty scene graph (all collections empty, zero bbox).
196    pub fn empty() -> Self {
197        Self {
198            nodes: Vec::new(),
199            faces: Vec::new(),
200            struts: Vec::new(),
201            bounding_box: (0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
202            metadata: serde_json::Map::new(),
203        }
204    }
205
206    /// Every scalar (number) value in `metadata`, walked recursively through
207    /// nested objects/arrays, formatted as `"dotted.path=value"` (floats via
208    /// `fmt::fmt6`, the golden-fixture float formatter — Task 13 Property 3
209    /// hook: "SceneGraph3D labeled-scalar accessor"). `metadata` is a
210    /// `serde_json::Map` (BTreeMap-backed, no `preserve_order` feature) so
211    /// iteration order is key-sorted and deterministic, never `HashMap`
212    /// order. Bounded: total scalar count in `metadata`, a small fixed tree
213    /// built by the instrument builders.
214    pub fn labeled_scalars(&self) -> Vec<String> {
215        let mut out = Vec::new();
216        for (k, v) in &self.metadata {
217            collect_scalars(v, k, &mut out);
218        }
219        out
220    }
221}
222
223/// Recursive walk backing [`SceneGraph3D::labeled_scalars`]. Bounded by the
224/// metadata JSON tree's own (small, fixed) size.
225fn collect_scalars(v: &serde_json::Value, prefix: &str, out: &mut Vec<String>) {
226    match v {
227        serde_json::Value::Number(n) => {
228            let text = match n.as_f64() {
229                Some(f) if !n.is_i64() && !n.is_u64() => fmt::fmt6(f),
230                _ => n.to_string(),
231            };
232            out.push(format!("{prefix}={text}"));
233        }
234        serde_json::Value::Object(map) => {
235            for (k, val) in map {
236                collect_scalars(val, &format!("{prefix}.{k}"), out);
237            }
238        }
239        serde_json::Value::Array(arr) => {
240            for (i, val) in arr.iter().enumerate() {
241                collect_scalars(val, &format!("{prefix}[{i}]"), out);
242            }
243        }
244        _ => {}
245    }
246}
247
248/// The banner's foreground: the deck's own readout ink
249/// (`rgba(138,122,97,.9)`, `topology-deck.html:430-431`).
250const BANNER_FG: Rgb = Rgb(138, 122, 97);
251/// The banner's background — the frame's clear color.
252const BANNER_BG: Rgb = Rgb(0, 0, 0);
253
254/// Greedy word-wrap of the labeled-scalar tokens into `cols`-wide rows, one
255/// space between tokens, never splitting a token that fits on its own row
256/// (an over-long token gets its own row and is clipped by `stamp_text`).
257/// Bounded: one pass over `tokens`.
258fn wrap_tokens(tokens: &[String], cols: usize) -> Vec<String> {
259    let mut out: Vec<String> = Vec::new();
260    let mut line = String::new();
261    for t in tokens {
262        if line.is_empty() {
263            line.push_str(t);
264        } else if line.chars().count() + 1 + t.chars().count() <= cols {
265            line.push(' ');
266            line.push_str(t);
267        } else {
268            out.push(core::mem::take(&mut line));
269            line.push_str(t);
270        }
271    }
272    if !line.is_empty() {
273        out.push(line);
274    }
275    out
276}
277
278/// Rasterize `scene` under `camera` into a `cols x rows` `CellGrid`
279/// (Task 3): near-plane-clip, painter's depth-sort, rasterize faces,
280/// struts and node discs into a braille 2x4 subcell buffer via the shared
281/// `grid::draw_scene` core, compose glyphs, then stamp the scene's labeled
282/// scalars across the top rows as literal glyph cells.
283///
284/// The banner stamp is the Global Constraint (plan §Global Constraints,
285/// PHASE-R-MAP §4): *every labeled scalar an instrument computes must
286/// appear as literal text somewhere in the `CellGrid`* — the deck's own
287/// `PHI = … r = … — invariant under zoom` conservation banner
288/// (`topology-deck.html:430-433`) is the canonical case. A scene with empty
289/// `metadata` stamps nothing, so the pure-geometry tests are unaffected.
290///
291/// Pure function of `(scene, camera, cols, rows)` — byte-exact
292/// golden-testable.
293pub fn rasterize(scene: &SceneGraph3D, camera: &Camera, cols: u16, rows: u16) -> CellGrid {
294    let mut buf = grid::SubBuffer::new(cols as usize * 2, rows as usize * 4);
295    grid::draw_scene(
296        &mut buf,
297        scene,
298        camera,
299        cols as f64 * 2.0,
300        rows as f64 * 4.0,
301    );
302    let mut out = grid::compose_braille(&buf, cols, rows);
303
304    for (i, line) in wrap_tokens(&scene.labeled_scalars(), cols as usize)
305        .iter()
306        .enumerate()
307    {
308        if i >= rows as usize {
309            break;
310        }
311        out.stamp_text(i as u16, 0, line, BANNER_FG, BANNER_BG);
312    }
313    out
314}