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

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