source: GTP/trunk/App/Demos/Vis/FriendlyCulling/src/AxisAlignedBox3.h @ 2913

Revision 2913, 12.5 KB checked in by mattausch, 16 years ago (diff)
Line 
1#ifndef _AxisAlignedBox3_H__
2#define _AxisAlignedBox3_H__
3
4
5#include "Matrix4x4.h"
6#include "Vector3.h"
7#include "common.h"
8
9
10namespace CHCDemoEngine
11{
12
13struct Triangle3;
14class Plane3;
15class Polygon3;
16class Polyhedron;
17
18
19struct SimpleRay
20{
21        SimpleRay() {}
22
23        SimpleRay(const Vector3 &o, const Vector3 &d): mOrigin(o), mDirection(d) {}
24
25        Vector3 mOrigin;
26        Vector3 mDirection;
27
28        Vector3 Extrap(const float t) const
29        {
30                return mOrigin + mDirection * t;
31        }
32};
33
34
35/** Axis alignedd box class.
36    This is a box in 3-space, defined by min and max
37        corner vectors.  Many useful operations are defined.
38*/
39class AxisAlignedBox3
40{
41
42public:
43
44        ///////////
45        //-- Constructors.
46
47        AxisAlignedBox3();
48
49        AxisAlignedBox3(const Vector3 &nMin, const Vector3 &nMax);
50        /** initialization to the non existing bounding box
51        */
52        void Initialize();
53        /** The center of the box
54        */
55        Vector3 Center() const;
56        /** The diagonal of the box
57        */
58        Vector3 Diagonal() const;
59
60        float Center(const int axis) const;
61
62        float Min(const int axis) const;
63
64        float Max(const int axis) const;
65
66        float Size(const int axis) const;
67
68        // Read-only const access tomMin and max vectors using references
69        const Vector3& Min() const;
70        const Vector3& Max() const;
71
72        void Enlarge(const Vector3 &v);
73
74        void EnlargeToMinSize();
75
76        void SetMin(const Vector3 &v);
77
78        void SetMax(const Vector3 &v);
79
80        void SetMin(int axis, const float value);
81
82        void SetMax(int axis, const float value);
83        /** Decrease box by given splitting plane
84        */
85        void Reduce(int axis, int right, float value);
86
87        bool Intersects(const Vector3 &lStart, const Vector3 &lEnd) const;
88
89        // the size of the box along all the axes
90        Vector3 Size() const;
91        float Radius() const { return 0.5f * Magnitude(Size()); }
92        float SqrRadius() const { return 0.5f * SqrMagnitude(Size()); }
93
94        // Return whether the box is unbounded.  Unbounded boxes appear
95        // when unbounded objects such as quadric surfaces are included.
96        bool Unbounded() const;
97
98        // Expand the axis-aligned box to include the given object.
99        void Include(const Vector3 &newpt);
100        void Include(const AxisAlignedBox3 &bbox);
101        void Include(const Polygon3 &newpoly);
102        void Include(const PolygonContainer &polys);
103       
104        /** Expand the axis-aligned box to include given values in particular axis.
105        */
106        void Include(const int &axis, const float &newBound);
107        /** Includes returns true if a includes b (completely)
108        */
109        bool Includes(const AxisAlignedBox3 &b) const;
110
111        /** Returns true if this point is inside box.
112        */
113        virtual int IsInside(const Vector3 &v) const;
114        /** Test if the box makes sense.
115        */
116        virtual bool IsCorrect();
117        /** To answer true requires the box of real volume of non-zero value.
118        */
119        bool IsSingularOrIncorrect() const;
120        /** When the box is not of non-zero or negative surface area.
121        */
122        bool IsCorrectAndNotPoint() const;
123        /** Returns true when the box degenerates to a point.
124        */
125        bool IsPoint() const;
126        /** Scales the box with the factor.
127        */
128        void Scale(float scale);
129
130        void Scale(const Vector3 &scale);
131        /** Translates the box with the factor.
132        */
133        void Translate(const Vector3 &shift);
134        /** Returns the square of the minimal and maximal distance to
135            a point on the box.
136        */
137        void GetSqrDistances(const Vector3 &point,
138                                 float &minDistance,
139                                                 float &maxDistance) const;
140        /** return random point in box.
141        */
142        Vector3 GetRandomPoint() const;
143        /** Returns surface area of the box.
144        */
145        float SurfaceArea() const;
146        /** Returns volume of the box.
147        */
148        float GetVolume() const;
149
150        // Six faces are distuinguished by their name.
151        enum EFaces {ID_Back = 0,
152                ID_Left = 1,
153                ID_Bottom = 2,
154                ID_Front = 3,
155                ID_Right = 4,
156                ID_Top = 5};
157
158        // Writes a brief description of the object, indenting by the given
159        // number of spaces first.
160        virtual void Describe(std::ostream& app, int ind) const;
161
162        // For edge .. number <0..11> returns two incident vertices
163        void GetEdge(int edge, Vector3 *a, Vector3 *b) const;
164
165        // Compute the coordinates of one vertex of the box for 0/1 in each axis
166        // 0 .. smaller coordinates, 1 .. large coordinates
167        Vector3 GetVertex(int xAxis, int yAxis, int zAxis) const;
168
169        // Compute the vertex for number N=<0..7>, N = 4*x + 2*y + z, where
170        // x,y,z are either 0 or 1; (0 .. lower coordinate, 1 .. large coordinate)
171        // (xmin,ymin, zmin) .. N = 0, (xmax, ymax, zmax) .. N= 7
172        void GetVertex(int N, Vector3 &vertex) const;
173
174        Vector3 GetVertex(int N) const;
175        /** get the extent of face.
176        */
177        float GetExtent(int face) const;
178        /** Returns 1, if the box includes on arbitrary face a given box
179        */
180        int IsPiercedByBox(const AxisAlignedBox3 &box, int &axis) const;
181
182        int GetFaceVisibilityMask(const Vector3 &position) const;
183        /** Returns vertex indices of edge.
184        */
185        void GetEdge(int edge, int  &aIdx, int &bIdx) const;
186        /** Get distance of plane to vertex with specified index.
187        */
188        float GetDistance(int index, const Plane3 &plane) const;
189        /** Returns the distance between the plane given by 'vecNearplaneNormal' and the vertex that
190            is closest to it (this vertex is unequivocally identified by the direction of the vector)
191        */
192        float GetMinVisibleDistance(const Plane3 &near) const;
193        /** Returns cross section of the plane as a polygon.
194        */
195        Polygon3 *CrossSection(const Plane3 &plane) const;
196        /** Returns the supporting plane of this face.
197        */
198        Plane3 GetPlane(const int face) const;
199        /** Returns
200                0 if box intersects plane
201                1 if box in front of plane
202                -1 if box behind plane
203        */
204        int Side(const Plane3 &plane) const;
205        /**  Calculates the intersection of the polyhedron with the box.
206        */
207        Polyhedron *CalcIntersection(const Polyhedron &polyhedron) const;
208
209
210        bool Intersects(const SimpleRay &ray, float &tnear, float &tfar) const;
211
212        ////////////
213        //-- friend functions
214
215        /// Overlap returns 1 if the two axis-aligned boxes overlap .. even weakly
216        friend inline bool Overlap(const AxisAlignedBox3 &, const AxisAlignedBox3 &);
217
218        /// Overlap returns 1 if the two axis-aligned boxes overlap .. only strongly
219        friend inline bool OverlapS(const AxisAlignedBox3 &,const AxisAlignedBox3 &);
220
221        /** Overlap returns 1 if the two axis-aligned boxes overlap for a given epsilon.
222        If eps > 0.0, then the boxes has to have the real intersection
223        box, if eps < 0.0, then the boxes need not intersect really, they
224        can be at eps distance in the projection.
225        */
226        friend inline bool Overlap(const AxisAlignedBox3 &,     const AxisAlignedBox3 &, float eps);
227
228
229        // Returns the smallest axis-aligned box that includes all points
230        // inside the two given boxes.
231        friend inline AxisAlignedBox3 Union(const AxisAlignedBox3 &x,
232                                                const AxisAlignedBox3 &y);
233
234        // Returns the intersection of two axis-aligned boxes.
235        friend inline AxisAlignedBox3 Intersect(const AxisAlignedBox3 &x,
236                                                    const AxisAlignedBox3 &y);
237
238        // Given 4x4 matrix, transform the current box to new one.
239        friend inline AxisAlignedBox3 Transform(const AxisAlignedBox3 &box,
240                                                    const Matrix4x4 &tform);
241
242
243        // returns true when two boxes are completely equal
244        friend inline int operator== (const AxisAlignedBox3 &A,
245                                          const AxisAlignedBox3 &B);
246
247        // input and output operator with stream
248        friend std::ostream& operator<<(std::ostream &s, const AxisAlignedBox3 &A);
249        friend std::istream& operator>>(std::istream &s, AxisAlignedBox3 &A);
250
251
252
253        // The vertices that form boundaries of the projected bounding box
254        // for all the regions possible, number of regions is 3^3 = 27,
255        // since two parallel sides of bbox forms three disjoint spaces
256        // the vertices are given in anti-clockwise order .. stopped by -1 elem.
257        static const int bvertices[27][9];
258
259        // The list of all faces visible from a given region (except region 13)
260        // the faces are identified by triple: (axis, min-vertex, max-vertex),
261        // that is maximaly three triples are defined. axis = 0 (x-axis),
262        // axis = 1 (y-axis), axis = 2 (z-axis), -1 .. terminator. Is is always
263        // true that: min-vertex < max-vertex for all coordinates excluding axis
264        static const int bfaces[27][10];
265
266        // The correct corners indexed starting from entry face to exit face
267        // first index determines entry face, second index exit face, and
268        // the two numbers (indx, inc) determines: ind = the index on the exit
269        // face, when starting from the vertex 0 on entry face, 'inc' is
270        // the increment when we go on entry face in order 0,1,2,3 to create
271        // convex shaft with the rectangle on exit face. That is, inc = -1 or 1.
272        static const int pairFaceRects[6][6][2];
273
274        // The vertices that form CLOSEST points with respect to the region
275        // for all the regions possible, number of regions is 3^3 = 27,
276        // since two parallel sides of bbox forms three disjoint spaces.
277        // The vertices are given in anti-clockwise order, stopped by -1 elem,
278        // at most 8 points, at least 1 point.
279        static const int cvertices[27][9];
280        static const int csvertices[27][6];
281
282        // The vertices that form FARTHEST points with respect to the region
283        // for all the regions possible, number of regions is 3^3 = 27,
284        // since two parallel sides of bbox forms three disjoint spaces.
285        // The vertices are given in anti-clockwise order, stopped by -1 elem,
286        // at most 8 points, at least 1 point.
287        static const int fvertices[27][9]; 
288        static const int fsvertices[27][9];
289
290        /** Returns the vertex index nearest from the plane specified by the normal.
291        */
292        static int GetIndexNearestVertex(const Vector3 &vecPlaneNormal);
293        /** Returns the vertwx index farthest from the plane specified by the normal.
294        */
295        static int GetIndexFarthestVertex(const Vector3 &vecPlaneNormal);
296
297
298
299protected:
300
301        Vector3 mMin, mMax;
302};
303
304
305// --------------------------------------------------------------------------
306// Implementation of inline (member) functions
307
308inline bool
309Overlap(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
310{
311        if (x.mMax.x < y.mMin.x ||
312                x.mMin.x > y.mMax.x ||
313                x.mMax.y < y.mMin.y ||
314                x.mMin.y > y.mMax.y ||
315                x.mMax.z < y.mMin.z ||
316                x.mMin.z > y.mMax.z) {
317                        return false;
318        }
319        return true;
320}
321
322inline bool
323OverlapS(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
324{
325        if (x.mMax.x <= y.mMin.x ||
326                x.mMin.x >= y.mMax.x ||
327                x.mMax.y <= y.mMin.y ||
328                x.mMin.y >= y.mMax.y ||
329                x.mMax.z <= y.mMin.z ||
330                x.mMin.z >= y.mMax.z) {
331                        return false;
332        }
333        return true;
334}
335
336inline bool
337Overlap(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y, float eps)
338{
339        if ( (x.mMax.x - eps) < y.mMin.x ||
340                (x.mMin.x + eps) > y.mMax.x ||
341                (x.mMax.y - eps) < y.mMin.y ||
342                (x.mMin.y + eps) > y.mMax.y ||
343                (x.mMax.z - eps) < y.mMin.z ||
344                (x.mMin.z + eps) > y.mMax.z ) {
345                        return false;
346        }
347        return true;
348}
349
350inline AxisAlignedBox3
351Intersect(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
352{
353        if (x.Unbounded())
354                return y;
355        else
356                if (y.Unbounded())
357                        return x;
358        AxisAlignedBox3 ret = x;
359        if (Overlap(ret, y)) {
360                Maximize(ret.mMin, y.mMin);
361                Minimize(ret.mMax, y.mMax);
362                return ret;
363        }
364        else      // Null intersection.
365                return AxisAlignedBox3(Vector3(0), Vector3(0));
366        // return AxisAlignedBox3(Vector3(0), Vector3(-1));
367}
368
369inline AxisAlignedBox3
370Union(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
371{
372        Vector3 min = x.mMin;
373        Vector3 max = x.mMax;
374        Minimize(min, y.mMin);
375        Maximize(max, y.mMax);
376        return AxisAlignedBox3(min, max);
377}
378
379inline AxisAlignedBox3
380Transform(const AxisAlignedBox3 &box, const Matrix4x4 &tform)
381{
382        Vector3 mmin(MAXFLOAT);
383        Vector3 mmax(-MAXFLOAT);
384       
385        AxisAlignedBox3 ret(mmin, mmax);
386       
387        ret.Include(tform * Vector3(box.mMin.x, box.mMin.y, box.mMin.z));
388        ret.Include(tform * Vector3(box.mMin.x, box.mMin.y, box.mMax.z));
389        ret.Include(tform * Vector3(box.mMin.x, box.mMax.y, box.mMin.z));
390        ret.Include(tform * Vector3(box.mMin.x, box.mMax.y, box.mMax.z));
391        ret.Include(tform * Vector3(box.mMax.x, box.mMin.y, box.mMin.z));
392        ret.Include(tform * Vector3(box.mMax.x, box.mMin.y, box.mMax.z));
393        ret.Include(tform * Vector3(box.mMax.x, box.mMax.y, box.mMin.z));
394        ret.Include(tform * Vector3(box.mMax.x, box.mMax.y, box.mMax.z));
395       
396        return ret;
397}
398
399inline float RatioOfOverlap(const AxisAlignedBox3 &box1, const AxisAlignedBox3 &box2)
400{
401        // return ratio of intersection to union
402        const AxisAlignedBox3 bisect = Intersect(box1, box2);
403        const AxisAlignedBox3 bunion = Union(box1, box2);
404
405        return bisect.GetVolume() / bunion.GetVolume();
406}
407
408inline int operator==(const AxisAlignedBox3 &A, const AxisAlignedBox3 &B)
409{
410        return (A.mMin == B.mMin) && (A.mMax == B.mMax);
411}
412
413
414}
415
416
417#endif
Note: See TracBrowser for help on using the repository browser.