geometry_3d.cpp 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. /*************************************************************************/
  2. /* geometry_3d.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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_3d.h"
  31. #include "core/string/print_string.h"
  32. #include "thirdparty/misc/clipper.hpp"
  33. #include "thirdparty/misc/polypartition.h"
  34. void Geometry3D::MeshData::optimize_vertices() {
  35. HashMap<int, int> vtx_remap;
  36. for (int i = 0; i < faces.size(); i++) {
  37. for (int j = 0; j < faces[i].indices.size(); j++) {
  38. int idx = faces[i].indices[j];
  39. if (!vtx_remap.has(idx)) {
  40. int ni = vtx_remap.size();
  41. vtx_remap[idx] = ni;
  42. }
  43. faces.write[i].indices.write[j] = vtx_remap[idx];
  44. }
  45. }
  46. for (int i = 0; i < edges.size(); i++) {
  47. int a = edges[i].a;
  48. int b = edges[i].b;
  49. if (!vtx_remap.has(a)) {
  50. int ni = vtx_remap.size();
  51. vtx_remap[a] = ni;
  52. }
  53. if (!vtx_remap.has(b)) {
  54. int ni = vtx_remap.size();
  55. vtx_remap[b] = ni;
  56. }
  57. edges.write[i].a = vtx_remap[a];
  58. edges.write[i].b = vtx_remap[b];
  59. }
  60. Vector<Vector3> new_vertices;
  61. new_vertices.resize(vtx_remap.size());
  62. for (int i = 0; i < vertices.size(); i++) {
  63. if (vtx_remap.has(i)) {
  64. new_vertices.write[vtx_remap[i]] = vertices[i];
  65. }
  66. }
  67. vertices = new_vertices;
  68. }
  69. struct _FaceClassify {
  70. struct _Link {
  71. int face = -1;
  72. int edge = -1;
  73. void clear() {
  74. face = -1;
  75. edge = -1;
  76. }
  77. _Link() {}
  78. };
  79. bool valid = false;
  80. int group = -1;
  81. _Link links[3];
  82. Face3 face;
  83. _FaceClassify() {}
  84. };
  85. static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
  86. // Connect faces, error will occur if an edge is shared between more than 2 faces.
  87. // Clear connections.
  88. bool error = false;
  89. for (int i = 0; i < len; i++) {
  90. for (int j = 0; j < 3; j++) {
  91. p_faces[i].links[j].clear();
  92. }
  93. }
  94. for (int i = 0; i < len; i++) {
  95. if (p_faces[i].group != p_group) {
  96. continue;
  97. }
  98. for (int j = i + 1; j < len; j++) {
  99. if (p_faces[j].group != p_group) {
  100. continue;
  101. }
  102. for (int k = 0; k < 3; k++) {
  103. Vector3 vi1 = p_faces[i].face.vertex[k];
  104. Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
  105. for (int l = 0; l < 3; l++) {
  106. Vector3 vj2 = p_faces[j].face.vertex[l];
  107. Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
  108. if (vi1.distance_to(vj1) < 0.00001f &&
  109. vi2.distance_to(vj2) < 0.00001f) {
  110. if (p_faces[i].links[k].face != -1) {
  111. ERR_PRINT("already linked\n");
  112. error = true;
  113. break;
  114. }
  115. if (p_faces[j].links[l].face != -1) {
  116. ERR_PRINT("already linked\n");
  117. error = true;
  118. break;
  119. }
  120. p_faces[i].links[k].face = j;
  121. p_faces[i].links[k].edge = l;
  122. p_faces[j].links[l].face = i;
  123. p_faces[j].links[l].edge = k;
  124. }
  125. }
  126. if (error) {
  127. break;
  128. }
  129. }
  130. if (error) {
  131. break;
  132. }
  133. }
  134. if (error) {
  135. break;
  136. }
  137. }
  138. for (int i = 0; i < len; i++) {
  139. p_faces[i].valid = true;
  140. for (int j = 0; j < 3; j++) {
  141. if (p_faces[i].links[j].face == -1) {
  142. p_faces[i].valid = false;
  143. }
  144. }
  145. }
  146. return error;
  147. }
  148. static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
  149. if (p_faces[p_index].group >= 0) {
  150. return false;
  151. }
  152. p_faces[p_index].group = p_group;
  153. for (int i = 0; i < 3; i++) {
  154. ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
  155. _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
  156. }
  157. return true;
  158. }
  159. Vector<Vector<Face3>> Geometry3D::separate_objects(Vector<Face3> p_array) {
  160. Vector<Vector<Face3>> objects;
  161. int len = p_array.size();
  162. const Face3 *arrayptr = p_array.ptr();
  163. Vector<_FaceClassify> fc;
  164. fc.resize(len);
  165. _FaceClassify *_fcptr = fc.ptrw();
  166. for (int i = 0; i < len; i++) {
  167. _fcptr[i].face = arrayptr[i];
  168. }
  169. bool error = _connect_faces(_fcptr, len, -1);
  170. ERR_FAIL_COND_V_MSG(error, Vector<Vector<Face3>>(), "Invalid geometry.");
  171. // Group connected faces in separate objects.
  172. int group = 0;
  173. for (int i = 0; i < len; i++) {
  174. if (!_fcptr[i].valid) {
  175. continue;
  176. }
  177. if (_group_face(_fcptr, len, i, group)) {
  178. group++;
  179. }
  180. }
  181. // Group connected faces in separate objects.
  182. for (int i = 0; i < len; i++) {
  183. _fcptr[i].face = arrayptr[i];
  184. }
  185. if (group >= 0) {
  186. objects.resize(group);
  187. Vector<Face3> *group_faces = objects.ptrw();
  188. for (int i = 0; i < len; i++) {
  189. if (!_fcptr[i].valid) {
  190. continue;
  191. }
  192. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  193. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  194. }
  195. }
  196. }
  197. return objects;
  198. }
  199. /*** GEOMETRY WRAPPER ***/
  200. enum _CellFlags {
  201. _CELL_SOLID = 1,
  202. _CELL_EXTERIOR = 2,
  203. _CELL_STEP_MASK = 0x1C,
  204. _CELL_STEP_NONE = 0 << 2,
  205. _CELL_STEP_Y_POS = 1 << 2,
  206. _CELL_STEP_Y_NEG = 2 << 2,
  207. _CELL_STEP_X_POS = 3 << 2,
  208. _CELL_STEP_X_NEG = 4 << 2,
  209. _CELL_STEP_Z_POS = 5 << 2,
  210. _CELL_STEP_Z_NEG = 6 << 2,
  211. _CELL_STEP_DONE = 7 << 2,
  212. _CELL_PREV_MASK = 0xE0,
  213. _CELL_PREV_NONE = 0 << 5,
  214. _CELL_PREV_Y_POS = 1 << 5,
  215. _CELL_PREV_Y_NEG = 2 << 5,
  216. _CELL_PREV_X_POS = 3 << 5,
  217. _CELL_PREV_X_NEG = 4 << 5,
  218. _CELL_PREV_Z_POS = 5 << 5,
  219. _CELL_PREV_Z_NEG = 6 << 5,
  220. _CELL_PREV_FIRST = 7 << 5,
  221. };
  222. 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) {
  223. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  224. aabb.position = aabb.position * voxelsize;
  225. aabb.size = aabb.size * voxelsize;
  226. if (!p_face.intersects_aabb(aabb)) {
  227. return;
  228. }
  229. if (len_x == 1 && len_y == 1 && len_z == 1) {
  230. p_cell_status[x][y][z] = _CELL_SOLID;
  231. return;
  232. }
  233. int div_x = len_x > 1 ? 2 : 1;
  234. int div_y = len_y > 1 ? 2 : 1;
  235. int div_z = len_z > 1 ? 2 : 1;
  236. #define SPLIT_DIV(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  237. if (m_div == 1) { \
  238. m_new_v = m_v; \
  239. m_new_len_v = 1; \
  240. } else if (m_i == 0) { \
  241. m_new_v = m_v; \
  242. m_new_len_v = m_len_v / 2; \
  243. } else { \
  244. m_new_v = m_v + m_len_v / 2; \
  245. m_new_len_v = m_len_v - m_len_v / 2; \
  246. }
  247. int new_x;
  248. int new_len_x;
  249. int new_y;
  250. int new_len_y;
  251. int new_z;
  252. int new_len_z;
  253. for (int i = 0; i < div_x; i++) {
  254. SPLIT_DIV(i, div_x, x, len_x, new_x, new_len_x);
  255. for (int j = 0; j < div_y; j++) {
  256. SPLIT_DIV(j, div_y, y, len_y, new_y, new_len_y);
  257. for (int k = 0; k < div_z; k++) {
  258. SPLIT_DIV(k, div_z, z, len_z, new_z, new_len_z);
  259. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  260. }
  261. }
  262. }
  263. #undef SPLIT_DIV
  264. }
  265. 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) {
  266. if (p_cell_status[x][y][z] & 3) {
  267. return; // Nothing to do, already used and/or visited.
  268. }
  269. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  270. while (true) {
  271. uint8_t &c = p_cell_status[x][y][z];
  272. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  273. // Haven't been in here, mark as outside.
  274. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  275. }
  276. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  277. // If not done, increase step.
  278. c += 1 << 2;
  279. }
  280. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  281. // Go back.
  282. switch (c & _CELL_PREV_MASK) {
  283. case _CELL_PREV_FIRST: {
  284. return;
  285. } break;
  286. case _CELL_PREV_Y_POS: {
  287. y++;
  288. ERR_FAIL_COND(y >= len_y);
  289. } break;
  290. case _CELL_PREV_Y_NEG: {
  291. y--;
  292. ERR_FAIL_COND(y < 0);
  293. } break;
  294. case _CELL_PREV_X_POS: {
  295. x++;
  296. ERR_FAIL_COND(x >= len_x);
  297. } break;
  298. case _CELL_PREV_X_NEG: {
  299. x--;
  300. ERR_FAIL_COND(x < 0);
  301. } break;
  302. case _CELL_PREV_Z_POS: {
  303. z++;
  304. ERR_FAIL_COND(z >= len_z);
  305. } break;
  306. case _CELL_PREV_Z_NEG: {
  307. z--;
  308. ERR_FAIL_COND(z < 0);
  309. } break;
  310. default: {
  311. ERR_FAIL();
  312. }
  313. }
  314. continue;
  315. }
  316. int next_x = x, next_y = y, next_z = z;
  317. uint8_t prev = 0;
  318. switch (c & _CELL_STEP_MASK) {
  319. case _CELL_STEP_Y_POS: {
  320. next_y++;
  321. prev = _CELL_PREV_Y_NEG;
  322. } break;
  323. case _CELL_STEP_Y_NEG: {
  324. next_y--;
  325. prev = _CELL_PREV_Y_POS;
  326. } break;
  327. case _CELL_STEP_X_POS: {
  328. next_x++;
  329. prev = _CELL_PREV_X_NEG;
  330. } break;
  331. case _CELL_STEP_X_NEG: {
  332. next_x--;
  333. prev = _CELL_PREV_X_POS;
  334. } break;
  335. case _CELL_STEP_Z_POS: {
  336. next_z++;
  337. prev = _CELL_PREV_Z_NEG;
  338. } break;
  339. case _CELL_STEP_Z_NEG: {
  340. next_z--;
  341. prev = _CELL_PREV_Z_POS;
  342. } break;
  343. default:
  344. ERR_FAIL();
  345. }
  346. if (next_x < 0 || next_x >= len_x) {
  347. continue;
  348. }
  349. if (next_y < 0 || next_y >= len_y) {
  350. continue;
  351. }
  352. if (next_z < 0 || next_z >= len_z) {
  353. continue;
  354. }
  355. if (p_cell_status[next_x][next_y][next_z] & 3) {
  356. continue;
  357. }
  358. x = next_x;
  359. y = next_y;
  360. z = next_z;
  361. p_cell_status[x][y][z] |= prev;
  362. }
  363. }
  364. 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) {
  365. ERR_FAIL_INDEX(x, len_x);
  366. ERR_FAIL_INDEX(y, len_y);
  367. ERR_FAIL_INDEX(z, len_z);
  368. if (p_cell_status[x][y][z] & _CELL_EXTERIOR) {
  369. return;
  370. }
  371. #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
  372. static const uint8_t indices[6][4] = {
  373. { 7, 6, 4, 5 },
  374. { 7, 3, 2, 6 },
  375. { 7, 5, 1, 3 },
  376. { 0, 2, 3, 1 },
  377. { 0, 1, 5, 4 },
  378. { 0, 4, 6, 2 },
  379. };
  380. for (int i = 0; i < 6; i++) {
  381. Vector3 face_points[4];
  382. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  383. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  384. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  385. bool plot = false;
  386. if (disp_x < 0 || disp_x >= len_x) {
  387. plot = true;
  388. }
  389. if (disp_y < 0 || disp_y >= len_y) {
  390. plot = true;
  391. }
  392. if (disp_z < 0 || disp_z >= len_z) {
  393. plot = true;
  394. }
  395. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR)) {
  396. plot = true;
  397. }
  398. if (!plot) {
  399. continue;
  400. }
  401. for (int j = 0; j < 4; j++) {
  402. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  403. }
  404. p_faces.push_back(
  405. Face3(
  406. face_points[0],
  407. face_points[1],
  408. face_points[2]));
  409. p_faces.push_back(
  410. Face3(
  411. face_points[2],
  412. face_points[3],
  413. face_points[0]));
  414. }
  415. }
  416. Vector<Face3> Geometry3D::wrap_geometry(Vector<Face3> p_array, real_t *p_error) {
  417. int face_count = p_array.size();
  418. const Face3 *faces = p_array.ptr();
  419. constexpr double min_size = 1.0;
  420. constexpr int max_length = 20;
  421. AABB global_aabb;
  422. for (int i = 0; i < face_count; i++) {
  423. if (i == 0) {
  424. global_aabb = faces[i].get_aabb();
  425. } else {
  426. global_aabb.merge_with(faces[i].get_aabb());
  427. }
  428. }
  429. global_aabb.grow_by(0.01f); // Avoid numerical error.
  430. // Determine amount of cells in grid axis.
  431. int div_x, div_y, div_z;
  432. if (global_aabb.size.x / min_size < max_length) {
  433. div_x = (int)(global_aabb.size.x / min_size) + 1;
  434. } else {
  435. div_x = max_length;
  436. }
  437. if (global_aabb.size.y / min_size < max_length) {
  438. div_y = (int)(global_aabb.size.y / min_size) + 1;
  439. } else {
  440. div_y = max_length;
  441. }
  442. if (global_aabb.size.z / min_size < max_length) {
  443. div_z = (int)(global_aabb.size.z / min_size) + 1;
  444. } else {
  445. div_z = max_length;
  446. }
  447. Vector3 voxelsize = global_aabb.size;
  448. voxelsize.x /= div_x;
  449. voxelsize.y /= div_y;
  450. voxelsize.z /= div_z;
  451. // Create and initialize cells to zero.
  452. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
  453. for (int i = 0; i < div_x; i++) {
  454. cell_status[i] = memnew_arr(uint8_t *, div_y);
  455. for (int j = 0; j < div_y; j++) {
  456. cell_status[i][j] = memnew_arr(uint8_t, div_z);
  457. for (int k = 0; k < div_z; k++) {
  458. cell_status[i][j][k] = 0;
  459. }
  460. }
  461. }
  462. // Plot faces into cells.
  463. for (int i = 0; i < face_count; i++) {
  464. Face3 f = faces[i];
  465. for (int j = 0; j < 3; j++) {
  466. f.vertex[j] -= global_aabb.position;
  467. }
  468. _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
  469. }
  470. // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
  471. for (int i = 0; i < div_x; i++) {
  472. for (int j = 0; j < div_y; j++) {
  473. _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
  474. _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
  475. }
  476. }
  477. for (int i = 0; i < div_z; i++) {
  478. for (int j = 0; j < div_y; j++) {
  479. _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
  480. _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
  481. }
  482. }
  483. for (int i = 0; i < div_x; i++) {
  484. for (int j = 0; j < div_z; j++) {
  485. _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
  486. _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
  487. }
  488. }
  489. // Build faces for the inside-outside cell divisors.
  490. Vector<Face3> wrapped_faces;
  491. for (int i = 0; i < div_x; i++) {
  492. for (int j = 0; j < div_y; j++) {
  493. for (int k = 0; k < div_z; k++) {
  494. _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
  495. }
  496. }
  497. }
  498. // Transform face vertices to global coords.
  499. int wrapped_faces_count = wrapped_faces.size();
  500. Face3 *wrapped_faces_ptr = wrapped_faces.ptrw();
  501. for (int i = 0; i < wrapped_faces_count; i++) {
  502. for (int j = 0; j < 3; j++) {
  503. Vector3 &v = wrapped_faces_ptr[i].vertex[j];
  504. v = v * voxelsize;
  505. v += global_aabb.position;
  506. }
  507. }
  508. // clean up grid
  509. for (int i = 0; i < div_x; i++) {
  510. for (int j = 0; j < div_y; j++) {
  511. memdelete_arr(cell_status[i][j]);
  512. }
  513. memdelete_arr(cell_status[i]);
  514. }
  515. memdelete_arr(cell_status);
  516. if (p_error) {
  517. *p_error = voxelsize.length();
  518. }
  519. return wrapped_faces;
  520. }
  521. Geometry3D::MeshData Geometry3D::build_convex_mesh(const Vector<Plane> &p_planes) {
  522. MeshData mesh;
  523. #define SUBPLANE_SIZE 1024.0
  524. real_t subplane_size = 1024.0; // Should compute this from the actual plane.
  525. for (int i = 0; i < p_planes.size(); i++) {
  526. Plane p = p_planes[i];
  527. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  528. if (ABS(p.normal.dot(ref)) > 0.95f) {
  529. ref = Vector3(0.0, 0.0, 1.0); // Change axis.
  530. }
  531. Vector3 right = p.normal.cross(ref).normalized();
  532. Vector3 up = p.normal.cross(right).normalized();
  533. Vector3 center = p.center();
  534. // make a quad clockwise
  535. Vector<Vector3> vertices = {
  536. center - up * subplane_size + right * subplane_size,
  537. center - up * subplane_size - right * subplane_size,
  538. center + up * subplane_size - right * subplane_size,
  539. center + up * subplane_size + right * subplane_size
  540. };
  541. for (int j = 0; j < p_planes.size(); j++) {
  542. if (j == i) {
  543. continue;
  544. }
  545. Vector<Vector3> new_vertices;
  546. Plane clip = p_planes[j];
  547. if (clip.normal.dot(p.normal) > 0.95f) {
  548. continue;
  549. }
  550. if (vertices.size() < 3) {
  551. break;
  552. }
  553. for (int k = 0; k < vertices.size(); k++) {
  554. int k_n = (k + 1) % vertices.size();
  555. Vector3 edge0_A = vertices[k];
  556. Vector3 edge1_A = vertices[k_n];
  557. real_t dist0 = clip.distance_to(edge0_A);
  558. real_t dist1 = clip.distance_to(edge1_A);
  559. if (dist0 <= 0) { // Behind plane.
  560. new_vertices.push_back(vertices[k]);
  561. }
  562. // Check for different sides and non coplanar.
  563. if ((dist0 * dist1) < 0) {
  564. // Calculate intersection.
  565. Vector3 rel = edge1_A - edge0_A;
  566. real_t den = clip.normal.dot(rel);
  567. if (Math::is_zero_approx(den)) {
  568. continue; // Point too short.
  569. }
  570. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
  571. Vector3 inters = edge0_A + rel * dist;
  572. new_vertices.push_back(inters);
  573. }
  574. }
  575. vertices = new_vertices;
  576. }
  577. if (vertices.size() < 3) {
  578. continue;
  579. }
  580. // Result is a clockwise face.
  581. MeshData::Face face;
  582. // Add face indices.
  583. for (int j = 0; j < vertices.size(); j++) {
  584. int idx = -1;
  585. for (int k = 0; k < mesh.vertices.size(); k++) {
  586. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001f) {
  587. idx = k;
  588. break;
  589. }
  590. }
  591. if (idx == -1) {
  592. idx = mesh.vertices.size();
  593. mesh.vertices.push_back(vertices[j]);
  594. }
  595. face.indices.push_back(idx);
  596. }
  597. face.plane = p;
  598. mesh.faces.push_back(face);
  599. // Add edge.
  600. for (int j = 0; j < face.indices.size(); j++) {
  601. int a = face.indices[j];
  602. int b = face.indices[(j + 1) % face.indices.size()];
  603. bool found = false;
  604. for (int k = 0; k < mesh.edges.size(); k++) {
  605. if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
  606. found = true;
  607. break;
  608. }
  609. if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
  610. found = true;
  611. break;
  612. }
  613. }
  614. if (found) {
  615. continue;
  616. }
  617. MeshData::Edge edge;
  618. edge.a = a;
  619. edge.b = b;
  620. mesh.edges.push_back(edge);
  621. }
  622. }
  623. return mesh;
  624. }
  625. Vector<Plane> Geometry3D::build_box_planes(const Vector3 &p_extents) {
  626. Vector<Plane> planes = {
  627. Plane(Vector3(1, 0, 0), p_extents.x),
  628. Plane(Vector3(-1, 0, 0), p_extents.x),
  629. Plane(Vector3(0, 1, 0), p_extents.y),
  630. Plane(Vector3(0, -1, 0), p_extents.y),
  631. Plane(Vector3(0, 0, 1), p_extents.z),
  632. Plane(Vector3(0, 0, -1), p_extents.z)
  633. };
  634. return planes;
  635. }
  636. Vector<Plane> Geometry3D::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  637. ERR_FAIL_INDEX_V(p_axis, 3, Vector<Plane>());
  638. Vector<Plane> planes;
  639. const double sides_step = Math_TAU / p_sides;
  640. for (int i = 0; i < p_sides; i++) {
  641. Vector3 normal;
  642. normal[(p_axis + 1) % 3] = Math::cos(i * sides_step);
  643. normal[(p_axis + 2) % 3] = Math::sin(i * sides_step);
  644. planes.push_back(Plane(normal, p_radius));
  645. }
  646. Vector3 axis;
  647. axis[p_axis] = 1.0;
  648. planes.push_back(Plane(axis, p_height * 0.5f));
  649. planes.push_back(Plane(-axis, p_height * 0.5f));
  650. return planes;
  651. }
  652. Vector<Plane> Geometry3D::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  653. ERR_FAIL_INDEX_V(p_axis, 3, Vector<Plane>());
  654. Vector<Plane> planes;
  655. Vector3 axis;
  656. axis[p_axis] = 1.0;
  657. Vector3 axis_neg;
  658. axis_neg[(p_axis + 1) % 3] = 1.0;
  659. axis_neg[(p_axis + 2) % 3] = 1.0;
  660. axis_neg[p_axis] = -1.0;
  661. const double lon_step = Math_TAU / p_lons;
  662. for (int i = 0; i < p_lons; i++) {
  663. Vector3 normal;
  664. normal[(p_axis + 1) % 3] = Math::cos(i * lon_step);
  665. normal[(p_axis + 2) % 3] = Math::sin(i * lon_step);
  666. planes.push_back(Plane(normal, p_radius));
  667. for (int j = 1; j <= p_lats; j++) {
  668. Vector3 plane_normal = normal.lerp(axis, j / (real_t)p_lats).normalized();
  669. planes.push_back(Plane(plane_normal, p_radius));
  670. planes.push_back(Plane(plane_normal * axis_neg, p_radius));
  671. }
  672. }
  673. return planes;
  674. }
  675. Vector<Plane> Geometry3D::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  676. ERR_FAIL_INDEX_V(p_axis, 3, Vector<Plane>());
  677. Vector<Plane> planes;
  678. Vector3 axis;
  679. axis[p_axis] = 1.0;
  680. Vector3 axis_neg;
  681. axis_neg[(p_axis + 1) % 3] = 1.0;
  682. axis_neg[(p_axis + 2) % 3] = 1.0;
  683. axis_neg[p_axis] = -1.0;
  684. const double sides_step = Math_TAU / p_sides;
  685. for (int i = 0; i < p_sides; i++) {
  686. Vector3 normal;
  687. normal[(p_axis + 1) % 3] = Math::cos(i * sides_step);
  688. normal[(p_axis + 2) % 3] = Math::sin(i * sides_step);
  689. planes.push_back(Plane(normal, p_radius));
  690. for (int j = 1; j <= p_lats; j++) {
  691. Vector3 plane_normal = normal.lerp(axis, j / (real_t)p_lats).normalized();
  692. Vector3 position = axis * p_height * 0.5f + plane_normal * p_radius;
  693. planes.push_back(Plane(plane_normal, position));
  694. planes.push_back(Plane(plane_normal * axis_neg, position * axis_neg));
  695. }
  696. }
  697. return planes;
  698. }
  699. Vector<Vector3> Geometry3D::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count) {
  700. Vector<Vector3> points;
  701. // Iterate through every unique combination of any three planes.
  702. for (int i = p_plane_count - 1; i >= 0; i--) {
  703. for (int j = i - 1; j >= 0; j--) {
  704. for (int k = j - 1; k >= 0; k--) {
  705. // Find the point where these planes all cross over (if they
  706. // do at all).
  707. Vector3 convex_shape_point;
  708. if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
  709. // See if any *other* plane excludes this point because it's
  710. // on the wrong side.
  711. bool excluded = false;
  712. for (int n = 0; n < p_plane_count; n++) {
  713. if (n != i && n != j && n != k) {
  714. real_t dp = p_planes[n].normal.dot(convex_shape_point);
  715. if (dp - p_planes[n].d > (real_t)CMP_EPSILON) {
  716. excluded = true;
  717. break;
  718. }
  719. }
  720. }
  721. // Only add the point if it passed all tests.
  722. if (!excluded) {
  723. points.push_back(convex_shape_point);
  724. }
  725. }
  726. }
  727. }
  728. }
  729. return points;
  730. }
  731. #define square(m_s) ((m_s) * (m_s))
  732. #define INF 1e20
  733. /* dt of 1d function using squared distance */
  734. static void edt(float *f, int stride, int n) {
  735. float *d = (float *)alloca(sizeof(float) * n + sizeof(int) * n + sizeof(float) * (n + 1));
  736. int *v = reinterpret_cast<int *>(&(d[n]));
  737. float *z = reinterpret_cast<float *>(&v[n]);
  738. int k = 0;
  739. v[0] = 0;
  740. z[0] = -INF;
  741. z[1] = +INF;
  742. for (int q = 1; q <= n - 1; q++) {
  743. float s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  744. while (s <= z[k]) {
  745. k--;
  746. s = ((f[q * stride] + square(q)) - (f[v[k] * stride] + square(v[k]))) / (2 * q - 2 * v[k]);
  747. }
  748. k++;
  749. v[k] = q;
  750. z[k] = s;
  751. z[k + 1] = +INF;
  752. }
  753. k = 0;
  754. for (int q = 0; q <= n - 1; q++) {
  755. while (z[k + 1] < q) {
  756. k++;
  757. }
  758. d[q] = square(q - v[k]) + f[v[k] * stride];
  759. }
  760. for (int i = 0; i < n; i++) {
  761. f[i * stride] = d[i];
  762. }
  763. }
  764. #undef square
  765. Vector<uint32_t> Geometry3D::generate_edf(const Vector<bool> &p_voxels, const Vector3i &p_size, bool p_negative) {
  766. uint32_t float_count = p_size.x * p_size.y * p_size.z;
  767. ERR_FAIL_COND_V((uint32_t)p_voxels.size() != float_count, Vector<uint32_t>());
  768. float *work_memory = memnew_arr(float, float_count);
  769. for (uint32_t i = 0; i < float_count; i++) {
  770. work_memory[i] = INF;
  771. }
  772. uint32_t y_mult = p_size.x;
  773. uint32_t z_mult = y_mult * p_size.y;
  774. //plot solid cells
  775. {
  776. const bool *voxr = p_voxels.ptr();
  777. for (uint32_t i = 0; i < float_count; i++) {
  778. bool plot = voxr[i];
  779. if (p_negative) {
  780. plot = !plot;
  781. }
  782. if (plot) {
  783. work_memory[i] = 0;
  784. }
  785. }
  786. }
  787. //process in each direction
  788. //xy->z
  789. for (int i = 0; i < p_size.x; i++) {
  790. for (int j = 0; j < p_size.y; j++) {
  791. edt(&work_memory[i + j * y_mult], z_mult, p_size.z);
  792. }
  793. }
  794. //xz->y
  795. for (int i = 0; i < p_size.x; i++) {
  796. for (int j = 0; j < p_size.z; j++) {
  797. edt(&work_memory[i + j * z_mult], y_mult, p_size.y);
  798. }
  799. }
  800. //yz->x
  801. for (int i = 0; i < p_size.y; i++) {
  802. for (int j = 0; j < p_size.z; j++) {
  803. edt(&work_memory[i * y_mult + j * z_mult], 1, p_size.x);
  804. }
  805. }
  806. Vector<uint32_t> ret;
  807. ret.resize(float_count);
  808. {
  809. uint32_t *w = ret.ptrw();
  810. for (uint32_t i = 0; i < float_count; i++) {
  811. w[i] = uint32_t(Math::sqrt(work_memory[i]));
  812. }
  813. }
  814. memdelete_arr(work_memory);
  815. return ret;
  816. }
  817. Vector<int8_t> Geometry3D::generate_sdf8(const Vector<uint32_t> &p_positive, const Vector<uint32_t> &p_negative) {
  818. ERR_FAIL_COND_V(p_positive.size() != p_negative.size(), Vector<int8_t>());
  819. Vector<int8_t> sdf8;
  820. int s = p_positive.size();
  821. sdf8.resize(s);
  822. const uint32_t *rpos = p_positive.ptr();
  823. const uint32_t *rneg = p_negative.ptr();
  824. int8_t *wsdf = sdf8.ptrw();
  825. for (int i = 0; i < s; i++) {
  826. int32_t diff = int32_t(rpos[i]) - int32_t(rneg[i]);
  827. wsdf[i] = CLAMP(diff, -128, 127);
  828. }
  829. return sdf8;
  830. }