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
151impl<'a> SpaceTree<'a> {
152    /// The spaces and surfaces of the scene `scene_layer` shows; `None`
153    /// when it shows none.
154    pub fn of(scene_layer: LayerRef<'a>) -> Option<Self> {
155        let scene = scene_of(scene_layer)?;
156        let mut tree = Self {
157            cells: Vec::new(),
158            surfaces: Vec::new(),
159        };
160        tree.open(scene_layer, scene, None);
161        Some(tree)
162    }
163
164    /// Whether `layer` is one of the tree's scenes.
165    pub fn holds_scene(&self, layer: LayerRef<'_>) -> bool {
166        layer.node_id().is_some()
167            && self
168                .cells
169                .iter()
170                .any(|cell| cell.layer.node_id() == layer.node_id())
171    }
172
173    /// The space an eye that walked through the doorways of the scene nodes
174    /// `path` stands in: as far along the path as its doorways still lead.
175    pub fn cell_along(&self, path: &[usize]) -> usize {
176        let mut cell = 0;
177        for &node in path {
178            let next = self.cells.iter().position(|inner| {
179                inner.parent == Some(cell) && inner.layer.node_id() == Some(NodeId(node))
180            });
181            match next {
182                Some(next) => cell = next,
183                None => break,
184            }
185        }
186        cell
187    }
188
189    /// Maps space `cell` into the window scene's.
190    pub fn to_root(&self, cell: usize) -> Mat4 {
191        let mut transform = Mat4::IDENTITY;
192        let mut at = Some(cell);
193        while let Some(index) = at {
194            let cell = &self.cells[index];
195            transform = transform.then(&cell.to_parent);
196            at = cell.parent;
197        }
198        transform
199    }
200
201    fn open(
202        &mut self,
203        layer: LayerRef<'a>,
204        scene: &'a Scene3d,
205        place: Option<(usize, Mat4, Option<Host>)>,
206    ) {
207        let index = self.cells.len();
208        let cell = match place {
209            None => Cell {
210                layer,
211                scene,
212                parent: None,
213                hole: None,
214                doorway: Mat4::IDENTITY,
215                to_parent: Mat4::IDENTITY,
216            },
217            Some((parent, frame, host)) => {
218                let rect = layer.local_bounds();
219                Cell {
220                    layer,
221                    scene,
222                    parent: Some(parent),
223                    hole: host
224                        .map(|(surface, to_content)| (surface, to_content.bounds_for_rect(rect))),
225                    doorway: Mat4::scaling(Vec3::new(rect.width, rect.height, 1.0))
226                        .then(&Mat4::translation(Vec3::new(rect.x, rect.y, 0.0)))
227                        .then(&frame),
228                    to_parent: scene.camera.doorway(rect).then(&frame),
229                }
230            }
231        };
232        self.cells.push(cell);
233        self.children(layer, &Mat4::IDENTITY, (index, None));
234    }
235
236    fn children(&mut self, layer: LayerRef<'a>, frame: &Mat4, (cell, host): (usize, Option<Host>)) {
237        for child in layer.children() {
238            if !child.has_space() {
239                continue;
240            }
241            let to_parent = child.transform_to_parent();
242            let child_frame = embed(to_parent).then(frame);
243            let child_host =
244                host.map(|(surface, to_content)| (surface, to_parent.then(to_content)));
245            match child.graphics_layer().space.as_deref() {
246                Some(LayerSpace::Scene(scene)) => {
247                    self.open(child, scene, Some((cell, child_frame, child_host)));
248                }
249                Some(LayerSpace::Surface(surfaces)) => {
250                    self.surface(child, surfaces, &child_frame, cell);
251                }
252                Some(LayerSpace::Transform(transform)) => {
253                    self.children(child, &transform.then(&child_frame), (cell, None));
254                }
255                None => self.children(child, &child_frame, (cell, child_host)),
256            }
257        }
258    }
259
260    fn surface(&mut self, layer: LayerRef<'a>, surfaces: &MeshSurfaces, frame: &Mat4, cell: usize) {
261        let content = layer.local_bounds();
262        let index = self.surfaces.len();
263        for (mesh, surface) in surfaces.iter().enumerate() {
264            self.surfaces.push(Placed {
265                layer,
266                surface: surface.placed_by(frame),
267                mesh,
268                cell,
269                content,
270            });
271        }
272        if let Some(to_scene) = self.surfaces[index]
273            .surface
274            .content_to_scene(content.size())
275        {
276            // The children lie in the layer, whose content starts at the
277            // corner of its bounds.
278            let to_content = ProjectiveTransform::translation(-content.x, -content.y);
279            self.children(
280                layer,
281                &embed(to_content).then(&to_scene),
282                (cell, Some((index, to_content))),
283            );
284        }
285    }
286}
287
288#[derive(Clone, Copy, PartialEq, Eq)]
289enum Through {
290    Inward,
291    Outward,
292}
293
294impl<'a> EyeView<'a> {
295    /// What the window's eye sees of `tree`, the scene of a node of `size`:
296    /// it stands where the window scene's [`Scene3d::eye`] says, and sees
297    /// through each doorway whose opening shows on screen.
298    pub fn of(tree: &SpaceTree<'a>, size: Size) -> Self {
299        let root = tree.cells[0].scene;
300        let cell = root
301            .eye
302            .as_ref()
303            .map_or(0, |eye| tree.cell_along(&eye.doorways));
304        let mut view = Self {
305            camera: root.camera,
306            size,
307            cell,
308            seen: vec![SeenSpace {
309                cell,
310                through: None,
311                depth: 0,
312                to_eye: Mat4::IDENTITY,
313                light: tree.cells[cell].scene.light,
314                door: None,
315            }],
316            surfaces: Vec::new(),
317        };
318        view.look_through(tree, (0, None), Rect::from_size(size));
319        let mut seen_of = vec![None; tree.cells.len()];
320        for (index, seen) in view.seen.iter().enumerate() {
321            seen_of[seen.cell] = Some(index);
322        }
323        for placed in &tree.surfaces {
324            let Some(seen) = seen_of[placed.cell] else {
325                continue;
326            };
327            view.surfaces.push(SeenSurface {
328                layer: placed.layer,
329                surface: placed.surface.placed_by(&view.seen[seen].to_eye),
330                mesh: placed.mesh,
331                content: placed.content,
332                seen,
333            });
334        }
335        view
336    }
337
338    fn look_through(
339        &mut self,
340        tree: &SpaceTree<'a>,
341        (seen, came_from): (usize, Option<usize>),
342        opening: Rect,
343    ) {
344        let (cell, to_eye) = (self.seen[seen].cell, self.seen[seen].to_eye);
345        for (inner, space) in tree.cells.iter().enumerate() {
346            if space.parent != Some(cell) || Some(inner) == came_from {
347                continue;
348            }
349            let inner_to_eye = space.to_parent.then(&to_eye);
350            let quad = space.doorway.then(&to_eye);
351            self.through(
352                tree,
353                (seen, inner, inner_to_eye),
354                (quad, Through::Inward),
355                opening,
356            );
357        }
358        let space = &tree.cells[cell];
359        if let Some(outer) = space.parent.filter(|outer| Some(*outer) != came_from)
360            && let Some(from_parent) = space.to_parent.inverse()
361        {
362            let outer_to_eye = from_parent.then(&to_eye);
363            let quad = space.doorway.then(&outer_to_eye);
364            self.through(
365                tree,
366                (seen, outer, outer_to_eye),
367                (quad, Through::Outward),
368                opening,
369            );
370        }
371    }
372
373    fn through(
374        &mut self,
375        tree: &SpaceTree<'a>,
376        (seen, cell, to_eye): (usize, usize, Mat4),
377        (quad, through): (Mat4, Through),
378        opening: Rect,
379    ) {
380        let Some(depth) = self.seen[seen].depth.checked_add(1) else {
381            return;
382        };
383        let corner = quad.transform_point(Vec3::ZERO);
384        let Some(normal) = quad.transform_vector(Vec3::new(0.0, 0.0, 1.0)).normalized() else {
385            return;
386        };
387        let side = normal.dot(self.camera.eye() - corner);
388        // A doorway opens one way: into its space from the side its z leaves,
389        // and back out of it from the side its z points to.
390        let (facing, away, clip) = match through {
391            Through::Inward => (side < 0.0, 1.0, plane(normal, corner, 0.0)),
392            Through::Outward => {
393                let margin = BACK_THROUGH_DOORWAY * normal.dot(corner).abs().max(1.0);
394                (side > 0.0, -1.0, plane(-normal, corner, margin))
395            }
396        };
397        let shown = facing
398            .then(|| self.opening(&quad))
399            .flatten()
400            .and_then(|shown| shown.intersect(opening))
401            .filter(|shown| shown.width * shown.height >= SMALLEST_OPENING);
402        let Some(shown) = shown else {
403            return;
404        };
405        let light = tree.cells[cell].scene.light.map(|light| Light {
406            direction: to_eye.transform_vector(light.direction),
407            ..light
408        });
409        self.seen.push(SeenSpace {
410            cell,
411            through: Some(seen),
412            depth,
413            to_eye,
414            light,
415            door: Some(SeenDoor {
416                quad,
417                away,
418                clip,
419                opening: shown,
420            }),
421        });
422        let index = self.seen.len() - 1;
423        self.look_through(tree, (index, Some(self.seen[seen].cell)), shown);
424    }
425
426    fn opening(&self, quad: &Mat4) -> Option<Rect> {
427        let to_camera = quad.then(&self.camera.view);
428        let corners = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
429            .map(|(u, v)| to_camera.transform_point(Vec3::new(u, v, 0.0)));
430        let near = self.camera.near() * DOORWAY_NEAR;
431        let (mut low, mut high) = (
432            (f32::INFINITY, f32::INFINITY),
433            (f32::NEG_INFINITY, f32::NEG_INFINITY),
434        );
435        let mut any = false;
436        let mut show = |point: Vec3| {
437            let scale = self.camera.focal_length / point.z;
438            let (x, y) = (
439                self.size.width * 0.5 + point.x * scale,
440                self.size.height * 0.5 + point.y * scale,
441            );
442            low = (low.0.min(x), low.1.min(y));
443            high = (high.0.max(x), high.1.max(y));
444            any = true;
445        };
446        for (index, &from) in corners.iter().enumerate() {
447            let to = corners[(index + 1) % corners.len()];
448            if from.z >= near {
449                show(from);
450            }
451            if (from.z >= near) != (to.z >= near) {
452                show(from + (to - from) * ((near - from.z) / (to.z - from.z)));
453            }
454        }
455        any.then_some(Rect {
456            x: low.0,
457            y: low.1,
458            width: high.0 - low.0,
459            height: high.1 - low.1,
460        })
461    }
462
463    /// Fills `world` with what the eye can bump into and walk through: the
464    /// space it stands in, the spaces one doorway from it, their solid
465    /// surfaces and the doorways between them, in the eye's space.
466    pub fn build_world(&self, tree: &SpaceTree<'_>, world: &mut EyeWorld) {
467        if let Some(window_scene) = tree.cells[0].layer.node_id() {
468            world.set_window_scene(window_scene.0);
469        }
470        let walked = tree.walked_to(self.cell);
471        let base = world.add_space(Arc::clone(&walked), Mat4::IDENTITY);
472        let mut spaces = vec![(self.cell, base, Mat4::IDENTITY)];
473        let own = &tree.cells[self.cell];
474        if let Some(outer) = own.parent
475            && let Some(from_parent) = own.to_parent.inverse()
476        {
477            let path: Arc<[usize]> = Arc::from(&walked[..walked.len().saturating_sub(1)]);
478            let index = world.add_space(path, from_parent);
479            world.add_doorway((index, base), own.doorway.then(&from_parent));
480            spaces.push((outer, index, from_parent));
481        }
482        for (inner, space) in tree.cells.iter().enumerate() {
483            let (Some(cell), Some(node)) = (space.parent, space.layer.node_id()) else {
484                continue;
485            };
486            if cell != self.cell {
487                continue;
488            }
489            let path: Arc<[usize]> = walked.iter().copied().chain([node.0]).collect();
490            let index = world.add_space(path, space.to_parent);
491            world.add_doorway((base, index), space.doorway);
492            spaces.push((inner, index, space.to_parent));
493        }
494        for (surface_index, placed) in tree.surfaces.iter().enumerate() {
495            let Some(&(_, space, to_base)) =
496                spaces.iter().find(|(cell, _, _)| *cell == placed.cell)
497            else {
498                continue;
499            };
500            if !placed.surface.solid {
501                continue;
502            }
503            let holes = tree.cells.iter().filter_map(|cell| {
504                cell.hole
505                    .filter(|(host, _)| *host == surface_index)
506                    .map(|(_, rect)| rect)
507            });
508            world.add_solid(
509                (space, Arc::clone(&placed.surface.mesh)),
510                placed.surface.transform.then(&to_base),
511                (placed.content.size(), holes),
512            );
513        }
514    }
515}
516
517impl SpaceTree<'_> {
518    fn walked_to(&self, cell: usize) -> Arc<[usize]> {
519        let mut path = Vec::new();
520        let mut at = cell;
521        while let Some(parent) = self.cells[at].parent {
522            if let Some(node) = self.cells[at].layer.node_id() {
523                path.push(node.0);
524            }
525            at = parent;
526        }
527        path.reverse();
528        Arc::from(path)
529    }
530}
531
532fn plane(normal: Vec3, point: Vec3, margin: f32) -> [f32; 4] {
533    [normal.x, normal.y, normal.z, -normal.dot(point) - margin]
534}
535
536/// A plane map of the frame's plane z = 0 as a 3D map: z stays and
537/// distances along it scale as the plane's do not.
538pub fn embed(transform: ProjectiveTransform) -> Mat4 {
539    let [[a, b, c], [d, e, f], [g, h, i]] = transform.matrix();
540    Mat4::from_rows([
541        [a, b, 0.0, c],
542        [d, e, 0.0, f],
543        [0.0, 0.0, 1.0, 0.0],
544        [g, h, 0.0, i],
545    ])
546}
547
548/// The scene a layer shows, or `None`.
549pub fn scene_of(layer: LayerRef<'_>) -> Option<&Scene3d> {
550    match layer.graphics_layer().space.as_deref()? {
551        LayerSpace::Scene(scene) => Some(scene),
552        LayerSpace::Surface(_) | LayerSpace::Transform(_) => None,
553    }
554}
555
556/// Visits the space tree of each scene the window shows from `layer` down,
557/// what its eye sees of it, and the map from the scene's own coordinates,
558/// the top left of its layer's bounds at the origin, to the window, given
559/// `to_window` for `layer`.
560pub fn for_each_window_eye(
561    layer: LayerRef<'_>,
562    to_window: ProjectiveTransform,
563    visit: &mut dyn FnMut(&SpaceTree<'_>, &EyeView<'_>, ProjectiveTransform),
564) {
565    for_each_window_scene(layer, to_window, &mut |scene_layer, to_window| {
566        let Some(tree) = SpaceTree::of(scene_layer) else {
567            return;
568        };
569        let rect = scene_layer.local_bounds();
570        let view = EyeView::of(&tree, rect.size());
571        visit(
572            &tree,
573            &view,
574            ProjectiveTransform::translation(rect.x, rect.y).then(to_window),
575        );
576    });
577}
578
579impl EyeView<'_> {
580    /// The map from the layer of seen surface `seen` to the window, as the
581    /// eye shows it, given `to_window` for the scene's own coordinates;
582    /// `None` for a surface whose mesh carries no texture plane.
583    pub fn content_to_window(
584        &self,
585        seen: &SeenSurface<'_>,
586        to_window: ProjectiveTransform,
587    ) -> Option<ProjectiveTransform> {
588        let content = seen.content;
589        seen.surface
590            .content_transform(&self.camera, self.size, content.size())
591            .map(|shown| {
592                ProjectiveTransform::translation(-content.x, -content.y)
593                    .then(shown)
594                    .then(to_window)
595            })
596    }
597}
598
599/// Visits each scene the window shows from `layer` down: a layer that
600/// shows a scene outside every other scene's space, with the map from its
601/// local space into the window, given `to_window` for `layer`.
602pub fn for_each_window_scene<'a>(
603    layer: LayerRef<'a>,
604    to_window: ProjectiveTransform,
605    visit: &mut dyn FnMut(LayerRef<'a>, ProjectiveTransform),
606) {
607    if scene_of(layer).is_some() {
608        visit(layer, to_window);
609        return;
610    }
611    for child in layer.children() {
612        if child.has_space() {
613            for_each_window_scene(child, child.transform_to_parent().then(to_window), visit);
614        }
615    }
616}