mathUtils.cpp 54 KB

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