geometry_3d.cpp 24 KB

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