use serde::{Deserialize, Serialize};
use crate::viz::NodeStyle;
pub mod algebra;
pub mod camera;
pub mod color;
pub mod deck;
pub mod fmt;
mod grid;
#[cfg(feature = "cells3d")]
pub mod h3;
pub mod ingest;
#[cfg(feature = "cells3d")]
pub mod instruments;
#[cfg(feature = "raster-png")]
pub mod png;
pub use camera::{
depth_sort, depth_sort_nodes, face_is_clipped, node_is_clipped, project, strut_is_clipped,
Camera, Projected,
};
pub use color::{heat, to_ansi256, Palette};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Rgb(pub u8, pub u8, pub u8);
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Cell {
pub ch: char,
pub fg: Rgb,
pub bg: Rgb,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CellGrid {
pub cols: u16,
pub rows: u16,
pub cells: Vec<Cell>,
}
impl CellGrid {
pub fn filled(cols: u16, rows: u16, fill: Cell) -> Self {
let n = cols as usize * rows as usize;
Self {
cols,
rows,
cells: vec![fill; n],
}
}
pub fn from_banner_text(text: &str) -> Self {
let cells: Vec<Cell> = text
.chars()
.map(|ch| Cell {
ch,
fg: Rgb(255, 255, 255),
bg: Rgb(0, 0, 0),
})
.collect();
let cols = cells.len() as u16;
Self {
cols,
rows: u16::from(!cells.is_empty()),
cells,
}
}
pub fn stamp_text(&mut self, row: u16, col: u16, text: &str, fg: Rgb, bg: Rgb) {
let cols = self.cols as usize;
if cols == 0 {
return;
}
let start = row as usize * cols + col as usize;
for (cell, ch) in self.cells.iter_mut().skip(start).zip(text.chars()) {
*cell = Cell { ch, fg, bg };
}
}
pub fn to_text(&self) -> String {
let cols = self.cols as usize;
self.cells
.chunks(cols.max(1))
.map(|row| row.iter().map(|c| c.ch).collect::<String>())
.collect::<Vec<_>>()
.join("\n")
}
pub fn to_ansi(&self, palette: Palette) -> String {
let cols = self.cols as usize;
let mut out = String::from("\x1b[0m");
for (i, cell) in self.cells.iter().enumerate() {
if i > 0 && i % cols.max(1) == 0 {
out.push('\n');
}
match palette {
Palette::TrueColor => {
out.push_str(&format!(
"\x1b[38;2;{};{};{}m\x1b[48;2;{};{};{}m",
cell.fg.0, cell.fg.1, cell.fg.2, cell.bg.0, cell.bg.1, cell.bg.2
));
}
Palette::Ansi256 => {
out.push_str(&format!(
"\x1b[38;5;{}m\x1b[48;5;{}m",
to_ansi256(cell.fg),
to_ansi256(cell.bg)
));
}
}
out.push(cell.ch);
}
out
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Vertex3 {
pub x: f64,
pub y: f64,
pub z: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Node3 {
pub id: String,
pub pos: Vertex3,
pub radius: f64,
pub color: Rgb,
pub style: NodeStyle,
pub attrs: serde_json::Value,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Face {
pub verts: [Vertex3; 3],
pub fill: Rgb,
pub opacity: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Strut {
pub a: Vertex3,
pub b: Vertex3,
pub color: Rgb,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SceneGraph3D {
pub nodes: Vec<Node3>,
pub faces: Vec<Face>,
pub struts: Vec<Strut>,
pub bounding_box: (f64, f64, f64, f64, f64, f64),
pub metadata: serde_json::Map<String, serde_json::Value>,
}
impl SceneGraph3D {
pub fn empty() -> Self {
Self {
nodes: Vec::new(),
faces: Vec::new(),
struts: Vec::new(),
bounding_box: (0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
metadata: serde_json::Map::new(),
}
}
pub fn labeled_scalars(&self) -> Vec<String> {
let mut out = Vec::new();
for (k, v) in &self.metadata {
collect_scalars(v, k, &mut out);
}
out
}
}
fn collect_scalars(v: &serde_json::Value, prefix: &str, out: &mut Vec<String>) {
match v {
serde_json::Value::Number(n) => {
let text = match n.as_f64() {
Some(f) if !n.is_i64() && !n.is_u64() => fmt::fmt6(f),
_ => n.to_string(),
};
out.push(format!("{prefix}={text}"));
}
serde_json::Value::Object(map) => {
for (k, val) in map {
collect_scalars(val, &format!("{prefix}.{k}"), out);
}
}
serde_json::Value::Array(arr) => {
for (i, val) in arr.iter().enumerate() {
collect_scalars(val, &format!("{prefix}[{i}]"), out);
}
}
_ => {}
}
}
const BANNER_FG: Rgb = Rgb(138, 122, 97);
const BANNER_BG: Rgb = Rgb(0, 0, 0);
fn wrap_tokens(tokens: &[String], cols: usize) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
let mut line = String::new();
for t in tokens {
if line.is_empty() {
line.push_str(t);
} else if line.chars().count() + 1 + t.chars().count() <= cols {
line.push(' ');
line.push_str(t);
} else {
out.push(core::mem::take(&mut line));
line.push_str(t);
}
}
if !line.is_empty() {
out.push(line);
}
out
}
pub fn rasterize(scene: &SceneGraph3D, camera: &Camera, cols: u16, rows: u16) -> CellGrid {
let mut buf = grid::SubBuffer::new(cols as usize * 2, rows as usize * 4);
grid::draw_scene(
&mut buf,
scene,
camera,
cols as f64 * 2.0,
rows as f64 * 4.0,
);
let mut out = grid::compose_braille(&buf, cols, rows);
for (i, line) in wrap_tokens(&scene.labeled_scalars(), cols as usize)
.iter()
.enumerate()
{
if i >= rows as usize {
break;
}
out.stamp_text(i as u16, 0, line, BANNER_FG, BANNER_BG);
}
out
}