Skip to main content

euv_core/scene/damage/
impl.rs

1use super::*;
2
3/// Default empty `DirtyRectSet`.
4impl Default for DirtyRectSet {
5    /// Creates an empty `DirtyRectSet` with zero active rectangles.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Clean multi-rect dirty set.
10    fn default() -> Self {
11        Self::new()
12    }
13}
14
15/// Surgical multi-rect dirty tracking, union-waste strategy selection, and `DamageRegion` interop for `DirtyRectSet`.
16impl DirtyRectSet {
17    /// Creates an empty `DirtyRectSet`.
18    ///
19    /// # Returns
20    ///
21    /// - `Self` - Empty dirty rect set.
22    #[must_use]
23    pub const fn new() -> Self {
24        Self {
25            rects: [Rect {
26                x: 0.0,
27                y: 0.0,
28                width: 0.0,
29                height: 0.0,
30            }; DIRTY_RECT_SET_CAPACITY],
31            len: 0,
32            full_frame: false,
33            overflowed: false,
34        }
35    }
36
37    /// Creates a `DirtyRectSet` representing full-viewport damage.
38    ///
39    /// # Returns
40    ///
41    /// - `Self` - Full-frame dirty rect set.
42    #[must_use]
43    pub const fn full() -> Self {
44        let mut set: Self = Self::new();
45        set.full_frame = true;
46        set
47    }
48
49    /// Returns `true` when neither full-frame damage nor any active dirty rectangle is present.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Self` - Dirty rect set reference.
54    ///
55    /// # Returns
56    ///
57    /// - `bool` - `true` when clean.
58    #[must_use]
59    pub fn is_empty(&self) -> bool {
60        !self.get_full_frame() && self.get_len() == 0
61    }
62
63    /// Returns the active slice of disjoint physical damage rectangles.
64    ///
65    /// # Arguments
66    ///
67    /// - `&Self` - Dirty rect set reference.
68    ///
69    /// # Returns
70    ///
71    /// - `&[Rect]` - Active dirty rectangle slice.
72    #[must_use]
73    pub fn rects(&self) -> &[Rect] {
74        let Self { rects, len, .. } = self;
75        let clamped: usize = (*len).min(DIRTY_RECT_SET_CAPACITY);
76        &rects[..clamped]
77    }
78
79    /// Clears all rectangles and resets full-frame and overflow flags.
80    ///
81    /// # Arguments
82    ///
83    /// - `&Self` - Mutable dirty rect set.
84    pub fn clear(&mut self) {
85        let Self {
86            rects,
87            len,
88            full_frame,
89            overflowed,
90        } = self;
91        *rects = [Rect::default(); DIRTY_RECT_SET_CAPACITY];
92        *len = 0;
93        *full_frame = false;
94        *overflowed = false;
95    }
96
97    /// Builds a `DirtyRectSet` from an existing `DamageRegion` clipped to `(width, height)`.
98    ///
99    /// # Arguments
100    ///
101    /// - `DamageRegion` - Source damage region.
102    /// - `u32` - Physical viewport width in pixels.
103    /// - `u32` - Physical viewport height in pixels.
104    ///
105    /// # Returns
106    ///
107    /// - `Self` - Equivalent bounded multi-rect dirty set.
108    #[must_use]
109    pub fn from_damage_region(damage: DamageRegion, width: u32, height: u32) -> Self {
110        if damage.get_full_damage() {
111            return Self::full();
112        }
113        let mut out: Self = Self::new();
114        let (rects, count): ([Rect; 8], usize) = damage.normalized_rects(width, height);
115        for item in rects.iter().take(count).copied() {
116            out.add_rect_clamped(item, width, height);
117        }
118        out
119    }
120
121    /// Adds a physical damage rectangle clipped to `(width, height)`, merging only overlapping or touching rectangles so distant rects remain disjoint.
122    ///
123    /// # Arguments
124    ///
125    /// - `&Self` - Mutable dirty rect set.
126    /// - `Rect` - Incoming damage rectangle in physical pixels.
127    /// - `u32` - Physical viewport width in pixels.
128    /// - `u32` - Physical viewport height in pixels.
129    pub fn add_rect_clamped(&mut self, rect: Rect, width: u32, height: u32) {
130        if width == 0 || height == 0 {
131            return;
132        }
133        let viewport: Rect = Rect::new(0.0, 0.0, width as f32, height as f32);
134        let Some(clamped) = rect.intersect(viewport) else {
135            return;
136        };
137        if clamped.get_width() <= 0.0 || clamped.get_height() <= 0.0 {
138            return;
139        }
140        self.add_rect(clamped);
141    }
142
143    /// Adds a physical damage rectangle, coalescing only overlapping or touching rectangles and keeping distant rectangles separate up to `DIRTY_RECT_SET_CAPACITY`.
144    ///
145    /// # Arguments
146    ///
147    /// - `&Self` - Mutable dirty rect set.
148    /// - `Rect` - Incoming non-empty damage rectangle.
149    pub fn add_rect(&mut self, rect: Rect) {
150        if self.get_full_frame()
151            || !rect.get_x().is_finite()
152            || !rect.get_y().is_finite()
153            || !rect.get_width().is_finite()
154            || !rect.get_height().is_finite()
155            || rect.get_width() <= 0.0
156            || rect.get_height() <= 0.0
157        {
158            return;
159        }
160        let mut candidate: Rect = rect;
161        let Self {
162            rects,
163            len,
164            full_frame,
165            overflowed,
166        } = self;
167        let mut merged_pass: bool = true;
168        while merged_pass {
169            merged_pass = false;
170            let mut idx: usize = 0;
171            while idx < *len {
172                if Self::rects_overlap_or_touch(rects[idx], candidate, DIRTY_RECT_OVERLAP_PAD_PX) {
173                    candidate = rects[idx].union(candidate);
174                    let last: usize = (*len).saturating_sub(1);
175                    rects[idx] = rects[last];
176                    rects[last] = Rect::default();
177                    *len = last;
178                    merged_pass = true;
179                } else {
180                    idx += 1;
181                }
182            }
183        }
184        if *len < DIRTY_RECT_SET_CAPACITY {
185            rects[*len] = candidate;
186            *len += 1;
187            return;
188        }
189        let mut best_idx: usize = 0;
190        let mut best_waste: f32 = f32::INFINITY;
191        let cand_area: f32 = candidate.get_width() * candidate.get_height();
192        for (idx, existing) in rects.iter().take(*len).enumerate() {
193            let ex_area: f32 = existing.get_width() * existing.get_height();
194            let rect_bounds: Rect = existing.union(candidate);
195            let u_area: f32 = rect_bounds.get_width() * rect_bounds.get_height();
196            let waste: f32 = (u_area - (ex_area + cand_area)).max(0.0);
197            if waste < best_waste {
198                best_waste = waste;
199                best_idx = idx;
200            }
201        }
202        let best_ex_area: f32 = rects[best_idx].get_width() * rects[best_idx].get_height();
203        if best_waste <= (best_ex_area + cand_area) * DIRTY_RECT_MERGE_WASTE_RATIO {
204            rects[best_idx] = rects[best_idx].union(candidate);
205        } else {
206            *full_frame = true;
207            *overflowed = true;
208            *len = 0;
209            *rects = [Rect::default(); DIRTY_RECT_SET_CAPACITY];
210        }
211    }
212
213    /// Returns `true` when `a` and `b` intersect or lie within `pad_px` pixels of each other.
214    ///
215    /// # Arguments
216    ///
217    /// - `Rect` - First rectangle.
218    /// - `Rect` - Second rectangle.
219    /// - `f32` - Touching tolerance in pixels.
220    ///
221    /// # Returns
222    ///
223    /// - `bool` - `true` when the rectangles overlap or touch.
224    #[must_use]
225    fn rects_overlap_or_touch(rect_bounds: Rect, clip_bounds: Rect, pad_px: f32) -> bool {
226        let a_right: f32 = rect_bounds.get_x() + rect_bounds.get_width() + pad_px;
227        let a_bottom: f32 = rect_bounds.get_y() + rect_bounds.get_height() + pad_px;
228        let b_right: f32 = clip_bounds.get_x() + clip_bounds.get_width() + pad_px;
229        let b_bottom: f32 = clip_bounds.get_y() + clip_bounds.get_height() + pad_px;
230        rect_bounds.get_x() <= b_right
231            && clip_bounds.get_x() <= a_right
232            && rect_bounds.get_y() <= b_bottom
233            && clip_bounds.get_y() <= a_bottom
234    }
235
236    /// Computes the union bounding box spanning all active dirty rectangles.
237    ///
238    /// # Arguments
239    ///
240    /// - `&Self` - Dirty rect set reference.
241    ///
242    /// # Returns
243    ///
244    /// - `Option<Rect>` - Tight union bounding box, or `None` if empty.
245    #[must_use]
246    pub fn merged_bbox(&self) -> Option<Rect> {
247        let slice: &[Rect] = self.rects();
248        let first: Rect = *slice.first()?;
249        let mut acc: Rect = first;
250        for rect in slice.iter().skip(1).copied() {
251            acc = acc.union(rect);
252        }
253        Some(acc)
254    }
255
256    /// Computes the sum of areas of all active disjoint dirty rectangles.
257    ///
258    /// # Arguments
259    ///
260    /// - `&Self` - Dirty rect set reference.
261    ///
262    /// # Returns
263    ///
264    /// - `f32` - Aggregate dirty pixel area.
265    #[must_use]
266    pub fn total_dirty_area(&self) -> f32 {
267        let mut sum: f32 = 0.0;
268        for rect in self.rects().iter() {
269            sum += rect.get_width().max(0.0) * rect.get_height().max(0.0);
270        }
271        sum
272    }
273
274    /// Computes the bounding-box merge waste ratio `(bbox_area - sum_area) / sum_area`.
275    ///
276    /// # Arguments
277    ///
278    /// - `&Self` - Dirty rect set reference.
279    ///
280    /// # Returns
281    ///
282    /// - `f32` - Non-negative waste ratio (`0.0` when `<= 1` rect or clean).
283    #[must_use]
284    pub fn union_waste_ratio(&self) -> f32 {
285        if self.get_full_frame() || self.get_len() <= 1 {
286            return 0.0;
287        }
288        let sum_area: f32 = self.total_dirty_area();
289        if sum_area <= 0.0 {
290            return 0.0;
291        }
292        let Some(bbox) = self.merged_bbox() else {
293            return 0.0;
294        };
295        let bbox_area: f32 = bbox.get_width().max(0.0) * bbox.get_height().max(0.0);
296        (bbox_area - sum_area).max(0.0) / sum_area
297    }
298
299    /// Selects the optimal submission strategy (`Empty`, `MultiRect`, `MergedBbox`, or `FullFrame`) using viewport coverage and union-area waste ratio.
300    ///
301    /// # Arguments
302    ///
303    /// - `&Self` - Dirty rect set reference.
304    /// - `u32` - Physical viewport width in pixels.
305    /// - `u32` - Physical viewport height in pixels.
306    /// - `f32` - Area coverage threshold in `(0.1..=1.0]` promoting to `FullFrame`.
307    /// - `f32` - Union-area waste ratio threshold above which disjoint rects stay `MultiRect`.
308    ///
309    /// # Returns
310    ///
311    /// - `DirtyRectStrategy` - Selected dirty-region execution strategy.
312    #[must_use]
313    pub fn select_strategy(
314        &self,
315        viewport_w: u32,
316        viewport_h: u32,
317        full_ratio_threshold: f32,
318        merge_waste_ratio: f32,
319    ) -> DirtyRectStrategy {
320        if self.is_empty() || viewport_w == 0 || viewport_h == 0 {
321            return DirtyRectStrategy::Empty;
322        }
323        if self.get_full_frame() || self.get_overflowed() {
324            return DirtyRectStrategy::FullFrame;
325        }
326        let vp_area: f32 = (viewport_w as f32) * (viewport_h as f32);
327        let threshold: f32 = full_ratio_threshold.clamp(0.1, 1.0);
328        let dirty_area: f32 = self.total_dirty_area();
329        if dirty_area / vp_area >= threshold {
330            return DirtyRectStrategy::FullFrame;
331        }
332        if self.get_len() <= 1 {
333            return DirtyRectStrategy::MergedBbox;
334        }
335        let waste_limit: f32 = merge_waste_ratio.max(0.0);
336        if self.union_waste_ratio() <= waste_limit {
337            DirtyRectStrategy::MergedBbox
338        } else {
339            DirtyRectStrategy::MultiRect
340        }
341    }
342
343    /// Selects the optimal submission strategy using default thresholds (`0.70` full-frame coverage, `0.35` merge waste ratio).
344    ///
345    /// # Arguments
346    ///
347    /// - `&Self` - Dirty rect set reference.
348    /// - `u32` - Physical viewport width in pixels.
349    /// - `u32` - Physical viewport height in pixels.
350    ///
351    /// # Returns
352    ///
353    /// - `DirtyRectStrategy` - Selected dirty-region execution strategy.
354    #[must_use]
355    pub fn select_default_strategy(&self, viewport_w: u32, viewport_h: u32) -> DirtyRectStrategy {
356        self.select_strategy(
357            viewport_w,
358            viewport_h,
359            DIRTY_RECT_FULL_FRAME_THRESHOLD,
360            DIRTY_RECT_MERGE_WASTE_RATIO,
361        )
362    }
363
364    /// Returns `true` when any active dirty rectangle intersects `region` (or when `full_frame` is set).
365    ///
366    /// # Arguments
367    ///
368    /// - `&Self` - Dirty rect set reference.
369    /// - `Rect` - Physical query rectangle.
370    ///
371    /// # Returns
372    ///
373    /// - `bool` - `true` if `region` overlaps any damaged area.
374    #[must_use]
375    pub fn intersects_rect(&self, region: Rect) -> bool {
376        if self.get_full_frame() {
377            return true;
378        }
379        self.rects()
380            .iter()
381            .any(|rect_bounds: &Rect| rect_bounds.intersect(region).is_some())
382    }
383
384    /// Converts this `DirtyRectSet` into a `DamageRegion` honoring `strategy` without collapsing disjoint `MultiRect` regions into a single giant bbox.
385    ///
386    /// # Arguments
387    ///
388    /// - `&Self` - Dirty rect set reference.
389    /// - `u32` - Physical viewport width in pixels.
390    /// - `u32` - Physical viewport height in pixels.
391    /// - `DirtyRectStrategy` - Chosen dirty-region submission strategy.
392    ///
393    /// # Returns
394    ///
395    /// - `DamageRegion` - Resulting renderer/platform damage region.
396    #[must_use]
397    pub fn to_damage_region(
398        &self,
399        viewport_w: u32,
400        viewport_h: u32,
401        strategy: DirtyRectStrategy,
402    ) -> DamageRegion {
403        match strategy {
404            DirtyRectStrategy::Empty => DamageRegion::default(),
405            DirtyRectStrategy::FullFrame => DamageRegion::full(),
406            DirtyRectStrategy::MergedBbox => {
407                let mut out: DamageRegion = DamageRegion::default();
408                if let Some(bbox) = self.merged_bbox() {
409                    let rect_bounds: Rect =
410                        Rect::new(0.0, 0.0, viewport_w as f32, viewport_h as f32);
411                    if let Some(clamped) = bbox.intersect(rect_bounds) {
412                        out.add_rect(clamped);
413                    }
414                }
415                out
416            }
417            DirtyRectStrategy::MultiRect => {
418                let mut out: DamageRegion = DamageRegion::default();
419                let clip_bounds: Rect = Rect::new(0.0, 0.0, viewport_w as f32, viewport_h as f32);
420                for rect in self.rects() {
421                    if let Some(clamped) = rect.intersect(clip_bounds) {
422                        out.add_rect(clamped);
423                    }
424                }
425                out
426            }
427        }
428    }
429
430    /// Evaluates surgical effect-dependency damage across visible portals and backdrop-blur regions, expanding ONLY intersecting or dirty regions by `ceil(2.0 * blur_radius)`.
431    ///
432    /// # Arguments
433    ///
434    /// - `&Self` - Mutable dirty rect set in physical pixels.
435    /// - `&[PortalBackdropRegion]` - Visible portal and backdrop-blur descriptors in logical coordinates.
436    /// - `u32` - Physical viewport width in pixels.
437    /// - `u32` - Physical viewport height in pixels.
438    /// - `f32` - Active display scale factor.
439    /// - `f32` - Area coverage threshold in `(0.1..=1.0]` promoting to `FullFrame`.
440    ///
441    /// # Returns
442    ///
443    /// - `EffectDamageReport` - Counts of expanded/skipped regions and whether full-frame escalation occurred.
444    pub fn apply_effect_dependency_damage(
445        &mut self,
446        regions: &[PortalBackdropRegion],
447        viewport_w: u32,
448        viewport_h: u32,
449        scale: f32,
450        full_ratio_threshold: f32,
451    ) -> EffectDamageReport {
452        if self.get_full_frame() {
453            return EffectDamageReport::new(0, regions.len(), true);
454        }
455        if regions.is_empty() || viewport_w == 0 || viewport_h == 0 {
456            return EffectDamageReport::new(0, 0, false);
457        }
458        let safe_scale: f32 = scale.max(0.5);
459        let region_count: usize = regions.len();
460        let mut applied: Vec<bool> = vec![false; region_count];
461        let mut expanded_regions: usize = 0;
462        let mut changed: bool = true;
463        while changed && !self.get_full_frame() {
464            changed = false;
465            for (idx, region) in regions.iter().enumerate() {
466                if applied[idx] {
467                    continue;
468                }
469                let bounds: Rect = region.get_bounds();
470                if bounds.get_width() <= 0.0 || bounds.get_height() <= 0.0 {
471                    applied[idx] = true;
472                    continue;
473                }
474                let blur_r: f32 = region.get_blur_radius().max(0.0);
475                let logical_halo: f32 = (EFFECT_BLUR_HALO_MULTIPLIER * blur_r).ceil();
476                let expanded_logical: Rect = Rect::new(
477                    bounds.get_x() - logical_halo,
478                    bounds.get_y() - logical_halo,
479                    bounds.get_width() + logical_halo * 2.0,
480                    bounds.get_height() + logical_halo * 2.0,
481                );
482                let expanded_phys: Rect = Rect::new(
483                    (expanded_logical.get_x() * safe_scale).floor(),
484                    (expanded_logical.get_y() * safe_scale).floor(),
485                    (expanded_logical.get_width() * safe_scale).ceil(),
486                    (expanded_logical.get_height() * safe_scale).ceil(),
487                );
488                let should_expand: bool =
489                    region.get_is_dirty() || self.intersects_rect(expanded_phys);
490                if should_expand {
491                    self.add_rect_clamped(expanded_phys, viewport_w, viewport_h);
492                    applied[idx] = true;
493                    expanded_regions += 1;
494                    changed = true;
495                }
496            }
497        }
498        let vp_area: f32 = (viewport_w as f32) * (viewport_h as f32);
499        let threshold: f32 = full_ratio_threshold.clamp(0.1, 1.0);
500        let escalated: bool = self.get_full_frame()
501            || self.get_overflowed()
502            || (vp_area > 0.0 && self.total_dirty_area() / vp_area >= threshold);
503        if escalated {
504            *self = Self::full();
505        }
506        let skipped_regions: usize = region_count.saturating_sub(expanded_regions);
507        EffectDamageReport::new(expanded_regions, skipped_regions, escalated)
508    }
509
510    /// Bridges this dirty-rect set's selected `DirtyRectStrategy` directly into the unified `UploadStrategy`.
511    ///
512    /// # Arguments
513    ///
514    /// - `&Self` - Dirty rect set reference.
515    /// - `u32` - Physical viewport width in pixels.
516    /// - `u32` - Physical viewport height in pixels.
517    ///
518    /// # Returns
519    ///
520    /// - `UploadStrategy` - Unified upload strategy (`None`, `MultiRect`, `MergedBbox`, or `FullFrame`).
521    #[must_use]
522    pub fn upload_strategy(&self, viewport_w: u32, viewport_h: u32) -> UploadStrategy {
523        let strategy: DirtyRectStrategy = self.select_strategy(
524            viewport_w,
525            viewport_h,
526            DIRTY_RECT_FULL_FRAME_THRESHOLD,
527            DIRTY_RECT_MERGE_WASTE_RATIO,
528        );
529        UploadStrategy::from_dirty_rect_strategy(strategy)
530    }
531
532    /// Bridges this dirty-rect set's selected `DirtyRectStrategy` directly into `MobileUploadStrategy`.
533    ///
534    /// # Arguments
535    ///
536    /// - `&Self` - Dirty rect set reference.
537    /// - `u32` - Physical viewport width in pixels.
538    /// - `u32` - Physical viewport height in pixels.
539    ///
540    /// # Returns
541    ///
542    /// - `MobileUploadStrategy` - Mobile upload strategy (`None`, `MultiRect`, `MergedBbox`, or `FullFrame`).
543    #[must_use]
544    pub fn mobile_upload_strategy(&self, viewport_w: u32, viewport_h: u32) -> MobileUploadStrategy {
545        self.upload_strategy(viewport_w, viewport_h)
546            .to_mobile_upload_strategy()
547    }
548}