use super::{
frame::FacetFrame,
projection::{ScreenPoint, ScreenSize, project},
};
use glam::Vec3;
use indicatrix::optics::raytracer::Camera;
pub const HANDLE_HIT_RADIUS_PX: f32 = 12.0;
const MAST_PROBE: f32 = 0.1;
const MIN_TIP_LENGTH_PX: f32 = 1e-3;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum HandleKind {
Angle,
Depth,
Index,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HandleLayout {
pub anchor: ScreenPoint,
pub angle_tip: ScreenPoint,
pub depth_tip: ScreenPoint,
pub index_tip: ScreenPoint,
pub angle_dir: (f32, f32),
pub depth_dir: (f32, f32),
pub index_dir: (f32, f32),
pub pixels_per_degree: f32,
pub pixels_per_mast_unit: f32,
pub pixels_per_tooth: f32,
}
impl HandleLayout {
#[must_use]
pub const fn tip(&self, kind: HandleKind) -> ScreenPoint {
match kind {
HandleKind::Angle => self.angle_tip,
HandleKind::Depth => self.depth_tip,
HandleKind::Index => self.index_tip,
}
}
#[must_use]
pub const fn dir(&self, kind: HandleKind) -> (f32, f32) {
match kind {
HandleKind::Angle => self.angle_dir,
HandleKind::Depth => self.depth_dir,
HandleKind::Index => self.index_dir,
}
}
}
fn unit_dir(anchor: ScreenPoint, tip: ScreenPoint, fallback: (f32, f32)) -> (f32, f32) {
let (dx, dy) = anchor.delta_to(tip);
let len = dx.hypot(dy);
if len > MIN_TIP_LENGTH_PX {
(dx / len, dy / len)
} else {
fallback
}
}
#[must_use]
pub fn handle_layout(
frame: &FacetFrame,
camera: &Camera,
size: ScreenSize,
handle_len_world: f32,
) -> Option<HandleLayout> {
if !handle_len_world.is_finite() || handle_len_world <= 0.0 {
return None;
}
let len = handle_len_world;
let centroid: Vec3 = frame.centroid;
let anchor = project(camera, centroid, size)?;
let angle_tip = project(camera, centroid + frame.tangent_theta() * len, size)?;
let depth_tip = project(camera, centroid + frame.normal * len, size)?;
let index_tip = project(camera, centroid + frame.tangent_phi() * len, size)?;
let mast_probe = project(camera, centroid + frame.normal * MAST_PROBE, size)?;
let radius = centroid.x.hypot(centroid.z).max(1e-3);
let tooth_arc = radius * std::f32::consts::TAU / frame.gear_teeth.max(1) as f32;
let tooth_probe = project(camera, centroid + frame.tangent_phi() * tooth_arc, size)?;
Some(HandleLayout {
anchor,
angle_tip,
depth_tip,
index_tip,
angle_dir: unit_dir(anchor, angle_tip, (0.0, -1.0)),
depth_dir: unit_dir(anchor, depth_tip, (1.0, 0.0)),
index_dir: unit_dir(anchor, index_tip, (1.0, 0.0)),
pixels_per_degree: (anchor.distance(angle_tip) / len).to_radians(),
pixels_per_mast_unit: 10.0 * anchor.distance(mast_probe),
pixels_per_tooth: anchor.distance(tooth_probe),
})
}
#[must_use]
pub fn hit_test(layout: &HandleLayout, p: ScreenPoint, radius_px: f32) -> Option<HandleKind> {
[HandleKind::Angle, HandleKind::Depth, HandleKind::Index]
.into_iter()
.map(|kind| (kind, layout.tip(kind).distance(p)))
.filter(|&(_, distance)| distance <= radius_px)
.min_by(|a, b| a.1.total_cmp(&b.1))
.map(|(kind, _)| kind)
}