geometry.cpp 34 KB

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