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

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