source: GTP/trunk/Lib/Vis/Preprocessing/src/AxisAlignedBox3.h @ 1999

Revision 1999, 18.0 KB checked in by mattausch, 18 years ago (diff)
Line 
1#ifndef _AxisAlignedBox3_H__
2#define _AxisAlignedBox3_H__
3
4#include "Rectangle3.h"
5#include "Matrix4x4.h"
6#include "Vector3.h"
7#include "Plane3.h"
8#include "Containers.h"
9
10namespace GtpVisibilityPreprocessor {
11
12class Ray;
13class Polygon3;
14class Mesh;
15struct Triangle3;
16
17/**
18        CAABox class.
19        This is a box in 3-space, defined by min and max
20        corner vectors.  Many useful operations are defined
21        on this
22*/
23class AxisAlignedBox3
24{
25protected:
26        Vector3 mMin, mMax;
27public:
28  // Constructors.
29  AxisAlignedBox3() { }
30 
31  AxisAlignedBox3(const Vector3 &nMin, const Vector3 &nMax)
32  {
33    mMin = nMin; mMax = nMax;
34  }
35
36  /** initialization to the non existing bounding box
37  */
38  void Initialize();
39
40  /** The center of the box
41  */
42  Vector3 Center() const;
43 
44  /** The diagonal of the box
45  */
46  Vector3 Diagonal() const;
47
48  float Center(const int axis) const;
49
50  float Min(const int axis) const;
51
52  float Max(const int axis) const;
53
54  float Size(const int axis) const;
55
56  // Read-only const access tomMin and max vectors using references
57  const Vector3& Min() const;
58  const Vector3& Max() const;
59
60  void Enlarge (const Vector3 &v);
61
62  void SetMin(const Vector3 &v);
63
64  void SetMax(const Vector3 &v);
65
66  void SetMin(int axis, const float value);
67
68  void SetMax(int axis, const float value);
69
70  // Decrease box by given splitting plane
71  void Reduce(int axis, int right, float value);
72 
73
74  // the size of the box along all the axes
75  Vector3 Size() const;
76  float Radius() const { return 0.5f*Magnitude(Size()); }
77  float SqrRadius() const { return 0.5f*SqrMagnitude(Size()); }
78 
79  // Return whether the box is unbounded.  Unbounded boxes appear
80  // when unbounded objects such as quadric surfaces are included.
81  bool Unbounded() const;
82
83  // Expand the axis-aligned box to include the given object.
84  void Include(const Vector3 &newpt);
85  void Include(const Polygon3 &newpoly);
86  void Include(const AxisAlignedBox3 &bbox);
87  void Include (const PolygonContainer &polys);
88  void Include(Mesh *mesh);
89
90  /** Expand the axis-aligned box to include given values in particular axis.
91  */
92  void Include(const int &axis, const float &newBound);
93
94
95  int
96  Side(const Plane3 &plane) const;
97
98  // Overlap returns 1 if the two axis-aligned boxes overlap .. even weakly
99  friend inline bool Overlap(const AxisAlignedBox3 &, const AxisAlignedBox3 &);
100
101  // Overlap returns 1 if the two axis-aligned boxes overlap .. only strongly
102  friend inline bool OverlapS(const AxisAlignedBox3 &,const AxisAlignedBox3 &);
103
104  /** Overlap returns 1 if the two axis-aligned boxes overlap for a given
105          epsilon. If eps > 0.0, then the boxes has to have the real intersection
106          box, if eps < 0.0, then the boxes need not intersect really, they
107          can be at eps distance in the projection.
108          */
109  friend inline bool Overlap(const AxisAlignedBox3 &,
110                                                         const AxisAlignedBox3 &,
111                                                         float eps);
112
113  /** Returns 'factor' of overlap of first box with the second box. i.e., a number
114        between 0 (no overlap) and 1 (same box).
115  */
116  friend inline float RatioOfOverlap(const AxisAlignedBox3 &, const AxisAlignedBox3 &);
117
118  /** Includes returns true if a includes b (completely)
119  */
120  bool Includes(const AxisAlignedBox3 &b) const;
121
122  virtual int IsInside(const Vector3 &v) const;
123 
124  /** Test if the box makes sense.
125  */
126  virtual bool IsCorrect();
127
128  /** To answer true requires the box of real volume of non-zero value.
129  */
130  bool IsSingularOrIncorrect() const;
131
132  /** When the box is not of non-zero or negative surface area.
133  */
134  bool IsCorrectAndNotPoint() const;
135
136  /** Returns true when the box degenerates to a point.
137  */
138  bool IsPoint() const;
139
140  /** Scales the box with the factor.
141  */
142  void Scale(const float scale);
143
144  void Scale(const Vector3 &scale);
145       
146  /** Translates the box with the factor.
147  */
148  void Translate(const Vector3 &shift);
149
150  /** Returns the square of the minimal and maximal distance to
151        a point on the box.
152        */
153  void
154  GetSqrDistances(const Vector3 &point,
155                  float &minDistance,
156                  float &maxDistance
157                  ) const;
158
159  // returns true, when the sphere specified by the origin and radius
160  // fully contains the box
161  bool IsFullyContainedInSphere(const Vector3 &center, float radius) const;
162
163  // returns true, when the volume of the sphere and volume of the
164  // axis aligned box has no intersection
165  bool HasNoIntersectionWithSphere(const Vector3 &center,
166                                   float radius) const;
167
168
169  // Given a sphere described by the center and radius,
170  // the fullowing function returns:
171  //   -1 ... the sphere and the box are completely separate
172  //    0 ... the sphere and the box only partially overlap
173  //    1 ... the sphere contains fully the box
174  //  Note: the case when box fully contains the sphere is not reported
175  //        since it was not required.
176  int MutualPositionWithSphere(const Vector3 &center, float radius) const;
177
178  // Given a cube described by the center and half-size (radius),
179  // the following function returns:
180  //   -1 ... the cube and the box are completely separate
181  //    0 ... the cube and the box only partially overlap
182  //    1 ... the cube contains fully the box
183  int MutualPositionWithCube(const Vector3 &center, float halfSize) const;
184
185
186  Vector3 GetRandomPoint(const Vector3 &r) const;
187  Vector3 GetRandomPoint() const;
188  Vector3 GetRandomSurfacePoint() const;
189  Vector3 GetUniformRandomSurfacePoint() const;
190
191  Vector3 GetPoint(const Vector3 &p) const {
192    return mMin + p*Size();
193  }
194
195  // Returns the smallest axis-aligned box that includes all points
196  // inside the two given boxes.
197  friend inline AxisAlignedBox3 Union(const AxisAlignedBox3 &x,
198                             const AxisAlignedBox3 &y);
199
200  // Returns the intersection of two axis-aligned boxes.
201  friend inline AxisAlignedBox3 Intersect(const AxisAlignedBox3 &x,
202                                 const AxisAlignedBox3 &y);
203
204  // Given 4x4 matrix, transform the current box to new one.
205  friend inline AxisAlignedBox3 Transform(const AxisAlignedBox3 &box,
206                                          const Matrix4x4 &tform);
207
208 
209  // returns true when two boxes are completely equal
210  friend inline int operator== (const AxisAlignedBox3 &A, const AxisAlignedBox3 &B);
211 
212  virtual float SurfaceArea() const;
213  virtual float GetVolume() const {
214    return (mMax.x - mMin.x) * (mMax.y - mMin.y) * (mMax.z - mMin.z);
215  }
216
217  // Six faces are distuinguished by their name.
218  enum EFaces { ID_Back = 0, ID_Left = 1, ID_Bottom = 2, ID_Front = 3,
219                ID_Right = 4, ID_Top = 5};
220 
221  int
222  ComputeMinMaxT(const Vector3 &origin,
223                                 const Vector3 &direction,
224                                 float *tmin,
225                                 float *tmax) const;
226       
227  // Compute tmin and tmax for a ray, whenever required .. need not pierce box
228  int ComputeMinMaxT(const Ray &ray, float *tmin, float *tmax) const;
229
230  // Compute tmin and tmax for a ray, whenever required .. need not pierce box
231  int ComputeMinMaxT(const Ray &ray,
232                                         float *tmin,
233                                         float *tmax,
234                                         EFaces &entryFace,
235                                         EFaces &exitFace) const;
236 
237  // If a ray pierces the box .. returns 1, otherwise 0.
238  // Computes the signed distances for case: tmin < tmax and tmax > 0
239  int GetMinMaxT(const Ray &ray, float *tmin, float *tmax) const;
240  // computes the signed distances for case: tmin < tmax and tmax > 0
241  int GetMinMaxT(const Ray &ray, float *tmin, float *tmax,
242                 EFaces &entryFace, EFaces &exitFace) const;
243 
244  // Writes a brief description of the object, indenting by the given
245  // number of spaces first.
246  virtual void Describe(ostream& app, int ind) const;
247
248  // For edge .. number <0..11> returns two incident vertices
249  void GetEdge(const int edge, Vector3 *a, Vector3 *b) const;
250
251  // Compute the coordinates of one vertex of the box for 0/1 in each axis
252  // 0 .. smaller coordinates, 1 .. large coordinates
253  Vector3 GetVertex(int xAxis, int yAxis, int zAxis) const;
254
255  // Compute the vertex for number N=<0..7>, N = 4*x + 2*y + z, where
256  // x,y,z are either 0 or 1; (0 .. lower coordinate, 1 .. large coordinate)
257  // (xmin,ymin, zmin) .. N = 0, (xmax, ymax, zmax) .. N= 7
258  void GetVertex(const int N, Vector3 &vertex) const;
259
260  Vector3 GetVertex(const int N) const {
261    Vector3 v;
262    GetVertex(N, v);
263    return v;
264  }
265
266  // Returns 1, if the box includes on arbitrary face a given box
267  int IsPiercedByBox(const AxisAlignedBox3 &box, int &axis) const;
268
269
270  int GetFaceVisibilityMask(const Vector3 &position) const;
271  int GetFaceVisibilityMask(const Rectangle3 &rectangle) const;
272
273  Rectangle3 GetFace(const int face) const;
274 
275  /** Extracts plane of bounding box.
276  */
277  Plane3 GetPlane(const int face) const;
278 
279  // For a given point returns the region, where the point is located
280  // there are 27 regions (0..26) .. determined by the planes embedding in the
281  // sides of the bounding box (0 .. lower the position of the box,
282  // 1 .. inside the box, 2 .. greater than box). The region number is given as
283  // R = 9*x + 3*y + z  ; e.g. region .. inside the box is 13.
284  int GetRegionID(const Vector3 &point) const;
285 
286  // Set the corner point of rectangle on the face of bounding box
287  // given by the index number and the rectangle lying on this face
288  //  void GetFaceRectCorner(const CRectLeaf2D *rect, EFaces faceIndx,
289  //                     const int &cornerIndx, Vector3 &cornerPoint);
290
291  // Project the box to a plane given a normal vector of this plane. Computes
292  // the surface area of projected silhouettes for parallel projection.
293  float ProjectToPlaneSA(const Vector3 &normal) const;
294
295  // Computes projected surface area of the box to a given viewing plane
296  // given a viewpoint. This corresponds the probability, the box will
297  // be hit by the ray .. moreover returns .. the region number (0-26).
298  // the function supposes all the points lie of the box lies in the viewing
299  // frustrum !!! The positive halfspace of viewplane has to contain
300  // viewpoint. "projectionType" == 0 .. perspective projection,
301  // == 1 .. parallel projection.
302  float ProjectToPlaneSA(const Plane3 &viewplane,
303                         const Vector3 &viewpoint,
304                         int *tcase,
305                         const float &maxSA,
306                         int projectionType) const;
307
308  // Computes projected surface area of the box to a given viewing plane
309  // and viewpoint. It clipps the area by all the planes given .. they should
310  // define the viewing frustrum. Variable tclip defines, which planes are
311  // used for clipping, parameter 31 is the most general, clip all the plane.
312  // 1 .. clip left, 2 .. clip top, 4 .. clip right, 8 .. clip bottom,
313  // 16 .. clip supporting plane(its normal towards the viewing frustrum).
314  // "typeProjection" == 0 .. perspective projection,
315  // == 1 .. parallel projection
316  float ProjectToPlaneSA(const Plane3 &viewplane,
317                         const Vector3 &viewpoint,
318                         int *tcase, int &tclip,
319                         const Plane3 &leftPlane,
320                         const Plane3 &topPlane,
321                         const Plane3 &rightPlane,
322                         const Plane3 &bottomPlane,
323                         const Plane3 &suppPlane,
324                         const float &maxSA,
325                         int typeProjection) const;
326
327  // Projects the box to a unit sphere enclosing a given viewpoint and
328  // returns the solid angle of the box projected to a unit sphere
329  float ProjectToSphereSA(const Vector3 &viewpoint, int *tcase) const;
330
331  /** Returns vertex indices of edge.
332  */
333  void GetEdge(const int edge, int  &aIdx, int &bIdx) const;
334
335  /** Computes cross section of plane with box (i.e., bounds box).
336          @returns the cross section
337  */
338  Polygon3 *CrossSection(const Plane3 &plane) const;
339
340  /** Computes minimal and maximal t of ray, including the object intersections.
341          @returns true if ray hits the bounding box.
342  */
343  bool GetRaySegment(const Ray &ray, float &minT, float &maxT) const;
344
345  /** If the boxes are intersecting on a common face, this function
346          returns the face intersection, false otherwise.
347   
348          @param neighbour the neighbouring box intersecting with this box.
349  */
350  bool GetIntersectionFace(Rectangle3 &face,
351                                                   const AxisAlignedBox3 &neighbour) const;
352
353  /** Includes the box faces to the mesh description
354  */
355  friend void IncludeBoxInMesh(const AxisAlignedBox3 &box, Mesh &mesh);
356
357  /** Box faces are turned into polygons.
358  */
359  void ExtractPolys(PolygonContainer &polys) const;
360
361  /** Returns true if the mesh intersects the bounding box.
362  */
363  bool Intersects(const Mesh &mesh) const;
364   /** Returns true if the triangle intersects the bounding box.
365  */
366  bool Intersects(const Triangle3 &tri) const;
367  /** Splits the box into two separate boxes with respect to the split plane
368  */
369  void Split(const int axis,
370                         const float value,
371                         AxisAlignedBox3 &left,
372                         AxisAlignedBox3 &right) const;
373
374#define __EXTENT_HACK
375  // get the extent of face
376  float GetExtent(const int &face) const {
377#if defined(__EXTENT_HACK) && defined(__VECTOR_HACK)
378    return mMin[face];
379#else
380    if (face < 3)
381      return mMin[face];
382    else
383      return mMax[face-3];
384#endif
385  }
386
387  // The vertices that form boundaries of the projected bounding box
388  // for all the regions possible, number of regions is 3^3 = 27,
389  // since two parallel sides of bbox forms three disjoint spaces
390  // the vertices are given in anti-clockwise order .. stopped by -1 elem.
391  static const int bvertices[27][9];
392
393  // The list of all faces visible from a given region (except region 13)
394  // the faces are identified by triple: (axis, min-vertex, max-vertex),
395  // that is maximaly three triples are defined. axis = 0 (x-axis),
396  // axis = 1 (y-axis), axis = 2 (z-axis), -1 .. terminator. Is is always
397  // true that: min-vertex < max-vertex for all coordinates excluding axis
398  static const int bfaces[27][10];
399 
400  // The correct corners indexed starting from entry face to exit face
401  // first index determines entry face, second index exit face, and
402  // the two numbers (indx, inc) determines: ind = the index on the exit
403  // face, when starting from the vertex 0 on entry face, 'inc' is
404  // the increment when we go on entry face in order 0,1,2,3 to create
405  // convex shaft with the rectangle on exit face. That is, inc = -1 or 1.
406  static const int pairFaceRects[6][6][2];
407
408  // The vertices that form CLOSEST points with respect to the region
409  // for all the regions possible, number of regions is 3^3 = 27,
410  // since two parallel sides of bbox forms three disjoint spaces.
411  // The vertices are given in anti-clockwise order, stopped by -1 elem,
412  // at most 8 points, at least 1 point.
413  static const int cvertices[27][9];
414  static const int csvertices[27][6];
415
416  // The vertices that form FARTHEST points with respect to the region
417  // for all the regions possible, number of regions is 3^3 = 27,
418  // since two parallel sides of bbox forms three disjoint spaces.
419  // The vertices are given in anti-clockwise order, stopped by -1 elem,
420  // at most 8 points, at least 1 point.
421  static const int fvertices[27][9]; 
422  static const int fsvertices[27][9];
423
424  // input and output operator with stream
425  friend ostream& operator<<(ostream &s, const AxisAlignedBox3 &A);
426  friend istream& operator>>(istream &s, AxisAlignedBox3 &A);
427
428protected:
429  // definition of friend functions
430  friend class Ray;
431};
432
433// --------------------------------------------------------------------------
434// Implementation of inline (member) functions
435 
436inline bool
437Overlap(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
438{
439  if (x.mMax.x < y.mMin.x ||
440      x.mMin.x > y.mMax.x ||
441      x.mMax.y < y.mMin.y ||
442      x.mMin.y > y.mMax.y ||
443      x.mMax.z < y.mMin.z ||
444      x.mMin.z > y.mMax.z) {
445    return false;
446  }
447  return true;
448}
449
450inline bool
451OverlapS(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
452{
453  if (x.mMax.x <= y.mMin.x ||
454      x.mMin.x >= y.mMax.x ||
455      x.mMax.y <= y.mMin.y ||
456      x.mMin.y >= y.mMax.y ||
457      x.mMax.z <= y.mMin.z ||
458      x.mMin.z >= y.mMax.z) {
459    return false;
460  }
461  return true;
462}
463
464inline bool
465Overlap(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y, float eps)
466{
467  if ( (x.mMax.x - eps) < y.mMin.x ||
468       (x.mMin.x + eps) > y.mMax.x ||
469       (x.mMax.y - eps) < y.mMin.y ||
470       (x.mMin.y + eps) > y.mMax.y ||
471       (x.mMax.z - eps) < y.mMin.z ||
472       (x.mMin.z + eps) > y.mMax.z ) {
473    return false;
474  }
475  return true;
476}
477
478inline AxisAlignedBox3
479Intersect(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
480{
481  if (x.Unbounded())
482    return y;
483  else
484    if (y.Unbounded())
485      return x;
486  AxisAlignedBox3 ret = x;
487  if (Overlap(ret, y)) {
488    Maximize(ret.mMin, y.mMin);
489    Minimize(ret.mMax, y.mMax);
490    return ret;
491  }
492  else      // Null intersection.
493    return AxisAlignedBox3(Vector3(0), Vector3(0));
494  // return AxisAlignedBox3(Vector3(0), Vector3(-1));
495}
496
497inline AxisAlignedBox3
498Union(const AxisAlignedBox3 &x, const AxisAlignedBox3 &y)
499{
500  Vector3 min = x.mMin;
501  Vector3 max = x.mMax;
502  Minimize(min, y.mMin);
503  Maximize(max, y.mMax);
504  return AxisAlignedBox3(min, max);
505}
506
507inline AxisAlignedBox3
508Transform(const AxisAlignedBox3 &box, const Matrix4x4 &tform)
509{
510  Vector3 mmin(MAXFLOAT);
511  Vector3 mmax(-MAXFLOAT);
512
513  AxisAlignedBox3 ret(mmin, mmax);
514  ret.Include(tform * Vector3(box.mMin.x, box.mMin.y, box.mMin.z));
515  ret.Include(tform * Vector3(box.mMin.x, box.mMin.y, box.mMax.z));
516  ret.Include(tform * Vector3(box.mMin.x, box.mMax.y, box.mMin.z));
517  ret.Include(tform * Vector3(box.mMin.x, box.mMax.y, box.mMax.z));
518  ret.Include(tform * Vector3(box.mMax.x, box.mMin.y, box.mMin.z));
519  ret.Include(tform * Vector3(box.mMax.x, box.mMin.y, box.mMax.z));
520  ret.Include(tform * Vector3(box.mMax.x, box.mMax.y, box.mMin.z));
521  ret.Include(tform * Vector3(box.mMax.x, box.mMax.y, box.mMax.z));
522  return ret;
523}
524
525inline float RatioOfOverlap(const AxisAlignedBox3 &box1, const AxisAlignedBox3 &box2)
526{
527        // return ratio of intersection to union
528        const AxisAlignedBox3 bisect = Intersect(box1, box2);
529        const AxisAlignedBox3 bunion = Union(box1, box2);
530
531        return bisect.GetVolume() / bunion.GetVolume();
532}
533
534inline int operator==(const AxisAlignedBox3 &A, const AxisAlignedBox3 &B)
535{
536  return (A.mMin == B.mMin) && (A.mMax == B.mMax);
537}
538
539 
540}
541
542
543#endif
Note: See TracBrowser for help on using the repository browser.