mathUtils.cpp 52 KB

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