Skip to main content

cranpose_render_common/
scene_builder.rs

1use std::{any::Any, rc::Rc};
2
3use cranpose_core::{
4    MemoryApplier, NodeId, RecordId,
5    collections::{growth_slack::GrowthSlack, map::HashMap},
6};
7use cranpose_ui::{ModifierNodeSlices, Point, Rect, SubcomposeLayoutNode};
8
9use crate::{
10    NodeUpdate, SceneUpdates,
11    graph::ProjectiveTransform,
12    layer_transform::layer_transform_to_parent,
13    scene_store::{HeadKind, Item, LayerHead, LayerRef, RecordKind, SceneStore},
14};
15
16mod dirty_records;
17use dirty_records::{DirtyPlace, update_dirty_records};
18mod draw_recording;
19#[cfg(feature = "layer-tree")]
20pub(crate) use draw_recording::draw_command_items;
21use draw_recording::{
22    DrawPass, DrawTarget, GroupPaint, NodeCommands, NodeDraws, OwnDraws, append_draw_nodes,
23    draw_nodes, layer_node_capacity, text_item,
24};
25mod graph_changes;
26use graph_changes::GraphChanges;
27mod hit_graph;
28pub(crate) use hit_graph::HitGraphState;
29use hit_graph::rebuild_tracking_hits;
30mod inline_leaf;
31use inline_leaf::{lower_child, update_dirty_inline};
32mod layer_shape;
33use layer_shape::shaped_graphics_layer;
34mod text_node;
35mod translate_geometry;
36use text_node::translate_unwrapped;
37use translate_geometry::{KeptChild, TranslateGeometry, move_kept_child, translate_retained_child};
38mod node_data;
39use node_data::{PlacedGeometry, placed_child_geometry, read_node_data, read_placed_node_data};
40mod node_layer;
41use node_layer::{
42    AbsOrigin, LowerContext, assign_layer, hit_test_from_slices, layer_and_node_bounds,
43    layer_identity, lower_root_into, modifier_slices_have_origin_sinks, outer_commands,
44    outer_draws, placing_transform, set_bounds, slices_hit_something, take_wrapped_layer,
45    with_node_layer, write_node_content, write_node_layer, write_wrapper,
46};
47mod parent_origin;
48use parent_origin::ParentOrigin;
49mod translate_layer;
50pub(crate) use translate_layer::TranslateScratch;
51use translate_layer::{
52    ItemParts, TranslatedContainer, translate_tracking_hits, translated_container,
53    write_own_content_around_children,
54};
55
56struct SnapshotNodeData<'a> {
57    layout_state: cranpose_ui::widgets::LayoutState,
58    modifier_slices: Rc<ModifierNodeSlices>,
59    children: &'a [NodeId],
60    window_root: bool,
61}
62
63/// Why a scoped scene update could not be applied, forcing the caller to throw
64/// the scene away and build it again from the applier.
65///
66/// The reason has to travel with the outcome because the shell picks the
67/// scoped path from the shape of the dirty set, before this code runs, and
68/// logs that choice. A frame that chose the scoped path and then rebuilt the
69/// whole scene is the expensive case, and in the log it reads exactly like a
70/// cheap patch -- so the fallback says so itself.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum GraphRebuildReason {
73    /// The root was dirty and its replacement layer could not be built.
74    RootLayerUnavailable,
75    /// A dirty subtree's replacement layer could not be built.
76    DirtyLayerUnavailable,
77    /// This many dirty nodes own no record in the scene, so the scoped walk
78    /// never reached them. A dirty node that never made a record, or whose
79    /// record left the scene this frame, cannot be patched in place.
80    UnmatchedDirtyNodes(usize),
81}
82
83/// The outcome of a scoped scene update.
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85pub enum GraphUpdate {
86    /// The dirty nodes were updated in place.
87    Patched,
88    /// The update could not be applied and the graph must be built again, for the given reason.
89    NeedsRebuild(GraphRebuildReason),
90}
91
92/// The outcome of a scoped update together with its effect on hit testing.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub struct GraphUpdateReport {
95    /// Whether the graph was patched or must be rebuilt.
96    pub update: GraphUpdate,
97    /// Whether the update changed hit geometry or handlers, so the hit targets must be collected
98    /// again.
99    pub hit_graph_dirty: bool,
100    /// Whether the update moved a layer in its parent by the layer's own properties, as an
101    /// animated graphics layer or offset moves it, which no layout pass reports.
102    pub layers_moved: bool,
103}
104
105impl GraphUpdateReport {
106    fn patched(changes: GraphChanges) -> Self {
107        Self {
108            update: GraphUpdate::Patched,
109            hit_graph_dirty: changes.contains(GraphChanges::Hits),
110            layers_moved: changes.contains(GraphChanges::Moves),
111        }
112    }
113
114    fn needs_rebuild(reason: GraphRebuildReason) -> Self {
115        Self {
116            update: GraphUpdate::NeedsRebuild(reason),
117            hit_graph_dirty: true,
118            layers_moved: true,
119        }
120    }
121
122    /// Whether the graph was patched in place.
123    pub fn applied(self) -> bool {
124        matches!(self.update, GraphUpdate::Patched)
125    }
126
127    /// Why the graph must be rebuilt, or `None` when it was patched.
128    pub fn rebuild_reason(self) -> Option<GraphRebuildReason> {
129        match self.update {
130            GraphUpdate::Patched => None,
131            GraphUpdate::NeedsRebuild(reason) => Some(reason),
132        }
133    }
134}
135
136// The room an update keeps its dirty nodes in, which the next update on the
137// thread takes again.
138#[derive(Default)]
139pub(crate) struct DirtyRoom {
140    nodes: HashMap<NodeId, NodeUpdate>,
141    order: Vec<DirtyPlace>,
142    ancestors: Vec<NodeId>,
143}
144
145impl DirtyRoom {
146    // Gives back the room a burst of dirty nodes took.
147    fn trim(&mut self) {
148        self.nodes.trim_growth_slack();
149        self.order.trim_growth_slack();
150        self.ancestors.trim_growth_slack();
151    }
152}
153
154// Gives back the room the updates of the thread took for their dirty nodes.
155pub(crate) fn trim_dirty_room() {
156    crate::thread_state::with(|state| {
157        if let Some(mut room) = state.dirty_node_scratch.take() {
158            room.trim();
159            state.dirty_node_scratch.set(Some(room));
160        }
161    });
162}
163
164/// Builds the records of the layout tree below `root`, read from `applier`.
165/// Returns `None` when `root` cannot be lowered to a layer.
166pub fn build_from_applier(applier: &MemoryApplier, root: NodeId) -> Option<SceneStore> {
167    let mut store = SceneStore::new();
168    rebuild_from_applier(applier, root, &mut store).then_some(store)
169}
170
171// Lowers the layout tree below `root` into `store` again, its records reusing
172// the store's rows and arenas. Returns `false` and leaves the store empty
173// when `root` cannot be lowered to a layer.
174pub(crate) fn rebuild_from_applier(
175    applier: &MemoryApplier,
176    root: NodeId,
177    store: &mut SceneStore,
178) -> bool {
179    store.begin_update();
180    if let Some(record) = store.root() {
181        release_for_rebuild(store, record);
182    }
183    if !lower_root_into(applier, store, root) {
184        store.clear();
185        return false;
186    }
187    if let Some(record) = store.root() {
188        store.note_content_change(record);
189    }
190    store.finish_update();
191    true
192}
193
194// Applies `updates` to `store` in place, and reports whether the hit targets
195// must be collected again or why the store must be built again.
196pub(crate) fn update_from_applier(
197    applier: &MemoryApplier,
198    store: &mut SceneStore,
199    updates: SceneUpdates<'_>,
200) -> GraphUpdateReport {
201    let report = update_from_applier_inner(applier, store, updates);
202    if !updates.is_empty() && report.applied() {
203        store.finish_update();
204    }
205    report
206}
207
208// Returns a move when a node's layer change merged into new content: its
209// layer is lowered again, which keeps no record of where it lay.
210fn dirty_node_updates(
211    updates: SceneUpdates<'_>,
212    dirty: &mut HashMap<NodeId, NodeUpdate>,
213) -> GraphChanges {
214    dirty.clear();
215    dirty.reserve(updates.len());
216    let mut changes = GraphChanges::default();
217    for &(id, update) in updates {
218        dirty
219            .entry(id)
220            .and_modify(|kind| {
221                let merged = kind.merge(update);
222                if merged == NodeUpdate::Content && (changes_layer(*kind) || changes_layer(update))
223                {
224                    changes = GraphChanges::Moves;
225                }
226                *kind = merged;
227            })
228            .or_insert(update);
229    }
230    changes
231}
232
233fn changes_layer(update: NodeUpdate) -> bool {
234    matches!(update, NodeUpdate::Layer | NodeUpdate::MovedLayer)
235}
236
237fn update_from_applier_inner(
238    applier: &MemoryApplier,
239    store: &mut SceneStore,
240    updates: SceneUpdates<'_>,
241) -> GraphUpdateReport {
242    if updates.is_empty() {
243        return GraphUpdateReport::patched(GraphChanges::default());
244    }
245    store.begin_update();
246
247    // The room of the frame before keeps its storage for this one.
248    let mut room =
249        crate::thread_state::with(|state| state.dirty_node_scratch.take()).unwrap_or_default();
250    let merged = dirty_node_updates(updates, &mut room.nodes);
251    let mut report = update_dirty_nodes(applier, store, &mut room);
252    report.layers_moved |= merged.contains(GraphChanges::Moves);
253    room.nodes.clear();
254    crate::thread_state::with(|state| state.dirty_node_scratch.set(Some(room)));
255    report
256}
257
258fn update_dirty_nodes(
259    applier: &MemoryApplier,
260    store: &mut SceneStore,
261    room: &mut DirtyRoom,
262) -> GraphUpdateReport {
263    let DirtyRoom {
264        nodes,
265        order,
266        ancestors,
267        ..
268    } = room;
269    let mut changes = match update_named_nodes(applier, store, nodes, order) {
270        Ok(changes) => changes,
271        Err(reason) => return GraphUpdateReport::needs_rebuild(reason),
272    };
273    // A node the store holds no record of, as one placed again, lowers with
274    // the nearest node above it that the store draws.
275    if !nodes.is_empty() {
276        name_drawn_ancestors(applier, store, nodes, ancestors);
277    }
278    if !nodes.is_empty() {
279        changes |= match update_named_nodes(applier, store, nodes, order) {
280            Ok(changes) => changes,
281            Err(reason) => return GraphUpdateReport::needs_rebuild(reason),
282        };
283        nodes.retain(|&node, _| is_drawn(applier, node));
284    }
285    if nodes.is_empty() {
286        GraphUpdateReport::patched(changes)
287    } else {
288        GraphUpdateReport::needs_rebuild(GraphRebuildReason::UnmatchedDirtyNodes(nodes.len()))
289    }
290}
291
292// Updates the root and the records of the nodes in `nodes`, taking each node
293// it updates out of `nodes`.
294fn update_named_nodes(
295    applier: &MemoryApplier,
296    store: &mut SceneStore,
297    nodes: &mut HashMap<NodeId, NodeUpdate>,
298    order: &mut Vec<DirtyPlace>,
299) -> Result<GraphChanges, GraphRebuildReason> {
300    let root = store
301        .root()
302        .ok_or(GraphRebuildReason::RootLayerUnavailable)?;
303    let mut changes = GraphChanges::default();
304    if let Some(root_id) = layer_identity(store.layer(root))
305        && let Some(kind) = nodes.remove(&root_id)
306    {
307        changes = update_dirty_root(applier, store, nodes, (root, root_id, kind))?;
308        if nodes.is_empty() {
309            return Ok(changes);
310        }
311    }
312    let records = update_dirty_records(applier, store, nodes, order)
313        .ok_or(GraphRebuildReason::DirtyLayerUnavailable)?;
314    Ok(changes | records)
315}
316
317// Updates the root, `kind` its update: a retained root layer takes it in
318// place, any other root is lowered again with every node beneath it, which
319// leaves no node in `nodes`. Out of line: most frames leave the root alone.
320#[inline(never)]
321fn update_dirty_root(
322    applier: &MemoryApplier,
323    store: &mut SceneStore,
324    nodes: &mut HashMap<NodeId, NodeUpdate>,
325    (root, root_id, kind): (RecordId, NodeId, NodeUpdate),
326) -> Result<GraphChanges, GraphRebuildReason> {
327    let ancestors = TranslateAncestorContext {
328        inherited: Inherited::default(),
329        parent_abs: ParentOrigin::Known(&AbsOrigin::ROOT),
330    };
331    if kind == NodeUpdate::Draws
332        && redraw_retained_layer(applier, store, root, Level::Root, ancestors.inherited)
333    {
334        return Ok(GraphChanges::default());
335    }
336    if let Some(changes) =
337        try_update_retained_layer(applier, store, root, nodes, kind, Level::Root, ancestors)
338    {
339        return Ok(changes);
340    }
341    let hit_graph_dirty = rebuild_tracking_hits(store, root, |store, root| {
342        release_for_rebuild(store, root);
343        lower_root_into(applier, store, root_id)
344    })
345    .ok_or(GraphRebuildReason::RootLayerUnavailable)?;
346    store.note_content_change(root);
347    nodes.clear();
348    Ok(GraphChanges::hits(hit_graph_dirty))
349}
350
351// Names in place of each node in `nodes` that the store holds no record of
352// the nearest node above it that the store draws, with new content, and
353// drops those a subcompose node above keeps inactive, which draw nothing.
354// `ancestors` is room for the nodes named.
355fn name_drawn_ancestors(
356    applier: &MemoryApplier,
357    store: &SceneStore,
358    nodes: &mut HashMap<NodeId, NodeUpdate>,
359    ancestors: &mut Vec<NodeId>,
360) {
361    ancestors.clear();
362    nodes.retain(|&node, _| {
363        if store.record_of(node).is_some() {
364            return true;
365        }
366        match climb(applier, node, |above| store.record_of(above).is_some()) {
367            ClimbEnd::Stop(ancestor) => {
368                ancestors.push(ancestor);
369                false
370            }
371            ClimbEnd::Inactive => false,
372            ClimbEnd::Top => true,
373        }
374    });
375    for &ancestor in ancestors.iter() {
376        nodes
377            .entry(ancestor)
378            .and_modify(|kind| *kind = kind.merge(NodeUpdate::Content))
379            .or_insert(NodeUpdate::Content);
380    }
381}
382
383fn is_drawn(applier: &MemoryApplier, node: NodeId) -> bool {
384    !matches!(climb(applier, node, |_| false), ClimbEnd::Inactive)
385}
386
387// Where a climb from a node through the nodes above it ended.
388enum ClimbEnd {
389    // At the node the climb's `stop` picked.
390    Stop(NodeId),
391    // Under a subcompose node that keeps the node the climb came from among
392    // its inactive children.
393    Inactive,
394    // Past the top.
395    Top,
396}
397
398// Climbs from `node` through the nodes above it that are not virtual, up to
399// the first that `stop` picks.
400fn climb(applier: &MemoryApplier, node: NodeId, stop: impl Fn(NodeId) -> bool) -> ClimbEnd {
401    let mut child = node;
402    let mut current = node;
403    while let Some(parent) = applier
404        .get_ref(current)
405        .ok()
406        .and_then(cranpose_core::Node::parent)
407    {
408        let Ok(parent_node) = applier.get_ref(parent) else {
409            return ClimbEnd::Top;
410        };
411        current = parent;
412        if parent_node.is_virtual() {
413            continue;
414        }
415        let parent_node: &dyn Any = parent_node;
416        if let Some(subcompose) = parent_node.downcast_ref::<SubcomposeLayoutNode>()
417            && !subcompose.with_active_children(|children| children.contains(&child))
418        {
419            return ClimbEnd::Inactive;
420        }
421        if stop(parent) {
422            return ClimbEnd::Stop(parent);
423        }
424        child = parent;
425    }
426    ClimbEnd::Top
427}
428
429// What the records above a layer pass to it, besides where they lie.
430#[derive(Clone, Copy, Default)]
431struct Inherited {
432    motion_context_animated: bool,
433    translated_content_context: bool,
434    parent_content_offset: Point,
435}
436
437#[derive(Clone, Copy)]
438struct TranslateAncestorContext<'a> {
439    inherited: Inherited,
440    parent_abs: ParentOrigin<'a>,
441}
442
443// Whether a node lowers as the graph's root, the one node that may be a
444// window root, which then draws at the origin.
445#[derive(Clone, Copy, PartialEq, Eq)]
446enum Level {
447    Root,
448    Child,
449}
450
451// Whether a retained layer's node kept its place in its parent.
452#[derive(Clone, Copy, PartialEq, Eq)]
453enum Position {
454    Kept,
455    Moved,
456}
457
458// Whether a node's layer lies in the wrapper that holds the draws chained
459// before its graphics layer.
460#[derive(Clone, Copy, PartialEq, Eq)]
461enum Wrapping {
462    Wrapped,
463    Bare,
464}
465
466fn try_update_retained_layer(
467    applier: &MemoryApplier,
468    store: &mut SceneStore,
469    layer: RecordId,
470    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
471    kind: NodeUpdate,
472    level: Level,
473    ancestors: TranslateAncestorContext<'_>,
474) -> Option<GraphChanges> {
475    match kind {
476        NodeUpdate::Moved if level == Level::Child => {
477            move_retained_layer(applier, store, layer, ancestors)
478                .or_else(|| translate_tracking_hits(applier, store, layer, dirty_nodes, ancestors))
479        }
480        // A translate keeps the layer's graphics layer: one that changed is
481        // lowered again. A draws update that `redraw_retained_layer` could
482        // not take comes here.
483        NodeUpdate::Content | NodeUpdate::Draws | NodeUpdate::Moved => {
484            translate_tracking_hits(applier, store, layer, dirty_nodes, ancestors)
485        }
486        NodeUpdate::Layer => {
487            update_layer_properties(applier, store, layer, level, Position::Kept, ancestors)
488        }
489        NodeUpdate::MovedLayer => {
490            update_layer_properties(applier, store, layer, level, Position::Moved, ancestors)
491        }
492    }
493}
494
495// Records the draws of the node of `container` again around the children its
496// layer keeps. False, with nothing written, when the node changed in more than
497// its draws. It reads no window geometry above the layer.
498fn redraw_retained_layer(
499    applier: &MemoryApplier,
500    store: &mut SceneStore,
501    container: RecordId,
502    level: Level,
503    inherited: Inherited,
504) -> bool {
505    let layer = store.layer(container);
506    // The wrapper of a node's outer draws is written with its layer.
507    if layer.kind() == RecordKind::Wrapper {
508        return false;
509    }
510    let Some(node_id) = layer.node_id() else {
511        return false;
512    };
513    read_placed_node_data(applier, node_id, level, |data| {
514        let layer = store.layer(container);
515        let placement = layer.origin_in_parent();
516        let kept = Position::Kept;
517        if !retained_layer_matches_layout(layer, &data, placement, Wrapping::Bare, kept) {
518            return false;
519        }
520        if translated_container(
521            store,
522            container,
523            &data.layout_state,
524            &data.modifier_slices,
525            inherited,
526            Wrapping::Bare,
527        )
528        .is_none()
529        {
530            return false;
531        }
532        let parts = ItemParts::of(store, container);
533        let mut list = store.lists.take();
534        list.extend_from_slice(parts.children());
535        let mut own = parts.own_draws();
536        write_own_content_around_children(
537            store,
538            container,
539            (&mut list, &mut own),
540            &data.modifier_slices,
541            data.layout_state.size(),
542        );
543        store.write_items(container, &list);
544        own.finish(store);
545        store.lists.give(list);
546        parts.give_back(store);
547        store.note_content_change(container);
548        true
549    })
550    .unwrap_or(false)
551}
552
553fn move_retained_layer(
554    applier: &MemoryApplier,
555    store: &mut SceneStore,
556    layer: RecordId,
557    ancestors: TranslateAncestorContext<'_>,
558) -> Option<GraphChanges> {
559    let placed = placed_child_geometry(applier, layer_identity(store.layer(layer))?)?;
560    if Rect::from_size(placed.size) != store.layer(layer).node_rect() {
561        return None;
562    }
563    let previous = HitGraphState::of(store.layer(layer));
564    translate_retained_child(
565        store,
566        layer,
567        placed.position,
568        ancestors.inherited.parent_content_offset,
569    );
570    let moved = store.layer(layer);
571    if moved.has_origin_sinks()
572        && let Some(parent_abs) = ancestors.parent_abs.resolve(store)
573    {
574        publish_retained_window_geometry(applier, moved, parent_abs);
575    }
576    Some(previous.changes_against(&HitGraphState::of(moved)))
577}
578
579fn content_layer(store: &SceneStore, container: RecordId) -> Option<RecordId> {
580    let layer = store.layer(container);
581    let Some(node_id) = layer.wraps() else {
582        return Some(container);
583    };
584    layer
585        .children()
586        .find(|child| child.kind() == RecordKind::Layer && child.node_id() == Some(node_id))
587        .map(LayerRef::id)
588}
589
590fn retained_layer_matches_layout(
591    layer: LayerRef<'_>,
592    data: &SnapshotNodeData<'_>,
593    placement: Point,
594    wrapping: Wrapping,
595    position: Position,
596) -> bool {
597    let state = &data.layout_state;
598    let slices = &data.modifier_slices;
599    (position == Position::Moved || state.position() == placement)
600        && Rect::from_size(state.size()) == layer.node_rect()
601        && slices.layer_bounds(state.size()) == layer.local_bounds()
602        && state.content_offset() == layer.content_offset()
603        && (slices.outer_draw_command_count() > 0) == (wrapping == Wrapping::Wrapped)
604}
605
606fn update_layer_properties(
607    applier: &MemoryApplier,
608    store: &mut SceneStore,
609    container: RecordId,
610    level: Level,
611    position: Position,
612    ancestors: TranslateAncestorContext<'_>,
613) -> Option<GraphChanges> {
614    let layer = store.layer(container);
615    let node_id = layer_identity(layer)?;
616    let wrapping = if layer.kind() == RecordKind::Wrapper {
617        Wrapping::Wrapped
618    } else {
619        Wrapping::Bare
620    };
621    let wrapped = wrapping == Wrapping::Wrapped;
622    // The wrapper of a node's outer draws holds its placement; a moved
623    // wrapped node is drawn again.
624    if position == Position::Moved && wrapped {
625        return None;
626    }
627    let placement = layer.origin_in_parent();
628    let changes = read_placed_node_data(applier, node_id, level, |data| {
629        let target = content_layer(store, container)?;
630        let slices = &data.modifier_slices;
631        let state = &data.layout_state;
632        if !retained_layer_matches_layout(store.layer(target), &data, placement, wrapping, position)
633        {
634            return None;
635        }
636        // The node's slices may be new in this update: they and the store's
637        // note of the sinks beneath the layer say whether a node reads where
638        // the layer lies.
639        let reads =
640            modifier_slices_have_origin_sinks(slices) || store.layer(target).has_origin_sinks();
641        let context = LowerContext {
642            inherited: ancestors.inherited,
643            parent_abs: if reads {
644                ancestors.parent_abs.resolve(store).copied()
645            } else {
646                None
647            },
648        };
649        let previous = HitGraphState::of(store.layer(target));
650        let child_context = with_node_layer(node_id, slices, state, context, |head, children| {
651            assign_layer(store, target, head);
652            children
653        });
654        if wrapped {
655            let layer = store.layer(target);
656            let transform = layer_transform_to_parent(
657                layer.local_bounds(),
658                Point::default(),
659                layer.graphics_layer(),
660            );
661            store.set_placement(target, Point::default(), Some(transform));
662        }
663        let layer = store.layer(target);
664        if layer.has_origin_sinks()
665            && let Some(child_abs) = &child_context.parent_abs
666        {
667            for child in layer.children() {
668                publish_retained_window_geometry(applier, child, child_abs);
669            }
670        }
671        Some(previous.changes_against(&HitGraphState::of(layer)))
672    })??;
673    if wrapped {
674        store.note_property_change(container);
675    }
676    Some(changes)
677}
678
679pub(crate) fn publish_space(applier: &MemoryApplier, store: &SceneStore) {
680    if !crate::thread_state::with(|state| state.space_changed.replace(false)) {
681        return;
682    }
683    publish_space_now(applier, store);
684}
685
686#[cold]
687#[inline(never)]
688fn publish_space_now(applier: &MemoryApplier, store: &SceneStore) {
689    let Some(root_layer) = store.root_layer() else {
690        return;
691    };
692    let root = ProjectiveTransform::identity();
693    crate::space::for_each_window_eye(root_layer, root, &mut |tree, view, to_window| {
694        if let Some(eye) = &tree.cells[0].scene.eye {
695            eye.world.rebuild(|world| view.build_world(tree, world));
696        }
697        // The owner of a layer drawn on several meshes places it.
698        for seen in view
699            .surfaces
700            .iter()
701            .filter(|seen| seen.mesh == 0 && seen.layer.has_origin_sinks())
702        {
703            if let Some(content) = view.content_to_window(seen, to_window) {
704                publish_content_geometry(applier, seen.layer, content);
705            }
706        }
707    });
708}
709
710fn publish_content_geometry(
711    applier: &MemoryApplier,
712    layer: LayerRef<'_>,
713    to_window: ProjectiveTransform,
714) {
715    if let Some(node_id) = layer.node_id() {
716        read_node_data(applier, node_id, |data| {
717            data.modifier_slices.publish_window_geometry(
718                Point::default(),
719                Some(to_window),
720                data.layout_state.size(),
721            );
722        });
723    }
724    for child in layer.children() {
725        if child.has_origin_sinks() && child.graphics_layer().space.is_none() {
726            publish_content_geometry(applier, child, child.transform_to_parent().then(to_window));
727        }
728    }
729}
730
731fn publish_retained_window_geometry(
732    applier: &MemoryApplier,
733    layer: LayerRef<'_>,
734    parent_abs: &AbsOrigin,
735) {
736    if !layer.has_origin_sinks() {
737        return;
738    }
739    let child_abs = parent_abs.children_of(layer);
740    if let Some(node_id) = layer.node_id() {
741        let origin = layer.origin_in_parent();
742        read_node_data(applier, node_id, |data| {
743            data.modifier_slices.publish_window_geometry(
744                Point {
745                    x: parent_abs.content_origin.x + origin.x,
746                    y: parent_abs.content_origin.y + origin.y,
747                },
748                child_abs.window_transform,
749                data.layout_state.size(),
750            );
751        });
752    }
753    for child in layer.children() {
754        publish_retained_window_geometry(applier, child, &child_abs);
755    }
756}
757
758#[cold]
759#[inline(never)]
760fn note_space_change() {
761    crate::thread_state::with(|state| state.space_changed.set(true));
762}
763
764fn release_for_rebuild(store: &mut SceneStore, record: RecordId) {
765    store.drop_items(record);
766    store.set_hit_test(record, None);
767}
768
769fn forget_dirty_subtree(
770    store: &SceneStore,
771    record: RecordId,
772    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
773) {
774    if let Some(node_id) = layer_identity(store.layer(record)) {
775        dirty_nodes.remove(&node_id);
776    }
777    remove_dirty_descendants(store, record, dirty_nodes);
778}
779
780// Takes the node of `item`, an item of a record, and every node beneath it
781// out of `dirty_nodes`.
782fn forget_dirty_node(
783    store: &SceneStore,
784    item: Item,
785    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
786) {
787    if let Some(record) = item.as_child() {
788        forget_dirty_subtree(store, record, dirty_nodes);
789    }
790}
791
792fn remove_dirty_descendants(
793    store: &SceneStore,
794    record: RecordId,
795    dirty_nodes: &mut HashMap<NodeId, NodeUpdate>,
796) {
797    for child in store.layer(record).children() {
798        if let Some(node_id) = child.node_id() {
799            dirty_nodes.remove(&node_id);
800        }
801        remove_dirty_descendants(store, child.id(), dirty_nodes);
802    }
803}
804
805// The node an item of a record draws: a child record's, `None` for the
806// record's own draws and draw groups.
807#[inline]
808fn child_identity(store: &SceneStore, item: Item) -> Option<NodeId> {
809    item.as_child()
810        .and_then(|child| layer_identity(store.layer(child)))
811}
812
813#[cfg(test)]
814#[path = "tests/scene_builder_tests.rs"]
815mod tests;