mathUtils.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _MATHUTILS_H_
  23. #define _MATHUTILS_H_
  24. #ifndef _MPOINT3_H_
  25. #include "math/mPoint3.h"
  26. #endif
  27. #ifndef _MMATRIX_H_
  28. #include "math/mMatrix.h"
  29. #endif
  30. #ifndef _MRECT_H_
  31. #include "math/mRect.h"
  32. #endif
  33. #ifndef _TVECTOR_H_
  34. #include "core/util/tVector.h"
  35. #endif
  36. class Box3F;
  37. class RectI;
  38. class Frustum;
  39. /// Miscellaneous math utility functions.
  40. namespace MathUtils
  41. {
  42. /// A simple helper struct to define a line.
  43. struct Line
  44. {
  45. Point3F origin;
  46. VectorF direction;
  47. };
  48. /// A ray is also a line.
  49. typedef Line Ray;
  50. /// A simple helper struct to define a line segment.
  51. struct LineSegment
  52. {
  53. Point3F p0;
  54. Point3F p1;
  55. };
  56. /// A simple helper struct to define a clockwise
  57. /// winding quad.
  58. struct Quad
  59. {
  60. Point3F p00;
  61. Point3F p01;
  62. Point3F p10;
  63. Point3F p11;
  64. };
  65. /// Used by mTriangleDistance() to pass along collision info
  66. struct IntersectInfo
  67. {
  68. LineSegment segment; // Starts at given point, ends at collision
  69. Point3F bary; // Barycentric coords for collision
  70. };
  71. /// Rotate the passed vector around the world-z axis by the passed radians.
  72. void vectorRotateZAxis( Point3F &vector, F32 radians );
  73. void vectorRotateZAxis( F32 radians, Point3F *vectors, U32 count );
  74. /// Generates a projection matrix with the near plane
  75. /// moved forward by the bias amount. This function is a helper primarily
  76. /// for working around z-fighting issues.
  77. ///
  78. /// @param bias The amount to move the near plane forward.
  79. /// @param frustum The frustum to generate the new projection matrix from.
  80. /// @param outMat The resulting z-biased projection matrix. Note: It must be initialized before the call.
  81. /// @param rotate Optional parameter specifying whether to rotate the projection matrix similarly to GFXDevice.
  82. ///
  83. void getZBiasProjectionMatrix( F32 bias, const Frustum &frustum, MatrixF *outMat, bool rotate = true );
  84. /// Creates orientation matrix from a direction vector. Assumes ( 0 0 1 ) is up.
  85. MatrixF createOrientFromDir( const Point3F &direction );
  86. /// Creates an orthonormal basis matrix with the unit length
  87. /// input vector in column 2 (up vector).
  88. ///
  89. /// @param up The non-zero unit length up vector.
  90. /// @param outMat The output matrix which must be initialized prior to the call.
  91. ///
  92. void getMatrixFromUpVector( const VectorF &up, MatrixF *outMat );
  93. /// Creates an orthonormal basis matrix with the unit length
  94. /// input vector in column 1 (forward vector).
  95. ///
  96. /// @param forward The non-zero unit length forward vector.
  97. /// @param outMat The output matrix which must be initialized prior to the call.
  98. ///
  99. void getMatrixFromForwardVector( const VectorF &forward, MatrixF *outMat );
  100. /// Creates random direction given angle parameters similar to the particle system.
  101. ///
  102. /// The angles are relative to the specified axis. Both phi and theta are in degrees.
  103. Point3F randomDir( const Point3F &axis, F32 thetaAngleMin, F32 thetaAngleMax, F32 phiAngleMin = 0.0, F32 phiAngleMax = 360.0 );
  104. /// Returns a random 3D point within a sphere of the specified radius
  105. /// centered at the origin.
  106. Point3F randomPointInSphere( F32 radius );
  107. /// Returns a random 2D point within a circle of the specified radius
  108. /// centered at the origin.
  109. Point2F randomPointInCircle( F32 radius );
  110. /// Returns yaw and pitch angles from a given vector.
  111. ///
  112. /// Angles are in RADIANS.
  113. ///
  114. /// Assumes north is (0.0, 1.0, 0.0), the degrees move upwards clockwise.
  115. ///
  116. /// The range of yaw is 0 - 2PI. The range of pitch is -PI/2 - PI/2.
  117. ///
  118. /// <b>ASSUMES Z AXIS IS UP</b>
  119. void getAnglesFromVector( const VectorF &vec, F32 &yawAng, F32 &pitchAng );
  120. /// Returns vector from given yaw and pitch angles.
  121. ///
  122. /// Angles are in RADIANS.
  123. ///
  124. /// Assumes north is (0.0, 1.0, 0.0), the degrees move upwards clockwise.
  125. ///
  126. /// The range of yaw is 0 - 2PI. The range of pitch is -PI/2 - PI/2.
  127. ///
  128. /// <b>ASSUMES Z AXIS IS UP</b>
  129. void getVectorFromAngles( VectorF &vec, F32 yawAng, F32 pitchAng );
  130. /// Simple reflection equation - pass in a vector and a normal to reflect off of
  131. inline Point3F reflect( Point3F &inVec, Point3F &norm )
  132. {
  133. return inVec - norm * ( mDot( inVec, norm ) * 2.0f );
  134. }
  135. /// Collide two capsules (sphere swept lines) against each other, reporting only if they intersect or not.
  136. /// Based on routine from "Real Time Collision Detection" by Christer Ericson pp 114.
  137. bool capsuleCapsuleOverlap(const Point3F & a1, const Point3F & b1, F32 radius1, const Point3F & a2, const Point3F & b2, F32 radius2);
  138. /// Return capsule-sphere overlap. Returns time of first overlap, where time
  139. /// is viewed as a sphere of radius radA moving from point A0 to A1.
  140. bool capsuleSphereNearestOverlap(const Point3F & A0, const Point3F A1, F32 radA, const Point3F & B, F32 radB, F32 & t);
  141. /// Intersect two line segments (p1,q1) and (p2,q2), returning points on lines (c1 & c2) and line parameters (s,t).
  142. /// Based on routine from "Real Time Collision Detection" by Christer Ericson pp 149.
  143. F32 segmentSegmentNearest(const Point3F & p1, const Point3F & q1, const Point3F & p2, const Point3F & q2, F32 & s, F32 & t, Point3F & c1, Point3F & c2);
  144. /// Transform bounding box making sure to keep original box entirely contained.
  145. void transformBoundingBox(const Box3F &sbox, const MatrixF &mat, const Point3F scale, Box3F &dbox);
  146. bool mProjectWorldToScreen( const Point3F &in,
  147. Point3F *out,
  148. const RectI &view,
  149. const MatrixF &world,
  150. const MatrixF &projection );
  151. bool mProjectWorldToScreen( const Point3F &in,
  152. Point3F *out,
  153. const RectI &view,
  154. const MatrixF &worldProjection );
  155. void mProjectScreenToWorld( const Point3F &in,
  156. Point3F *out,
  157. const RectI &view,
  158. const MatrixF &world,
  159. const MatrixF &projection,
  160. F32 far,
  161. F32 near);
  162. /// Clip @a inFrustum by the given polygon.
  163. ///
  164. /// @note The input polygon is limited to 58 vertices.
  165. ///
  166. /// @param points Polygon vertices.
  167. /// @param numPoints Number of vertices in @a points.
  168. /// @param viewport Screen viewport. Note that this corresponds to the root frustum and not necessarily to @a inFrustum.
  169. /// @param world World->view transform.
  170. /// @param projection Projection matrix.
  171. /// @param inFrustum Frustum to clip.
  172. /// @param rootFrustum Frustum corresponding to @a viewport.
  173. /// @param outFrustum Resulting clipped frustum.
  174. ///
  175. /// @return True if the frustum was successfully clipped and @a outFrustum is valid, false otherwise
  176. /// (if, for example, the input polygon is completely outside @a inFrustum).
  177. bool clipFrustumByPolygon( const Point3F* points,
  178. U32 numPoints,
  179. const RectI& viewport,
  180. const MatrixF& world,
  181. const MatrixF& projection,
  182. const Frustum& inFrustum,
  183. const Frustum& rootFrustum,
  184. Frustum& outFrustum );
  185. /// Returns true if the test point is within the polygon.
  186. /// @param verts The array of points which forms the polygon.
  187. /// @param vertCount The number of points in the polygon.
  188. /// @param testPt The point to test.
  189. bool pointInPolygon( const Point2F *verts, U32 vertCount, const Point2F &testPt );
  190. /// Remove all edges from the given polygon that have a total length shorter
  191. /// than @a epsilon.
  192. ///
  193. U32 removeShortPolygonEdges( const Point3F* verts, U32 vertCount, F32 epsilon );
  194. /// Calculates the shortest line segment between two lines.
  195. ///
  196. /// @param outSegment The result where .p0 is the point on line0 and .p1 is the point on line1.
  197. ///
  198. void mShortestSegmentBetweenLines( const Line &line0, const Line &line1, LineSegment *outSegment );
  199. /// Returns the greatest common divisor of two positive integers.
  200. U32 greatestCommonDivisor( U32 u, U32 v );
  201. /// Returns the barycentric coordinates and time of intersection between
  202. /// a line segment and a triangle.
  203. ///
  204. /// @param p1 The first point of the line segment.
  205. /// @param p2 The second point of the line segment.
  206. /// @param t1 The first point of the triangle.
  207. /// @param t2 The second point of the triangle.
  208. /// @param t2 The third point of the triangle.
  209. /// @param outUVW The optional output barycentric coords.
  210. /// @param outT The optional output time of intersection.
  211. ///
  212. /// @return Returns true if a collision occurs.
  213. ///
  214. bool mLineTriangleCollide( const Point3F &p1, const Point3F &p2,
  215. const Point3F &t1, const Point3F &t2, const Point3F &t3,
  216. Point3F *outUVW = NULL,
  217. F32 *outT = NULL );
  218. /// Returns the uv coords and time of intersection between
  219. /// a ray and a quad.
  220. ///
  221. /// @param quad The quad.
  222. /// @param ray The ray.
  223. /// @param outUV The optional output UV coords of the intersection.
  224. /// @param outT The optional output time of intersection.
  225. ///
  226. /// @return Returns true if a collision occurs.
  227. ///
  228. bool mRayQuadCollide( const Quad &quad,
  229. const Ray &ray,
  230. Point2F *outUV = NULL,
  231. F32 *outT = NULL );
  232. /// Returns the distance between a point and triangle 'abc'.
  233. F32 mTriangleDistance( const Point3F &a, const Point3F &b, const Point3F &c, const Point3F &p, IntersectInfo* info=NULL );
  234. /// Returns the normal of the passed triangle 'abc'.
  235. ///
  236. /// If we assume counter-clockwise triangle culling, normal will point
  237. /// out from the 'solid' side of the triangle.
  238. ///
  239. Point3F mTriangleNormal( const Point3F &a, const Point3F &b, const Point3F &c );
  240. /// Returns the closest point on the segment defined by
  241. /// points a, b to the point p.
  242. Point3F mClosestPointOnSegment( const Point3F &a,
  243. const Point3F &b,
  244. const Point3F &p );
  245. /// Sort the passed verts ( Point3F ) in a clockwise or counter-clockwise winding order.
  246. /// Verts must be co-planar and non-collinear.
  247. ///
  248. /// @param quadMat Transform matrix from vert space to quad space.
  249. /// @param clockwise Sort clockwise or counter-clockwise
  250. /// @param verts Array of Point3F verts.
  251. /// @param vertMap Output - Array of vert element ids sorted by winding order.
  252. /// @param count Element count of the verts and vertMap arrays which must be allocated prior to this call.
  253. ///
  254. void sortQuadWindingOrder( const MatrixF &quadMat, bool clockwise, const Point3F *verts, U32 *vertMap, U32 count );
  255. /// Same as above except we assume that the passed verts ( Point3F ) are already
  256. /// transformed into 'quad space'. If this was done correctly and the points
  257. /// are coplanar this means their z components will all be zero.
  258. void sortQuadWindingOrder( bool clockwise, const Point3F *verts, U32 *vertMap, U32 count );
  259. ///
  260. /// WORK IN PROGRESS
  261. ///
  262. /// Creates an orthonormal basis matrix from one, two, or three unit length
  263. /// input vectors. If more than one input vector is provided they must be
  264. /// mutually perpendicular.
  265. ///
  266. /// @param rvec Optional unit length right vector.
  267. /// @param fvec Optional unit length forward vector.
  268. /// @param uvec Optional unit length up vector.
  269. /// @param pos Optional position to initialize the matrix.
  270. /// @param outMat The output matrix which must be initialized prior to the call.
  271. ///
  272. void buildMatrix( const VectorF *rvec, const VectorF *fvec, const VectorF *uvec, const VectorF *pos, MatrixF *outMat );
  273. ///
  274. bool reduceFrustum( const Frustum& frustum, const RectI& viewport, const RectF& area, Frustum& outFrustum );
  275. /// Build the frustum near plane dimensions from the parameters.
  276. void makeFrustum( F32 *outLeft,
  277. F32 *outRight,
  278. F32 *outTop,
  279. F32 *outBottom,
  280. F32 fovYInRadians,
  281. F32 aspectRatio,
  282. F32 nearPlane );
  283. /// Build a GFX projection matrix from the frustum parameters
  284. /// including the optional rotation required by GFX.
  285. void makeProjection( MatrixF *outMatrix,
  286. F32 fovYInRadians,
  287. F32 aspectRatio,
  288. F32 nearPlane,
  289. F32 farPlane,
  290. bool gfxRotate );
  291. /// Build a projection matrix from the frustum near plane dimensions
  292. /// including the optional rotation required by GFX.
  293. void makeProjection( MatrixF *outMatrix,
  294. F32 left,
  295. F32 right,
  296. F32 top,
  297. F32 bottom,
  298. F32 nearPlane,
  299. F32 farPlane,
  300. bool gfxRotate );
  301. /// Build an orthographic projection matrix from the frustum near
  302. /// plane dimensions including the optional rotation required by GFX.
  303. void makeOrthoProjection( MatrixF *outMatrix,
  304. F32 left,
  305. F32 right,
  306. F32 top,
  307. F32 bottom,
  308. F32 nearPlane,
  309. F32 farPlane,
  310. bool gfxRotate );
  311. /// Find the intersection of the line going from @a edgeA to @a edgeB with the triangle
  312. /// given by @a faceA, @a faceB, and @a faceC.
  313. /// @param edgeA Starting point of edge.
  314. /// @param edgeB End point of edge.
  315. /// @param faceA First vertex of triangle.
  316. /// @param faceB Second vertex of triangle.
  317. /// @param faceC Third vertex of triangle.
  318. /// @param intersection If there is an intersection, the point of intersection on the triangle's
  319. /// face is stored here.
  320. /// @param True if there is an intersection, false otherwise.
  321. bool edgeFaceIntersect( const Point3F &edgeA, const Point3F &edgeB,
  322. const Point3F &faceA, const Point3F &faceB, const Point3F &faceC, const Point3F &faceD, Point3F *intersection );
  323. /// Find out whether the given polygon is planar.
  324. /// @param vertices Array of vertices of the polygon.
  325. /// @param numVertices Number of vertices in @a vertices.
  326. /// @return True if the polygon is planar, false otherwise.
  327. bool isPlanarPolygon( const Point3F* vertices, U32 numVertices );
  328. /// Find out whether the given polygon is convex.
  329. /// @param vertices Array of vertices of the polygon.
  330. /// @param numVertices Number of vertices in @a vertices.
  331. /// @return True if the polygon is convex, false otherwise.
  332. bool isConvexPolygon( const Point3F* vertices, U32 numVertices );
  333. /// Extrude the given polygon along the given direction.
  334. U32 extrudePolygonEdges( const Point3F* vertices, U32 numVertices, const Point3F& direction, PlaneF* outPlanes );
  335. /// Extrude the edges of the given polygon away from @a fromPoint by constructing a set of planes
  336. /// that each go through @a fromPoint and a pair of vertices.
  337. ///
  338. /// The resulting planes are in the same order as the vertices and have their normals facing *inwards*,
  339. /// i.e. the resulting volume will enclose the polygon's interior space.
  340. ///
  341. /// @param vertices Vertices of the polygon in CCW or CW order (both are acceptable).
  342. /// @param numVertices Number of vertices in @a vertices.
  343. /// @param fromPoint
  344. /// @param outPlanes Array in which the resulting planes are stored. Must have room for at least as many
  345. /// planes are there are edges in the polygon.
  346. ///
  347. /// @return
  348. ///
  349. /// @note The input polygon does not necessarily need to be planar but it must be convex.
  350. U32 extrudePolygonEdgesFromPoint( const Point3F* vertices, U32 numVertices,
  351. const Point3F& fromPoint,
  352. PlaneF* outPlanes );
  353. //void findFarthestPoint( const Point3F* points, U32 numPoints, const Point3F& fromPoint, )
  354. } // namespace MathUtils
  355. #endif // _MATHUTILS_H_