epaint/
viewport.rs

1use crate::Rect;
2
3/// Size of the viewport in whole, physical pixels.
4pub struct ViewportInPixels {
5    /// Physical pixel offset for left side of the viewport.
6    pub left_px: i32,
7
8    /// Physical pixel offset for top side of the viewport.
9    pub top_px: i32,
10
11    /// Physical pixel offset for bottom side of the viewport.
12    ///
13    /// This is what `glViewport`, `glScissor` etc expects for the y axis.
14    pub from_bottom_px: i32,
15
16    /// Viewport width in physical pixels.
17    pub width_px: i32,
18
19    /// Viewport height in physical pixels.
20    pub height_px: i32,
21}
22
23impl ViewportInPixels {
24    /// Convert from ui points.
25    pub fn from_points(rect: &Rect, pixels_per_point: f32, screen_size_px: [u32; 2]) -> Self {
26        // Fractional pixel values for viewports are generally valid, but may cause sampling issues
27        // and rounding errors might cause us to get out of bounds.
28
29        // Round:
30        let left_px = (pixels_per_point * rect.min.x).round() as i32; // inclusive
31        let top_px = (pixels_per_point * rect.min.y).round() as i32; // inclusive
32        let right_px = (pixels_per_point * rect.max.x).round() as i32; // exclusive
33        let bottom_px = (pixels_per_point * rect.max.y).round() as i32; // exclusive
34
35        // Clamp to screen:
36        let screen_width = screen_size_px[0] as i32;
37        let screen_height = screen_size_px[1] as i32;
38        let left_px = left_px.clamp(0, screen_width);
39        let right_px = right_px.clamp(left_px, screen_width);
40        let top_px = top_px.clamp(0, screen_height);
41        let bottom_px = bottom_px.clamp(top_px, screen_height);
42
43        let width_px = right_px - left_px;
44        let height_px = bottom_px - top_px;
45
46        Self {
47            left_px,
48            top_px,
49            from_bottom_px: screen_height - height_px - top_px,
50            width_px,
51            height_px,
52        }
53    }
54}