]> git.tdb.fi Git - libs/math.git/blob - source/geometry/halfspace.h
Avoid division by zero in HalfSpace::get_intersections
[libs/math.git] / source / geometry / halfspace.h
1 #ifndef MSP_GEOMETRY_HALFSPACE_H_
2 #define MSP_GEOMETRY_HALFSPACE_H_
3
4 #include "shape.h"
5
6 namespace Msp {
7 namespace Geometry {
8
9 /**
10 An infinite shape consisting of the space on one side of a plane.  Mostly
11 useful when composited with other shapes.
12 */
13 template<typename T, unsigned D>
14 class HalfSpace: public Shape<T, D>
15 {
16 private:
17         LinAl::Vector<T, D> normal;
18
19 public:
20         HalfSpace();
21         HalfSpace(const LinAl::Vector<T, D> &);
22
23         virtual HalfSpace *clone() const;
24
25         const LinAl::Vector<T, D> &get_normal() const { return normal; }
26
27         virtual BoundingBox<T, D> get_axis_aligned_bounding_box() const;
28         virtual bool contains(const LinAl::Vector<T, D> &) const;
29         virtual unsigned get_max_ray_intersections() const { return 1; }
30         virtual unsigned get_intersections(const Ray<T, D> &, SurfacePoint<T, D> *, unsigned) const;
31 };
32
33 template<typename T, unsigned D>
34 inline HalfSpace<T, D>::HalfSpace()
35 {
36         normal[0] = T(1);
37 }
38
39 template<typename T, unsigned D>
40 inline HalfSpace<T, D>::HalfSpace(const LinAl::Vector<T, D> &n):
41         normal(normalize(n))
42 { }
43
44 template<typename T, unsigned D>
45 inline HalfSpace<T, D> *HalfSpace<T, D>::clone() const
46 {
47         return new HalfSpace<T, D>(normal);
48 }
49
50 template<typename T, unsigned D>
51 inline BoundingBox<T, D> HalfSpace<T, D>::get_axis_aligned_bounding_box() const
52 {
53         // XXX If the normal is aligned to an axis, should the bounding box reflect that?
54         return ~BoundingBox<T, D>();
55 }
56
57 template<typename T, unsigned D>
58 inline bool HalfSpace<T, D>::contains(const LinAl::Vector<T, D> &point) const
59 {
60         return inner_product(point, normal)<=T(0);
61 }
62
63 template<typename T, unsigned D>
64 inline unsigned HalfSpace<T, D>::get_intersections(const Ray<T, D> &ray, SurfacePoint<T, D> *points, unsigned size) const
65 {
66         T d = inner_product(ray.get_start(), normal);
67         T c = inner_product(ray.get_direction(), normal);
68         if(c==T(0))
69                 return 0;
70
71         T x = -d/c;
72         if(ray.check_limits(x))
73         {
74                 if(points && size>0)
75                 {
76                         points[0].position = ray.get_start()+ray.get_direction()*x;
77                         points[0].normal = normal;
78                         points[0].distance = x;
79                 }
80
81                 return 1;
82         }
83
84         return 0;
85 }
86
87 } // namespace Geometry
88 } // namespace Msp
89
90 #endif