Skip to main content

sim_logic/rendering/
visual.rs

1//! Standard visual components for the first Sim;Logic slice.
2
3use bevy_ecs::prelude::{Component, Resource};
4use sim_engine::{
5    Camera2d, Color, DrawCommand, Interpolate, Layer, StrokeCap2d, StrokeStyle2d, Vec2,
6};
7use std::{error::Error, fmt};
8
9/// Interpolated world-space translation of a managed visual entity.
10///
11/// Fixed-update code changes the current translation through
12/// [`Transform2d::set_translation`] or [`Transform2d::translate_by`]. The
13/// runtime snapshots the previous value at a fixed-tick boundary. Render
14/// extraction reads both values but never writes the interpolated result back.
15/// FrameUpdate must treat this component as read-only: Sim;Logic rejects
16/// mutable component access when the FrameUpdate System is prepared.
17/// Standard world-space visual and collider components add a default transform
18/// at the world origin when their spawn bundle does not provide one.
19#[derive(Debug, Clone, Copy, PartialEq, Component)]
20pub struct Transform2d {
21    previous_translation: Vec2,
22    translation: Vec2,
23}
24
25impl Transform2d {
26    /// Creates a transform snapped to one finite world-space translation.
27    pub fn new(translation: Vec2) -> Result<Self, VisualValueError> {
28        validate_translation(translation)?;
29        Ok(Self {
30            previous_translation: translation,
31            translation,
32        })
33    }
34
35    /// Creates a transform snapped to the finite world-space coordinates `(x, y)`.
36    ///
37    /// This is exactly equivalent to `Transform2d::new(Vec2::new(x, y))`.
38    /// Either non-finite coordinate returns
39    /// [`VisualValueError::InvalidTranslation`].
40    #[inline]
41    pub fn from_xy(x: f32, y: f32) -> Result<Self, VisualValueError> {
42        Self::new(Vec2::new(x, y))
43    }
44
45    /// Returns the current canonical world-space translation.
46    pub const fn translation(&self) -> Vec2 {
47        self.translation
48    }
49
50    /// Returns the previous committed fixed-tick translation.
51    pub const fn previous_translation(&self) -> Vec2 {
52        self.previous_translation
53    }
54
55    /// Replaces the current translation after finite-value validation.
56    ///
57    /// The previous translation is retained for fixed-step interpolation. Use
58    /// [`Transform2d::teleport`] when the change must not be interpolated.
59    /// FrameUpdate Systems cannot request mutable access to this component in
60    /// the first-slice runner.
61    pub fn set_translation(&mut self, translation: Vec2) -> Result<(), VisualValueError> {
62        validate_translation(translation)?;
63        self.translation = translation;
64        Ok(())
65    }
66
67    /// Applies a finite world-space offset atomically.
68    ///
69    /// An invalid offset or arithmetic overflow leaves the transform unchanged.
70    /// FrameUpdate Systems cannot request mutable access to this component in
71    /// the first-slice runner.
72    pub fn translate_by(&mut self, delta: Vec2) -> Result<(), VisualValueError> {
73        validate_translation(delta)?;
74        let translation = self.translation + delta;
75        validate_translation(translation)?;
76        self.translation = translation;
77        Ok(())
78    }
79
80    /// Returns a copy with a finite world-space offset applied atomically.
81    ///
82    /// The source and the returned previous interpolation endpoint remain
83    /// unchanged. Validation and arithmetic are exactly those of
84    /// [`Transform2d::translate_by`]. This is useful for checking a proposed
85    /// pose before deciding whether to update the live component.
86    pub fn translated_by(&self, delta: Vec2) -> Result<Self, VisualValueError> {
87        let mut translated = *self;
88        translated.translate_by(delta)?;
89        Ok(translated)
90    }
91
92    /// Replaces both interpolation endpoints with one finite translation.
93    /// FrameUpdate Systems cannot request mutable access to this component in
94    /// the first-slice runner.
95    pub fn teleport(&mut self, translation: Vec2) -> Result<(), VisualValueError> {
96        validate_translation(translation)?;
97        self.previous_translation = translation;
98        self.translation = translation;
99        Ok(())
100    }
101
102    /// Captures the current translation as the previous fixed-tick endpoint.
103    pub(crate) fn begin_fixed_tick(&mut self) {
104        self.previous_translation = self.translation;
105    }
106
107    /// Removes interpolation history without changing canonical translation.
108    pub(crate) fn snap_interpolation(&mut self) {
109        self.previous_translation = self.translation;
110    }
111
112    pub(crate) fn restore_previous_translation(&mut self, previous: Vec2) {
113        self.previous_translation = previous;
114    }
115}
116
117impl Default for Transform2d {
118    fn default() -> Self {
119        Self {
120            previous_translation: Vec2::ZERO,
121            translation: Vec2::ZERO,
122        }
123    }
124}
125
126/// Filled world-space circle rendered by the standard Sim;Engine bridge.
127///
128/// Radius uses caller-defined world units. Layer controls primary draw order;
129/// lower layers are drawn first. Within one layer, lower draw-order depth is
130/// drawn first, followed by stable entity identity as the final tie-breaker.
131/// Spawning this component without a [`Transform2d`] automatically inserts a
132/// default transform at the world origin. The canonical translation of a
133/// transform supplied in the same bundle takes precedence; normal spawn
134/// snapping may reset its previous interpolation endpoint to that translation.
135#[derive(Debug, Clone, Copy, PartialEq, Component)]
136#[require(Transform2d)]
137pub struct CircleVisual {
138    radius: f32,
139    color: Color,
140    layer: Layer,
141    draw_order_depth: f32,
142}
143
144impl CircleVisual {
145    /// Creates a filled circle on the default layer and draw-order depth zero.
146    pub fn new(radius: f32, color: Color) -> Result<Self, VisualValueError> {
147        validate_radius(radius)?;
148        validate_color(color)?;
149        Ok(Self {
150            radius,
151            color,
152            layer: Layer::DEFAULT,
153            draw_order_depth: 0.0,
154        })
155    }
156
157    /// Returns the radius in caller-defined world units.
158    pub const fn radius(&self) -> f32 {
159        self.radius
160    }
161
162    /// Returns the normalized straight-linear RGBA fill color.
163    pub const fn color(&self) -> Color {
164        self.color
165    }
166
167    /// Returns the Sim;Engine layer used for primary ordering.
168    pub const fn layer(&self) -> Layer {
169        self.layer
170    }
171
172    /// Returns the within-layer draw-order depth.
173    ///
174    /// This value affects ordering only. It is not Sim;Engine pseudo-depth and
175    /// does not change camera projection.
176    pub const fn draw_order_depth(&self) -> f32 {
177        self.draw_order_depth
178    }
179
180    /// Replaces the world-space radius after validation.
181    pub fn set_radius(&mut self, radius: f32) -> Result<(), VisualValueError> {
182        validate_radius(radius)?;
183        self.radius = radius;
184        Ok(())
185    }
186
187    /// Replaces the fill color after normalized-color validation.
188    pub fn set_color(&mut self, color: Color) -> Result<(), VisualValueError> {
189        validate_color(color)?;
190        self.color = color;
191        Ok(())
192    }
193
194    /// Replaces the primary draw layer.
195    pub fn set_layer(&mut self, layer: Layer) {
196        self.layer = layer;
197    }
198
199    /// Replaces within-layer draw depth after finite-value validation.
200    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), VisualValueError> {
201        validate_draw_order_depth(depth)?;
202        self.draw_order_depth = depth;
203        Ok(())
204    }
205}
206
207/// Filled axis-aligned world-space rectangle rendered by the standard bridge.
208///
209/// [`Transform2d::translation`] is the rectangle center and `size` is its full
210/// width and height in caller-defined world units. Layer and draw-order depth
211/// follow the same ordering rules as [`CircleVisual`]. If both visuals belong
212/// to one entity with the same layer and depth, the rectangle is drawn first.
213/// Spawning this component without a [`Transform2d`] automatically inserts a
214/// default transform at the world origin. The canonical translation of a
215/// transform supplied in the same bundle takes precedence; normal spawn
216/// snapping may reset its previous interpolation endpoint to that translation.
217#[derive(Debug, Clone, Copy, PartialEq, Component)]
218#[require(Transform2d)]
219pub struct RectangleVisual {
220    size: Vec2,
221    corner_radius: f32,
222    color: Color,
223    layer: Layer,
224    draw_order_depth: f32,
225}
226
227impl RectangleVisual {
228    /// Creates a filled square-cornered rectangle on the default layer at depth zero.
229    pub fn new(size: Vec2, color: Color) -> Result<Self, VisualValueError> {
230        validate_size(size)?;
231        validate_color(color)?;
232        Ok(Self {
233            size,
234            corner_radius: 0.0,
235            color,
236            layer: Layer::DEFAULT,
237            draw_order_depth: 0.0,
238        })
239    }
240
241    /// Creates a filled rounded rectangle on the default layer at depth zero.
242    ///
243    /// The requested corner radius must be finite and nonnegative. Values
244    /// larger than half the smaller side are retained here and clamped only
245    /// when Sim;Engine presents the rectangle. This is exactly equivalent to
246    /// [`RectangleVisual::new`] followed by
247    /// [`RectangleVisual::set_corner_radius`].
248    pub fn rounded(size: Vec2, color: Color, corner_radius: f32) -> Result<Self, VisualValueError> {
249        let mut visual = Self::new(size, color)?;
250        visual.set_corner_radius(corner_radius)?;
251        Ok(visual)
252    }
253
254    /// Returns the full width and height in caller-defined world units.
255    pub const fn size(&self) -> Vec2 {
256        self.size
257    }
258
259    /// Returns the requested corner radius in world units.
260    ///
261    /// A radius larger than half the smaller side is retained here and clamped
262    /// only while Sim;Engine presents the rectangle.
263    pub const fn corner_radius(&self) -> f32 {
264        self.corner_radius
265    }
266
267    /// Returns the normalized straight-linear RGBA fill color.
268    pub const fn color(&self) -> Color {
269        self.color
270    }
271
272    /// Returns the Sim;Engine layer used for primary ordering.
273    pub const fn layer(&self) -> Layer {
274        self.layer
275    }
276
277    /// Returns the within-layer draw-order depth.
278    ///
279    /// This value affects ordering only. It is not Sim;Engine pseudo-depth and
280    /// does not change camera projection.
281    pub const fn draw_order_depth(&self) -> f32 {
282        self.draw_order_depth
283    }
284
285    /// Replaces the full width and height after validation.
286    pub fn set_size(&mut self, size: Vec2) -> Result<(), VisualValueError> {
287        validate_size(size)?;
288        self.size = size;
289        Ok(())
290    }
291
292    /// Replaces the requested corner radius after validation.
293    pub fn set_corner_radius(&mut self, radius: f32) -> Result<(), VisualValueError> {
294        validate_corner_radius(radius)?;
295        self.corner_radius = radius;
296        Ok(())
297    }
298
299    /// Replaces the fill color after normalized-color validation.
300    pub fn set_color(&mut self, color: Color) -> Result<(), VisualValueError> {
301        validate_color(color)?;
302        self.color = color;
303        Ok(())
304    }
305
306    /// Replaces the primary draw layer.
307    pub fn set_layer(&mut self, layer: Layer) {
308        self.layer = layer;
309    }
310
311    /// Replaces within-layer draw depth after finite-value validation.
312    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), VisualValueError> {
313        validate_draw_order_depth(depth)?;
314        self.draw_order_depth = depth;
315        Ok(())
316    }
317}
318
319/// A world-axis line segment anchored at an entity's [`Transform2d`].
320///
321/// The interpolated transform translation is the segment start. `vector` is
322/// added in caller-defined world units to obtain its end and is not rotated or
323/// scaled. Only the transform translation is interpolated; vector and style
324/// changes are sampled at extraction like other visual geometry.
325///
326/// Stroke width is measured in logical screen pixels and remains readable as
327/// the camera zooms. Rendering uses butt caps, so the segment body stops at
328/// its mathematical endpoints. A zero vector is valid and emits no resolved
329/// record or Scene command.
330///
331/// Lower layers and then lower draw-order depths are drawn first, followed by
332/// stable entity identity. On an otherwise exact tie, rectangles are drawn
333/// before circles and lines are drawn last, which keeps a line visible over a
334/// body on the same entity. Spawning without a [`Transform2d`] supplies an
335/// origin transform. An explicit transform in the same spawn bundle takes
336/// precedence; normal spawn snapping may reset its previous interpolation
337/// endpoint to its canonical translation.
338#[derive(Debug, Clone, Copy, PartialEq, Component)]
339#[require(Transform2d)]
340pub struct LineVisual {
341    vector: Vec2,
342    stroke_width_logical_pixels: f32,
343    color: Color,
344    layer: Layer,
345    draw_order_depth: f32,
346}
347
348impl LineVisual {
349    /// Creates an anchored line on the default layer at draw-order depth zero.
350    ///
351    /// Validation order is vector, logical-pixel width, then color. Zero is a
352    /// valid vector and represents an omitted line.
353    pub fn new(
354        vector: Vec2,
355        stroke_width_logical_pixels: f32,
356        color: Color,
357    ) -> Result<Self, VisualValueError> {
358        validate_line_vector(vector)?;
359        validate_line_width(stroke_width_logical_pixels)?;
360        validate_color(color)?;
361        Ok(Self {
362            vector,
363            stroke_width_logical_pixels,
364            color,
365            layer: Layer::DEFAULT,
366            draw_order_depth: 0.0,
367        })
368    }
369
370    /// Returns the world-axis offset from the transform anchor to the endpoint.
371    pub const fn vector(&self) -> Vec2 {
372        self.vector
373    }
374
375    /// Returns stroke width in logical screen pixels.
376    pub const fn stroke_width_logical_pixels(&self) -> f32 {
377        self.stroke_width_logical_pixels
378    }
379
380    /// Returns the normalized straight-linear RGBA stroke color.
381    pub const fn color(&self) -> Color {
382        self.color
383    }
384
385    /// Returns the Sim;Engine layer used for primary ordering.
386    pub const fn layer(&self) -> Layer {
387        self.layer
388    }
389
390    /// Returns the within-layer draw-order value.
391    ///
392    /// This affects ordering only and is not Sim;Engine projection depth.
393    pub const fn draw_order_depth(&self) -> f32 {
394        self.draw_order_depth
395    }
396
397    /// Replaces the world-axis vector after finite-value validation.
398    ///
399    /// Zero is accepted and omits the line at extraction. A rejected value
400    /// leaves the previous vector unchanged.
401    pub fn set_vector(&mut self, vector: Vec2) -> Result<(), VisualValueError> {
402        validate_line_vector(vector)?;
403        self.vector = vector;
404        Ok(())
405    }
406
407    /// Replaces the logical-pixel stroke width after Sim;Engine validation.
408    ///
409    /// A rejected value leaves the previous width unchanged.
410    pub fn set_stroke_width_logical_pixels(&mut self, width: f32) -> Result<(), VisualValueError> {
411        validate_line_width(width)?;
412        self.stroke_width_logical_pixels = width;
413        Ok(())
414    }
415
416    /// Replaces the stroke color after normalized-color validation.
417    pub fn set_color(&mut self, color: Color) -> Result<(), VisualValueError> {
418        validate_color(color)?;
419        self.color = color;
420        Ok(())
421    }
422
423    /// Replaces the primary draw layer.
424    pub fn set_layer(&mut self, layer: Layer) {
425        self.layer = layer;
426    }
427
428    /// Replaces within-layer draw order after finite-value validation.
429    pub fn set_draw_order_depth(&mut self, depth: f32) -> Result<(), VisualValueError> {
430        validate_draw_order_depth(depth)?;
431        self.draw_order_depth = depth;
432        Ok(())
433    }
434}
435
436/// The only active world camera, with a fixed-step-interpolated center.
437///
438/// FixedUpdate code changes the canonical center through
439/// [`ActiveCamera2d::set_center`] or [`ActiveCamera2d::pan_by`]. The runtime
440/// retains the previous center and extraction presents an interpolated copy of
441/// the wrapped Sim;Engine camera. Zoom, rotation, and projection remain the
442/// static values supplied at construction in this slice.
443///
444/// FrameUpdate Systems cannot request mutable access to this component.
445/// Extraction also fails when a World contains zero or more than one enabled
446/// `ActiveCamera2d`. This component intentionally denotes the fixed-owned
447/// active camera and does not add a [`Transform2d`]; its wrapped camera center
448/// is the sole position source. A future frame-driven camera must use a
449/// distinct camera source instead of changing this component's ownership at
450/// runtime.
451#[derive(Debug, Clone, Copy, PartialEq, Component)]
452pub struct ActiveCamera2d {
453    previous_camera: Camera2d,
454    camera: Camera2d,
455}
456
457impl ActiveCamera2d {
458    /// Marks a validated Sim;Engine camera as active and snaps its history.
459    pub const fn new(camera: Camera2d) -> Self {
460        Self {
461            previous_camera: camera,
462            camera,
463        }
464    }
465
466    /// Creates an active camera centered at the world origin.
467    ///
468    /// `zoom` is logical screen pixels per world unit and must be finite and
469    /// positive. Validation is delegated to [`Camera2d::new`]. Use
470    /// [`ActiveCamera2d::new`] when the initial center is not the origin.
471    pub fn centered(zoom: f32) -> Result<Self, sim_engine::Camera2dError> {
472        Camera2d::new(Vec2::ZERO, zoom).map(Self::new)
473    }
474
475    /// Returns the current canonical Sim;Engine camera value.
476    ///
477    /// During a partial fixed interval this can differ from the presentation
478    /// camera returned by [`crate::ExtractedFrame::camera`].
479    pub const fn camera(&self) -> Camera2d {
480        self.camera
481    }
482
483    /// Returns the current canonical world-space center.
484    pub fn center(&self) -> Vec2 {
485        self.camera.center()
486    }
487
488    /// Returns the previous center endpoint retained for interpolation.
489    pub fn previous_center(&self) -> Vec2 {
490        self.previous_camera.center()
491    }
492
493    /// Replaces the canonical center after Sim;Engine validation.
494    ///
495    /// The previous center is retained for fixed-step interpolation. Use
496    /// [`ActiveCamera2d::teleport_center`] when the change must be immediate.
497    pub fn set_center(&mut self, center: Vec2) -> Result<(), sim_engine::Camera2dError> {
498        self.camera.set_center(center)
499    }
500
501    /// Applies a validated world-space offset to the canonical center.
502    pub fn pan_by(&mut self, delta: Vec2) -> Result<(), sim_engine::Camera2dError> {
503        self.camera.pan_by(delta)
504    }
505
506    /// Replaces both center interpolation endpoints with one validated value.
507    pub fn teleport_center(&mut self, center: Vec2) -> Result<(), sim_engine::Camera2dError> {
508        self.camera.set_center(center)?;
509        self.previous_camera.set_center(center)?;
510        Ok(())
511    }
512
513    pub(crate) fn begin_fixed_tick(&mut self) {
514        self.previous_camera = self.camera;
515    }
516
517    pub(crate) fn snap_interpolation(&mut self) {
518        self.previous_camera = self.camera;
519    }
520
521    pub(crate) fn restore_previous_center(&mut self, previous: Vec2) {
522        let result = self.previous_camera.set_center(previous);
523        debug_assert!(result.is_ok(), "valid camera backup was rejected");
524    }
525
526    pub(crate) fn interpolated_camera(&self, alpha: f32) -> Camera2d {
527        let center = self
528            .previous_camera
529            .center()
530            .interpolate(self.camera.center(), alpha);
531        let mut camera = self.camera;
532        // Both endpoints and alpha are validated by their public/runtime
533        // contracts. Sim;Engine's interpolation also preserves a finite
534        // endpoint defensively, so this setter cannot reject here.
535        let result = camera.set_center(center);
536        debug_assert!(
537            result.is_ok(),
538            "validated camera interpolation became invalid"
539        );
540        camera
541    }
542}
543
544/// Normalized clear color owned by one logical World.
545#[derive(Debug, Clone, Copy, PartialEq, Resource)]
546pub struct WorldBackground(Color);
547
548impl WorldBackground {
549    /// Creates a World background after normalized-color validation.
550    pub fn new(color: Color) -> Result<Self, VisualValueError> {
551        validate_color(color)?;
552        Ok(Self(color))
553    }
554
555    /// Returns the normalized straight-linear RGBA clear color.
556    pub const fn color(self) -> Color {
557        self.0
558    }
559}
560
561impl Default for WorldBackground {
562    fn default() -> Self {
563        Self(Color::BLACK)
564    }
565}
566
567/// Invalid value rejected by a standard visual component operation.
568#[derive(Debug, Clone, Copy, PartialEq)]
569#[non_exhaustive]
570pub enum VisualValueError {
571    /// A world-space translation or offset contained a non-finite component.
572    InvalidTranslation {
573        /// Rejected translation or offset.
574        value: Vec2,
575    },
576    /// A circle radius was non-finite or not strictly positive.
577    InvalidRadius {
578        /// Rejected radius in world units.
579        value: f32,
580    },
581    /// A rectangle size had a non-finite or non-positive component.
582    InvalidSize {
583        /// Rejected full width and height in world units.
584        value: Vec2,
585    },
586    /// A line vector contained a non-finite component.
587    InvalidLineVector {
588        /// Rejected world-axis vector.
589        value: Vec2,
590    },
591    /// A logical-pixel line width was rejected by Sim;Engine.
592    InvalidLineWidth {
593        /// Rejected untyped logical-pixel width.
594        value: f32,
595    },
596    /// A rectangle corner radius was non-finite or negative.
597    InvalidCornerRadius {
598        /// Rejected corner radius in world units.
599        value: f32,
600    },
601    /// A color was non-finite or outside the normalized `0.0..=1.0` range.
602    InvalidColor {
603        /// Rejected straight-linear RGBA color.
604        value: Color,
605    },
606    /// A draw-order depth was not finite.
607    InvalidDrawOrderDepth {
608        /// Rejected ordering value.
609        value: f32,
610    },
611}
612
613impl fmt::Display for VisualValueError {
614    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
615        match self {
616            Self::InvalidTranslation { value } => {
617                write!(formatter, "world translation must be finite, got {value:?}")
618            }
619            Self::InvalidRadius { value } => {
620                write!(
621                    formatter,
622                    "circle radius must be positive and finite, got {value}"
623                )
624            }
625            Self::InvalidSize { value } => write!(
626                formatter,
627                "rectangle size components must be positive and finite, got {value:?}"
628            ),
629            Self::InvalidLineVector { value } => {
630                write!(formatter, "line vector must be finite, got {value:?}")
631            }
632            Self::InvalidLineWidth { value } => write!(
633                formatter,
634                "line stroke width in logical pixels is invalid, got {value}"
635            ),
636            Self::InvalidCornerRadius { value } => write!(
637                formatter,
638                "rectangle corner radius must be nonnegative and finite, got {value}"
639            ),
640            Self::InvalidColor { value } => {
641                write!(
642                    formatter,
643                    "visual color must be normalized linear RGBA, got {value:?}"
644                )
645            }
646            Self::InvalidDrawOrderDepth { value } => {
647                write!(formatter, "draw-order depth must be finite, got {value}")
648            }
649        }
650    }
651}
652
653impl Error for VisualValueError {}
654
655pub(crate) fn validate_translation(value: Vec2) -> Result<(), VisualValueError> {
656    value
657        .is_finite()
658        .then_some(())
659        .ok_or(VisualValueError::InvalidTranslation { value })
660}
661
662pub(crate) fn validate_radius(value: f32) -> Result<(), VisualValueError> {
663    (value.is_finite() && value > 0.0)
664        .then_some(())
665        .ok_or(VisualValueError::InvalidRadius { value })
666}
667
668pub(crate) fn validate_size(value: Vec2) -> Result<(), VisualValueError> {
669    (value.is_finite() && value.x() > 0.0 && value.y() > 0.0)
670        .then_some(())
671        .ok_or(VisualValueError::InvalidSize { value })
672}
673
674pub(crate) fn validate_line_vector(value: Vec2) -> Result<(), VisualValueError> {
675    value
676        .is_finite()
677        .then_some(())
678        .ok_or(VisualValueError::InvalidLineVector { value })
679}
680
681pub(crate) fn validate_line_width(value: f32) -> Result<(), VisualValueError> {
682    let style = line_stroke_style(value, Color::WHITE);
683    DrawCommand::styled_line(Vec2::ZERO, Vec2::new(1.0, 0.0), style)
684        .map(|_| ())
685        .map_err(|_| VisualValueError::InvalidLineWidth { value })
686}
687
688pub(crate) const fn line_stroke_style(width: f32, color: Color) -> StrokeStyle2d {
689    StrokeStyle2d::new(width, color).with_cap(StrokeCap2d::Butt)
690}
691
692pub(crate) fn validate_corner_radius(value: f32) -> Result<(), VisualValueError> {
693    (value.is_finite() && value >= 0.0)
694        .then_some(())
695        .ok_or(VisualValueError::InvalidCornerRadius { value })
696}
697
698pub(crate) fn validate_color(value: Color) -> Result<(), VisualValueError> {
699    value
700        .is_normalized()
701        .then_some(())
702        .ok_or(VisualValueError::InvalidColor { value })
703}
704
705pub(crate) fn validate_draw_order_depth(value: f32) -> Result<(), VisualValueError> {
706    value
707        .is_finite()
708        .then_some(())
709        .ok_or(VisualValueError::InvalidDrawOrderDepth { value })
710}
711
712#[cfg(test)]
713mod tests {
714    use super::*;
715
716    #[test]
717    fn transform_from_xy_exactly_delegates_to_vector_construction() {
718        let valid = [
719            (-0.0, 0.0),
720            (f32::from_bits(1), -f32::from_bits(1)),
721            (12.5, -98.25),
722            (f32::MAX, -f32::MAX),
723        ];
724        for (x, y) in valid {
725            let direct = Transform2d::new(Vec2::new(x, y)).unwrap();
726            let scalar = Transform2d::from_xy(x, y).unwrap();
727            assert_eq!(scalar, direct);
728            assert_eq!(scalar.translation().x().to_bits(), x.to_bits());
729            assert_eq!(scalar.translation().y().to_bits(), y.to_bits());
730            assert_eq!(scalar.previous_translation().x().to_bits(), x.to_bits());
731            assert_eq!(scalar.previous_translation().y().to_bits(), y.to_bits());
732        }
733
734        let nan = f32::from_bits(0x7fc0_1234);
735        for (x, y) in [
736            (nan, -0.0),
737            (-0.0, nan),
738            (f32::INFINITY, 1.0),
739            (1.0, f32::INFINITY),
740            (f32::NEG_INFINITY, -1.0),
741            (-1.0, f32::NEG_INFINITY),
742            (nan, f32::NEG_INFINITY),
743        ] {
744            let direct = Transform2d::new(Vec2::new(x, y)).unwrap_err();
745            let scalar = Transform2d::from_xy(x, y).unwrap_err();
746            match (direct, scalar) {
747                (
748                    VisualValueError::InvalidTranslation { value: direct },
749                    VisualValueError::InvalidTranslation { value: scalar },
750                ) => {
751                    assert_eq!(scalar.x().to_bits(), direct.x().to_bits());
752                    assert_eq!(scalar.y().to_bits(), direct.y().to_bits());
753                }
754                errors => panic!("from_xy changed the validation error: {errors:?}"),
755            }
756        }
757    }
758
759    #[test]
760    fn centered_camera_exactly_delegates_to_sim_engine_camera() {
761        for zoom in [0.0001, 1.0, 20.0, f32::MAX] {
762            let direct = ActiveCamera2d::new(Camera2d::new(Vec2::ZERO, zoom).unwrap());
763            let centered = ActiveCamera2d::centered(zoom).unwrap();
764
765            assert_eq!(centered, direct);
766            assert_eq!(centered.center(), Vec2::ZERO);
767            assert_eq!(centered.previous_center(), Vec2::ZERO);
768        }
769
770        for zoom in [0.0, -0.0, -1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
771            let direct = Camera2d::new(Vec2::ZERO, zoom).unwrap_err();
772            let centered = ActiveCamera2d::centered(zoom).unwrap_err();
773
774            match (direct, centered) {
775                (
776                    sim_engine::Camera2dError::InvalidZoom { zoom: direct },
777                    sim_engine::Camera2dError::InvalidZoom { zoom: centered },
778                ) => assert_eq!(centered.to_bits(), direct.to_bits()),
779                errors => panic!("centered camera changed the validation error: {errors:?}"),
780            }
781        }
782    }
783
784    #[test]
785    fn rejected_transform_updates_are_atomic() -> Result<(), VisualValueError> {
786        let initial = Vec2::splat(f32::MAX);
787        let mut transform = Transform2d::new(initial)?;
788
789        let error = transform.translate_by(Vec2::new(f32::MAX, f32::MAX));
790
791        assert!(matches!(
792            error,
793            Err(VisualValueError::InvalidTranslation { .. })
794        ));
795        assert_eq!(transform.translation(), initial);
796        assert_eq!(transform.previous_translation(), initial);
797        Ok(())
798    }
799
800    #[test]
801    fn translated_transform_exactly_matches_mutating_a_copy() -> Result<(), VisualValueError> {
802        let mut with_history = Transform2d::new(Vec2::new(-0.0, f32::from_bits(1)))?;
803        with_history.set_translation(Vec2::new(4.0, -8.0))?;
804        let valid = [
805            (with_history, Vec2::new(0.5, 2.0)),
806            (Transform2d::default(), Vec2::new(-0.0, f32::from_bits(1))),
807            (Transform2d::default(), Vec2::new(f32::MAX, -f32::MAX)),
808        ];
809
810        for (source, delta) in valid {
811            let original = source;
812            let mut direct = source;
813            direct.translate_by(delta)?;
814            let translated = source.translated_by(delta)?;
815
816            assert_transform_bits_eq(translated, direct);
817            assert_transform_bits_eq(source, original);
818            assert_vec2_bits_eq(
819                translated.previous_translation(),
820                original.previous_translation(),
821            );
822        }
823
824        let nan = f32::from_bits(0x7fc0_1234);
825        let invalid = [
826            (with_history, Vec2::new(nan, -0.0)),
827            (with_history, Vec2::new(-0.0, f32::INFINITY)),
828            (
829                Transform2d::new(Vec2::new(f32::MAX, -f32::MAX))?,
830                Vec2::new(f32::MAX, -f32::MAX),
831            ),
832        ];
833
834        for (source, delta) in invalid {
835            let original = source;
836            let mut direct = source;
837            let direct_error = direct
838                .translate_by(delta)
839                .expect_err("test offset should be rejected");
840            let translated_error = source
841                .translated_by(delta)
842                .expect_err("test offset should be rejected");
843
844            assert_translation_error_bits_eq(translated_error, direct_error);
845            assert_transform_bits_eq(source, original);
846            assert_transform_bits_eq(direct, original);
847        }
848        Ok(())
849    }
850
851    fn assert_transform_bits_eq(actual: Transform2d, expected: Transform2d) {
852        assert_vec2_bits_eq(actual.translation(), expected.translation());
853        assert_vec2_bits_eq(
854            actual.previous_translation(),
855            expected.previous_translation(),
856        );
857    }
858
859    fn assert_vec2_bits_eq(actual: Vec2, expected: Vec2) {
860        assert_eq!(actual.x().to_bits(), expected.x().to_bits());
861        assert_eq!(actual.y().to_bits(), expected.y().to_bits());
862    }
863
864    fn assert_translation_error_bits_eq(actual: VisualValueError, expected: VisualValueError) {
865        match (actual, expected) {
866            (
867                VisualValueError::InvalidTranslation { value: actual },
868                VisualValueError::InvalidTranslation { value: expected },
869            ) => assert_vec2_bits_eq(actual, expected),
870            errors => panic!("translated_by changed the validation error: {errors:?}"),
871        }
872    }
873
874    #[test]
875    fn fixed_tick_and_teleport_have_distinct_interpolation_semantics()
876    -> Result<(), VisualValueError> {
877        let mut transform = Transform2d::default();
878        transform.set_translation(Vec2::new(1.0, 0.0))?;
879        transform.begin_fixed_tick();
880        transform.set_translation(Vec2::new(2.0, 0.0))?;
881
882        assert_eq!(transform.previous_translation(), Vec2::new(1.0, 0.0));
883        assert_eq!(transform.translation(), Vec2::new(2.0, 0.0));
884
885        transform.teleport(Vec2::new(8.0, 4.0))?;
886        assert_eq!(transform.previous_translation(), Vec2::new(8.0, 4.0));
887        assert_eq!(transform.translation(), Vec2::new(8.0, 4.0));
888        Ok(())
889    }
890
891    #[test]
892    fn camera_center_updates_and_teleports_have_distinct_interpolation_semantics()
893    -> Result<(), sim_engine::Camera2dError> {
894        let mut camera = ActiveCamera2d::new(Camera2d::new(Vec2::ZERO, 20.0)?);
895        camera.set_center(Vec2::new(1.0, 0.0))?;
896        camera.begin_fixed_tick();
897        camera.pan_by(Vec2::new(3.0, 2.0))?;
898
899        assert_eq!(camera.previous_center(), Vec2::new(1.0, 0.0));
900        assert_eq!(camera.center(), Vec2::new(4.0, 2.0));
901        assert_eq!(
902            camera.interpolated_camera(0.5).center(),
903            Vec2::new(2.5, 1.0)
904        );
905
906        camera.teleport_center(Vec2::new(8.0, 4.0))?;
907        assert_eq!(camera.previous_center(), Vec2::new(8.0, 4.0));
908        assert_eq!(camera.center(), Vec2::new(8.0, 4.0));
909        Ok(())
910    }
911
912    #[test]
913    fn rejected_camera_updates_are_atomic() -> Result<(), sim_engine::Camera2dError> {
914        let mut camera = ActiveCamera2d::new(Camera2d::new(Vec2::ZERO, 20.0)?);
915
916        assert!(camera.set_center(Vec2::splat(f32::NAN)).is_err());
917        camera.teleport_center(Vec2::splat(f32::MAX))?;
918        assert!(camera.pan_by(Vec2::splat(f32::MAX)).is_err());
919        assert_eq!(camera.center(), Vec2::splat(f32::MAX));
920        assert_eq!(camera.previous_center(), Vec2::splat(f32::MAX));
921        Ok(())
922    }
923
924    #[test]
925    fn whole_camera_replacement_interpolates_only_a_restored_center() -> Result<(), Box<dyn Error>>
926    {
927        let mut active = ActiveCamera2d::new(Camera2d::new(Vec2::ZERO, 20.0)?);
928        let previous = active.previous_center();
929
930        let mut replacement = Camera2d::new(Vec2::new(10.0, 4.0), 40.0)?;
931        replacement.set_rotation(0.75)?;
932        replacement.set_projection(sim_engine::Projection2d::new(0.25, 2.0)?);
933        active = ActiveCamera2d::new(replacement);
934        active.restore_previous_center(previous);
935
936        let presentation = active.interpolated_camera(0.5);
937        assert_eq!(presentation.center(), Vec2::new(5.0, 2.0));
938        assert_eq!(presentation.zoom(), 40.0);
939        assert_eq!(presentation.rotation(), 0.75);
940        assert_eq!(presentation.projection(), replacement.projection());
941        Ok(())
942    }
943
944    #[test]
945    fn circle_rejects_invalid_required_values() {
946        assert!(matches!(
947            CircleVisual::new(0.0, Color::WHITE),
948            Err(VisualValueError::InvalidRadius { .. })
949        ));
950        assert!(matches!(
951            CircleVisual::new(1.0, Color::rgb(1.1, 0.0, 0.0)),
952            Err(VisualValueError::InvalidColor { .. })
953        ));
954    }
955
956    #[test]
957    fn line_defaults_and_rejected_updates_are_atomic_and_bit_exact() -> Result<(), VisualValueError>
958    {
959        let vector = Vec2::new(4.0, -2.0);
960        let color = Color::rgb8(255, 120, 72);
961        let mut line = LineVisual::new(vector, 2.5, color)?;
962
963        assert_eq!(line.vector(), vector);
964        assert_eq!(line.stroke_width_logical_pixels(), 2.5);
965        assert_eq!(line.color(), color);
966        assert_eq!(line.layer(), Layer::DEFAULT);
967        assert_eq!(line.draw_order_depth(), 0.0);
968
969        for valid in [
970            Vec2::ZERO,
971            Vec2::new(-0.0, 0.0),
972            Vec2::new(f32::from_bits(1), -f32::from_bits(1)),
973            Vec2::new(f32::MAX, -f32::MAX),
974        ] {
975            line.set_vector(valid)?;
976            assert_eq!(line.vector().x().to_bits(), valid.x().to_bits());
977            assert_eq!(line.vector().y().to_bits(), valid.y().to_bits());
978        }
979
980        let retained_vector = line.vector();
981        for invalid in [
982            Vec2::new(f32::NAN, 0.0),
983            Vec2::new(0.0, f32::INFINITY),
984            Vec2::new(f32::NEG_INFINITY, f32::NAN),
985        ] {
986            assert!(matches!(
987                line.set_vector(invalid),
988                Err(VisualValueError::InvalidLineVector { value })
989                    if value.x().to_bits() == invalid.x().to_bits()
990                        && value.y().to_bits() == invalid.y().to_bits()
991            ));
992            assert_eq!(line.vector(), retained_vector);
993        }
994
995        let retained_width = line.stroke_width_logical_pixels();
996        for invalid in [
997            0.0,
998            -0.0,
999            -1.0,
1000            f32::NAN,
1001            f32::INFINITY,
1002            f32::NEG_INFINITY,
1003            f32::MAX,
1004        ] {
1005            assert!(matches!(
1006                line.set_stroke_width_logical_pixels(invalid),
1007                Err(VisualValueError::InvalidLineWidth { value })
1008                    if value.to_bits() == invalid.to_bits()
1009            ));
1010            assert_eq!(line.stroke_width_logical_pixels(), retained_width);
1011        }
1012
1013        assert!(matches!(
1014            LineVisual::new(Vec2::new(f32::NAN, 0.0), 0.0, Color::rgb(2.0, 0.0, 0.0),),
1015            Err(VisualValueError::InvalidLineVector { .. })
1016        ));
1017        assert!(matches!(
1018            LineVisual::new(vector, 0.0, Color::rgb(2.0, 0.0, 0.0)),
1019            Err(VisualValueError::InvalidLineWidth { .. })
1020        ));
1021        assert!(matches!(
1022            LineVisual::new(vector, 2.5, Color::rgb(2.0, 0.0, 0.0)),
1023            Err(VisualValueError::InvalidColor { .. })
1024        ));
1025
1026        assert!(matches!(
1027            line.set_color(Color::rgb(-0.1, 0.0, 0.0)),
1028            Err(VisualValueError::InvalidColor { .. })
1029        ));
1030        assert_eq!(line.color(), color);
1031        line.set_layer(Layer::new(-7));
1032        assert_eq!(line.layer(), Layer::new(-7));
1033        line.set_draw_order_depth(3.0)?;
1034        assert!(matches!(
1035            line.set_draw_order_depth(f32::NAN),
1036            Err(VisualValueError::InvalidDrawOrderDepth { .. })
1037        ));
1038        assert_eq!(line.draw_order_depth(), 3.0);
1039        line.set_layer(Layer::new(4));
1040        assert_eq!(line.layer(), Layer::new(4));
1041        Ok(())
1042    }
1043
1044    #[test]
1045    fn rectangle_defaults_and_rejected_updates_are_atomic() -> Result<(), VisualValueError> {
1046        let size = Vec2::new(4.0, 2.0);
1047        let color = Color::rgb8(68, 144, 255);
1048        let mut rectangle = RectangleVisual::new(size, color)?;
1049
1050        assert_eq!(rectangle.size(), size);
1051        assert_eq!(rectangle.corner_radius(), 0.0);
1052        assert_eq!(rectangle.color(), color);
1053        assert_eq!(rectangle.layer(), Layer::DEFAULT);
1054        assert_eq!(rectangle.draw_order_depth(), 0.0);
1055
1056        for invalid in [
1057            Vec2::ZERO,
1058            Vec2::new(-1.0, 1.0),
1059            Vec2::new(1.0, f32::NAN),
1060            Vec2::new(1.0, f32::NEG_INFINITY),
1061            Vec2::new(f32::INFINITY, 1.0),
1062        ] {
1063            assert!(matches!(
1064                rectangle.set_size(invalid),
1065                Err(VisualValueError::InvalidSize { .. })
1066            ));
1067            assert_eq!(rectangle.size(), size);
1068        }
1069
1070        for invalid in [-1.0, f32::NAN, f32::INFINITY] {
1071            assert!(matches!(
1072                rectangle.set_corner_radius(invalid),
1073                Err(VisualValueError::InvalidCornerRadius { .. })
1074            ));
1075            assert_eq!(rectangle.corner_radius(), 0.0);
1076        }
1077
1078        rectangle.set_corner_radius(20.0)?;
1079        assert_eq!(rectangle.corner_radius(), 20.0);
1080
1081        assert!(matches!(
1082            RectangleVisual::new(Vec2::ZERO, color),
1083            Err(VisualValueError::InvalidSize { .. })
1084        ));
1085        assert!(matches!(
1086            RectangleVisual::new(size, Color::rgb(1.1, 0.0, 0.0)),
1087            Err(VisualValueError::InvalidColor { .. })
1088        ));
1089
1090        assert!(matches!(
1091            rectangle.set_color(Color::rgb(-0.1, 0.0, 0.0)),
1092            Err(VisualValueError::InvalidColor { .. })
1093        ));
1094        assert_eq!(rectangle.color(), color);
1095
1096        rectangle.set_draw_order_depth(3.0)?;
1097        assert!(matches!(
1098            rectangle.set_draw_order_depth(f32::NAN),
1099            Err(VisualValueError::InvalidDrawOrderDepth { .. })
1100        ));
1101        assert_eq!(rectangle.draw_order_depth(), 3.0);
1102        Ok(())
1103    }
1104
1105    #[test]
1106    fn rounded_rectangle_exactly_delegates_to_constructor_and_setter() {
1107        let size = Vec2::new(4.0, 2.0);
1108        let color = Color::rgb8(68, 144, 255);
1109        for corner_radius in [0.0, -0.0, f32::from_bits(1), 0.25, 20.0, f32::MAX] {
1110            let mut direct = RectangleVisual::new(size, color).unwrap();
1111            direct.set_corner_radius(corner_radius).unwrap();
1112            let rounded = RectangleVisual::rounded(size, color, corner_radius).unwrap();
1113
1114            assert_eq!(rounded, direct);
1115            assert_eq!(rounded.corner_radius().to_bits(), corner_radius.to_bits());
1116        }
1117
1118        assert!(matches!(
1119            RectangleVisual::rounded(
1120                Vec2::new(f32::NAN, 1.0),
1121                Color::rgb(2.0, 0.0, 0.0),
1122                f32::NAN,
1123            ),
1124            Err(VisualValueError::InvalidSize { .. })
1125        ));
1126        assert!(matches!(
1127            RectangleVisual::rounded(size, Color::rgb(2.0, 0.0, 0.0), f32::NAN),
1128            Err(VisualValueError::InvalidColor { .. })
1129        ));
1130        for corner_radius in [-1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
1131            assert!(matches!(
1132                RectangleVisual::rounded(size, color, corner_radius),
1133                Err(VisualValueError::InvalidCornerRadius { value })
1134                    if value.to_bits() == corner_radius.to_bits()
1135            ));
1136        }
1137    }
1138}