1use super::{Error, TernaryCartesian, TernaryGeometry, Tolerance};
2
3#[derive(Clone, Copy, Debug, PartialEq)]
8pub struct TernaryViewport {
9 x_min: f64,
10 x_max: f64,
11 y_min: f64,
12 y_max: f64,
13}
14
15impl TernaryViewport {
16 pub fn new(x_min: f64, x_max: f64, y_min: f64, y_max: f64) -> Result<Self, Error> {
18 Self::new_with_tolerance(x_min, x_max, y_min, y_max, Tolerance::default())
19 }
20
21 pub fn new_with_tolerance(
23 x_min: f64,
24 x_max: f64,
25 y_min: f64,
26 y_max: f64,
27 tolerance: Tolerance,
28 ) -> Result<Self, Error> {
29 tolerance.validate()?;
30 if !x_min.is_finite() || !x_max.is_finite() || !y_min.is_finite() || !y_max.is_finite() {
31 return Err(Error::NonFiniteViewportBounds {
32 x_min,
33 x_max,
34 y_min,
35 y_max,
36 });
37 }
38
39 let width = x_max - x_min;
40 let height = y_max - y_min;
41 if !width.is_finite()
42 || !height.is_finite()
43 || width <= tolerance.absolute
44 || height <= tolerance.absolute
45 {
46 return Err(Error::InvalidViewport {
47 x_min,
48 x_max,
49 y_min,
50 y_max,
51 minimum_span: tolerance.absolute,
52 });
53 }
54
55 Ok(Self {
56 x_min,
57 x_max,
58 y_min,
59 y_max,
60 })
61 }
62
63 pub fn full(geometry: TernaryGeometry) -> Self {
73 let vertices = geometry.vertices();
74 let x_min = vertices
75 .iter()
76 .map(|vertex| vertex.x)
77 .fold(f64::INFINITY, f64::min);
78 let x_max = vertices
79 .iter()
80 .map(|vertex| vertex.x)
81 .fold(f64::NEG_INFINITY, f64::max);
82 let y_min = vertices
83 .iter()
84 .map(|vertex| vertex.y)
85 .fold(f64::INFINITY, f64::min);
86 let y_max = vertices
87 .iter()
88 .map(|vertex| vertex.y)
89 .fold(f64::NEG_INFINITY, f64::max);
90 Self {
91 x_min,
92 x_max,
93 y_min,
94 y_max,
95 }
96 }
97
98 pub const fn x_min(self) -> f64 {
100 self.x_min
101 }
102
103 pub const fn x_max(self) -> f64 {
105 self.x_max
106 }
107
108 pub const fn y_min(self) -> f64 {
110 self.y_min
111 }
112
113 pub const fn y_max(self) -> f64 {
115 self.y_max
116 }
117
118 pub const fn width(self) -> f64 {
120 self.x_max - self.x_min
121 }
122
123 pub const fn height(self) -> f64 {
125 self.y_max - self.y_min
126 }
127
128 pub fn contains(
130 self,
131 cartesian: TernaryCartesian,
132 tolerance: Tolerance,
133 ) -> Result<bool, Error> {
134 Ok(self.classify(cartesian, tolerance)? != ViewportPointLocation::Outside)
135 }
136
137 pub fn classify(
139 self,
140 cartesian: TernaryCartesian,
141 tolerance: Tolerance,
142 ) -> Result<ViewportPointLocation, Error> {
143 tolerance.validate()?;
144 if !cartesian.x.is_finite() || !cartesian.y.is_finite() {
145 return Err(Error::NonFiniteCartesian {
146 x: cartesian.x,
147 y: cartesian.y,
148 });
149 }
150
151 let outside = (cartesian.x < self.x_min && !tolerance.is_close(cartesian.x, self.x_min))
152 || (cartesian.x > self.x_max && !tolerance.is_close(cartesian.x, self.x_max))
153 || (cartesian.y < self.y_min && !tolerance.is_close(cartesian.y, self.y_min))
154 || (cartesian.y > self.y_max && !tolerance.is_close(cartesian.y, self.y_max));
155 if outside {
156 return Ok(ViewportPointLocation::Outside);
157 }
158
159 if tolerance.is_close(cartesian.x, self.x_min)
160 || tolerance.is_close(cartesian.x, self.x_max)
161 || tolerance.is_close(cartesian.y, self.y_min)
162 || tolerance.is_close(cartesian.y, self.y_max)
163 {
164 Ok(ViewportPointLocation::Boundary)
165 } else {
166 Ok(ViewportPointLocation::Inside)
167 }
168 }
169}
170
171#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
173pub enum ViewportPointLocation {
174 Inside,
176 Boundary,
178 Outside,
180}
181
182#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
187pub struct PixelRect {
188 pub x: i32,
189 pub y: i32,
190 pub width: u32,
191 pub height: u32,
192}
193
194impl PixelRect {
195 pub fn new(x: i32, y: i32, width: u32, height: u32) -> Result<Self, Error> {
197 let rectangle = Self {
198 x,
199 y,
200 width,
201 height,
202 };
203 rectangle.validate()?;
204 Ok(rectangle)
205 }
206
207 pub fn validate(self) -> Result<(), Error> {
209 if self.width == 0 || self.height == 0 {
210 return Err(Error::InvalidPixelRect {
211 x: self.x,
212 y: self.y,
213 width: self.width,
214 height: self.height,
215 });
216 }
217 Ok(())
218 }
219}
220
221#[derive(Clone, Copy, Debug, PartialEq)]
223pub struct PixelPoint {
224 pub x: f64,
225 pub y: f64,
226}
227
228impl PixelPoint {
229 pub const fn new(x: f64, y: f64) -> Self {
230 Self { x, y }
231 }
232}
233
234#[derive(Clone, Copy, Debug, PartialEq)]
236pub struct PixelBounds {
237 pub x_min: f64,
238 pub x_max: f64,
239 pub y_min: f64,
240 pub y_max: f64,
241}
242
243impl PixelBounds {
244 pub const fn width(self) -> f64 {
245 self.x_max - self.x_min
246 }
247
248 pub const fn height(self) -> f64 {
249 self.y_max - self.y_min
250 }
251
252 fn contains(self, point: PixelPoint) -> bool {
253 point.x >= self.x_min
254 && point.x <= self.x_max
255 && point.y >= self.y_min
256 && point.y <= self.y_max
257 }
258}
259
260#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
262pub enum ViewportFit {
263 #[default]
265 PreserveAspect,
266 Stretch,
268}
269
270#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
272pub enum ViewportAlignment {
273 #[default]
274 Center,
275 Top,
276 Bottom,
277 Left,
278 Right,
279 TopLeft,
280 TopRight,
281 BottomLeft,
282 BottomRight,
283}
284
285impl ViewportAlignment {
286 const fn factors(self) -> (f64, f64) {
287 match self {
288 Self::Center => (0.5, 0.5),
289 Self::Top => (0.5, 0.0),
290 Self::Bottom => (0.5, 1.0),
291 Self::Left => (0.0, 0.5),
292 Self::Right => (1.0, 0.5),
293 Self::TopLeft => (0.0, 0.0),
294 Self::TopRight => (1.0, 0.0),
295 Self::BottomLeft => (0.0, 1.0),
296 Self::BottomRight => (1.0, 1.0),
297 }
298 }
299}
300
301#[derive(Clone, Copy, Debug, PartialEq)]
303pub struct ViewportTransform {
304 viewport: TernaryViewport,
305 allocated: PixelRect,
306 fitted: PixelBounds,
307 fit: ViewportFit,
308 alignment: ViewportAlignment,
309}
310
311impl ViewportTransform {
312 pub fn new(
331 viewport: TernaryViewport,
332 allocated: PixelRect,
333 fit: ViewportFit,
334 alignment: ViewportAlignment,
335 ) -> Result<Self, Error> {
336 allocated.validate()?;
337 let allocated_width = f64::from(allocated.width);
338 let allocated_height = f64::from(allocated.height);
339 let allocated_x = f64::from(allocated.x);
340 let allocated_y = f64::from(allocated.y);
341
342 let (fitted_width, fitted_height) = match fit {
343 ViewportFit::PreserveAspect => {
344 let scale =
345 (allocated_width / viewport.width()).min(allocated_height / viewport.height());
346 (viewport.width() * scale, viewport.height() * scale)
347 }
348 ViewportFit::Stretch => (allocated_width, allocated_height),
349 };
350 let (horizontal, vertical) = alignment.factors();
351 let x_min = allocated_x + (allocated_width - fitted_width) * horizontal;
352 let y_min = allocated_y + (allocated_height - fitted_height) * vertical;
353 let fitted = PixelBounds {
354 x_min,
355 x_max: x_min + fitted_width,
356 y_min,
357 y_max: y_min + fitted_height,
358 };
359
360 Ok(Self {
361 viewport,
362 allocated,
363 fitted,
364 fit,
365 alignment,
366 })
367 }
368
369 pub const fn viewport(self) -> TernaryViewport {
370 self.viewport
371 }
372
373 pub const fn allocated_pixel_rect(self) -> PixelRect {
374 self.allocated
375 }
376
377 pub const fn fitted_pixel_bounds(self) -> PixelBounds {
378 self.fitted
379 }
380
381 pub const fn fit(self) -> ViewportFit {
382 self.fit
383 }
384
385 pub const fn alignment(self) -> ViewportAlignment {
386 self.alignment
387 }
388
389 pub fn logical_to_pixel(self, logical: TernaryCartesian) -> Result<PixelPoint, Error> {
391 if !logical.x.is_finite() || !logical.y.is_finite() {
392 return Err(Error::NonFiniteCartesian {
393 x: logical.x,
394 y: logical.y,
395 });
396 }
397 let x_fraction = (logical.x - self.viewport.x_min) / self.viewport.width();
398 let y_fraction = (self.viewport.y_max - logical.y) / self.viewport.height();
399 Ok(PixelPoint::new(
400 self.fitted.x_min + x_fraction * self.fitted.width(),
401 self.fitted.y_min + y_fraction * self.fitted.height(),
402 ))
403 }
404
405 pub fn pixel_to_logical(self, pixel: PixelPoint) -> Result<TernaryCartesian, Error> {
407 if !pixel.x.is_finite() || !pixel.y.is_finite() {
408 return Err(Error::NonFinitePixelCoordinate {
409 x: pixel.x,
410 y: pixel.y,
411 });
412 }
413 let x_fraction = (pixel.x - self.fitted.x_min) / self.fitted.width();
414 let y_fraction = (pixel.y - self.fitted.y_min) / self.fitted.height();
415 Ok(TernaryCartesian::new(
416 self.viewport.x_min + x_fraction * self.viewport.width(),
417 self.viewport.y_max - y_fraction * self.viewport.height(),
418 ))
419 }
420
421 pub fn pixel_to_logical_checked(
423 self,
424 pixel: PixelPoint,
425 ) -> Result<Option<TernaryCartesian>, Error> {
426 if !pixel.x.is_finite() || !pixel.y.is_finite() {
427 return Err(Error::NonFinitePixelCoordinate {
428 x: pixel.x,
429 y: pixel.y,
430 });
431 }
432 if self.fitted.contains(pixel) {
433 self.pixel_to_logical(pixel).map(Some)
434 } else {
435 Ok(None)
436 }
437 }
438}
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443 use crate::{EQUILATERAL_TRIANGLE_HEIGHT, TriangleOrientation, VertexOrder};
444
445 const TOLERANCE: Tolerance = Tolerance {
446 absolute: 1.0e-9,
447 relative: 1.0e-9,
448 };
449 const EPSILON: f64 = 1.0e-10;
450
451 fn assert_close(actual: f64, expected: f64) {
452 assert!(
453 (actual - expected).abs() < EPSILON,
454 "{actual} != {expected}"
455 );
456 }
457
458 fn test_viewport() -> TernaryViewport {
459 TernaryViewport::new(0.0, 2.0, 0.0, 1.0).unwrap()
460 }
461
462 #[test]
463 fn viewport_construction_and_full_bounds_cover_both_orientations() {
464 let arbitrary = TernaryViewport::new(-2.0, 3.0, -4.0, 5.0).unwrap();
465 assert_eq!(arbitrary.width(), 5.0);
466 assert_eq!(arbitrary.height(), 9.0);
467
468 let upward = TernaryViewport::full(TernaryGeometry::default());
469 assert_eq!((upward.x_min(), upward.x_max()), (0.0, 1.0));
470 assert_eq!(
471 (upward.y_min(), upward.y_max()),
472 (0.0, EQUILATERAL_TRIANGLE_HEIGHT)
473 );
474
475 let downward = TernaryViewport::full(TernaryGeometry::new(
476 TriangleOrientation::Down,
477 VertexOrder::default(),
478 ));
479 assert_eq!((downward.x_min(), downward.x_max()), (0.0, 1.0));
480 assert_eq!(
481 (downward.y_min(), downward.y_max()),
482 (-EQUILATERAL_TRIANGLE_HEIGHT, 0.0)
483 );
484
485 assert!(TernaryViewport::new(10.0, 11.0, 10.0, 11.0).is_ok());
486 }
487
488 #[test]
489 fn viewport_validation_rejects_reversed_degenerate_and_non_finite_bounds() {
490 for result in [
491 TernaryViewport::new(1.0, 0.0, 0.0, 1.0),
492 TernaryViewport::new(0.0, 1.0, 1.0, 0.0),
493 TernaryViewport::new(0.0, 0.0, 0.0, 1.0),
494 TernaryViewport::new(0.0, 1.0, 0.0, 0.0),
495 TernaryViewport::new_with_tolerance(0.0, 5.0e-10, 0.0, 1.0, TOLERANCE),
496 TernaryViewport::new_with_tolerance(0.0, 1.0, 0.0, 5.0e-10, TOLERANCE),
497 ] {
498 assert!(matches!(result, Err(Error::InvalidViewport { .. })));
499 }
500
501 for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
502 assert!(matches!(
503 TernaryViewport::new(value, 1.0, 0.0, 1.0),
504 Err(Error::NonFiniteViewportBounds { .. })
505 ));
506 }
507 }
508
509 #[test]
510 fn viewport_classification_is_independent_and_boundary_aware() {
511 let viewport = TernaryViewport::new(0.2, 0.8, 0.1, 0.6).unwrap();
512 assert_eq!(
513 viewport
514 .classify(TernaryCartesian::new(0.5, 0.3), TOLERANCE)
515 .unwrap(),
516 ViewportPointLocation::Inside
517 );
518 assert_eq!(
519 viewport
520 .classify(TernaryCartesian::new(0.2, 0.3), TOLERANCE)
521 .unwrap(),
522 ViewportPointLocation::Boundary
523 );
524 assert!(
525 viewport
526 .contains(TernaryCartesian::new(0.2 - 5.0e-10, 0.3), TOLERANCE)
527 .unwrap()
528 );
529 assert!(
530 !viewport
531 .contains(TernaryCartesian::new(0.2 - 1.0e-5, 0.3), TOLERANCE)
532 .unwrap()
533 );
534 }
535
536 #[test]
537 fn transform_maps_corners_centre_and_inverts_y() {
538 let transform = ViewportTransform::new(
539 test_viewport(),
540 PixelRect::new(10, 20, 200, 100).unwrap(),
541 ViewportFit::PreserveAspect,
542 ViewportAlignment::Center,
543 )
544 .unwrap();
545 let fitted = transform.fitted_pixel_bounds();
546 assert_eq!(
547 fitted,
548 PixelBounds {
549 x_min: 10.0,
550 x_max: 210.0,
551 y_min: 20.0,
552 y_max: 120.0
553 }
554 );
555 assert_eq!(
556 transform
557 .logical_to_pixel(TernaryCartesian::new(0.0, 1.0))
558 .unwrap(),
559 PixelPoint::new(10.0, 20.0)
560 );
561 assert_eq!(
562 transform
563 .logical_to_pixel(TernaryCartesian::new(2.0, 0.0))
564 .unwrap(),
565 PixelPoint::new(210.0, 120.0)
566 );
567 assert_eq!(
568 transform
569 .logical_to_pixel(TernaryCartesian::new(1.0, 0.5))
570 .unwrap(),
571 PixelPoint::new(110.0, 70.0)
572 );
573 }
574
575 #[test]
576 fn preserve_aspect_handles_wide_tall_portrait_landscape_and_offsets() {
577 let cases = [
578 (
579 PixelRect::new(0, 0, 300, 100).unwrap(),
580 PixelBounds {
581 x_min: 50.0,
582 x_max: 250.0,
583 y_min: 0.0,
584 y_max: 100.0,
585 },
586 ),
587 (
588 PixelRect::new(0, 0, 200, 200).unwrap(),
589 PixelBounds {
590 x_min: 0.0,
591 x_max: 200.0,
592 y_min: 50.0,
593 y_max: 150.0,
594 },
595 ),
596 (
597 PixelRect::new(0, 0, 100, 300).unwrap(),
598 PixelBounds {
599 x_min: 0.0,
600 x_max: 100.0,
601 y_min: 125.0,
602 y_max: 175.0,
603 },
604 ),
605 (
606 PixelRect::new(7, 11, 400, 100).unwrap(),
607 PixelBounds {
608 x_min: 107.0,
609 x_max: 307.0,
610 y_min: 11.0,
611 y_max: 111.0,
612 },
613 ),
614 ];
615 for (allocated, expected) in cases {
616 let transform = ViewportTransform::new(
617 test_viewport(),
618 allocated,
619 ViewportFit::PreserveAspect,
620 ViewportAlignment::Center,
621 )
622 .unwrap();
623 assert_eq!(transform.fitted_pixel_bounds(), expected);
624 assert_close(
625 transform.fitted_pixel_bounds().width() / transform.fitted_pixel_bounds().height(),
626 2.0,
627 );
628 }
629 }
630
631 #[test]
632 fn every_alignment_places_unused_horizontal_and_vertical_space() {
633 let alignments = [
634 (ViewportAlignment::Center, 0.5, 0.5),
635 (ViewportAlignment::Top, 0.5, 0.0),
636 (ViewportAlignment::Bottom, 0.5, 1.0),
637 (ViewportAlignment::Left, 0.0, 0.5),
638 (ViewportAlignment::Right, 1.0, 0.5),
639 (ViewportAlignment::TopLeft, 0.0, 0.0),
640 (ViewportAlignment::TopRight, 1.0, 0.0),
641 (ViewportAlignment::BottomLeft, 0.0, 1.0),
642 (ViewportAlignment::BottomRight, 1.0, 1.0),
643 ];
644 for (alignment, horizontal, vertical) in alignments {
645 let wide = ViewportTransform::new(
646 test_viewport(),
647 PixelRect::new(10, 20, 300, 100).unwrap(),
648 ViewportFit::PreserveAspect,
649 alignment,
650 )
651 .unwrap();
652 assert_close(wide.fitted_pixel_bounds().x_min, 10.0 + 100.0 * horizontal);
653
654 let tall = ViewportTransform::new(
655 test_viewport(),
656 PixelRect::new(10, 20, 200, 200).unwrap(),
657 ViewportFit::PreserveAspect,
658 alignment,
659 )
660 .unwrap();
661 assert_close(tall.fitted_pixel_bounds().y_min, 20.0 + 100.0 * vertical);
662 }
663 }
664
665 #[test]
666 fn stretch_fills_allocation_and_round_trips_inside_and_outside_points() {
667 let transform = ViewportTransform::new(
668 test_viewport(),
669 PixelRect::new(-20, 30, 300, 200).unwrap(),
670 ViewportFit::Stretch,
671 ViewportAlignment::BottomRight,
672 )
673 .unwrap();
674 assert_eq!(
675 transform.fitted_pixel_bounds(),
676 PixelBounds {
677 x_min: -20.0,
678 x_max: 280.0,
679 y_min: 30.0,
680 y_max: 230.0
681 }
682 );
683
684 for logical in [
685 TernaryCartesian::new(0.25, 0.75),
686 TernaryCartesian::new(1.0, 0.5),
687 TernaryCartesian::new(2.5, -0.5),
688 ] {
689 let pixel = transform.logical_to_pixel(logical).unwrap();
690 let recovered = transform.pixel_to_logical(pixel).unwrap();
691 assert_close(recovered.x, logical.x);
692 assert_close(recovered.y, logical.y);
693 }
694
695 let outside_pixel = PixelPoint::new(-100.0, -100.0);
696 assert!(transform.pixel_to_logical(outside_pixel).is_ok());
697 assert_eq!(
698 transform.pixel_to_logical_checked(outside_pixel).unwrap(),
699 None
700 );
701 }
702
703 #[test]
704 fn invalid_pixel_rectangles_and_non_finite_mapping_inputs_are_rejected() {
705 assert!(matches!(
706 PixelRect::new(0, 0, 0, 10),
707 Err(Error::InvalidPixelRect { .. })
708 ));
709 assert!(matches!(
710 ViewportTransform::new(
711 test_viewport(),
712 PixelRect {
713 x: 0,
714 y: 0,
715 width: 10,
716 height: 0
717 },
718 ViewportFit::PreserveAspect,
719 ViewportAlignment::Center,
720 ),
721 Err(Error::InvalidPixelRect { .. })
722 ));
723 let transform = ViewportTransform::new(
724 test_viewport(),
725 PixelRect::new(0, 0, 100, 100).unwrap(),
726 ViewportFit::PreserveAspect,
727 ViewportAlignment::Center,
728 )
729 .unwrap();
730 assert!(matches!(
731 transform.logical_to_pixel(TernaryCartesian::new(f64::NAN, 0.0)),
732 Err(Error::NonFiniteCartesian { .. })
733 ));
734 assert!(matches!(
735 transform.pixel_to_logical(PixelPoint::new(f64::INFINITY, 0.0)),
736 Err(Error::NonFinitePixelCoordinate { .. })
737 ));
738 }
739}