1use 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#[derive(Debug, Clone, Copy, PartialEq, Component)]
20pub struct Transform2d {
21 previous_translation: Vec2,
22 translation: Vec2,
23}
24
25impl Transform2d {
26 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 #[inline]
41 pub fn from_xy(x: f32, y: f32) -> Result<Self, VisualValueError> {
42 Self::new(Vec2::new(x, y))
43 }
44
45 pub const fn translation(&self) -> Vec2 {
47 self.translation
48 }
49
50 pub const fn previous_translation(&self) -> Vec2 {
52 self.previous_translation
53 }
54
55 pub fn set_translation(&mut self, translation: Vec2) -> Result<(), VisualValueError> {
62 validate_translation(translation)?;
63 self.translation = translation;
64 Ok(())
65 }
66
67 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 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 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 pub(crate) fn begin_fixed_tick(&mut self) {
104 self.previous_translation = self.translation;
105 }
106
107 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#[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 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 pub const fn radius(&self) -> f32 {
159 self.radius
160 }
161
162 pub const fn color(&self) -> Color {
164 self.color
165 }
166
167 pub const fn layer(&self) -> Layer {
169 self.layer
170 }
171
172 pub const fn draw_order_depth(&self) -> f32 {
177 self.draw_order_depth
178 }
179
180 pub fn set_radius(&mut self, radius: f32) -> Result<(), VisualValueError> {
182 validate_radius(radius)?;
183 self.radius = radius;
184 Ok(())
185 }
186
187 pub fn set_color(&mut self, color: Color) -> Result<(), VisualValueError> {
189 validate_color(color)?;
190 self.color = color;
191 Ok(())
192 }
193
194 pub fn set_layer(&mut self, layer: Layer) {
196 self.layer = layer;
197 }
198
199 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#[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 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 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 pub const fn size(&self) -> Vec2 {
256 self.size
257 }
258
259 pub const fn corner_radius(&self) -> f32 {
264 self.corner_radius
265 }
266
267 pub const fn color(&self) -> Color {
269 self.color
270 }
271
272 pub const fn layer(&self) -> Layer {
274 self.layer
275 }
276
277 pub const fn draw_order_depth(&self) -> f32 {
282 self.draw_order_depth
283 }
284
285 pub fn set_size(&mut self, size: Vec2) -> Result<(), VisualValueError> {
287 validate_size(size)?;
288 self.size = size;
289 Ok(())
290 }
291
292 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 pub fn set_color(&mut self, color: Color) -> Result<(), VisualValueError> {
301 validate_color(color)?;
302 self.color = color;
303 Ok(())
304 }
305
306 pub fn set_layer(&mut self, layer: Layer) {
308 self.layer = layer;
309 }
310
311 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#[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 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 pub const fn vector(&self) -> Vec2 {
372 self.vector
373 }
374
375 pub const fn stroke_width_logical_pixels(&self) -> f32 {
377 self.stroke_width_logical_pixels
378 }
379
380 pub const fn color(&self) -> Color {
382 self.color
383 }
384
385 pub const fn layer(&self) -> Layer {
387 self.layer
388 }
389
390 pub const fn draw_order_depth(&self) -> f32 {
394 self.draw_order_depth
395 }
396
397 pub fn set_vector(&mut self, vector: Vec2) -> Result<(), VisualValueError> {
402 validate_line_vector(vector)?;
403 self.vector = vector;
404 Ok(())
405 }
406
407 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 pub fn set_color(&mut self, color: Color) -> Result<(), VisualValueError> {
418 validate_color(color)?;
419 self.color = color;
420 Ok(())
421 }
422
423 pub fn set_layer(&mut self, layer: Layer) {
425 self.layer = layer;
426 }
427
428 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#[derive(Debug, Clone, Copy, PartialEq, Component)]
452pub struct ActiveCamera2d {
453 previous_camera: Camera2d,
454 camera: Camera2d,
455}
456
457impl ActiveCamera2d {
458 pub const fn new(camera: Camera2d) -> Self {
460 Self {
461 previous_camera: camera,
462 camera,
463 }
464 }
465
466 pub fn centered(zoom: f32) -> Result<Self, sim_engine::Camera2dError> {
472 Camera2d::new(Vec2::ZERO, zoom).map(Self::new)
473 }
474
475 pub const fn camera(&self) -> Camera2d {
480 self.camera
481 }
482
483 pub fn center(&self) -> Vec2 {
485 self.camera.center()
486 }
487
488 pub fn previous_center(&self) -> Vec2 {
490 self.previous_camera.center()
491 }
492
493 pub fn set_center(&mut self, center: Vec2) -> Result<(), sim_engine::Camera2dError> {
498 self.camera.set_center(center)
499 }
500
501 pub fn pan_by(&mut self, delta: Vec2) -> Result<(), sim_engine::Camera2dError> {
503 self.camera.pan_by(delta)
504 }
505
506 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 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#[derive(Debug, Clone, Copy, PartialEq, Resource)]
546pub struct WorldBackground(Color);
547
548impl WorldBackground {
549 pub fn new(color: Color) -> Result<Self, VisualValueError> {
551 validate_color(color)?;
552 Ok(Self(color))
553 }
554
555 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#[derive(Debug, Clone, Copy, PartialEq)]
569#[non_exhaustive]
570pub enum VisualValueError {
571 InvalidTranslation {
573 value: Vec2,
575 },
576 InvalidRadius {
578 value: f32,
580 },
581 InvalidSize {
583 value: Vec2,
585 },
586 InvalidLineVector {
588 value: Vec2,
590 },
591 InvalidLineWidth {
593 value: f32,
595 },
596 InvalidCornerRadius {
598 value: f32,
600 },
601 InvalidColor {
603 value: Color,
605 },
606 InvalidDrawOrderDepth {
608 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}