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    let mut children = Reach::Empty;
116    for position in 0..span.len() {
117        if let Some(child) = store.items.span(span)[position].as_child() {
118            refresh(store, child);
119            children = children.union(child_reach(LayerRef::new(store, child)));
120        }
121    }
122    let own = own_marks::reach(store.marks.pool.span(store.warm[index].own_marks));
123    settle(store, id, own.union(children));
124}
125
126// Where `child`, whose reach is worked out, draws in its parent's space; an
127// elevation shadow may reach anywhere.
128#[cfg(feature = "window-damage")]
129pub(super) fn child_reach(child: LayerRef<'_>) -> Reach {
130    let extent = child.extent();
131    match extent.caster {
132        Some(_) => Reach::Unknown,
133        None => extent.reach,
134    }
135}
136
137// Keeps `drawn`, where the own draws and the children of `id` reach, within
138// its clip as its reach.
139#[cfg(feature = "window-damage")]
140pub(super) fn settle(store: &mut SceneStore, id: RecordId, drawn: Reach) {
141    let index = id.index();
142    let clip = LayerRef::new(store, id).visual_clip_rect();
143    store.set_reach(index, drawn.within(clip));
144    let flags = &mut store.tree[index].flags;
145    *flags = flags.without(RecordFlags::REACH_STALE);
146}
147
148// Where an own draw of a record draws, in the record's space; `None` for a
149// child.
150#[cfg(feature = "window-damage")]
151pub(super) fn own_draw_reach(item: ItemRef<'_>) -> Option<Reach> {
152    match item {
153        ItemRef::Draw(draw) => Some(draw_reach(draw)),
154        ItemRef::Text(text) => Some(Reach::of(text.draw_bounds())),
155        ItemRef::Run(run) => Some(run_reach(run)),
156        ItemRef::Shape(shape) => Some(shape.coverage().map_or(Reach::Empty, Reach::Finite)),
157        ItemRef::Layer(_) | ItemRef::Leaf(_) => None,
158    }
159}
160
161#[cfg(feature = "window-damage")]
162fn draw_reach(draw: &DrawPrimitiveNode) -> Reach {
163    primitive_reach(&draw.primitive).within(draw.clip)
164}
165
166#[cfg(feature = "window-damage")]
167fn run_reach(run: &DrawRunNode) -> Reach {
168    let reach = run.recording.bounds().map_or(Reach::Empty, Reach::Finite);
169    if !run.summary.has_shadow {
170        return reach;
171    }
172    let recording = &*run.recording;
173    recording
174        .segments_in(&run.segments)
175        .filter(|segment| segment.lane == RecordLane::Others)
176        .flat_map(|segment| &recording.others()[segment.range()])
177        .fold(reach, |reach, primitive| {
178            reach.union(primitive_reach(primitive))
179        })
180}
181
182// Where `primitive` draws. A shadow's blur reaches past its shape by at most
183// its radius and [`BLUR_PIXEL_SLACK`] pixels; at a raster scale under one,
184// a renderer adds the pixels the logical units here leave out.
185#[cfg(feature = "window-damage")]
186fn primitive_reach(primitive: &DrawPrimitive) -> Reach {
187    match primitive {
188        DrawPrimitive::Blend { primitive, .. } => primitive_reach(primitive),
189        DrawPrimitive::Shadow(ShadowPrimitive::Drop {
190            shape, blur_radius, ..
191        }) => primitive_reach(shape)
192            .mapped(|rect| expand_rect(rect, blur_radius.max(0.0) + BLUR_PIXEL_SLACK)),
193        DrawPrimitive::Shadow(ShadowPrimitive::Inner { clip_rect, .. }) => {
194            Reach::Finite(*clip_rect)
195        }
196        primitive => Reach::of(primitive_coverage_rect(primitive)),
197    }
198}
199
200/// The most device pixels a blur reaches past its radius: the scratch
201/// block's rounding and the taps' tail.
202pub const BLUR_PIXEL_SLACK: f32 = 17.0;
203
204// The extent of `layer` in its parent's space.
205#[cfg(feature = "window-damage")]
206pub(super) fn extent(layer: LayerRef<'_>) -> Extent {
207    let placement = layer.placement();
208    let Some(graphics_layer) = layer.store().graphics_layer(layer.id()) else {
209        return Extent {
210            reach: layer.reach().mapped(|rect| placement.bounds_for_rect(rect)),
211            caster: None,
212        };
213    };
214    let effect = graphics_layer.render_effect.as_ref().map_or(0.0, |effect| {
215        effect.input_padding() + effect.output_padding()
216    });
217    let backdrop = graphics_layer
218        .backdrop_effect
219        .as_ref()
220        .map_or(Reach::Empty, |backdrop| {
221            Reach::Finite(expand_rect(layer.local_bounds(), backdrop.output_padding()))
222        });
223    // A blend other than source-over, or an effect that does not keep
224    // transparency, writes the layer's whole surface whatever its content
225    // draws: a shader may paint a layer that holds nothing.
226    let paints_surface = graphics_layer.blend_mode != BlendMode::SrcOver
227        || graphics_layer
228            .render_effect
229            .as_ref()
230            .is_some_and(|effect| !effect.preserves_transparency());
231    let surface = if paints_surface {
232        Reach::Finite(expand_rect(layer.local_bounds(), effect))
233    } else {
234        Reach::Empty
235    };
236    let space = graphics_layer.space.is_some();
237    let reach = if space {
238        Reach::Unknown
239    } else {
240        layer
241            .reach()
242            .mapped(|rect| expand_rect(rect, effect))
243            .union(surface)
244            .union(backdrop)
245            .mapped(|rect| placement.bounds_for_rect(rect))
246    };
247    let caster = (graphics_layer.shadow_elevation > 0.0).then(|| ShadowCaster {
248        bounds: placement.bounds_for_rect(layer.local_bounds()),
249        height: crate::layer_shadow::shadow_height(graphics_layer),
250    });
251    Extent { reach, caster }
252}