gjk_epa.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. /**************************************************************************/
  2. /* gjk_epa.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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_ACCURACY ((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 128
  66. #define EPA_MAX_FACES (EPA_MAX_VERTICES*2)
  67. #define EPA_MAX_ITERATIONS 255
  68. // -- GODOT start --
  69. //#define EPA_ACCURACY ((real_t)0.0001)
  70. #define EPA_ACCURACY ((real_t)0.00001)
  71. // -- GODOT end --
  72. #define EPA_FALLBACK (10*EPA_ACCURACY)
  73. #define EPA_PLANE_EPS ((real_t)0.00001)
  74. #define EPA_INSIDE_EPS ((real_t)0.01)
  75. namespace GjkEpa2 {
  76. struct sResults {
  77. enum eStatus {
  78. Separated, /* Shapes doesn't penetrate */
  79. Penetrating, /* Shapes are penetrating */
  80. GJK_Failed, /* GJK phase fail, no big issue, shapes are probably just 'touching' */
  81. EPA_Failed /* EPA phase fail, bigger problem, need to save parameters, and debug */
  82. } status;
  83. Vector3 witnesses[2];
  84. Vector3 normal;
  85. real_t distance = 0.0;
  86. };
  87. // Shorthands
  88. typedef unsigned int U;
  89. typedef unsigned char U1;
  90. // MinkowskiDiff
  91. struct MinkowskiDiff {
  92. const GodotShape3D* m_shapes[2];
  93. Transform3D transform_A;
  94. Transform3D transform_B;
  95. real_t margin_A = 0.0;
  96. real_t margin_B = 0.0;
  97. Vector3 (*get_support)(const GodotShape3D*, const Vector3&, real_t) = nullptr;
  98. void Initialize(const GodotShape3D* shape0, const Transform3D& wtrs0, const real_t margin0,
  99. const GodotShape3D* shape1, const Transform3D& wtrs1, const real_t margin1) {
  100. m_shapes[0] = shape0;
  101. m_shapes[1] = shape1;
  102. transform_A = wtrs0;
  103. transform_B = wtrs1;
  104. margin_A = margin0;
  105. margin_B = margin1;
  106. if ((margin0 > 0.0) || (margin1 > 0.0)) {
  107. get_support = get_support_with_margin;
  108. } else {
  109. get_support = get_support_without_margin;
  110. }
  111. }
  112. static Vector3 get_support_without_margin(const GodotShape3D* p_shape, const Vector3& p_dir, real_t p_margin) {
  113. return p_shape->get_support(p_dir.normalized());
  114. }
  115. static Vector3 get_support_with_margin(const GodotShape3D* p_shape, const Vector3& p_dir, real_t p_margin) {
  116. Vector3 local_dir_norm = p_dir;
  117. if (local_dir_norm.length_squared() < CMP_EPSILON2) {
  118. local_dir_norm = Vector3(-1.0, -1.0, -1.0);
  119. }
  120. local_dir_norm.normalize();
  121. return p_shape->get_support(local_dir_norm) + p_margin * local_dir_norm;
  122. }
  123. // i wonder how this could be sped up... if it can
  124. _FORCE_INLINE_ Vector3 Support0(const Vector3& d) const {
  125. return transform_A.xform(get_support(m_shapes[0], transform_A.basis.xform_inv(d), margin_A));
  126. }
  127. _FORCE_INLINE_ Vector3 Support1(const Vector3& d) const {
  128. return transform_B.xform(get_support(m_shapes[1], transform_B.basis.xform_inv(d), margin_B));
  129. }
  130. _FORCE_INLINE_ Vector3 Support (const Vector3& d) const {
  131. return (Support0(d) - Support1(-d));
  132. }
  133. _FORCE_INLINE_ Vector3 Support(const Vector3& d, U index) const {
  134. if (index) {
  135. return Support1(d);
  136. } else {
  137. return Support0(d);
  138. }
  139. }
  140. };
  141. typedef MinkowskiDiff tShape;
  142. // GJK
  143. struct GJK
  144. {
  145. /* Types */
  146. struct sSV
  147. {
  148. Vector3 d,w;
  149. };
  150. struct sSimplex
  151. {
  152. sSV* c[4];
  153. real_t p[4];
  154. U rank;
  155. };
  156. struct eStatus { enum _ {
  157. Valid,
  158. Inside,
  159. Failed };};
  160. /* Fields */
  161. tShape m_shape;
  162. Vector3 m_ray;
  163. real_t m_distance = 0.0f;
  164. sSimplex m_simplices[2];
  165. sSV m_store[4];
  166. sSV* m_free[4];
  167. U m_nfree = 0;
  168. U m_current = 0;
  169. sSimplex* m_simplex = nullptr;
  170. eStatus::_ m_status;
  171. /* Methods */
  172. GJK()
  173. {
  174. Initialize();
  175. }
  176. void Initialize()
  177. {
  178. m_ray = Vector3(0,0,0);
  179. m_nfree = 0;
  180. m_status = eStatus::Failed;
  181. m_current = 0;
  182. m_distance = 0;
  183. }
  184. eStatus::_ Evaluate(const tShape& shapearg,const Vector3& guess)
  185. {
  186. U iterations=0;
  187. real_t sqdist=0;
  188. real_t alpha=0;
  189. Vector3 lastw[4];
  190. U clastw=0;
  191. /* Initialize solver */
  192. m_free[0] = &m_store[0];
  193. m_free[1] = &m_store[1];
  194. m_free[2] = &m_store[2];
  195. m_free[3] = &m_store[3];
  196. m_nfree = 4;
  197. m_current = 0;
  198. m_status = eStatus::Valid;
  199. m_shape = shapearg;
  200. m_distance = 0;
  201. /* Initialize simplex */
  202. m_simplices[0].rank = 0;
  203. m_ray = guess;
  204. const real_t sqrl= m_ray.length_squared();
  205. appendvertice(m_simplices[0],sqrl>0?-m_ray:Vector3(1,0,0));
  206. m_simplices[0].p[0] = 1;
  207. m_ray = m_simplices[0].c[0]->w;
  208. sqdist = sqrl;
  209. lastw[0] =
  210. lastw[1] =
  211. lastw[2] =
  212. lastw[3] = m_ray;
  213. /* Loop */
  214. do {
  215. const U next=1-m_current;
  216. sSimplex& cs=m_simplices[m_current];
  217. sSimplex& ns=m_simplices[next];
  218. /* Check zero */
  219. const real_t rl=m_ray.length();
  220. if(rl<GJK_MIN_DISTANCE)
  221. {/* Touching or inside */
  222. m_status=eStatus::Inside;
  223. break;
  224. }
  225. /* Append new vertice in -'v' direction */
  226. appendvertice(cs,-m_ray);
  227. const Vector3& w=cs.c[cs.rank-1]->w;
  228. bool found=false;
  229. for(U i=0;i<4;++i)
  230. {
  231. if((w-lastw[i]).length_squared()<GJK_DUPLICATED_EPS)
  232. { found=true;break; }
  233. }
  234. if(found)
  235. {/* Return old simplex */
  236. removevertice(m_simplices[m_current]);
  237. break;
  238. }
  239. else
  240. {/* Update lastw */
  241. lastw[clastw=(clastw+1)&3]=w;
  242. }
  243. /* Check for termination */
  244. const real_t omega=vec3_dot(m_ray,w)/rl;
  245. alpha=MAX(omega,alpha);
  246. if(((rl-alpha)-(GJK_ACCURACY*rl))<=0)
  247. {/* Return old simplex */
  248. removevertice(m_simplices[m_current]);
  249. break;
  250. }
  251. /* Reduce simplex */
  252. real_t weights[4];
  253. U mask=0;
  254. switch(cs.rank)
  255. {
  256. case 2: sqdist=projectorigin( cs.c[0]->w,
  257. cs.c[1]->w,
  258. weights,mask);break;
  259. case 3: sqdist=projectorigin( cs.c[0]->w,
  260. cs.c[1]->w,
  261. cs.c[2]->w,
  262. weights,mask);break;
  263. case 4: sqdist=projectorigin( cs.c[0]->w,
  264. cs.c[1]->w,
  265. cs.c[2]->w,
  266. cs.c[3]->w,
  267. weights,mask);break;
  268. }
  269. if(sqdist>=0)
  270. {/* Valid */
  271. ns.rank = 0;
  272. m_ray = Vector3(0,0,0);
  273. m_current = next;
  274. for(U i=0,ni=cs.rank;i<ni;++i)
  275. {
  276. if(mask&(1<<i))
  277. {
  278. ns.c[ns.rank] = cs.c[i];
  279. ns.p[ns.rank++] = weights[i];
  280. m_ray += cs.c[i]->w*weights[i];
  281. }
  282. else
  283. {
  284. m_free[m_nfree++] = cs.c[i];
  285. }
  286. }
  287. if(mask==15) { m_status=eStatus::Inside;
  288. }
  289. }
  290. else
  291. {/* Return old simplex */
  292. removevertice(m_simplices[m_current]);
  293. break;
  294. }
  295. m_status=((++iterations)<GJK_MAX_ITERATIONS)?m_status:eStatus::Failed;
  296. } while(m_status==eStatus::Valid);
  297. m_simplex=&m_simplices[m_current];
  298. switch(m_status)
  299. {
  300. case eStatus::Valid: m_distance=m_ray.length();break;
  301. case eStatus::Inside: m_distance=0;break;
  302. default: {}
  303. }
  304. return(m_status);
  305. }
  306. bool EncloseOrigin()
  307. {
  308. switch(m_simplex->rank)
  309. {
  310. case 1:
  311. {
  312. for(U i=0;i<3;++i)
  313. {
  314. Vector3 axis=Vector3(0,0,0);
  315. axis[i]=1;
  316. appendvertice(*m_simplex, axis);
  317. if(EncloseOrigin()) { return(true);
  318. }
  319. removevertice(*m_simplex);
  320. appendvertice(*m_simplex,-axis);
  321. if(EncloseOrigin()) { return(true);
  322. }
  323. removevertice(*m_simplex);
  324. }
  325. }
  326. break;
  327. case 2:
  328. {
  329. const Vector3 d=m_simplex->c[1]->w-m_simplex->c[0]->w;
  330. for(U i=0;i<3;++i)
  331. {
  332. Vector3 axis=Vector3(0,0,0);
  333. axis[i]=1;
  334. const Vector3 p=vec3_cross(d,axis);
  335. if(p.length_squared()>0)
  336. {
  337. appendvertice(*m_simplex, p);
  338. if(EncloseOrigin()) { return(true);
  339. }
  340. removevertice(*m_simplex);
  341. appendvertice(*m_simplex,-p);
  342. if(EncloseOrigin()) { return(true);
  343. }
  344. removevertice(*m_simplex);
  345. }
  346. }
  347. }
  348. break;
  349. case 3:
  350. {
  351. const Vector3 n=vec3_cross(m_simplex->c[1]->w-m_simplex->c[0]->w,
  352. m_simplex->c[2]->w-m_simplex->c[0]->w);
  353. if(n.length_squared()>0)
  354. {
  355. appendvertice(*m_simplex,n);
  356. if(EncloseOrigin()) { return(true);
  357. }
  358. removevertice(*m_simplex);
  359. appendvertice(*m_simplex,-n);
  360. if(EncloseOrigin()) { return(true);
  361. }
  362. removevertice(*m_simplex);
  363. }
  364. }
  365. break;
  366. case 4:
  367. {
  368. if(Math::abs(det( m_simplex->c[0]->w-m_simplex->c[3]->w,
  369. m_simplex->c[1]->w-m_simplex->c[3]->w,
  370. m_simplex->c[2]->w-m_simplex->c[3]->w))>0) {
  371. return(true);
  372. }
  373. }
  374. break;
  375. }
  376. return(false);
  377. }
  378. /* Internals */
  379. void getsupport(const Vector3& d,sSV& sv) const
  380. {
  381. sv.d = d/d.length();
  382. sv.w = m_shape.Support(sv.d);
  383. }
  384. void removevertice(sSimplex& simplex)
  385. {
  386. m_free[m_nfree++]=simplex.c[--simplex.rank];
  387. }
  388. void appendvertice(sSimplex& simplex,const Vector3& v)
  389. {
  390. simplex.p[simplex.rank]=0;
  391. simplex.c[simplex.rank]=m_free[--m_nfree];
  392. getsupport(v,*simplex.c[simplex.rank++]);
  393. }
  394. static real_t det(const Vector3& a,const Vector3& b,const Vector3& c)
  395. {
  396. return( a.y*b.z*c.x+a.z*b.x*c.y-
  397. a.x*b.z*c.y-a.y*b.x*c.z+
  398. a.x*b.y*c.z-a.z*b.y*c.x);
  399. }
  400. static real_t projectorigin( const Vector3& a,
  401. const Vector3& b,
  402. real_t* w,U& m)
  403. {
  404. const Vector3 d=b-a;
  405. const real_t l=d.length_squared();
  406. if(l>GJK_SIMPLEX2_EPS)
  407. {
  408. const real_t t(l>0?-vec3_dot(a,d)/l:0);
  409. if(t>=1) { w[0]=0;w[1]=1;m=2;return(b.length_squared()); }
  410. else if(t<=0) { w[0]=1;w[1]=0;m=1;return(a.length_squared()); }
  411. else { w[0]=1-(w[1]=t);m=3;return((a+d*t).length_squared()); }
  412. }
  413. return(-1);
  414. }
  415. static real_t projectorigin( const Vector3& a,
  416. const Vector3& b,
  417. const Vector3& c,
  418. real_t* w,U& m)
  419. {
  420. static const U imd3[]={1,2,0};
  421. const Vector3* vt[]={&a,&b,&c};
  422. const Vector3 dl[]={a-b,b-c,c-a};
  423. const Vector3 n=vec3_cross(dl[0],dl[1]);
  424. const real_t l=n.length_squared();
  425. if(l>GJK_SIMPLEX3_EPS)
  426. {
  427. real_t mindist=-1;
  428. real_t subw[2] = { 0 , 0};
  429. U subm = 0;
  430. for(U i=0;i<3;++i)
  431. {
  432. if(vec3_dot(*vt[i],vec3_cross(dl[i],n))>0)
  433. {
  434. const U j=imd3[i];
  435. const real_t subd(projectorigin(*vt[i],*vt[j],subw,subm));
  436. if((mindist<0)||(subd<mindist))
  437. {
  438. mindist = subd;
  439. m = static_cast<U>(((subm&1)?1<<i:0)+((subm&2)?1<<j:0));
  440. w[i] = subw[0];
  441. w[j] = subw[1];
  442. w[imd3[j]] = 0;
  443. }
  444. }
  445. }
  446. if(mindist<0)
  447. {
  448. const real_t d=vec3_dot(a,n);
  449. const real_t s=Math::sqrt(l);
  450. const Vector3 p=n*(d/l);
  451. mindist = p.length_squared();
  452. m = 7;
  453. w[0] = (vec3_cross(dl[1],b-p)).length()/s;
  454. w[1] = (vec3_cross(dl[2],c-p)).length()/s;
  455. w[2] = 1-(w[0]+w[1]);
  456. }
  457. return(mindist);
  458. }
  459. return(-1);
  460. }
  461. static real_t projectorigin( const Vector3& a,
  462. const Vector3& b,
  463. const Vector3& c,
  464. const Vector3& d,
  465. real_t* w,U& m)
  466. {
  467. static const U imd3[]={1,2,0};
  468. const Vector3* vt[]={&a,&b,&c,&d};
  469. const Vector3 dl[]={a-d,b-d,c-d};
  470. const real_t vl=det(dl[0],dl[1],dl[2]);
  471. const bool ng=(vl*vec3_dot(a,vec3_cross(b-c,a-b)))<=0;
  472. if(ng&&(Math::abs(vl)>GJK_SIMPLEX4_EPS))
  473. {
  474. real_t mindist=-1;
  475. real_t subw[3] = {0.f, 0.f, 0.f};
  476. U subm=0;
  477. for(U i=0;i<3;++i)
  478. {
  479. const U j=imd3[i];
  480. const real_t s=vl*vec3_dot(d,vec3_cross(dl[i],dl[j]));
  481. if(s>0)
  482. {
  483. const real_t subd=projectorigin(*vt[i],*vt[j],d,subw,subm);
  484. if((mindist<0)||(subd<mindist))
  485. {
  486. mindist = subd;
  487. m = static_cast<U>((subm&1?1<<i:0)+
  488. (subm&2?1<<j:0)+
  489. (subm&4?8:0));
  490. w[i] = subw[0];
  491. w[j] = subw[1];
  492. w[imd3[j]] = 0;
  493. w[3] = subw[2];
  494. }
  495. }
  496. }
  497. if(mindist<0)
  498. {
  499. mindist = 0;
  500. m = 15;
  501. w[0] = det(c,b,d)/vl;
  502. w[1] = det(a,c,d)/vl;
  503. w[2] = det(b,a,d)/vl;
  504. w[3] = 1-(w[0]+w[1]+w[2]);
  505. }
  506. return(mindist);
  507. }
  508. return(-1);
  509. }
  510. };
  511. // EPA
  512. struct EPA
  513. {
  514. /* Types */
  515. typedef GJK::sSV sSV;
  516. struct sFace
  517. {
  518. Vector3 n;
  519. real_t d = 0.0f;
  520. sSV* c[3];
  521. sFace* f[3];
  522. sFace* l[2];
  523. U1 e[3];
  524. U1 pass = 0;
  525. };
  526. struct sList
  527. {
  528. sFace* root = nullptr;
  529. U count = 0;
  530. sList() {}
  531. };
  532. struct sHorizon
  533. {
  534. sFace* cf = nullptr;
  535. sFace* ff = nullptr;
  536. U nf = 0;
  537. sHorizon() {}
  538. };
  539. struct eStatus { enum _ {
  540. Valid,
  541. Touching,
  542. Degenerated,
  543. NonConvex,
  544. InvalidHull,
  545. OutOfFaces,
  546. OutOfVertices,
  547. AccuraryReached,
  548. FallBack,
  549. Failed };};
  550. /* Fields */
  551. eStatus::_ m_status;
  552. GJK::sSimplex m_result;
  553. Vector3 m_normal;
  554. real_t m_depth = 0.0f;
  555. sSV m_sv_store[EPA_MAX_VERTICES];
  556. sFace m_fc_store[EPA_MAX_FACES];
  557. U m_nextsv = 0;
  558. sList m_hull;
  559. sList m_stock;
  560. /* Methods */
  561. EPA()
  562. {
  563. Initialize();
  564. }
  565. static inline void bind(sFace* fa,U ea,sFace* fb,U eb)
  566. {
  567. fa->e[ea]=(U1)eb;fa->f[ea]=fb;
  568. fb->e[eb]=(U1)ea;fb->f[eb]=fa;
  569. }
  570. static inline void append(sList& list,sFace* face)
  571. {
  572. face->l[0] = nullptr;
  573. face->l[1] = list.root;
  574. if(list.root) { list.root->l[0]=face;
  575. }
  576. list.root = face;
  577. ++list.count;
  578. }
  579. static inline void remove(sList& list,sFace* face)
  580. {
  581. if(face->l[1]) { face->l[1]->l[0]=face->l[0];
  582. }
  583. if(face->l[0]) { face->l[0]->l[1]=face->l[1];
  584. }
  585. if(face==list.root) { list.root=face->l[1];
  586. }
  587. --list.count;
  588. }
  589. void Initialize()
  590. {
  591. m_status = eStatus::Failed;
  592. m_normal = Vector3(0,0,0);
  593. m_depth = 0;
  594. m_nextsv = 0;
  595. for(U i=0;i<EPA_MAX_FACES;++i)
  596. {
  597. append(m_stock,&m_fc_store[EPA_MAX_FACES-i-1]);
  598. }
  599. }
  600. eStatus::_ Evaluate(GJK& gjk,const Vector3& guess)
  601. {
  602. GJK::sSimplex& simplex=*gjk.m_simplex;
  603. if((simplex.rank>1)&&gjk.EncloseOrigin())
  604. {
  605. /* Clean up */
  606. while(m_hull.root)
  607. {
  608. sFace* f = m_hull.root;
  609. remove(m_hull,f);
  610. append(m_stock,f);
  611. }
  612. m_status = eStatus::Valid;
  613. m_nextsv = 0;
  614. /* Orient simplex */
  615. if(gjk.det( simplex.c[0]->w-simplex.c[3]->w,
  616. simplex.c[1]->w-simplex.c[3]->w,
  617. simplex.c[2]->w-simplex.c[3]->w)<0)
  618. {
  619. SWAP(simplex.c[0],simplex.c[1]);
  620. SWAP(simplex.p[0],simplex.p[1]);
  621. }
  622. /* Build initial hull */
  623. sFace* tetra[]={newface(simplex.c[0],simplex.c[1],simplex.c[2],true),
  624. newface(simplex.c[1],simplex.c[0],simplex.c[3],true),
  625. newface(simplex.c[2],simplex.c[1],simplex.c[3],true),
  626. newface(simplex.c[0],simplex.c[2],simplex.c[3],true)};
  627. if(m_hull.count==4)
  628. {
  629. sFace* best=findbest();
  630. sFace outer=*best;
  631. U pass=0;
  632. U iterations=0;
  633. bind(tetra[0],0,tetra[1],0);
  634. bind(tetra[0],1,tetra[2],0);
  635. bind(tetra[0],2,tetra[3],0);
  636. bind(tetra[1],1,tetra[3],2);
  637. bind(tetra[1],2,tetra[2],1);
  638. bind(tetra[2],2,tetra[3],1);
  639. m_status=eStatus::Valid;
  640. for(;iterations<EPA_MAX_ITERATIONS;++iterations)
  641. {
  642. if(m_nextsv<EPA_MAX_VERTICES)
  643. {
  644. sHorizon horizon;
  645. sSV* w=&m_sv_store[m_nextsv++];
  646. bool valid=true;
  647. best->pass = (U1)(++pass);
  648. gjk.getsupport(best->n,*w);
  649. const real_t wdist=vec3_dot(best->n,w->w)-best->d;
  650. if(wdist>EPA_ACCURACY)
  651. {
  652. for(U j=0;(j<3)&&valid;++j)
  653. {
  654. valid&=expand( pass,w,
  655. best->f[j],best->e[j],
  656. horizon);
  657. }
  658. if(valid&&(horizon.nf>=3))
  659. {
  660. bind(horizon.cf,1,horizon.ff,2);
  661. remove(m_hull,best);
  662. append(m_stock,best);
  663. best=findbest();
  664. outer=*best;
  665. } else { m_status=eStatus::InvalidHull;break; }
  666. } else { m_status=eStatus::AccuraryReached;break; }
  667. } else { m_status=eStatus::OutOfVertices;break; }
  668. }
  669. const Vector3 projection=outer.n*outer.d;
  670. m_normal = outer.n;
  671. m_depth = outer.d;
  672. m_result.rank = 3;
  673. m_result.c[0] = outer.c[0];
  674. m_result.c[1] = outer.c[1];
  675. m_result.c[2] = outer.c[2];
  676. m_result.p[0] = vec3_cross( outer.c[1]->w-projection,
  677. outer.c[2]->w-projection).length();
  678. m_result.p[1] = vec3_cross( outer.c[2]->w-projection,
  679. outer.c[0]->w-projection).length();
  680. m_result.p[2] = vec3_cross( outer.c[0]->w-projection,
  681. outer.c[1]->w-projection).length();
  682. const real_t sum=m_result.p[0]+m_result.p[1]+m_result.p[2];
  683. m_result.p[0] /= sum;
  684. m_result.p[1] /= sum;
  685. m_result.p[2] /= sum;
  686. return(m_status);
  687. }
  688. }
  689. /* Fallback */
  690. m_status = eStatus::FallBack;
  691. m_normal = -guess;
  692. const real_t nl = m_normal.length();
  693. if (nl > 0) {
  694. m_normal = m_normal/nl;
  695. } else {
  696. m_normal = Vector3(1,0,0);
  697. }
  698. m_depth = 0;
  699. m_result.rank=1;
  700. m_result.c[0]=simplex.c[0];
  701. m_result.p[0]=1;
  702. return(m_status);
  703. }
  704. bool getedgedist(sFace* face, sSV* a, sSV* b, real_t& dist)
  705. {
  706. const Vector3 ba = b->w - a->w;
  707. const Vector3 n_ab = vec3_cross(ba, face->n); // Outward facing edge normal direction, on triangle plane
  708. const real_t a_dot_nab = vec3_dot(a->w, n_ab); // Only care about the sign to determine inside/outside, so not normalization required
  709. if (a_dot_nab < 0) {
  710. // Outside of edge a->b
  711. const real_t ba_l2 = ba.length_squared();
  712. const real_t a_dot_ba = vec3_dot(a->w, ba);
  713. const real_t b_dot_ba = vec3_dot(b->w, ba);
  714. if (a_dot_ba > 0) {
  715. // Pick distance vertex a
  716. dist = a->w.length();
  717. } else if (b_dot_ba < 0) {
  718. // Pick distance vertex b
  719. dist = b->w.length();
  720. } else {
  721. // Pick distance to edge a->b
  722. const real_t a_dot_b = vec3_dot(a->w, b->w);
  723. dist = Math::sqrt(MAX((a->w.length_squared() * b->w.length_squared() - a_dot_b * a_dot_b) / ba_l2, 0.0));
  724. }
  725. return true;
  726. }
  727. return false;
  728. }
  729. sFace* newface(sSV* a,sSV* b,sSV* c,bool forced)
  730. {
  731. if (m_stock.root) {
  732. sFace* face=m_stock.root;
  733. remove(m_stock,face);
  734. append(m_hull,face);
  735. face->pass = 0;
  736. face->c[0] = a;
  737. face->c[1] = b;
  738. face->c[2] = c;
  739. face->n = vec3_cross(b->w-a->w,c->w-a->w);
  740. const real_t l=face->n.length();
  741. const bool v=l>EPA_ACCURACY;
  742. if (v) {
  743. if (!(getedgedist(face, a, b, face->d) ||
  744. getedgedist(face, b, c, face->d) ||
  745. getedgedist(face, c, a, face->d))) {
  746. // Origin projects to the interior of the triangle
  747. // Use distance to triangle plane
  748. face->d = vec3_dot(a->w, face->n) / l;
  749. }
  750. face->n /= l;
  751. if (forced||(face->d>=-EPA_PLANE_EPS)) {
  752. return(face);
  753. } else {
  754. m_status=eStatus::NonConvex;
  755. }
  756. } else {
  757. m_status=eStatus::Degenerated;
  758. }
  759. remove(m_hull,face);
  760. append(m_stock,face);
  761. return(nullptr);
  762. }
  763. // -- GODOT start --
  764. //m_status=m_stock.root?eStatus::OutOfVertices:eStatus::OutOfFaces;
  765. m_status=eStatus::OutOfFaces;
  766. // -- GODOT end --
  767. return(nullptr);
  768. }
  769. sFace* findbest()
  770. {
  771. sFace* minf=m_hull.root;
  772. real_t mind=minf->d*minf->d;
  773. for(sFace* f=minf->l[1];f;f=f->l[1])
  774. {
  775. const real_t sqd=f->d*f->d;
  776. if(sqd<mind)
  777. {
  778. minf=f;
  779. mind=sqd;
  780. }
  781. }
  782. return(minf);
  783. }
  784. bool expand(U pass,sSV* w,sFace* f,U e,sHorizon& horizon)
  785. {
  786. static const U i1m3[]={1,2,0};
  787. static const U i2m3[]={2,0,1};
  788. if(f->pass!=pass)
  789. {
  790. const U e1=i1m3[e];
  791. if((vec3_dot(f->n,w->w)-f->d)<-EPA_PLANE_EPS)
  792. {
  793. sFace* nf=newface(f->c[e1],f->c[e],w,false);
  794. if(nf)
  795. {
  796. bind(nf,0,f,e);
  797. if(horizon.cf) { bind(horizon.cf,1,nf,2); } else { horizon.ff=nf;
  798. }
  799. horizon.cf=nf;
  800. ++horizon.nf;
  801. return(true);
  802. }
  803. }
  804. else
  805. {
  806. const U e2=i2m3[e];
  807. f->pass = (U1)pass;
  808. if( expand(pass,w,f->f[e1],f->e[e1],horizon)&&
  809. expand(pass,w,f->f[e2],f->e[e2],horizon))
  810. {
  811. remove(m_hull,f);
  812. append(m_stock,f);
  813. return(true);
  814. }
  815. }
  816. }
  817. return(false);
  818. }
  819. };
  820. //
  821. static void Initialize( const GodotShape3D* shape0, const Transform3D& wtrs0, real_t margin0,
  822. const GodotShape3D* shape1, const Transform3D& wtrs1, real_t margin1,
  823. sResults& results,
  824. tShape& shape)
  825. {
  826. /* Results */
  827. results.witnesses[0] = Vector3(0,0,0);
  828. results.witnesses[1] = Vector3(0,0,0);
  829. results.status = sResults::Separated;
  830. /* Shape */
  831. shape.Initialize(shape0, wtrs0, margin0, shape1, wtrs1, margin1);
  832. }
  833. //
  834. // Api
  835. //
  836. //
  837. //
  838. bool Distance( const GodotShape3D* shape0,
  839. const Transform3D& wtrs0,
  840. real_t margin0,
  841. const GodotShape3D* shape1,
  842. const Transform3D& wtrs1,
  843. real_t margin1,
  844. const Vector3& guess,
  845. sResults& results)
  846. {
  847. tShape shape;
  848. Initialize(shape0, wtrs0, margin0, shape1, wtrs1, margin1, results, shape);
  849. GJK gjk;
  850. GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,guess);
  851. if(gjk_status==GJK::eStatus::Valid)
  852. {
  853. Vector3 w0=Vector3(0,0,0);
  854. Vector3 w1=Vector3(0,0,0);
  855. for(U i=0;i<gjk.m_simplex->rank;++i)
  856. {
  857. const real_t p=gjk.m_simplex->p[i];
  858. w0+=shape.Support( gjk.m_simplex->c[i]->d,0)*p;
  859. w1+=shape.Support(-gjk.m_simplex->c[i]->d,1)*p;
  860. }
  861. results.witnesses[0] = w0;
  862. results.witnesses[1] = w1;
  863. results.normal = w0-w1;
  864. results.distance = results.normal.length();
  865. results.normal /= results.distance>GJK_MIN_DISTANCE?results.distance:1;
  866. return(true);
  867. }
  868. else
  869. {
  870. results.status = gjk_status==GJK::eStatus::Inside?
  871. sResults::Penetrating :
  872. sResults::GJK_Failed;
  873. return(false);
  874. }
  875. }
  876. //
  877. bool Penetration( const GodotShape3D* shape0,
  878. const Transform3D& wtrs0,
  879. real_t margin0,
  880. const GodotShape3D* shape1,
  881. const Transform3D& wtrs1,
  882. real_t margin1,
  883. const Vector3& guess,
  884. sResults& results
  885. )
  886. {
  887. tShape shape;
  888. Initialize(shape0, wtrs0, margin0, shape1, wtrs1, margin1, results, shape);
  889. GJK gjk;
  890. GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,-guess);
  891. switch(gjk_status)
  892. {
  893. case GJK::eStatus::Inside:
  894. {
  895. EPA epa;
  896. EPA::eStatus::_ epa_status=epa.Evaluate(gjk,-guess);
  897. if(epa_status!=EPA::eStatus::Failed)
  898. {
  899. Vector3 w0=Vector3(0,0,0);
  900. for(U i=0;i<epa.m_result.rank;++i)
  901. {
  902. w0+=shape.Support(epa.m_result.c[i]->d,0)*epa.m_result.p[i];
  903. }
  904. results.status = sResults::Penetrating;
  905. results.witnesses[0] = w0;
  906. results.witnesses[1] = w0-epa.m_normal*epa.m_depth;
  907. results.normal = -epa.m_normal;
  908. results.distance = -epa.m_depth;
  909. return(true);
  910. } else { results.status=sResults::EPA_Failed;
  911. }
  912. }
  913. break;
  914. case GJK::eStatus::Failed:
  915. results.status=sResults::GJK_Failed;
  916. break;
  917. default: {}
  918. }
  919. return(false);
  920. }
  921. /* Symbols cleanup */
  922. #undef GJK_MAX_ITERATIONS
  923. #undef GJK_ACCURARY
  924. #undef GJK_MIN_DISTANCE
  925. #undef GJK_DUPLICATED_EPS
  926. #undef GJK_SIMPLEX2_EPS
  927. #undef GJK_SIMPLEX3_EPS
  928. #undef GJK_SIMPLEX4_EPS
  929. #undef EPA_MAX_VERTICES
  930. #undef EPA_MAX_FACES
  931. #undef EPA_MAX_ITERATIONS
  932. #undef EPA_ACCURACY
  933. #undef EPA_FALLBACK
  934. #undef EPA_PLANE_EPS
  935. #undef EPA_INSIDE_EPS
  936. } // end of namespace
  937. /* clang-format on */
  938. bool gjk_epa_calculate_distance(const GodotShape3D *p_shape_A, const Transform3D &p_transform_A, const GodotShape3D *p_shape_B, const Transform3D &p_transform_B, Vector3 &r_result_A, Vector3 &r_result_B) {
  939. GjkEpa2::sResults res;
  940. if (GjkEpa2::Distance(p_shape_A, p_transform_A, 0.0, p_shape_B, p_transform_B, 0.0, p_transform_B.origin - p_transform_A.origin, res)) {
  941. r_result_A = res.witnesses[0];
  942. r_result_B = res.witnesses[1];
  943. return true;
  944. }
  945. return false;
  946. }
  947. bool gjk_epa_calculate_penetration(const GodotShape3D *p_shape_A, const Transform3D &p_transform_A, const GodotShape3D *p_shape_B, const Transform3D &p_transform_B, GodotCollisionSolver3D::CallbackResult p_result_callback, void *p_userdata, bool p_swap, real_t p_margin_A, real_t p_margin_B) {
  948. GjkEpa2::sResults res;
  949. if (GjkEpa2::Penetration(p_shape_A, p_transform_A, p_margin_A, p_shape_B, p_transform_B, p_margin_B, p_transform_B.origin - p_transform_A.origin, res)) {
  950. if (p_result_callback) {
  951. if (p_swap) {
  952. Vector3 normal = (res.witnesses[1] - res.witnesses[0]).normalized();
  953. p_result_callback(res.witnesses[1], 0, res.witnesses[0], 0, normal, p_userdata);
  954. } else {
  955. Vector3 normal = (res.witnesses[0] - res.witnesses[1]).normalized();
  956. p_result_callback(res.witnesses[0], 0, res.witnesses[1], 0, normal, p_userdata);
  957. }
  958. }
  959. return true;
  960. }
  961. return false;
  962. }