use std::collections::{HashMap, HashSet};
use crate::element::LayerPaint;
use crate::geometry::{Point, Rect, Size};
use crate::id::LayerId;
use crate::paint::LayerEffect;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Affine2D {
pub a: f32,
pub b: f32,
pub c: f32,
pub d: f32,
pub tx: f32,
pub ty: f32,
}
impl Affine2D {
pub const IDENTITY: Self = Self { a: 1.0, b: 0.0, c: 0.0, d: 1.0, tx: 0.0, ty: 0.0 };
pub fn translate(x: f32, y: f32) -> Self {
Self { tx: x, ty: y, ..Self::IDENTITY }
}
pub fn then(&self, inner: &Self) -> Self {
Self {
a: self.a * inner.a + self.b * inner.c,
b: self.a * inner.b + self.b * inner.d,
c: self.c * inner.a + self.d * inner.c,
d: self.c * inner.b + self.d * inner.d,
tx: self.a * inner.tx + self.b * inner.ty + self.tx,
ty: self.c * inner.tx + self.d * inner.ty + self.ty,
}
}
pub fn apply(&self, p: Point) -> Point {
Point::new(self.a * p.x + self.b * p.y + self.tx, self.c * p.x + self.d * p.y + self.ty)
}
pub fn apply_rect(&self, rect: Rect) -> Rect {
let p0 = self.apply(Point::new(rect.x, rect.y));
let p1 = self.apply(Point::new(rect.x + rect.width, rect.y));
let p2 = self.apply(Point::new(rect.x, rect.y + rect.height));
let p3 = self.apply(Point::new(rect.x + rect.width, rect.y + rect.height));
let min_x = p0.x.min(p1.x).min(p2.x).min(p3.x);
let min_y = p0.y.min(p1.y).min(p2.y).min(p3.y);
let max_x = p0.x.max(p1.x).max(p2.x).max(p3.x);
let max_y = p0.y.max(p1.y).max(p2.y).max(p3.y);
Rect::new(min_x, min_y, max_x - min_x, max_y - min_y)
}
pub fn scale_hint(&self) -> f32 {
let sx = (self.a * self.a + self.c * self.c).sqrt();
let sy = (self.b * self.b + self.d * self.d).sqrt();
(sx + sy) * 0.5
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ClipShape {
pub rect: Rect,
pub radius: f32,
}
#[derive(Clone, Debug)]
pub struct LayerComposition {
pub affine: Affine2D,
pub opacity: f32,
pub clips: Vec<ClipShape>,
}
impl LayerComposition {
pub fn single(layer: &LayerPaint, size: Size) -> Self {
let own = own_effect(layer.effect, size);
let placement = Affine2D::translate(layer.offset.x, layer.offset.y);
let affine = placement.then(&own.affine);
let mut clips = Vec::new();
if let Some(radius) = own.clip_radius {
if radius > 0.0 {
clips.push(ClipShape {
rect: affine.apply_rect(Rect::new(0.0, 0.0, size.width, size.height)),
radius: radius * affine.scale_hint(),
});
}
}
Self { affine, opacity: own.opacity, clips }
}
}
pub struct OwnEffect {
pub affine: Affine2D,
pub opacity: f32,
pub clip_radius: Option<f32>,
}
pub fn own_effect(effect: LayerEffect, size: Size) -> OwnEffect {
match effect {
LayerEffect::None => OwnEffect { affine: Affine2D::IDENTITY, opacity: 1.0, clip_radius: None },
LayerEffect::Opacity(a) => {
OwnEffect { affine: Affine2D::IDENTITY, opacity: a.clamp(0.0, 1.0), clip_radius: None }
}
LayerEffect::Transform(t) if !t.is_identity() => {
let (sin, cos) = t.rotation.sin_cos();
let cx = size.width * 0.5;
let cy = size.height * 0.5;
let a = cos * t.scale_x;
let b = -sin * t.scale_y;
let c = sin * t.scale_x;
let d = cos * t.scale_y;
OwnEffect {
affine: Affine2D {
a,
b,
c,
d,
tx: cx + t.translate.x - (a * cx + b * cy),
ty: cy + t.translate.y - (c * cx + d * cy),
},
opacity: 1.0,
clip_radius: None,
}
}
LayerEffect::Transform(_) => OwnEffect { affine: Affine2D::IDENTITY, opacity: 1.0, clip_radius: None },
LayerEffect::ClipRRect(def) => {
OwnEffect { affine: Affine2D::IDENTITY, opacity: 1.0, clip_radius: Some(def.radius.max(0.0)) }
}
}
}
pub fn resolve_layer_compositions(
layers: &[LayerPaint],
sizes: &HashMap<LayerId, Size>,
) -> HashMap<LayerId, LayerComposition> {
let mut scratch = CompositionScratch::default();
scratch.resolve(layers, sizes);
scratch.into_map()
}
#[derive(Default)]
pub struct CompositionScratch {
by_id: HashMap<LayerId, usize>,
memo: HashMap<LayerId, LayerComposition>,
visiting: HashSet<LayerId>,
}
impl CompositionScratch {
pub fn resolve(&mut self, layers: &[LayerPaint], sizes: &HashMap<LayerId, Size>) {
self.by_id.clear();
self.by_id.extend(layers.iter().enumerate().map(|(i, lp)| (lp.layer_id, i)));
self.memo.clear();
self.visiting.clear();
for i in 0..layers.len() {
self.resolve_one(i, layers, sizes);
}
}
pub fn get(&self, layer_id: LayerId) -> Option<&LayerComposition> {
self.memo.get(&layer_id)
}
fn into_map(mut self) -> HashMap<LayerId, LayerComposition> {
std::mem::take(&mut self.memo)
}
fn resolve_one(&mut self, idx: usize, layers: &[LayerPaint], sizes: &HashMap<LayerId, Size>) -> LayerComposition {
let lp = &layers[idx];
if let Some(c) = self.memo.get(&lp.layer_id) {
return c.clone();
}
if !self.visiting.insert(lp.layer_id) {
let comp = LayerComposition::single(lp, layer_size(lp, sizes));
self.memo.insert(lp.layer_id, comp.clone());
return comp;
}
let size = layer_size(lp, sizes);
let own = own_effect(lp.effect, size);
let parent_idx = lp.parent.and_then(|pid| self.by_id.get(&pid).copied());
let (parent_affine, parent_opacity, mut clips, parent_offset) = match parent_idx {
Some(pi) => {
let pc = self.resolve_one(pi, layers, sizes);
(pc.affine, pc.opacity, pc.clips, layers[pi].offset)
}
None => (Affine2D::IDENTITY, 1.0, Vec::new(), Point::ZERO),
};
let local_offset = Point::new(lp.offset.x - parent_offset.x, lp.offset.y - parent_offset.y);
let affine = parent_affine.then(&Affine2D::translate(local_offset.x, local_offset.y)).then(&own.affine);
if let Some(radius) = own.clip_radius {
if radius > 0.0 {
clips.push(ClipShape {
rect: affine.apply_rect(Rect::new(0.0, 0.0, size.width, size.height)),
radius: radius * affine.scale_hint(),
});
if clips.len() > 2 {
clips.remove(0);
}
}
}
self.visiting.remove(&lp.layer_id);
let comp = LayerComposition { affine, opacity: (parent_opacity * own.opacity).clamp(0.0, 1.0), clips };
self.memo.insert(lp.layer_id, comp.clone());
comp
}
}
fn layer_size(lp: &LayerPaint, sizes: &HashMap<LayerId, Size>) -> Size {
sizes.get(&lp.layer_id).copied().or(lp.logical_size).unwrap_or(Size::ZERO)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::arena::Arena;
fn new_ids(n: usize) -> Vec<LayerId> {
let mut arena = Arena::<LayerId, ()>::new();
(0..n).map(|_| arena.insert(())).collect()
}
fn layer(id: LayerId, offset: Point, effect: LayerEffect) -> LayerPaint {
LayerPaint {
layer_id: id,
paint_list: std::rc::Rc::new(crate::paint::PaintList::new()),
is_dirty: false,
parent: None,
offset,
logical_size: Some(Size::new(100.0, 50.0)),
effect,
}
}
#[test]
fn opacity_and_translation_accumulate() {
let ids = new_ids(2);
let mut child = layer(ids[1], Point::new(10.0, 20.0), LayerEffect::Opacity(0.5));
child.parent = Some(ids[0]);
let parent = layer(ids[0], Point::new(5.0, 6.0), LayerEffect::Opacity(0.4));
let layers = vec![parent, child];
let sizes =
layers.iter().map(|lp| (lp.layer_id, lp.logical_size.unwrap_or(Size::ZERO))).collect::<HashMap<_, _>>();
let comps = resolve_layer_compositions(&layers, &sizes);
let c = &comps[&ids[1]];
assert!((c.opacity - 0.2).abs() < 1e-6, "父透明度应乘到子层");
assert_eq!(c.affine.apply(Point::ZERO), Point::new(10.0, 20.0));
}
#[test]
fn clip_keeps_at_most_two_layers() {
let ids = new_ids(3);
let mut l1 = layer(ids[0], Point::ZERO, LayerEffect::ClipRRect(crate::RRectDef { radius: 4.0 }));
let mut l2 = layer(ids[1], Point::ZERO, LayerEffect::ClipRRect(crate::RRectDef { radius: 6.0 }));
let mut l3 = layer(ids[2], Point::ZERO, LayerEffect::ClipRRect(crate::RRectDef { radius: 8.0 }));
l2.parent = Some(l1.layer_id);
l3.parent = Some(l2.layer_id);
l1.parent = None;
let layers = vec![l1, l2, l3];
let sizes =
layers.iter().map(|lp| (lp.layer_id, lp.logical_size.unwrap_or(Size::ZERO))).collect::<HashMap<_, _>>();
let comps = resolve_layer_compositions(&layers, &sizes);
assert_eq!(comps[&ids[2]].clips.len(), 2, "最多保留最内两层 clip");
}
#[test]
fn composition_scratch_matches_eager_and_clears_between_frames() {
let ids = new_ids(3);
let mut parent = layer(ids[0], Point::new(10.0, 20.0), LayerEffect::Opacity(0.5));
let mut child = layer(ids[1], Point::new(12.0, 26.0), LayerEffect::None);
child.parent = Some(parent.layer_id);
parent.parent = None;
let layers = vec![parent, child];
let sizes =
layers.iter().map(|lp| (lp.layer_id, lp.logical_size.unwrap_or(Size::ZERO))).collect::<HashMap<_, _>>();
let eager = resolve_layer_compositions(&layers, &sizes);
let mut scratch = CompositionScratch::default();
scratch.resolve(&layers, &sizes);
for lp in &layers {
let a = &eager[&lp.layer_id];
let b = scratch.get(lp.layer_id).expect("scratch composition");
assert_eq!(a.affine, b.affine);
assert_eq!(a.opacity, b.opacity);
assert_eq!(a.clips, b.clips);
}
let one = vec![layer(ids[0], Point::new(10.0, 20.0), LayerEffect::Opacity(0.5))];
scratch.resolve(&one, &sizes);
assert!(scratch.get(ids[0]).is_some());
assert!(scratch.get(ids[1]).is_none(), "新一帧不应保留旧 layer 的 composition");
}
}