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