Skip to main content

cranpose_render_common/
scene_pick.rs

1use std::{
2    cell::{Cell, RefCell},
3    rc::Rc,
4};
5
6use cranpose_core::NodeId;
7use cranpose_ui_graphics::{
8    Point, Rect, Size,
9    space::{Camera, Mat4, MeshSurface, Ray, SurfaceHit, Vec3},
10};
11
12use crate::{
13    graph::ProjectiveTransform,
14    scene_store::LayerRef,
15    space::{EyeView, SpaceTree},
16};
17
18const PAST_DOORWAY: f32 = 1.0e-4;
19
20/// Finds which mesh surface of a scene a window point, or any ray, shows,
21/// and the point of the surface's content there: the nearest surface along
22/// the ray in the space the window's eye stands in, or behind a doorway the
23/// ray meets first, in the spaces the eye sees. A layer drawn on several
24/// meshes is found by its owner's index, through whichever of its meshes
25/// is nearest.
26pub struct ScenePick {
27    scene: Option<NodeId>,
28    camera: Camera,
29    size: Size,
30    window_to_scene: ProjectiveTransform,
31    scene_to_window: ProjectiveTransform,
32    surfaces: Vec<PickSurface>,
33    seen: Vec<PickSpace>,
34    scenes: Vec<NodeId>,
35    seen_scenes: Vec<NodeId>,
36    last: Cell<Option<LastPick>>,
37    holds: SurfaceHolds,
38}
39
40/// The mesh and triangle the gesture on each surface layer holds, kept
41/// beside a window's hit targets: the targets are collected again whenever
42/// a surface moves, and a drag stays on the mesh it started on through that.
43/// A clone is a handle to the same holds.
44#[derive(Clone, Default)]
45pub struct SurfaceHolds(Rc<Holds>);
46
47#[derive(Default)]
48struct Holds {
49    holds: RefCell<Vec<Hold>>,
50    collection: Cell<u32>,
51}
52
53#[derive(Clone, Copy)]
54struct Hold {
55    layer: NodeId,
56    mesh: usize,
57    triangle: u32,
58    // The last collection of the hit targets that found the layer.
59    collection: u32,
60}
61
62impl SurfaceHolds {
63    /// Starts a new collection of the hit targets: the holds on layers the
64    /// last one did not find go.
65    pub fn collect_again(&self) {
66        let last = self.0.collection.get();
67        self.0
68            .holds
69            .borrow_mut()
70            .retain(|hold| hold.collection == last);
71        self.0.collection.set(last.wrapping_add(1));
72    }
73
74    // The collection finds `layer`: its hold stays.
75    fn keep(&self, layer: NodeId) {
76        let now = self.0.collection.get();
77        if let Some(hold) = self
78            .0
79            .holds
80            .borrow_mut()
81            .iter_mut()
82            .find(|hold| hold.layer == layer)
83        {
84            hold.collection = now;
85        }
86    }
87
88    fn of(&self, layer: NodeId) -> Option<Hold> {
89        self.0
90            .holds
91            .borrow()
92            .iter()
93            .find(|hold| hold.layer == layer)
94            .copied()
95    }
96
97    fn hold(&self, layer: NodeId, mesh: usize, triangle: u32) {
98        let hold = Hold {
99            layer,
100            mesh,
101            triangle,
102            collection: self.0.collection.get(),
103        };
104        let mut holds = self.0.holds.borrow_mut();
105        match holds.iter_mut().find(|held| held.layer == layer) {
106            Some(held) => *held = hold,
107            None => holds.push(hold),
108        }
109    }
110}
111
112struct PickSpace {
113    through: Option<usize>,
114    to_door: Mat4,
115}
116
117impl PickSpace {
118    fn meet(&self, ray: Ray) -> Option<f32> {
119        let origin = self.to_door.transform_point(ray.origin);
120        let direction = self.to_door.transform_vector(ray.direction);
121        if direction.z.abs() < f32::EPSILON {
122            return None;
123        }
124        let distance = -origin.z / direction.z;
125        let at = origin + direction * distance;
126        let inside = (0.0..=1.0).contains(&at.x) && (0.0..=1.0).contains(&at.y);
127        (inside && distance > 0.0).then_some(distance)
128    }
129}
130
131type LastPick = (Point, Option<(usize, SurfaceHit)>);
132
133struct PickSurface {
134    node_id: Option<NodeId>,
135    surface: MeshSurface,
136    // Which of its layer's meshes it is; the owner, 0, comes first.
137    mesh: usize,
138    // The rect of its content in its layer, which the mesh's texture
139    // spans. The pick's content points lie in the layer.
140    content: Rect,
141    seen: usize,
142}
143
144impl PickSurface {
145    // The content point `point`, from the corner of the texture, in the
146    // surface's layer.
147    fn in_layer(&self, point: Point) -> Point {
148        Point::new(point.x + self.content.x, point.y + self.content.y)
149    }
150
151    // Where `ray` meets the surface, its content point in the layer.
152    fn cast(&self, ray: Ray) -> Option<SurfaceHit> {
153        let mut hit = self.surface.cast(ray, self.content.size())?;
154        hit.point = self.in_layer(hit.point);
155        Some(hit)
156    }
157}
158
159impl ScenePick {
160    /// The pick of the scene that `layer` shows, with `to_window` mapping
161    /// the layer to the window; `None` when the layer shows no scene. Its
162    /// surfaces are those the window's eye sees. The gestures on them keep
163    /// the meshes they hold in `holds`, or in the pick's own store when
164    /// `holds` is `None`.
165    pub fn of(
166        layer: LayerRef<'_>,
167        to_window: ProjectiveTransform,
168        holds: Option<&SurfaceHolds>,
169    ) -> Option<Self> {
170        // A hit walk asks every layer: one that opens no scene stops here,
171        // before any transform work.
172        let tree = SpaceTree::of(layer)?;
173        let holds = holds.cloned().unwrap_or_default();
174        // The scene fills its layer's bounds.
175        let bounds = layer.local_bounds();
176        let to_window = ProjectiveTransform::translation(bounds.x, bounds.y).then(to_window);
177        let window_to_scene = to_window.inverse()?;
178        let view = EyeView::of(&tree, bounds.size());
179        let seen_scenes = view
180            .seen
181            .iter()
182            .filter_map(|seen| tree.cells[seen.cell].layer.node_id())
183            .collect();
184        let seen = view
185            .seen
186            .iter()
187            .map(|space| PickSpace {
188                through: space.through,
189                to_door: space
190                    .door
191                    .and_then(|door| door.quad.inverse())
192                    .unwrap_or(Mat4::IDENTITY),
193            })
194            .collect();
195        let surfaces = view
196            .surfaces
197            .into_iter()
198            .map(|seen| {
199                let node_id = seen.layer.node_id();
200                if let Some(layer) = node_id.filter(|_| seen.mesh == 0) {
201                    holds.keep(layer);
202                }
203                PickSurface {
204                    node_id,
205                    surface: seen.surface,
206                    mesh: seen.mesh,
207                    content: seen.content,
208                    seen: seen.seen,
209                }
210            })
211            .collect();
212        Some(Self {
213            scene: layer.node_id(),
214            camera: view.camera,
215            size: view.size,
216            window_to_scene,
217            scene_to_window: to_window,
218            surfaces,
219            seen,
220            scenes: tree
221                .cells
222                .iter()
223                .filter_map(|cell| cell.layer.node_id())
224                .collect(),
225            seen_scenes,
226            last: Cell::new(None),
227            holds,
228        })
229    }
230
231    /// The node of the scene the window shows.
232    pub fn scene(&self) -> Option<NodeId> {
233        self.scene
234    }
235
236    /// Whether `layer` shows one of this scene's spaces, a scene behind one
237    /// of its doorways, whose surfaces this pick finds.
238    pub fn holds_scene(&self, layer: LayerRef<'_>) -> bool {
239        layer
240            .node_id()
241            .is_some_and(|node_id| self.scenes.contains(&node_id))
242    }
243
244    /// Whether the eye sees the space of the scene `layer` shows, through
245    /// the doorways before it.
246    pub fn sees_scene(&self, layer: LayerRef<'_>) -> bool {
247        layer
248            .node_id()
249            .is_some_and(|node_id| self.seen_scenes.contains(&node_id))
250    }
251
252    /// The index among the scene's surfaces of the surface layer `layer`:
253    /// of its owner mesh, the first of its meshes.
254    pub fn index_of(&self, layer: LayerRef<'_>) -> Option<usize> {
255        let node_id = layer.node_id()?;
256        self.surfaces
257            .iter()
258            .position(|surface| surface.node_id == Some(node_id))
259    }
260
261    /// The content point of the layer of owner `index` that the window
262    /// point shows, when one of its meshes is the nearest surface there.
263    pub fn content_point(&self, window: Point, index: usize) -> Option<Point> {
264        let (nearest, hit) = self.nearest(window)?;
265        (self.owner(nearest) == index).then_some(hit.point)
266    }
267
268    /// [`Self::content_point`] for a ray in the space the window's eye
269    /// stands in.
270    pub fn content_point_along(&self, ray: Ray, index: usize) -> Option<Point> {
271        let (nearest, hit) = self.nearest_along(ray)?;
272        (self.owner(nearest) == index).then_some(hit.point)
273    }
274
275    /// The content point of the layer of owner `index` under the window
276    /// point for a gesture the layer holds: where the ray meets the mesh the
277    /// gesture started on, or past its edge, where the ray meets the plane
278    /// of the triangle it last met there.
279    pub fn drag_point(&self, window: Point, index: usize) -> Option<Point> {
280        self.drag_point_along(self.ray(window)?, index)
281    }
282
283    /// [`Self::drag_point`] for a ray in the space the window's eye stands
284    /// in.
285    pub fn drag_point_along(&self, ray: Ray, index: usize) -> Option<Point> {
286        let layer = self.surfaces.get(index)?.node_id;
287        let Some(held) = layer.and_then(|layer| self.holds.of(layer)) else {
288            let (target, hit) = self.nearest_mesh(ray, index)?;
289            self.hold(target, hit.triangle);
290            return Some(hit.point);
291        };
292        let target = index + held.mesh;
293        let surface = self
294            .surfaces
295            .get(target)
296            .filter(|surface| surface.mesh == held.mesh)?;
297        if let Some(hit) = surface.cast(ray) {
298            self.hold(target, hit.triangle);
299            return Some(hit.point);
300        }
301        surface
302            .surface
303            .cast_plane(ray, held.triangle, surface.content.size())
304            .map(|point| surface.in_layer(point))
305    }
306
307    /// Where the content point `content` of the layer of owner `index`
308    /// shows in the window, on its owner mesh, also for a surface behind a
309    /// doorway; `None` when it lies nearer than the camera's near plane or
310    /// behind the eye.
311    pub fn window_point(&self, index: usize, content: Point) -> Option<Point> {
312        let target = self.surfaces.get(index)?;
313        let from_corner = Point::new(content.x - target.content.x, content.y - target.content.y);
314        let at = target
315            .surface
316            .point_at(from_corner, target.content.size())?;
317        let shown = self.camera.project(at, self.size)?;
318        Some(self.scene_to_window.map_point(shown))
319    }
320
321    /// Where `point`, in the space the window's eye stands in, shows in the
322    /// window; `None` behind the eye.
323    pub fn window_point_of(&self, point: Vec3) -> Option<Point> {
324        let shown = self.camera.project(point, self.size)?;
325        Some(self.scene_to_window.map_point(shown))
326    }
327
328    fn ray(&self, window: Point) -> Option<Ray> {
329        let local = self.window_to_scene.map_point(window);
330        self.camera.ray(local, self.size)
331    }
332
333    // The owner of the layer of surface `index`.
334    fn owner(&self, index: usize) -> usize {
335        index - self.surfaces[index].mesh
336    }
337
338    fn hold(&self, index: usize, triangle: u32) {
339        let surface = &self.surfaces[index];
340        if let Some(layer) = surface.node_id {
341            self.holds.hold(layer, surface.mesh, triangle);
342        }
343    }
344
345    // The mesh of the layer of owner `index` that `ray` meets first, by its
346    // index, and where.
347    fn nearest_mesh(&self, ray: Ray, index: usize) -> Option<(usize, SurfaceHit)> {
348        self.surfaces[index..]
349            .iter()
350            .enumerate()
351            .take_while(|(mesh, surface)| surface.mesh == *mesh)
352            .filter_map(|(mesh, surface)| surface.cast(ray).map(|hit| (index + mesh, hit)))
353            .min_by(|(_, a), (_, b)| a.distance.total_cmp(&b.distance))
354    }
355
356    fn nearest(&self, window: Point) -> Option<(usize, SurfaceHit)> {
357        if let Some((point, nearest)) = self.last.get()
358            && point == window
359        {
360            return nearest;
361        }
362        let nearest = self.ray(window).and_then(|ray| self.nearest_along(ray));
363        self.last.set(Some((window, nearest)));
364        nearest
365    }
366
367    // The surface `ray` meets first, by its index, and where; the gesture
368    // on its layer holds it from there.
369    fn nearest_along(&self, ray: Ray) -> Option<(usize, SurfaceHit)> {
370        let nearest = self.nearest_in(ray, 0, f32::NEG_INFINITY);
371        if let Some((index, hit)) = nearest {
372            self.hold(index, hit.triangle);
373        }
374        nearest
375    }
376
377    fn nearest_in(&self, ray: Ray, seen: usize, beyond: f32) -> Option<(usize, SurfaceHit)> {
378        let surface = self
379            .surfaces
380            .iter()
381            .enumerate()
382            .filter(|(_, target)| target.seen == seen)
383            .filter_map(|(index, target)| {
384                target
385                    .cast(ray)
386                    .filter(|hit| hit.distance > beyond)
387                    .map(|hit| (index, hit))
388            })
389            .min_by(|(_, a), (_, b)| a.distance.total_cmp(&b.distance));
390        let doorway = self
391            .seen
392            .iter()
393            .enumerate()
394            .filter(|(_, space)| space.through == Some(seen))
395            .filter_map(|(index, space)| {
396                space
397                    .meet(ray)
398                    .filter(|distance| *distance > beyond)
399                    .map(|distance| (index, distance))
400            })
401            .min_by(|(_, a), (_, b)| a.total_cmp(b));
402        let Some((door, distance)) = doorway.filter(|(_, distance)| {
403            surface.is_none_or(|(_, hit)| *distance <= hit.distance * (1.0 + PAST_DOORWAY))
404        }) else {
405            return surface;
406        };
407        self.nearest_in(ray, door, distance * (1.0 + PAST_DOORWAY))
408            .or(surface)
409    }
410}