mathUtils.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908
  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. #include "platform/platform.h"
  23. #include "math/util/frustum.h"
  24. #include "math/mathUtils.h"
  25. #include "math/mMath.h"
  26. #include "math/mRandom.h"
  27. #include "math/util/frustum.h"
  28. #include "platform/profiler.h"
  29. #include "core/tAlgorithm.h"
  30. namespace MathUtils
  31. {
  32. MRandomLCG sgRandom(0xdeadbeef); ///< Our random number generator.
  33. //-----------------------------------------------------------------------------
  34. bool capsuleCapsuleOverlap(const Point3F & a1, const Point3F & b1, F32 rad1, const Point3F & a2, const Point3F & b2, F32 rad2)
  35. {
  36. F32 s,t;
  37. Point3F c1,c2;
  38. F32 dist = segmentSegmentNearest(a1,b1,a2,b2,s,t,c1,c2);
  39. return dist <= (rad1+rad2)*(rad1+rad2);
  40. }
  41. //-----------------------------------------------------------------------------
  42. F32 segmentSegmentNearest(const Point3F & p1, const Point3F & q1, const Point3F & p2, const Point3F & q2, F32 & s, F32 & t, Point3F & c1, Point3F & c2)
  43. {
  44. Point3F d1 = q1-p1;
  45. Point3F d2 = q2-p2;
  46. Point3F r = p1-p2;
  47. F32 a = mDot(d1,d1);
  48. F32 e = mDot(d2,d2);
  49. F32 f = mDot(d2,r);
  50. const F32 EPSILON = 0.001f;
  51. if (a <= EPSILON && e <= EPSILON)
  52. {
  53. s = t = 0.0f;
  54. c1 = p1;
  55. c2 = p2;
  56. return mDot(c1-c2,c1-c2);
  57. }
  58. if (a <= EPSILON)
  59. {
  60. s = 0.0f;
  61. t = mClampF(f/e,0.0f,1.0f);
  62. }
  63. else
  64. {
  65. F32 c = mDot(d1,r);
  66. if (e <= EPSILON)
  67. {
  68. t = 0.0f;
  69. s = mClampF(-c/a,0.0f,1.0f);
  70. }
  71. else
  72. {
  73. F32 b = mDot(d1,d2);
  74. F32 denom = a*e-b*b;
  75. if (denom != 0.0f)
  76. s = mClampF((b*f-c*e)/denom,0.0f,1.0f);
  77. else
  78. s = 0.0f;
  79. F32 tnom = b*s+f;
  80. if (tnom < 0.0f)
  81. {
  82. t = 0.0f;
  83. s = mClampF(-c/a,0.0f,1.0f);
  84. }
  85. else if (tnom>e)
  86. {
  87. t = 1.0f;
  88. s = mClampF((b-c)/a,0.0f,1.0f);
  89. }
  90. else
  91. t = tnom/e;
  92. }
  93. }
  94. c1 = p1 + d1*s;
  95. c2 = p2 + d2*t;
  96. return mDot(c1-c2,c1-c2);
  97. }
  98. //-----------------------------------------------------------------------------
  99. bool capsuleSphereNearestOverlap(const Point3F & A0, const Point3F A1, F32 radA, const Point3F & B, F32 radB, F32 & t)
  100. {
  101. Point3F V = A1-A0;
  102. Point3F A0B = A0-B;
  103. F32 d1 = mDot(A0B,V);
  104. F32 d2 = mDot(A0B,A0B);
  105. F32 d3 = mDot(V,V);
  106. F32 R2 = (radA+radB)*(radA+radB);
  107. if (d2<R2)
  108. {
  109. // starting in collision state
  110. t=0;
  111. return true;
  112. }
  113. if (d3<0.01f)
  114. // no movement, and don't start in collision state, so no collision
  115. return false;
  116. F32 b24ac = mSqrt(d1*d1-d2*d3+d3*R2);
  117. F32 t1 = (-d1-b24ac)/d3;
  118. if (t1>0 && t1<1.0f)
  119. {
  120. t=t1;
  121. return true;
  122. }
  123. F32 t2 = (-d1+b24ac)/d3;
  124. if (t2>0 && t2<1.0f)
  125. {
  126. t=t2;
  127. return true;
  128. }
  129. if (t1<0 && t2>0)
  130. {
  131. t=0;
  132. return true;
  133. }
  134. return false;
  135. }
  136. //-----------------------------------------------------------------------------
  137. void vectorRotateZAxis( Point3F &vector, F32 radians )
  138. {
  139. F32 sin, cos;
  140. mSinCos(radians, sin, cos);
  141. F32 x = cos * vector.x - sin * vector.y;
  142. F32 y = sin * vector.x + cos * vector.y;
  143. vector.x = x;
  144. vector.y = y;
  145. }
  146. void vectorRotateZAxis( F32 radians, Point3F *vectors, U32 count )
  147. {
  148. F32 sin, cos;
  149. mSinCos(radians, sin, cos);
  150. F32 x, y;
  151. const Point3F *end = vectors + count;
  152. for ( ; vectors != end; vectors++ )
  153. {
  154. x = cos * vectors->x - sin * vectors->y;
  155. y = sin * vectors->x + cos * vectors->y;
  156. vectors->x = x;
  157. vectors->y = y;
  158. }
  159. }
  160. //-----------------------------------------------------------------------------
  161. void getZBiasProjectionMatrix( F32 bias, const Frustum &frustum, MatrixF *outMat, bool rotate )
  162. {
  163. Frustum temp(frustum);
  164. temp.setNearDist(frustum.getNearDist() + bias);
  165. temp.getProjectionMatrix(outMat, rotate);
  166. }
  167. //-----------------------------------------------------------------------------
  168. MatrixF createOrientFromDir( const Point3F &direction )
  169. {
  170. Point3F j = direction;
  171. Point3F k(0.0f, 0.0f, 1.0f);
  172. Point3F i;
  173. mCross( j, k, &i );
  174. if( i.magnitudeSafe() == 0.0f )
  175. {
  176. i.set( 0.0f, -1.0f, 0.0f );
  177. }
  178. i.normalizeSafe();
  179. mCross( i, j, &k );
  180. MatrixF mat( true );
  181. mat.setColumn( 0, i );
  182. mat.setColumn( 1, j );
  183. mat.setColumn( 2, k );
  184. return mat;
  185. }
  186. //-----------------------------------------------------------------------------
  187. void getMatrixFromUpVector( const VectorF &up, MatrixF *outMat )
  188. {
  189. AssertFatal( up.isUnitLength(), "MathUtils::getMatrixFromUpVector() - Up vector was not normalized!" );
  190. AssertFatal( outMat, "MathUtils::getMatrixFromUpVector() - Got null output matrix!" );
  191. AssertFatal( outMat->isAffine(), "MathUtils::getMatrixFromUpVector() - Got uninitialized matrix!" );
  192. VectorF forward = mPerp( up );
  193. VectorF right = mCross( forward, up );
  194. right.normalize();
  195. forward = mCross( up, right );
  196. forward.normalize();
  197. outMat->setColumn( 0, right );
  198. outMat->setColumn( 1, forward );
  199. outMat->setColumn( 2, up );
  200. }
  201. //-----------------------------------------------------------------------------
  202. void getMatrixFromForwardVector( const VectorF &forward, MatrixF *outMat )
  203. {
  204. AssertFatal( forward.isUnitLength(), "MathUtils::getMatrixFromForwardVector() - Forward vector was not normalized!" );
  205. AssertFatal( outMat, "MathUtils::getMatrixFromForwardVector() - Got null output matrix!" );
  206. AssertFatal( outMat->isAffine(), "MathUtils::getMatrixFromForwardVector() - Got uninitialized matrix!" );
  207. VectorF up = mPerp( forward );
  208. VectorF right = mCross( forward, up );
  209. right.normalize();
  210. up = mCross( right, forward );
  211. up.normalize();
  212. outMat->setColumn( 0, right );
  213. outMat->setColumn( 1, forward );
  214. outMat->setColumn( 2, up );
  215. }
  216. //-----------------------------------------------------------------------------
  217. Point3F randomDir( const Point3F &axis, F32 thetaAngleMin, F32 thetaAngleMax,
  218. F32 phiAngleMin, F32 phiAngleMax )
  219. {
  220. MatrixF orient = createOrientFromDir( axis );
  221. Point3F axisx;
  222. orient.getColumn( 0, &axisx );
  223. F32 theta = (thetaAngleMax - thetaAngleMin) * sgRandom.randF() + thetaAngleMin;
  224. F32 phi = (phiAngleMax - phiAngleMin) * sgRandom.randF() + phiAngleMin;
  225. // Both phi and theta are in degs. Create axis angles out of them, and create the
  226. // appropriate rotation matrix...
  227. AngAxisF thetaRot(axisx, theta * (M_PI_F / 180.0f));
  228. AngAxisF phiRot(axis, phi * (M_PI_F / 180.0f));
  229. Point3F ejectionAxis = axis;
  230. MatrixF temp(true);
  231. thetaRot.setMatrix(&temp);
  232. temp.mulP(ejectionAxis);
  233. phiRot.setMatrix(&temp);
  234. temp.mulP(ejectionAxis);
  235. return ejectionAxis;
  236. }
  237. //-----------------------------------------------------------------------------
  238. Point3F randomPointInSphere( F32 radius )
  239. {
  240. AssertFatal( radius > 0.0f, "MathUtils::randomPointInRadius - radius must be positive" );
  241. #define MAX_TRIES 20
  242. Point3F out;
  243. F32 radiusSq = radius * radius;
  244. for ( S32 i = 0; i < MAX_TRIES; i++ )
  245. {
  246. out.x = sgRandom.randF(-radius,radius);
  247. out.y = sgRandom.randF(-radius,radius);
  248. out.z = sgRandom.randF(-radius,radius);
  249. if ( out.lenSquared() < radiusSq )
  250. return out;
  251. }
  252. AssertFatal( false, "MathUtils::randomPointInRadius - something is wrong, should not fail this many times." );
  253. return Point3F::Zero;
  254. }
  255. //-----------------------------------------------------------------------------
  256. Point2F randomPointInCircle( F32 radius )
  257. {
  258. AssertFatal( radius > 0.0f, "MathUtils::randomPointInRadius - radius must be positive" );
  259. #define MAX_TRIES 20
  260. Point2F out;
  261. F32 radiusSq = radius * radius;
  262. for ( S32 i = 0; i < MAX_TRIES; i++ )
  263. {
  264. out.x = sgRandom.randF(-radius,radius);
  265. out.y = sgRandom.randF(-radius,radius);
  266. if ( out.lenSquared() < radiusSq )
  267. return out;
  268. }
  269. AssertFatal( false, "MathUtils::randomPointInRadius - something is wrong, should not fail this many times." );
  270. return Point2F::Zero;
  271. }
  272. //-----------------------------------------------------------------------------
  273. void getAnglesFromVector( const VectorF &vec, F32 &yawAng, F32 &pitchAng )
  274. {
  275. yawAng = mAtan2( vec.x, vec.y );
  276. if( yawAng < 0.0f )
  277. yawAng += M_2PI_F;
  278. if( mFabs(vec.x) > mFabs(vec.y) )
  279. pitchAng = mAtan2( mFabs(vec.z), mFabs(vec.x) );
  280. else
  281. pitchAng = mAtan2( mFabs(vec.z), mFabs(vec.y) );
  282. if( vec.z < 0.0f )
  283. pitchAng = -pitchAng;
  284. }
  285. //-----------------------------------------------------------------------------
  286. void getVectorFromAngles( VectorF &vec, F32 yawAng, F32 pitchAng )
  287. {
  288. VectorF pnt( 0.0f, 1.0f, 0.0f );
  289. EulerF rot( -pitchAng, 0.0f, 0.0f );
  290. MatrixF mat( rot );
  291. rot.set( 0.0f, 0.0f, yawAng );
  292. MatrixF mat2( rot );
  293. mat.mulV( pnt );
  294. mat2.mulV( pnt );
  295. vec = pnt;
  296. }
  297. F32 getAngleBetweenVectors(VectorF vecA, VectorF vecB)
  298. {
  299. F32 dot = mDot(vecA, vecB);
  300. F32 lenSq1 = vecA.lenSquared();
  301. F32 lenSq2 = vecB.lenSquared();
  302. F32 angle = mAcos(dot / mSqrt(lenSq1 * lenSq2));
  303. return angle;
  304. }
  305. //-----------------------------------------------------------------------------
  306. void transformBoundingBox(const Box3F &sbox, const MatrixF &mat, const Point3F scale, Box3F &dbox)
  307. {
  308. Point3F center;
  309. // set transformed center...
  310. sbox.getCenter(&center);
  311. center.convolve(scale);
  312. mat.mulP(center);
  313. dbox.minExtents = center;
  314. dbox.maxExtents = center;
  315. Point3F val;
  316. for(U32 ix=0; ix<2; ix++)
  317. {
  318. if(ix & 0x1)
  319. val.x = sbox.minExtents.x;
  320. else
  321. val.x = sbox.maxExtents.x;
  322. for(U32 iy=0; iy<2; iy++)
  323. {
  324. if(iy & 0x1)
  325. val.y = sbox.minExtents.y;
  326. else
  327. val.y = sbox.maxExtents.y;
  328. for(U32 iz=0; iz<2; iz++)
  329. {
  330. if(iz & 0x1)
  331. val.z = sbox.minExtents.z;
  332. else
  333. val.z = sbox.maxExtents.z;
  334. Point3F v1, v2;
  335. v1 = val;
  336. v1.convolve(scale);
  337. mat.mulP(v1, &v2);
  338. dbox.minExtents.setMin(v2);
  339. dbox.maxExtents.setMax(v2);
  340. }
  341. }
  342. }
  343. }
  344. //-----------------------------------------------------------------------------
  345. bool mProjectWorldToScreen( const Point3F &in,
  346. Point3F *out,
  347. const RectI &view,
  348. const MatrixF &world,
  349. const MatrixF &projection )
  350. {
  351. MatrixF worldProjection = projection;
  352. worldProjection.mul(world);
  353. return mProjectWorldToScreen( in, out, view, worldProjection );
  354. }
  355. //-----------------------------------------------------------------------------
  356. bool mProjectWorldToScreen( const Point3F &in,
  357. Point3F *out,
  358. const RectI &view,
  359. const MatrixF &worldProjection )
  360. {
  361. Point4F temp(in.x,in.y,in.z,1.0f);
  362. worldProjection.mul(temp);
  363. // Perform the perspective division. For orthographic
  364. // projections, temp.w will be 1.
  365. temp.x /= temp.w;
  366. temp.y /= temp.w;
  367. temp.z /= temp.w;
  368. // Take the normalized device coordinates (NDC) and transform them
  369. // into device coordinates.
  370. out->x = (temp.x + 1.0f) / 2.0f * view.extent.x + view.point.x;
  371. out->y = (1.0f - temp.y) / 2.0f * view.extent.y + view.point.y;
  372. out->z = temp.z;
  373. if ( out->z < 0.0f || out->z > 1.0f ||
  374. out->x < (F32)view.point.x || out->x > (F32)view.point.x + (F32)view.extent.x ||
  375. out->y < (F32)view.point.y || out->y > (F32)view.point.y + (F32)view.extent.y )
  376. return false;
  377. return true;
  378. }
  379. //-----------------------------------------------------------------------------
  380. void mProjectScreenToWorld( const Point3F &in,
  381. Point3F *out,
  382. const RectI &view,
  383. const MatrixF &world,
  384. const MatrixF &projection,
  385. F32 zfar,
  386. F32 znear )
  387. {
  388. MatrixF invWorldProjection = projection;
  389. invWorldProjection.mul(world);
  390. invWorldProjection.inverse();
  391. Point3F vec;
  392. vec.x = (in.x - view.point.x) * 2.0f / view.extent.x - 1.0f;
  393. vec.y = -(in.y - view.point.y) * 2.0f / view.extent.y + 1.0f;
  394. vec.z = (znear + in.z * (zfar - znear))/zfar;
  395. invWorldProjection.mulV(vec);
  396. vec *= 1.0f + in.z * zfar;
  397. invWorldProjection.getColumn(3, out);
  398. (*out) += vec;
  399. }
  400. //-----------------------------------------------------------------------------
  401. bool pointInPolygon( const Point2F *verts, U32 vertCount, const Point2F &testPt )
  402. {
  403. U32 i, j, c = 0;
  404. for ( i = 0, j = vertCount-1; i < vertCount; j = i++ )
  405. {
  406. if ( ( ( verts[i].y > testPt.y ) != ( verts[j].y > testPt.y ) ) &&
  407. ( testPt.x < ( verts[j].x - verts[i].x ) *
  408. ( testPt.y - verts[i].y ) /
  409. ( verts[j].y - verts[i].y ) + verts[i].x ) )
  410. c = !c;
  411. }
  412. return c != 0;
  413. }
  414. //-----------------------------------------------------------------------------
  415. F32 mTriangleDistance( const Point3F &A, const Point3F &B, const Point3F &C, const Point3F &P, IntersectInfo* info )
  416. {
  417. Point3F diff = A - P;
  418. Point3F edge0 = B - A;
  419. Point3F edge1 = C - A;
  420. F32 a00 = edge0.lenSquared();
  421. F32 a01 = mDot( edge0, edge1 );
  422. F32 a11 = edge1.lenSquared();
  423. F32 b0 = mDot( diff, edge0 );
  424. F32 b1 = mDot( diff, edge1 );
  425. F32 c = diff.lenSquared();
  426. F32 det = mFabs(a00*a11-a01*a01);
  427. F32 s = a01*b1-a11*b0;
  428. F32 t = a01*b0-a00*b1;
  429. F32 sqrDistance;
  430. if (s + t <= det)
  431. {
  432. if (s < 0.0f)
  433. {
  434. if (t < 0.0f) // region 4
  435. {
  436. if (b0 < 0.0f)
  437. {
  438. t = 0.0f;
  439. if (-b0 >= a00)
  440. {
  441. s = 1.0f;
  442. sqrDistance = a00 + (2.0f)*b0 + c;
  443. }
  444. else
  445. {
  446. s = -b0/a00;
  447. sqrDistance = b0*s + c;
  448. }
  449. }
  450. else
  451. {
  452. s = 0.0f;
  453. if (b1 >= 0.0f)
  454. {
  455. t = 0.0f;
  456. sqrDistance = c;
  457. }
  458. else if (-b1 >= a11)
  459. {
  460. t = 1.0f;
  461. sqrDistance = a11 + 2.0f*b1 + c;
  462. }
  463. else
  464. {
  465. t = -b1/a11;
  466. sqrDistance = b1*t + c;
  467. }
  468. }
  469. }
  470. else // region 3
  471. {
  472. s = 0.0f;
  473. if (b1 >= 0.0f)
  474. {
  475. t = 0.0f;
  476. sqrDistance = c;
  477. }
  478. else if (-b1 >= a11)
  479. {
  480. t = 1.0f;
  481. sqrDistance = a11 + 2.0f*b1 + c;
  482. }
  483. else
  484. {
  485. t = -b1/a11;
  486. sqrDistance = b1*t + c;
  487. }
  488. }
  489. }
  490. else if (t < 0.0f) // region 5
  491. {
  492. t = 0.0f;
  493. if (b0 >= 0.0f)
  494. {
  495. s = 0.0f;
  496. sqrDistance = c;
  497. }
  498. else if (-b0 >= a00)
  499. {
  500. s = 1.0f;
  501. sqrDistance = a00 + 2.0f*b0 + c;
  502. }
  503. else
  504. {
  505. s = -b0/a00;
  506. sqrDistance = b0*s + c;
  507. }
  508. }
  509. else // region 0
  510. {
  511. // minimum at interior point
  512. F32 invDet = 1.0f / det;
  513. s *= invDet;
  514. t *= invDet;
  515. sqrDistance = s * (a00*s + a01*t + 2.0f*b0) +
  516. t * (a01*s + a11*t + 2.0f*b1) + c;
  517. }
  518. }
  519. else
  520. {
  521. F32 tmp0, tmp1, numer, denom;
  522. if (s < 0.0f) // region 2
  523. {
  524. tmp0 = a01 + b0;
  525. tmp1 = a11 + b1;
  526. if (tmp1 > tmp0)
  527. {
  528. numer = tmp1 - tmp0;
  529. denom = a00 - 2.0f*a01 + a11;
  530. if (numer >= denom)
  531. {
  532. s = 1.0f;
  533. t = 0.0f;
  534. sqrDistance = a00 + 2.0f*b0 + c;
  535. }
  536. else
  537. {
  538. s = numer/denom;
  539. t = 1.0f - s;
  540. sqrDistance = s * (a00*s + a01*t + 2.0f*b0) +
  541. t * (a01*s + a11*t + 2.0f*b1) + c;
  542. }
  543. }
  544. else
  545. {
  546. s = 0.0f;
  547. if (tmp1 <= 0.0f)
  548. {
  549. t = 1.0f;
  550. sqrDistance = a11 + 2.0f*b1 + c;
  551. }
  552. else if (b1 >= 0.0f)
  553. {
  554. t = 0.0f;
  555. sqrDistance = c;
  556. }
  557. else
  558. {
  559. t = -b1/a11;
  560. sqrDistance = b1*t + c;
  561. }
  562. }
  563. }
  564. else if (t < 0.0f) // region 6
  565. {
  566. tmp0 = a01 + b1;
  567. tmp1 = a00 + b0;
  568. if (tmp1 > tmp0)
  569. {
  570. numer = tmp1 - tmp0;
  571. denom = a00 - 2.0f*a01 + a11;
  572. if (numer >= denom)
  573. {
  574. t = 1.0f;
  575. s = 0.0f;
  576. sqrDistance = a11 + 2.0f*b1 + c;
  577. }
  578. else
  579. {
  580. t = numer/denom;
  581. s = 1.0f - t;
  582. sqrDistance = s * (a00*s + a01*t + 2.0f*b0) +
  583. t * (a01*s + a11*t + 2.0f*b1) + c;
  584. }
  585. }
  586. else
  587. {
  588. t = 0.0f;
  589. if (tmp1 <= 0.0f)
  590. {
  591. s = 1.0f;
  592. sqrDistance = a00 + 2.0f*b0 + c;
  593. }
  594. else if (b0 >= 0.0f)
  595. {
  596. s = 0.0f;
  597. sqrDistance = c;
  598. }
  599. else
  600. {
  601. s = -b0/a00;
  602. sqrDistance = b0*s + c;
  603. }
  604. }
  605. }
  606. else // region 1
  607. {
  608. numer = a11 + b1 - a01 - b0;
  609. if (numer <= 0.0f)
  610. {
  611. s = 0.0f;
  612. t = 1.0f;
  613. sqrDistance = a11 + 2.0f*b1 + c;
  614. }
  615. else
  616. {
  617. denom = a00 - 2.0f*a01 + a11;
  618. if (numer >= denom)
  619. {
  620. s = 1.0f;
  621. t = 0.0f;
  622. sqrDistance = a00 + 2.0f*b0 + c;
  623. }
  624. else
  625. {
  626. s = numer/denom;
  627. t = 1.0f - s;
  628. sqrDistance = s * (a00*s + a01*t + 2.0f*b0) +
  629. t * (a01*s + a11*t + 2.0f*b1) + c;
  630. }
  631. }
  632. }
  633. }
  634. // account for numerical round-off error
  635. if (sqrDistance < 0.0f)
  636. sqrDistance = 0.0f;
  637. // This also calculates the barycentric coordinates and the closest point!
  638. //m_kClosestPoint0 = P;
  639. //m_kClosestPoint1 = A + s*edge0 + t*edge1;
  640. //m_afTriangleBary[1] = s;
  641. //m_afTriangleBary[2] = t;
  642. //m_afTriangleBary[0] = (Real)1.0 - fS - fT;
  643. if(info)
  644. {
  645. info->segment.p0 = P;
  646. info->segment.p1 = A + s*edge0 + t*edge1;
  647. info->bary.x = s;
  648. info->bary.y = t;
  649. info->bary.z = 1.0f - s - t;
  650. }
  651. return sqrDistance;
  652. }
  653. //-----------------------------------------------------------------------------
  654. Point3F mTriangleNormal( const Point3F &a, const Point3F &b, const Point3F &c )
  655. {
  656. // Vector from b to a.
  657. const F32 ax = a.x-b.x;
  658. const F32 ay = a.y-b.y;
  659. const F32 az = a.z-b.z;
  660. // Vector from b to c.
  661. const F32 cx = c.x-b.x;
  662. const F32 cy = c.y-b.y;
  663. const F32 cz = c.z-b.z;
  664. Point3F n;
  665. // This is an in-line cross product.
  666. n.x = ay*cz - az*cy;
  667. n.y = az*cx - ax*cz;
  668. n.z = ax*cy - ay*cx;
  669. m_point3F_normalize( (F32*)(&n) );
  670. return n;
  671. }
  672. //-----------------------------------------------------------------------------
  673. Point3F mClosestPointOnSegment( const Point3F &a, const Point3F &b, const Point3F &p )
  674. {
  675. Point3F c = p - a; // Vector from a to Point
  676. Point3F v = (b - a);
  677. F32 d = v.len(); // Length of the line segment
  678. v.normalize(); // Unit Vector from a to b
  679. F32 t = mDot( v, c ); // Intersection point Distance from a
  680. // Check to see if the point is on the line
  681. // if not then return the endpoint
  682. if(t < 0) return a;
  683. if(t > d) return b;
  684. // get the distance to move from point a
  685. v *= t;
  686. // move from point a to the nearest point on the segment
  687. return a + v;
  688. }
  689. //-----------------------------------------------------------------------------
  690. void mShortestSegmentBetweenLines( const Line &line0, const Line &line1, LineSegment *outSegment )
  691. {
  692. // compute intermediate parameters
  693. Point3F w0 = line0.origin - line1.origin;
  694. F32 a = mDot( line0.direction, line0.direction );
  695. F32 b = mDot( line0.direction, line1.direction );
  696. F32 c = mDot( line1.direction, line1.direction );
  697. F32 d = mDot( line0.direction, w0 );
  698. F32 e = mDot( line1.direction, w0 );
  699. F32 denom = a*c - b*b;
  700. if ( denom > -0.001f && denom < 0.001f )
  701. {
  702. outSegment->p0 = line0.origin;
  703. outSegment->p1 = line1.origin + (e/c)*line1.direction;
  704. }
  705. else
  706. {
  707. outSegment->p0 = line0.origin + ((b*e - c*d)/denom)*line0.direction;
  708. outSegment->p1 = line1.origin + ((a*e - b*d)/denom)*line1.direction;
  709. }
  710. }
  711. //-----------------------------------------------------------------------------
  712. U32 greatestCommonDivisor( U32 u, U32 v )
  713. {
  714. // http://en.wikipedia.org/wiki/Binary_GCD_algorithm
  715. S32 shift;
  716. /* GCD(0,x) := x */
  717. if (u == 0 || v == 0)
  718. return u | v;
  719. /* Left shift := lg K, where K is the greatest power of 2
  720. dividing both u and v. */
  721. for (shift = 0; ((u | v) & 1) == 0; ++shift) {
  722. u >>= 1;
  723. v >>= 1;
  724. }
  725. while ((u & 1) == 0)
  726. u >>= 1;
  727. /* From here on, u is always odd. */
  728. do {
  729. while ((v & 1) == 0) /* Loop X */
  730. v >>= 1;
  731. /* Now u and v are both odd, so diff(u, v) is even.
  732. Let u = min(u, v), v = diff(u, v)/2. */
  733. if (u < v) {
  734. v -= u;
  735. } else {
  736. U32 diff = u - v;
  737. u = v;
  738. v = diff;
  739. }
  740. v >>= 1;
  741. } while (v != 0);
  742. return u << shift;
  743. }
  744. //-----------------------------------------------------------------------------
  745. bool mLineTriangleCollide( const Point3F &p1, const Point3F &p2,
  746. const Point3F &t1, const Point3F &t2, const Point3F &t3,
  747. Point3F *outUVW, F32 *outT )
  748. {
  749. VectorF ab = t2 - t1;
  750. VectorF ac = t3 - t1;
  751. VectorF qp = p1 - p2;
  752. // Compute triangle normal. Can be precalculated or cached if
  753. // intersecting multiple segments against the same triangle
  754. VectorF n = mCross( ab, ac );
  755. // Compute denominator d. If d <= 0, segment is parallel to or points
  756. // away from triangle, so exit early
  757. F32 d = mDot( qp, n );
  758. if ( d <= 0.0f )
  759. return false;
  760. // Compute intersection t value of pq with plane of triangle. A ray
  761. // intersects if 0 <= t. Segment intersects iff 0 <= t <= 1. Delay
  762. // dividing by d until intersection has been found to pierce triangle
  763. VectorF ap = p1 - t1;
  764. F32 t = mDot( ap, n );
  765. if ( t < 0.0f )
  766. return false;
  767. if ( t > d )
  768. return false; // For segment; exclude this code line for a ray test
  769. // Compute barycentric coordinate components and test if within bounds
  770. VectorF e = mCross( qp, ap );
  771. F32 v = mDot( ac, e );
  772. if ( v < 0.0f || v > d )
  773. return false;
  774. F32 w = -mDot( ab, e );
  775. if ( w < 0.0f || v + w > d )
  776. return false;
  777. // Segment/ray intersects triangle. Perform delayed division and
  778. // compute the last barycentric coordinate component
  779. const F32 ood = 1.0f / d;
  780. if ( outT )
  781. *outT = t * ood;
  782. if ( outUVW )
  783. {
  784. v *= ood;
  785. w *= ood;
  786. outUVW->set( 1.0f - v - w, v, w );
  787. }
  788. return true;
  789. }
  790. //-----------------------------------------------------------------------------
  791. bool mRayQuadCollide( const Quad &quad,
  792. const Ray &ray,
  793. Point2F *outUV,
  794. F32 *outT )
  795. {
  796. static const F32 eps = F32(10e-6);
  797. // Rejects rays that are parallel to Q, and rays that intersect the plane of
  798. // Q either on the left of the line V00V01 or on the right of the line V00V10.
  799. // p01-----eXX-----p11
  800. // ^ . ^ |
  801. // | . |
  802. // e03 e02 eXX
  803. // | . |
  804. // | . |
  805. // p00-----e01---->p10
  806. VectorF e01 = quad.p10 - quad.p00;
  807. VectorF e03 = quad.p01 - quad.p00;
  808. // If the ray is perfectly perpendicular to e03, which
  809. // represents the entire planes tangent, then the
  810. // result of this cross product (P) will equal e01
  811. // If it is parallel it will result in a vector opposite e01.
  812. // If the ray is heading DOWN the cross product will point to the RIGHT
  813. // If the ray is heading UP the cross product will point to the LEFT
  814. // We do not reject based on this though...
  815. //
  816. // In either case cross product will be more parallel to e01 the more
  817. // perpendicular the ray is to e03, and it will be more perpendicular to
  818. // e01 the more parallel it is to e03.
  819. VectorF P = mCross(ray.direction, e03);
  820. // det can be seen as 'the amount of vector e01 in the direction P'
  821. F32 det = mDot(e01, P);
  822. // Take a Abs of the dot because we do not care if the ray is heading up or down,
  823. // but if it is perfectly parallel to the quad we want to reject it.
  824. if ( mFabs(det) < eps )
  825. return false;
  826. F32 inv_det = 1.0f / det;
  827. VectorF T = ray.origin - quad.p00;
  828. // alpha can be seen as 'the amount of vector T in the direction P'
  829. // T is a vector up from the quads corner point 00 to the ray's origin.
  830. // P is the cross product of the ray and e01, which should be "roughly"
  831. // parallel with e03 but might be of either positive or negative magnitude.
  832. F32 alpha = mDot(T, P) * inv_det;
  833. if ( alpha < 0.0f )
  834. return false;
  835. // if (alpha > real(1.0)) return false; // Uncomment if VR is used.
  836. // The cross product of T and e01 should be roughly parallel to e03
  837. // and of either positive or negative magnitude.
  838. VectorF Q = mCross(T, e01);
  839. F32 beta = mDot(ray.direction, Q) * inv_det;
  840. if ( beta < 0.0f )
  841. return false;
  842. // if (beta > real(1.0)) return false; // Uncomment if VR is used.
  843. if ( alpha + beta > 1.0f )
  844. //if ( false )
  845. {
  846. // Rejects rays that intersect the plane of Q either on the
  847. // left of the line V11V10 or on the right of the line V11V01.
  848. VectorF e23 = quad.p01 - quad.p11;
  849. VectorF e21 = quad.p10 - quad.p11;
  850. VectorF P_prime = mCross(ray.direction, e21);
  851. F32 det_prime = mDot(e23, P_prime);
  852. if ( mFabs(det_prime) < eps)
  853. return false;
  854. F32 inv_det_prime = 1.0f / det_prime;
  855. VectorF T_prime = ray.origin - quad.p11;
  856. F32 alpha_prime = mDot(T_prime, P_prime) * inv_det_prime;
  857. if (alpha_prime < 0.0f)
  858. return false;
  859. VectorF Q_prime = mCross(T_prime, e23);
  860. F32 beta_prime = mDot(ray.direction, Q_prime) * inv_det_prime;
  861. if (beta_prime < 0.0f)
  862. return false;
  863. }
  864. // Compute the ray parameter of the intersection point, and
  865. // reject the ray if it does not hit Q.
  866. F32 t = mDot(e03, Q) * inv_det;
  867. if ( t < 0.0f )
  868. return false;
  869. // Compute the barycentric coordinates of the fourth vertex.
  870. // These do not depend on the ray, and can be precomputed
  871. // and stored with the quadrilateral.
  872. F32 alpha_11, beta_11;
  873. VectorF e02 = quad.p11 - quad.p00;
  874. VectorF n = mCross(e01, e03);
  875. if ( mFabs(n.x) >= mFabs(n.y) &&
  876. mFabs(n.x) >= mFabs(n.z) )
  877. {
  878. alpha_11 = ( e02.y * e03.z - e02.z * e03.y ) / n.x;
  879. beta_11 = ( e01.y * e02.z - e01.z * e02.y ) / n.x;
  880. }
  881. else if ( mFabs(n.y) >= mFabs(n.x) &&
  882. mFabs(n.y) >= mFabs(n.z) )
  883. {
  884. alpha_11 = ((e02.z * e03.x) - (e02.x * e03.z)) / n.y;
  885. beta_11 = ((e01.z * e02.x) - (e01.x * e02.z)) / n.y;
  886. }
  887. else
  888. {
  889. alpha_11 = ((e02.x * e03.y) - (e02.y * e03.x)) / n.z;
  890. beta_11 = ((e01.x * e02.y) - (e01.y * e02.x)) / n.z;
  891. }
  892. // Compute the bilinear coordinates of the intersection point.
  893. F32 u,v;
  894. if ( mFabs(alpha_11 - 1.0f) < eps)
  895. {
  896. // Q is a trapezium.
  897. u = alpha;
  898. if ( mFabs(beta_11 - 1.0f) < eps)
  899. v = beta; // Q is a parallelogram.
  900. else
  901. v = beta / ((u * (beta_11 - 1.0f)) + 1.0f); // Q is a trapezium.
  902. }
  903. else if ( mFabs(beta_11 - 1.0f) < eps)
  904. {
  905. // Q is a trapezium.
  906. v = beta;
  907. u = alpha / ((v * (alpha_11 - 1.0f)) + 1.0f);
  908. }
  909. else
  910. {
  911. F32 A = 1.0f - beta_11;
  912. F32 B = (alpha * (beta_11 - 1.0f))
  913. - (beta * (alpha_11 - 1.0f)) - 1.0f;
  914. F32 C = alpha;
  915. F32 D = (B * B) - (4.0f * A * C);
  916. F32 Q = -0.5f * (B + (B < 0.0f ? -1.0f : 1.0f) ) * mSqrt(D);
  917. u = Q / A;
  918. if ((u < 0.0f) || (u > 1.0f)) u = C / Q;
  919. v = beta / ((u * (beta_11 - 1.0f)) + 1.0f);
  920. }
  921. if ( outUV )
  922. outUV->set( u, v );
  923. if ( outT )
  924. *outT = t;
  925. return true;
  926. }
  927. //-----------------------------------------------------------------------------
  928. // Used by sortQuadWindingOrder.
  929. struct QuadSortPoint
  930. {
  931. U32 id;
  932. F32 theta;
  933. };
  934. // Used by sortQuadWindingOrder.
  935. S32 QSORT_CALLBACK cmpAngleAscending( const void *a, const void *b )
  936. {
  937. const QuadSortPoint *p0 = (const QuadSortPoint*)a;
  938. const QuadSortPoint *p1 = (const QuadSortPoint*)b;
  939. F32 diff = p1->theta - p0->theta;
  940. if ( diff > 0.0f )
  941. return -1;
  942. else if ( diff < 0.0f )
  943. return 1;
  944. else
  945. return 0;
  946. }
  947. // Used by sortQuadWindingOrder.
  948. S32 QSORT_CALLBACK cmpAngleDescending( const void *a, const void *b )
  949. {
  950. const QuadSortPoint *p0 = (const QuadSortPoint*)a;
  951. const QuadSortPoint *p1 = (const QuadSortPoint*)b;
  952. F32 diff = p1->theta - p0->theta;
  953. if ( diff > 0.0f )
  954. return 1;
  955. else if ( diff < 0.0f )
  956. return -1;
  957. else
  958. return 0;
  959. }
  960. void sortQuadWindingOrder( const MatrixF &quadMat, bool clockwise, const Point3F *verts, U32 *vertMap, U32 count )
  961. {
  962. PROFILE_SCOPE( MathUtils_sortQuadWindingOrder );
  963. if ( count == 0 )
  964. return;
  965. Point3F *quadPoints = new Point3F[count];
  966. for ( S32 i = 0; i < count; i++ )
  967. {
  968. quadMat.mulP( verts[i], &quadPoints[i] );
  969. quadPoints[i].normalizeSafe();
  970. }
  971. sortQuadWindingOrder( clockwise, quadPoints, vertMap, count );
  972. delete [] quadPoints;
  973. }
  974. void sortQuadWindingOrder( bool clockwise, const Point3F *verts, U32 *vertMap, U32 count )
  975. {
  976. QuadSortPoint *sortPoints = new QuadSortPoint[count];
  977. for ( S32 i = 0; i < count; i++ )
  978. {
  979. QuadSortPoint &sortPnt = sortPoints[i];
  980. const Point3F &vec = verts[i];
  981. sortPnt.id = i;
  982. F32 theta = mAtan2( vec.y, vec.x );
  983. if ( vec.y < 0.0f )
  984. theta = M_2PI_F + theta;
  985. sortPnt.theta = theta;
  986. }
  987. dQsort( sortPoints, count, sizeof( QuadSortPoint ), clockwise ? cmpAngleDescending : cmpAngleAscending );
  988. for ( S32 i = 0; i < count; i++ )
  989. vertMap[i] = sortPoints[i].id;
  990. delete [] sortPoints;
  991. }
  992. //-----------------------------------------------------------------------------
  993. void buildMatrix( const VectorF *rvec, const VectorF *fvec, const VectorF *uvec, const VectorF *pos, MatrixF *outMat )
  994. {
  995. /// Work in Progress
  996. /*
  997. AssertFatal( !rvec || rvec->isUnitLength(), "MathUtils::buildMatrix() - Right vector was not normalized!" );
  998. AssertFatal( !fvec || fvec->isUnitLength(), "MathUtils::buildMatrix() - Forward vector was not normalized!" );
  999. AssertFatal( !uvec || uvec->isUnitLength(), "MathUtils::buildMatrix() - Up vector was not normalized!" );
  1000. // Note this relationship:
  1001. //
  1002. // Column0 Column1 Column2
  1003. // Axis X Axis Y Axis Z
  1004. // Rvec Fvec Uvec
  1005. //
  1006. enum
  1007. {
  1008. RVEC = 1,
  1009. FVEC = 1 << 1,
  1010. UVEC = 1 << 2,
  1011. ALL = RVEC | FVEC | UVEC
  1012. };
  1013. U8 mask = 0;
  1014. U8 count = 0;
  1015. U8 axis0, axis1;
  1016. if ( rvec )
  1017. {
  1018. mask |= RVEC;
  1019. axis0 == 0;
  1020. count++;
  1021. }
  1022. if ( fvec )
  1023. {
  1024. mask |= FVEC;
  1025. if ( count == 0 )
  1026. axis0 = 1;
  1027. else
  1028. axis1 = 1;
  1029. count++;
  1030. }
  1031. if ( uvec )
  1032. {
  1033. mask |= UVEC;
  1034. count++;
  1035. }
  1036. U8 bR = 1;
  1037. U8 bF = 1 << 1;
  1038. U8 bU = 1 << 2;
  1039. U8 bRF = bR | bF;
  1040. U8 bRU = bR | bU;
  1041. U8 bFU = bF | bU;
  1042. U8 bRFU = bR | bF | bU;
  1043. // Cross product map.
  1044. U8 cpdMap[3][2] =
  1045. {
  1046. { 1, 2 },
  1047. { 2, 0 },
  1048. { 0, 1 },
  1049. }
  1050. if ( count == 1 )
  1051. {
  1052. if ( mask == bR )
  1053. {
  1054. }
  1055. else if ( mask == bF )
  1056. {
  1057. }
  1058. else if ( mask == bU )
  1059. {
  1060. }
  1061. }
  1062. else if ( count == 2 )
  1063. {
  1064. if ( mask == bRF )
  1065. {
  1066. }
  1067. else if ( mask == bRU )
  1068. {
  1069. }
  1070. else if ( mask == bFU )
  1071. {
  1072. }
  1073. }
  1074. else // bRFU
  1075. {
  1076. }
  1077. if ( rvec )
  1078. {
  1079. outMat->setColumn( 0, *rvec );
  1080. if ( fvec )
  1081. {
  1082. outMat->setColumn( 1, *fvec );
  1083. if ( uvec )
  1084. outMat->setColumn( 2, *uvec );
  1085. else
  1086. {
  1087. // Set uvec from rvec/fvec
  1088. tmp = mCross( rvec, fvec );
  1089. tmp.normalizeSafe();
  1090. outMat->setColumn( 2, tmp );
  1091. }
  1092. }
  1093. else if ( uvec )
  1094. {
  1095. // Set fvec from uvec/rvec
  1096. tmp = mCross( uvec, rvec );
  1097. tmp.normalizeSafe();
  1098. outMat->setColumn( 1, tmp );
  1099. }
  1100. else
  1101. {
  1102. // Set fvec and uvec from rvec
  1103. Point3F tempFvec = mPerp( rvec );
  1104. Point3F tempUvec = mCross( )
  1105. }
  1106. }
  1107. AssertFatal( rvec->isUnitLength(), "MathUtils::buildMatrix() - Right vector was not normalized!" );
  1108. AssertFatal( fvec->isUnitLength(), "MathUtils::buildMatrix() - Forward vector was not normalized!" );
  1109. AssertFatal( uvec->isUnitLength(), "MathUtils::buildMatrix() - UpVector vector was not normalized!" );
  1110. AssertFatal( outMat, "MathUtils::buildMatrix() - Got null output matrix!" );
  1111. AssertFatal( outMat->isAffine(), "MathUtils::buildMatrix() - Got uninitialized matrix!" );
  1112. */
  1113. }
  1114. //-----------------------------------------------------------------------------
  1115. bool reduceFrustum( const Frustum& frustum, const RectI& viewport, const RectF& area, Frustum& outFrustum )
  1116. {
  1117. // Just to be safe, clamp the area to the viewport.
  1118. Point2F clampedMin;
  1119. Point2F clampedMax;
  1120. clampedMin.x = mClampF( area.extent.x, ( F32 ) viewport.point.x, ( F32 ) viewport.point.x + viewport.extent.x );
  1121. clampedMin.y = mClampF( area.extent.y, ( F32 ) viewport.point.y, ( F32 ) viewport.point.y + viewport.extent.y );
  1122. clampedMax.x = mClampF( area.extent.x, ( F32 ) viewport.point.x, ( F32 ) viewport.point.x + viewport.extent.x );
  1123. clampedMax.y = mClampF( area.extent.y, ( F32 ) viewport.point.y, ( F32 ) viewport.point.y + viewport.extent.y );
  1124. // If we have ended up without a visible region on the screen,
  1125. // terminate now.
  1126. if( mFloor( clampedMin.x ) == mFloor( clampedMax.x ) ||
  1127. mFloor( clampedMin.y ) == mFloor( clampedMax.y ) )
  1128. return false;
  1129. // Get the extents of the frustum.
  1130. const F32 frustumXExtent = mFabs( frustum.getNearRight() - frustum.getNearLeft() );
  1131. const F32 frustumYExtent = mFabs( frustum.getNearTop() - frustum.getNearBottom() );
  1132. // Now, normalize the screen-space pixel coordinates to lie within the screen-centered
  1133. // -1 to 1 coordinate space that is used for the frustum planes.
  1134. Point2F normalizedMin;
  1135. Point2F normalizedMax;
  1136. normalizedMin.x = ( ( clampedMin.x / viewport.extent.x ) * frustumXExtent ) - ( frustumXExtent / 2.f );
  1137. normalizedMin.y = ( ( clampedMin.y / viewport.extent.y ) * frustumYExtent ) - ( frustumYExtent / 2.f );
  1138. normalizedMax.x = ( ( clampedMax.x / viewport.extent.x ) * frustumXExtent ) - ( frustumXExtent / 2.f );
  1139. normalizedMax.y = ( ( clampedMax.y / viewport.extent.y ) * frustumYExtent ) - ( frustumYExtent / 2.f );
  1140. // Make sure the generated frustum metrics are somewhat sane.
  1141. if( normalizedMax.x - normalizedMin.x < 0.001f ||
  1142. normalizedMax.y - normalizedMin.y < 0.001f )
  1143. return false;
  1144. // Finally, create the new frustum using the original's frustum
  1145. // information except its left/right/top/bottom planes.
  1146. //
  1147. // Note that screen-space coordinates go upside down on Y whereas
  1148. // camera-space frustum coordinates go downside up on Y which is
  1149. // why we are inverting Y here.
  1150. outFrustum.set(
  1151. frustum.isOrtho(),
  1152. normalizedMin.x,
  1153. normalizedMax.x,
  1154. - normalizedMin.y,
  1155. - normalizedMax.y,
  1156. frustum.getNearDist(),
  1157. frustum.getFarDist(),
  1158. frustum.getTransform()
  1159. );
  1160. return true;
  1161. }
  1162. //-----------------------------------------------------------------------------
  1163. void makeFrustum( F32 *outLeft,
  1164. F32 *outRight,
  1165. F32 *outTop,
  1166. F32 *outBottom,
  1167. F32 fovYInRadians,
  1168. F32 aspectRatio,
  1169. F32 nearPlane )
  1170. {
  1171. F32 top = nearPlane * mTan( fovYInRadians / 2.0 );
  1172. if ( outTop ) *outTop = top;
  1173. if ( outBottom ) *outBottom = -top;
  1174. F32 left = top * aspectRatio;
  1175. if ( outLeft ) *outLeft = -left;
  1176. if ( outRight ) *outRight = left;
  1177. }
  1178. //-----------------------------------------------------------------------------
  1179. void makeProjection( MatrixF *outMatrix,
  1180. F32 fovYInRadians,
  1181. F32 aspectRatio,
  1182. F32 nearPlane,
  1183. F32 farPlane,
  1184. bool gfxRotate )
  1185. {
  1186. F32 left, right, top, bottom;
  1187. makeFrustum( &left, &right, &top, &bottom, fovYInRadians, aspectRatio, nearPlane );
  1188. makeProjection( outMatrix, left, right, top, bottom, nearPlane, farPlane, gfxRotate );
  1189. }
  1190. //-----------------------------------------------------------------------------
  1191. void makeFovPortFrustum(
  1192. Frustum *outFrustum,
  1193. bool isOrtho,
  1194. F32 nearDist,
  1195. F32 farDist,
  1196. const FovPort &inPort,
  1197. const MatrixF &transform)
  1198. {
  1199. F32 leftSize = nearDist * inPort.leftTan;
  1200. F32 rightSize = nearDist * inPort.rightTan;
  1201. F32 upSize = nearDist * inPort.upTan;
  1202. F32 downSize = nearDist * inPort.downTan;
  1203. F32 left = -leftSize;
  1204. F32 right = rightSize;
  1205. F32 top = upSize;
  1206. F32 bottom = -downSize;
  1207. outFrustum->set(isOrtho, left, right, top, bottom, nearDist, farDist, transform);
  1208. }
  1209. //-----------------------------------------------------------------------------
  1210. /// This is the special rotation matrix applied to
  1211. /// projection matricies for GFX.
  1212. ///
  1213. /// It is a wart of the OGL to DX change over.
  1214. ///
  1215. static const MatrixF sGFXProjRotMatrix( EulerF( (M_PI_F / 2.0f), 0.0f, 0.0f ) );
  1216. void makeProjection( MatrixF *outMatrix,
  1217. F32 left,
  1218. F32 right,
  1219. F32 top,
  1220. F32 bottom,
  1221. F32 nearPlane,
  1222. F32 farPlane,
  1223. bool gfxRotate )
  1224. {
  1225. Point4F row;
  1226. row.x = 2.0*nearPlane / (right-left);
  1227. row.y = 0.0;
  1228. row.z = 0.0;
  1229. row.w = 0.0;
  1230. outMatrix->setRow( 0, row );
  1231. row.x = 0.0;
  1232. row.y = 2.0 * nearPlane / (top-bottom);
  1233. row.z = 0.0;
  1234. row.w = 0.0;
  1235. outMatrix->setRow( 1, row );
  1236. row.x = (left+right) / (right-left);
  1237. row.y = (top+bottom) / (top-bottom);
  1238. row.z = farPlane / (nearPlane - farPlane);
  1239. row.w = -1.0;
  1240. outMatrix->setRow( 2, row );
  1241. row.x = 0.0;
  1242. row.y = 0.0;
  1243. row.z = nearPlane * farPlane / (nearPlane - farPlane);
  1244. row.w = 0.0;
  1245. outMatrix->setRow( 3, row );
  1246. outMatrix->transpose();
  1247. if ( gfxRotate )
  1248. outMatrix->mul( sGFXProjRotMatrix );
  1249. }
  1250. //-----------------------------------------------------------------------------
  1251. void makeOrthoProjection( MatrixF *outMatrix,
  1252. F32 left,
  1253. F32 right,
  1254. F32 top,
  1255. F32 bottom,
  1256. F32 nearPlane,
  1257. F32 farPlane,
  1258. bool gfxRotate )
  1259. {
  1260. Point4F row;
  1261. row.x = 2.0f / (right - left);
  1262. row.y = 0.0f;
  1263. row.z = 0.0f;
  1264. row.w = 0.0f;
  1265. outMatrix->setRow( 0, row );
  1266. row.x = 0.0f;
  1267. row.y = 2.0f / (top - bottom);
  1268. row.z = 0.0f;
  1269. row.w = 0.0f;
  1270. outMatrix->setRow( 1, row );
  1271. row.x = 0.0f;
  1272. row.y = 0.0f;
  1273. row.w = 0.0f;
  1274. //Unlike D3D, which has a 0-1 range, OpenGL uses a -1-1 range.
  1275. //However, epoxy internally handles the swap, so the math here is the same for both APIs
  1276. row.z = 1.0f / (nearPlane - farPlane);
  1277. outMatrix->setRow( 2, row );
  1278. row.x = (left + right) / (left - right);
  1279. row.y = (top + bottom) / (bottom - top);
  1280. row.z = nearPlane / (nearPlane - farPlane);
  1281. row.w = 1.0f;
  1282. outMatrix->setRow( 3, row );
  1283. outMatrix->transpose();
  1284. if ( gfxRotate )
  1285. outMatrix->mul( sGFXProjRotMatrix );
  1286. }
  1287. //-----------------------------------------------------------------------------
  1288. bool edgeFaceIntersect( const Point3F &edgeA, const Point3F &edgeB,
  1289. const Point3F &faceA, const Point3F &faceB, const Point3F &faceC, const Point3F &faceD, Point3F *intersection )
  1290. {
  1291. VectorF edgeAB = edgeB - edgeA;
  1292. VectorF edgeAFaceA = faceA - edgeA;
  1293. VectorF edgeAFaceB = faceB - edgeA;
  1294. VectorF edgeAFaceC = faceC - edgeA;
  1295. VectorF m = mCross( edgeAFaceC, edgeAB );
  1296. F32 v = mDot( edgeAFaceA, m );
  1297. if ( v >= 0.0f )
  1298. {
  1299. F32 u = -mDot( edgeAFaceB, m );
  1300. if ( u < 0.0f )
  1301. return false;
  1302. VectorF tmp = mCross( edgeAFaceB, edgeAB );
  1303. F32 w = mDot( edgeAFaceA, tmp );
  1304. if ( w < 0.0f )
  1305. return false;
  1306. F32 denom = 1.0f / (u + v + w );
  1307. u *= denom;
  1308. v *= denom;
  1309. w *= denom;
  1310. (*intersection) = u * faceA + v * faceB + w * faceC;
  1311. }
  1312. else
  1313. {
  1314. VectorF edgeAFaceD = faceD - edgeA;
  1315. F32 u = mDot( edgeAFaceD, m );
  1316. if ( u < 0.0f )
  1317. return false;
  1318. VectorF tmp = mCross( edgeAFaceA, edgeAB );
  1319. F32 w = mDot( edgeAFaceD, tmp );
  1320. if ( w < 0.0f )
  1321. return false;
  1322. v = -v;
  1323. F32 denom = 1.0f / ( u + v + w );
  1324. u *= denom;
  1325. v *= denom;
  1326. w *= denom;
  1327. (*intersection) = u * faceA + v * faceD + w * faceC;
  1328. }
  1329. return true;
  1330. }
  1331. //-----------------------------------------------------------------------------
  1332. bool isPlanarPolygon( const Point3F* vertices, U32 numVertices )
  1333. {
  1334. AssertFatal( vertices != NULL, "MathUtils::isPlanarPolygon - Received NULL pointer" );
  1335. AssertFatal( numVertices >= 3, "MathUtils::isPlanarPolygon - Must have at least three vertices" );
  1336. // Triangles are always planar. Letting smaller numVertices
  1337. // slip through provides robustness for errors in release builds.
  1338. if( numVertices <= 3 )
  1339. return true;
  1340. // Compute the normal of the first triangle in the polygon.
  1341. Point3F triangle1Normal = mTriangleNormal( vertices[ 0 ], vertices[ 1 ], vertices[ 2 ] );
  1342. // Now go through all the remaining vertices and build triangles
  1343. // with the first two vertices. Then the normals of all these triangles
  1344. // must be the same (minus some variance due to floating-point inaccuracies)
  1345. // as the normal of the first triangle.
  1346. for( U32 i = 3; i < numVertices; ++ i )
  1347. {
  1348. Point3F triangle2Normal = mTriangleNormal( vertices[ 0 ], vertices[ 1 ], vertices[ i ] );
  1349. if( !triangle1Normal.equal( triangle2Normal ) )
  1350. return false;
  1351. }
  1352. return true;
  1353. }
  1354. //-----------------------------------------------------------------------------
  1355. bool isConvexPolygon( const Point3F* vertices, U32 numVertices )
  1356. {
  1357. AssertFatal( vertices != NULL, "MathUtils::isConvexPolygon - Received NULL pointer" );
  1358. AssertFatal( numVertices >= 3, "MathUtils::isConvexPolygon - Must have at least three vertices" );
  1359. // Triangles are always convex. Letting smaller numVertices
  1360. // slip through provides robustness for errors in release builds.
  1361. if( numVertices <= 3 )
  1362. return true;
  1363. U32 numPositive = 0;
  1364. U32 numNegative = 0;
  1365. for( U32 i = 0; i < numVertices; ++ i )
  1366. {
  1367. const Point3F& a = vertices[ i ];
  1368. const Point3F& b = vertices[ ( i + 1 ) % numVertices ];
  1369. const Point3F& c = vertices[ ( i + 2 ) % numVertices ];
  1370. const F32 crossProductLength = mCross( b - a, c - b ).len();
  1371. if( crossProductLength < 0.f )
  1372. numNegative ++;
  1373. else if( crossProductLength > 0.f )
  1374. numPositive ++;
  1375. if( numNegative && numPositive )
  1376. return false;
  1377. }
  1378. return true;
  1379. }
  1380. //-----------------------------------------------------------------------------
  1381. bool clipFrustumByPolygon( const Point3F* points, U32 numPoints, const RectI& viewport, const MatrixF& world,
  1382. const MatrixF& projection, const Frustum& inFrustum, const Frustum& rootFrustum, Frustum& outFrustum )
  1383. {
  1384. enum
  1385. {
  1386. MAX_RESULT_VERTICES = 64,
  1387. MAX_INPUT_VERTICES = MAX_RESULT_VERTICES - Frustum::PlaneCount // Clipping against each plane may add a vertex.
  1388. };
  1389. AssertFatal( numPoints <= MAX_INPUT_VERTICES, "MathUtils::clipFrustumByPolygon - Too many vertices!" );
  1390. if( numPoints > MAX_INPUT_VERTICES )
  1391. return false;
  1392. // First, we need to clip the polygon against inFrustum.
  1393. //
  1394. // Use two buffers here in interchanging roles as sources and targets
  1395. // in clipping against the frustum planes.
  1396. Point3F polygonBuffer1[ MAX_RESULT_VERTICES ];
  1397. Point3F polygonBuffer2[ MAX_RESULT_VERTICES ];
  1398. Point3F* tempPolygon = polygonBuffer1;
  1399. Point3F* clippedPolygon = polygonBuffer2;
  1400. dMemcpy( clippedPolygon, points, numPoints * sizeof( points[ 0 ] ) );
  1401. U32 numClippedPolygonVertices = numPoints;
  1402. U32 numTempPolygonVertices = 0;
  1403. for( U32 nplane = 0; nplane < Frustum::PlaneCount; ++ nplane )
  1404. {
  1405. // Make the output of the last iteration the
  1406. // input of this iteration.
  1407. swap( tempPolygon, clippedPolygon );
  1408. numTempPolygonVertices = numClippedPolygonVertices;
  1409. // Clip our current remainder of the original polygon
  1410. // against the current plane.
  1411. const PlaneF& plane = inFrustum.getPlanes()[ nplane ];
  1412. numClippedPolygonVertices = plane.clipPolygon( tempPolygon, numTempPolygonVertices, clippedPolygon );
  1413. // If the polygon was completely on the backside of the plane,
  1414. // then polygon is outside the frustum. In this case, return false
  1415. // to indicate we haven't clipped anything.
  1416. if( !numClippedPolygonVertices )
  1417. return false;
  1418. }
  1419. // Project the clipped polygon into screen space.
  1420. MatrixF worldProjection = projection;
  1421. worldProjection.mul( world ); // Premultiply world*projection so we don't have to do this over and over for each point.
  1422. Point3F projectedPolygon[ 10 ];
  1423. for( U32 i = 0; i < numClippedPolygonVertices; ++ i )
  1424. mProjectWorldToScreen(
  1425. clippedPolygon[ i ],
  1426. &projectedPolygon[ i ],
  1427. viewport,
  1428. worldProjection
  1429. );
  1430. // Put an axis-aligned rectangle around our polygon.
  1431. Point2F minPoint( projectedPolygon[ 0 ].x, projectedPolygon[ 0 ].y );
  1432. Point2F maxPoint( projectedPolygon[ 0 ].x, projectedPolygon[ 0 ].y );
  1433. for( U32 i = 1; i < numClippedPolygonVertices; ++ i )
  1434. {
  1435. minPoint.setMin( Point2F( projectedPolygon[ i ].x, projectedPolygon[ i ].y ) );
  1436. maxPoint.setMax( Point2F( projectedPolygon[ i ].x, projectedPolygon[ i ].y ) );
  1437. }
  1438. RectF area( minPoint, maxPoint - minPoint );
  1439. // Finally, reduce the input frustum to the given area. Note that we
  1440. // use rootFrustum here instead of inFrustum as the latter does not necessarily
  1441. // represent the full viewport we are using here which thus would skew the mapping.
  1442. return reduceFrustum( rootFrustum, viewport, area, outFrustum );
  1443. }
  1444. //-----------------------------------------------------------------------------
  1445. U32 extrudePolygonEdges( const Point3F* vertices, U32 numVertices, const Point3F& direction, PlaneF* outPlanes )
  1446. {
  1447. U32 numPlanes = 0;
  1448. U32 lastVertex = numVertices - 1;
  1449. bool invert = false;
  1450. for( U32 i = 0; i < numVertices; lastVertex = i, ++ i )
  1451. {
  1452. const Point3F& v1 = vertices[ i ];
  1453. const Point3F& v2 = vertices[ lastVertex ];
  1454. // Skip the edge if it's length is really short.
  1455. const Point3F edgeVector = v2 - v1;
  1456. if( edgeVector.len() < 0.05 )
  1457. continue;
  1458. // Compute the plane normal. The direction and the edge vector
  1459. // basically define the orientation of the plane so their cross
  1460. // product is the plane normal.
  1461. Point3F normal;
  1462. if( !invert )
  1463. normal = mCross( edgeVector, direction );
  1464. else
  1465. normal = mCross( direction, edgeVector );
  1466. // Create a plane for the edge.
  1467. outPlanes[ numPlanes ] = PlaneF( v1, normal );
  1468. numPlanes ++;
  1469. // If this is the first plane that we have created, find out whether
  1470. // the vertex ordering is giving us the plane orientations that we want
  1471. // (facing inside). If not, invert vertex order from now on.
  1472. if( i == 0 )
  1473. {
  1474. const PlaneF& plane = outPlanes[ numPlanes - 1 ];
  1475. for( U32 n = i + 1; n < numVertices; ++ n )
  1476. {
  1477. const PlaneF::Side side = plane.whichSide( vertices[ n ] );
  1478. if( side == PlaneF::On )
  1479. continue;
  1480. if( side != PlaneF::Front )
  1481. invert = true;
  1482. break;
  1483. }
  1484. }
  1485. }
  1486. return numPlanes;
  1487. }
  1488. //-----------------------------------------------------------------------------
  1489. U32 extrudePolygonEdgesFromPoint( const Point3F* vertices, U32 numVertices, const Point3F& fromPoint, PlaneF* outPlanes )
  1490. {
  1491. U32 numPlanes = 0;
  1492. U32 lastVertex = numVertices - 1;
  1493. bool invert = false;
  1494. for( U32 i = 0; i < numVertices; lastVertex = i, ++ i )
  1495. {
  1496. const Point3F& v1 = vertices[ i ];
  1497. const Point3F& v2 = vertices[ lastVertex ];
  1498. // Skip the edge if it's length is really short.
  1499. const Point3F edgeVector = v2 - v1;
  1500. if( edgeVector.len() < 0.05 )
  1501. continue;
  1502. // Create a plane for the edge.
  1503. if( !invert )
  1504. outPlanes[ numPlanes ] = PlaneF( v1, fromPoint, v2 );
  1505. else
  1506. outPlanes[ numPlanes ] = PlaneF( v2, fromPoint, v1 );
  1507. numPlanes ++;
  1508. // If this is the first plane that we have created, find out whether
  1509. // the vertex ordering is giving us the plane orientations that we want
  1510. // (facing inside). If not, invert vertex order from now on.
  1511. if( i == 0 )
  1512. {
  1513. const PlaneF& plane = outPlanes[ numPlanes - 1 ];
  1514. for( U32 n = i + 1; n < numVertices; ++ n )
  1515. {
  1516. const PlaneF::Side side = plane.whichSide( vertices[ n ] );
  1517. if( side == PlaneF::On )
  1518. continue;
  1519. if( side != PlaneF::Front )
  1520. invert = true;
  1521. break;
  1522. }
  1523. }
  1524. }
  1525. return numPlanes;
  1526. }
  1527. //-----------------------------------------------------------------------------
  1528. void mBuildHull2D(const Vector<Point2F> _inPoints, Vector<Point2F> &hullPoints)
  1529. {
  1530. /// Andrew's monotone chain convex hull algorithm implementation
  1531. struct Util
  1532. {
  1533. //compare by x and then by y
  1534. static int CompareLexicographic( const Point2F *a, const Point2F *b)
  1535. {
  1536. return a->x < b->x || (a->x == b->x && a->y < b->y);
  1537. }
  1538. };
  1539. hullPoints.clear();
  1540. hullPoints.setSize( _inPoints.size()*2 );
  1541. // sort in points by x and then by y
  1542. Vector<Point2F> inSortedPoints = _inPoints;
  1543. inSortedPoints.sort( &Util::CompareLexicographic );
  1544. Point2F* lowerHullPtr = hullPoints.address();
  1545. U32 lowerHullIdx = 0;
  1546. //lower part of hull
  1547. for( int i = 0; i < inSortedPoints.size(); ++i )
  1548. {
  1549. while( lowerHullIdx >= 2 && mCross( lowerHullPtr[ lowerHullIdx - 2], lowerHullPtr[lowerHullIdx - 1], inSortedPoints[i] ) <= 0 )
  1550. --lowerHullIdx;
  1551. lowerHullPtr[lowerHullIdx++] = inSortedPoints[i];
  1552. }
  1553. --lowerHullIdx; // last point are the same as first in upperHullPtr
  1554. Point2F* upperHullPtr = hullPoints.address() + lowerHullIdx;
  1555. U32 upperHullIdx = 0;
  1556. //upper part of hull
  1557. for( int i = inSortedPoints.size()-1; i >= 0; --i )
  1558. {
  1559. while( upperHullIdx >= 2 && mCross( upperHullPtr[ upperHullIdx - 2], upperHullPtr[upperHullIdx - 1], inSortedPoints[i] ) <= 0 )
  1560. --upperHullIdx;
  1561. upperHullPtr[upperHullIdx++] = inSortedPoints[i];
  1562. }
  1563. hullPoints.setSize( lowerHullIdx + upperHullIdx );
  1564. }
  1565. } // namespace MathUtils