geometry.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  1. /*************************************************************************/
  2. /* geometry.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "geometry.h"
  31. #include "core/print_string.h"
  32. #include "thirdparty/misc/clipper.hpp"
  33. #include "thirdparty/misc/triangulator.h"
  34. #define STB_RECT_PACK_IMPLEMENTATION
  35. #include "thirdparty/stb_rect_pack/stb_rect_pack.h"
  36. #define SCALE_FACTOR 100000.0 // Based on CMP_EPSILON.
  37. // This implementation is very inefficient, commenting unless bugs happen. See the other one.
  38. /*
  39. bool Geometry::is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  40. Vector<int> indices = Geometry::triangulate_polygon(p_polygon);
  41. for (int j = 0; j + 3 <= indices.size(); j += 3) {
  42. int i1 = indices[j], i2 = indices[j + 1], i3 = indices[j + 2];
  43. if (Geometry::is_point_in_triangle(p_point, p_polygon[i1], p_polygon[i2], p_polygon[i3]))
  44. return true;
  45. }
  46. return false;
  47. }
  48. */
  49. void Geometry::MeshData::optimize_vertices() {
  50. Map<int, int> vtx_remap;
  51. for (int i = 0; i < faces.size(); i++) {
  52. for (int j = 0; j < faces[i].indices.size(); j++) {
  53. int idx = faces[i].indices[j];
  54. if (!vtx_remap.has(idx)) {
  55. int ni = vtx_remap.size();
  56. vtx_remap[idx] = ni;
  57. }
  58. faces.write[i].indices.write[j] = vtx_remap[idx];
  59. }
  60. }
  61. for (int i = 0; i < edges.size(); i++) {
  62. int a = edges[i].a;
  63. int b = edges[i].b;
  64. if (!vtx_remap.has(a)) {
  65. int ni = vtx_remap.size();
  66. vtx_remap[a] = ni;
  67. }
  68. if (!vtx_remap.has(b)) {
  69. int ni = vtx_remap.size();
  70. vtx_remap[b] = ni;
  71. }
  72. edges.write[i].a = vtx_remap[a];
  73. edges.write[i].b = vtx_remap[b];
  74. }
  75. Vector<Vector3> new_vertices;
  76. new_vertices.resize(vtx_remap.size());
  77. for (int i = 0; i < vertices.size(); i++) {
  78. if (vtx_remap.has(i)) {
  79. new_vertices.write[vtx_remap[i]] = vertices[i];
  80. }
  81. }
  82. vertices = new_vertices;
  83. }
  84. struct _FaceClassify {
  85. struct _Link {
  86. int face;
  87. int edge;
  88. void clear() {
  89. face = -1;
  90. edge = -1;
  91. }
  92. _Link() {
  93. face = -1;
  94. edge = -1;
  95. }
  96. };
  97. bool valid;
  98. int group;
  99. _Link links[3];
  100. Face3 face;
  101. _FaceClassify() {
  102. group = -1;
  103. valid = false;
  104. };
  105. };
  106. static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
  107. // Connect faces, error will occur if an edge is shared between more than 2 faces.
  108. // Clear connections.
  109. bool error = false;
  110. for (int i = 0; i < len; i++) {
  111. for (int j = 0; j < 3; j++) {
  112. p_faces[i].links[j].clear();
  113. }
  114. }
  115. for (int i = 0; i < len; i++) {
  116. if (p_faces[i].group != p_group) {
  117. continue;
  118. }
  119. for (int j = i + 1; j < len; j++) {
  120. if (p_faces[j].group != p_group) {
  121. continue;
  122. }
  123. for (int k = 0; k < 3; k++) {
  124. Vector3 vi1 = p_faces[i].face.vertex[k];
  125. Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
  126. for (int l = 0; l < 3; l++) {
  127. Vector3 vj2 = p_faces[j].face.vertex[l];
  128. Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
  129. if (vi1.distance_to(vj1) < 0.00001 &&
  130. vi2.distance_to(vj2) < 0.00001) {
  131. if (p_faces[i].links[k].face != -1) {
  132. ERR_PRINT("already linked\n");
  133. error = true;
  134. break;
  135. }
  136. if (p_faces[j].links[l].face != -1) {
  137. ERR_PRINT("already linked\n");
  138. error = true;
  139. break;
  140. }
  141. p_faces[i].links[k].face = j;
  142. p_faces[i].links[k].edge = l;
  143. p_faces[j].links[l].face = i;
  144. p_faces[j].links[l].edge = k;
  145. }
  146. }
  147. if (error) {
  148. break;
  149. }
  150. }
  151. if (error) {
  152. break;
  153. }
  154. }
  155. if (error) {
  156. break;
  157. }
  158. }
  159. for (int i = 0; i < len; i++) {
  160. p_faces[i].valid = true;
  161. for (int j = 0; j < 3; j++) {
  162. if (p_faces[i].links[j].face == -1) {
  163. p_faces[i].valid = false;
  164. }
  165. }
  166. }
  167. return error;
  168. }
  169. static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
  170. if (p_faces[p_index].group >= 0) {
  171. return false;
  172. }
  173. p_faces[p_index].group = p_group;
  174. for (int i = 0; i < 3; i++) {
  175. ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
  176. _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
  177. }
  178. return true;
  179. }
  180. PoolVector<PoolVector<Face3>> Geometry::separate_objects(PoolVector<Face3> p_array) {
  181. PoolVector<PoolVector<Face3>> objects;
  182. int len = p_array.size();
  183. PoolVector<Face3>::Read r = p_array.read();
  184. const Face3 *arrayptr = r.ptr();
  185. PoolVector<_FaceClassify> fc;
  186. fc.resize(len);
  187. PoolVector<_FaceClassify>::Write fcw = fc.write();
  188. _FaceClassify *_fcptr = fcw.ptr();
  189. for (int i = 0; i < len; i++) {
  190. _fcptr[i].face = arrayptr[i];
  191. }
  192. bool error = _connect_faces(_fcptr, len, -1);
  193. ERR_FAIL_COND_V_MSG(error, PoolVector<PoolVector<Face3>>(), "Invalid geometry.");
  194. // Group connected faces in separate objects.
  195. int group = 0;
  196. for (int i = 0; i < len; i++) {
  197. if (!_fcptr[i].valid) {
  198. continue;
  199. }
  200. if (_group_face(_fcptr, len, i, group)) {
  201. group++;
  202. }
  203. }
  204. // Group connected faces in separate objects.
  205. for (int i = 0; i < len; i++) {
  206. _fcptr[i].face = arrayptr[i];
  207. }
  208. if (group >= 0) {
  209. objects.resize(group);
  210. PoolVector<PoolVector<Face3>>::Write obw = objects.write();
  211. PoolVector<Face3> *group_faces = obw.ptr();
  212. for (int i = 0; i < len; i++) {
  213. if (!_fcptr[i].valid) {
  214. continue;
  215. }
  216. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  217. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  218. }
  219. }
  220. }
  221. return objects;
  222. }
  223. /*** GEOMETRY WRAPPER ***/
  224. enum _CellFlags {
  225. _CELL_SOLID = 1,
  226. _CELL_EXTERIOR = 2,
  227. _CELL_STEP_MASK = 0x1C,
  228. _CELL_STEP_NONE = 0 << 2,
  229. _CELL_STEP_Y_POS = 1 << 2,
  230. _CELL_STEP_Y_NEG = 2 << 2,
  231. _CELL_STEP_X_POS = 3 << 2,
  232. _CELL_STEP_X_NEG = 4 << 2,
  233. _CELL_STEP_Z_POS = 5 << 2,
  234. _CELL_STEP_Z_NEG = 6 << 2,
  235. _CELL_STEP_DONE = 7 << 2,
  236. _CELL_PREV_MASK = 0xE0,
  237. _CELL_PREV_NONE = 0 << 5,
  238. _CELL_PREV_Y_POS = 1 << 5,
  239. _CELL_PREV_Y_NEG = 2 << 5,
  240. _CELL_PREV_X_POS = 3 << 5,
  241. _CELL_PREV_X_NEG = 4 << 5,
  242. _CELL_PREV_Z_POS = 5 << 5,
  243. _CELL_PREV_Z_NEG = 6 << 5,
  244. _CELL_PREV_FIRST = 7 << 5,
  245. };
  246. static inline void _plot_face(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, const Vector3 &voxelsize, const Face3 &p_face) {
  247. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  248. aabb.position = aabb.position * voxelsize;
  249. aabb.size = aabb.size * voxelsize;
  250. if (!p_face.intersects_aabb(aabb)) {
  251. return;
  252. }
  253. if (len_x == 1 && len_y == 1 && len_z == 1) {
  254. p_cell_status[x][y][z] = _CELL_SOLID;
  255. return;
  256. }
  257. int div_x = len_x > 1 ? 2 : 1;
  258. int div_y = len_y > 1 ? 2 : 1;
  259. int div_z = len_z > 1 ? 2 : 1;
  260. #define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  261. if (m_div == 1) { \
  262. m_new_v = m_v; \
  263. m_new_len_v = 1; \
  264. } else if (m_i == 0) { \
  265. m_new_v = m_v; \
  266. m_new_len_v = m_len_v / 2; \
  267. } else { \
  268. m_new_v = m_v + m_len_v / 2; \
  269. m_new_len_v = m_len_v - m_len_v / 2; \
  270. }
  271. int new_x;
  272. int new_len_x;
  273. int new_y;
  274. int new_len_y;
  275. int new_z;
  276. int new_len_z;
  277. for (int i = 0; i < div_x; i++) {
  278. _SPLIT(i, div_x, x, len_x, new_x, new_len_x);
  279. for (int j = 0; j < div_y; j++) {
  280. _SPLIT(j, div_y, y, len_y, new_y, new_len_y);
  281. for (int k = 0; k < div_z; k++) {
  282. _SPLIT(k, div_z, z, len_z, new_z, new_len_z);
  283. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  284. }
  285. }
  286. }
  287. }
  288. static inline void _mark_outside(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z) {
  289. if (p_cell_status[x][y][z] & 3) {
  290. return; // Nothing to do, already used and/or visited.
  291. }
  292. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  293. while (true) {
  294. uint8_t &c = p_cell_status[x][y][z];
  295. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  296. // Haven't been in here, mark as outside.
  297. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  298. }
  299. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  300. // If not done, increase step.
  301. c += 1 << 2;
  302. }
  303. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  304. // Go back.
  305. switch (c & _CELL_PREV_MASK) {
  306. case _CELL_PREV_FIRST: {
  307. return;
  308. } break;
  309. case _CELL_PREV_Y_POS: {
  310. y++;
  311. ERR_FAIL_COND(y >= len_y);
  312. } break;
  313. case _CELL_PREV_Y_NEG: {
  314. y--;
  315. ERR_FAIL_COND(y < 0);
  316. } break;
  317. case _CELL_PREV_X_POS: {
  318. x++;
  319. ERR_FAIL_COND(x >= len_x);
  320. } break;
  321. case _CELL_PREV_X_NEG: {
  322. x--;
  323. ERR_FAIL_COND(x < 0);
  324. } break;
  325. case _CELL_PREV_Z_POS: {
  326. z++;
  327. ERR_FAIL_COND(z >= len_z);
  328. } break;
  329. case _CELL_PREV_Z_NEG: {
  330. z--;
  331. ERR_FAIL_COND(z < 0);
  332. } break;
  333. default: {
  334. ERR_FAIL();
  335. }
  336. }
  337. continue;
  338. }
  339. int next_x = x, next_y = y, next_z = z;
  340. uint8_t prev = 0;
  341. switch (c & _CELL_STEP_MASK) {
  342. case _CELL_STEP_Y_POS: {
  343. next_y++;
  344. prev = _CELL_PREV_Y_NEG;
  345. } break;
  346. case _CELL_STEP_Y_NEG: {
  347. next_y--;
  348. prev = _CELL_PREV_Y_POS;
  349. } break;
  350. case _CELL_STEP_X_POS: {
  351. next_x++;
  352. prev = _CELL_PREV_X_NEG;
  353. } break;
  354. case _CELL_STEP_X_NEG: {
  355. next_x--;
  356. prev = _CELL_PREV_X_POS;
  357. } break;
  358. case _CELL_STEP_Z_POS: {
  359. next_z++;
  360. prev = _CELL_PREV_Z_NEG;
  361. } break;
  362. case _CELL_STEP_Z_NEG: {
  363. next_z--;
  364. prev = _CELL_PREV_Z_POS;
  365. } break;
  366. default:
  367. ERR_FAIL();
  368. }
  369. if (next_x < 0 || next_x >= len_x) {
  370. continue;
  371. }
  372. if (next_y < 0 || next_y >= len_y) {
  373. continue;
  374. }
  375. if (next_z < 0 || next_z >= len_z) {
  376. continue;
  377. }
  378. if (p_cell_status[next_x][next_y][next_z] & 3) {
  379. continue;
  380. }
  381. x = next_x;
  382. y = next_y;
  383. z = next_z;
  384. p_cell_status[x][y][z] |= prev;
  385. }
  386. }
  387. static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, PoolVector<Face3> &p_faces) {
  388. ERR_FAIL_INDEX(x, len_x);
  389. ERR_FAIL_INDEX(y, len_y);
  390. ERR_FAIL_INDEX(z, len_z);
  391. if (p_cell_status[x][y][z] & _CELL_EXTERIOR) {
  392. return;
  393. }
  394. #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
  395. static const uint8_t indices[6][4] = {
  396. { 7, 6, 4, 5 },
  397. { 7, 3, 2, 6 },
  398. { 7, 5, 1, 3 },
  399. { 0, 2, 3, 1 },
  400. { 0, 1, 5, 4 },
  401. { 0, 4, 6, 2 },
  402. };
  403. for (int i = 0; i < 6; i++) {
  404. Vector3 face_points[4];
  405. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  406. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  407. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  408. bool plot = false;
  409. if (disp_x < 0 || disp_x >= len_x) {
  410. plot = true;
  411. }
  412. if (disp_y < 0 || disp_y >= len_y) {
  413. plot = true;
  414. }
  415. if (disp_z < 0 || disp_z >= len_z) {
  416. plot = true;
  417. }
  418. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR)) {
  419. plot = true;
  420. }
  421. if (!plot) {
  422. continue;
  423. }
  424. for (int j = 0; j < 4; j++) {
  425. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  426. }
  427. p_faces.push_back(
  428. Face3(
  429. face_points[0],
  430. face_points[1],
  431. face_points[2]));
  432. p_faces.push_back(
  433. Face3(
  434. face_points[2],
  435. face_points[3],
  436. face_points[0]));
  437. }
  438. }
  439. PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_error) {
  440. #define _MIN_SIZE 1.0
  441. #define _MAX_LENGTH 20
  442. int face_count = p_array.size();
  443. PoolVector<Face3>::Read facesr = p_array.read();
  444. const Face3 *faces = facesr.ptr();
  445. AABB global_aabb;
  446. for (int i = 0; i < face_count; i++) {
  447. if (i == 0) {
  448. global_aabb = faces[i].get_aabb();
  449. } else {
  450. global_aabb.merge_with(faces[i].get_aabb());
  451. }
  452. }
  453. global_aabb.grow_by(0.01); // Avoid numerical error.
  454. // Determine amount of cells in grid axis.
  455. int div_x, div_y, div_z;
  456. if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH) {
  457. div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
  458. } else {
  459. div_x = _MAX_LENGTH;
  460. }
  461. if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH) {
  462. div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
  463. } else {
  464. div_y = _MAX_LENGTH;
  465. }
  466. if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH) {
  467. div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
  468. } else {
  469. div_z = _MAX_LENGTH;
  470. }
  471. Vector3 voxelsize = global_aabb.size;
  472. voxelsize.x /= div_x;
  473. voxelsize.y /= div_y;
  474. voxelsize.z /= div_z;
  475. // Create and initialize cells to zero.
  476. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
  477. for (int i = 0; i < div_x; i++) {
  478. cell_status[i] = memnew_arr(uint8_t *, div_y);
  479. for (int j = 0; j < div_y; j++) {
  480. cell_status[i][j] = memnew_arr(uint8_t, div_z);
  481. for (int k = 0; k < div_z; k++) {
  482. cell_status[i][j][k] = 0;
  483. }
  484. }
  485. }
  486. // Plot faces into cells.
  487. for (int i = 0; i < face_count; i++) {
  488. Face3 f = faces[i];
  489. for (int j = 0; j < 3; j++) {
  490. f.vertex[j] -= global_aabb.position;
  491. }
  492. _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
  493. }
  494. // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
  495. for (int i = 0; i < div_x; i++) {
  496. for (int j = 0; j < div_y; j++) {
  497. _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
  498. _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
  499. }
  500. }
  501. for (int i = 0; i < div_z; i++) {
  502. for (int j = 0; j < div_y; j++) {
  503. _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
  504. _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
  505. }
  506. }
  507. for (int i = 0; i < div_x; i++) {
  508. for (int j = 0; j < div_z; j++) {
  509. _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
  510. _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
  511. }
  512. }
  513. // Build faces for the inside-outside cell divisors.
  514. PoolVector<Face3> wrapped_faces;
  515. for (int i = 0; i < div_x; i++) {
  516. for (int j = 0; j < div_y; j++) {
  517. for (int k = 0; k < div_z; k++) {
  518. _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
  519. }
  520. }
  521. }
  522. // Transform face vertices to global coords.
  523. int wrapped_faces_count = wrapped_faces.size();
  524. PoolVector<Face3>::Write wrapped_facesw = wrapped_faces.write();
  525. Face3 *wrapped_faces_ptr = wrapped_facesw.ptr();
  526. for (int i = 0; i < wrapped_faces_count; i++) {
  527. for (int j = 0; j < 3; j++) {
  528. Vector3 &v = wrapped_faces_ptr[i].vertex[j];
  529. v = v * voxelsize;
  530. v += global_aabb.position;
  531. }
  532. }
  533. // clean up grid
  534. for (int i = 0; i < div_x; i++) {
  535. for (int j = 0; j < div_y; j++) {
  536. memdelete_arr(cell_status[i][j]);
  537. }
  538. memdelete_arr(cell_status[i]);
  539. }
  540. memdelete_arr(cell_status);
  541. if (p_error) {
  542. *p_error = voxelsize.length();
  543. }
  544. return wrapped_faces;
  545. }
  546. Vector<Vector<Vector2>> Geometry::decompose_polygon_in_convex(Vector<Point2> polygon) {
  547. Vector<Vector<Vector2>> decomp;
  548. List<TriangulatorPoly> in_poly, out_poly;
  549. TriangulatorPoly inp;
  550. inp.Init(polygon.size());
  551. for (int i = 0; i < polygon.size(); i++) {
  552. inp.GetPoint(i) = polygon[i];
  553. }
  554. inp.SetOrientation(TRIANGULATOR_CCW);
  555. in_poly.push_back(inp);
  556. TriangulatorPartition tpart;
  557. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  558. ERR_PRINT("Convex decomposing failed!");
  559. return decomp;
  560. }
  561. decomp.resize(out_poly.size());
  562. int idx = 0;
  563. for (List<TriangulatorPoly>::Element *I = out_poly.front(); I; I = I->next()) {
  564. TriangulatorPoly &tp = I->get();
  565. decomp.write[idx].resize(tp.GetNumPoints());
  566. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  567. decomp.write[idx].write[i] = tp.GetPoint(i);
  568. }
  569. idx++;
  570. }
  571. return decomp;
  572. }
  573. Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes) {
  574. MeshData mesh;
  575. #define SUBPLANE_SIZE 1024.0
  576. real_t subplane_size = 1024.0; // Should compute this from the actual plane.
  577. for (int i = 0; i < p_planes.size(); i++) {
  578. Plane p = p_planes[i];
  579. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  580. if (ABS(p.normal.dot(ref)) > 0.95) {
  581. ref = Vector3(0.0, 0.0, 1.0); // Change axis.
  582. }
  583. Vector3 right = p.normal.cross(ref).normalized();
  584. Vector3 up = p.normal.cross(right).normalized();
  585. Vector<Vector3> vertices;
  586. Vector3 center = p.get_any_point();
  587. // make a quad clockwise
  588. vertices.push_back(center - up * subplane_size + right * subplane_size);
  589. vertices.push_back(center - up * subplane_size - right * subplane_size);
  590. vertices.push_back(center + up * subplane_size - right * subplane_size);
  591. vertices.push_back(center + up * subplane_size + right * subplane_size);
  592. for (int j = 0; j < p_planes.size(); j++) {
  593. if (j == i) {
  594. continue;
  595. }
  596. Vector<Vector3> new_vertices;
  597. Plane clip = p_planes[j];
  598. if (clip.normal.dot(p.normal) > 0.95) {
  599. continue;
  600. }
  601. if (vertices.size() < 3) {
  602. break;
  603. }
  604. for (int k = 0; k < vertices.size(); k++) {
  605. int k_n = (k + 1) % vertices.size();
  606. Vector3 edge0_A = vertices[k];
  607. Vector3 edge1_A = vertices[k_n];
  608. real_t dist0 = clip.distance_to(edge0_A);
  609. real_t dist1 = clip.distance_to(edge1_A);
  610. if (dist0 <= 0) { // Behind plane.
  611. new_vertices.push_back(vertices[k]);
  612. }
  613. // Check for different sides and non coplanar.
  614. if ((dist0 * dist1) < 0) {
  615. // Calculate intersection.
  616. Vector3 rel = edge1_A - edge0_A;
  617. real_t den = clip.normal.dot(rel);
  618. if (Math::is_zero_approx(den)) {
  619. continue; // Point too short.
  620. }
  621. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
  622. Vector3 inters = edge0_A + rel * dist;
  623. new_vertices.push_back(inters);
  624. }
  625. }
  626. vertices = new_vertices;
  627. }
  628. if (vertices.size() < 3) {
  629. continue;
  630. }
  631. // Result is a clockwise face.
  632. MeshData::Face face;
  633. // Add face indices.
  634. for (int j = 0; j < vertices.size(); j++) {
  635. int idx = -1;
  636. for (int k = 0; k < mesh.vertices.size(); k++) {
  637. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) {
  638. idx = k;
  639. break;
  640. }
  641. }
  642. if (idx == -1) {
  643. idx = mesh.vertices.size();
  644. mesh.vertices.push_back(vertices[j]);
  645. }
  646. face.indices.push_back(idx);
  647. }
  648. face.plane = p;
  649. mesh.faces.push_back(face);
  650. // Add edge.
  651. for (int j = 0; j < face.indices.size(); j++) {
  652. int a = face.indices[j];
  653. int b = face.indices[(j + 1) % face.indices.size()];
  654. bool found = false;
  655. for (int k = 0; k < mesh.edges.size(); k++) {
  656. if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
  657. found = true;
  658. break;
  659. }
  660. if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
  661. found = true;
  662. break;
  663. }
  664. }
  665. if (found) {
  666. continue;
  667. }
  668. MeshData::Edge edge;
  669. edge.a = a;
  670. edge.b = b;
  671. mesh.edges.push_back(edge);
  672. }
  673. }
  674. return mesh;
  675. }
  676. PoolVector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {
  677. PoolVector<Plane> planes;
  678. planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
  679. planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
  680. planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
  681. planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
  682. planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
  683. planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
  684. return planes;
  685. }
  686. PoolVector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  687. ERR_FAIL_INDEX_V(p_axis, 3, PoolVector<Plane>());
  688. PoolVector<Plane> planes;
  689. for (int i = 0; i < p_sides; i++) {
  690. Vector3 normal;
  691. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  692. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  693. planes.push_back(Plane(normal, p_radius));
  694. }
  695. Vector3 axis;
  696. axis[p_axis] = 1.0;
  697. planes.push_back(Plane(axis, p_height * 0.5));
  698. planes.push_back(Plane(-axis, p_height * 0.5));
  699. return planes;
  700. }
  701. PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  702. ERR_FAIL_INDEX_V(p_axis, 3, PoolVector<Plane>());
  703. PoolVector<Plane> planes;
  704. Vector3 axis;
  705. axis[p_axis] = 1.0;
  706. Vector3 axis_neg;
  707. axis_neg[(p_axis + 1) % 3] = 1.0;
  708. axis_neg[(p_axis + 2) % 3] = 1.0;
  709. axis_neg[p_axis] = -1.0;
  710. for (int i = 0; i < p_lons; i++) {
  711. Vector3 normal;
  712. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons);
  713. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons);
  714. planes.push_back(Plane(normal, p_radius));
  715. for (int j = 1; j <= p_lats; j++) {
  716. // FIXME: This is stupid.
  717. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  718. Vector3 pos = angle * p_radius;
  719. planes.push_back(Plane(pos, angle));
  720. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  721. }
  722. }
  723. return planes;
  724. }
  725. PoolVector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  726. ERR_FAIL_INDEX_V(p_axis, 3, PoolVector<Plane>());
  727. PoolVector<Plane> planes;
  728. Vector3 axis;
  729. axis[p_axis] = 1.0;
  730. Vector3 axis_neg;
  731. axis_neg[(p_axis + 1) % 3] = 1.0;
  732. axis_neg[(p_axis + 2) % 3] = 1.0;
  733. axis_neg[p_axis] = -1.0;
  734. for (int i = 0; i < p_sides; i++) {
  735. Vector3 normal;
  736. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  737. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  738. planes.push_back(Plane(normal, p_radius));
  739. for (int j = 1; j <= p_lats; j++) {
  740. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  741. Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
  742. planes.push_back(Plane(pos, angle));
  743. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  744. }
  745. }
  746. return planes;
  747. }
  748. struct _AtlasWorkRect {
  749. Size2i s;
  750. Point2i p;
  751. int idx;
  752. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
  753. };
  754. struct _AtlasWorkRectResult {
  755. Vector<_AtlasWorkRect> result;
  756. int max_w;
  757. int max_h;
  758. };
  759. void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  760. // Super simple, almost brute force scanline stacking fitter.
  761. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  762. // resulting atlas is somehow square. This is necessary because video cards have limits.
  763. // On texture size (usually 2048 or 4096), so the more square a texture, the more chances.
  764. // It will work in every hardware.
  765. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  766. // 256x8192 atlas (won't work anywhere).
  767. ERR_FAIL_COND(p_rects.size() == 0);
  768. for (int i = 0; i < p_rects.size(); i++) {
  769. ERR_FAIL_COND(p_rects[i].width <= 0);
  770. ERR_FAIL_COND(p_rects[i].height <= 0);
  771. }
  772. Vector<_AtlasWorkRect> wrects;
  773. wrects.resize(p_rects.size());
  774. for (int i = 0; i < p_rects.size(); i++) {
  775. wrects.write[i].s = p_rects[i];
  776. wrects.write[i].idx = i;
  777. }
  778. wrects.sort();
  779. int widest = wrects[0].s.width;
  780. Vector<_AtlasWorkRectResult> results;
  781. for (int i = 0; i <= 12; i++) {
  782. int w = 1 << i;
  783. int max_h = 0;
  784. int max_w = 0;
  785. if (w < widest) {
  786. continue;
  787. }
  788. Vector<int> hmax;
  789. hmax.resize(w);
  790. for (int j = 0; j < w; j++) {
  791. hmax.write[j] = 0;
  792. }
  793. // Place them.
  794. int ofs = 0;
  795. int limit_h = 0;
  796. for (int j = 0; j < wrects.size(); j++) {
  797. if (ofs + wrects[j].s.width > w) {
  798. ofs = 0;
  799. }
  800. int from_y = 0;
  801. for (int k = 0; k < wrects[j].s.width; k++) {
  802. if (hmax[ofs + k] > from_y) {
  803. from_y = hmax[ofs + k];
  804. }
  805. }
  806. wrects.write[j].p.x = ofs;
  807. wrects.write[j].p.y = from_y;
  808. int end_h = from_y + wrects[j].s.height;
  809. int end_w = ofs + wrects[j].s.width;
  810. if (ofs == 0) {
  811. limit_h = end_h;
  812. }
  813. for (int k = 0; k < wrects[j].s.width; k++) {
  814. hmax.write[ofs + k] = end_h;
  815. }
  816. if (end_h > max_h) {
  817. max_h = end_h;
  818. }
  819. if (end_w > max_w) {
  820. max_w = end_w;
  821. }
  822. if (ofs == 0 || end_h > limit_h) { // While h limit not reached, keep stacking.
  823. ofs += wrects[j].s.width;
  824. }
  825. }
  826. _AtlasWorkRectResult result;
  827. result.result = wrects;
  828. result.max_h = max_h;
  829. result.max_w = max_w;
  830. results.push_back(result);
  831. }
  832. // Find the result with the best aspect ratio.
  833. int best = -1;
  834. real_t best_aspect = 1e20;
  835. for (int i = 0; i < results.size(); i++) {
  836. real_t h = next_power_of_2(results[i].max_h);
  837. real_t w = next_power_of_2(results[i].max_w);
  838. real_t aspect = h > w ? h / w : w / h;
  839. if (aspect < best_aspect) {
  840. best = i;
  841. best_aspect = aspect;
  842. }
  843. }
  844. r_result.resize(p_rects.size());
  845. for (int i = 0; i < p_rects.size(); i++) {
  846. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  847. }
  848. r_size = Size2(results[best].max_w, results[best].max_h);
  849. }
  850. Vector<Vector<Point2>> Geometry::_polypaths_do_operation(PolyBooleanOperation p_op, const Vector<Point2> &p_polypath_a, const Vector<Point2> &p_polypath_b, bool is_a_open) {
  851. using namespace ClipperLib;
  852. ClipType op = ctUnion;
  853. switch (p_op) {
  854. case OPERATION_UNION:
  855. op = ctUnion;
  856. break;
  857. case OPERATION_DIFFERENCE:
  858. op = ctDifference;
  859. break;
  860. case OPERATION_INTERSECTION:
  861. op = ctIntersection;
  862. break;
  863. case OPERATION_XOR:
  864. op = ctXor;
  865. break;
  866. }
  867. Path path_a, path_b;
  868. // Need to scale points (Clipper's requirement for robust computation).
  869. for (int i = 0; i != p_polypath_a.size(); ++i) {
  870. path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR);
  871. }
  872. for (int i = 0; i != p_polypath_b.size(); ++i) {
  873. path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR);
  874. }
  875. Clipper clp;
  876. clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0.
  877. clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip.
  878. Paths paths;
  879. if (is_a_open) {
  880. PolyTree tree; // Needed to populate polylines.
  881. clp.Execute(op, tree);
  882. OpenPathsFromPolyTree(tree, paths);
  883. } else {
  884. clp.Execute(op, paths); // Works on closed polygons only.
  885. }
  886. // Have to scale points down now.
  887. Vector<Vector<Point2>> polypaths;
  888. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  889. Vector<Vector2> polypath;
  890. const Path &scaled_path = paths[i];
  891. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  892. polypath.push_back(Point2(
  893. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  894. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  895. }
  896. polypaths.push_back(polypath);
  897. }
  898. return polypaths;
  899. }
  900. Vector<Vector<Point2>> Geometry::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  901. using namespace ClipperLib;
  902. JoinType jt = jtSquare;
  903. switch (p_join_type) {
  904. case JOIN_SQUARE:
  905. jt = jtSquare;
  906. break;
  907. case JOIN_ROUND:
  908. jt = jtRound;
  909. break;
  910. case JOIN_MITER:
  911. jt = jtMiter;
  912. break;
  913. }
  914. EndType et = etClosedPolygon;
  915. switch (p_end_type) {
  916. case END_POLYGON:
  917. et = etClosedPolygon;
  918. break;
  919. case END_JOINED:
  920. et = etClosedLine;
  921. break;
  922. case END_BUTT:
  923. et = etOpenButt;
  924. break;
  925. case END_SQUARE:
  926. et = etOpenSquare;
  927. break;
  928. case END_ROUND:
  929. et = etOpenRound;
  930. break;
  931. }
  932. ClipperOffset co(2.0, 0.25 * SCALE_FACTOR); // Defaults from ClipperOffset.
  933. Path path;
  934. // Need to scale points (Clipper's requirement for robust computation).
  935. for (int i = 0; i != p_polypath.size(); ++i) {
  936. path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR);
  937. }
  938. co.AddPath(path, jt, et);
  939. Paths paths;
  940. co.Execute(paths, p_delta * SCALE_FACTOR); // Inflate/deflate.
  941. // Have to scale points down now.
  942. Vector<Vector<Point2>> polypaths;
  943. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  944. Vector<Vector2> polypath;
  945. const Path &scaled_path = paths[i];
  946. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  947. polypath.push_back(Point2(
  948. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  949. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  950. }
  951. polypaths.push_back(polypath);
  952. }
  953. return polypaths;
  954. }
  955. real_t Geometry::calculate_convex_hull_volume(const Geometry::MeshData &p_md) {
  956. if (!p_md.vertices.size()) {
  957. return 0.0;
  958. }
  959. // find center
  960. Vector3 center;
  961. for (int n = 0; n < p_md.vertices.size(); n++) {
  962. center += p_md.vertices[n];
  963. }
  964. center /= p_md.vertices.size();
  965. Face3 fa;
  966. real_t volume = 0.0;
  967. // volume of each cone is 1/3 * height * area of face
  968. for (int f = 0; f < p_md.faces.size(); f++) {
  969. const Geometry::MeshData::Face &face = p_md.faces[f];
  970. real_t height = 0.0;
  971. real_t face_area = 0.0;
  972. for (int c = 0; c < face.indices.size() - 2; c++) {
  973. fa.vertex[0] = p_md.vertices[face.indices[0]];
  974. fa.vertex[1] = p_md.vertices[face.indices[c + 1]];
  975. fa.vertex[2] = p_md.vertices[face.indices[c + 2]];
  976. if (!c) {
  977. // calculate height
  978. Plane plane(fa.vertex[0], fa.vertex[1], fa.vertex[2]);
  979. height = -plane.distance_to(center);
  980. }
  981. face_area += Math::sqrt(fa.get_twice_area_squared());
  982. }
  983. volume += face_area * height;
  984. }
  985. volume *= (1.0 / 3.0) * 0.5;
  986. return volume;
  987. }
  988. // note this function is slow, because it builds meshes etc. Not ideal to use in realtime.
  989. // Planes must face OUTWARD from the center of the convex hull, by convention.
  990. bool Geometry::convex_hull_intersects_convex_hull(const Plane *p_planes_a, int p_plane_count_a, const Plane *p_planes_b, int p_plane_count_b) {
  991. if (!p_plane_count_a || !p_plane_count_b) {
  992. return false;
  993. }
  994. // OR alternative approach, we can call compute_convex_mesh_points()
  995. // with both sets of planes, to get an intersection. Not sure which method is
  996. // faster... this may be faster with more complex hulls.
  997. // the usual silliness to get from one vector format to another...
  998. PoolVector<Plane> planes_a;
  999. PoolVector<Plane> planes_b;
  1000. {
  1001. planes_a.resize(p_plane_count_a);
  1002. PoolVector<Plane>::Write w = planes_a.write();
  1003. memcpy(w.ptr(), p_planes_a, p_plane_count_a * sizeof(Plane));
  1004. }
  1005. {
  1006. planes_b.resize(p_plane_count_b);
  1007. PoolVector<Plane>::Write w = planes_b.write();
  1008. memcpy(w.ptr(), p_planes_b, p_plane_count_b * sizeof(Plane));
  1009. }
  1010. Geometry::MeshData md_A = build_convex_mesh(planes_a);
  1011. Geometry::MeshData md_B = build_convex_mesh(planes_b);
  1012. // hull can't be built
  1013. if (!md_A.vertices.size() || !md_B.vertices.size()) {
  1014. return false;
  1015. }
  1016. // first check the points against the planes
  1017. for (int p = 0; p < p_plane_count_a; p++) {
  1018. const Plane &plane = p_planes_a[p];
  1019. for (int n = 0; n < md_B.vertices.size(); n++) {
  1020. if (!plane.is_point_over(md_B.vertices[n])) {
  1021. return true;
  1022. }
  1023. }
  1024. }
  1025. for (int p = 0; p < p_plane_count_b; p++) {
  1026. const Plane &plane = p_planes_b[p];
  1027. for (int n = 0; n < md_A.vertices.size(); n++) {
  1028. if (!plane.is_point_over(md_A.vertices[n])) {
  1029. return true;
  1030. }
  1031. }
  1032. }
  1033. // now check edges
  1034. for (int n = 0; n < md_A.edges.size(); n++) {
  1035. const Vector3 &pt_a = md_A.vertices[md_A.edges[n].a];
  1036. const Vector3 &pt_b = md_A.vertices[md_A.edges[n].b];
  1037. if (segment_intersects_convex(pt_a, pt_b, p_planes_b, p_plane_count_b, nullptr, nullptr)) {
  1038. return true;
  1039. }
  1040. }
  1041. for (int n = 0; n < md_B.edges.size(); n++) {
  1042. const Vector3 &pt_a = md_B.vertices[md_B.edges[n].a];
  1043. const Vector3 &pt_b = md_B.vertices[md_B.edges[n].b];
  1044. if (segment_intersects_convex(pt_a, pt_b, p_planes_a, p_plane_count_a, nullptr, nullptr)) {
  1045. return true;
  1046. }
  1047. }
  1048. return false;
  1049. }
  1050. Vector<Vector3> Geometry::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count, real_t p_epsilon) {
  1051. Vector<Vector3> points;
  1052. // Iterate through every unique combination of any three planes.
  1053. for (int i = p_plane_count - 1; i >= 0; i--) {
  1054. for (int j = i - 1; j >= 0; j--) {
  1055. for (int k = j - 1; k >= 0; k--) {
  1056. // Find the point where these planes all cross over (if they
  1057. // do at all).
  1058. Vector3 convex_shape_point;
  1059. if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
  1060. // See if any *other* plane excludes this point because it's
  1061. // on the wrong side.
  1062. bool excluded = false;
  1063. for (int n = 0; n < p_plane_count; n++) {
  1064. if (n != i && n != j && n != k) {
  1065. real_t dist = p_planes[n].distance_to(convex_shape_point);
  1066. if (dist > p_epsilon) {
  1067. excluded = true;
  1068. break;
  1069. }
  1070. }
  1071. }
  1072. // Only add the point if it passed all tests.
  1073. if (!excluded) {
  1074. points.push_back(convex_shape_point);
  1075. }
  1076. }
  1077. }
  1078. }
  1079. }
  1080. return points;
  1081. }
  1082. Vector<Geometry::PackRectsResult> Geometry::partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size) {
  1083. Vector<stbrp_node> nodes;
  1084. nodes.resize(p_atlas_size.width);
  1085. memset(nodes.ptrw(), 0, sizeof(stbrp_node) * nodes.size());
  1086. stbrp_context context;
  1087. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  1088. Vector<stbrp_rect> rects;
  1089. rects.resize(p_sizes.size());
  1090. for (int i = 0; i < p_sizes.size(); i++) {
  1091. rects.write[i].id = i;
  1092. rects.write[i].w = p_sizes[i].width;
  1093. rects.write[i].h = p_sizes[i].height;
  1094. rects.write[i].x = 0;
  1095. rects.write[i].y = 0;
  1096. rects.write[i].was_packed = 0;
  1097. }
  1098. stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  1099. Vector<PackRectsResult> ret;
  1100. ret.resize(p_sizes.size());
  1101. for (int i = 0; i < p_sizes.size(); i++) {
  1102. ret.write[rects[i].id] = { rects[i].x, rects[i].y, static_cast<bool>(rects[i].was_packed) };
  1103. }
  1104. return ret;
  1105. }
  1106. // adapted from:
  1107. // https://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order
  1108. void Geometry::sort_polygon_winding(Vector<Vector2> &r_verts, bool p_clockwise) {
  1109. // sort winding order of a (primarily convex) polygon.
  1110. // It can handle some concave polygons, but not
  1111. // where a vertex 'goes back on' a previous vertex ..
  1112. // i.e. it will change the shape in some concave cases.
  1113. struct ElementComparator {
  1114. Vector2 center;
  1115. bool operator()(const Vector2 &a, const Vector2 &b) const {
  1116. if (a.x - center.x >= 0 && b.x - center.x < 0) {
  1117. return true;
  1118. }
  1119. if (a.x - center.x < 0 && b.x - center.x >= 0) {
  1120. return false;
  1121. }
  1122. if (a.x - center.x == 0 && b.x - center.x == 0) {
  1123. if (a.y - center.y >= 0 || b.y - center.y >= 0) {
  1124. return a.y > b.y;
  1125. }
  1126. return b.y > a.y;
  1127. }
  1128. // compute the cross product of vectors (center -> a) x (center -> b)
  1129. real_t det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);
  1130. if (det < 0.0) {
  1131. return true;
  1132. }
  1133. if (det > 0.0) {
  1134. return false;
  1135. }
  1136. // points a and b are on the same line from the center
  1137. // check which point is closer to the center
  1138. real_t d1 = (a.x - center.x) * (a.x - center.x) + (a.y - center.y) * (a.y - center.y);
  1139. real_t d2 = (b.x - center.x) * (b.x - center.x) + (b.y - center.y) * (b.y - center.y);
  1140. return d1 > d2;
  1141. }
  1142. };
  1143. int npoints = r_verts.size();
  1144. if (!npoints) {
  1145. return;
  1146. }
  1147. // first calculate center
  1148. Vector2 center;
  1149. for (int n = 0; n < npoints; n++) {
  1150. center += r_verts[n];
  1151. }
  1152. center /= npoints;
  1153. SortArray<Vector2, ElementComparator> sorter;
  1154. sorter.compare.center = center;
  1155. sorter.sort(r_verts.ptrw(), r_verts.size());
  1156. // if not clockwise, reverse order
  1157. if (!p_clockwise) {
  1158. r_verts.invert();
  1159. }
  1160. }