hypergraph_rs/raster/camera.rs
1//! Camera + perspective projection + painter's depth sort (Task 2).
2//!
3//! Pipeline (PHASE-R-MAP §3, deck `topology-deck.html` `cam.ry`/`cam.rx`
4//! model, mined from `tui-3d-renderer/src/raster.rs::prepare_position` +
5//! `src/clip.rs`, but pure f64 and rotate-Y-then-X per the deck):
6//!
7//! 1. Camera space: `v' = RotX(rx) · RotY(ry) · v`, then `z' += dist`.
8//! 2. Near-plane clip FIRST: reject the whole primitive if any vertex has
9//! `z' <= NEAR_EPS` (never divide by a near-zero/negative `z'`).
10//! 3. Perspective divide with focal length `f = 1 / tan(fov*pi/360)`,
11//! aspect-corrected for braille subcell space (`cols*2` x `rows*4`).
12//! 4. Viewport remap to subcell coordinates; `depth = v'.z` (smaller = nearer).
13
14use core::cmp::Ordering;
15
16use serde::{Deserialize, Serialize};
17
18use super::{Face, Node3, Strut, Vertex3};
19
20/// Near-plane epsilon: a vertex at/behind the camera (`z' <= NEAR_EPS`)
21/// makes its whole primitive rejected rather than risking a near-zero or
22/// negative perspective divide (Power-of-10 rule 4; `tui-3d/src/clip.rs`).
23pub const NEAR_EPS: f64 = 1e-6;
24
25/// Camera model: rotate about Y then X, camera distance, vertical FOV
26/// (degrees) — mirrors the deck's `cam.ry`/`cam.rx`.
27#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
28pub struct Camera {
29 pub ry: f64,
30 pub rx: f64,
31 pub dist: f64,
32 pub fov: f64,
33}
34
35/// A vertex projected to subcell screen space; `depth` is camera-space z
36/// after rotation+translation (before the perspective divide), smaller =
37/// nearer. `scale` is the local perspective magnification in target units
38/// per world unit at this vertex's depth — the Rust analogue of the deck's
39/// `proj()` returning `s = fov/z3` alongside `x`/`y` (`topology-deck.html
40/// :273-277`), which every disc the deck draws uses for its radius
41/// (`2.1*p.s/300`, `:308`; `2.6*top.s/300`, `:325`; `2.4*p.s/300`, `:357`;
42/// `√(c+v)*.62*top.s/300`, `:412`). Measured on the **vertical** axis
43/// (`d sy / d world-y`), which is the isotropic one in braille subcell
44/// space (a 2x4 subcell of a 1:2 terminal cell is square).
45#[derive(Debug, Clone, Copy, PartialEq)]
46pub struct Projected {
47 pub sx: f64,
48 pub sy: f64,
49 pub depth: f64,
50 pub scale: f64,
51}
52
53/// Rotate `v` about Y by `ry`, then about X by `rx`, then place the camera
54/// at `+dist` on z looking toward the origin (camera-space z decreases as
55/// world z increases — a vertex nearer the camera gets a smaller depth).
56/// Returns the camera-space vertex.
57fn to_camera_space(v: &Vertex3, cam: &Camera) -> Vertex3 {
58 // Rotate about Y.
59 let (sy, cy) = cam.ry.sin_cos();
60 let x1 = v.x * cy + v.z * sy;
61 let y1 = v.y;
62 let z1 = -v.x * sy + v.z * cy;
63
64 // Rotate about X.
65 let (sx, cx) = cam.rx.sin_cos();
66 let x2 = x1;
67 let y2 = y1 * cx - z1 * sx;
68 let z2 = y1 * sx + z1 * cx;
69
70 Vertex3 {
71 x: x2,
72 y: y2,
73 z: cam.dist - z2,
74 }
75}
76
77/// Project a single 3D point into subcell screen space under `cam`, for a
78/// `cols x rows` character grid (braille 2x4 subcells per cell). Returns
79/// `None` if the vertex is at/behind the near plane (`z' <= NEAR_EPS`).
80pub fn project(v: &Vertex3, cam: &Camera, cols: u16, rows: u16) -> Projected {
81 project_wh(v, cam, cols as f64 * 2.0, rows as f64 * 4.0)
82}
83
84/// Shared projection core (Task 14 DRY): rotation + perspective divide +
85/// viewport remap into a `width x height` target space. `project` (braille,
86/// `cols*2 x rows*4`) and `raster::png::render_pixels` (`width_px x
87/// height_px`) both call this — only the final NDC->viewport resolution
88/// differs (reuse ledger, Task 14 Step 1 note).
89pub(crate) fn project_wh(v: &Vertex3, cam: &Camera, width: f64, height: f64) -> Projected {
90 let cs = to_camera_space(v, cam);
91
92 // Guard the perspective divide: at/behind the near plane, clamp z' to
93 // NEAR_EPS so 1/z' never yields inf/NaN (primitive-level rejection is
94 // the caller's responsibility via `is_clipped`).
95 let z = if cs.z <= NEAR_EPS { NEAR_EPS } else { cs.z };
96
97 let f = 1.0 / (cam.fov * core::f64::consts::PI / 360.0).tan();
98 let aspect = height / width;
99 let ndc_x = f * cs.x / z * aspect;
100 let ndc_y = f * cs.y / z;
101
102 let sx = (ndc_x + 1.0) / 2.0 * (width - 1.0);
103 let sy = (1.0 - ndc_y) / 2.0 * (height - 1.0);
104
105 Projected {
106 sx,
107 sy,
108 depth: cs.z,
109 scale: f / z * (height - 1.0) / 2.0,
110 }
111}
112
113/// `true` if `v` is at/behind the near plane under `cam` (camera-space
114/// `z' <= NEAR_EPS`) — the whole primitive containing it must be rejected,
115/// never partially divided.
116fn is_clipped(v: &Vertex3, cam: &Camera) -> bool {
117 to_camera_space(v, cam).z <= NEAR_EPS
118}
119
120/// `true` if any vertex of the face is at/behind the near plane.
121pub fn face_is_clipped(face: &Face, cam: &Camera) -> bool {
122 face.verts.iter().any(|v| is_clipped(v, cam))
123}
124
125/// `true` if either endpoint of the strut is at/behind the near plane.
126pub fn strut_is_clipped(strut: &Strut, cam: &Camera) -> bool {
127 is_clipped(&strut.a, cam) || is_clipped(&strut.b, cam)
128}
129
130/// `true` if the node's center is at/behind the near plane (the whole disc
131/// is rejected — a node is a point primitive, never split).
132pub fn node_is_clipped(node: &Node3, cam: &Camera) -> bool {
133 is_clipped(&node.pos, cam)
134}
135
136fn nan_safe_cmp(a: f64, b: f64) -> Ordering {
137 a.partial_cmp(&b).unwrap_or(Ordering::Equal)
138}
139
140/// Stable painter's depth sort: farthest-first, keyed on each primitive's
141/// centroid camera-space depth. Stable so equal-depth primitives keep
142/// scene (insertion) order — no draw-order nondeterminism. Bounded: one
143/// pass over each finite slice.
144pub fn depth_sort(faces: &mut [Face], struts: &mut [Strut], cam: &Camera) {
145 faces.sort_by(|a, b| {
146 let da = face_centroid_depth(a, cam);
147 let db = face_centroid_depth(b, cam);
148 // Farthest first: descending depth.
149 nan_safe_cmp(db, da)
150 });
151 struts.sort_by(|a, b| {
152 let da = strut_centroid_depth(a, cam);
153 let db = strut_centroid_depth(b, cam);
154 nan_safe_cmp(db, da)
155 });
156}
157
158/// Stable painter's depth sort for node discs: farthest-first on each
159/// node's own center depth. Separate from [`depth_sort`] so the existing
160/// `(faces, struts)` signature (and its golden-pinned behaviour) is
161/// untouched; nodes are drawn after faces/struts in both raster tiers so
162/// an annotation dot at exactly equal depth wins its subcell. Bounded: one
163/// pass over a finite slice.
164pub fn depth_sort_nodes(nodes: &mut [Node3], cam: &Camera) {
165 nodes.sort_by(|a, b| {
166 let da = to_camera_space(&a.pos, cam).z;
167 let db = to_camera_space(&b.pos, cam).z;
168 nan_safe_cmp(db, da)
169 });
170}
171
172fn face_centroid_depth(face: &Face, cam: &Camera) -> f64 {
173 let cx = (face.verts[0].x + face.verts[1].x + face.verts[2].x) / 3.0;
174 let cy = (face.verts[0].y + face.verts[1].y + face.verts[2].y) / 3.0;
175 let cz = (face.verts[0].z + face.verts[1].z + face.verts[2].z) / 3.0;
176 to_camera_space(
177 &Vertex3 {
178 x: cx,
179 y: cy,
180 z: cz,
181 },
182 cam,
183 )
184 .z
185}
186
187fn strut_centroid_depth(strut: &Strut, cam: &Camera) -> f64 {
188 let cx = (strut.a.x + strut.b.x) / 2.0;
189 let cy = (strut.a.y + strut.b.y) / 2.0;
190 let cz = (strut.a.z + strut.b.z) / 2.0;
191 to_camera_space(
192 &Vertex3 {
193 x: cx,
194 y: cy,
195 z: cz,
196 },
197 cam,
198 )
199 .z
200}