Skip to main content

sim_logic/rendering/screen/
clip.rs

1//! Explicit, allocation-free screen clipping, shared by rendering and hit tests.
2
3use crate::input::PointerSample;
4use sim_engine::{LogicalScreenPosition, LogicalScreenVector, SceneError, ScreenClipRect};
5
6/// A logical-pixel clip scope. Disjoint intersections are empty, not unclipped.
7///
8/// Build parent/child scopes with `intersection` and assign the resulting value
9/// to each visual. This has constant storage and no implicit entity hierarchy.
10/// Clips stay fixed in screen space when content moves, rotates, or scrolls.
11#[derive(Debug, Default, Clone, Copy, PartialEq)]
12pub enum ScreenClip {
13    /// No additional clip beyond the viewport.
14    #[default]
15    Unclipped,
16    /// Nothing is drawn or hit. Still counted in source/extraction budgets.
17    Empty,
18    /// A validated rectangle in top-left/downward logical pixels.
19    Rectangle(ScreenClipRect),
20}
21
22impl ScreenClip {
23    /// Constructs a nonempty clip; invalid bounds return Engine's typed error.
24    /// Negative sizes follow Engine's normalization policy.
25    pub fn new(
26        position: LogicalScreenPosition,
27        size: LogicalScreenVector,
28    ) -> Result<Self, SceneError> {
29        Ok(Self::Rectangle(ScreenClipRect::from_min_size(
30            position, size,
31        )?))
32    }
33
34    /// Intersects two scopes, preserving empty intersections without allocations.
35    pub fn intersection(self, other: Self) -> Self {
36        match (self, other) {
37            (Self::Empty, _) | (_, Self::Empty) => Self::Empty,
38            (Self::Unclipped, clip) | (clip, Self::Unclipped) => clip,
39            (Self::Rectangle(a), Self::Rectangle(b)) => {
40                a.intersection(b).map_or(Self::Empty, Self::Rectangle)
41            }
42        }
43    }
44
45    /// Tests viewport and half-open clip bounds. Does not test the visual itself.
46    pub fn contains_pointer(self, sample: PointerSample) -> bool {
47        sample.is_inside_viewport() && self.contains(sample.position())
48    }
49
50    pub(super) fn contains(self, position: LogicalScreenPosition) -> bool {
51        let p = position.to_vec2();
52        match self {
53            Self::Unclipped => position.is_finite(),
54            Self::Empty => false,
55            Self::Rectangle(rect) => {
56                let min = rect.min().to_vec2();
57                let max = rect.max().to_vec2();
58                p.x() >= min.x() && p.y() >= min.y() && p.x() < max.x() && p.y() < max.y()
59            }
60        }
61    }
62}