mathUtils.cpp 51 KB

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