gjk_epa.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. /*************************************************************************/
  2. /* gjk_epa.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "gjk_epa.h"
  31. /* Disabling formatting for thirdparty code snippet */
  32. /* clang-format off */
  33. /*************** Bullet's GJK-EPA2 IMPLEMENTATION *******************/
  34. /*
  35. Bullet Continuous Collision Detection and Physics Library
  36. Copyright (c) 2003-2008 Erwin Coumans http://continuousphysics.com/Bullet/
  37. This software is provided 'as-is', without any express or implied warranty.
  38. In no event will the authors be held liable for any damages arising from the
  39. use of this software.
  40. Permission is granted to anyone to use this software for any purpose,
  41. including commercial applications, and to alter it and redistribute it
  42. freely,
  43. subject to the following restrictions:
  44. 1. The origin of this software must not be misrepresented; you must not
  45. claim that you wrote the original software. If you use this software in a
  46. product, an acknowledgment in the product documentation would be appreciated
  47. but is not required.
  48. 2. Altered source versions must be plainly marked as such, and must not be
  49. misrepresented as being the original software.
  50. 3. This notice may not be removed or altered from any source distribution.
  51. */
  52. /*
  53. GJK-EPA collision solver by Nathanael Presson, 2008
  54. */
  55. // Config
  56. /* GJK */
  57. #define GJK_MAX_ITERATIONS 128
  58. #define GJK_ACCURARY ((real_t)0.0001)
  59. #define GJK_MIN_DISTANCE ((real_t)0.0001)
  60. #define GJK_DUPLICATED_EPS ((real_t)0.0001)
  61. #define GJK_SIMPLEX2_EPS ((real_t)0.0)
  62. #define GJK_SIMPLEX3_EPS ((real_t)0.0)
  63. #define GJK_SIMPLEX4_EPS ((real_t)0.0)
  64. /* EPA */
  65. #define EPA_MAX_VERTICES 64
  66. #define EPA_MAX_FACES (EPA_MAX_VERTICES*2)
  67. #define EPA_MAX_ITERATIONS 255
  68. #define EPA_ACCURACY ((real_t)0.0001)
  69. #define EPA_FALLBACK (10*EPA_ACCURACY)
  70. #define EPA_PLANE_EPS ((real_t)0.00001)
  71. #define EPA_INSIDE_EPS ((real_t)0.01)
  72. namespace GjkEpa2 {
  73. struct sResults {
  74. enum eStatus {
  75. Separated, /* Shapes doesn't penetrate */
  76. Penetrating, /* Shapes are penetrating */
  77. GJK_Failed, /* GJK phase fail, no big issue, shapes are probably just 'touching' */
  78. EPA_Failed /* EPA phase fail, bigger problem, need to save parameters, and debug */
  79. } status;
  80. Vector3 witnesses[2];
  81. Vector3 normal;
  82. real_t distance;
  83. };
  84. // Shorthands
  85. typedef unsigned int U;
  86. typedef unsigned char U1;
  87. // MinkowskiDiff
  88. struct MinkowskiDiff {
  89. const ShapeSW* m_shapes[2];
  90. Transform transform_A;
  91. Transform transform_B;
  92. // i wonder how this could be sped up... if it can
  93. _FORCE_INLINE_ Vector3 Support0 ( const Vector3& d ) const {
  94. return transform_A.xform( m_shapes[0]->get_support( transform_A.basis.xform_inv(d).normalized() ) );
  95. }
  96. _FORCE_INLINE_ Vector3 Support1 ( const Vector3& d ) const {
  97. return transform_B.xform( m_shapes[1]->get_support( transform_B.basis.xform_inv(d).normalized() ) );
  98. }
  99. _FORCE_INLINE_ Vector3 Support ( const Vector3& d ) const {
  100. return ( Support0 ( d )-Support1 ( -d ) );
  101. }
  102. _FORCE_INLINE_ Vector3 Support ( const Vector3& d,U index ) const
  103. {
  104. if ( index )
  105. return ( Support1 ( d ) );
  106. else
  107. return ( Support0 ( d ) );
  108. }
  109. };
  110. typedef MinkowskiDiff tShape;
  111. // GJK
  112. struct GJK
  113. {
  114. /* Types */
  115. struct sSV
  116. {
  117. Vector3 d,w;
  118. };
  119. struct sSimplex
  120. {
  121. sSV* c[4];
  122. real_t p[4];
  123. U rank;
  124. };
  125. struct eStatus { enum _ {
  126. Valid,
  127. Inside,
  128. Failed };};
  129. /* Fields */
  130. tShape m_shape;
  131. Vector3 m_ray;
  132. real_t m_distance;
  133. sSimplex m_simplices[2];
  134. sSV m_store[4];
  135. sSV* m_free[4];
  136. U m_nfree;
  137. U m_current;
  138. sSimplex* m_simplex;
  139. eStatus::_ m_status;
  140. /* Methods */
  141. GJK()
  142. {
  143. Initialize();
  144. }
  145. void Initialize()
  146. {
  147. m_ray = Vector3(0,0,0);
  148. m_nfree = 0;
  149. m_status = eStatus::Failed;
  150. m_current = 0;
  151. m_distance = 0;
  152. }
  153. eStatus::_ Evaluate(const tShape& shapearg,const Vector3& guess)
  154. {
  155. U iterations=0;
  156. real_t sqdist=0;
  157. real_t alpha=0;
  158. Vector3 lastw[4];
  159. U clastw=0;
  160. /* Initialize solver */
  161. m_free[0] = &m_store[0];
  162. m_free[1] = &m_store[1];
  163. m_free[2] = &m_store[2];
  164. m_free[3] = &m_store[3];
  165. m_nfree = 4;
  166. m_current = 0;
  167. m_status = eStatus::Valid;
  168. m_shape = shapearg;
  169. m_distance = 0;
  170. /* Initialize simplex */
  171. m_simplices[0].rank = 0;
  172. m_ray = guess;
  173. const real_t sqrl= m_ray.length_squared();
  174. appendvertice(m_simplices[0],sqrl>0?-m_ray:Vector3(1,0,0));
  175. m_simplices[0].p[0] = 1;
  176. m_ray = m_simplices[0].c[0]->w;
  177. sqdist = sqrl;
  178. lastw[0] =
  179. lastw[1] =
  180. lastw[2] =
  181. lastw[3] = m_ray;
  182. /* Loop */
  183. do {
  184. const U next=1-m_current;
  185. sSimplex& cs=m_simplices[m_current];
  186. sSimplex& ns=m_simplices[next];
  187. /* Check zero */
  188. const real_t rl=m_ray.length();
  189. if(rl<GJK_MIN_DISTANCE)
  190. {/* Touching or inside */
  191. m_status=eStatus::Inside;
  192. break;
  193. }
  194. /* Append new vertice in -'v' direction */
  195. appendvertice(cs,-m_ray);
  196. const Vector3& w=cs.c[cs.rank-1]->w;
  197. bool found=false;
  198. for(U i=0;i<4;++i)
  199. {
  200. if((w-lastw[i]).length_squared()<GJK_DUPLICATED_EPS)
  201. { found=true;break; }
  202. }
  203. if(found)
  204. {/* Return old simplex */
  205. removevertice(m_simplices[m_current]);
  206. break;
  207. }
  208. else
  209. {/* Update lastw */
  210. lastw[clastw=(clastw+1)&3]=w;
  211. }
  212. /* Check for termination */
  213. const real_t omega=vec3_dot(m_ray,w)/rl;
  214. alpha=MAX(omega,alpha);
  215. if(((rl-alpha)-(GJK_ACCURARY*rl))<=0)
  216. {/* Return old simplex */
  217. removevertice(m_simplices[m_current]);
  218. break;
  219. }
  220. /* Reduce simplex */
  221. real_t weights[4];
  222. U mask=0;
  223. switch(cs.rank)
  224. {
  225. case 2: sqdist=projectorigin( cs.c[0]->w,
  226. cs.c[1]->w,
  227. weights,mask);break;
  228. case 3: sqdist=projectorigin( cs.c[0]->w,
  229. cs.c[1]->w,
  230. cs.c[2]->w,
  231. weights,mask);break;
  232. case 4: sqdist=projectorigin( cs.c[0]->w,
  233. cs.c[1]->w,
  234. cs.c[2]->w,
  235. cs.c[3]->w,
  236. weights,mask);break;
  237. }
  238. if(sqdist>=0)
  239. {/* Valid */
  240. ns.rank = 0;
  241. m_ray = Vector3(0,0,0);
  242. m_current = next;
  243. for(U i=0,ni=cs.rank;i<ni;++i)
  244. {
  245. if(mask&(1<<i))
  246. {
  247. ns.c[ns.rank] = cs.c[i];
  248. ns.p[ns.rank++] = weights[i];
  249. m_ray += cs.c[i]->w*weights[i];
  250. }
  251. else
  252. {
  253. m_free[m_nfree++] = cs.c[i];
  254. }
  255. }
  256. if(mask==15) m_status=eStatus::Inside;
  257. }
  258. else
  259. {/* Return old simplex */
  260. removevertice(m_simplices[m_current]);
  261. break;
  262. }
  263. m_status=((++iterations)<GJK_MAX_ITERATIONS)?m_status:eStatus::Failed;
  264. } while(m_status==eStatus::Valid);
  265. m_simplex=&m_simplices[m_current];
  266. switch(m_status)
  267. {
  268. case eStatus::Valid: m_distance=m_ray.length();break;
  269. case eStatus::Inside: m_distance=0;break;
  270. default: {}
  271. }
  272. return(m_status);
  273. }
  274. bool EncloseOrigin()
  275. {
  276. switch(m_simplex->rank)
  277. {
  278. case 1:
  279. {
  280. for(U i=0;i<3;++i)
  281. {
  282. Vector3 axis=Vector3(0,0,0);
  283. axis[i]=1;
  284. appendvertice(*m_simplex, axis);
  285. if(EncloseOrigin()) return(true);
  286. removevertice(*m_simplex);
  287. appendvertice(*m_simplex,-axis);
  288. if(EncloseOrigin()) return(true);
  289. removevertice(*m_simplex);
  290. }
  291. }
  292. break;
  293. case 2:
  294. {
  295. const Vector3 d=m_simplex->c[1]->w-m_simplex->c[0]->w;
  296. for(U i=0;i<3;++i)
  297. {
  298. Vector3 axis=Vector3(0,0,0);
  299. axis[i]=1;
  300. const Vector3 p=vec3_cross(d,axis);
  301. if(p.length_squared()>0)
  302. {
  303. appendvertice(*m_simplex, p);
  304. if(EncloseOrigin()) return(true);
  305. removevertice(*m_simplex);
  306. appendvertice(*m_simplex,-p);
  307. if(EncloseOrigin()) return(true);
  308. removevertice(*m_simplex);
  309. }
  310. }
  311. }
  312. break;
  313. case 3:
  314. {
  315. const Vector3 n=vec3_cross(m_simplex->c[1]->w-m_simplex->c[0]->w,
  316. m_simplex->c[2]->w-m_simplex->c[0]->w);
  317. if(n.length_squared()>0)
  318. {
  319. appendvertice(*m_simplex,n);
  320. if(EncloseOrigin()) return(true);
  321. removevertice(*m_simplex);
  322. appendvertice(*m_simplex,-n);
  323. if(EncloseOrigin()) return(true);
  324. removevertice(*m_simplex);
  325. }
  326. }
  327. break;
  328. case 4:
  329. {
  330. if(Math::abs(det( m_simplex->c[0]->w-m_simplex->c[3]->w,
  331. m_simplex->c[1]->w-m_simplex->c[3]->w,
  332. m_simplex->c[2]->w-m_simplex->c[3]->w))>0)
  333. return(true);
  334. }
  335. break;
  336. }
  337. return(false);
  338. }
  339. /* Internals */
  340. void getsupport(const Vector3& d,sSV& sv) const
  341. {
  342. sv.d = d/d.length();
  343. sv.w = m_shape.Support(sv.d);
  344. }
  345. void removevertice(sSimplex& simplex)
  346. {
  347. m_free[m_nfree++]=simplex.c[--simplex.rank];
  348. }
  349. void appendvertice(sSimplex& simplex,const Vector3& v)
  350. {
  351. simplex.p[simplex.rank]=0;
  352. simplex.c[simplex.rank]=m_free[--m_nfree];
  353. getsupport(v,*simplex.c[simplex.rank++]);
  354. }
  355. static real_t det(const Vector3& a,const Vector3& b,const Vector3& c)
  356. {
  357. return( a.y*b.z*c.x+a.z*b.x*c.y-
  358. a.x*b.z*c.y-a.y*b.x*c.z+
  359. a.x*b.y*c.z-a.z*b.y*c.x);
  360. }
  361. static real_t projectorigin( const Vector3& a,
  362. const Vector3& b,
  363. real_t* w,U& m)
  364. {
  365. const Vector3 d=b-a;
  366. const real_t l=d.length_squared();
  367. if(l>GJK_SIMPLEX2_EPS)
  368. {
  369. const real_t t(l>0?-vec3_dot(a,d)/l:0);
  370. if(t>=1) { w[0]=0;w[1]=1;m=2;return(b.length_squared()); }
  371. else if(t<=0) { w[0]=1;w[1]=0;m=1;return(a.length_squared()); }
  372. else { w[0]=1-(w[1]=t);m=3;return((a+d*t).length_squared()); }
  373. }
  374. return(-1);
  375. }
  376. static real_t projectorigin( const Vector3& a,
  377. const Vector3& b,
  378. const Vector3& c,
  379. real_t* w,U& m)
  380. {
  381. static const U imd3[]={1,2,0};
  382. const Vector3* vt[]={&a,&b,&c};
  383. const Vector3 dl[]={a-b,b-c,c-a};
  384. const Vector3 n=vec3_cross(dl[0],dl[1]);
  385. const real_t l=n.length_squared();
  386. if(l>GJK_SIMPLEX3_EPS)
  387. {
  388. real_t mindist=-1;
  389. real_t subw[2] = { 0 , 0};
  390. U subm = 0;
  391. for(U i=0;i<3;++i)
  392. {
  393. if(vec3_dot(*vt[i],vec3_cross(dl[i],n))>0)
  394. {
  395. const U j=imd3[i];
  396. const real_t subd(projectorigin(*vt[i],*vt[j],subw,subm));
  397. if((mindist<0)||(subd<mindist))
  398. {
  399. mindist = subd;
  400. m = static_cast<U>(((subm&1)?1<<i:0)+((subm&2)?1<<j:0));
  401. w[i] = subw[0];
  402. w[j] = subw[1];
  403. w[imd3[j]] = 0;
  404. }
  405. }
  406. }
  407. if(mindist<0)
  408. {
  409. const real_t d=vec3_dot(a,n);
  410. const real_t s=Math::sqrt(l);
  411. const Vector3 p=n*(d/l);
  412. mindist = p.length_squared();
  413. m = 7;
  414. w[0] = (vec3_cross(dl[1],b-p)).length()/s;
  415. w[1] = (vec3_cross(dl[2],c-p)).length()/s;
  416. w[2] = 1-(w[0]+w[1]);
  417. }
  418. return(mindist);
  419. }
  420. return(-1);
  421. }
  422. static real_t projectorigin( const Vector3& a,
  423. const Vector3& b,
  424. const Vector3& c,
  425. const Vector3& d,
  426. real_t* w,U& m)
  427. {
  428. static const U imd3[]={1,2,0};
  429. const Vector3* vt[]={&a,&b,&c,&d};
  430. const Vector3 dl[]={a-d,b-d,c-d};
  431. const real_t vl=det(dl[0],dl[1],dl[2]);
  432. const bool ng=(vl*vec3_dot(a,vec3_cross(b-c,a-b)))<=0;
  433. if(ng&&(Math::abs(vl)>GJK_SIMPLEX4_EPS))
  434. {
  435. real_t mindist=-1;
  436. real_t subw[3];
  437. U subm=0;
  438. for(U i=0;i<3;++i)
  439. {
  440. const U j=imd3[i];
  441. const real_t s=vl*vec3_dot(d,vec3_cross(dl[i],dl[j]));
  442. if(s>0)
  443. {
  444. const real_t subd=projectorigin(*vt[i],*vt[j],d,subw,subm);
  445. if((mindist<0)||(subd<mindist))
  446. {
  447. mindist = subd;
  448. m = static_cast<U>((subm&1?1<<i:0)+
  449. (subm&2?1<<j:0)+
  450. (subm&4?8:0));
  451. w[i] = subw[0];
  452. w[j] = subw[1];
  453. w[imd3[j]] = 0;
  454. w[3] = subw[2];
  455. }
  456. }
  457. }
  458. if(mindist<0)
  459. {
  460. mindist = 0;
  461. m = 15;
  462. w[0] = det(c,b,d)/vl;
  463. w[1] = det(a,c,d)/vl;
  464. w[2] = det(b,a,d)/vl;
  465. w[3] = 1-(w[0]+w[1]+w[2]);
  466. }
  467. return(mindist);
  468. }
  469. return(-1);
  470. }
  471. };
  472. // EPA
  473. struct EPA
  474. {
  475. /* Types */
  476. typedef GJK::sSV sSV;
  477. struct sFace
  478. {
  479. Vector3 n;
  480. real_t d;
  481. real_t p;
  482. sSV* c[3];
  483. sFace* f[3];
  484. sFace* l[2];
  485. U1 e[3];
  486. U1 pass;
  487. };
  488. struct sList
  489. {
  490. sFace* root;
  491. U count;
  492. sList() : root(0),count(0) {}
  493. };
  494. struct sHorizon
  495. {
  496. sFace* cf;
  497. sFace* ff;
  498. U nf;
  499. sHorizon() : cf(0),ff(0),nf(0) {}
  500. };
  501. struct eStatus { enum _ {
  502. Valid,
  503. Touching,
  504. Degenerated,
  505. NonConvex,
  506. InvalidHull,
  507. OutOfFaces,
  508. OutOfVertices,
  509. AccuraryReached,
  510. FallBack,
  511. Failed };};
  512. /* Fields */
  513. eStatus::_ m_status;
  514. GJK::sSimplex m_result;
  515. Vector3 m_normal;
  516. real_t m_depth;
  517. sSV m_sv_store[EPA_MAX_VERTICES];
  518. sFace m_fc_store[EPA_MAX_FACES];
  519. U m_nextsv;
  520. sList m_hull;
  521. sList m_stock;
  522. /* Methods */
  523. EPA()
  524. {
  525. Initialize();
  526. }
  527. static inline void bind(sFace* fa,U ea,sFace* fb,U eb)
  528. {
  529. fa->e[ea]=(U1)eb;fa->f[ea]=fb;
  530. fb->e[eb]=(U1)ea;fb->f[eb]=fa;
  531. }
  532. static inline void append(sList& list,sFace* face)
  533. {
  534. face->l[0] = 0;
  535. face->l[1] = list.root;
  536. if(list.root) list.root->l[0]=face;
  537. list.root = face;
  538. ++list.count;
  539. }
  540. static inline void remove(sList& list,sFace* face)
  541. {
  542. if(face->l[1]) face->l[1]->l[0]=face->l[0];
  543. if(face->l[0]) face->l[0]->l[1]=face->l[1];
  544. if(face==list.root) list.root=face->l[1];
  545. --list.count;
  546. }
  547. void Initialize()
  548. {
  549. m_status = eStatus::Failed;
  550. m_normal = Vector3(0,0,0);
  551. m_depth = 0;
  552. m_nextsv = 0;
  553. for(U i=0;i<EPA_MAX_FACES;++i)
  554. {
  555. append(m_stock,&m_fc_store[EPA_MAX_FACES-i-1]);
  556. }
  557. }
  558. eStatus::_ Evaluate(GJK& gjk,const Vector3& guess)
  559. {
  560. GJK::sSimplex& simplex=*gjk.m_simplex;
  561. if((simplex.rank>1)&&gjk.EncloseOrigin())
  562. {
  563. /* Clean up */
  564. while(m_hull.root)
  565. {
  566. sFace* f = m_hull.root;
  567. remove(m_hull,f);
  568. append(m_stock,f);
  569. }
  570. m_status = eStatus::Valid;
  571. m_nextsv = 0;
  572. /* Orient simplex */
  573. if(gjk.det( simplex.c[0]->w-simplex.c[3]->w,
  574. simplex.c[1]->w-simplex.c[3]->w,
  575. simplex.c[2]->w-simplex.c[3]->w)<0)
  576. {
  577. SWAP(simplex.c[0],simplex.c[1]);
  578. SWAP(simplex.p[0],simplex.p[1]);
  579. }
  580. /* Build initial hull */
  581. sFace* tetra[]={newface(simplex.c[0],simplex.c[1],simplex.c[2],true),
  582. newface(simplex.c[1],simplex.c[0],simplex.c[3],true),
  583. newface(simplex.c[2],simplex.c[1],simplex.c[3],true),
  584. newface(simplex.c[0],simplex.c[2],simplex.c[3],true)};
  585. if(m_hull.count==4)
  586. {
  587. sFace* best=findbest();
  588. sFace outer=*best;
  589. U pass=0;
  590. U iterations=0;
  591. bind(tetra[0],0,tetra[1],0);
  592. bind(tetra[0],1,tetra[2],0);
  593. bind(tetra[0],2,tetra[3],0);
  594. bind(tetra[1],1,tetra[3],2);
  595. bind(tetra[1],2,tetra[2],1);
  596. bind(tetra[2],2,tetra[3],1);
  597. m_status=eStatus::Valid;
  598. for(;iterations<EPA_MAX_ITERATIONS;++iterations)
  599. {
  600. if(m_nextsv<EPA_MAX_VERTICES)
  601. {
  602. sHorizon horizon;
  603. sSV* w=&m_sv_store[m_nextsv++];
  604. bool valid=true;
  605. best->pass = (U1)(++pass);
  606. gjk.getsupport(best->n,*w);
  607. const real_t wdist=vec3_dot(best->n,w->w)-best->d;
  608. if(wdist>EPA_ACCURACY)
  609. {
  610. for(U j=0;(j<3)&&valid;++j)
  611. {
  612. valid&=expand( pass,w,
  613. best->f[j],best->e[j],
  614. horizon);
  615. }
  616. if(valid&&(horizon.nf>=3))
  617. {
  618. bind(horizon.cf,1,horizon.ff,2);
  619. remove(m_hull,best);
  620. append(m_stock,best);
  621. best=findbest();
  622. if(best->p>=outer.p) outer=*best;
  623. } else { m_status=eStatus::InvalidHull;break; }
  624. } else { m_status=eStatus::AccuraryReached;break; }
  625. } else { m_status=eStatus::OutOfVertices;break; }
  626. }
  627. const Vector3 projection=outer.n*outer.d;
  628. m_normal = outer.n;
  629. m_depth = outer.d;
  630. m_result.rank = 3;
  631. m_result.c[0] = outer.c[0];
  632. m_result.c[1] = outer.c[1];
  633. m_result.c[2] = outer.c[2];
  634. m_result.p[0] = vec3_cross( outer.c[1]->w-projection,
  635. outer.c[2]->w-projection).length();
  636. m_result.p[1] = vec3_cross( outer.c[2]->w-projection,
  637. outer.c[0]->w-projection).length();
  638. m_result.p[2] = vec3_cross( outer.c[0]->w-projection,
  639. outer.c[1]->w-projection).length();
  640. const real_t sum=m_result.p[0]+m_result.p[1]+m_result.p[2];
  641. m_result.p[0] /= sum;
  642. m_result.p[1] /= sum;
  643. m_result.p[2] /= sum;
  644. return(m_status);
  645. }
  646. }
  647. /* Fallback */
  648. m_status = eStatus::FallBack;
  649. m_normal = -guess;
  650. const real_t nl=m_normal.length();
  651. if(nl>0)
  652. m_normal = m_normal/nl;
  653. else
  654. m_normal = Vector3(1,0,0);
  655. m_depth = 0;
  656. m_result.rank=1;
  657. m_result.c[0]=simplex.c[0];
  658. m_result.p[0]=1;
  659. return(m_status);
  660. }
  661. sFace* newface(sSV* a,sSV* b,sSV* c,bool forced)
  662. {
  663. if(m_stock.root)
  664. {
  665. sFace* face=m_stock.root;
  666. remove(m_stock,face);
  667. append(m_hull,face);
  668. face->pass = 0;
  669. face->c[0] = a;
  670. face->c[1] = b;
  671. face->c[2] = c;
  672. face->n = vec3_cross(b->w-a->w,c->w-a->w);
  673. const real_t l=face->n.length();
  674. const bool v=l>EPA_ACCURACY;
  675. face->p = MIN(MIN(
  676. vec3_dot(a->w,vec3_cross(face->n,a->w-b->w)),
  677. vec3_dot(b->w,vec3_cross(face->n,b->w-c->w))),
  678. vec3_dot(c->w,vec3_cross(face->n,c->w-a->w))) /
  679. (v?l:1);
  680. face->p = face->p>=-EPA_INSIDE_EPS?0:face->p;
  681. if(v)
  682. {
  683. face->d = vec3_dot(a->w,face->n)/l;
  684. face->n /= l;
  685. if(forced||(face->d>=-EPA_PLANE_EPS))
  686. {
  687. return(face);
  688. } else m_status=eStatus::NonConvex;
  689. } else m_status=eStatus::Degenerated;
  690. remove(m_hull,face);
  691. append(m_stock,face);
  692. return(0);
  693. }
  694. m_status=m_stock.root?eStatus::OutOfVertices:eStatus::OutOfFaces;
  695. return(0);
  696. }
  697. sFace* findbest()
  698. {
  699. sFace* minf=m_hull.root;
  700. real_t mind=minf->d*minf->d;
  701. real_t maxp=minf->p;
  702. for(sFace* f=minf->l[1];f;f=f->l[1])
  703. {
  704. const real_t sqd=f->d*f->d;
  705. if((f->p>=maxp)&&(sqd<mind))
  706. {
  707. minf=f;
  708. mind=sqd;
  709. maxp=f->p;
  710. }
  711. }
  712. return(minf);
  713. }
  714. bool expand(U pass,sSV* w,sFace* f,U e,sHorizon& horizon)
  715. {
  716. static const U i1m3[]={1,2,0};
  717. static const U i2m3[]={2,0,1};
  718. if(f->pass!=pass)
  719. {
  720. const U e1=i1m3[e];
  721. if((vec3_dot(f->n,w->w)-f->d)<-EPA_PLANE_EPS)
  722. {
  723. sFace* nf=newface(f->c[e1],f->c[e],w,false);
  724. if(nf)
  725. {
  726. bind(nf,0,f,e);
  727. if(horizon.cf) bind(horizon.cf,1,nf,2); else horizon.ff=nf;
  728. horizon.cf=nf;
  729. ++horizon.nf;
  730. return(true);
  731. }
  732. }
  733. else
  734. {
  735. const U e2=i2m3[e];
  736. f->pass = (U1)pass;
  737. if( expand(pass,w,f->f[e1],f->e[e1],horizon)&&
  738. expand(pass,w,f->f[e2],f->e[e2],horizon))
  739. {
  740. remove(m_hull,f);
  741. append(m_stock,f);
  742. return(true);
  743. }
  744. }
  745. }
  746. return(false);
  747. }
  748. };
  749. //
  750. static void Initialize( const ShapeSW* shape0,const Transform& wtrs0,
  751. const ShapeSW* shape1,const Transform& wtrs1,
  752. sResults& results,
  753. tShape& shape,
  754. bool withmargins)
  755. {
  756. /* Results */
  757. results.witnesses[0] =
  758. results.witnesses[1] = Vector3(0,0,0);
  759. results.status = sResults::Separated;
  760. /* Shape */
  761. shape.m_shapes[0] = shape0;
  762. shape.m_shapes[1] = shape1;
  763. shape.transform_A = wtrs0;
  764. shape.transform_B = wtrs1;
  765. }
  766. //
  767. // Api
  768. //
  769. //
  770. //
  771. bool Distance( const ShapeSW* shape0,
  772. const Transform& wtrs0,
  773. const ShapeSW* shape1,
  774. const Transform& wtrs1,
  775. const Vector3& guess,
  776. sResults& results)
  777. {
  778. tShape shape;
  779. Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,false);
  780. GJK gjk;
  781. GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,guess);
  782. if(gjk_status==GJK::eStatus::Valid)
  783. {
  784. Vector3 w0=Vector3(0,0,0);
  785. Vector3 w1=Vector3(0,0,0);
  786. for(U i=0;i<gjk.m_simplex->rank;++i)
  787. {
  788. const real_t p=gjk.m_simplex->p[i];
  789. w0+=shape.Support( gjk.m_simplex->c[i]->d,0)*p;
  790. w1+=shape.Support(-gjk.m_simplex->c[i]->d,1)*p;
  791. }
  792. results.witnesses[0] = w0;
  793. results.witnesses[1] = w1;
  794. results.normal = w0-w1;
  795. results.distance = results.normal.length();
  796. results.normal /= results.distance>GJK_MIN_DISTANCE?results.distance:1;
  797. return(true);
  798. }
  799. else
  800. {
  801. results.status = gjk_status==GJK::eStatus::Inside?
  802. sResults::Penetrating :
  803. sResults::GJK_Failed ;
  804. return(false);
  805. }
  806. }
  807. //
  808. bool Penetration( const ShapeSW* shape0,
  809. const Transform& wtrs0,
  810. const ShapeSW* shape1,
  811. const Transform& wtrs1,
  812. const Vector3& guess,
  813. sResults& results
  814. )
  815. {
  816. tShape shape;
  817. Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,false);
  818. GJK gjk;
  819. GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,-guess);
  820. switch(gjk_status)
  821. {
  822. case GJK::eStatus::Inside:
  823. {
  824. EPA epa;
  825. EPA::eStatus::_ epa_status=epa.Evaluate(gjk,-guess);
  826. if(epa_status!=EPA::eStatus::Failed)
  827. {
  828. Vector3 w0=Vector3(0,0,0);
  829. for(U i=0;i<epa.m_result.rank;++i)
  830. {
  831. w0+=shape.Support(epa.m_result.c[i]->d,0)*epa.m_result.p[i];
  832. }
  833. results.status = sResults::Penetrating;
  834. results.witnesses[0] = w0;
  835. results.witnesses[1] = w0-epa.m_normal*epa.m_depth;
  836. results.normal = -epa.m_normal;
  837. results.distance = -epa.m_depth;
  838. return(true);
  839. } else results.status=sResults::EPA_Failed;
  840. }
  841. break;
  842. case GJK::eStatus::Failed:
  843. results.status=sResults::GJK_Failed;
  844. break;
  845. default: {}
  846. }
  847. return(false);
  848. }
  849. /* Symbols cleanup */
  850. #undef GJK_MAX_ITERATIONS
  851. #undef GJK_ACCURARY
  852. #undef GJK_MIN_DISTANCE
  853. #undef GJK_DUPLICATED_EPS
  854. #undef GJK_SIMPLEX2_EPS
  855. #undef GJK_SIMPLEX3_EPS
  856. #undef GJK_SIMPLEX4_EPS
  857. #undef EPA_MAX_VERTICES
  858. #undef EPA_MAX_FACES
  859. #undef EPA_MAX_ITERATIONS
  860. #undef EPA_ACCURACY
  861. #undef EPA_FALLBACK
  862. #undef EPA_PLANE_EPS
  863. #undef EPA_INSIDE_EPS
  864. } // end of namespace
  865. /* clang-format on */
  866. bool gjk_epa_calculate_distance(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, Vector3 &r_result_A, Vector3 &r_result_B) {
  867. GjkEpa2::sResults res;
  868. if (GjkEpa2::Distance(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_transform_B.origin - p_transform_A.origin, res)) {
  869. r_result_A = res.witnesses[0];
  870. r_result_B = res.witnesses[1];
  871. return true;
  872. }
  873. return false;
  874. }
  875. bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform &p_transform_A, const ShapeSW *p_shape_B, const Transform &p_transform_B, CollisionSolverSW::CallbackResult p_result_callback, void *p_userdata, bool p_swap) {
  876. GjkEpa2::sResults res;
  877. if (GjkEpa2::Penetration(p_shape_A, p_transform_A, p_shape_B, p_transform_B, p_transform_B.origin - p_transform_A.origin, res)) {
  878. if (p_result_callback) {
  879. if (p_swap)
  880. p_result_callback(res.witnesses[1], res.witnesses[0], p_userdata);
  881. else
  882. p_result_callback(res.witnesses[0], res.witnesses[1], p_userdata);
  883. }
  884. return true;
  885. }
  886. return false;
  887. }