Skip to main content

euv_core/platform/viewport/
impl.rs

1use super::*;
2
3/// Default `1280 x 720` `1.0x` viewport metrics.
4impl Default for ViewportMetrics {
5    /// Returns a standard `1280 x 720` `1.0x` lossless viewport metrics snapshot.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default `1280 x 720` `1.0x` viewport metrics.
10    fn default() -> Self {
11        Self::from_logical(1280.0, 720.0, 1.0)
12    }
13}
14
15/// Construction, exact change detection, coordinate transforms, and tile planning for `ViewportMetrics`.
16impl ViewportMetrics {
17    /// Constructs lossless viewport metrics from exact logical dimensions and DPI scale without upper pixel clamping.
18    ///
19    /// # Arguments
20    ///
21    /// - `f64` - Logical viewport width in CSS/point coordinates.
22    /// - `f64` - Logical viewport height in CSS/point coordinates.
23    /// - `f32` - Active display DPI scale factor.
24    ///
25    /// # Returns
26    ///
27    /// - `Self` - Authoritative lossless viewport metrics.
28    #[must_use]
29    pub fn from_logical(logical_width: f64, logical_height: f64, scale_factor: f32) -> Self {
30        let safe_scale: f32 = clamp_viewport_scale(scale_factor);
31        let safe_lw: f64 = if logical_width.is_finite() && logical_width > 0.0 {
32            logical_width.max(1.0)
33        } else {
34            1.0
35        };
36        let safe_lh: f64 = if logical_height.is_finite() && logical_height > 0.0 {
37            logical_height.max(1.0)
38        } else {
39            1.0
40        };
41        let physical_width: u32 = compute_lossless_physical_dim(safe_lw, safe_scale);
42        let physical_height: u32 = compute_lossless_physical_dim(safe_lh, safe_scale);
43        Self {
44            logical_width: safe_lw,
45            logical_height: safe_lh,
46            physical_width,
47            physical_height,
48            scale_factor: safe_scale,
49        }
50    }
51
52    /// Constructs lossless viewport metrics from exact physical pixel dimensions and DPI scale.
53    ///
54    /// # Arguments
55    ///
56    /// - `u32` - Authoritative physical backing surface width in device pixels.
57    /// - `u32` - Authoritative physical backing surface height in device pixels.
58    /// - `f32` - Active display DPI scale factor.
59    ///
60    /// # Returns
61    ///
62    /// - `Self` - Authoritative lossless viewport metrics preserving exact integer backing size.
63    #[must_use]
64    pub fn from_physical(physical_width: u32, physical_height: u32, scale_factor: f32) -> Self {
65        let safe_scale: f32 = clamp_viewport_scale(scale_factor);
66        let safe_pw: u32 = physical_width.max(1);
67        let safe_ph: u32 = physical_height.max(1);
68        let scale_f64: f64 = f64::from(safe_scale);
69        let logical_width: f64 = (f64::from(safe_pw) / scale_f64).max(1.0);
70        let logical_height: f64 = (f64::from(safe_ph) / scale_f64).max(1.0);
71        Self {
72            logical_width,
73            logical_height,
74            physical_width: safe_pw,
75            physical_height: safe_ph,
76            scale_factor: safe_scale,
77        }
78    }
79
80    /// Constructs lossless viewport metrics from independent exact OS/DOM logical bounds and physical pixel counts.
81    ///
82    /// # Arguments
83    ///
84    /// - `f64` - Exact logical width reported by the host (e.g. `getBoundingClientRect().width` or `NSView.bounds.size.width`).
85    /// - `f64` - Exact logical height reported by the host.
86    /// - `u32` - Exact physical backing width in device pixels (e.g. `devicePixelContentBoxSize` or `CAMetalLayer.drawableSize`).
87    /// - `u32` - Exact physical backing height in device pixels.
88    /// - `f32` - Active display DPI scale factor.
89    ///
90    /// # Returns
91    ///
92    /// - `Self` - Authoritative viewport metrics preserving both exact logical geometry and exact backing pixels.
93    #[must_use]
94    pub fn from_exact(
95        logical_width: f64,
96        logical_height: f64,
97        physical_width: u32,
98        physical_height: u32,
99        scale_factor: f32,
100    ) -> Self {
101        let safe_scale: f32 = clamp_viewport_scale(scale_factor);
102        let safe_pw: u32 = physical_width.max(1);
103        let safe_ph: u32 = physical_height.max(1);
104        let scale_f64: f64 = f64::from(safe_scale);
105        let safe_lw: f64 = if logical_width.is_finite() && logical_width > 0.0 {
106            logical_width.max(1.0)
107        } else {
108            (f64::from(safe_pw) / scale_f64).max(1.0)
109        };
110        let safe_lh: f64 = if logical_height.is_finite() && logical_height > 0.0 {
111            logical_height.max(1.0)
112        } else {
113            (f64::from(safe_ph) / scale_f64).max(1.0)
114        };
115        Self {
116            logical_width: safe_lw,
117            logical_height: safe_lh,
118            physical_width: safe_pw,
119            physical_height: safe_ph,
120            scale_factor: safe_scale,
121        }
122    }
123
124    /// Returns `true` when physical pixel dimensions, bit-exact scale factor, or logical geometry changed beyond `VIEWPORT_LOGICAL_EPSILON`.
125    ///
126    /// # Arguments
127    ///
128    /// - `&Self` - Candidate updated viewport metrics.
129    /// - `Self` - Previously committed viewport metrics.
130    ///
131    /// # Returns
132    ///
133    /// - `bool` - `true` when any physical, scale, or sub-pixel logical change requires relayout/redraw.
134    #[must_use]
135    pub fn has_changed(&self, previous: Self) -> bool {
136        self.get_physical_width() != previous.get_physical_width()
137            || self.get_physical_height() != previous.get_physical_height()
138            || self.get_scale_factor().to_bits() != previous.get_scale_factor().to_bits()
139            || (self.get_logical_width() - previous.get_logical_width()).abs()
140                > VIEWPORT_LOGICAL_EPSILON
141            || (self.get_logical_height() - previous.get_logical_height()).abs()
142                > VIEWPORT_LOGICAL_EPSILON
143    }
144
145    /// Returns the exact horizontal physical-to-logical pixel ratio (`physical_width / logical_width`).
146    ///
147    /// # Arguments
148    ///
149    /// - `&Self` - Viewport metrics reference.
150    ///
151    /// # Returns
152    ///
153    /// - `f64` - Exact horizontal pixel density ratio.
154    #[must_use]
155    pub fn effective_scale_x(&self) -> f64 {
156        f64::from(self.get_physical_width()) / self.get_logical_width().max(1.0)
157    }
158
159    /// Returns the exact vertical physical-to-logical pixel ratio (`physical_height / logical_height`).
160    ///
161    /// # Arguments
162    ///
163    /// - `&Self` - Viewport metrics reference.
164    ///
165    /// # Returns
166    ///
167    /// - `f64` - Exact vertical pixel density ratio.
168    #[must_use]
169    pub fn effective_scale_y(&self) -> f64 {
170        f64::from(self.get_physical_height()) / self.get_logical_height().max(1.0)
171    }
172
173    /// Converts these viewport metrics into a `Size` in logical pixels for layout and UI queries.
174    ///
175    /// # Arguments
176    ///
177    /// - `&Self` - Viewport metrics reference.
178    ///
179    /// # Returns
180    ///
181    /// - `Size` - Logical `(width, height)` size.
182    #[must_use]
183    pub fn logical_size(&self) -> Size {
184        Size::new(
185            self.get_logical_width() as f32,
186            self.get_logical_height() as f32,
187        )
188    }
189
190    /// Returns total physical pixel count (`physical_width * physical_height`).
191    ///
192    /// # Arguments
193    ///
194    /// - `&Self` - Viewport metrics reference.
195    ///
196    /// # Returns
197    ///
198    /// - `u64` - Total physical surface area in device pixels.
199    #[must_use]
200    pub fn physical_pixel_area(&self) -> u64 {
201        u64::from(self.get_physical_width()).saturating_mul(u64::from(self.get_physical_height()))
202    }
203
204    /// Maps a logical coordinate `(logical_x, logical_y)` into exact global physical device pixel coordinates.
205    ///
206    /// # Arguments
207    ///
208    /// - `&Self` - Viewport metrics reference.
209    /// - `f64` - Logical X coordinate.
210    /// - `f64` - Logical Y coordinate.
211    ///
212    /// # Returns
213    ///
214    /// - `(f64, f64)` - Exact physical `(x, y)` coordinate in device pixels.
215    #[must_use]
216    pub fn logical_to_physical(&self, logical_x: f64, logical_y: f64) -> (f64, f64) {
217        (
218            logical_x * self.effective_scale_x(),
219            logical_y * self.effective_scale_y(),
220        )
221    }
222
223    /// Maps a global physical device pixel coordinate `(physical_x, physical_y)` back into exact logical coordinates.
224    ///
225    /// # Arguments
226    ///
227    /// - `&Self` - Viewport metrics reference.
228    /// - `f64` - Physical X coordinate in device pixels.
229    /// - `f64` - Physical Y coordinate in device pixels.
230    ///
231    /// # Returns
232    ///
233    /// - `(f64, f64)` - Exact logical `(x, y)` coordinate.
234    #[must_use]
235    pub fn physical_to_logical(&self, physical_x: f64, physical_y: f64) -> (f64, f64) {
236        (
237            physical_x / self.effective_scale_x(),
238            physical_y / self.effective_scale_y(),
239        )
240    }
241
242    /// Builds a lossless `TiledSurfacePlan` obeying `limits` with zero DPR reduction.
243    ///
244    /// # Arguments
245    ///
246    /// - `&Self` - Viewport metrics reference.
247    /// - `SurfaceTileLimit` - Hardware single-surface dimension and pixel-area ceiling.
248    ///
249    /// # Returns
250    ///
251    /// - `TiledSurfacePlan` - Single-surface or multi-tile 1:1 physical plan.
252    #[must_use]
253    pub fn plan_tiled_surface(&self, limits: SurfaceTileLimit) -> TiledSurfacePlan {
254        TiledSurfacePlan::build(*self, limits)
255    }
256}
257
258/// Default conservative WebGL2/GPU single-surface tile limits (`4096` max dim, `16.7 MP` max area).
259impl Default for SurfaceTileLimit {
260    /// Returns conservative single-surface limits (`4096` max texture dim, `16_777_216` max pixel area).
261    ///
262    /// # Returns
263    ///
264    /// - `Self` - Default hardware tile limits.
265    fn default() -> Self {
266        Self::new(DEFAULT_MAX_TEXTURE_DIM, DEFAULT_MAX_SURFACE_AREA)
267    }
268}
269
270/// Construction and capacity checks for `SurfaceTileLimit`.
271impl SurfaceTileLimit {
272    /// Creates a new `SurfaceTileLimit` clamped above `MIN_SURFACE_TILE_DIM`.
273    ///
274    /// # Arguments
275    ///
276    /// - `u32` - Maximum supported texture or drawing-buffer single-axis dimension in pixels.
277    /// - `u64` - Maximum supported single-surface pixel area (`width * height`).
278    ///
279    /// # Returns
280    ///
281    /// - `Self` - Validated hardware surface limit descriptor.
282    #[must_use]
283    pub fn new(max_texture_dim: u32, max_surface_area: u64) -> Self {
284        let safe_dim: u32 = max_texture_dim.max(MIN_SURFACE_TILE_DIM);
285        let min_area: u64 =
286            u64::from(MIN_SURFACE_TILE_DIM).saturating_mul(u64::from(MIN_SURFACE_TILE_DIM));
287        let safe_area: u64 = max_surface_area.max(min_area);
288        Self {
289            max_texture_dim: safe_dim,
290            max_surface_area: safe_area,
291        }
292    }
293
294    /// Returns `true` when `(physical_width, physical_height)` fits in one native surface without tiling.
295    ///
296    /// # Arguments
297    ///
298    /// - `&Self` - Hardware surface limit descriptor.
299    /// - `u32` - Physical surface width in device pixels.
300    /// - `u32` - Physical surface height in device pixels.
301    ///
302    /// # Returns
303    ///
304    /// - `bool` - `true` when a single backing surface can hold all physical pixels 1:1.
305    #[must_use]
306    pub fn fits_single_surface(&self, physical_width: u32, physical_height: u32) -> bool {
307        let area: u64 = u64::from(physical_width).saturating_mul(u64::from(physical_height));
308        physical_width <= self.get_max_texture_dim()
309            && physical_height <= self.get_max_texture_dim()
310            && area <= self.get_max_surface_area()
311    }
312}
313
314/// Exact tile partitioning, coverage validation, and 1:1 pointer hit-testing for `TiledSurfacePlan`.
315impl TiledSurfacePlan {
316    /// Partitions `viewport` into the minimum number of 1:1 physical tiles strictly obeying `limits` without dropping DPI.
317    ///
318    /// # Arguments
319    ///
320    /// - `ViewportMetrics` - Authoritative lossless viewport metrics.
321    /// - `SurfaceTileLimit` - Hardware single-surface dimension and pixel-area ceiling.
322    ///
323    /// # Returns
324    ///
325    /// - `Self` - Complete non-overlapping 1:1 physical tile plan covering 100% of `viewport`.
326    #[must_use]
327    pub fn build(viewport: ViewportMetrics, limits: SurfaceTileLimit) -> Self {
328        let phys_w: u32 = viewport.get_physical_width();
329        let phys_h: u32 = viewport.get_physical_height();
330        let logical_w: f64 = viewport.get_logical_width();
331        let logical_h: f64 = viewport.get_logical_height();
332        if limits.fits_single_surface(phys_w, phys_h) {
333            let single_tile: SurfaceTileRect = SurfaceTileRect {
334                tile_col: 0,
335                tile_row: 0,
336                physical_x: 0,
337                physical_y: 0,
338                physical_width: phys_w,
339                physical_height: phys_h,
340                logical_x: 0.0,
341                logical_y: 0.0,
342                logical_width: logical_w,
343                logical_height: logical_h,
344            };
345            return Self {
346                viewport,
347                limits,
348                columns: 1,
349                rows: 1,
350                tiled: false,
351                tiles: vec![single_tile],
352            };
353        }
354        let (tile_step_w, tile_step_h): (u32, u32) =
355            compute_effective_tile_dims(phys_w, phys_h, limits);
356        let columns: u32 = phys_w.div_ceil(tile_step_w).max(1);
357        let rows: u32 = phys_h.div_ceil(tile_step_h).max(1);
358        let scale_x: f64 = viewport.effective_scale_x();
359        let scale_y: f64 = viewport.effective_scale_y();
360        let tile_count: usize = (columns as usize).saturating_mul(rows as usize);
361        let mut tiles: Vec<SurfaceTileRect> = Vec::with_capacity(tile_count);
362        for row_idx in 0..rows {
363            let phys_y: u32 = row_idx.saturating_mul(tile_step_h);
364            let tile_phys_h: u32 = tile_step_h.min(phys_h.saturating_sub(phys_y));
365            let log_y: f64 = f64::from(phys_y) / scale_y;
366            let log_y_end: f64 = if row_idx + 1 == rows {
367                logical_h
368            } else {
369                f64::from(phys_y.saturating_add(tile_phys_h)) / scale_y
370            };
371            let tile_log_h: f64 = (log_y_end - log_y).max(0.0);
372            for col_idx in 0..columns {
373                let phys_x: u32 = col_idx.saturating_mul(tile_step_w);
374                let tile_phys_w: u32 = tile_step_w.min(phys_w.saturating_sub(phys_x));
375                let log_x: f64 = f64::from(phys_x) / scale_x;
376                let log_x_end: f64 = if col_idx + 1 == columns {
377                    logical_w
378                } else {
379                    f64::from(phys_x.saturating_add(tile_phys_w)) / scale_x
380                };
381                let tile_log_w: f64 = (log_x_end - log_x).max(0.0);
382                tiles.push(SurfaceTileRect {
383                    tile_col: col_idx,
384                    tile_row: row_idx,
385                    physical_x: phys_x,
386                    physical_y: phys_y,
387                    physical_width: tile_phys_w,
388                    physical_height: tile_phys_h,
389                    logical_x: log_x,
390                    logical_y: log_y,
391                    logical_width: tile_log_w,
392                    logical_height: tile_log_h,
393                });
394            }
395        }
396        Self {
397            viewport,
398            limits,
399            columns,
400            rows,
401            tiled: true,
402            tiles,
403        }
404    }
405
406    /// Verifies that every generated tile obeys `limits` and that the disjoint union of all tiles covers 100% of `viewport` physical pixels.
407    ///
408    /// # Arguments
409    ///
410    /// - `&Self` - Tiled surface plan reference.
411    ///
412    /// # Returns
413    ///
414    /// - `bool` - `true` when tile geometry is gapless, non-overlapping, and strictly within hardware ceilings.
415    #[must_use]
416    pub fn covers_entire_viewport(&self) -> bool {
417        let expected_count: usize =
418            (self.get_columns() as usize).saturating_mul(self.get_rows() as usize);
419        let tiles: &[SurfaceTileRect] = self.get_tiles().as_slice();
420        if tiles.len() != expected_count || expected_count == 0 {
421            return false;
422        }
423        let vp: ViewportMetrics = self.get_viewport();
424        let limits: SurfaceTileLimit = self.get_limits();
425        let cols: usize = self.get_columns() as usize;
426        let rows: usize = self.get_rows() as usize;
427        let mut covered_area: u64 = 0;
428        for row_idx in 0..rows {
429            let mut expected_x: u32 = 0;
430            let row_first: SurfaceTileRect = tiles[row_idx * cols];
431            let row_h: u32 = row_first.get_physical_height();
432            let expected_y: u32 = if row_idx == 0 {
433                0
434            } else {
435                let prev_row: SurfaceTileRect = tiles[(row_idx - 1) * cols];
436                prev_row
437                    .get_physical_y()
438                    .saturating_add(prev_row.get_physical_height())
439            };
440            for col_idx in 0..cols {
441                let tile: SurfaceTileRect = tiles[row_idx * cols + col_idx];
442                if tile.get_physical_x() != expected_x
443                    || tile.get_physical_y() != expected_y
444                    || tile.get_physical_height() != row_h
445                    || tile.get_physical_width() == 0
446                    || tile.get_physical_height() == 0
447                    || !limits
448                        .fits_single_surface(tile.get_physical_width(), tile.get_physical_height())
449                {
450                    return false;
451                }
452                expected_x = expected_x.saturating_add(tile.get_physical_width());
453                covered_area = covered_area.saturating_add(
454                    u64::from(tile.get_physical_width())
455                        .saturating_mul(u64::from(tile.get_physical_height())),
456                );
457            }
458            if expected_x != vp.get_physical_width() {
459                return false;
460            }
461        }
462        let last_tile: SurfaceTileRect = tiles[tiles.len() - 1];
463        let total_h: u32 = last_tile
464            .get_physical_y()
465            .saturating_add(last_tile.get_physical_height());
466        total_h == vp.get_physical_height() && covered_area == vp.physical_pixel_area()
467    }
468
469    /// Resolves a logical pointer coordinate `(logical_x, logical_y)` to its owning surface tile and tile-local physical coordinates.
470    ///
471    /// # Arguments
472    ///
473    /// - `&Self` - Tiled surface plan reference.
474    /// - `f64` - Pointer X coordinate in logical viewport space.
475    /// - `f64` - Pointer Y coordinate in logical viewport space.
476    ///
477    /// # Returns
478    ///
479    /// - `Option<TileHitResult>` - Owning tile and physical coordinates, or `None` when outside viewport bounds.
480    #[must_use]
481    pub fn hit_test_logical(&self, logical_x: f64, logical_y: f64) -> Option<TileHitResult> {
482        let vp: ViewportMetrics = self.get_viewport();
483        if !logical_x.is_finite()
484            || !logical_y.is_finite()
485            || logical_x < 0.0
486            || logical_y < 0.0
487            || logical_x > vp.get_logical_width()
488            || logical_y > vp.get_logical_height()
489        {
490            return None;
491        }
492        let (global_px, global_py): (f64, f64) = vp.logical_to_physical(logical_x, logical_y);
493        let max_px: f64 = f64::from(vp.get_physical_width());
494        let max_py: f64 = f64::from(vp.get_physical_height());
495        let clamped_px: f64 = global_px.clamp(0.0, max_px);
496        let clamped_py: f64 = global_py.clamp(0.0, max_py);
497        let cols: usize = self.get_columns() as usize;
498        let rows: usize = self.get_rows() as usize;
499        let tiles: &[SurfaceTileRect] = self.get_tiles().as_slice();
500        let mut hit_col: usize = cols.saturating_sub(1);
501        for (col_idx, &tile) in tiles.iter().enumerate().take(cols) {
502            let end_x: f64 = f64::from(
503                tile.get_physical_x()
504                    .saturating_add(tile.get_physical_width()),
505            );
506            if clamped_px < end_x || col_idx + 1 == cols {
507                hit_col = col_idx;
508                break;
509            }
510        }
511        let mut hit_row: usize = rows.saturating_sub(1);
512        for row_idx in 0..rows {
513            let tile: SurfaceTileRect = tiles[row_idx * cols];
514            let end_y: f64 = f64::from(
515                tile.get_physical_y()
516                    .saturating_add(tile.get_physical_height()),
517            );
518            if clamped_py < end_y || row_idx + 1 == rows {
519                hit_row = row_idx;
520                break;
521            }
522        }
523        let tile_index: usize = hit_row * cols + hit_col;
524        let tile: SurfaceTileRect = *tiles.get(tile_index)?;
525        Some(TileHitResult {
526            tile_index,
527            tile_col: tile.get_tile_col(),
528            tile_row: tile.get_tile_row(),
529            local_physical_x: clamped_px - f64::from(tile.get_physical_x()),
530            local_physical_y: clamped_py - f64::from(tile.get_physical_y()),
531            global_physical_x: clamped_px,
532            global_physical_y: clamped_py,
533        })
534    }
535
536    /// Converts a tile-local physical pixel coordinate back into exact global logical viewport coordinates.
537    ///
538    /// # Arguments
539    ///
540    /// - `&Self` - Tiled surface plan reference.
541    /// - `usize` - Row-major index into `tiles`.
542    /// - `f64` - Tile-local physical X coordinate.
543    /// - `f64` - Tile-local physical Y coordinate.
544    ///
545    /// # Returns
546    ///
547    /// - `Option<(f64, f64)>` - Global logical `(x, y)` coordinates, or `None` when `tile_index` is invalid.
548    #[must_use]
549    pub fn tile_local_to_logical(
550        &self,
551        tile_index: usize,
552        local_physical_x: f64,
553        local_physical_y: f64,
554    ) -> Option<(f64, f64)> {
555        let tile: SurfaceTileRect = *self.get_tiles().get(tile_index)?;
556        let global_px: f64 = f64::from(tile.get_physical_x()) + local_physical_x;
557        let global_py: f64 = f64::from(tile.get_physical_y()) + local_physical_y;
558        Some(
559            self.get_viewport()
560                .physical_to_logical(global_px, global_py),
561        )
562    }
563}