]> git.tdb.fi Git - libs/math.git/blobdiff - source/geometry/hypersphere.h
Beginnings of a geometry library
[libs/math.git] / source / geometry / hypersphere.h
diff --git a/source/geometry/hypersphere.h b/source/geometry/hypersphere.h
new file mode 100644 (file)
index 0000000..8b7d0a4
--- /dev/null
@@ -0,0 +1,71 @@
+#ifndef MSP_GEOMETRY_HYPERSPHERE_H_
+#define MSP_GEOMETRY_HYPERSPHERE_H_
+
+#include <msp/linal/vector.h>
+#include "hyperbox.h"
+#include "ray.h"
+#include "shape.h"
+
+namespace Msp {
+namespace Geometry {
+
+template<typename T, unsigned D>
+class HyperSphere: public Shape<T, D>
+{
+private:
+       T radius;
+
+public:
+       HyperSphere();
+       explicit HyperSphere(T);
+
+       virtual HyperSphere *clone() const;
+
+       T get_radius() const { return radius; }
+
+       virtual HyperBox<T, D> get_axis_aligned_bounding_box() const;
+       virtual bool check_intersection(const Ray<T, D> &) const;
+};
+
+template<typename T, unsigned D>
+inline HyperSphere<T, D>::HyperSphere():
+       radius(1)
+{ }
+
+template<typename T, unsigned D>
+inline HyperSphere<T, D>::HyperSphere(T r):
+       radius(r)
+{ }
+
+template<typename T, unsigned D>
+inline HyperSphere<T, D> *HyperSphere<T, D>::clone() const
+{
+       return new HyperSphere<T, D>(radius);
+}
+
+template<typename T, unsigned D>
+inline HyperBox<T, D> HyperSphere<T, D>::get_axis_aligned_bounding_box() const
+{
+       LinAl::Vector<T, D> dimensions;
+       for(unsigned i=0; i<D; ++i)
+               dimensions[i] = radius;
+       return HyperBox<T, D>(dimensions);
+}
+
+template<typename T, unsigned D>
+inline bool HyperSphere<T, D>::check_intersection(const Ray<T, D> &ray) const
+{
+       T x = inner_product(ray.get_direction(), ray.get_start());
+       if(x>0)
+               return inner_product(ray.get_start(), ray.get_start())<=radius*radius;
+       else
+       {
+               LinAl::Vector<T, D> nearest = ray.get_start()-ray.get_direction()*x;
+               return inner_product(nearest, nearest)<=radius*radius;
+       }
+}
+
+} // namespace Geometry
+} // namespace Msp
+
+#endif