Skip to main content

sim_engine/
pseudo3d.rs

1use std::{error::Error, fmt};
2
3use crate::{LogicalScreenPosition, LogicalViewport, WorldLength};
4
5/// Finite vector or point in a right-handed 3D coordinate space.
6///
7/// Construction and arithmetic are fallible so finite inputs cannot silently
8/// produce NaN or infinity at the visual-state boundary.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Vec3 {
11    x: f32,
12    y: f32,
13    z: f32,
14}
15
16impl Vec3 {
17    /// Origin or zero-length vector.
18    pub const ZERO: Self = Self::new_unchecked(0.0, 0.0, 0.0);
19    /// Positive X unit axis.
20    pub const X: Self = Self::new_unchecked(1.0, 0.0, 0.0);
21    /// Positive Y unit axis.
22    pub const Y: Self = Self::new_unchecked(0.0, 1.0, 0.0);
23    /// Positive Z unit axis.
24    pub const Z: Self = Self::new_unchecked(0.0, 0.0, 1.0);
25
26    /// Builds a vector from finite caller-defined world components.
27    pub fn new(x: f32, y: f32, z: f32) -> Result<Self, Pseudo3dError> {
28        if x.is_finite() && y.is_finite() && z.is_finite() {
29            Ok(Self::new_unchecked(x, y, z))
30        } else {
31            Err(Pseudo3dError::NonFiniteVector { x, y, z })
32        }
33    }
34
35    pub(crate) const fn new_unchecked(x: f32, y: f32, z: f32) -> Self {
36        Self { x, y, z }
37    }
38
39    fn from_f64(x: f64, y: f64, z: f64) -> Result<Self, Pseudo3dError> {
40        if x.is_finite()
41            && y.is_finite()
42            && z.is_finite()
43            && x.abs() <= f32::MAX as f64
44            && y.abs() <= f32::MAX as f64
45            && z.abs() <= f32::MAX as f64
46        {
47            Ok(Self::new_unchecked(x as f32, y as f32, z as f32))
48        } else {
49            Err(Pseudo3dError::ArithmeticOverflow)
50        }
51    }
52
53    /// Returns the X component in caller-defined world units.
54    pub const fn x(self) -> f32 {
55        self.x
56    }
57
58    /// Returns the Y component in caller-defined world units.
59    pub const fn y(self) -> f32 {
60        self.y
61    }
62
63    /// Returns the Z component in caller-defined world units.
64    pub const fn z(self) -> f32 {
65        self.z
66    }
67
68    /// Adds two vectors while rejecting a finite-input overflow.
69    pub fn checked_add(self, other: Self) -> Result<Self, Pseudo3dError> {
70        Self::from_f64(
71            self.x as f64 + other.x as f64,
72            self.y as f64 + other.y as f64,
73            self.z as f64 + other.z as f64,
74        )
75    }
76
77    /// Subtracts two vectors while rejecting a finite-input overflow.
78    pub fn checked_sub(self, other: Self) -> Result<Self, Pseudo3dError> {
79        Self::from_f64(
80            self.x as f64 - other.x as f64,
81            self.y as f64 - other.y as f64,
82            self.z as f64 - other.z as f64,
83        )
84    }
85
86    /// Multiplies every component by a finite scalar.
87    pub fn checked_scale(self, scale: f32) -> Result<Self, Pseudo3dError> {
88        if !scale.is_finite() {
89            return Err(Pseudo3dError::NonFiniteScalar { value: scale });
90        }
91        Self::from_f64(
92            self.x as f64 * scale as f64,
93            self.y as f64 * scale as f64,
94            self.z as f64 * scale as f64,
95        )
96    }
97
98    /// Computes a dot product using wider intermediates and rejects an f32 overflow.
99    pub fn checked_dot(self, other: Self) -> Result<f32, Pseudo3dError> {
100        f64_to_f32(
101            self.x as f64 * other.x as f64
102                + self.y as f64 * other.y as f64
103                + self.z as f64 * other.z as f64,
104        )
105    }
106
107    /// Computes a cross product using wider intermediates.
108    pub fn checked_cross(self, other: Self) -> Result<Self, Pseudo3dError> {
109        Self::from_f64(
110            self.y as f64 * other.z as f64 - self.z as f64 * other.y as f64,
111            self.z as f64 * other.x as f64 - self.x as f64 * other.z as f64,
112            self.x as f64 * other.y as f64 - self.y as f64 * other.x as f64,
113        )
114    }
115
116    /// Returns a unit vector without overflowing on large finite components.
117    pub fn normalized(self) -> Result<Self, Pseudo3dError> {
118        let length = length_f64(self);
119        if length == 0.0 {
120            return Err(Pseudo3dError::ZeroLengthVector);
121        }
122        Self::from_f64(
123            self.x as f64 / length,
124            self.y as f64 / length,
125            self.z as f64 / length,
126        )
127    }
128}
129
130/// Normalized 3D rotation applied in a right-handed coordinate system.
131#[derive(Debug, Clone, Copy, PartialEq)]
132pub struct Rotation3d {
133    x: f32,
134    y: f32,
135    z: f32,
136    w: f32,
137}
138
139impl Rotation3d {
140    /// Rotation that leaves vectors unchanged.
141    pub const IDENTITY: Self = Self {
142        x: 0.0,
143        y: 0.0,
144        z: 0.0,
145        w: 1.0,
146    };
147
148    /// Builds a rotation around a non-zero finite axis by radians.
149    pub fn from_axis_angle(axis: Vec3, radians: f32) -> Result<Self, Pseudo3dError> {
150        if !radians.is_finite() {
151            return Err(Pseudo3dError::NonFiniteAngle { radians });
152        }
153        let axis = axis.normalized()?;
154        let (sine, cosine) = (radians as f64 * 0.5).sin_cos();
155        Self::normalized_from_f64(
156            axis.x as f64 * sine,
157            axis.y as f64 * sine,
158            axis.z as f64 * sine,
159            cosine,
160        )
161    }
162
163    /// Builds a rotation that applies X, then Y, then Z rotations in radians.
164    pub fn from_euler_xyz(x: f32, y: f32, z: f32) -> Result<Self, Pseudo3dError> {
165        let x_rotation = Self::from_axis_angle(Vec3::X, x)?;
166        let y_rotation = Self::from_axis_angle(Vec3::Y, y)?;
167        let z_rotation = Self::from_axis_angle(Vec3::Z, z)?;
168        x_rotation.then(y_rotation)?.then(z_rotation)
169    }
170
171    /// Composes rotations so `self` is applied first and `next` second.
172    pub fn then(self, next: Self) -> Result<Self, Pseudo3dError> {
173        let left = next;
174        let right = self;
175        Self::normalized_from_f64(
176            left.w as f64 * right.x as f64
177                + left.x as f64 * right.w as f64
178                + left.y as f64 * right.z as f64
179                - left.z as f64 * right.y as f64,
180            left.w as f64 * right.y as f64 - left.x as f64 * right.z as f64
181                + left.y as f64 * right.w as f64
182                + left.z as f64 * right.x as f64,
183            left.w as f64 * right.z as f64 + left.x as f64 * right.y as f64
184                - left.y as f64 * right.x as f64
185                + left.z as f64 * right.w as f64,
186            left.w as f64 * right.w as f64
187                - left.x as f64 * right.x as f64
188                - left.y as f64 * right.y as f64
189                - left.z as f64 * right.z as f64,
190        )
191    }
192
193    /// Rotates a finite vector and rejects arithmetic overflow.
194    pub fn rotate(self, vector: Vec3) -> Result<Vec3, Pseudo3dError> {
195        let qx = self.x as f64;
196        let qy = self.y as f64;
197        let qz = self.z as f64;
198        let qw = self.w as f64;
199        let vx = vector.x as f64;
200        let vy = vector.y as f64;
201        let vz = vector.z as f64;
202
203        let tx = 2.0 * (qy * vz - qz * vy);
204        let ty = 2.0 * (qz * vx - qx * vz);
205        let tz = 2.0 * (qx * vy - qy * vx);
206        Vec3::from_f64(
207            vx + qw * tx + (qy * tz - qz * ty),
208            vy + qw * ty + (qz * tx - qx * tz),
209            vz + qw * tz + (qx * ty - qy * tx),
210        )
211    }
212
213    fn normalized_from_f64(x: f64, y: f64, z: f64, w: f64) -> Result<Self, Pseudo3dError> {
214        let length = (x * x + y * y + z * z + w * w).sqrt();
215        if !length.is_finite() || length == 0.0 {
216            return Err(Pseudo3dError::ArithmeticOverflow);
217        }
218        let x = f64_to_f32(x / length)?;
219        let y = f64_to_f32(y / length)?;
220        let z = f64_to_f32(z / length)?;
221        let w = f64_to_f32(w / length)?;
222        Ok(Self { x, y, z, w })
223    }
224}
225
226/// Model transform with translation, rotation, and positive per-axis scale.
227#[derive(Debug, Clone, Copy, PartialEq)]
228pub struct Transform3d {
229    translation: Vec3,
230    rotation: Rotation3d,
231    scale: Vec3,
232}
233
234impl Transform3d {
235    /// Transform that leaves model-space points unchanged.
236    pub const IDENTITY: Self = Self {
237        translation: Vec3::ZERO,
238        rotation: Rotation3d::IDENTITY,
239        scale: Vec3::new_unchecked(1.0, 1.0, 1.0),
240    };
241
242    /// Builds a model transform. Every scale component must be positive.
243    pub fn new(
244        translation: Vec3,
245        rotation: Rotation3d,
246        scale: Vec3,
247    ) -> Result<Self, Pseudo3dError> {
248        if scale.x <= 0.0 || scale.y <= 0.0 || scale.z <= 0.0 {
249            return Err(Pseudo3dError::InvalidScale { scale });
250        }
251        Ok(Self {
252            translation,
253            rotation,
254            scale,
255        })
256    }
257
258    /// Builds a transform with the same positive finite scale on every axis.
259    pub fn from_rotation_scale(rotation: Rotation3d, scale: f32) -> Result<Self, Pseudo3dError> {
260        let scale = Vec3::new(scale, scale, scale)?;
261        Self::new(Vec3::ZERO, rotation, scale)
262    }
263
264    /// Returns model translation in world units.
265    pub const fn translation(self) -> Vec3 {
266        self.translation
267    }
268
269    /// Returns model rotation.
270    pub const fn rotation(self) -> Rotation3d {
271        self.rotation
272    }
273
274    /// Returns positive per-axis model scale.
275    pub const fn scale(self) -> Vec3 {
276        self.scale
277    }
278
279    /// Applies scale, then rotation, then translation to a model-space point.
280    pub fn transform_point(self, point: Vec3) -> Result<Vec3, Pseudo3dError> {
281        let scaled = Vec3::from_f64(
282            point.x as f64 * self.scale.x as f64,
283            point.y as f64 * self.scale.y as f64,
284            point.z as f64 * self.scale.z as f64,
285        )?;
286        self.rotation.rotate(scaled)?.checked_add(self.translation)
287    }
288
289    #[cfg(feature = "wgpu")]
290    pub(crate) fn model_rows(self) -> Result<[[f32; 4]; 3], Pseudo3dError> {
291        let x = self.rotation.x as f64;
292        let y = self.rotation.y as f64;
293        let z = self.rotation.z as f64;
294        let w = self.rotation.w as f64;
295        let scale_x = self.scale.x as f64;
296        let scale_y = self.scale.y as f64;
297        let scale_z = self.scale.z as f64;
298        let rows = [
299            [
300                (1.0 - 2.0 * (y * y + z * z)) * scale_x,
301                (2.0 * (x * y - z * w)) * scale_y,
302                (2.0 * (x * z + y * w)) * scale_z,
303                self.translation.x as f64,
304            ],
305            [
306                (2.0 * (x * y + z * w)) * scale_x,
307                (1.0 - 2.0 * (x * x + z * z)) * scale_y,
308                (2.0 * (y * z - x * w)) * scale_z,
309                self.translation.y as f64,
310            ],
311            [
312                (2.0 * (x * z - y * w)) * scale_x,
313                (2.0 * (y * z + x * w)) * scale_y,
314                (1.0 - 2.0 * (x * x + y * y)) * scale_z,
315                self.translation.z as f64,
316            ],
317        ];
318        Ok([
319            f64_row_to_f32(rows[0])?,
320            f64_row_to_f32(rows[1])?,
321            f64_row_to_f32(rows[2])?,
322        ])
323    }
324}
325
326/// Perspective or orthographic camera projection with a finite depth range.
327#[derive(Debug, Clone, Copy, PartialEq)]
328pub struct Projection3d {
329    kind: Projection3dKind,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq)]
333enum Projection3dKind {
334    Perspective {
335        vertical_fov_radians: f32,
336        aspect_ratio: f32,
337        near: WorldLength,
338        far: WorldLength,
339    },
340    Orthographic {
341        vertical_span: WorldLength,
342        aspect_ratio: f32,
343        near: WorldLength,
344        far: WorldLength,
345    },
346}
347
348impl Projection3d {
349    /// Builds a perspective projection.
350    ///
351    /// The vertical field of view is in radians and must be in `0..PI`.
352    /// Aspect ratio and near distance must be positive; far must exceed near.
353    pub fn perspective(
354        vertical_fov_radians: f32,
355        aspect_ratio: f32,
356        near: WorldLength,
357        far: WorldLength,
358    ) -> Result<Self, Pseudo3dError> {
359        if !valid_projection_range(aspect_ratio, near.get(), far.get())
360            || !vertical_fov_radians.is_finite()
361            || vertical_fov_radians <= 0.0
362            || vertical_fov_radians >= std::f32::consts::PI
363            || !(vertical_fov_radians as f64 * 0.5).tan().is_finite()
364        {
365            return Err(Pseudo3dError::InvalidProjection);
366        }
367        Ok(Self {
368            kind: Projection3dKind::Perspective {
369                vertical_fov_radians,
370                aspect_ratio,
371                near,
372                far,
373            },
374        })
375    }
376
377    /// Builds an orthographic projection from its vertical world-space span.
378    pub fn orthographic(
379        vertical_span: WorldLength,
380        aspect_ratio: f32,
381        near: WorldLength,
382        far: WorldLength,
383    ) -> Result<Self, Pseudo3dError> {
384        if !valid_projection_range(aspect_ratio, near.get(), far.get()) {
385            return Err(Pseudo3dError::InvalidProjection);
386        }
387        Ok(Self {
388            kind: Projection3dKind::Orthographic {
389                vertical_span,
390                aspect_ratio,
391                near,
392                far,
393            },
394        })
395    }
396
397    /// Returns the viewport width-to-height ratio.
398    pub const fn aspect_ratio(self) -> f32 {
399        match self.kind {
400            Projection3dKind::Perspective { aspect_ratio, .. }
401            | Projection3dKind::Orthographic { aspect_ratio, .. } => aspect_ratio,
402        }
403    }
404
405    /// Returns the nearest visible positive view-space depth.
406    pub const fn near(self) -> WorldLength {
407        match self.kind {
408            Projection3dKind::Perspective { near, .. }
409            | Projection3dKind::Orthographic { near, .. } => near,
410        }
411    }
412
413    /// Returns the farthest visible positive view-space depth.
414    pub const fn far(self) -> WorldLength {
415        match self.kind {
416            Projection3dKind::Perspective { far, .. }
417            | Projection3dKind::Orthographic { far, .. } => far,
418        }
419    }
420
421    /// Returns true for perspective and false for orthographic projection.
422    pub const fn is_perspective(self) -> bool {
423        matches!(self.kind, Projection3dKind::Perspective { .. })
424    }
425}
426
427/// Validated 3D view and projection used for stereometry rendering.
428#[derive(Debug, Clone, Copy, PartialEq)]
429pub struct Camera3d {
430    position: Vec3,
431    right: Vec3,
432    up: Vec3,
433    forward: Vec3,
434    projection: Projection3d,
435}
436
437impl Camera3d {
438    /// Builds a camera looking from `position` toward `target`.
439    ///
440    /// `up_hint` must not be zero or parallel to the view direction.
441    pub fn look_at(
442        position: Vec3,
443        target: Vec3,
444        up_hint: Vec3,
445        projection: Projection3d,
446    ) -> Result<Self, Pseudo3dError> {
447        let forward = target.checked_sub(position)?.normalized()?;
448        let right = cross_f64(forward, up_hint)
449            .and_then(normalize_f64)
450            .ok_or(Pseudo3dError::InvalidCameraBasis)?;
451        let up = cross_f64(right, forward)
452            .and_then(normalize_f64)
453            .ok_or(Pseudo3dError::InvalidCameraBasis)?;
454        Ok(Self {
455            position,
456            right,
457            up,
458            forward,
459            projection,
460        })
461    }
462
463    /// Returns camera position in world units.
464    pub const fn position(self) -> Vec3 {
465        self.position
466    }
467
468    /// Returns the current perspective or orthographic projection.
469    pub const fn projection(self) -> Projection3d {
470        self.projection
471    }
472
473    /// Projects a world point into logical screen coordinates.
474    ///
475    /// Points behind the camera return an error. Points outside the configured
476    /// frustum still return finite coordinates with `inside_view` set to false,
477    /// allowing a later mesh stage to clip segments and triangles explicitly.
478    pub fn project_world(
479        self,
480        point: Vec3,
481        viewport: LogicalViewport,
482    ) -> Result<ProjectedPoint3d, Pseudo3dError> {
483        let relative = subtract_f64(point, self.position);
484        let view_x = dot_f64_tuple(relative, self.right);
485        let view_y = dot_f64_tuple(relative, self.up);
486        let view_depth = dot_f64_tuple(relative, self.forward);
487        if !view_depth.is_finite() || view_depth <= 0.0 {
488            return Err(Pseudo3dError::PointBehindCamera);
489        }
490
491        let (ndc_x, ndc_y, normalized_depth, near, far) = match self.projection.kind {
492            Projection3dKind::Perspective {
493                vertical_fov_radians,
494                aspect_ratio,
495                near,
496                far,
497            } => {
498                let near_value = near.get();
499                let far_value = far.get();
500                let half_height = view_depth * (vertical_fov_radians as f64 * 0.5).tan();
501                (
502                    view_x / (half_height * aspect_ratio as f64),
503                    view_y / half_height,
504                    far_value as f64 / (far_value as f64 - near_value as f64)
505                        - (far_value as f64 * near_value as f64)
506                            / ((far_value as f64 - near_value as f64) * view_depth),
507                    near,
508                    far,
509                )
510            }
511            Projection3dKind::Orthographic {
512                vertical_span,
513                aspect_ratio,
514                near,
515                far,
516            } => {
517                let near_value = near.get();
518                let far_value = far.get();
519                let normalized_depth =
520                    (view_depth - near_value as f64) / (far_value as f64 - near_value as f64);
521                (
522                    view_x / (vertical_span.get() as f64 * aspect_ratio as f64 * 0.5),
523                    view_y / (vertical_span.get() as f64 * 0.5),
524                    normalized_depth,
525                    near,
526                    far,
527                )
528            }
529        };
530
531        let screen_x = (ndc_x * 0.5 + 0.5) * viewport.width() as f64;
532        let screen_y = (0.5 - ndc_y * 0.5) * viewport.height() as f64;
533        let screen_x = f64_to_f32(screen_x)?;
534        let screen_y = f64_to_f32(screen_y)?;
535        let view_depth_f32 = f64_to_f32(view_depth)?;
536        let normalized_depth_f32 = f64_to_f32(normalized_depth)?;
537        let inside_view = view_depth >= near.get() as f64
538            && view_depth <= far.get() as f64
539            && (-1.0..=1.0).contains(&ndc_x)
540            && (-1.0..=1.0).contains(&ndc_y);
541        Ok(ProjectedPoint3d {
542            logical_position: LogicalScreenPosition::new(screen_x, screen_y),
543            view_depth: view_depth_f32,
544            normalized_depth: normalized_depth_f32,
545            inside_view,
546        })
547    }
548
549    #[cfg(any(feature = "wgpu", test))]
550    pub(crate) fn world_to_clip_rows(self) -> Result<[[f32; 4]; 4], Pseudo3dError> {
551        let right_offset = -dot_f64(self.position, self.right);
552        let up_offset = -dot_f64(self.position, self.up);
553        let depth_offset = -dot_f64(self.position, self.forward);
554        let rows = match self.projection.kind {
555            Projection3dKind::Perspective {
556                vertical_fov_radians,
557                aspect_ratio,
558                near,
559                far,
560            } => {
561                let near = near.get() as f64;
562                let far = far.get() as f64;
563                let vertical_scale = (vertical_fov_radians as f64 * 0.5).tan();
564                let horizontal_scale = vertical_scale * aspect_ratio as f64;
565                let depth_scale = far / (far - near);
566                let depth_translation = -(far * near) / (far - near);
567                [
568                    camera_row(self.right, right_offset, 1.0 / horizontal_scale),
569                    camera_row(self.up, up_offset, 1.0 / vertical_scale),
570                    camera_row(
571                        self.forward,
572                        depth_offset + depth_translation / depth_scale,
573                        depth_scale,
574                    ),
575                    [
576                        self.forward.x as f64,
577                        self.forward.y as f64,
578                        self.forward.z as f64,
579                        depth_offset,
580                    ],
581                ]
582            }
583            Projection3dKind::Orthographic {
584                vertical_span,
585                aspect_ratio,
586                near,
587                far,
588            } => {
589                let near = near.get() as f64;
590                let far = far.get() as f64;
591                let vertical_span = vertical_span.get() as f64;
592                let depth_extent = far - near;
593                [
594                    camera_row(
595                        self.right,
596                        right_offset,
597                        2.0 / (vertical_span * aspect_ratio as f64),
598                    ),
599                    camera_row(self.up, up_offset, 2.0 / vertical_span),
600                    camera_row(self.forward, depth_offset - near, 1.0 / depth_extent),
601                    [0.0, 0.0, 0.0, 1.0],
602                ]
603            }
604        };
605        Ok([
606            f64_row_to_f32(rows[0])?,
607            f64_row_to_f32(rows[1])?,
608            f64_row_to_f32(rows[2])?,
609            f64_row_to_f32(rows[3])?,
610        ])
611    }
612}
613
614/// Result of projecting a 3D point into a logical viewport.
615#[derive(Debug, Clone, Copy, PartialEq)]
616pub struct ProjectedPoint3d {
617    logical_position: LogicalScreenPosition,
618    view_depth: f32,
619    normalized_depth: f32,
620    inside_view: bool,
621}
622
623impl ProjectedPoint3d {
624    /// Returns the point in logical screen pixels with a top-left origin.
625    pub const fn logical_position(self) -> LogicalScreenPosition {
626        self.logical_position
627    }
628
629    /// Returns positive distance along the camera forward axis in world units.
630    pub const fn view_depth(self) -> f32 {
631        self.view_depth
632    }
633
634    /// Returns the hardware depth value, normally in `0.0..=1.0`.
635    ///
636    /// Orthographic depth is linear. Perspective depth follows the nonlinear
637    /// projection used by the GPU depth attachment so CPU anchors and rendered
638    /// surfaces share one visibility coordinate.
639    pub const fn normalized_depth(self) -> f32 {
640        self.normalized_depth
641    }
642
643    /// Returns whether the point lies inside every configured clip boundary.
644    pub const fn inside_view(self) -> bool {
645        self.inside_view
646    }
647}
648
649/// Invalid pseudo-3D visual state or arithmetic.
650#[derive(Debug, Clone, Copy, PartialEq)]
651pub enum Pseudo3dError {
652    /// A 3D vector component was NaN or infinite.
653    NonFiniteVector {
654        /// Rejected X component.
655        x: f32,
656        /// Rejected Y component.
657        y: f32,
658        /// Rejected Z component.
659        z: f32,
660    },
661    /// A scalar input was NaN or infinite.
662    NonFiniteScalar {
663        /// Rejected scalar.
664        value: f32,
665    },
666    /// A rotation angle was NaN or infinite.
667    NonFiniteAngle {
668        /// Rejected angle in radians.
669        radians: f32,
670    },
671    /// A direction or rotation axis had zero length.
672    ZeroLengthVector,
673    /// Model scale contained a zero or negative component.
674    InvalidScale {
675        /// Rejected per-axis scale.
676        scale: Vec3,
677    },
678    /// Projection parameters did not define a finite usable frustum.
679    InvalidProjection,
680    /// View direction and up hint could not form an orthonormal camera basis.
681    InvalidCameraBasis,
682    /// A point lies on or behind the camera plane.
683    PointBehindCamera,
684    /// Finite inputs produced a value outside the representable f32 range.
685    ArithmeticOverflow,
686}
687
688impl fmt::Display for Pseudo3dError {
689    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
690        match self {
691            Self::NonFiniteVector { x, y, z } => {
692                write!(formatter, "3D vector must be finite, got ({x}, {y}, {z})")
693            }
694            Self::NonFiniteScalar { value } => {
695                write!(formatter, "3D scalar must be finite, got {value}")
696            }
697            Self::NonFiniteAngle { radians } => {
698                write!(formatter, "3D rotation angle must be finite, got {radians}")
699            }
700            Self::ZeroLengthVector => write!(formatter, "3D direction must have non-zero length"),
701            Self::InvalidScale { scale } => {
702                write!(formatter, "3D model scale must be positive, got {scale:?}")
703            }
704            Self::InvalidProjection => write!(formatter, "3D projection parameters are invalid"),
705            Self::InvalidCameraBasis => write!(formatter, "3D camera basis is degenerate"),
706            Self::PointBehindCamera => write!(formatter, "3D point is behind the camera"),
707            Self::ArithmeticOverflow => write!(formatter, "3D arithmetic overflowed f32 output"),
708        }
709    }
710}
711
712impl Error for Pseudo3dError {}
713
714fn valid_projection_range(aspect_ratio: f32, near: f32, far: f32) -> bool {
715    aspect_ratio.is_finite()
716        && aspect_ratio > 0.0
717        && near.is_finite()
718        && near > 0.0
719        && far.is_finite()
720        && far > near
721        && (far as f64 - near as f64) <= f32::MAX as f64
722}
723
724fn f64_to_f32(value: f64) -> Result<f32, Pseudo3dError> {
725    if value.is_finite() && value.abs() <= f32::MAX as f64 {
726        Ok(value as f32)
727    } else {
728        Err(Pseudo3dError::ArithmeticOverflow)
729    }
730}
731
732fn length_f64(vector: Vec3) -> f64 {
733    let x = vector.x as f64;
734    let y = vector.y as f64;
735    let z = vector.z as f64;
736    (x * x + y * y + z * z).sqrt()
737}
738
739fn subtract_f64(left: Vec3, right: Vec3) -> (f64, f64, f64) {
740    (
741        left.x as f64 - right.x as f64,
742        left.y as f64 - right.y as f64,
743        left.z as f64 - right.z as f64,
744    )
745}
746
747fn dot_f64_tuple(left: (f64, f64, f64), right: Vec3) -> f64 {
748    left.0 * right.x as f64 + left.1 * right.y as f64 + left.2 * right.z as f64
749}
750
751#[cfg(any(feature = "wgpu", test))]
752fn dot_f64(left: Vec3, right: Vec3) -> f64 {
753    left.x as f64 * right.x as f64 + left.y as f64 * right.y as f64 + left.z as f64 * right.z as f64
754}
755
756#[cfg(any(feature = "wgpu", test))]
757fn camera_row(axis: Vec3, offset: f64, scale: f64) -> [f64; 4] {
758    [
759        axis.x as f64 * scale,
760        axis.y as f64 * scale,
761        axis.z as f64 * scale,
762        offset * scale,
763    ]
764}
765
766#[cfg(any(feature = "wgpu", test))]
767fn f64_row_to_f32(row: [f64; 4]) -> Result<[f32; 4], Pseudo3dError> {
768    Ok([
769        f64_to_f32(row[0])?,
770        f64_to_f32(row[1])?,
771        f64_to_f32(row[2])?,
772        f64_to_f32(row[3])?,
773    ])
774}
775
776fn cross_f64(left: Vec3, right: Vec3) -> Option<(f64, f64, f64)> {
777    let result = (
778        left.y as f64 * right.z as f64 - left.z as f64 * right.y as f64,
779        left.z as f64 * right.x as f64 - left.x as f64 * right.z as f64,
780        left.x as f64 * right.y as f64 - left.y as f64 * right.x as f64,
781    );
782    result.0.is_finite().then_some(result)
783}
784
785fn normalize_f64(vector: (f64, f64, f64)) -> Option<Vec3> {
786    let length = (vector.0 * vector.0 + vector.1 * vector.1 + vector.2 * vector.2).sqrt();
787    if !length.is_finite() || length == 0.0 {
788        return None;
789    }
790    Vec3::from_f64(vector.0 / length, vector.1 / length, vector.2 / length).ok()
791}
792
793#[cfg(test)]
794mod tests {
795    use super::{Camera3d, Projection3d, Pseudo3dError, Rotation3d, Transform3d, Vec3};
796    use crate::{LogicalViewport, WorldLength};
797
798    fn vector(x: f32, y: f32, z: f32) -> Vec3 {
799        Vec3::new(x, y, z).unwrap()
800    }
801
802    fn world(value: f32) -> WorldLength {
803        WorldLength::new(value).unwrap()
804    }
805
806    fn close(actual: f32, expected: f32) {
807        assert!((actual - expected).abs() < 0.0001, "{actual} != {expected}");
808    }
809
810    #[test]
811    fn vector_normalization_preserves_extreme_finite_direction() {
812        let normalized = vector(f32::MAX, -f32::MAX, f32::MAX).normalized().unwrap();
813        let expected = 1.0 / 3.0_f32.sqrt();
814        close(normalized.x(), expected);
815        close(normalized.y(), -expected);
816        close(normalized.z(), expected);
817        assert_eq!(
818            Vec3::ZERO.normalized(),
819            Err(Pseudo3dError::ZeroLengthVector)
820        );
821    }
822
823    #[test]
824    fn rotation_composition_uses_documented_application_order() {
825        let quarter_turn = std::f32::consts::FRAC_PI_2;
826        let rotation = Rotation3d::from_euler_xyz(quarter_turn, quarter_turn, 0.0).unwrap();
827        let rotated = rotation.rotate(Vec3::Y).unwrap();
828        close(rotated.x(), 1.0);
829        close(rotated.y(), 0.0);
830        close(rotated.z(), 0.0);
831    }
832
833    #[test]
834    fn transform_rejects_invalid_scale_and_keeps_point_finite() {
835        let rotation = Rotation3d::from_axis_angle(Vec3::Z, std::f32::consts::FRAC_PI_2).unwrap();
836        assert!(matches!(
837            Transform3d::new(Vec3::ZERO, rotation, vector(1.0, 0.0, 1.0)),
838            Err(Pseudo3dError::InvalidScale { .. })
839        ));
840        let transform =
841            Transform3d::new(vector(3.0, 4.0, 5.0), rotation, vector(2.0, 2.0, 2.0)).unwrap();
842        let point = transform.transform_point(Vec3::X).unwrap();
843        close(point.x(), 3.0);
844        close(point.y(), 6.0);
845        close(point.z(), 5.0);
846    }
847
848    #[test]
849    fn perspective_camera_projects_center_and_reports_clip_membership() {
850        let viewport = LogicalViewport::new(800.0, 600.0).unwrap();
851        let projection = Projection3d::perspective(
852            std::f32::consts::FRAC_PI_2,
853            800.0 / 600.0,
854            world(0.1),
855            world(100.0),
856        )
857        .unwrap();
858        let camera =
859            Camera3d::look_at(vector(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Y, projection).unwrap();
860        let projected = camera.project_world(Vec3::ZERO, viewport).unwrap();
861        close(projected.logical_position().to_vec2().x(), 400.0);
862        close(projected.logical_position().to_vec2().y(), 300.0);
863        close(projected.view_depth(), 5.0);
864        assert!(projected.inside_view());
865
866        let outside = camera
867            .project_world(vector(50.0, 0.0, 0.0), viewport)
868            .unwrap();
869        assert!(!outside.inside_view());
870        assert_eq!(
871            camera.project_world(vector(0.0, 0.0, 6.0), viewport),
872            Err(Pseudo3dError::PointBehindCamera)
873        );
874    }
875
876    #[test]
877    fn orthographic_camera_preserves_size_across_depth() {
878        let viewport = LogicalViewport::new(800.0, 600.0).unwrap();
879        let projection =
880            Projection3d::orthographic(world(6.0), 800.0 / 600.0, world(0.1), world(100.0))
881                .unwrap();
882        let camera =
883            Camera3d::look_at(vector(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Y, projection).unwrap();
884        let near = camera
885            .project_world(vector(1.0, 0.0, 0.0), viewport)
886            .unwrap();
887        let far = camera
888            .project_world(vector(1.0, 0.0, -20.0), viewport)
889            .unwrap();
890        close(
891            near.logical_position().to_vec2().x(),
892            far.logical_position().to_vec2().x(),
893        );
894        assert!(near.normalized_depth() < far.normalized_depth());
895    }
896
897    #[test]
898    fn camera_and_projection_reject_degenerate_configuration() {
899        assert_eq!(
900            Projection3d::perspective(0.0, 1.0, world(0.1), world(10.0)),
901            Err(Pseudo3dError::InvalidProjection)
902        );
903        let projection = Projection3d::perspective(1.0, 1.0, world(0.1), world(10.0)).unwrap();
904        assert_eq!(
905            Camera3d::look_at(Vec3::ZERO, Vec3::ZERO, Vec3::Y, projection),
906            Err(Pseudo3dError::ZeroLengthVector)
907        );
908        assert_eq!(
909            Camera3d::look_at(vector(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Z, projection),
910            Err(Pseudo3dError::InvalidCameraBasis)
911        );
912    }
913
914    #[test]
915    fn gpu_clip_rows_match_public_camera_projection() {
916        let viewport = LogicalViewport::new(800.0, 600.0).unwrap();
917        for projection in [
918            Projection3d::perspective(1.1, 800.0 / 600.0, world(0.1), world(50.0)).unwrap(),
919            Projection3d::orthographic(world(7.0), 800.0 / 600.0, world(0.1), world(50.0)).unwrap(),
920        ] {
921            let camera = Camera3d::look_at(
922                vector(3.0, 2.0, 6.0),
923                vector(0.0, 0.5, 0.0),
924                Vec3::Y,
925                projection,
926            )
927            .unwrap();
928            let point = vector(0.5, 0.25, -1.0);
929            let projected = camera.project_world(point, viewport).unwrap();
930            let rows = camera.world_to_clip_rows().unwrap();
931            let homogeneous = [point.x(), point.y(), point.z(), 1.0];
932            let clip = rows.map(|row| {
933                row[0] * homogeneous[0] + row[1] * homogeneous[1] + row[2] * homogeneous[2] + row[3]
934            });
935            let ndc_x = clip[0] / clip[3];
936            let ndc_y = clip[1] / clip[3];
937            let screen_x = (ndc_x * 0.5 + 0.5) * viewport.width();
938            let screen_y = (0.5 - ndc_y * 0.5) * viewport.height();
939            close(screen_x, projected.logical_position().to_vec2().x());
940            close(screen_y, projected.logical_position().to_vec2().y());
941            close(clip[2] / clip[3], projected.normalized_depth());
942        }
943    }
944}