geometry_3d.cpp 24 KB

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