1use std::collections::{HashMap, HashSet};
13
14use crate::element::LayerPaint;
15use crate::geometry::{Point, Rect, Size};
16use crate::id::LayerId;
17use crate::paint::LayerEffect;
18
19#[derive(Clone, Copy, Debug, PartialEq)]
21pub struct Affine2D {
22 pub a: f32,
23 pub b: f32,
24 pub c: f32,
25 pub d: f32,
26 pub tx: f32,
27 pub ty: f32,
28}
29
30impl Affine2D {
31 pub const IDENTITY: Self = Self { a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0 };
32
33 pub fn translate(x: f32, y: f32) -> Self {
34 Self { tx: x, ty: y, ..Self::IDENTITY }
35 }
36
37 pub fn then(&self, inner: &Self) -> Self {
39 Self {
40 a: self.a * inner.a + self.b * inner.c,
41 b: self.a * inner.b + self.b * inner.d,
42 c: self.c * inner.a + self.d * inner.c,
43 d: self.c * inner.b + self.d * inner.d,
44 tx: self.a * inner.tx + self.b * inner.ty + self.tx,
45 ty: self.c * inner.tx + self.d * inner.ty + self.ty,
46 }
47 }
48
49 pub fn apply(&self, p: Point) -> Point {
50 Point::new(self.a * p.x + self.b * p.y + self.tx, self.c * p.x + self.d * p.y + self.ty)
51 }
52
53 pub fn apply_rect(&self, rect: Rect) -> Rect {
54 let p0 = self.apply(Point::new(rect.x, rect.y));
55 let p1 = self.apply(Point::new(rect.x + rect.width, rect.y));
56 let p2 = self.apply(Point::new(rect.x, rect.y + rect.height));
57 let p3 = self.apply(Point::new(rect.x + rect.width, rect.y + rect.height));
58 let min_x = p0.x.min(p1.x).min(p2.x).min(p3.x);
59 let min_y = p0.y.min(p1.y).min(p2.y).min(p3.y);
60 let max_x = p0.x.max(p1.x).max(p2.x).max(p3.x);
61 let max_y = p0.y.max(p1.y).max(p2.y).max(p3.y);
62 Rect::new(min_x, min_y, max_x - min_x, max_y - min_y)
63 }
64
65 pub fn scale_hint(&self) -> f32 {
67 let sx = (self.a * self.a + self.c * self.c).sqrt();
68 let sy = (self.b * self.b + self.d * self.d).sqrt();
69 (sx + sy) * 0.5
70 }
71}
72
73#[derive(Clone, Copy, Debug, PartialEq)]
74pub struct ClipShape {
75 pub rect: Rect,
77 pub radius: f32,
78}
79
80#[derive(Clone, Debug)]
81pub struct LayerComposition {
82 pub affine: Affine2D,
84 pub opacity: f32,
85 pub clips: Vec<ClipShape>,
87}
88
89impl LayerComposition {
90 pub fn single(layer: &LayerPaint, size: Size) -> Self {
91 let own = own_effect(layer.effect, size);
92 let placement = Affine2D::translate(layer.offset.x, layer.offset.y);
93 let affine = placement.then(&own.affine);
94 let mut clips = Vec::new();
95 if let Some(radius) = own.clip_radius {
96 if radius > 0.0 {
97 clips.push(ClipShape {
98 rect: affine.apply_rect(Rect::new(0.0, 0.0, size.width, size.height)),
99 radius: radius * affine.scale_hint(),
100 });
101 }
102 }
103 Self { affine, opacity: own.opacity, clips }
104 }
105}
106
107pub struct OwnEffect {
108 pub affine: Affine2D,
109 pub opacity: f32,
110 pub clip_radius: Option<f32>,
111}
112
113pub fn own_effect(effect: LayerEffect, size: Size) -> OwnEffect {
114 match effect {
115 LayerEffect::None => OwnEffect { affine: Affine2D::IDENTITY, opacity: 1.0, clip_radius: None },
116 LayerEffect::Opacity(a) => {
117 OwnEffect { affine: Affine2D::IDENTITY, opacity: a.clamp(0.0, 1.0), clip_radius: None }
118 }
119 LayerEffect::Transform(t) if !t.is_identity() => {
120 let (sin, cos) = t.rotation.sin_cos();
121 let cx = size.width * 0.5;
122 let cy = size.height * 0.5;
123 let a = cos * t.scale_x;
124 let b = -sin * t.scale_y;
125 let c = sin * t.scale_x;
126 let d = cos * t.scale_y;
127 OwnEffect {
128 affine: Affine2D {
129 a,
130 b,
131 c,
132 d,
133 tx: cx + t.translate.x - (a * cx + b * cy),
134 ty: cy + t.translate.y - (c * cx + d * cy),
135 },
136 opacity: 1.0,
137 clip_radius: None,
138 }
139 }
140 LayerEffect::Transform(_) => OwnEffect { affine: Affine2D::IDENTITY, opacity: 1.0, clip_radius: None },
141 LayerEffect::ClipRRect(def) => {
142 OwnEffect { affine: Affine2D::IDENTITY, opacity: 1.0, clip_radius: Some(def.radius.max(0.0)) }
143 }
144 }
145}
146
147pub fn resolve_layer_compositions(
153 layers: &[LayerPaint],
154 sizes: &HashMap<LayerId, Size>,
155) -> HashMap<LayerId, LayerComposition> {
156 let mut scratch = CompositionScratch::default();
157 scratch.resolve(layers, sizes);
158 scratch.into_map()
159}
160
161#[derive(Default)]
166pub struct CompositionScratch {
167 by_id: HashMap<LayerId, usize>,
168 memo: HashMap<LayerId, LayerComposition>,
169 visiting: HashSet<LayerId>,
170}
171
172impl CompositionScratch {
173 pub fn resolve(&mut self, layers: &[LayerPaint], sizes: &HashMap<LayerId, Size>) {
175 self.by_id.clear();
176 self.by_id.extend(layers.iter().enumerate().map(|(i, lp)| (lp.layer_id, i)));
177 self.memo.clear();
178 self.visiting.clear();
179 for i in 0..layers.len() {
180 self.resolve_one(i, layers, sizes);
181 }
182 }
183
184 pub fn get(&self, layer_id: LayerId) -> Option<&LayerComposition> {
186 self.memo.get(&layer_id)
187 }
188
189 fn into_map(mut self) -> HashMap<LayerId, LayerComposition> {
190 std::mem::take(&mut self.memo)
191 }
192
193 fn resolve_one(&mut self, idx: usize, layers: &[LayerPaint], sizes: &HashMap<LayerId, Size>) -> LayerComposition {
194 let lp = &layers[idx];
195 if let Some(c) = self.memo.get(&lp.layer_id) {
196 return c.clone();
197 }
198 if !self.visiting.insert(lp.layer_id) {
199 let comp = LayerComposition::single(lp, layer_size(lp, sizes));
201 self.memo.insert(lp.layer_id, comp.clone());
202 return comp;
203 }
204
205 let size = layer_size(lp, sizes);
206 let own = own_effect(lp.effect, size);
207 let parent_idx = lp.parent.and_then(|pid| self.by_id.get(&pid).copied());
208 let (parent_affine, parent_opacity, mut clips, parent_offset) = match parent_idx {
209 Some(pi) => {
210 let pc = self.resolve_one(pi, layers, sizes);
211 (pc.affine, pc.opacity, pc.clips, layers[pi].offset)
212 }
213 None => (Affine2D::IDENTITY, 1.0, Vec::new(), Point::ZERO),
214 };
215
216 let local_offset = Point::new(lp.offset.x - parent_offset.x, lp.offset.y - parent_offset.y);
217 let affine = parent_affine.then(&Affine2D::translate(local_offset.x, local_offset.y)).then(&own.affine);
218
219 if let Some(radius) = own.clip_radius {
220 if radius > 0.0 {
221 clips.push(ClipShape {
222 rect: affine.apply_rect(Rect::new(0.0, 0.0, size.width, size.height)),
223 radius: radius * affine.scale_hint(),
224 });
225 if clips.len() > 2 {
227 clips.remove(0);
228 }
229 }
230 }
231
232 self.visiting.remove(&lp.layer_id);
233 let comp = LayerComposition { affine, opacity: (parent_opacity * own.opacity).clamp(0.0, 1.0), clips };
234 self.memo.insert(lp.layer_id, comp.clone());
235 comp
236 }
237}
238
239fn layer_size(lp: &LayerPaint, sizes: &HashMap<LayerId, Size>) -> Size {
240 sizes.get(&lp.layer_id).copied().or(lp.logical_size).unwrap_or(Size::ZERO)
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246 use crate::arena::Arena;
247
248 fn new_ids(n: usize) -> Vec<LayerId> {
249 let mut arena = Arena::<LayerId, ()>::new();
250 (0..n).map(|_| arena.insert(())).collect()
251 }
252
253 fn layer(id: LayerId, offset: Point, effect: LayerEffect) -> LayerPaint {
254 LayerPaint {
255 layer_id: id,
256 paint_list: std::rc::Rc::new(crate::paint::PaintList::new()),
257 is_dirty: false,
258 parent: None,
259 offset,
260 logical_size: Some(Size::new(100.0, 50.0)),
261 effect,
262 }
263 }
264
265 #[test]
266 fn opacity_and_translation_accumulate() {
267 let ids = new_ids(2);
268 let mut child = layer(ids[1], Point::new(10.0, 20.0), LayerEffect::Opacity(0.5));
269 child.parent = Some(ids[0]);
270 let parent = layer(ids[0], Point::new(5.0, 6.0), LayerEffect::Opacity(0.4));
271 let layers = vec![parent, child];
272 let sizes =
273 layers.iter().map(|lp| (lp.layer_id, lp.logical_size.unwrap_or(Size::ZERO))).collect::<HashMap<_, _>>();
274 let comps = resolve_layer_compositions(&layers, &sizes);
275 let c = &comps[&ids[1]];
276 assert!((c.opacity - 0.2).abs() < 1e-6, "父透明度应乘到子层");
277 assert_eq!(c.affine.apply(Point::ZERO), Point::new(10.0, 20.0));
279 }
280
281 #[test]
282 fn clip_keeps_at_most_two_layers() {
283 let ids = new_ids(3);
284 let mut l1 = layer(ids[0], Point::ZERO, LayerEffect::ClipRRect(crate::RRectDef { radius: 4.0 }));
285 let mut l2 = layer(ids[1], Point::ZERO, LayerEffect::ClipRRect(crate::RRectDef { radius: 6.0 }));
286 let mut l3 = layer(ids[2], Point::ZERO, LayerEffect::ClipRRect(crate::RRectDef { radius: 8.0 }));
287 l2.parent = Some(l1.layer_id);
288 l3.parent = Some(l2.layer_id);
289 l1.parent = None;
290 let layers = vec![l1, l2, l3];
291 let sizes =
292 layers.iter().map(|lp| (lp.layer_id, lp.logical_size.unwrap_or(Size::ZERO))).collect::<HashMap<_, _>>();
293 let comps = resolve_layer_compositions(&layers, &sizes);
294 assert_eq!(comps[&ids[2]].clips.len(), 2, "最多保留最内两层 clip");
295 }
296
297 #[test]
299 fn composition_scratch_matches_eager_and_clears_between_frames() {
300 let ids = new_ids(3);
301 let mut parent = layer(ids[0], Point::new(10.0, 20.0), LayerEffect::Opacity(0.5));
302 let mut child = layer(ids[1], Point::new(12.0, 26.0), LayerEffect::None);
303 child.parent = Some(parent.layer_id);
304 parent.parent = None;
305 let layers = vec![parent, child];
306 let sizes =
307 layers.iter().map(|lp| (lp.layer_id, lp.logical_size.unwrap_or(Size::ZERO))).collect::<HashMap<_, _>>();
308
309 let eager = resolve_layer_compositions(&layers, &sizes);
310 let mut scratch = CompositionScratch::default();
311 scratch.resolve(&layers, &sizes);
312 for lp in &layers {
313 let a = &eager[&lp.layer_id];
314 let b = scratch.get(lp.layer_id).expect("scratch composition");
315 assert_eq!(a.affine, b.affine);
316 assert_eq!(a.opacity, b.opacity);
317 assert_eq!(a.clips, b.clips);
318 }
319
320 let one = vec![layer(ids[0], Point::new(10.0, 20.0), LayerEffect::Opacity(0.5))];
322 scratch.resolve(&one, &sizes);
323 assert!(scratch.get(ids[0]).is_some());
324 assert!(scratch.get(ids[1]).is_none(), "新一帧不应保留旧 layer 的 composition");
325 }
326}