use crate::math::{Real, Vector};
use crate::shape::SupportMap;
#[cfg(feature = "alloc")]
use either::Either;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)
)]
#[derive(PartialEq, Debug, Copy, Clone)]
#[repr(C)]
pub struct Cone {
pub half_height: Real,
pub radius: Real,
}
impl Cone {
pub fn new(half_height: Real, radius: Real) -> Cone {
Cone {
half_height,
radius,
}
}
#[cfg(feature = "alloc")]
#[inline]
pub fn scaled(
self,
scale: Vector,
nsubdivs: u32,
) -> Option<Either<Self, super::ConvexPolyhedron>> {
if scale.x != scale.z || scale.y < 0.0 {
let (mut vtx, idx) = self.to_trimesh(nsubdivs);
vtx.iter_mut().for_each(|pt| *pt *= scale);
Some(Either::Right(super::ConvexPolyhedron::from_convex_mesh(
vtx, &idx,
)?))
} else {
Some(Either::Left(Self::new(
self.half_height * scale.y,
self.radius * scale.x,
)))
}
}
}
impl SupportMap for Cone {
#[inline]
fn local_support_point(&self, dir: Vector) -> Vector {
let mut vres = dir;
vres[1] = 0.0;
let (mut vres, length) = vres.normalize_and_length();
if length == 0.0 {
vres = Vector::ZERO;
vres[1] = self.half_height.copysign(dir[1]);
} else {
vres *= self.radius;
vres[1] = -self.half_height;
if dir.dot(vres) < dir[1] * self.half_height {
vres = Vector::ZERO;
vres[1] = self.half_height
}
}
vres
}
}