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// Whether all that `inner` reaches lies within `outer`; an unknown reach
149// holds nothing and is held by nothing.
150#[cfg(feature = "window-damage")]
151pub(super) fn holds(outer: Reach, inner: Reach) -> bool {
152    match (outer, inner) {
153        (_, Reach::Empty) => true,
154        (Reach::Finite(outer), Reach::Finite(inner)) => {
155            outer.x <= inner.x
156                && outer.y <= inner.y
157                && inner.x + inner.width <= outer.x + outer.width
158                && inner.y + inner.height <= outer.y + outer.height
159        }
160        _ => false,
161    }
162}
163
164// Where an own draw of a record draws, in the record's space; `None` for a
165// child.
166#[cfg(feature = "window-damage")]
167pub(super) fn own_draw_reach(item: ItemRef<'_>) -> Option<Reach> {
168    match item {
169        ItemRef::Draw(draw) => Some(draw_reach(draw)),
170        ItemRef::Text(text) => Some(Reach::of(text.draw_bounds())),
171        ItemRef::Run(run) => Some(run_reach(run)),
172        ItemRef::Shape(shape) => Some(shape.coverage().map_or(Reach::Empty, Reach::Finite)),
173        ItemRef::Layer(_) | ItemRef::Leaf(_) => None,
174    }
175}
176
177#[cfg(feature = "window-damage")]
178fn draw_reach(draw: &DrawPrimitiveNode) -> Reach {
179    primitive_reach(&draw.primitive).within(draw.clip)
180}
181
182#[cfg(feature = "window-damage")]
183fn run_reach(run: &DrawRunNode) -> Reach {
184    let reach = run.recording.bounds().map_or(Reach::Empty, Reach::Finite);
185    if !run.summary.has_shadow {
186        return reach;
187    }
188    let recording = &*run.recording;
189    recording
190        .segments_in(&run.segments)
191        .filter(|segment| segment.lane == RecordLane::Others)
192        .flat_map(|segment| &recording.others()[segment.range()])
193        .fold(reach, |reach, primitive| {
194            reach.union(primitive_reach(primitive))
195        })
196}
197
198// Where `primitive` draws. A shadow's blur reaches past its shape by at most
199// its radius and [`BLUR_PIXEL_SLACK`] pixels; at a raster scale under one,
200// a renderer adds the pixels the logical units here leave out.
201#[cfg(feature = "window-damage")]
202fn primitive_reach(primitive: &DrawPrimitive) -> Reach {
203    match primitive {
204        DrawPrimitive::Blend { primitive, .. } => primitive_reach(primitive),
205        DrawPrimitive::Shadow(ShadowPrimitive::Drop {
206            shape, blur_radius, ..
207        }) => primitive_reach(shape)
208            .mapped(|rect| expand_rect(rect, blur_radius.max(0.0) + BLUR_PIXEL_SLACK)),
209        DrawPrimitive::Shadow(ShadowPrimitive::Inner { clip_rect, .. }) => {
210            Reach::Finite(*clip_rect)
211        }
212        primitive => Reach::of(primitive_coverage_rect(primitive)),
213    }
214}
215
216/// The most device pixels a blur reaches past its radius: the scratch
217/// block's rounding and the taps' tail.
218pub const BLUR_PIXEL_SLACK: f32 = 17.0;
219
220// The extent of `layer` in its parent's space.
221#[cfg(feature = "window-damage")]
222pub(super) fn extent(layer: LayerRef<'_>) -> Extent {
223    let placement = layer.placement();
224    let Some(graphics_layer) = layer.store().graphics_layer(layer.id()) else {
225        return Extent {
226            reach: layer.reach().mapped(|rect| placement.bounds_for_rect(rect)),
227            caster: None,
228        };
229    };
230    let effect = graphics_layer.render_effect.as_ref().map_or(0.0, |effect| {
231        effect.input_padding() + effect.output_padding()
232    });
233    let backdrop = graphics_layer
234        .backdrop_effect
235        .as_ref()
236        .map_or(Reach::Empty, |backdrop| {
237            Reach::Finite(expand_rect(layer.local_bounds(), backdrop.output_padding()))
238        });
239    // A blend other than source-over, or an effect that does not keep
240    // transparency, writes the layer's whole surface whatever its content
241    // draws: a shader may paint a layer that holds nothing.
242    let paints_surface = graphics_layer.blend_mode != BlendMode::SrcOver
243        || graphics_layer
244            .render_effect
245            .as_ref()
246            .is_some_and(|effect| !effect.preserves_transparency());
247    let surface = if paints_surface {
248        Reach::Finite(expand_rect(layer.local_bounds(), effect))
249    } else {
250        Reach::Empty
251    };
252    let space = graphics_layer.space.is_some();
253    let reach = if space {
254        Reach::Unknown
255    } else {
256        layer
257            .reach()
258            .mapped(|rect| expand_rect(rect, effect))
259            .union(surface)
260            .union(backdrop)
261            .mapped(|rect| placement.bounds_for_rect(rect))
262    };
263    let caster = (graphics_layer.shadow_elevation > 0.0).then(|| ShadowCaster {
264        bounds: placement.bounds_for_rect(layer.local_bounds()),
265        height: crate::layer_shadow::shadow_height(graphics_layer),
266    });
267    Extent { reach, caster }
268}