1 #ifndef MSP_GEOMETRY_HYPERSPHERE_H_
2 #define MSP_GEOMETRY_HYPERSPHERE_H_
5 #include <msp/linal/vector.h>
9 #include "surfacepoint.h"
15 A shape consisting of the points within a specific distance from the origin.
16 Two- and three-dimensional cases are Circle and Sphere, respectively.
18 template<typename T, unsigned D>
19 class HyperSphere: public Shape<T, D>
26 explicit HyperSphere(T);
28 virtual HyperSphere *clone() const;
30 T get_radius() const { return radius; }
32 virtual HyperBox<T, D> get_axis_aligned_bounding_box() const;
33 virtual bool contains(const LinAl::Vector<T, D> &) const;
34 virtual bool check_intersection(const Ray<T, D> &) const;
35 virtual unsigned get_max_ray_intersections() const { return 2; }
36 virtual unsigned get_intersections(const Ray<T, D> &, SurfacePoint<T, D> *, unsigned) const;
39 template<typename T, unsigned D>
40 inline HyperSphere<T, D>::HyperSphere():
44 template<typename T, unsigned D>
45 inline HyperSphere<T, D>::HyperSphere(T r):
49 template<typename T, unsigned D>
50 inline HyperSphere<T, D> *HyperSphere<T, D>::clone() const
52 return new HyperSphere<T, D>(radius);
55 template<typename T, unsigned D>
56 inline HyperBox<T, D> HyperSphere<T, D>::get_axis_aligned_bounding_box() const
58 LinAl::Vector<T, D> dimensions;
59 for(unsigned i=0; i<D; ++i)
60 dimensions[i] = radius;
61 return HyperBox<T, D>(dimensions);
64 template<typename T, unsigned D>
65 inline bool HyperSphere<T, D>::contains(const LinAl::Vector<T, D> &point) const
67 return inner_product(point, point)<=radius*radius;
70 template<typename T, unsigned D>
71 inline bool HyperSphere<T, D>::check_intersection(const Ray<T, D> &ray) const
73 T x = inner_product(ray.get_direction(), ray.get_start());
75 return contains(ray.get_start());
77 return contains(ray.get_start()-ray.get_direction()*x);
80 template<typename T, unsigned D>
81 inline unsigned HyperSphere<T, D>::get_intersections(const Ray<T, D> &ray, SurfacePoint<T, D> *points, unsigned size) const
85 T mid = -inner_product(ray.get_direction(), ray.get_start());
86 LinAl::Vector<T, D> nearest = ray.get_start()+ray.get_direction()*mid;
87 T offset_sq = radius*radius-inner_product(nearest, nearest);
90 T offset = sqrt(offset_sq);
93 for(int i=-1; i<=1; i+=2)
96 if(ray.check_limits(x) && n<size)
100 points[n].position = ray.get_start()+ray.get_direction()*x;
101 points[n].normal = normalize(points[n].position);
102 points[n].distance = x;
114 } // namespace Geometry