Skip to main content

cranpose_render_common/
space.rs

1//! Where the scenes a window shows put their 3D layers, as one map that
2//! drawing, picking, window geometry and the eye's walking all read.
3//!
4//! Inside a scene, a layer takes its 3D frame from its parent's: its place in
5//! the parent's layout, turned into 3D on the parent's plane. A mesh surface
6//! places its mesh in that frame and its children's frames in its content; a
7//! 3D transform moves the frames beneath it; a scene opens a space of its
8//! own, behind a doorway at its layer's bounds. The window's eye stands in
9//! one of these spaces and sees the others through the doorways that show on
10//! screen, as deep as they show.
11//!
12//! A scene and a mesh surface each cover their layer's bounds, as a Compose
13//! graphics layer covers the coordinator after it: a modifier before them,
14//! as a padding or a size the parent does not hold, moves or sizes them
15//! apart from their node.
16
17use std::sync::Arc;
18
19use cranpose_core::NodeId;
20use cranpose_ui_graphics::{
21    Rect, Size,
22    space::{Camera, EyeWorld, LayerSpace, Light, Mat4, MeshSurface, MeshSurfaces, Scene3d, Vec3},
23};
24
25use crate::{graph::ProjectiveTransform, scene_store::LayerRef};
26
27const BACK_THROUGH_DOORWAY: f32 = 1.0e-4;
28
29const SMALLEST_OPENING: f32 = 0.25;
30
31/// How near the eye a doorway still opens, as a fraction of the distance of
32/// the camera's near plane: a renderer shows the part of a doorway between
33/// this depth and the near plane on the near plane, so an eye that steps
34/// into a doorway keeps seeing through it.
35pub const DOORWAY_NEAR: f32 = 1.0 / 1024.0;
36
37/// A space a scene opens.
38pub struct Cell<'a> {
39    /// The scene's layer.
40    pub layer: LayerRef<'a>,
41    /// The scene.
42    pub scene: &'a Scene3d,
43    /// The space its doorway lies in; `None` for the window's scene.
44    pub parent: Option<usize>,
45    /// The surface of the parent space whose content holds the doorway, by
46    /// its number among the tree's surfaces, and the doorway's rect in that
47    /// content, when the doorway lies flat in it. Of a layer drawn on several
48    /// meshes, it is the owner's.
49    pub hole: Option<(usize, Rect)>,
50    /// Places the unit square on the doorway in the parent space, the space
51    /// lying beyond it along its z; the identity for the window's scene.
52    pub doorway: Mat4,
53    /// Maps the space into its parent's.
54    pub to_parent: Mat4,
55}
56
57/// A mesh surface placed in its space.
58pub struct Placed<'a> {
59    /// The surface's layer.
60    pub layer: LayerRef<'a>,
61    /// The surface, its mesh placed in its space.
62    pub surface: MeshSurface,
63    /// Which of the layer's meshes it is: 0 for the owner, which places the
64    /// layer's children and its window geometry.
65    pub mesh: usize,
66    /// Its space.
67    pub cell: usize,
68    /// The rect of its content in its layer: the layer's bounds, which the
69    /// mesh's texture spans.
70    pub content: Rect,
71}
72
73type Host = (usize, ProjectiveTransform);
74
75/// The spaces of a window's scene and the scenes behind its doorways, and
76/// their mesh surfaces, in the order the composition holds them.
77pub struct SpaceTree<'a> {
78    /// The spaces; the first is the window scene's own.
79    pub cells: Vec<Cell<'a>>,
80    /// The mesh surfaces, in draw order; the meshes of one layer follow
81    /// each other, its owner first.
82    pub surfaces: Vec<Placed<'a>>,
83}
84
85/// Where the window's eye stands, with its camera, and what it sees from
86/// there: the spaces it sees through doorways and their surfaces, all in
87/// the coordinates of the space it stands in.
88pub struct EyeView<'a> {
89    /// The eye's camera.
90    pub camera: Camera,
91    /// The size of the window scene's layer bounds, which the camera fills.
92    pub size: Size,
93    /// The space the eye stands in, by its number in the tree.
94    pub cell: usize,
95    /// The spaces the eye sees: its own first, then each through the
96    /// doorway it shows through, before the spaces seen through it.
97    pub seen: Vec<SeenSpace>,
98    /// The surfaces of the spaces it sees, in draw order; the meshes of one
99    /// layer follow each other, its owner first.
100    pub surfaces: Vec<SeenSurface<'a>>,
101}
102
103/// A space the eye sees.
104pub struct SeenSpace {
105    /// The space, by its number in the tree.
106    pub cell: usize,
107    /// The seen space whose doorway it shows through; `None` for the eye's
108    /// own.
109    pub through: Option<usize>,
110    /// How many doorways deep it shows: 0 for the eye's own space. The
111    /// stencil that marks where each doorway opens counts them in eight
112    /// bits, so the eye sees no deeper than 255.
113    pub depth: u8,
114    /// Maps the space into the eye's.
115    pub to_eye: Mat4,
116    /// The space's light, in the eye's space.
117    pub light: Option<Light>,
118    /// The doorway it shows through; `None` for the eye's own space.
119    pub door: Option<SeenDoor>,
120}
121
122/// A doorway as the eye sees through it.
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub struct SeenDoor {
125    /// Places the unit square on the doorway, in the eye's space.
126    pub quad: Mat4,
127    /// Which way along the quad's z points away from the eye: 1 or -1.
128    pub away: f32,
129    /// The plane past which the space behind the doorway shows, in the eye's
130    /// space: a point `p` shows where `normal . p + offset >= 0`.
131    pub clip: [f32; 4],
132    /// The bounds of the doorway's opening on screen, within those of the
133    /// doorways it shows through, in the window scene node's coordinates.
134    pub opening: Rect,
135}
136
137/// A surface the eye sees.
138pub struct SeenSurface<'a> {
139    /// The surface's layer.
140    pub layer: LayerRef<'a>,
141    /// The surface, its mesh placed in the eye's space.
142    pub surface: MeshSurface,
143    /// Which of the layer's meshes it is, as [`Placed::mesh`].
144    pub mesh: usize,
145    /// The rect of its content in its layer, as [`Placed::content`].
146    pub content: Rect,
147    /// The seen space it lies in, by its number among [`EyeView::seen`].
148    pub seen: usize,
149}
150
151// What a walk of a scene's layers keeps. The walk finds the 3D layers in order and the frame that
152// each takes; the walker keeps what it needs of them.
153trait Walker<'a> {
154    // The scene layer `layer` opens a space, at `place` in the space it lies in: that space's
155    // number, the layer's frame there and the surface whose content holds it. `None` for the
156    // window's own scene. Returns the number of the new space, or `None` to leave it unwalked.
157    fn open(
158        &mut self,
159        layer: LayerRef<'a>,
160        scene: &'a Scene3d,
161        place: Option<(usize, Mat4, Option<Host>)>,
162    ) -> Option<usize>;
163
164    // The mesh surfaces of `layer`, at `frame` in space `cell`. Returns the number of the first of
165    // its meshes among those the walker keeps, and the map from its content to the space.
166    fn surface(
167        &mut self,
168        layer: LayerRef<'a>,
169        surfaces: &MeshSurfaces,
170        frame: &Mat4,
171        cell: usize,
172    ) -> (usize, Option<Mat4>);
173}
174
175// Walks the children of `layer`, which lies at `frame` in space `cell`.
176fn walk<'a>(
177    walker: &mut impl Walker<'a>,
178    layer: LayerRef<'a>,
179    frame: &Mat4,
180    (cell, host): (usize, Option<Host>),
181) {
182    for child in layer.children() {
183        if !child.has_space() {
184            continue;
185        }
186        let to_parent = child.transform_to_parent();
187        let child_frame = embed(to_parent).then(frame);
188        let child_host = host.map(|(surface, to_content)| (surface, to_parent.then(to_content)));
189        match child.graphics_layer().space.as_deref() {
190            Some(LayerSpace::Scene(scene)) => {
191                let place = Some((cell, child_frame, child_host));
192                if let Some(inner) = walker.open(child, scene, place) {
193                    walk(walker, child, &Mat4::IDENTITY, (inner, None));
194                }
195            }
196            Some(LayerSpace::Surface(surfaces)) => {
197                let content = child.local_bounds();
198                let (index, to_scene) = walker.surface(child, surfaces, &child_frame, cell);
199                if let Some(to_scene) = to_scene {
200                    // The children lie in the layer, whose content starts at the corner of its
201                    // bounds.
202                    let to_content = ProjectiveTransform::translation(-content.x, -content.y);
203                    walk(
204                        walker,
205                        child,
206                        &embed(to_content).then(&to_scene),
207                        (cell, Some((index, to_content))),
208                    );
209                }
210            }
211            Some(LayerSpace::Transform(transform)) => {
212                walk(walker, child, &transform.then(&child_frame), (cell, None));
213            }
214            None => walk(walker, child, &child_frame, (cell, child_host)),
215        }
216    }
217}
218
219impl<'a> Walker<'a> for SpaceTree<'a> {
220    fn open(
221        &mut self,
222        layer: LayerRef<'a>,
223        scene: &'a Scene3d,
224        place: Option<(usize, Mat4, Option<Host>)>,
225    ) -> Option<usize> {
226        let index = self.cells.len();
227        let cell = match place {
228            None => Cell {
229                layer,
230                scene,
231                parent: None,
232                hole: None,
233                doorway: Mat4::IDENTITY,
234                to_parent: Mat4::IDENTITY,
235            },
236            Some((parent, frame, host)) => {
237                let rect = layer.local_bounds();
238                Cell {
239                    layer,
240                    scene,
241                    parent: Some(parent),
242                    hole: host
243                        .map(|(surface, to_content)| (surface, to_content.bounds_for_rect(rect))),
244                    doorway: Mat4::scaling(Vec3::new(rect.width, rect.height, 1.0))
245                        .then(&Mat4::translation(Vec3::new(rect.x, rect.y, 0.0)))
246                        .then(&frame),
247                    to_parent: scene.camera.doorway(rect).then(&frame),
248                }
249            }
250        };
251        self.cells.push(cell);
252        Some(index)
253    }
254
255    fn surface(
256        &mut self,
257        layer: LayerRef<'a>,
258        surfaces: &MeshSurfaces,
259        frame: &Mat4,
260        cell: usize,
261    ) -> (usize, Option<Mat4>) {
262        let content = layer.local_bounds();
263        let index = self.surfaces.len();
264        for (mesh, surface) in surfaces.iter().enumerate() {
265            self.surfaces.push(Placed {
266                layer,
267                surface: surface.placed_by(frame),
268                mesh,
269                cell,
270                content,
271            });
272        }
273        let to_scene = self.surfaces[index]
274            .surface
275            .content_to_scene(content.size());
276        (index, to_scene)
277    }
278}
279
280impl<'a> SpaceTree<'a> {
281    /// The spaces and surfaces of the scene `scene_layer` shows; `None`
282    /// when it shows none.
283    pub fn of(scene_layer: LayerRef<'a>) -> Option<Self> {
284        let scene = scene_of(scene_layer)?;
285        let mut tree = Self {
286            cells: Vec::new(),
287            surfaces: Vec::new(),
288        };
289        let index = tree.open(scene_layer, scene, None)?;
290        walk(&mut tree, scene_layer, &Mat4::IDENTITY, (index, None));
291        Some(tree)
292    }
293
294    /// Whether `layer` is one of the tree's scenes.
295    pub fn holds_scene(&self, layer: LayerRef<'_>) -> bool {
296        layer.node_id().is_some()
297            && self
298                .cells
299                .iter()
300                .any(|cell| cell.layer.node_id() == layer.node_id())
301    }
302
303    /// The space an eye that walked through the doorways of the scene nodes
304    /// `path` stands in: as far along the path as its doorways still lead.
305    pub fn cell_along(&self, path: &[usize]) -> usize {
306        let mut cell = 0;
307        for &node in path {
308            let next = self.cells.iter().position(|inner| {
309                inner.parent == Some(cell) && inner.layer.node_id() == Some(NodeId(node))
310            });
311            match next {
312                Some(next) => cell = next,
313                None => break,
314            }
315        }
316        cell
317    }
318
319    /// Maps space `cell` into the window scene's.
320    pub fn to_root(&self, cell: usize) -> Mat4 {
321        let mut transform = Mat4::IDENTITY;
322        let mut at = Some(cell);
323        while let Some(index) = at {
324            let cell = &self.cells[index];
325            transform = transform.then(&cell.to_parent);
326            at = cell.parent;
327        }
328        transform
329    }
330}
331
332/// A mesh of a surface layer that [`visit_meshes`] found.
333pub struct MeshVisit<'v> {
334    /// The node whose layer carries the surface.
335    pub node: Option<NodeId>,
336    /// Which of the layer's meshes it is: 0 for the owner.
337    pub mesh: usize,
338    /// The surface as the layer's modifier gave it, with its own transform.
339    pub surface: &'v MeshSurface,
340    /// Maps the mesh's own space to the frame of the layer that the walk started from, through
341    /// the surface's own transform.
342    pub to_frame: Mat4,
343}
344
345// Reports each surface of the walk's own space, and leaves the scenes inside it alone.
346struct Meshes<'f> {
347    visit: &'f mut dyn FnMut(&MeshVisit<'_>),
348}
349
350impl<'a> Walker<'a> for Meshes<'_> {
351    fn open(
352        &mut self,
353        _layer: LayerRef<'a>,
354        _scene: &'a Scene3d,
355        _place: Option<(usize, Mat4, Option<Host>)>,
356    ) -> Option<usize> {
357        None
358    }
359
360    fn surface(
361        &mut self,
362        layer: LayerRef<'a>,
363        surfaces: &MeshSurfaces,
364        frame: &Mat4,
365        _cell: usize,
366    ) -> (usize, Option<Mat4>) {
367        for (mesh, surface) in surfaces.iter().enumerate() {
368            (self.visit)(&MeshVisit {
369                node: layer.node_id(),
370                mesh,
371                surface,
372                to_frame: surface.transform.then(frame),
373            });
374        }
375        let to_scene = surfaces
376            .owner()
377            .placed_by(frame)
378            .content_to_scene(layer.local_bounds().size());
379        (0, to_scene)
380    }
381}
382
383/// Visits each mesh of the surface layers under `layer`, in `layer`'s own frame, with no
384/// allocation: the pick of a pointer that points along a ray reads them each frame. A scene
385/// under `layer` opens a space of its own, which the visit leaves out.
386pub fn visit_meshes(layer: LayerRef<'_>, visit: &mut dyn FnMut(&MeshVisit<'_>)) {
387    walk(&mut Meshes { visit }, layer, &Mat4::IDENTITY, (0, None));
388}
389
390/// The layer of the node `node` at or under `layer`.
391pub fn layer_of_node(layer: LayerRef<'_>, node: NodeId) -> Option<LayerRef<'_>> {
392    if layer.node_id() == Some(node) {
393        return Some(layer);
394    }
395    layer
396        .children()
397        .find_map(|child| layer_of_node(child, node))
398}
399
400#[derive(Clone, Copy, PartialEq, Eq)]
401enum Through {
402    Inward,
403    Outward,
404}
405
406impl<'a> EyeView<'a> {
407    /// What the window's eye sees of `tree`, the scene of a node of `size`:
408    /// it stands where the window scene's [`Scene3d::eye`] says, and sees
409    /// through each doorway whose opening shows on screen.
410    pub fn of(tree: &SpaceTree<'a>, size: Size) -> Self {
411        let root = tree.cells[0].scene;
412        let cell = root
413            .eye
414            .as_ref()
415            .map_or(0, |eye| tree.cell_along(&eye.doorways));
416        let mut view = Self {
417            camera: root.camera,
418            size,
419            cell,
420            seen: vec![SeenSpace {
421                cell,
422                through: None,
423                depth: 0,
424                to_eye: Mat4::IDENTITY,
425                light: tree.cells[cell].scene.light,
426                door: None,
427            }],
428            surfaces: Vec::new(),
429        };
430        view.look_through(tree, (0, None), Rect::from_size(size));
431        let mut seen_of = vec![None; tree.cells.len()];
432        for (index, seen) in view.seen.iter().enumerate() {
433            seen_of[seen.cell] = Some(index);
434        }
435        for placed in &tree.surfaces {
436            let Some(seen) = seen_of[placed.cell] else {
437                continue;
438            };
439            view.surfaces.push(SeenSurface {
440                layer: placed.layer,
441                surface: placed.surface.placed_by(&view.seen[seen].to_eye),
442                mesh: placed.mesh,
443                content: placed.content,
444                seen,
445            });
446        }
447        view
448    }
449
450    fn look_through(
451        &mut self,
452        tree: &SpaceTree<'a>,
453        (seen, came_from): (usize, Option<usize>),
454        opening: Rect,
455    ) {
456        let (cell, to_eye) = (self.seen[seen].cell, self.seen[seen].to_eye);
457        for (inner, space) in tree.cells.iter().enumerate() {
458            if space.parent != Some(cell) || Some(inner) == came_from {
459                continue;
460            }
461            let inner_to_eye = space.to_parent.then(&to_eye);
462            let quad = space.doorway.then(&to_eye);
463            self.through(
464                tree,
465                (seen, inner, inner_to_eye),
466                (quad, Through::Inward),
467                opening,
468            );
469        }
470        let space = &tree.cells[cell];
471        if let Some(outer) = space.parent.filter(|outer| Some(*outer) != came_from)
472            && let Some(from_parent) = space.to_parent.inverse()
473        {
474            let outer_to_eye = from_parent.then(&to_eye);
475            let quad = space.doorway.then(&outer_to_eye);
476            self.through(
477                tree,
478                (seen, outer, outer_to_eye),
479                (quad, Through::Outward),
480                opening,
481            );
482        }
483    }
484
485    fn through(
486        &mut self,
487        tree: &SpaceTree<'a>,
488        (seen, cell, to_eye): (usize, usize, Mat4),
489        (quad, through): (Mat4, Through),
490        opening: Rect,
491    ) {
492        let Some(depth) = self.seen[seen].depth.checked_add(1) else {
493            return;
494        };
495        let corner = quad.transform_point(Vec3::ZERO);
496        let Some(normal) = quad.transform_vector(Vec3::new(0.0, 0.0, 1.0)).normalized() else {
497            return;
498        };
499        let side = normal.dot(self.camera.eye() - corner);
500        // A doorway opens one way: into its space from the side its z leaves,
501        // and back out of it from the side its z points to.
502        let (facing, away, clip) = match through {
503            Through::Inward => (side < 0.0, 1.0, plane(normal, corner, 0.0)),
504            Through::Outward => {
505                let margin = BACK_THROUGH_DOORWAY * normal.dot(corner).abs().max(1.0);
506                (side > 0.0, -1.0, plane(-normal, corner, margin))
507            }
508        };
509        let shown = facing
510            .then(|| self.opening(&quad))
511            .flatten()
512            .and_then(|shown| shown.intersect(opening))
513            .filter(|shown| shown.width * shown.height >= SMALLEST_OPENING);
514        let Some(shown) = shown else {
515            return;
516        };
517        let light = tree.cells[cell].scene.light.map(|light| Light {
518            direction: to_eye.transform_vector(light.direction),
519            ..light
520        });
521        self.seen.push(SeenSpace {
522            cell,
523            through: Some(seen),
524            depth,
525            to_eye,
526            light,
527            door: Some(SeenDoor {
528                quad,
529                away,
530                clip,
531                opening: shown,
532            }),
533        });
534        let index = self.seen.len() - 1;
535        self.look_through(tree, (index, Some(self.seen[seen].cell)), shown);
536    }
537
538    fn opening(&self, quad: &Mat4) -> Option<Rect> {
539        let to_camera = quad.then(&self.camera.view);
540        let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
541            .map(|(u, v)| to_camera.transform_point(Vec3::new(u, v, 0.0)));
542        let near = self.camera.near() * DOORWAY_NEAR;
543        let (mut low, mut high) = (
544            (f32::INFINITY, f32::INFINITY),
545            (f32::NEG_INFINITY, f32::NEG_INFINITY),
546        );
547        let mut any = false;
548        let mut show = |point: Vec3| {
549            let scale = self.camera.focal_length / point.z;
550            let (x, y) = (
551                self.size.width * 0.5 + point.x * scale,
552                self.size.height * 0.5 + point.y * scale,
553            );
554            low = (low.0.min(x), low.1.min(y));
555            high = (high.0.max(x), high.1.max(y));
556            any = true;
557        };
558        for (index, &from) in corners.iter().enumerate() {
559            let to = corners[(index + 1) % corners.len()];
560            if from.z >= near {
561                show(from);
562            }
563            if (from.z >= near) != (to.z >= near) {
564                show(from + (to - from) * ((near - from.z) / (to.z - from.z)));
565            }
566        }
567        any.then_some(Rect {
568            x: low.0,
569            y: low.1,
570            width: high.0 - low.0,
571            height: high.1 - low.1,
572        })
573    }
574
575    /// Fills `world` with what the eye can bump into and walk through: the
576    /// space it stands in, the spaces one doorway from it, their solid
577    /// surfaces and the doorways between them, in the eye's space.
578    pub fn build_world(&self, tree: &SpaceTree<'_>, world: &mut EyeWorld) {
579        if let Some(window_scene) = tree.cells[0].layer.node_id() {
580            world.set_window_scene(window_scene.0);
581        }
582        let walked = tree.walked_to(self.cell);
583        let base = world.add_space(Arc::clone(&walked), Mat4::IDENTITY);
584        let mut spaces = vec![(self.cell, base, Mat4::IDENTITY)];
585        let own = &tree.cells[self.cell];
586        if let Some(outer) = own.parent
587            && let Some(from_parent) = own.to_parent.inverse()
588        {
589            let path: Arc<[usize]> = Arc::from(&walked[..walked.len().saturating_sub(1)]);
590            let index = world.add_space(path, from_parent);
591            world.add_doorway((index, base), own.doorway.then(&from_parent));
592            spaces.push((outer, index, from_parent));
593        }
594        for (inner, space) in tree.cells.iter().enumerate() {
595            let (Some(cell), Some(node)) = (space.parent, space.layer.node_id()) else {
596                continue;
597            };
598            if cell != self.cell {
599                continue;
600            }
601            let path: Arc<[usize]> = walked.iter().copied().chain([node.0]).collect();
602            let index = world.add_space(path, space.to_parent);
603            world.add_doorway((base, index), space.doorway);
604            spaces.push((inner, index, space.to_parent));
605        }
606        for (surface_index, placed) in tree.surfaces.iter().enumerate() {
607            let Some(&(_, space, to_base)) =
608                spaces.iter().find(|(cell, _, _)| *cell == placed.cell)
609            else {
610                continue;
611            };
612            if !placed.surface.solid {
613                continue;
614            }
615            let holes = tree.cells.iter().filter_map(|cell| {
616                cell.hole
617                    .filter(|(host, _)| *host == surface_index)
618                    .map(|(_, rect)| rect)
619            });
620            world.add_solid(
621                (space, Arc::clone(&placed.surface.mesh)),
622                placed.surface.transform.then(&to_base),
623                (placed.content.size(), holes),
624            );
625        }
626    }
627}
628
629impl SpaceTree<'_> {
630    fn walked_to(&self, cell: usize) -> Arc<[usize]> {
631        let mut path = Vec::new();
632        let mut at = cell;
633        while let Some(parent) = self.cells[at].parent {
634            if let Some(node) = self.cells[at].layer.node_id() {
635                path.push(node.0);
636            }
637            at = parent;
638        }
639        path.reverse();
640        Arc::from(path)
641    }
642}
643
644fn plane(normal: Vec3, point: Vec3, margin: f32) -> [f32; 4] {
645    [normal.x, normal.y, normal.z, -normal.dot(point) - margin]
646}
647
648/// A plane map of the frame's plane z = 0 as a 3D map: z stays and
649/// distances along it scale as the plane's do not.
650pub fn embed(transform: ProjectiveTransform) -> Mat4 {
651    let [[a, b, c], [d, e, f], [g, h, i]] = transform.matrix();
652    Mat4::from_rows([
653        [a, b, 0.0, c],
654        [d, e, 0.0, f],
655        [0.0, 0.0, 1.0, 0.0],
656        [g, h, 0.0, i],
657    ])
658}
659
660/// The scene a layer shows, or `None`.
661pub fn scene_of(layer: LayerRef<'_>) -> Option<&Scene3d> {
662    match layer.graphics_layer().space.as_deref()? {
663        LayerSpace::Scene(scene) => Some(scene),
664        LayerSpace::Surface(_) | LayerSpace::Transform(_) => None,
665    }
666}
667
668/// Visits the space tree of each scene the window shows from `layer` down,
669/// what its eye sees of it, and the map from the scene's own coordinates,
670/// the top left of its layer's bounds at the origin, to the window, given
671/// `to_window` for `layer`.
672pub fn for_each_window_eye(
673    layer: LayerRef<'_>,
674    to_window: ProjectiveTransform,
675    visit: &mut dyn FnMut(&SpaceTree<'_>, &EyeView<'_>, ProjectiveTransform),
676) {
677    for_each_window_scene(layer, to_window, &mut |scene_layer, to_window| {
678        let Some(tree) = SpaceTree::of(scene_layer) else {
679            return;
680        };
681        let rect = scene_layer.local_bounds();
682        let view = EyeView::of(&tree, rect.size());
683        visit(
684            &tree,
685            &view,
686            ProjectiveTransform::translation(rect.x, rect.y).then(to_window),
687        );
688    });
689}
690
691impl EyeView<'_> {
692    /// The map from the layer of seen surface `seen` to the window, as the
693    /// eye shows it, given `to_window` for the scene's own coordinates;
694    /// `None` for a surface whose mesh carries no texture plane.
695    pub fn content_to_window(
696        &self,
697        seen: &SeenSurface<'_>,
698        to_window: ProjectiveTransform,
699    ) -> Option<ProjectiveTransform> {
700        let content = seen.content;
701        seen.surface
702            .content_transform(&self.camera, self.size, content.size())
703            .map(|shown| {
704                ProjectiveTransform::translation(-content.x, -content.y)
705                    .then(shown)
706                    .then(to_window)
707            })
708    }
709}
710
711/// Visits each scene the window shows from `layer` down: a layer that
712/// shows a scene outside every other scene's space, with the map from its
713/// local space into the window, given `to_window` for `layer`.
714pub fn for_each_window_scene<'a>(
715    layer: LayerRef<'a>,
716    to_window: ProjectiveTransform,
717    visit: &mut dyn FnMut(LayerRef<'a>, ProjectiveTransform),
718) {
719    if scene_of(layer).is_some() {
720        visit(layer, to_window);
721        return;
722    }
723    for child in layer.children() {
724        if child.has_space() {
725            for_each_window_scene(child, child.transform_to_parent().then(to_window), visit);
726        }
727    }
728}