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

Revision 2947, 12.9 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 GetMinDistance(const Plane3 &near) const;
193        /** Returns the distance between the plane given by 'vecNearplaneNormal' and the vertex that
194            is farthest to it (this vertex is unequivocally identified by the direction of the vector)
195        */
196        float GetMaxDistance(const Plane3 &near) const;
197       
198        /** Returns cross section of the plane as a polygon.
199        */
200        Polygon3 *CrossSection(const Plane3 &plane) const;
201        /** Returns the supporting plane of this face.
202        */
203        Plane3 GetPlane(const int face) const;
204        /** Returns
205                0 if box intersects plane
206                1 if box in front of plane
207                -1 if box behind plane
208        */
209        int Side(const Plane3 &plane) const;
210        /**  Calculates the intersection of the polyhedron with the box.
211        */
212        Polyhedron *CalcIntersection(const Polyhedron &polyhedron) const;
213        /** Tests for intersection of the ray with the box.
214        */
215        bool Intersects(const SimpleRay &ray, float &tnear, float &tfar) const;
216        /** Extracts the box sides as polygons.
217        */
218        void ExtractPolygons(PolygonContainer &polys) const;
219
220
221        ////////////
222        //-- friend functions
223
224        /// Overlap returns 1 if the two axis-aligned boxes overlap .. even weakly
225        friend inline bool Overlap(const AxisAlignedBox3 &, const AxisAlignedBox3 &);
226
227        /// Overlap returns 1 if the two axis-aligned boxes overlap .. only strongly
228        friend inline bool OverlapS(const AxisAlignedBox3 &,const AxisAlignedBox3 &);
229
230        /** Overlap returns 1 if the two axis-aligned boxes overlap for a given epsilon.
231        If eps > 0.0, then the boxes has to have the real intersection
232        box, if eps < 0.0, then the boxes need not intersect really, they
233        can be at eps distance in the projection.
234        */
235        friend inline bool Overlap(const AxisAlignedBox3 &,     const AxisAlignedBox3 &, float eps);
236
237
238        // Returns the smallest axis-aligned box that includes all points
239        // inside the two given boxes.
240        friend inline AxisAlignedBox3 Union(const AxisAlignedBox3 &x,
241                                                const AxisAlignedBox3 &y);
242
243        // Returns the intersection of two axis-aligned boxes.
244        friend inline AxisAlignedBox3 Intersect(const AxisAlignedBox3 &x,
245                                                    const AxisAlignedBox3 &y);
246
247        // Given 4x4 matrix, transform the current box to new one.
248        friend inline AxisAlignedBox3 Transform(const AxisAlignedBox3 &box,
249                                                    const Matrix4x4 &tform);
250
251
252        // returns true when two boxes are completely equal
253        friend inline int operator== (const AxisAlignedBox3 &A,
254                                          const AxisAlignedBox3 &B);
255
256        // input and output operator with stream
257        friend std::ostream& operator<<(std::ostream &s, const AxisAlignedBox3 &A);
258        friend std::istream& operator>>(std::istream &s, AxisAlignedBox3 &A);
259
260
261
262        // The vertices that form boundaries of the projected bounding box
263        // for all the regions possible, number of regions is 3^3 = 27,
264        // since two parallel sides of bbox forms three disjoint spaces
265        // the vertices are given in anti-clockwise order .. stopped by -1 elem.
266        static const int bvertices[27][9];
267
268        // The list of all faces visible from a given region (except region 13)
269        // the faces are identified by triple: (axis, min-vertex, max-vertex),
270        // that is maximaly three triples are defined. axis = 0 (x-axis),
271        // axis = 1 (y-axis), axis = 2 (z-axis), -1 .. terminator. Is is always
272        // true that: min-vertex < max-vertex for all coordinates excluding axis
273        static const int bfaces[27][10];
274
275        // The correct corners indexed starting from entry face to exit face
276        // first index determines entry face, second index exit face, and
277        // the two numbers (indx, inc) determines: ind = the index on the exit
278        // face, when starting from the vertex 0 on entry face, 'inc' is
279        // the increment when we go on entry face in order 0,1,2,3 to create
280        // convex shaft with the rectangle on exit face. That is, inc = -1 or 1.
281        static const int pairFaceRects[6][6][2];
282
283        // The vertices that form CLOSEST points with respect to the region
284        // for all the regions possible, number of regions is 3^3 = 27,
285        // since two parallel sides of bbox forms three disjoint spaces.
286        // The vertices are given in anti-clockwise order, stopped by -1 elem,
287        // at most 8 points, at least 1 point.
288        static const int cvertices[27][9];
289        static const int csvertices[27][6];
290
291        // The vertices that form FARTHEST points with respect to the region
292        // for all the regions possible, number of regions is 3^3 = 27,
293        // since two parallel sides of bbox forms three disjoint spaces.
294        // The vertices are given in anti-clockwise order, stopped by -1 elem,
295        // at most 8 points, at least 1 point.
296        static const int fvertices[27][9]; 
297        static const int fsvertices[27][9];
298
299        /** Returns the vertex index nearest from the plane specified by the normal.
300        */
301        static int GetIndexNearestVertex(const Vector3 &vecPlaneNormal);
302        /** Returns the vertwx index farthest from the plane specified by the normal.
303        */
304        static int GetIndexFarthestVertex(const Vector3 &vecPlaneNormal);
305
306
307
308protected:
309
310        Vector3 mMin, mMax;
311};
312
313
314// --------------------------------------------------------------------------
315// Implementation of inline (member) functions
316
317inline bool
318Overlap(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
319{
320        if (x.mMax.x < y.mMin.x ||
321                x.mMin.x > y.mMax.x ||
322                x.mMax.y < y.mMin.y ||
323                x.mMin.y > y.mMax.y ||
324                x.mMax.z < y.mMin.z ||
325                x.mMin.z > y.mMax.z) {
326                        return false;
327        }
328        return true;
329}
330
331inline bool
332OverlapS(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
333{
334        if (x.mMax.x <= y.mMin.x ||
335                x.mMin.x >= y.mMax.x ||
336                x.mMax.y <= y.mMin.y ||
337                x.mMin.y >= y.mMax.y ||
338                x.mMax.z <= y.mMin.z ||
339                x.mMin.z >= y.mMax.z) {
340                        return false;
341        }
342        return true;
343}
344
345inline bool
346Overlap(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y, float eps)
347{
348        if ( (x.mMax.x - eps) < y.mMin.x ||
349                (x.mMin.x + eps) > y.mMax.x ||
350                (x.mMax.y - eps) < y.mMin.y ||
351                (x.mMin.y + eps) > y.mMax.y ||
352                (x.mMax.z - eps) < y.mMin.z ||
353                (x.mMin.z + eps) > y.mMax.z ) {
354                        return false;
355        }
356        return true;
357}
358
359inline AxisAlignedBox3
360Intersect(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
361{
362        if (x.Unbounded())
363                return y;
364        else
365                if (y.Unbounded())
366                        return x;
367        AxisAlignedBox3 ret = x;
368        if (Overlap(ret, y)) {
369                Maximize(ret.mMin, y.mMin);
370                Minimize(ret.mMax, y.mMax);
371                return ret;
372        }
373        else      // Null intersection.
374                return AxisAlignedBox3(Vector3(0), Vector3(0));
375        // return AxisAlignedBox3(Vector3(0), Vector3(-1));
376}
377
378inline AxisAlignedBox3
379Union(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
380{
381        Vector3 min = x.mMin;
382        Vector3 max = x.mMax;
383        Minimize(min, y.mMin);
384        Maximize(max, y.mMax);
385        return AxisAlignedBox3(min, max);
386}
387
388inline AxisAlignedBox3
389Transform(const AxisAlignedBox3 &box, const Matrix4x4 &tform)
390{
391        Vector3 mmin(MAXFLOAT);
392        Vector3 mmax(-MAXFLOAT);
393       
394        AxisAlignedBox3 ret(mmin, mmax);
395       
396        ret.Include(tform * Vector3(box.mMin.x, box.mMin.y, box.mMin.z));
397        ret.Include(tform * Vector3(box.mMin.x, box.mMin.y, box.mMax.z));
398        ret.Include(tform * Vector3(box.mMin.x, box.mMax.y, box.mMin.z));
399        ret.Include(tform * Vector3(box.mMin.x, box.mMax.y, box.mMax.z));
400        ret.Include(tform * Vector3(box.mMax.x, box.mMin.y, box.mMin.z));
401        ret.Include(tform * Vector3(box.mMax.x, box.mMin.y, box.mMax.z));
402        ret.Include(tform * Vector3(box.mMax.x, box.mMax.y, box.mMin.z));
403        ret.Include(tform * Vector3(box.mMax.x, box.mMax.y, box.mMax.z));
404       
405        return ret;
406}
407
408inline float RatioOfOverlap(const AxisAlignedBox3 &box1, const AxisAlignedBox3 &box2)
409{
410        // return ratio of intersection to union
411        const AxisAlignedBox3 bisect = Intersect(box1, box2);
412        const AxisAlignedBox3 bunion = Union(box1, box2);
413
414        return bisect.GetVolume() / bunion.GetVolume();
415}
416
417inline int operator==(const AxisAlignedBox3 &A, const AxisAlignedBox3 &B)
418{
419        return (A.mMin == B.mMin) && (A.mMax == B.mMax);
420}
421
422
423}
424
425
426#endif
Note: See TracBrowser for help on using the repository browser.