forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBb0eb8adIvan Molodetskikh3 months ago2857 commits

region.rs320 lines, 10.1 KiBHistoryRawDownload
1use std::cmp::{max, min};
2use std::collections::BTreeSet;
3use std::sync::Arc;
4
5use smithay::utils::{Logical, Physical, Point, Rectangle, Scale};
6use smithay::wayland::compositor::{RectangleKind, RegionAttributes};
7
8/// Helper for fractionally transforming an i32 region while preserving adjacent rects.
9///
10/// Naively applying floating point transforms may cause adjacent rects to go misaligned due to
11/// rounding differences. This struct helps apply the transforms in such a way as to preserve
12/// alignment.
13#[derive(Debug, Clone)]
14pub struct TransformedRegion {
15 /// Non-overlapping rects (usually in surface-local coordinates).
16 pub rects: Arc<Vec<Rectangle<i32, Logical>>>,
17 /// Scale to apply to each rect.
18 pub scale: Scale<f64>,
19 /// Translation to apply to each rect after scaling.
20 pub offset: Point<f64, Logical>,
21}
22
23impl TransformedRegion {
24 /// Returns an iterator over the top-left and bottom-right corners of transformed rects.
25 pub fn iter(&self) -> impl Iterator<Item = (Point<f64, Logical>, Point<f64, Logical>)> + '_ {
26 self.rects.iter().map(|r| {
27 // Here we start in a happy i32 world where everything lines up, and rectangle loc +
28 // size is exactly equal to the adjacent rectangle's loc.
29 //
30 // Unfortunately, we're about to descend to the floating point hell. And we *really*
31 // want adjacent rects to remain adjacent no matter what. So we'll convert our rects to
32 // their extremities (rather than loc and size), and operate on those. Coordinates from
33 // adjacent rects will undergo exactly the same floating point operations, so when
34 // they're ultimately rounded to physical pixels, they will remain adjacent.
35 let r = r.to_f64();
36
37 let mut a = r.loc;
38 // f64 is enough to represent this i32 addition exactly.
39 let mut b = r.loc + r.size.to_point();
40
41 a = a.upscale(self.scale);
42 b = b.upscale(self.scale);
43
44 a += self.offset;
45 b += self.offset;
46
47 (a, b)
48 })
49 }
50
51 /// Intersects damage with this subregion.
52 pub fn filter_damage(
53 &self,
54 // Same coordinate space as self.iter().
55 crop: Rectangle<f64, Logical>,
56 dst: Rectangle<i32, Physical>,
57 damage: &[Rectangle<i32, Physical>],
58 filtered: &mut Vec<Rectangle<i32, Physical>>,
59 ) {
60 let scale = dst.size.to_f64() / crop.size;
61
62 let cs = crop.size.to_point();
63
64 for (mut a, mut b) in self.iter() {
65 // Convert to dst-relative.
66 a -= crop.loc;
67 b -= crop.loc;
68
69 // Intersect with crop.
70 let ia = Point::new(f64::max(a.x, 0.), f64::max(a.y, 0.));
71 let ib = Point::new(f64::min(b.x, cs.x), f64::min(b.y, cs.y));
72 if ib.x <= ia.x || ib.y <= ia.y {
73 // No intersection.
74 continue;
75 }
76
77 // Round extremities to physical pixels, ensuring that adjacent rectangles stay adjacent
78 // at fractional scales.
79 let ia = ia.to_physical_precise_round(scale);
80 let ib = ib.to_physical_precise_round(scale);
81
82 let r = Rectangle::from_extremities(ia, ib);
83
84 // Intersect with each damage rect.
85 for d in damage {
86 if let Some(intersection) = r.intersection(*d) {
87 filtered.push(intersection);
88 }
89 }
90 }
91 }
92}
93
94pub fn region_to_non_overlapping_rects(
95 region: &RegionAttributes,
96 output: &mut Vec<Rectangle<i32, Logical>>,
97) {
98 let _span = tracy_client::span!("region_to_non_overlapping_rects");
99
100 output.clear();
101
102 // Collect all unique Y coordinates.
103 let ys = BTreeSet::from_iter(
104 region
105 .rects
106 .iter()
107 .flat_map(|(_, r)| [r.loc.y, r.loc.y + r.size.h]),
108 );
109
110 let mut ys = ys.into_iter();
111 let Some(mut lo) = ys.next() else {
112 // The region was empty.
113 return;
114 };
115
116 // Sorted list of non-overlapping [start, end) tuples.
117 let mut spans = Vec::<(i32, i32)>::new();
118
119 // Iterate over Y bands.
120 for hi in ys {
121 spans.clear();
122
123 'region: for (kind, r) in &region.rects {
124 // Skip rects that don't overlap with the Y band.
125 if hi <= r.loc.y || r.loc.y + r.size.h <= lo {
126 continue;
127 }
128
129 let mut x1 = r.loc.x;
130 let mut x2 = r.loc.x + r.size.w;
131 if x1 == x2 {
132 // Empty rect.
133 continue;
134 }
135
136 match *kind {
137 RectangleKind::Add => {
138 // Iterate over existing spans backwards.
139 for i in (0..spans.len()).rev() {
140 let (start, end) = spans[i];
141
142 // New span is to the right.
143 if end < x1 {
144 spans.insert(i + 1, (x1, x2));
145 continue 'region;
146 }
147
148 // New span is to the left.
149 if x2 < start {
150 continue;
151 }
152
153 // New span overlaps this span; merge them.
154 spans.remove(i);
155 x1 = min(x1, start);
156 x2 = max(x2, end);
157 }
158
159 spans.insert(0, (x1, x2));
160 }
161 RectangleKind::Subtract => {
162 // Iterate over existing spans backwards.
163 for i in (0..spans.len()).rev() {
164 let (start, end) = spans[i];
165
166 // Subtract span is to the right.
167 if end <= x1 {
168 continue 'region;
169 }
170
171 // Subtract span is to the left.
172 if x2 <= start {
173 continue;
174 }
175
176 // Subtract span overlaps this span.
177 spans.remove(i);
178 if x2 < end {
179 spans.insert(i, (x2, end));
180 }
181 if start < x1 {
182 spans.insert(i, (start, x1));
183 }
184 }
185 }
186 }
187 }
188
189 for (x1, x2) in spans.drain(..) {
190 output.push(Rectangle::from_extremities((x1, lo), (x2, hi)));
191 }
192
193 lo = hi;
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 use std::fmt::Write as _;
200
201 use insta::assert_snapshot;
202 use proptest::prelude::*;
203 use smithay::utils::{Logical, Point, Rectangle, Size};
204 use smithay::wayland::compositor::{RectangleKind, RegionAttributes};
205
206 use super::region_to_non_overlapping_rects;
207
208 #[allow(clippy::type_complexity)]
209 fn check(rects: &[(RectangleKind, (i32, i32, i32, i32))]) -> String {
210 let region = RegionAttributes {
211 rects: rects
212 .iter()
213 .map(|(kind, (x1, y1, x2, y2))| {
214 (*kind, Rectangle::from_extremities((*x1, *y1), (*x2, *y2)))
215 })
216 .collect(),
217 };
218 let mut output = Vec::new();
219 region_to_non_overlapping_rects(&region, &mut output);
220 let mut s = String::new();
221 for r in &output {
222 let x1 = r.loc.x;
223 let y1 = r.loc.y;
224 let x2 = x1 + r.size.w;
225 let y2 = y1 + r.size.h;
226 writeln!(s, "{x1:2} {y1:2} - {x2:2} {y2:2}").unwrap();
227 }
228 s
229 }
230
231 #[test]
232 fn test_region_to_non_overlapping_rects() {
233 use RectangleKind::*;
234
235 // empty_region
236 assert_snapshot!(check(&[]), @"");
237
238 // single_rectangle
239 assert_snapshot!(check(&[(Add, (0, 0, 10, 10))]), @" 0 0 - 10 10");
240
241 // empty_rectangle
242 assert_snapshot!(check(&[(Add, (0, 0, 0, 1))]), @"");
243 assert_snapshot!(check(&[(Add, (0, 0, 1, 0))]), @"");
244
245 // two_non_overlapping
246 assert_snapshot!(
247 check(&[(Add, (0, 0, 5, 10)), (Add, (7, 0, 12, 10))]),
248 @"
249 0 0 - 5 10
250 7 0 - 12 10
251 "
252 );
253
254 // two_overlapping
255 assert_snapshot!(
256 check(&[(Add, (0, 0, 10, 10)), (Add, (5, 5, 15, 15))]),
257 @"
258 0 0 - 10 5
259 0 5 - 15 10
260 5 10 - 15 15
261 "
262 );
263
264 // subtraction
265 assert_snapshot!(
266 check(&[(Add, (0, 0, 20, 20)), (Subtract, (5, 5, 15, 15))]),
267 @"
268 0 0 - 20 5
269 0 5 - 5 15
270 15 5 - 20 15
271 0 15 - 20 20
272 "
273 );
274
275 // adjacent_rectangles
276 assert_snapshot!(
277 check(&[(Add, (0, 0, 10, 10)), (Add, (10, 0, 20, 10))]),
278 @" 0 0 - 20 10"
279 );
280 }
281
282 proptest! {
283 #[test]
284 fn non_overlapping_output(
285 rects in proptest::collection::vec(
286 (
287 prop_oneof![Just(RectangleKind::Add), Just(RectangleKind::Subtract)],
288 (0..20i32, 0..20i32, 0..20i32, 0..20i32),
289 ),
290 1..10,
291 )
292 ) {
293 let region = RegionAttributes {
294 rects: rects
295 .into_iter()
296 .map(|(kind, (x, y, w, h))| {
297 (kind, Rectangle::new(Point::new(x, y), Size::new(w, h)))
298 })
299 .collect(),
300 };
301
302 let mut output: Vec<Rectangle<i32, Logical>> = Vec::new();
303 region_to_non_overlapping_rects(&region, &mut output);
304
305 for i in 0..output.len() {
306 prop_assert!(!output[i].is_empty());
307
308 // Verify no pair of output rectangles overlaps.
309 for j in (i + 1)..output.len() {
310 prop_assert!(
311 !output[i].overlaps(output[j]),
312 "rectangles overlap: {:?} and {:?}",
313 output[i],
314 output[j],
315 );
316 }
317 }
318 }
319 }
320}