Skip to main content

sciart_core/
geom.rs

1//! Geometry helpers shared by generators (CORE-R16..R18, CORE-R45, CORE-R50, CORE-R60..R63).
2
3use std::f64::consts::{PI, TAU};
4
5use crate::trig::Trig;
6
7/// Terminal cells are ~2x taller than wide; scale x by this for round shapes.
8pub const ASPECT: f64 = 2.0;
9
10/// Point at angle `theta` (radians) on a circle of radius `r` rows around `(cx, cy)`,
11/// with x stretched by [`ASPECT`].
12pub fn polar(cx: f64, cy: f64, r: f64, theta: f64) -> (i32, i32) {
13    let x = cx + r * theta.cos_det() * ASPECT;
14    let y = cy + r * theta.sin_det();
15    (x.round() as i32, y.round() as i32)
16}
17
18/// `v` wrapped into `[0, max)`. `max` must be positive.
19pub fn wrap(v: f64, max: f64) -> f64 {
20    let w = v.rem_euclid(max);
21    // rem_euclid can round up to exactly `max` for tiny negative v.
22    if w >= max { 0.0 } else { w }
23}
24
25/// Angle `a` (radians) wrapped into `[−π, π)`, e.g. the signed turn from one heading to
26/// another, `wrap_angle(to − from)` (CORE-R61). Non-finite input gives NaN.
27#[inline]
28pub fn wrap_angle(a: f64) -> f64 {
29    wrap(a + PI, TAU) - PI
30}
31
32/// Plain 3-vectors as `[f64; 3]` (CORE-R60): the handful of operations the 3-D scenes
33/// need, so each scene does not grow its own `dot`/`cross`/`norm`.
34///
35/// Free functions on arrays rather than a newtype, so scene data (`Camera` points,
36/// orbital samples, model atoms) stays plain `[f64; 3]` and needs no conversions.
37/// Every function spells out the same component-wise arithmetic the scenes used, so
38/// swapping one in is bit-identical.
39pub mod v3 {
40    /// A 3-vector.
41    pub type V3 = [f64; 3];
42
43    /// `a + b`.
44    #[inline]
45    pub fn add(a: V3, b: V3) -> V3 {
46        [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
47    }
48
49    /// `a − b`.
50    #[inline]
51    pub fn sub(a: V3, b: V3) -> V3 {
52        [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
53    }
54
55    /// `a · k`.
56    #[inline]
57    pub fn scale(a: V3, k: f64) -> V3 {
58        [a[0] * k, a[1] * k, a[2] * k]
59    }
60
61    /// `k·a + b` (BLAS `axpy`).
62    #[inline]
63    pub fn axpy(k: f64, a: V3, b: V3) -> V3 {
64        [k * a[0] + b[0], k * a[1] + b[1], k * a[2] + b[2]]
65    }
66
67    /// The dot product `a · b`.
68    #[inline]
69    pub fn dot(a: V3, b: V3) -> f64 {
70        a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
71    }
72
73    /// The cross product `a × b` (right-handed).
74    #[inline]
75    pub fn cross(a: V3, b: V3) -> V3 {
76        [
77            a[1] * b[2] - a[2] * b[1],
78            a[2] * b[0] - a[0] * b[2],
79            a[0] * b[1] - a[1] * b[0],
80        ]
81    }
82
83    /// The Euclidean length `|a|`.
84    #[inline]
85    pub fn norm(a: V3) -> f64 {
86        dot(a, a).sqrt()
87    }
88
89    /// `a / |a|`; the zero vector gives NaNs (callers normalise non-degenerate
90    /// directions only).
91    #[inline]
92    pub fn unit(a: V3) -> V3 {
93        let n = norm(a);
94        a.map(|c| c / n)
95    }
96}
97
98/// A minimal 3-D view for scenes that spin a model in front of the viewer (CORE-R45).
99///
100/// World axes: x right, y up, z toward the viewer. The model is turned by `yaw` about
101/// y, then by `pitch` about x; the eye sits on the +z axis at `distance` (use
102/// `f64::INFINITY`, the default, for an orthographic view).
103#[derive(Debug, Clone, Copy, PartialEq)]
104pub struct Camera {
105    /// Rotation about the world y axis, radians.
106    pub yaw: f64,
107    /// Rotation about the x axis after the yaw, radians.
108    pub pitch: f64,
109    /// Eye distance from the origin in world units; `INFINITY` ⇒ orthographic.
110    pub distance: f64,
111}
112
113impl Default for Camera {
114    fn default() -> Self {
115        Self {
116            yaw: 0.0,
117            pitch: 0.0,
118            distance: f64::INFINITY,
119        }
120    }
121}
122
123impl Camera {
124    /// Project world point `p` onto the screen: `(x, y)` in cell units around
125    /// `centre` (x stretched by [`ASPECT`], y down) with `scale` rows per world unit,
126    /// plus the rotated depth `z` (larger = nearer, for painter's sorting and shading).
127    ///
128    /// `None` for non-finite input or output, and for points at or behind the eye
129    /// (`z ≥ distance − 1e-9`), so callers can `let Some(..) else { continue }`.
130    pub fn project(&self, p: [f64; 3], centre: (f64, f64), scale: f64) -> Option<(f64, f64, f64)> {
131        self.projector().project(p, centre, scale)
132    }
133
134    /// This view with its rotation's sines and cosines computed once (CORE-R50), for
135    /// projecting many points per frame without four transcendental calls each.
136    pub fn projector(&self) -> Projector {
137        let (sy, cy) = self.yaw.sin_cos_det();
138        let (sp, cp) = self.pitch.sin_cos_det();
139        Projector {
140            sy,
141            cy,
142            sp,
143            cp,
144            distance: self.distance,
145        }
146    }
147}
148
149/// A [`Camera`] with its rotation cached, from [`Camera::projector`] (CORE-R50).
150///
151/// [`Camera::project`] is implemented through this type, so the two are bit-identical.
152#[derive(Debug, Clone, Copy, PartialEq)]
153pub struct Projector {
154    sy: f64,
155    cy: f64,
156    sp: f64,
157    cp: f64,
158    distance: f64,
159}
160
161impl Projector {
162    /// `p` in camera space: turned by yaw about y, then by pitch about x. The result's
163    /// `z` is the depth that [`project`](Self::project) reports (larger = nearer).
164    #[inline]
165    pub fn rotate(&self, p: [f64; 3]) -> [f64; 3] {
166        let [x, y, z] = p;
167        // R_x(pitch) · R_y(yaw) · p; at yaw = π/2, +x lands on −z (away from the eye).
168        let (x1, z1) = (x * self.cy + z * self.sy, z * self.cy - x * self.sy);
169        let (y2, z2) = (y * self.cp - z1 * self.sp, y * self.sp + z1 * self.cp);
170        [x1, y2, z2]
171    }
172
173    /// The perspective factor `d / (d − depth)` that [`project`](Self::project) scales
174    /// a point at `depth` by: how much nearer things look bigger (CORE-R63). Exactly 1
175    /// for an orthographic view (`distance = ∞`), so a scene can size sprites by it
176    /// without keeping its own copy of the eye distance.
177    #[inline]
178    pub fn magnification(&self, depth: f64) -> f64 {
179        if self.distance.is_finite() {
180            self.distance / (self.distance - depth)
181        } else {
182            1.0
183        }
184    }
185
186    /// Same contract as [`Camera::project`] (CORE-R45).
187    #[inline]
188    pub fn project(&self, p: [f64; 3], centre: (f64, f64), scale: f64) -> Option<(f64, f64, f64)> {
189        let [x1, y2, z2] = self.rotate(p);
190        // An infinite `distance` passes (orthographic); a NaN on either side fails.
191        let in_front = z2 < self.distance - 1e-9;
192        if !in_front {
193            return None;
194        }
195        let k = if self.distance.is_finite() {
196            scale * self.distance / (self.distance - z2)
197        } else {
198            scale
199        };
200        let out = (centre.0 + x1 * k * ASPECT, centre.1 - y2 * k, z2);
201        (out.0.is_finite() && out.1.is_finite() && out.2.is_finite()).then_some(out)
202    }
203}
204
205/// Bresenham line from `(x0, y0)` to `(x1, y1)`, both endpoints inclusive.
206pub fn line(x0: i32, y0: i32, x1: i32, y1: i32) -> impl Iterator<Item = (i32, i32)> {
207    let dx = (x1 - x0).abs();
208    let dy = -(y1 - y0).abs();
209    let sx = if x0 < x1 { 1 } else { -1 };
210    let sy = if y0 < y1 { 1 } else { -1 };
211    let (mut x, mut y, mut err, mut done) = (x0, y0, dx + dy, false);
212    std::iter::from_fn(move || {
213        if done {
214            return None;
215        }
216        let p = (x, y);
217        if x == x1 && y == y1 {
218            done = true;
219        } else {
220            let e2 = 2 * err;
221            if e2 >= dy {
222                err += dy;
223                x += sx;
224            }
225            if e2 <= dx {
226                err += dx;
227                y += sy;
228            }
229        }
230        Some(p)
231    })
232}
233
234/// Walk the Bresenham line [`line`] from `(x0, y0)` to `(x1, y1)` as a stroke: `f(k, x,
235/// y, (dx, dy))` gets each cell's index `k` along the line and the step into it, so a
236/// scene can pick a glyph per step (CORE-R62). The first cell takes its outgoing step,
237/// and a lone cell `(0, 1)`, a step down a column. [`draw::step_glyph`] is the default
238/// glyph policy.
239///
240/// [`draw::step_glyph`]: crate::draw::step_glyph
241pub fn stroked_line(
242    x0: i32,
243    y0: i32,
244    x1: i32,
245    y1: i32,
246    mut f: impl FnMut(i32, i32, i32, (i32, i32)),
247) {
248    let mut cells = line(x0, y0, x1, y1).peekable();
249    let mut prev: Option<(i32, i32)> = None;
250    let mut k = 0;
251    while let Some((x, y)) = cells.next() {
252        let step = match (prev, cells.peek()) {
253            (Some((px, py)), _) => (x - px, y - py),
254            (None, Some(&(nx, ny))) => (nx - x, ny - y),
255            (None, None) => (0, 1),
256        };
257        f(k, x, y, step);
258        prev = Some((x, y));
259        k += 1;
260    }
261}