Skip to main content

cranpose_render_common/scene_store/
reach.rs

1// Where a record's subtree draws: its reach, worked out when a reader asks
2// for the records a change left stale, and its extent in its parent's space.
3
4#[cfg(feature = "window-damage")]
5use cranpose_core::RecordId;
6use cranpose_ui::Rect;
7#[cfg(feature = "window-damage")]
8use cranpose_ui_graphics::{
9    BlendMode, DrawPrimitive, RecordLane, ShadowPrimitive, expand_rect, primitive_coverage_rect,
10};
11
12#[cfg(feature = "window-damage")]
13use super::{ItemRef, LayerRef, RecordFlags, SceneStore, own_marks};
14#[cfg(feature = "window-damage")]
15use crate::graph::{DrawPrimitiveNode, DrawRunNode};
16
17/// Where a record's subtree draws, in one space.
18#[derive(Clone, Copy, Debug, PartialEq)]
19pub enum Reach {
20    /// It draws nothing.
21    Empty,
22    /// It draws within the rect.
23    Finite(Rect),
24    /// It may draw anywhere: paint whose bounds are not known, an elevation
25    /// shadow, whose reach depends on the window's light, or a projection
26    /// that reaches the eye plane.
27    Unknown,
28}
29
30impl Reach {
31    /// The reach of `rect`; `None` reads as unknown.
32    pub fn of(rect: Option<Rect>) -> Self {
33        rect.map_or(Self::Unknown, Self::Finite)
34    }
35
36    /// Where either draws.
37    #[must_use]
38    pub fn union(self, other: Self) -> Self {
39        match (self, other) {
40            (Self::Unknown, _) | (_, Self::Unknown) => Self::Unknown,
41            (Self::Empty, reach) | (reach, Self::Empty) => reach,
42            (Self::Finite(a), Self::Finite(b)) => Self::Finite(a.union(b)),
43        }
44    }
45
46    /// The part `clip` leaves; `None` cuts nothing.
47    #[must_use]
48    pub fn within(self, clip: Option<Rect>) -> Self {
49        let Some(clip) = clip else {
50            return self;
51        };
52        match self {
53            Self::Empty => Self::Empty,
54            Self::Finite(rect) => rect.intersect(clip).map_or(Self::Empty, Self::Finite),
55            Self::Unknown => Self::Finite(clip),
56        }
57    }
58
59    /// The reach with its rect mapped by `map`; a rect mapped to a value
60    /// that is not finite reads as unknown.
61    #[must_use]
62    pub fn mapped(self, map: impl FnOnce(Rect) -> Rect) -> Self {
63        let Self::Finite(rect) = self else {
64            return self;
65        };
66        let mapped = map(rect);
67        if [mapped.x, mapped.y, mapped.width, mapped.height]
68            .iter()
69            .all(|value| value.is_finite())
70        {
71            Self::Finite(mapped)
72        } else {
73            Self::Unknown
74        }
75    }
76
77    /// The rect, when the reach is finite.
78    pub fn rect(self) -> Option<Rect> {
79        match self {
80            Self::Finite(rect) => Some(rect),
81            Self::Empty | Self::Unknown => None,
82        }
83    }
84}
85
86/// What a record draws in its parent's space.
87#[derive(Clone, Copy, Debug, PartialEq)]
88pub struct Extent {
89    /// Where its subtree draws, placed by its transform and grown by its
90    /// effects, beside its elevation shadow.
91    pub reach: Reach,
92    /// What casts its elevation shadow, whose reach depends on the
93    /// window's light; `None` without one.
94    pub caster: Option<ShadowCaster>,
95}
96
97/// A record's elevation shadow, in its parent's space.
98#[derive(Clone, Copy, Debug, PartialEq)]
99pub struct ShadowCaster {
100    /// The record's bounds, placed by its transform.
101    pub bounds: Rect,
102    /// The elevation, scaled by the record's own scale.
103    pub height: f32,
104}
105
106// Works out the reach of `id` when a change left it stale, after that of
107// each of its children a change left stale.
108#[cfg(feature = "window-damage")]
109pub(super) fn refresh(store: &mut SceneStore, id: RecordId) {
110    let index = id.index();
111    if !store.tree[index].flags.contains(RecordFlags::REACH_STALE) {
112        return;
113    }
114    let span = store.tree[index].items;
115    for position in 0..span.len() {
116        if let Some(child) = store.items.span(span)[position].as_child() {
117            refresh(store, child);
118        }
119    }
120    let layer = LayerRef::new(store, id);
121    let clip = layer.visual_clip_rect();
122    let own = own_marks::reach(store.marks.pool.span(store.warm[index].own_marks));
123    let children = layer
124        .children()
125        .map(|child| {
126            let extent = child.extent();
127            match extent.caster {
128                Some(_) => Reach::Unknown,
129                None => extent.reach,
130            }
131        })
132        .fold(Reach::Empty, Reach::union);
133    let reach = own.union(children).within(clip);
134    store.set_reach(index, reach);
135    let flags = &mut store.tree[index].flags;
136    *flags = flags.without(RecordFlags::REACH_STALE);
137}
138
139// Where an own draw of a record draws, in the record's space; `None` for a
140// child.
141#[cfg(feature = "window-damage")]
142pub(super) fn own_draw_reach(item: ItemRef<'_>) -> Option<Reach> {
143    match item {
144        ItemRef::Draw(draw) => Some(draw_reach(draw)),
145        ItemRef::Text(text) => Some(Reach::of(text.draw_bounds())),
146        ItemRef::Run(run) => Some(run_reach(run)),
147        ItemRef::Shape(shape) => Some(shape.coverage().map_or(Reach::Empty, Reach::Finite)),
148        ItemRef::Layer(_) | ItemRef::Leaf(_) => None,
149    }
150}
151
152#[cfg(feature = "window-damage")]
153fn draw_reach(draw: &DrawPrimitiveNode) -> Reach {
154    primitive_reach(&draw.primitive).within(draw.clip)
155}
156
157#[cfg(feature = "window-damage")]
158fn run_reach(run: &DrawRunNode) -> Reach {
159    let reach = run.recording.bounds().map_or(Reach::Empty, Reach::Finite);
160    if !run.summary.has_shadow {
161        return reach;
162    }
163    let recording = &*run.recording;
164    recording
165        .segments_in(&run.segments)
166        .filter(|segment| segment.lane == RecordLane::Others)
167        .flat_map(|segment| &recording.others()[segment.range()])
168        .fold(reach, |reach, primitive| {
169            reach.union(primitive_reach(primitive))
170        })
171}
172
173// Where `primitive` draws. A shadow's blur reaches past its shape by at most
174// its radius and [`BLUR_PIXEL_SLACK`] pixels; at a raster scale under one,
175// a renderer adds the pixels the logical units here leave out.
176#[cfg(feature = "window-damage")]
177fn primitive_reach(primitive: &DrawPrimitive) -> Reach {
178    match primitive {
179        DrawPrimitive::Blend { primitive, .. } => primitive_reach(primitive),
180        DrawPrimitive::Shadow(ShadowPrimitive::Drop {
181            shape, blur_radius, ..
182        }) => primitive_reach(shape)
183            .mapped(|rect| expand_rect(rect, blur_radius.max(0.0) + BLUR_PIXEL_SLACK)),
184        DrawPrimitive::Shadow(ShadowPrimitive::Inner { clip_rect, .. }) => {
185            Reach::Finite(*clip_rect)
186        }
187        primitive => Reach::of(primitive_coverage_rect(primitive)),
188    }
189}
190
191/// The most device pixels a blur reaches past its radius: the scratch
192/// block's rounding and the taps' tail.
193pub const BLUR_PIXEL_SLACK: f32 = 17.0;
194
195// The extent of `layer` in its parent's space.
196#[cfg(feature = "window-damage")]
197pub(super) fn extent(layer: LayerRef<'_>) -> Extent {
198    let to_parent = layer.transform_to_parent();
199    let Some(graphics_layer) = layer.store().graphics_layer(layer.id()) else {
200        return Extent {
201            reach: layer.reach().mapped(|rect| to_parent.bounds_for_rect(rect)),
202            caster: None,
203        };
204    };
205    let effect = graphics_layer.render_effect.as_ref().map_or(0.0, |effect| {
206        effect.input_padding() + effect.output_padding()
207    });
208    let backdrop = graphics_layer
209        .backdrop_effect
210        .as_ref()
211        .map_or(Reach::Empty, |backdrop| {
212            Reach::Finite(expand_rect(layer.local_bounds(), backdrop.output_padding()))
213        });
214    // A blend other than source-over, or an effect that does not keep
215    // transparency, writes the layer's whole surface whatever its content
216    // draws: a shader may paint a layer that holds nothing.
217    let paints_surface = graphics_layer.blend_mode != BlendMode::SrcOver
218        || graphics_layer
219            .render_effect
220            .as_ref()
221            .is_some_and(|effect| !effect.preserves_transparency());
222    let surface = if paints_surface {
223        Reach::Finite(expand_rect(layer.local_bounds(), effect))
224    } else {
225        Reach::Empty
226    };
227    let space = graphics_layer.space.is_some();
228    let reach = if space {
229        Reach::Unknown
230    } else {
231        layer
232            .reach()
233            .mapped(|rect| expand_rect(rect, effect))
234            .union(surface)
235            .union(backdrop)
236            .mapped(|rect| to_parent.bounds_for_rect(rect))
237    };
238    let caster = (graphics_layer.shadow_elevation > 0.0).then(|| ShadowCaster {
239        bounds: to_parent.bounds_for_rect(layer.local_bounds()),
240        height: crate::layer_shadow::shadow_height(graphics_layer),
241    });
242    Extent { reach, caster }
243}