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
20pub 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#[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 collection: u32,
60}
61
62impl SurfaceHolds {
63 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 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 mesh: usize,
138 content: Rect,
141 seen: usize,
142}
143
144impl PickSurface {
145 fn in_layer(&self, point: Point) -> Point {
148 Point::new(point.x + self.content.x, point.y + self.content.y)
149 }
150
151 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 pub fn of(
166 layer: LayerRef<'_>,
167 to_window: ProjectiveTransform,
168 holds: Option<&SurfaceHolds>,
169 ) -> Option<Self> {
170 let tree = SpaceTree::of(layer)?;
173 let holds = holds.cloned().unwrap_or_default();
174 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 pub fn scene(&self) -> Option<NodeId> {
233 self.scene
234 }
235
236 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 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 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 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 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 pub fn drag_point(&self, window: Point, index: usize) -> Option<Point> {
280 self.drag_point_along(self.ray(window)?, index)
281 }
282
283 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 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 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 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 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 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}