Skip to main content

sim_engine/
camera.rs

1use std::{error::Error, fmt};
2
3use crate::{
4    math::{Rect, Vec2},
5    tween::{Interpolate, Tween, TweenError},
6};
7
8const MIN_ZOOM: f32 = 0.0001;
9const MIN_PROJECTION_COSINE: f32 = 0.001;
10
11/// Point measured in logical screen pixels with a top-left origin.
12///
13/// Camera picking accepts this type so physical pointer coordinates require an
14/// explicit DPI conversion before they can enter camera math.
15#[derive(Debug, Clone, Copy, PartialEq, Default)]
16pub struct LogicalScreenPosition {
17    value: Vec2,
18}
19
20impl LogicalScreenPosition {
21    /// Builds a position from logical horizontal and vertical pixel coordinates.
22    pub const fn new(x: f32, y: f32) -> Self {
23        Self {
24            value: Vec2::new(x, y),
25        }
26    }
27
28    /// Builds a position from a vector whose units are explicitly logical pixels.
29    pub const fn from_vec2(value: Vec2) -> Self {
30        Self { value }
31    }
32
33    /// Returns the position as a logical-pixel vector.
34    pub const fn to_vec2(self) -> Vec2 {
35        self.value
36    }
37
38    /// Returns true when both coordinates are finite.
39    pub fn is_finite(self) -> bool {
40        self.value.is_finite()
41    }
42}
43
44/// Offset or size measured in logical screen pixels.
45///
46/// This is distinct from [`LogicalScreenPosition`] because vectors do not carry
47/// a screen origin. It prevents world-space and physical-pixel vectors from
48/// entering clipping and screen-effect APIs accidentally.
49#[derive(Debug, Clone, Copy, PartialEq, Default)]
50pub struct LogicalScreenVector {
51    value: Vec2,
52}
53
54impl LogicalScreenVector {
55    /// Builds a logical-pixel vector from horizontal and vertical components.
56    pub const fn new(x: f32, y: f32) -> Self {
57        Self {
58            value: Vec2::new(x, y),
59        }
60    }
61
62    /// Explicitly labels an existing vector as logical screen pixels.
63    pub const fn from_vec2(value: Vec2) -> Self {
64        Self { value }
65    }
66
67    /// Returns the underlying logical-pixel vector.
68    pub const fn to_vec2(self) -> Vec2 {
69        self.value
70    }
71
72    /// Returns true when both components are finite.
73    pub fn is_finite(self) -> bool {
74        self.value.is_finite()
75    }
76}
77
78/// Point measured in physical surface pixels with a top-left origin.
79///
80/// Window systems commonly report pointer positions in this space. A renderer
81/// converts them to [`LogicalScreenPosition`] using its validated DPI scale.
82#[derive(Debug, Clone, Copy, PartialEq, Default)]
83pub struct PhysicalScreenPosition {
84    value: Vec2,
85}
86
87impl PhysicalScreenPosition {
88    /// Builds a position from physical horizontal and vertical pixel coordinates.
89    pub const fn new(x: f32, y: f32) -> Self {
90        Self {
91            value: Vec2::new(x, y),
92        }
93    }
94
95    /// Builds a position from a vector whose units are explicitly physical pixels.
96    pub const fn from_vec2(value: Vec2) -> Self {
97        Self { value }
98    }
99
100    /// Returns the position as a physical-pixel vector.
101    pub const fn to_vec2(self) -> Vec2 {
102        self.value
103    }
104
105    /// Returns true when both coordinates are finite.
106    pub fn is_finite(self) -> bool {
107        self.value.is_finite()
108    }
109}
110
111/// Logical pixel dimensions of the viewport currently being drawn into.
112#[derive(Debug, Clone, Copy, PartialEq)]
113pub struct LogicalViewport {
114    width: f32,
115    height: f32,
116}
117
118impl LogicalViewport {
119    /// Builds a viewport from logical pixel dimensions.
120    ///
121    /// Both dimensions must be finite and strictly positive.
122    pub fn new(width: f32, height: f32) -> Result<Self, LogicalViewportError> {
123        if width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0 {
124            Ok(Self { width, height })
125        } else {
126            Err(LogicalViewportError::InvalidDimensions { width, height })
127        }
128    }
129
130    /// Returns viewport width in logical screen pixels.
131    pub fn width(self) -> f32 {
132        self.width
133    }
134
135    /// Returns viewport height in logical screen pixels.
136    pub fn height(self) -> f32 {
137        self.height
138    }
139
140    /// Returns the center point in logical screen pixel coordinates.
141    pub fn center(self) -> LogicalScreenPosition {
142        LogicalScreenPosition::new(self.width * 0.5, self.height * 0.5)
143    }
144
145    /// Returns viewport size in logical screen pixels.
146    pub fn size(self) -> Vec2 {
147        Vec2::new(self.width, self.height)
148    }
149}
150
151/// Invalid logical dimensions supplied to [`LogicalViewport`].
152#[derive(Debug, Clone, Copy, PartialEq)]
153pub enum LogicalViewportError {
154    /// Width and height must both be finite and strictly positive.
155    InvalidDimensions {
156        /// Rejected width in logical screen pixels.
157        width: f32,
158        /// Rejected height in logical screen pixels.
159        height: f32,
160    },
161}
162
163impl fmt::Display for LogicalViewportError {
164    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
165        match self {
166            Self::InvalidDimensions { width, height } => write!(
167                formatter,
168                "viewport dimensions must be finite and positive, got {width}x{height}"
169            ),
170        }
171    }
172}
173
174impl Error for LogicalViewportError {}
175
176/// Lightweight pseudo-depth projection for 2D scenes.
177///
178/// This is not a mesh renderer or z-buffer. It offsets 2D points using a scalar
179/// depth value so host applications can create camera-like depth transitions
180/// without leaving the 2D rendering model.
181#[derive(Debug, Clone, Copy, PartialEq)]
182pub struct Projection2d {
183    tilt: f32,
184    depth_scale: f32,
185}
186
187impl Projection2d {
188    /// Projection that leaves points in their original 2D plane.
189    pub const FLAT: Self = Self {
190        tilt: 0.0,
191        depth_scale: 1.0,
192    };
193
194    /// Builds a projection from tilt in radians and depth conversion scale.
195    ///
196    /// `depth_scale` is measured in world units per caller-defined depth unit.
197    /// Both values must be finite.
198    pub fn new(tilt: f32, depth_scale: f32) -> Result<Self, Projection2dError> {
199        if tilt.is_finite() && depth_scale.is_finite() {
200            Ok(Self { tilt, depth_scale })
201        } else {
202            Err(Projection2dError::NonFinite { tilt, depth_scale })
203        }
204    }
205
206    /// Returns projection tilt in radians.
207    pub fn tilt(self) -> f32 {
208        self.tilt
209    }
210
211    /// Returns depth conversion in world units per caller-defined depth unit.
212    pub fn depth_scale(self) -> f32 {
213        self.depth_scale
214    }
215
216    /// Projects a camera-relative world-space point with caller-provided pseudo-depth.
217    ///
218    /// This is the same relative-coordinate operation used by [`Camera2d`].
219    /// It is not an absolute-world transform and must not be applied before
220    /// [`Camera2d::world_to_screen`], which performs it itself.
221    pub fn project_relative(self, point: Vec2, depth: f32) -> Result<Vec2, Projection2dError> {
222        if !point.is_finite() || !depth.is_finite() {
223            return Err(Projection2dError::InvalidInput { point, depth });
224        }
225        let lifted = depth * self.depth_scale;
226        let projected = Vec2::new(
227            point.x + lifted * self.tilt.sin() * 0.5,
228            point.y * self.tilt.cos() + lifted * self.tilt.sin(),
229        );
230        if projected.is_finite() {
231            Ok(projected)
232        } else {
233            Err(Projection2dError::Overflow { point, depth })
234        }
235    }
236}
237
238/// Invalid pseudo-depth projection parameters.
239#[derive(Debug, Clone, Copy, PartialEq)]
240pub enum Projection2dError {
241    /// Tilt and depth scale must both be finite.
242    NonFinite {
243        /// Rejected projection tilt in radians.
244        tilt: f32,
245        /// Rejected world units per depth unit.
246        depth_scale: f32,
247    },
248    /// Relative world coordinates or depth are non-finite.
249    InvalidInput {
250        /// Rejected camera-relative world point.
251        point: Vec2,
252        /// Rejected caller-defined depth.
253        depth: f32,
254    },
255    /// Finite inputs overflowed while applying projection.
256    Overflow {
257        /// Camera-relative world point.
258        point: Vec2,
259        /// Caller-defined depth.
260        depth: f32,
261    },
262}
263
264impl fmt::Display for Projection2dError {
265    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
266        match self {
267            Self::NonFinite { tilt, depth_scale } => write!(
268                formatter,
269                "projection tilt and depth scale must be finite, got tilt {tilt} and scale {depth_scale}"
270            ),
271            Self::InvalidInput { point, depth } => write!(
272                formatter,
273                "projection point and depth must be finite, got {point:?} at depth {depth}"
274            ),
275            Self::Overflow { point, depth } => write!(
276                formatter,
277                "projection overflowed for {point:?} at depth {depth}"
278            ),
279        }
280    }
281}
282
283impl Error for Projection2dError {}
284
285/// 2D camera mapping world coordinates into logical screen pixels.
286///
287/// `center` and all input positions are in world units. `zoom` is logical screen
288/// pixels per world unit. `rotation` is in radians.
289#[derive(Debug, Clone, Copy, PartialEq)]
290pub struct Camera2d {
291    center: Vec2,
292    zoom: f32,
293    rotation: f32,
294    projection: Projection2d,
295}
296
297/// Invalid camera configuration or inverse projection request.
298#[derive(Debug, Clone, Copy, PartialEq)]
299pub enum Camera2dError {
300    /// Camera center must contain finite world coordinates.
301    InvalidCenter {
302        /// Rejected world-space center.
303        center: Vec2,
304    },
305    /// Zoom must be finite and strictly positive because it is logical pixels per world unit.
306    InvalidZoom {
307        /// Rejected zoom value.
308        zoom: f32,
309    },
310    /// Camera rotation must be finite.
311    InvalidRotation {
312        /// Rejected clockwise rotation in radians.
313        rotation: f32,
314    },
315    /// Screen coordinates and pseudo-depth used for picking must be finite.
316    InvalidPickingInput {
317        /// Rejected point in logical screen pixels.
318        screen: LogicalScreenPosition,
319        /// Rejected caller-defined pseudo-depth.
320        depth: f32,
321    },
322    /// The current projection collapses the requested picking plane.
323    SingularProjection {
324        /// Projection tilt in radians.
325        tilt: f32,
326    },
327    /// World coordinates or depth supplied for forward projection are non-finite.
328    InvalidProjectionInput {
329        /// Rejected world-space point.
330        world: Vec2,
331        /// Rejected caller-defined pseudo-depth.
332        depth: f32,
333    },
334    /// Finite forward-projection inputs overflowed logical screen coordinates.
335    ProjectionOverflow {
336        /// World-space point that could not be represented on screen.
337        world: Vec2,
338        /// Caller-defined pseudo-depth.
339        depth: f32,
340    },
341    /// World-space panning delta was non-finite or overflowed the center.
342    InvalidPan {
343        /// Rejected world-space delta.
344        delta: Vec2,
345    },
346    /// Cursor-centered zoom needs a finite, strictly positive multiplier.
347    InvalidZoomFactor {
348        /// Rejected multiplier.
349        factor: f32,
350    },
351    /// Bounds fitting requires finite, non-empty bounds and usable padding.
352    InvalidFitBounds {
353        /// Rejected world-space bounds.
354        bounds: Rect,
355        /// Rejected logical-pixel padding.
356        padding: f32,
357    },
358}
359
360impl fmt::Display for Camera2dError {
361    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
362        match self {
363            Self::InvalidCenter { center } => {
364                write!(formatter, "camera center must be finite, got {center:?}")
365            }
366            Self::InvalidZoom { zoom } => {
367                write!(
368                    formatter,
369                    "camera zoom must be finite and positive, got {zoom}"
370                )
371            }
372            Self::InvalidRotation { rotation } => {
373                write!(formatter, "camera rotation must be finite, got {rotation}")
374            }
375            Self::InvalidPickingInput { screen, depth } => write!(
376                formatter,
377                "screen coordinates and picking depth must be finite, got {screen:?} at depth {depth}"
378            ),
379            Self::SingularProjection { tilt } => {
380                write!(
381                    formatter,
382                    "projection tilt is singular for screen picking: {tilt}"
383                )
384            }
385            Self::InvalidProjectionInput { world, depth } => write!(
386                formatter,
387                "world coordinates and projection depth must be finite, got {world:?} at depth {depth}"
388            ),
389            Self::ProjectionOverflow { world, depth } => write!(
390                formatter,
391                "world-to-screen projection overflowed for {world:?} at depth {depth}"
392            ),
393            Self::InvalidPan { delta } => {
394                write!(
395                    formatter,
396                    "camera pan delta must be finite and keep the center finite, got {delta:?}"
397                )
398            }
399            Self::InvalidZoomFactor { factor } => {
400                write!(
401                    formatter,
402                    "camera zoom factor must be finite and positive, got {factor}"
403                )
404            }
405            Self::InvalidFitBounds { bounds, padding } => write!(
406                formatter,
407                "camera fit bounds must be finite and non-empty with usable padding, got {bounds:?} and padding {padding}"
408            ),
409        }
410    }
411}
412
413impl Error for Camera2dError {}
414
415impl Camera2d {
416    /// Smallest zoom accepted by camera constructors and setters.
417    pub const MIN_ZOOM: f32 = MIN_ZOOM;
418}
419
420impl Camera2d {
421    /// Builds a camera centered on a world-space point.
422    ///
423    /// `zoom` is logical screen pixels per world unit and must be finite and
424    /// positive. Invalid values return [`Camera2dError::InvalidZoom`] instead of
425    /// being silently clamped.
426    pub fn new(center: Vec2, zoom: f32) -> Result<Self, Camera2dError> {
427        validate_center(center)?;
428        validate_zoom(zoom)?;
429
430        Ok(Self {
431            center,
432            zoom,
433            rotation: 0.0,
434            projection: Projection2d::FLAT,
435        })
436    }
437
438    /// Returns the world-space point displayed at the viewport center.
439    pub fn center(self) -> Vec2 {
440        self.center
441    }
442
443    /// Replaces the world-space point displayed at the viewport center.
444    /// Invalid coordinates leave the current center unchanged.
445    pub fn set_center(&mut self, center: Vec2) -> Result<(), Camera2dError> {
446        validate_center(center)?;
447        self.center = center;
448        Ok(())
449    }
450
451    /// Returns camera scale in logical screen pixels per world unit.
452    pub fn zoom(self) -> f32 {
453        self.zoom
454    }
455
456    /// Replaces camera scale in logical screen pixels per world unit.
457    ///
458    /// Invalid values return [`Camera2dError::InvalidZoom`] and leave the
459    /// current zoom unchanged.
460    pub fn set_zoom(&mut self, zoom: f32) -> Result<(), Camera2dError> {
461        validate_zoom(zoom)?;
462        self.zoom = zoom;
463        Ok(())
464    }
465
466    /// Returns clockwise screen rotation in radians.
467    pub fn rotation(self) -> f32 {
468        self.rotation
469    }
470
471    /// Replaces clockwise screen rotation in radians.
472    /// Non-finite values leave the current rotation unchanged.
473    pub fn set_rotation(&mut self, rotation: f32) -> Result<(), Camera2dError> {
474        validate_rotation(rotation)?;
475        self.rotation = rotation;
476        Ok(())
477    }
478
479    /// Returns the pseudo-depth projection applied to camera-relative coordinates.
480    pub fn projection(self) -> Projection2d {
481        self.projection
482    }
483
484    /// Replaces the pseudo-depth projection applied to camera-relative coordinates.
485    pub fn set_projection(&mut self, projection: Projection2d) {
486        self.projection = projection;
487    }
488
489    /// Pans the displayed world center by a finite world-space delta.
490    pub fn pan_by(&mut self, delta: Vec2) -> Result<(), Camera2dError> {
491        let center = self.center + delta;
492        if !delta.is_finite() || !center.is_finite() {
493            return Err(Camera2dError::InvalidPan { delta });
494        }
495        self.center = center;
496        Ok(())
497    }
498
499    /// Changes zoom while keeping the depth-zero world point under `anchor` fixed.
500    ///
501    /// `anchor` is measured in logical pixels. The operation is atomic: invalid
502    /// factors, singular projections, or overflows leave this camera unchanged.
503    pub fn zoom_about_screen(
504        &mut self,
505        factor: f32,
506        anchor: LogicalScreenPosition,
507        viewport: LogicalViewport,
508    ) -> Result<(), Camera2dError> {
509        if !factor.is_finite() || factor <= 0.0 {
510            return Err(Camera2dError::InvalidZoomFactor { factor });
511        }
512        let world_before = self.screen_to_world(anchor, viewport)?;
513        let zoom = self.zoom * factor;
514        validate_zoom(zoom)?;
515        let mut candidate = *self;
516        candidate.zoom = zoom;
517        let world_after = candidate.screen_to_world(anchor, viewport)?;
518        let center = candidate.center + (world_before - world_after);
519        validate_center(center)?;
520        candidate.center = center;
521        *self = candidate;
522        Ok(())
523    }
524
525    /// Centers and zooms the camera so finite non-empty world bounds fit a viewport.
526    ///
527    /// `padding` is measured in logical pixels on every edge. The extent
528    /// calculation accounts for this camera's rotation and depth-zero tilt.
529    pub fn fit_to_bounds(
530        &mut self,
531        bounds: Rect,
532        padding: f32,
533        viewport: LogicalViewport,
534    ) -> Result<(), Camera2dError> {
535        let bounds = bounds.normalized();
536        if !bounds.min.is_finite()
537            || !bounds.max.is_finite()
538            || !padding.is_finite()
539            || padding < 0.0
540        {
541            return Err(Camera2dError::InvalidFitBounds { bounds, padding });
542        }
543        let available = viewport.size() - Vec2::splat(padding * 2.0);
544        let size = bounds.size();
545        let projection_y = self.projection.tilt.cos().abs();
546        let cos = self.rotation.cos().abs();
547        let sin = self.rotation.sin().abs();
548        let screen_extent = Vec2::new(
549            cos * size.x + sin * size.y * projection_y,
550            sin * size.x + cos * size.y * projection_y,
551        );
552        if size.x <= 0.0
553            || size.y <= 0.0
554            || available.x <= 0.0
555            || available.y <= 0.0
556            || screen_extent.x <= 0.0
557            || screen_extent.y <= 0.0
558            || !screen_extent.is_finite()
559        {
560            return Err(Camera2dError::InvalidFitBounds { bounds, padding });
561        }
562        let zoom = (available.x / screen_extent.x).min(available.y / screen_extent.y);
563        validate_zoom(zoom)?;
564        let center = bounds.center();
565        validate_center(center)?;
566        self.center = center;
567        self.zoom = zoom;
568        Ok(())
569    }
570
571    /// Converts a world-space point into logical screen pixel coordinates.
572    ///
573    /// Returns an error if finite values overflow during the transform.
574    pub fn world_to_screen(
575        self,
576        world: Vec2,
577        viewport: LogicalViewport,
578    ) -> Result<LogicalScreenPosition, Camera2dError> {
579        self.projected_world_to_screen(world, 0.0, viewport)
580    }
581
582    /// Converts a world-space point and pseudo-depth into logical screen pixels.
583    pub fn projected_world_to_screen(
584        self,
585        world: Vec2,
586        depth: f32,
587        viewport: LogicalViewport,
588    ) -> Result<LogicalScreenPosition, Camera2dError> {
589        if !world.is_finite() || !depth.is_finite() {
590            return Err(Camera2dError::InvalidProjectionInput { world, depth });
591        }
592        let relative = world - self.center;
593        let translated = self
594            .projection
595            .project_relative(relative, depth)
596            .map_err(|_| Camera2dError::ProjectionOverflow { world, depth })?;
597        let cos = self.rotation.cos();
598        let sin = self.rotation.sin();
599        let rotated = Vec2::new(
600            translated.x * cos - translated.y * sin,
601            translated.x * sin + translated.y * cos,
602        );
603
604        let screen = LogicalScreenPosition::new(
605            viewport.width() * 0.5 + rotated.x * self.zoom,
606            viewport.height() * 0.5 - rotated.y * self.zoom,
607        );
608        if screen.is_finite() {
609            Ok(screen)
610        } else {
611            Err(Camera2dError::ProjectionOverflow { world, depth })
612        }
613    }
614
615    /// Converts logical screen pixel coordinates back into world coordinates.
616    ///
617    /// This is equivalent to [`Camera2d::screen_to_world_at_depth`] with
618    /// `depth = 0.0`.
619    pub fn screen_to_world(
620        self,
621        screen: LogicalScreenPosition,
622        viewport: LogicalViewport,
623    ) -> Result<Vec2, Camera2dError> {
624        self.screen_to_world_at_depth(screen, 0.0, viewport)
625    }
626
627    /// Converts logical screen pixel coordinates into world coordinates on a pseudo-depth plane.
628    ///
629    /// `depth` must match the same caller-defined scalar depth passed to
630    /// [`Camera2d::projected_world_to_screen`]. If projection tilt is close to
631    /// 90 degrees, the inverse mapping is singular and returns
632    /// [`Camera2dError::SingularProjection`].
633    pub fn screen_to_world_at_depth(
634        self,
635        screen: LogicalScreenPosition,
636        depth: f32,
637        viewport: LogicalViewport,
638    ) -> Result<Vec2, Camera2dError> {
639        if !screen.is_finite() || !depth.is_finite() {
640            return Err(Camera2dError::InvalidPickingInput { screen, depth });
641        }
642
643        let screen = screen.to_vec2();
644
645        let translated = Vec2::new(
646            (screen.x - viewport.width() * 0.5) / self.zoom,
647            -(screen.y - viewport.height() * 0.5) / self.zoom,
648        );
649        let cos = self.rotation.cos();
650        let sin = self.rotation.sin();
651        let projected_delta = Vec2::new(
652            translated.x * cos + translated.y * sin,
653            -translated.x * sin + translated.y * cos,
654        );
655        let projection_cos = self.projection.tilt.cos();
656
657        if projection_cos.abs() < MIN_PROJECTION_COSINE {
658            return Err(Camera2dError::SingularProjection {
659                tilt: self.projection.tilt,
660            });
661        }
662
663        let lifted = depth * self.projection.depth_scale;
664        let relative = Vec2::new(
665            projected_delta.x - lifted * self.projection.tilt.sin() * 0.5,
666            (projected_delta.y - lifted * self.projection.tilt.sin()) / projection_cos,
667        );
668        let world = self.center + relative;
669        if world.is_finite() {
670            Ok(world)
671        } else {
672            Err(Camera2dError::InvalidPickingInput {
673                screen: LogicalScreenPosition::from_vec2(screen),
674                depth,
675            })
676        }
677    }
678
679    /// Creates a tween initialized with this camera state.
680    pub fn tween(self) -> Result<Tween<Self>, TweenError> {
681        Tween::new(self)
682    }
683}
684
685impl Default for Camera2d {
686    fn default() -> Self {
687        Self {
688            center: Vec2::ZERO,
689            zoom: 1.0,
690            rotation: 0.0,
691            projection: Projection2d::FLAT,
692        }
693    }
694}
695
696impl Interpolate for Projection2d {
697    fn interpolate(self, end: Self, amount: f32) -> Self {
698        let amount = finite_interpolation_amount(amount);
699        let tilt = self.tilt.interpolate(end.tilt, amount);
700        let depth_scale = self.depth_scale.interpolate(end.depth_scale, amount);
701        Self {
702            tilt: finite_or(tilt, self.tilt),
703            depth_scale: finite_or(depth_scale, self.depth_scale),
704        }
705    }
706
707    fn is_valid_interpolation_value(self) -> bool {
708        self.tilt.is_finite() && self.depth_scale.is_finite()
709    }
710}
711
712impl Interpolate for Camera2d {
713    fn interpolate(self, end: Self, amount: f32) -> Self {
714        let amount = finite_interpolation_amount(amount);
715        let center = self.center.interpolate(end.center, amount);
716        let zoom = self.zoom.interpolate(end.zoom, amount);
717        let rotation = self.rotation.interpolate(end.rotation, amount);
718        Self {
719            center: if center.is_finite() {
720                center
721            } else {
722                self.center
723            },
724            zoom: if zoom.is_finite() {
725                zoom.max(MIN_ZOOM)
726            } else {
727                self.zoom
728            },
729            rotation: finite_or(rotation, self.rotation),
730            projection: self.projection.interpolate(end.projection, amount),
731        }
732    }
733
734    fn is_valid_interpolation_value(self) -> bool {
735        self.center.is_finite()
736            && self.zoom.is_finite()
737            && self.zoom >= MIN_ZOOM
738            && self.rotation.is_finite()
739            && self.projection.is_valid_interpolation_value()
740    }
741}
742
743fn validate_zoom(zoom: f32) -> Result<(), Camera2dError> {
744    if zoom.is_finite() && zoom >= MIN_ZOOM {
745        Ok(())
746    } else {
747        Err(Camera2dError::InvalidZoom { zoom })
748    }
749}
750
751fn validate_center(center: Vec2) -> Result<(), Camera2dError> {
752    if center.is_finite() {
753        Ok(())
754    } else {
755        Err(Camera2dError::InvalidCenter { center })
756    }
757}
758
759fn validate_rotation(rotation: f32) -> Result<(), Camera2dError> {
760    if rotation.is_finite() {
761        Ok(())
762    } else {
763        Err(Camera2dError::InvalidRotation { rotation })
764    }
765}
766
767fn finite_interpolation_amount(amount: f32) -> f32 {
768    if amount.is_finite() { amount } else { 0.0 }
769}
770
771fn finite_or(value: f32, fallback: f32) -> f32 {
772    if value.is_finite() { value } else { fallback }
773}
774
775#[cfg(test)]
776mod tests {
777    use crate::{
778        Camera2d, Camera2dError, Interpolate, LogicalScreenPosition, LogicalViewport,
779        LogicalViewportError, PhysicalScreenPosition, Projection2d, Projection2dError, Vec2,
780    };
781
782    fn test_viewport() -> LogicalViewport {
783        let Ok(viewport) = LogicalViewport::new(1280.0, 720.0) else {
784            panic!("test viewport should be valid");
785        };
786        viewport
787    }
788
789    fn test_projection(tilt: f32, depth_scale: f32) -> Projection2d {
790        let Ok(projection) = Projection2d::new(tilt, depth_scale) else {
791            panic!("test projection should be valid");
792        };
793        projection
794    }
795
796    #[test]
797    fn camera_roundtrip_without_projection() {
798        let Ok(mut camera) = Camera2d::new(Vec2::new(20.0, -10.0), 2.5) else {
799            panic!("test camera should be valid");
800        };
801        assert!(camera.set_rotation(0.35).is_ok());
802
803        let viewport = test_viewport();
804        let world = Vec2::new(44.0, 12.0);
805
806        let screen = camera.world_to_screen(world, viewport).unwrap();
807        let Ok(roundtrip) = camera.screen_to_world(screen, viewport) else {
808            panic!("flat projection should be invertible");
809        };
810
811        assert!((roundtrip.x - world.x).abs() < 0.001);
812        assert!((roundtrip.y - world.y).abs() < 0.001);
813    }
814
815    #[test]
816    fn camera_roundtrip_at_depth() {
817        let Ok(mut camera) = Camera2d::new(Vec2::new(20.0, -10.0), 2.5) else {
818            panic!("test camera should be valid");
819        };
820        assert!(camera.set_rotation(0.35).is_ok());
821        camera.set_projection(test_projection(0.5, 1.25));
822
823        let viewport = test_viewport();
824        let world = Vec2::new(44.0, 12.0);
825        let depth = 9.0;
826
827        let screen = camera
828            .projected_world_to_screen(world, depth, viewport)
829            .unwrap();
830        let Ok(roundtrip) = camera.screen_to_world_at_depth(screen, depth, viewport) else {
831            panic!("projection should be invertible at this tilt");
832        };
833
834        assert!((roundtrip.x - world.x).abs() < 0.001);
835        assert!((roundtrip.y - world.y).abs() < 0.001);
836    }
837
838    #[test]
839    fn camera_rejects_invalid_zoom() {
840        let result = Camera2d::new(Vec2::ZERO, 0.0);
841
842        assert!(matches!(
843            result,
844            Err(Camera2dError::InvalidZoom { zoom }) if zoom == 0.0
845        ));
846    }
847
848    #[test]
849    fn projected_camera_center_stays_at_viewport_center() {
850        let center = Vec2::new(0.0, 100.0);
851        let Ok(mut camera) = Camera2d::new(center, 2.0) else {
852            panic!("test camera should be valid");
853        };
854        camera.set_projection(test_projection(std::f32::consts::FRAC_PI_3, 1.0));
855        assert!(camera.set_rotation(0.4).is_ok());
856        let viewport = test_viewport();
857
858        let screen = camera.world_to_screen(center, viewport).unwrap();
859
860        assert_eq!(screen, viewport.center());
861    }
862
863    #[test]
864    fn picking_requires_a_logical_screen_position_at_hidpi() {
865        let viewport = test_viewport();
866        let camera = Camera2d::default();
867        let physical_pointer = PhysicalScreenPosition::new(1_280.0, 720.0);
868        let logical_pointer = LogicalScreenPosition::from_vec2(physical_pointer.to_vec2() / 2.0);
869
870        let Ok(world) = camera.screen_to_world(logical_pointer, viewport) else {
871            panic!("logical center should be pickable");
872        };
873
874        assert_eq!(world, Vec2::ZERO);
875    }
876
877    #[test]
878    fn large_camera_center_uses_relative_projection_math() {
879        let center = Vec2::new(2.0e38, 0.0);
880        let world = Vec2::new(center.x + 1.0e33, 0.0);
881        let Ok(camera) = Camera2d::new(center, 2.0) else {
882            panic!("large finite camera should be valid");
883        };
884        let viewport = test_viewport();
885
886        let screen = camera.world_to_screen(world, viewport).unwrap();
887
888        assert!(screen.is_finite());
889        assert!(screen.to_vec2().x > viewport.center().to_vec2().x);
890    }
891
892    #[test]
893    fn forward_projection_reports_finite_overflow() {
894        let camera = Camera2d::new(Vec2::ZERO, f32::MAX).unwrap();
895        let viewport = test_viewport();
896
897        assert!(matches!(
898            camera.world_to_screen(Vec2::new(f32::MAX, 0.0), viewport),
899            Err(Camera2dError::ProjectionOverflow { .. })
900        ));
901    }
902
903    #[test]
904    fn pan_cursor_zoom_and_fit_preserve_coordinate_contracts() {
905        let viewport = test_viewport();
906        let mut camera = Camera2d::new(Vec2::new(5.0, -3.0), 2.0).unwrap();
907        camera.pan_by(Vec2::new(4.0, 7.0)).unwrap();
908        assert_eq!(camera.center(), Vec2::new(9.0, 4.0));
909
910        let anchor = LogicalScreenPosition::new(192.0, 531.0);
911        let world_before = camera.screen_to_world(anchor, viewport).unwrap();
912        camera.zoom_about_screen(1.75, anchor, viewport).unwrap();
913        let world_after = camera.screen_to_world(anchor, viewport).unwrap();
914        assert!((world_before.x - world_after.x).abs() < 0.0001);
915        assert!((world_before.y - world_after.y).abs() < 0.0001);
916
917        camera.set_rotation(0.35).unwrap();
918        camera.set_projection(test_projection(0.4, 1.0));
919        let bounds = crate::Rect::from_center_size(Vec2::new(30.0, -20.0), Vec2::new(80.0, 40.0));
920        camera.fit_to_bounds(bounds, 24.0, viewport).unwrap();
921        assert_eq!(camera.center(), bounds.center());
922        for corner in [bounds.min, bounds.max] {
923            let screen = camera.world_to_screen(corner, viewport).unwrap().to_vec2();
924            assert!(screen.x >= 24.0 && screen.x <= viewport.width() - 24.0);
925            assert!(screen.y >= 24.0 && screen.y <= viewport.height() - 24.0);
926        }
927    }
928
929    #[test]
930    fn camera_helpers_reject_invalid_inputs_without_mutation() {
931        let viewport = test_viewport();
932        let mut camera = Camera2d::default();
933        let before = camera;
934        assert!(matches!(
935            camera.pan_by(Vec2::new(f32::NAN, 0.0)),
936            Err(Camera2dError::InvalidPan { .. })
937        ));
938        assert_eq!(camera, before);
939        assert!(matches!(
940            camera.zoom_about_screen(0.0, viewport.center(), viewport),
941            Err(Camera2dError::InvalidZoomFactor { .. })
942        ));
943        assert_eq!(camera, before);
944        assert!(matches!(
945            camera.fit_to_bounds(
946                crate::Rect::from_center_size(Vec2::ZERO, Vec2::new(0.0, 1.0)),
947                0.0,
948                viewport
949            ),
950            Err(Camera2dError::InvalidFitBounds { .. })
951        ));
952        assert_eq!(camera, before);
953    }
954
955    #[test]
956    fn relative_projection_matches_camera_centered_pipeline() {
957        let center = Vec2::new(10.0, 100.0);
958        let mut camera = Camera2d::new(center, 2.0).unwrap();
959        let projection = test_projection(0.6, 1.25);
960        camera.set_projection(projection);
961        let viewport = test_viewport();
962
963        assert_eq!(
964            projection.project_relative(Vec2::ZERO, 0.0).unwrap(),
965            Vec2::ZERO
966        );
967        assert_eq!(
968            camera
969                .projected_world_to_screen(center, 0.0, viewport)
970                .unwrap(),
971            viewport.center()
972        );
973    }
974
975    #[test]
976    fn picking_rejects_non_finite_and_near_singular_inputs() {
977        let Ok(mut camera) = Camera2d::new(Vec2::ZERO, 1.0) else {
978            panic!("test camera should be valid");
979        };
980        let viewport = test_viewport();
981
982        assert!(matches!(
983            camera.screen_to_world(LogicalScreenPosition::new(f32::NAN, 0.0), viewport),
984            Err(Camera2dError::InvalidPickingInput { .. })
985        ));
986
987        camera.set_projection(test_projection(std::f32::consts::FRAC_PI_2 - 0.00001, 1.0));
988        assert!(matches!(
989            camera.screen_to_world(viewport.center(), viewport),
990            Err(Camera2dError::SingularProjection { .. })
991        ));
992    }
993
994    #[test]
995    fn camera_projection_and_viewport_reject_non_finite_configuration() {
996        assert!(matches!(
997            Camera2d::new(Vec2::new(f32::INFINITY, 0.0), 1.0),
998            Err(Camera2dError::InvalidCenter { .. })
999        ));
1000        assert!(matches!(
1001            Projection2d::new(f32::NAN, 1.0),
1002            Err(Projection2dError::NonFinite { .. })
1003        ));
1004        assert!(matches!(
1005            LogicalViewport::new(0.0, f32::INFINITY),
1006            Err(LogicalViewportError::InvalidDimensions { .. })
1007        ));
1008    }
1009
1010    #[test]
1011    fn camera_interpolation_preserves_finite_invariants() {
1012        let Ok(start) = Camera2d::new(Vec2::splat(f32::MAX), f32::MAX) else {
1013            panic!("finite extreme camera should be valid");
1014        };
1015        let Ok(end) = Camera2d::new(Vec2::splat(-f32::MAX), 1.0) else {
1016            panic!("finite extreme camera should be valid");
1017        };
1018
1019        let interpolated = start.interpolate(end, 0.5);
1020
1021        assert!(interpolated.center().is_finite());
1022        assert!(interpolated.zoom().is_finite());
1023    }
1024}