1#[cfg(test)]
4use crate::render::camera::orbit_forward;
5use crate::render::camera::{orbit_eye_position_target, CameraState};
6use crate::render::pga::{sandwich_point, semantic_motor_phase2c};
7use crate::render::telemetry::ObserverStandpoint;
8use crate::tensor::buffer_export::read_tensor_at;
9
10pub const PICK_SENTINEL: u32 = u32::MAX;
12
13pub const FLY_TO_FRAMES: u32 = 24;
15
16pub const Q_COLLAPSED_EPS: f32 = 0.001;
18
19#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub struct CameraFlyTo {
22 pub target: CameraState,
23 pub remaining: u32,
24}
25
26impl CameraFlyTo {
27 #[inline]
28 pub fn is_active(&self) -> bool {
30 self.remaining > 0
31 }
32
33 pub fn start_toward(target: CameraState) -> Self {
35 Self {
36 target: target.clamped(),
37 remaining: FLY_TO_FRAMES,
38 }
39 }
40
41 pub fn advance(&mut self, current: CameraState) -> CameraState {
43 if self.remaining == 0 {
44 return current.clamped();
45 }
46 let t = 1.0 - (self.remaining as f32 / FLY_TO_FRAMES as f32);
47 let blended = lerp_camera(current, self.target, t.clamp(0.0, 1.0));
48 self.remaining = self.remaining.saturating_sub(1);
49 blended
50 }
51}
52
53#[inline]
55pub fn camera_frame_node(node: [f32; 3]) -> CameraState {
56 let [x, y, z] = node;
57 let dist = (x * x + y * y + z * z).sqrt().max(0.05);
58 let yaw = x.atan2(z);
59 let pitch = (y / dist).clamp(-1.0, 1.0).asin();
60 let zoom = (dist * 1.75).clamp(0.35, 48.0);
61 CameraState::new(yaw, pitch, zoom)
62 .with_target([0.0, 0.0, 0.0])
63 .clamped()
64}
65
66#[inline]
67pub fn lerp_camera(a: CameraState, b: CameraState, t: f32) -> CameraState {
69 CameraState {
70 near_plane: a.near_plane + (b.near_plane - a.near_plane) * t,
71 yaw: a.yaw + (b.yaw - a.yaw) * t,
72 pitch: a.pitch + (b.pitch - a.pitch) * t,
73 zoom: a.zoom + (b.zoom - a.zoom) * t,
74 target: [
75 a.target[0] + (b.target[0] - a.target[0]) * t,
76 a.target[1] + (b.target[1] - a.target[1]) * t,
77 a.target[2] + (b.target[2] - a.target[2]) * t,
78 ],
79 sun_dir: [
80 a.sun_dir[0] + (b.sun_dir[0] - a.sun_dir[0]) * t,
81 a.sun_dir[1] + (b.sun_dir[1] - a.sun_dir[1]) * t,
82 a.sun_dir[2] + (b.sun_dir[2] - a.sun_dir[2]) * t,
83 ],
84 sun_intensity: a.sun_intensity + (b.sun_intensity - a.sun_intensity) * t,
85 ambient_intensity: a.ambient_intensity + (b.ambient_intensity - a.ambient_intensity) * t,
86 }
87 .clamped()
88}
89
90pub fn cpu_pick_node_at(
92 tensor: &[u8],
93 canvas_w: f64,
94 canvas_h: f64,
95 pick_x: f64,
96 pick_y: f64,
97 yaw: f32,
98 standpoint: &ObserverStandpoint,
99) -> Option<u32> {
100 let count = crate::tensor::buffer_export::tensor_node_count(tensor).ok()?;
101 if count == 0 {
102 return None;
103 }
104
105 let mut best: Option<(u32, f64)> = None;
106 for i in 0..count {
107 let Ok(t) = read_tensor_at(tensor, i) else {
108 continue;
109 };
110 if !standpoint.temporal_visible(t.t) {
111 continue;
112 }
113 let (px, py, _) = project_xyz_canvas(t.x, t.y, t.z, canvas_w, canvas_h, yaw as f64);
114 let dx = px - pick_x;
115 let dy = py - pick_y;
116 let hit_r = 8.0 + t.alpha as f64 * 6.0;
117 let d2 = dx * dx + dy * dy;
118 if d2 > hit_r * hit_r {
119 continue;
120 }
121 if best.map_or(true, |(_, bd)| d2 < bd) {
122 best = Some((i as u32, d2));
123 }
124 }
125 best.map(|(idx, _)| idx)
126}
127
128pub fn cpu_pick_node_at_camera(
136 tensor: &[u8],
137 canvas_w: u32,
138 canvas_h: u32,
139 pick_x: f64,
140 pick_y: f64,
141 frame_time: f32,
142 camera: CameraState,
143 standpoint: &ObserverStandpoint,
144) -> Option<u32> {
145 if canvas_w == 0
146 || canvas_h == 0
147 || !pick_x.is_finite()
148 || !pick_y.is_finite()
149 || !frame_time.is_finite()
150 {
151 return None;
152 }
153
154 let count = crate::tensor::buffer_export::tensor_node_count(tensor).ok()?;
155 if count == 0 {
156 return None;
157 }
158
159 let pixel_x = pick_x
162 .floor()
163 .clamp(0.0, f64::from(canvas_w.saturating_sub(1)))
164 + 0.5;
165 let pixel_y = pick_y
166 .floor()
167 .clamp(0.0, f64::from(canvas_h.saturating_sub(1)))
168 + 0.5;
169 let aspect = canvas_w as f32 / canvas_h as f32;
170 let view_projection = camera.view_projection(aspect);
171 let camera_eye =
172 orbit_eye_position_target(camera.yaw, camera.pitch, camera.zoom, camera.target);
173
174 let mut best: Option<(u32, f32)> = None;
175 for index in 0..count {
176 let Ok(node) = read_tensor_at(tensor, index) else {
177 continue;
178 };
179 if !node.t.is_finite()
180 || !standpoint.temporal_visible(node.t)
181 || !node.alpha.is_finite()
182 || !node.x.is_finite()
183 || !node.y.is_finite()
184 || !node.z.is_finite()
185 {
186 continue;
187 }
188
189 let temporal_delta = (node.t - standpoint.t_slice).abs();
191 let ramp_width = standpoint.t_window * 0.2;
192 if !ramp_width.is_finite() || standpoint.t_window - temporal_delta <= 0.0 {
193 continue;
194 }
195
196 let local = [node.x, node.y, node.z];
197 let motor = semantic_motor_phase2c(
198 node.v,
199 node.w,
200 node.q,
201 node.sigma,
202 frame_time,
203 node.alpha,
204 node.mu,
205 local,
206 camera_eye,
207 standpoint.standpoint_class,
208 standpoint.epistemic_q,
209 );
210 let world = sandwich_point(motor, local);
211 let clip = transform_point(view_projection, world);
212 if !clip.iter().all(|component| component.is_finite())
213 || clip[3] <= 0.0
214 || clip[2] < 0.0
215 || clip[2] > clip[3]
216 {
217 continue;
218 }
219
220 let ndc_x = clip[0] / clip[3];
221 let ndc_y = clip[1] / clip[3];
222 let center_x = (f64::from(ndc_x) * 0.5 + 0.5) * f64::from(canvas_w);
223 let center_y = (0.5 - f64::from(ndc_y) * 0.5) * f64::from(canvas_h);
224 let point_scale = 0.012 * (0.65 + node.alpha * 0.55);
225 let radius_x = f64::from(point_scale.abs()) * f64::from(canvas_w) * 0.5;
226 let radius_y = f64::from(point_scale.abs()) * f64::from(canvas_h) * 0.5;
227 if radius_x <= 0.0 || radius_y <= 0.0 {
228 continue;
229 }
230 let local_x = (pixel_x - center_x) / radius_x;
231 let local_y = (pixel_y - center_y) / radius_y;
232 if local_x * local_x + local_y * local_y > 1.0 {
233 continue;
234 }
235
236 let depth = clip[2] / clip[3];
237 if best.map_or(true, |(_, best_depth)| depth < best_depth) {
240 best = Some((index as u32, depth));
241 }
242 }
243 best.map(|(index, _)| index)
244}
245
246#[inline]
247fn transform_point(matrix: [[f32; 4]; 4], point: [f32; 3]) -> [f32; 4] {
248 [
249 matrix[0][0] * point[0] + matrix[1][0] * point[1] + matrix[2][0] * point[2] + matrix[3][0],
250 matrix[0][1] * point[0] + matrix[1][1] * point[1] + matrix[2][1] * point[2] + matrix[3][1],
251 matrix[0][2] * point[0] + matrix[1][2] * point[1] + matrix[2][2] * point[2] + matrix[3][2],
252 matrix[0][3] * point[0] + matrix[1][3] * point[1] + matrix[2][3] * point[2] + matrix[3][3],
253 ]
254}
255
256#[inline]
257fn project_xyz_canvas(x: f32, y: f32, z: f32, w: f64, h: f64, yaw: f64) -> (f64, f64, f32) {
258 let cx = yaw.cos() as f32;
259 let sx = yaw.sin() as f32;
260 let xr = x * cx + z * sx;
261 let zr = -x * sx + z * cx;
262 let depth = (1.0 / (1.0 + zr * 0.35)).clamp(0.2, 1.0);
263 let scale = 0.42 * w.min(h) * depth as f64;
264 let px = w * 0.5 + xr as f64 * scale;
265 let py = h * 0.5 - y as f64 * scale;
266 (px, py, depth)
267}
268
269#[cfg(test)]
270mod tests {
271 use super::*;
272 use crate::render::telemetry::STANDPOINT_SPECTATOR;
273 use crate::tensor::buffer_export::{write_tensor_buffer, TensorBufferHeader};
274 use crate::tensor::Tensor10D;
275
276 #[test]
277 fn camera_frame_node_produces_finite_orbit() {
278 let cam = camera_frame_node([1.0, 0.5, -2.0]);
279 assert!(cam.yaw.is_finite());
280 assert!(cam.pitch.is_finite());
281 assert!(cam.zoom.is_finite());
282 }
283
284 #[test]
285 fn fly_to_converges_toward_target() {
286 let target = camera_frame_node([0.0, 1.0, 2.0]);
287 let mut fly = CameraFlyTo::start_toward(target);
288 let mut cam = CameraState::default();
289 for _ in 0..FLY_TO_FRAMES {
290 cam = fly.advance(cam);
291 }
292 assert!((cam.yaw - target.yaw).abs() < 0.05);
293 }
294
295 fn tensor_bytes(nodes: &[Tensor10D]) -> Vec<u8> {
296 let mut bytes = vec![0; TensorBufferHeader::total_bytes(nodes.len())];
297 write_tensor_buffer(nodes, &mut bytes).expect("tensor export");
298 bytes
299 }
300
301 fn pick_observer() -> ObserverStandpoint {
302 ObserverStandpoint::new(0, 0, STANDPOINT_SPECTATOR, 1.0, 0.0, 10.0, 1, 0)
303 }
304
305 fn euclidean_node(x: f32, y: f32, z: f32) -> Tensor10D {
306 Tensor10D {
307 q: 0.0,
308 v: 0.0,
309 w: 0.0,
310 x,
311 y,
312 z,
313 t: 0.0,
314 alpha: 1.0,
315 mu: 0.0,
316 sigma: 0.0,
317 }
318 }
319
320 #[test]
321 fn gpu_oracle_picks_nearest_overlapping_projected_node() {
322 let camera = CameraState::default();
323 let forward = orbit_forward(camera.yaw, camera.pitch);
324 let near = [-forward[0] * 0.5, -forward[1] * 0.5, -forward[2] * 0.5];
327 let bytes = tensor_bytes(&[
328 euclidean_node(0.0, 0.0, 0.0),
329 euclidean_node(near[0], near[1], near[2]),
330 ]);
331 let picked = cpu_pick_node_at_camera(
332 &bytes,
333 800,
334 600,
335 400.0,
336 300.0,
337 0.0,
338 camera,
339 &pick_observer(),
340 );
341 assert_eq!(picked, Some(1), "nearer depth-tested point should win");
342 }
343
344 #[test]
345 fn gpu_oracle_matches_shader_point_footprint_and_pixel_centres() {
346 let bytes = tensor_bytes(&[euclidean_node(0.0, 0.0, 0.0)]);
347 let pick = |x| {
348 cpu_pick_node_at_camera(
349 &bytes,
350 800,
351 600,
352 x,
353 300.0,
354 0.0,
355 CameraState::default(),
356 &pick_observer(),
357 )
358 };
359 assert_eq!(pick(405.0), Some(0), "pixel is inside the shader disc");
360 assert_eq!(pick(407.0), None, "pixel lies outside the shader disc");
361 }
362
363 #[test]
364 fn gpu_oracle_rejects_behind_camera_and_temporally_hidden_nodes() {
365 let camera = CameraState::default();
366 let eye = orbit_eye_position_target(camera.yaw, camera.pitch, camera.zoom, camera.target);
367 let bytes = tensor_bytes(&[
368 euclidean_node(0.0, 0.0, 8.0), euclidean_node(eye[0], eye[1], eye[2]), Tensor10D {
371 t: 20.0,
372 ..euclidean_node(0.0, 0.0, 0.0)
373 },
374 Tensor10D {
375 t: 10.0,
376 ..euclidean_node(0.0, 0.0, 0.0)
377 }, ]);
379 assert_eq!(
380 cpu_pick_node_at_camera(
381 &bytes,
382 800,
383 600,
384 400.0,
385 300.0,
386 0.0,
387 camera,
388 &pick_observer(),
389 ),
390 None
391 );
392 }
393
394 #[test]
395 fn gpu_oracle_rejects_invalid_extents_and_non_finite_pointer() {
396 let bytes = tensor_bytes(&[euclidean_node(0.0, 0.0, 0.0)]);
397 assert_eq!(
398 cpu_pick_node_at_camera(
399 &bytes,
400 0,
401 600,
402 0.0,
403 0.0,
404 0.0,
405 CameraState::default(),
406 &pick_observer(),
407 ),
408 None
409 );
410 assert_eq!(
411 cpu_pick_node_at_camera(
412 &bytes,
413 800,
414 600,
415 f64::NAN,
416 300.0,
417 0.0,
418 CameraState::default(),
419 &pick_observer(),
420 ),
421 None
422 );
423 }
424}