]> git.tdb.fi Git - libs/math.git/blob - source/geometry/halfspace.h
f671629e56194b0a93a00220c5ef17ef0c6ad0f7
[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 x = -inner_product(ray.get_start(), normal)/inner_product(ray.get_direction(), normal);
67         if(ray.check_limits(x))
68         {
69                 if(points && size>0)
70                 {
71                         points[0].position = ray.get_start()+ray.get_direction()*x;
72                         points[0].normal = normal;
73                         points[0].distance = x;
74                 }
75
76                 return 1;
77         }
78
79         return 0;
80 }
81
82 } // namespace Geometry
83 } // namespace Msp
84
85 #endif