Skip to main content

strata_render/
camera64.rs

1//! f64 camera and relative-to-centre (RTC) geometry path.
2//!
3//! The reference builds its render frame in f64 relative to the camera centre.
4//! At Earth radius (6 378 137 m) an f32 world coordinate steps by a metre, so
5//! sub-metre detail disappears before the vertex is even transformed. This
6//! module keeps the camera, the view transform, and the vertex subtraction in
7//! f64, and narrows only the final screen coordinates.
8//!
9//! Matrices are stored column-major, the same convention as
10//! [`crate::math3d::Mat4`], so an f64 frame and an f32 scene camera project a
11//! shared anchor to the same pixel.
12
13/// Double-precision 3D vector.
14#[derive(Debug, Clone, Copy, PartialEq, Default)]
15pub struct DVec3 {
16    pub x: f64,
17    pub y: f64,
18    pub z: f64,
19}
20
21impl DVec3 {
22    pub const ZERO: Self = Self {
23        x: 0.0,
24        y: 0.0,
25        z: 0.0,
26    };
27    pub const UP: Self = Self {
28        x: 0.0,
29        y: 1.0,
30        z: 0.0,
31    };
32
33    #[inline(always)]
34    pub const fn new(x: f64, y: f64, z: f64) -> Self {
35        Self { x, y, z }
36    }
37
38    #[inline(always)]
39    pub fn sub(self, other: Self) -> Self {
40        self - other
41    }
42
43    #[inline(always)]
44    pub fn add(self, other: Self) -> Self {
45        self + other
46    }
47}
48
49impl std::ops::Sub for DVec3 {
50    type Output = Self;
51    #[inline(always)]
52    fn sub(self, other: Self) -> Self {
53        Self::new(self.x - other.x, self.y - other.y, self.z - other.z)
54    }
55}
56
57impl std::ops::Add for DVec3 {
58    type Output = Self;
59    #[inline(always)]
60    fn add(self, other: Self) -> Self {
61        Self::new(self.x + other.x, self.y + other.y, self.z + other.z)
62    }
63}
64
65impl DVec3 {
66    #[inline(always)]
67    pub fn scale(self, k: f64) -> Self {
68        Self::new(self.x * k, self.y * k, self.z * k)
69    }
70
71    #[inline(always)]
72    pub fn dot(self, other: Self) -> f64 {
73        self.x * other.x + self.y * other.y + self.z * other.z
74    }
75
76    #[inline(always)]
77    pub fn cross(self, other: Self) -> Self {
78        Self::new(
79            self.y * other.z - self.z * other.y,
80            self.z * other.x - self.x * other.z,
81            self.x * other.y - self.y * other.x,
82        )
83    }
84
85    #[inline(always)]
86    pub fn length(self) -> f64 {
87        self.dot(self).sqrt()
88    }
89
90    #[inline(always)]
91    pub fn normalize(self) -> Self {
92        let len = self.length();
93        if len <= f64::EPSILON {
94            Self::ZERO
95        } else {
96            self.scale(1.0 / len)
97        }
98    }
99
100    #[inline(always)]
101    pub fn lerp(self, other: Self, t: f64) -> Self {
102        self.add(other.sub(self).scale(t))
103    }
104
105    #[inline(always)]
106    pub fn as_f32(self) -> [f32; 3] {
107        [self.x as f32, self.y as f32, self.z as f32]
108    }
109
110    /// Splits double-precision components into high and low single-precision floats (Float-Float / Double-Single split).
111    #[inline(always)]
112    pub fn split_high_low(self) -> ([f32; 3], [f32; 3]) {
113        let xh = self.x as f32;
114        let xl = (self.x - xh as f64) as f32;
115        let yh = self.y as f32;
116        let yl = (self.y - yh as f64) as f32;
117        let zh = self.z as f32;
118        let zl = (self.z - zh as f64) as f32;
119        ([xh, yh, zh], [xl, yl, zl])
120    }
121}
122
123/// Double-precision 4x4 matrix stored column-major.
124#[derive(Debug, Clone, Copy, PartialEq)]
125pub struct DMat4 {
126    /// Column-major elements: `m[col * 4 + row]`.
127    pub m: [f64; 16],
128}
129
130impl DMat4 {
131    pub const IDENTITY: Self = Self {
132        m: [
133            1.0, 0.0, 0.0, 0.0, //
134            0.0, 1.0, 0.0, 0.0, //
135            0.0, 0.0, 1.0, 0.0, //
136            0.0, 0.0, 0.0, 1.0,
137        ],
138    };
139
140    pub fn multiply(&self, rhs: &Self) -> Self {
141        let mut out = [0.0f64; 16];
142        for col in 0..4 {
143            for row in 0..4 {
144                let mut sum = 0.0;
145                for k in 0..4 {
146                    sum += self.m[k * 4 + row] * rhs.m[col * 4 + k];
147                }
148                out[col * 4 + row] = sum;
149            }
150        }
151        Self { m: out }
152    }
153
154    /// Transforms a point and returns clip space `[x, y, z, w]`.
155    pub fn transform_point4(&self, p: DVec3) -> [f64; 4] {
156        let m = &self.m;
157        [
158            m[0] * p.x + m[4] * p.y + m[8] * p.z + m[12],
159            m[1] * p.x + m[5] * p.y + m[9] * p.z + m[13],
160            m[2] * p.x + m[6] * p.y + m[10] * p.z + m[14],
161            m[3] * p.x + m[7] * p.y + m[11] * p.z + m[15],
162        ]
163    }
164
165    /// Right-handed look-at, matching `math3d::Mat4::look_at` exactly.
166    pub fn look_at(eye: DVec3, target: DVec3, up: DVec3) -> Self {
167        let f = target.sub(eye).normalize();
168        // A view direction parallel to the up hint has no unique right vector.
169        // Fall back to a non-parallel axis, as the f32 path does in practice for
170        // every camera it is handed.
171        let up = if f.cross(up).length() < 1e-6 {
172            if f.cross(DVec3::new(0.0, 0.0, 1.0)).length() > 1e-6 {
173                DVec3::new(0.0, 0.0, 1.0)
174            } else {
175                DVec3::new(0.0, 1.0, 0.0)
176            }
177        } else {
178            up
179        };
180        let s = f.cross(up).normalize();
181        let u = s.cross(f);
182
183        Self {
184            m: [
185                s.x,
186                u.x,
187                -f.x,
188                0.0,
189                s.y,
190                u.y,
191                -f.y,
192                0.0,
193                s.z,
194                u.z,
195                -f.z,
196                0.0,
197                -s.dot(eye),
198                -u.dot(eye),
199                f.dot(eye),
200                1.0,
201            ],
202        }
203    }
204
205    /// Right-handed look-at without translation, suitable for Relative-To-Eye (RTE) rendering.
206    pub fn view_rotation_only(eye: DVec3, target: DVec3, up: DVec3) -> Self {
207        Self::look_at(DVec3::ZERO, target.sub(eye), up)
208    }
209
210    /// Perspective projection with depth in `0..=1`, column-major.
211    ///
212    /// `math3d::Mat4` multiplies with `M * v` where the third and fourth rows
213    /// are swapped relative to the usual convention. The f32 3D path therefore
214    /// uses this layout, and the f64 path mirrors it so a point projects to the
215    /// same pixel through either matrix.
216    pub fn perspective(fov_y_rad: f64, aspect: f64, near: f64, far: f64) -> Self {
217        let f = 1.0 / (fov_y_rad * 0.5).tan();
218        let range_inv = 1.0 / (near - far);
219        Self {
220            m: [
221                f / aspect,
222                0.0,
223                0.0,
224                0.0,
225                0.0,
226                f,
227                0.0,
228                0.0,
229                0.0,
230                0.0,
231                -far * range_inv,
232                -1.0,
233                0.0,
234                0.0,
235                near * far * range_inv,
236                0.0,
237            ],
238        }
239    }
240}
241
242/// Earth's nominal radius in metres.
243pub const EARTH_RADIUS_M: f64 = 6_378_137.0;
244
245/// A camera whose position and basis stay in f64.
246#[derive(Debug, Clone, Copy, PartialEq)]
247pub struct Camera64 {
248    pub eye: DVec3,
249    pub target: DVec3,
250    pub up: DVec3,
251    /// Horizontal field of view in degrees, matching
252    /// `Camera3D::Perspective::fov_horizontal_deg`.
253    pub fov_horizontal_deg: f64,
254    pub near: f64,
255    pub far: f64,
256}
257
258impl Default for Camera64 {
259    fn default() -> Self {
260        Self {
261            eye: DVec3::new(0.0, 0.0, 10.0),
262            target: DVec3::ZERO,
263            up: DVec3::UP,
264            fov_horizontal_deg: 60.0,
265            near: 0.1,
266            far: 1.0e9,
267        }
268    }
269}
270
271/// A prepared frame: f64 projection plus the RTC origin subtracted from world
272/// positions before they are narrowed.
273#[derive(Debug, Clone, Copy, PartialEq)]
274pub struct RenderFrame64 {
275    pub view_from_world: DMat4,
276    pub projection: DMat4,
277    /// World-space point treated as the origin of the local vertex stream.
278    pub rtc_origin: DVec3,
279    /// Viewport size in logical pixels.
280    pub width: f64,
281    pub height: f64,
282}
283
284/// A projected screen position in f64 logical pixels.
285#[derive(Debug, Clone, Copy, PartialEq)]
286pub struct ProjectedPoint64 {
287    pub x: f64,
288    pub y: f64,
289    /// Normalized device depth in `0..=1` for front-facing points.
290    pub depth: f64,
291    /// Clip-space w, positive in front of the camera.
292    pub w: f64,
293    /// True when the point is behind or on the near plane.
294    pub clipped: bool,
295}
296
297impl RenderFrame64 {
298    /// Prepares a frame. `rtc_origin` should be the camera target, a tile
299    /// centre, or another point inside the region being drawn; everything
300    /// nearby then stays small enough to survive f32 narrowing at the end.
301    pub fn new(camera: &Camera64, rtc_origin: DVec3, width: f64, height: f64) -> Self {
302        let aspect = if height.abs() > f64::EPSILON {
303            width / height
304        } else {
305            1.0
306        };
307        // `Camera3D::Perspective` applies its field of view on the horizontal
308        // axis, while the projection matrix takes a vertical one.
309        let fov_x = camera.fov_horizontal_deg.to_radians();
310        let fov_y = 2.0 * ((fov_x * 0.5).tan() / aspect).atan();
311        // Build the view around the RTC origin too. `project` subtracts that
312        // origin from each world point before applying this matrix, so the eye
313        // and target must be shifted by the same amount or the origin would
314        // not cancel.
315        Self {
316            view_from_world: DMat4::look_at(
317                camera.eye.sub(rtc_origin),
318                camera.target.sub(rtc_origin),
319                camera.up,
320            ),
321            projection: DMat4::perspective(fov_y, aspect, camera.near, camera.far),
322            rtc_origin,
323            width,
324            height,
325        }
326    }
327
328    /// Builds a frame whose RTC origin is the camera target.
329    pub fn from_camera(camera: &Camera64, width: f64, height: f64) -> Self {
330        Self::new(camera, camera.target, width, height)
331    }
332
333    /// Computes the Relative-To-Eye (RTE) view-projection matrix without translation.
334    pub fn relative_to_eye_view_proj(camera: &Camera64, aspect: f64) -> DMat4 {
335        let fov_x = camera.fov_horizontal_deg.to_radians();
336        let fov_y = 2.0 * ((fov_x * 0.5).tan() / aspect).atan();
337        let view_rel = DMat4::view_rotation_only(camera.eye, camera.target, camera.up);
338        let proj = DMat4::perspective(fov_y, aspect, camera.near, camera.far);
339        proj.multiply(&view_rel)
340    }
341
342    /// Projects a world-space point. Subtraction from the RTC origin happens in
343    /// f64 before any narrowing.
344    ///
345    /// `math3d::Mat4` multiplies with `M * v` and stores the view translation
346    /// in the last row, so clip-space `w` comes out as `-z` for a point in
347    /// front of the camera. The sign is flipped here so `w` reads as positive
348    /// depth, which is what the clipping test and callers expect.
349    pub fn project(&self, world: DVec3) -> ProjectedPoint64 {
350        let local = world.sub(self.rtc_origin);
351        let view = self.view_from_world.transform_point4(local);
352        let clip = self
353            .projection
354            .transform_point4(DVec3::new(view[0], view[1], view[2]));
355        // With `math3d::Mat4`'s row layout a point in front of the camera
356        // yields a positive clip w, and negative eye-space z.
357        if clip[3] <= 1e-9 {
358            return ProjectedPoint64 {
359                x: 0.0,
360                y: 0.0,
361                depth: 1.0,
362                w: clip[3],
363                clipped: true,
364            };
365        }
366        let ndc_x = clip[0] / clip[3];
367        let ndc_y = clip[1] / clip[3];
368        let ndc_z = -clip[2] / clip[3];
369        ProjectedPoint64 {
370            x: (ndc_x + 1.0) * 0.5 * self.width,
371            y: (1.0 - ndc_y) * 0.5 * self.height,
372            depth: ndc_z,
373            w: clip[3],
374            clipped: false,
375        }
376    }
377
378    /// Projects and narrows to f32 screen coordinates, the hand-off point to
379    /// the f32 rasterizer.
380    pub fn project_f32(&self, world: DVec3) -> [f32; 2] {
381        let p = self.project(world);
382        [p.x as f32, p.y as f32]
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    #[test]
391    fn rtc_subtraction_keeps_sub_metre_detail_visible_at_earth_radius() {
392        let a = DVec3::new(EARTH_RADIUS_M, 0.0, 0.0);
393        let b = DVec3::new(EARTH_RADIUS_M + 1.0, 0.0, 0.0);
394
395        // The f32 path cannot hold sub-metre detail at this magnitude.
396        let a32 = a.as_f32();
397        let quarter = DVec3::new(EARTH_RADIUS_M + 0.25, 0.0, 0.0).as_f32();
398        assert_eq!(
399            a32, quarter,
400            "an f32 world coordinate at Earth radius must quantise sub-metre offsets away"
401        );
402
403        // The f64 RTC path keeps the pair distinct: the step at constant
404        // latitude runs along local east, so look down from above the polar
405        // axis to see it as a screen offset.
406        let camera = Camera64 {
407            eye: DVec3::new(0.0, 0.0, 20_000.0),
408            target: DVec3::ZERO,
409            up: DVec3::new(0.0, 1.0, 0.0),
410            fov_horizontal_deg: 120.0,
411            near: 1.0,
412            far: 1e9,
413        };
414        let frame = RenderFrame64::from_camera(&camera, 1440.0, 900.0);
415        let pa = frame.project(a);
416        let pb = frame.project(b);
417        assert!(
418            !pa.clipped && !pb.clipped,
419            "both points must be in front of the eye"
420        );
421        let separation = (pa.x - pb.x).hypot(pa.y - pb.y);
422        assert!(
423            separation > 0.0,
424            "f64 RTC must resolve the metre, got {pa:?} and {pb:?}"
425        );
426    }
427
428    #[test]
429    fn double_single_split_reconstructs_with_sub_millimeter_precision() {
430        let p = DVec3::new(EARTH_RADIUS_M + 123.456789, -234.567891, 56789.012345);
431        let (high, low) = p.split_high_low();
432
433        let rx = high[0] as f64 + low[0] as f64;
434        let ry = high[1] as f64 + low[1] as f64;
435        let rz = high[2] as f64 + low[2] as f64;
436
437        assert!(
438            (rx - p.x).abs() < 1e-6,
439            "x reconstruction error: {}",
440            (rx - p.x).abs()
441        );
442        assert!(
443            (ry - p.y).abs() < 1e-6,
444            "y reconstruction error: {}",
445            (ry - p.y).abs()
446        );
447        assert!(
448            (rz - p.z).abs() < 1e-6,
449            "z reconstruction error: {}",
450            (rz - p.z).abs()
451        );
452    }
453
454    #[test]
455    fn view_rotation_only_matches_look_at_on_relative_position() {
456        let eye = DVec3::new(EARTH_RADIUS_M + 10_000.0, 500.0, 200.0);
457        let target = DVec3::new(EARTH_RADIUS_M, 0.0, 0.0);
458        let up = DVec3::UP;
459
460        let look_at = DMat4::look_at(eye, target, up);
461        let rot_only = DMat4::view_rotation_only(eye, target, up);
462
463        let point = DVec3::new(EARTH_RADIUS_M + 50.0, 10.0, 5.0);
464        let res_look_at = look_at.transform_point4(point);
465
466        let rel = point.sub(eye);
467        let res_rot_only = rot_only.transform_point4(rel);
468
469        for i in 0..4 {
470            assert!(
471                (res_look_at[i] - res_rot_only[i]).abs() < 1e-6,
472                "mismatch at coordinate {}: {} vs {}",
473                i,
474                res_look_at[i],
475                res_rot_only[i]
476            );
477        }
478    }
479}