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. Outside-frustum points whose
476    /// projection remains representable return finite coordinates with
477    /// `inside_view` set to false, allowing host-side classification without
478    /// losing the projected anchor; extreme finite inputs may instead return
479    /// [`Pseudo3dError::ArithmeticOverflow`]. In the v0.2 retained renderer,
480    /// explicit display edges are clipped while partially clipped surface
481    /// triangles are rejected fail-closed as unportable topology.
482    pub fn project_world(
483        self,
484        point: Vec3,
485        viewport: LogicalViewport,
486    ) -> Result<ProjectedPoint3d, Pseudo3dError> {
487        let relative = subtract_f64(point, self.position);
488        let view_x = dot_f64_tuple(relative, self.right);
489        let view_y = dot_f64_tuple(relative, self.up);
490        let view_depth = dot_f64_tuple(relative, self.forward);
491        if !view_depth.is_finite() || view_depth <= 0.0 {
492            return Err(Pseudo3dError::PointBehindCamera);
493        }
494
495        let (ndc_x, ndc_y, normalized_depth, near, far) = match self.projection.kind {
496            Projection3dKind::Perspective {
497                vertical_fov_radians,
498                aspect_ratio,
499                near,
500                far,
501            } => {
502                let near_value = near.get();
503                let far_value = far.get();
504                let half_height = view_depth * (vertical_fov_radians as f64 * 0.5).tan();
505                (
506                    view_x / (half_height * aspect_ratio as f64),
507                    view_y / half_height,
508                    far_value as f64 / (far_value as f64 - near_value as f64)
509                        - (far_value as f64 * near_value as f64)
510                            / ((far_value as f64 - near_value as f64) * view_depth),
511                    near,
512                    far,
513                )
514            }
515            Projection3dKind::Orthographic {
516                vertical_span,
517                aspect_ratio,
518                near,
519                far,
520            } => {
521                let near_value = near.get();
522                let far_value = far.get();
523                let normalized_depth =
524                    (view_depth - near_value as f64) / (far_value as f64 - near_value as f64);
525                (
526                    view_x / (vertical_span.get() as f64 * aspect_ratio as f64 * 0.5),
527                    view_y / (vertical_span.get() as f64 * 0.5),
528                    normalized_depth,
529                    near,
530                    far,
531                )
532            }
533        };
534
535        let screen_x = (ndc_x * 0.5 + 0.5) * viewport.width() as f64;
536        let screen_y = (0.5 - ndc_y * 0.5) * viewport.height() as f64;
537        let screen_x = f64_to_f32(screen_x)?;
538        let screen_y = f64_to_f32(screen_y)?;
539        let view_depth_f32 = f64_to_f32(view_depth)?;
540        let normalized_depth_f32 = f64_to_f32(normalized_depth)?;
541        let inside_view = view_depth >= near.get() as f64
542            && view_depth <= far.get() as f64
543            && (-1.0..=1.0).contains(&ndc_x)
544            && (-1.0..=1.0).contains(&ndc_y);
545        Ok(ProjectedPoint3d {
546            logical_position: LogicalScreenPosition::new(screen_x, screen_y),
547            view_depth: view_depth_f32,
548            normalized_depth: normalized_depth_f32,
549            inside_view,
550        })
551    }
552
553    #[cfg(any(feature = "wgpu", test))]
554    pub(crate) fn world_to_clip_rows(self) -> Result<[[f32; 4]; 4], Pseudo3dError> {
555        let right_offset = -dot_f64(self.position, self.right);
556        let up_offset = -dot_f64(self.position, self.up);
557        let depth_offset = -dot_f64(self.position, self.forward);
558        let rows = match self.projection.kind {
559            Projection3dKind::Perspective {
560                vertical_fov_radians,
561                aspect_ratio,
562                near,
563                far,
564            } => {
565                let near = near.get() as f64;
566                let far = far.get() as f64;
567                let vertical_scale = (vertical_fov_radians as f64 * 0.5).tan();
568                let horizontal_scale = vertical_scale * aspect_ratio as f64;
569                let depth_scale = far / (far - near);
570                let depth_translation = -(far * near) / (far - near);
571                [
572                    camera_row(self.right, right_offset, 1.0 / horizontal_scale),
573                    camera_row(self.up, up_offset, 1.0 / vertical_scale),
574                    camera_row(
575                        self.forward,
576                        depth_offset + depth_translation / depth_scale,
577                        depth_scale,
578                    ),
579                    [
580                        self.forward.x as f64,
581                        self.forward.y as f64,
582                        self.forward.z as f64,
583                        depth_offset,
584                    ],
585                ]
586            }
587            Projection3dKind::Orthographic {
588                vertical_span,
589                aspect_ratio,
590                near,
591                far,
592            } => {
593                let near = near.get() as f64;
594                let far = far.get() as f64;
595                let vertical_span = vertical_span.get() as f64;
596                let depth_extent = far - near;
597                [
598                    camera_row(
599                        self.right,
600                        right_offset,
601                        2.0 / (vertical_span * aspect_ratio as f64),
602                    ),
603                    camera_row(self.up, up_offset, 2.0 / vertical_span),
604                    camera_row(self.forward, depth_offset - near, 1.0 / depth_extent),
605                    [0.0, 0.0, 0.0, 1.0],
606                ]
607            }
608        };
609        Ok([
610            f64_row_to_f32(rows[0])?,
611            f64_row_to_f32(rows[1])?,
612            f64_row_to_f32(rows[2])?,
613            f64_row_to_f32(rows[3])?,
614        ])
615    }
616}
617
618/// Result of projecting a 3D point into a logical viewport.
619#[derive(Debug, Clone, Copy, PartialEq)]
620pub struct ProjectedPoint3d {
621    logical_position: LogicalScreenPosition,
622    view_depth: f32,
623    normalized_depth: f32,
624    inside_view: bool,
625}
626
627impl ProjectedPoint3d {
628    /// Returns the point in logical screen pixels with a top-left origin.
629    pub const fn logical_position(self) -> LogicalScreenPosition {
630        self.logical_position
631    }
632
633    /// Returns positive distance along the camera forward axis in world units.
634    pub const fn view_depth(self) -> f32 {
635        self.view_depth
636    }
637
638    /// Returns the hardware depth value, normally in `0.0..=1.0`.
639    ///
640    /// Orthographic depth is linear. Perspective depth follows the nonlinear
641    /// projection used by the GPU depth attachment so CPU anchors and rendered
642    /// surfaces share one visibility coordinate.
643    pub const fn normalized_depth(self) -> f32 {
644        self.normalized_depth
645    }
646
647    /// Returns whether the point lies inside every configured clip boundary.
648    pub const fn inside_view(self) -> bool {
649        self.inside_view
650    }
651}
652
653/// Invalid pseudo-3D visual state or arithmetic.
654#[derive(Debug, Clone, Copy, PartialEq)]
655pub enum Pseudo3dError {
656    /// A 3D vector component was NaN or infinite.
657    NonFiniteVector {
658        /// Rejected X component.
659        x: f32,
660        /// Rejected Y component.
661        y: f32,
662        /// Rejected Z component.
663        z: f32,
664    },
665    /// A scalar input was NaN or infinite.
666    NonFiniteScalar {
667        /// Rejected scalar.
668        value: f32,
669    },
670    /// A rotation angle was NaN or infinite.
671    NonFiniteAngle {
672        /// Rejected angle in radians.
673        radians: f32,
674    },
675    /// A direction or rotation axis had zero length.
676    ZeroLengthVector,
677    /// Model scale contained a zero or negative component.
678    InvalidScale {
679        /// Rejected per-axis scale.
680        scale: Vec3,
681    },
682    /// Projection parameters did not define a finite usable frustum.
683    InvalidProjection,
684    /// View direction and up hint could not form an orthonormal camera basis.
685    InvalidCameraBasis,
686    /// A point lies on or behind the camera plane.
687    PointBehindCamera,
688    /// Finite inputs produced a value outside the representable f32 range.
689    ArithmeticOverflow,
690}
691
692impl fmt::Display for Pseudo3dError {
693    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
694        match self {
695            Self::NonFiniteVector { x, y, z } => {
696                write!(formatter, "3D vector must be finite, got ({x}, {y}, {z})")
697            }
698            Self::NonFiniteScalar { value } => {
699                write!(formatter, "3D scalar must be finite, got {value}")
700            }
701            Self::NonFiniteAngle { radians } => {
702                write!(formatter, "3D rotation angle must be finite, got {radians}")
703            }
704            Self::ZeroLengthVector => write!(formatter, "3D direction must have non-zero length"),
705            Self::InvalidScale { scale } => {
706                write!(formatter, "3D model scale must be positive, got {scale:?}")
707            }
708            Self::InvalidProjection => write!(formatter, "3D projection parameters are invalid"),
709            Self::InvalidCameraBasis => write!(formatter, "3D camera basis is degenerate"),
710            Self::PointBehindCamera => write!(formatter, "3D point is behind the camera"),
711            Self::ArithmeticOverflow => write!(formatter, "3D arithmetic overflowed f32 output"),
712        }
713    }
714}
715
716impl Error for Pseudo3dError {}
717
718fn valid_projection_range(aspect_ratio: f32, near: f32, far: f32) -> bool {
719    aspect_ratio.is_finite()
720        && aspect_ratio > 0.0
721        && near.is_finite()
722        && near > 0.0
723        && far.is_finite()
724        && far > near
725        && (far as f64 - near as f64) <= f32::MAX as f64
726}
727
728fn f64_to_f32(value: f64) -> Result<f32, Pseudo3dError> {
729    if value.is_finite() && value.abs() <= f32::MAX as f64 {
730        Ok(value as f32)
731    } else {
732        Err(Pseudo3dError::ArithmeticOverflow)
733    }
734}
735
736fn length_f64(vector: Vec3) -> f64 {
737    let x = vector.x as f64;
738    let y = vector.y as f64;
739    let z = vector.z as f64;
740    (x * x + y * y + z * z).sqrt()
741}
742
743fn subtract_f64(left: Vec3, right: Vec3) -> (f64, f64, f64) {
744    (
745        left.x as f64 - right.x as f64,
746        left.y as f64 - right.y as f64,
747        left.z as f64 - right.z as f64,
748    )
749}
750
751fn dot_f64_tuple(left: (f64, f64, f64), right: Vec3) -> f64 {
752    left.0 * right.x as f64 + left.1 * right.y as f64 + left.2 * right.z as f64
753}
754
755#[cfg(any(feature = "wgpu", test))]
756fn dot_f64(left: Vec3, right: Vec3) -> f64 {
757    left.x as f64 * right.x as f64 + left.y as f64 * right.y as f64 + left.z as f64 * right.z as f64
758}
759
760#[cfg(any(feature = "wgpu", test))]
761fn camera_row(axis: Vec3, offset: f64, scale: f64) -> [f64; 4] {
762    [
763        axis.x as f64 * scale,
764        axis.y as f64 * scale,
765        axis.z as f64 * scale,
766        offset * scale,
767    ]
768}
769
770#[cfg(any(feature = "wgpu", test))]
771fn f64_row_to_f32(row: [f64; 4]) -> Result<[f32; 4], Pseudo3dError> {
772    Ok([
773        f64_to_f32(row[0])?,
774        f64_to_f32(row[1])?,
775        f64_to_f32(row[2])?,
776        f64_to_f32(row[3])?,
777    ])
778}
779
780fn cross_f64(left: Vec3, right: Vec3) -> Option<(f64, f64, f64)> {
781    let result = (
782        left.y as f64 * right.z as f64 - left.z as f64 * right.y as f64,
783        left.z as f64 * right.x as f64 - left.x as f64 * right.z as f64,
784        left.x as f64 * right.y as f64 - left.y as f64 * right.x as f64,
785    );
786    result.0.is_finite().then_some(result)
787}
788
789fn normalize_f64(vector: (f64, f64, f64)) -> Option<Vec3> {
790    let length = (vector.0 * vector.0 + vector.1 * vector.1 + vector.2 * vector.2).sqrt();
791    if !length.is_finite() || length == 0.0 {
792        return None;
793    }
794    Vec3::from_f64(vector.0 / length, vector.1 / length, vector.2 / length).ok()
795}
796
797#[cfg(test)]
798mod tests {
799    use super::{Camera3d, Projection3d, Pseudo3dError, Rotation3d, Transform3d, Vec3};
800    use crate::{LogicalViewport, WorldLength};
801
802    fn vector(x: f32, y: f32, z: f32) -> Vec3 {
803        Vec3::new(x, y, z).unwrap()
804    }
805
806    fn world(value: f32) -> WorldLength {
807        WorldLength::new(value).unwrap()
808    }
809
810    fn close(actual: f32, expected: f32) {
811        assert!((actual - expected).abs() < 0.0001, "{actual} != {expected}");
812    }
813
814    #[test]
815    fn vector_normalization_preserves_extreme_finite_direction() {
816        let normalized = vector(f32::MAX, -f32::MAX, f32::MAX).normalized().unwrap();
817        let expected = 1.0 / 3.0_f32.sqrt();
818        close(normalized.x(), expected);
819        close(normalized.y(), -expected);
820        close(normalized.z(), expected);
821        assert_eq!(
822            Vec3::ZERO.normalized(),
823            Err(Pseudo3dError::ZeroLengthVector)
824        );
825    }
826
827    #[test]
828    fn rotation_composition_uses_documented_application_order() {
829        let quarter_turn = std::f32::consts::FRAC_PI_2;
830        let rotation = Rotation3d::from_euler_xyz(quarter_turn, quarter_turn, 0.0).unwrap();
831        let rotated = rotation.rotate(Vec3::Y).unwrap();
832        close(rotated.x(), 1.0);
833        close(rotated.y(), 0.0);
834        close(rotated.z(), 0.0);
835    }
836
837    #[test]
838    fn transform_rejects_invalid_scale_and_keeps_point_finite() {
839        let rotation = Rotation3d::from_axis_angle(Vec3::Z, std::f32::consts::FRAC_PI_2).unwrap();
840        assert!(matches!(
841            Transform3d::new(Vec3::ZERO, rotation, vector(1.0, 0.0, 1.0)),
842            Err(Pseudo3dError::InvalidScale { .. })
843        ));
844        let transform =
845            Transform3d::new(vector(3.0, 4.0, 5.0), rotation, vector(2.0, 2.0, 2.0)).unwrap();
846        let point = transform.transform_point(Vec3::X).unwrap();
847        close(point.x(), 3.0);
848        close(point.y(), 6.0);
849        close(point.z(), 5.0);
850    }
851
852    #[test]
853    fn perspective_camera_projects_center_and_reports_clip_membership() {
854        let viewport = LogicalViewport::new(800.0, 600.0).unwrap();
855        let projection = Projection3d::perspective(
856            std::f32::consts::FRAC_PI_2,
857            800.0 / 600.0,
858            world(0.1),
859            world(100.0),
860        )
861        .unwrap();
862        let camera =
863            Camera3d::look_at(vector(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Y, projection).unwrap();
864        let projected = camera.project_world(Vec3::ZERO, viewport).unwrap();
865        close(projected.logical_position().to_vec2().x(), 400.0);
866        close(projected.logical_position().to_vec2().y(), 300.0);
867        close(projected.view_depth(), 5.0);
868        assert!(projected.inside_view());
869
870        let outside = camera
871            .project_world(vector(50.0, 0.0, 0.0), viewport)
872            .unwrap();
873        assert!(!outside.inside_view());
874        assert_eq!(
875            camera.project_world(vector(0.0, 0.0, 6.0), viewport),
876            Err(Pseudo3dError::PointBehindCamera)
877        );
878    }
879
880    #[test]
881    fn perspective_camera_reports_unrepresentable_outside_projection() {
882        let camera = Camera3d::look_at(
883            Vec3::ZERO,
884            vector(0.0, 0.0, -1.0),
885            Vec3::Y,
886            Projection3d::perspective(std::f32::consts::FRAC_PI_2, 1.0, world(0.1), world(10.0))
887                .unwrap(),
888        )
889        .unwrap();
890        assert_eq!(
891            camera.project_world(
892                vector(f32::MAX, 0.0, -f32::MIN_POSITIVE),
893                LogicalViewport::new(100.0, 100.0).unwrap(),
894            ),
895            Err(Pseudo3dError::ArithmeticOverflow)
896        );
897    }
898
899    #[test]
900    fn orthographic_camera_preserves_size_across_depth() {
901        let viewport = LogicalViewport::new(800.0, 600.0).unwrap();
902        let projection =
903            Projection3d::orthographic(world(6.0), 800.0 / 600.0, world(0.1), world(100.0))
904                .unwrap();
905        let camera =
906            Camera3d::look_at(vector(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Y, projection).unwrap();
907        let near = camera
908            .project_world(vector(1.0, 0.0, 0.0), viewport)
909            .unwrap();
910        let far = camera
911            .project_world(vector(1.0, 0.0, -20.0), viewport)
912            .unwrap();
913        close(
914            near.logical_position().to_vec2().x(),
915            far.logical_position().to_vec2().x(),
916        );
917        assert!(near.normalized_depth() < far.normalized_depth());
918    }
919
920    #[test]
921    fn camera_and_projection_reject_degenerate_configuration() {
922        assert_eq!(
923            Projection3d::perspective(0.0, 1.0, world(0.1), world(10.0)),
924            Err(Pseudo3dError::InvalidProjection)
925        );
926        let projection = Projection3d::perspective(1.0, 1.0, world(0.1), world(10.0)).unwrap();
927        assert_eq!(
928            Camera3d::look_at(Vec3::ZERO, Vec3::ZERO, Vec3::Y, projection),
929            Err(Pseudo3dError::ZeroLengthVector)
930        );
931        assert_eq!(
932            Camera3d::look_at(vector(0.0, 0.0, 5.0), Vec3::ZERO, Vec3::Z, projection),
933            Err(Pseudo3dError::InvalidCameraBasis)
934        );
935    }
936
937    #[test]
938    fn gpu_clip_rows_match_public_camera_projection() {
939        let viewport = LogicalViewport::new(800.0, 600.0).unwrap();
940        for projection in [
941            Projection3d::perspective(1.1, 800.0 / 600.0, world(0.1), world(50.0)).unwrap(),
942            Projection3d::orthographic(world(7.0), 800.0 / 600.0, world(0.1), world(50.0)).unwrap(),
943        ] {
944            let camera = Camera3d::look_at(
945                vector(3.0, 2.0, 6.0),
946                vector(0.0, 0.5, 0.0),
947                Vec3::Y,
948                projection,
949            )
950            .unwrap();
951            let point = vector(0.5, 0.25, -1.0);
952            let projected = camera.project_world(point, viewport).unwrap();
953            let rows = camera.world_to_clip_rows().unwrap();
954            let homogeneous = [point.x(), point.y(), point.z(), 1.0];
955            let clip = rows.map(|row| {
956                row[0] * homogeneous[0] + row[1] * homogeneous[1] + row[2] * homogeneous[2] + row[3]
957            });
958            let ndc_x = clip[0] / clip[3];
959            let ndc_y = clip[1] / clip[3];
960            let screen_x = (ndc_x * 0.5 + 0.5) * viewport.width();
961            let screen_y = (0.5 - ndc_y * 0.5) * viewport.height();
962            close(screen_x, projected.logical_position().to_vec2().x());
963            close(screen_y, projected.logical_position().to_vec2().y());
964            close(clip[2] / clip[3], projected.normalized_depth());
965        }
966    }
967}