geometry.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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 SCALE_FACTOR 100000.0 // Based on CMP_EPSILON.
  35. // This implementation is very inefficient, commenting unless bugs happen. See the other one.
  36. /*
  37. bool Geometry::is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  38. Vector<int> indices = Geometry::triangulate_polygon(p_polygon);
  39. for (int j = 0; j + 3 <= indices.size(); j += 3) {
  40. int i1 = indices[j], i2 = indices[j + 1], i3 = indices[j + 2];
  41. if (Geometry::is_point_in_triangle(p_point, p_polygon[i1], p_polygon[i2], p_polygon[i3]))
  42. return true;
  43. }
  44. return false;
  45. }
  46. */
  47. void Geometry::MeshData::optimize_vertices() {
  48. Map<int, int> vtx_remap;
  49. for (int i = 0; i < faces.size(); i++) {
  50. for (int j = 0; j < faces[i].indices.size(); j++) {
  51. int idx = faces[i].indices[j];
  52. if (!vtx_remap.has(idx)) {
  53. int ni = vtx_remap.size();
  54. vtx_remap[idx] = ni;
  55. }
  56. faces.write[i].indices.write[j] = vtx_remap[idx];
  57. }
  58. }
  59. for (int i = 0; i < edges.size(); i++) {
  60. int a = edges[i].a;
  61. int b = edges[i].b;
  62. if (!vtx_remap.has(a)) {
  63. int ni = vtx_remap.size();
  64. vtx_remap[a] = ni;
  65. }
  66. if (!vtx_remap.has(b)) {
  67. int ni = vtx_remap.size();
  68. vtx_remap[b] = ni;
  69. }
  70. edges.write[i].a = vtx_remap[a];
  71. edges.write[i].b = vtx_remap[b];
  72. }
  73. Vector<Vector3> new_vertices;
  74. new_vertices.resize(vtx_remap.size());
  75. for (int i = 0; i < vertices.size(); i++) {
  76. if (vtx_remap.has(i))
  77. new_vertices.write[vtx_remap[i]] = vertices[i];
  78. }
  79. vertices = new_vertices;
  80. }
  81. struct _FaceClassify {
  82. struct _Link {
  83. int face;
  84. int edge;
  85. void clear() {
  86. face = -1;
  87. edge = -1;
  88. }
  89. _Link() {
  90. face = -1;
  91. edge = -1;
  92. }
  93. };
  94. bool valid;
  95. int group;
  96. _Link links[3];
  97. Face3 face;
  98. _FaceClassify() {
  99. group = -1;
  100. valid = false;
  101. };
  102. };
  103. static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
  104. // Connect faces, error will occur if an edge is shared between more than 2 faces.
  105. // Clear connections.
  106. bool error = false;
  107. for (int i = 0; i < len; i++) {
  108. for (int j = 0; j < 3; j++) {
  109. p_faces[i].links[j].clear();
  110. }
  111. }
  112. for (int i = 0; i < len; i++) {
  113. if (p_faces[i].group != p_group)
  114. continue;
  115. for (int j = i + 1; j < len; j++) {
  116. if (p_faces[j].group != p_group)
  117. continue;
  118. for (int k = 0; k < 3; k++) {
  119. Vector3 vi1 = p_faces[i].face.vertex[k];
  120. Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
  121. for (int l = 0; l < 3; l++) {
  122. Vector3 vj2 = p_faces[j].face.vertex[l];
  123. Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
  124. if (vi1.distance_to(vj1) < 0.00001 &&
  125. vi2.distance_to(vj2) < 0.00001) {
  126. if (p_faces[i].links[k].face != -1) {
  127. ERR_PRINT("already linked\n");
  128. error = true;
  129. break;
  130. }
  131. if (p_faces[j].links[l].face != -1) {
  132. ERR_PRINT("already linked\n");
  133. error = true;
  134. break;
  135. }
  136. p_faces[i].links[k].face = j;
  137. p_faces[i].links[k].edge = l;
  138. p_faces[j].links[l].face = i;
  139. p_faces[j].links[l].edge = k;
  140. }
  141. }
  142. if (error)
  143. break;
  144. }
  145. if (error)
  146. break;
  147. }
  148. if (error)
  149. break;
  150. }
  151. for (int i = 0; i < len; i++) {
  152. p_faces[i].valid = true;
  153. for (int j = 0; j < 3; j++) {
  154. if (p_faces[i].links[j].face == -1)
  155. p_faces[i].valid = false;
  156. }
  157. }
  158. return error;
  159. }
  160. static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
  161. if (p_faces[p_index].group >= 0)
  162. return false;
  163. p_faces[p_index].group = p_group;
  164. for (int i = 0; i < 3; i++) {
  165. ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
  166. _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
  167. }
  168. return true;
  169. }
  170. PoolVector<PoolVector<Face3> > Geometry::separate_objects(PoolVector<Face3> p_array) {
  171. PoolVector<PoolVector<Face3> > objects;
  172. int len = p_array.size();
  173. PoolVector<Face3>::Read r = p_array.read();
  174. const Face3 *arrayptr = r.ptr();
  175. PoolVector<_FaceClassify> fc;
  176. fc.resize(len);
  177. PoolVector<_FaceClassify>::Write fcw = fc.write();
  178. _FaceClassify *_fcptr = fcw.ptr();
  179. for (int i = 0; i < len; i++) {
  180. _fcptr[i].face = arrayptr[i];
  181. }
  182. bool error = _connect_faces(_fcptr, len, -1);
  183. ERR_FAIL_COND_V_MSG(error, PoolVector<PoolVector<Face3> >(), "Invalid geometry.");
  184. // Group connected faces in separate objects.
  185. int group = 0;
  186. for (int i = 0; i < len; i++) {
  187. if (!_fcptr[i].valid)
  188. continue;
  189. if (_group_face(_fcptr, len, i, group)) {
  190. group++;
  191. }
  192. }
  193. // Group connected faces in separate objects.
  194. for (int i = 0; i < len; i++) {
  195. _fcptr[i].face = arrayptr[i];
  196. }
  197. if (group >= 0) {
  198. objects.resize(group);
  199. PoolVector<PoolVector<Face3> >::Write obw = objects.write();
  200. PoolVector<Face3> *group_faces = obw.ptr();
  201. for (int i = 0; i < len; i++) {
  202. if (!_fcptr[i].valid)
  203. continue;
  204. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  205. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  206. }
  207. }
  208. }
  209. return objects;
  210. }
  211. /*** GEOMETRY WRAPPER ***/
  212. enum _CellFlags {
  213. _CELL_SOLID = 1,
  214. _CELL_EXTERIOR = 2,
  215. _CELL_STEP_MASK = 0x1C,
  216. _CELL_STEP_NONE = 0 << 2,
  217. _CELL_STEP_Y_POS = 1 << 2,
  218. _CELL_STEP_Y_NEG = 2 << 2,
  219. _CELL_STEP_X_POS = 3 << 2,
  220. _CELL_STEP_X_NEG = 4 << 2,
  221. _CELL_STEP_Z_POS = 5 << 2,
  222. _CELL_STEP_Z_NEG = 6 << 2,
  223. _CELL_STEP_DONE = 7 << 2,
  224. _CELL_PREV_MASK = 0xE0,
  225. _CELL_PREV_NONE = 0 << 5,
  226. _CELL_PREV_Y_POS = 1 << 5,
  227. _CELL_PREV_Y_NEG = 2 << 5,
  228. _CELL_PREV_X_POS = 3 << 5,
  229. _CELL_PREV_X_NEG = 4 << 5,
  230. _CELL_PREV_Z_POS = 5 << 5,
  231. _CELL_PREV_Z_NEG = 6 << 5,
  232. _CELL_PREV_FIRST = 7 << 5,
  233. };
  234. 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) {
  235. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  236. aabb.position = aabb.position * voxelsize;
  237. aabb.size = aabb.size * voxelsize;
  238. if (!p_face.intersects_aabb(aabb))
  239. return;
  240. if (len_x == 1 && len_y == 1 && len_z == 1) {
  241. p_cell_status[x][y][z] = _CELL_SOLID;
  242. return;
  243. }
  244. int div_x = len_x > 1 ? 2 : 1;
  245. int div_y = len_y > 1 ? 2 : 1;
  246. int div_z = len_z > 1 ? 2 : 1;
  247. #define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  248. if (m_div == 1) { \
  249. m_new_v = m_v; \
  250. m_new_len_v = 1; \
  251. } else if (m_i == 0) { \
  252. m_new_v = m_v; \
  253. m_new_len_v = m_len_v / 2; \
  254. } else { \
  255. m_new_v = m_v + m_len_v / 2; \
  256. m_new_len_v = m_len_v - m_len_v / 2; \
  257. }
  258. int new_x;
  259. int new_len_x;
  260. int new_y;
  261. int new_len_y;
  262. int new_z;
  263. int new_len_z;
  264. for (int i = 0; i < div_x; i++) {
  265. _SPLIT(i, div_x, x, len_x, new_x, new_len_x);
  266. for (int j = 0; j < div_y; j++) {
  267. _SPLIT(j, div_y, y, len_y, new_y, new_len_y);
  268. for (int k = 0; k < div_z; k++) {
  269. _SPLIT(k, div_z, z, len_z, new_z, new_len_z);
  270. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  271. }
  272. }
  273. }
  274. }
  275. 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) {
  276. if (p_cell_status[x][y][z] & 3)
  277. return; // Nothing to do, already used and/or visited.
  278. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  279. while (true) {
  280. uint8_t &c = p_cell_status[x][y][z];
  281. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  282. // Haven't been in here, mark as outside.
  283. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  284. }
  285. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  286. // If not done, increase step.
  287. c += 1 << 2;
  288. }
  289. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  290. // Go back.
  291. switch (c & _CELL_PREV_MASK) {
  292. case _CELL_PREV_FIRST: {
  293. return;
  294. } break;
  295. case _CELL_PREV_Y_POS: {
  296. y++;
  297. ERR_FAIL_COND(y >= len_y);
  298. } break;
  299. case _CELL_PREV_Y_NEG: {
  300. y--;
  301. ERR_FAIL_COND(y < 0);
  302. } break;
  303. case _CELL_PREV_X_POS: {
  304. x++;
  305. ERR_FAIL_COND(x >= len_x);
  306. } break;
  307. case _CELL_PREV_X_NEG: {
  308. x--;
  309. ERR_FAIL_COND(x < 0);
  310. } break;
  311. case _CELL_PREV_Z_POS: {
  312. z++;
  313. ERR_FAIL_COND(z >= len_z);
  314. } break;
  315. case _CELL_PREV_Z_NEG: {
  316. z--;
  317. ERR_FAIL_COND(z < 0);
  318. } break;
  319. default: {
  320. ERR_FAIL();
  321. }
  322. }
  323. continue;
  324. }
  325. int next_x = x, next_y = y, next_z = z;
  326. uint8_t prev = 0;
  327. switch (c & _CELL_STEP_MASK) {
  328. case _CELL_STEP_Y_POS: {
  329. next_y++;
  330. prev = _CELL_PREV_Y_NEG;
  331. } break;
  332. case _CELL_STEP_Y_NEG: {
  333. next_y--;
  334. prev = _CELL_PREV_Y_POS;
  335. } break;
  336. case _CELL_STEP_X_POS: {
  337. next_x++;
  338. prev = _CELL_PREV_X_NEG;
  339. } break;
  340. case _CELL_STEP_X_NEG: {
  341. next_x--;
  342. prev = _CELL_PREV_X_POS;
  343. } break;
  344. case _CELL_STEP_Z_POS: {
  345. next_z++;
  346. prev = _CELL_PREV_Z_NEG;
  347. } break;
  348. case _CELL_STEP_Z_NEG: {
  349. next_z--;
  350. prev = _CELL_PREV_Z_POS;
  351. } break;
  352. default: ERR_FAIL();
  353. }
  354. if (next_x < 0 || next_x >= len_x)
  355. continue;
  356. if (next_y < 0 || next_y >= len_y)
  357. continue;
  358. if (next_z < 0 || next_z >= len_z)
  359. continue;
  360. if (p_cell_status[next_x][next_y][next_z] & 3)
  361. continue;
  362. x = next_x;
  363. y = next_y;
  364. z = next_z;
  365. p_cell_status[x][y][z] |= prev;
  366. }
  367. }
  368. static inline void _build_faces(uint8_t ***p_cell_status, int x, int y, int z, int len_x, int len_y, int len_z, PoolVector<Face3> &p_faces) {
  369. ERR_FAIL_INDEX(x, len_x);
  370. ERR_FAIL_INDEX(y, len_y);
  371. ERR_FAIL_INDEX(z, len_z);
  372. if (p_cell_status[x][y][z] & _CELL_EXTERIOR)
  373. return;
  374. #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
  375. static const uint8_t indices[6][4] = {
  376. { 7, 6, 4, 5 },
  377. { 7, 3, 2, 6 },
  378. { 7, 5, 1, 3 },
  379. { 0, 2, 3, 1 },
  380. { 0, 1, 5, 4 },
  381. { 0, 4, 6, 2 },
  382. };
  383. for (int i = 0; i < 6; i++) {
  384. Vector3 face_points[4];
  385. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  386. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  387. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  388. bool plot = false;
  389. if (disp_x < 0 || disp_x >= len_x)
  390. plot = true;
  391. if (disp_y < 0 || disp_y >= len_y)
  392. plot = true;
  393. if (disp_z < 0 || disp_z >= len_z)
  394. plot = true;
  395. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR))
  396. plot = true;
  397. if (!plot)
  398. continue;
  399. for (int j = 0; j < 4; j++)
  400. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  401. p_faces.push_back(
  402. Face3(
  403. face_points[0],
  404. face_points[1],
  405. face_points[2]));
  406. p_faces.push_back(
  407. Face3(
  408. face_points[2],
  409. face_points[3],
  410. face_points[0]));
  411. }
  412. }
  413. PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_error) {
  414. #define _MIN_SIZE 1.0
  415. #define _MAX_LENGTH 20
  416. int face_count = p_array.size();
  417. PoolVector<Face3>::Read facesr = p_array.read();
  418. const Face3 *faces = facesr.ptr();
  419. AABB global_aabb;
  420. for (int i = 0; i < face_count; i++) {
  421. if (i == 0) {
  422. global_aabb = faces[i].get_aabb();
  423. } else {
  424. global_aabb.merge_with(faces[i].get_aabb());
  425. }
  426. }
  427. global_aabb.grow_by(0.01); // Avoid numerical error.
  428. // Determine amount of cells in grid axis.
  429. int div_x, div_y, div_z;
  430. if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH)
  431. div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
  432. else
  433. div_x = _MAX_LENGTH;
  434. if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH)
  435. div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
  436. else
  437. div_y = _MAX_LENGTH;
  438. if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH)
  439. div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
  440. else
  441. div_z = _MAX_LENGTH;
  442. Vector3 voxelsize = global_aabb.size;
  443. voxelsize.x /= div_x;
  444. voxelsize.y /= div_y;
  445. voxelsize.z /= div_z;
  446. // Create and initialize cells to zero.
  447. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
  448. for (int i = 0; i < div_x; i++) {
  449. cell_status[i] = memnew_arr(uint8_t *, div_y);
  450. for (int j = 0; j < div_y; j++) {
  451. cell_status[i][j] = memnew_arr(uint8_t, div_z);
  452. for (int k = 0; k < div_z; k++) {
  453. cell_status[i][j][k] = 0;
  454. }
  455. }
  456. }
  457. // Plot faces into cells.
  458. for (int i = 0; i < face_count; i++) {
  459. Face3 f = faces[i];
  460. for (int j = 0; j < 3; j++) {
  461. f.vertex[j] -= global_aabb.position;
  462. }
  463. _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
  464. }
  465. // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
  466. for (int i = 0; i < div_x; i++) {
  467. for (int j = 0; j < div_y; j++) {
  468. _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
  469. _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
  470. }
  471. }
  472. for (int i = 0; i < div_z; i++) {
  473. for (int j = 0; j < div_y; j++) {
  474. _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
  475. _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
  476. }
  477. }
  478. for (int i = 0; i < div_x; i++) {
  479. for (int j = 0; j < div_z; j++) {
  480. _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
  481. _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
  482. }
  483. }
  484. // Build faces for the inside-outside cell divisors.
  485. PoolVector<Face3> wrapped_faces;
  486. for (int i = 0; i < div_x; i++) {
  487. for (int j = 0; j < div_y; j++) {
  488. for (int k = 0; k < div_z; k++) {
  489. _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
  490. }
  491. }
  492. }
  493. // Transform face vertices to global coords.
  494. int wrapped_faces_count = wrapped_faces.size();
  495. PoolVector<Face3>::Write wrapped_facesw = wrapped_faces.write();
  496. Face3 *wrapped_faces_ptr = wrapped_facesw.ptr();
  497. for (int i = 0; i < wrapped_faces_count; i++) {
  498. for (int j = 0; j < 3; j++) {
  499. Vector3 &v = wrapped_faces_ptr[i].vertex[j];
  500. v = v * voxelsize;
  501. v += global_aabb.position;
  502. }
  503. }
  504. // clean up grid
  505. for (int i = 0; i < div_x; i++) {
  506. for (int j = 0; j < div_y; j++) {
  507. memdelete_arr(cell_status[i][j]);
  508. }
  509. memdelete_arr(cell_status[i]);
  510. }
  511. memdelete_arr(cell_status);
  512. if (p_error)
  513. *p_error = voxelsize.length();
  514. return wrapped_faces;
  515. }
  516. Vector<Vector<Vector2> > Geometry::decompose_polygon_in_convex(Vector<Point2> polygon) {
  517. Vector<Vector<Vector2> > decomp;
  518. List<TriangulatorPoly> in_poly, out_poly;
  519. TriangulatorPoly inp;
  520. inp.Init(polygon.size());
  521. for (int i = 0; i < polygon.size(); i++) {
  522. inp.GetPoint(i) = polygon[i];
  523. }
  524. inp.SetOrientation(TRIANGULATOR_CCW);
  525. in_poly.push_back(inp);
  526. TriangulatorPartition tpart;
  527. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  528. ERR_PRINT("Convex decomposing failed!");
  529. return decomp;
  530. }
  531. decomp.resize(out_poly.size());
  532. int idx = 0;
  533. for (List<TriangulatorPoly>::Element *I = out_poly.front(); I; I = I->next()) {
  534. TriangulatorPoly &tp = I->get();
  535. decomp.write[idx].resize(tp.GetNumPoints());
  536. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  537. decomp.write[idx].write[i] = tp.GetPoint(i);
  538. }
  539. idx++;
  540. }
  541. return decomp;
  542. }
  543. Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes) {
  544. MeshData mesh;
  545. #define SUBPLANE_SIZE 1024.0
  546. real_t subplane_size = 1024.0; // Should compute this from the actual plane.
  547. for (int i = 0; i < p_planes.size(); i++) {
  548. Plane p = p_planes[i];
  549. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  550. if (ABS(p.normal.dot(ref)) > 0.95)
  551. ref = Vector3(0.0, 0.0, 1.0); // Change axis.
  552. Vector3 right = p.normal.cross(ref).normalized();
  553. Vector3 up = p.normal.cross(right).normalized();
  554. Vector<Vector3> vertices;
  555. Vector3 center = p.get_any_point();
  556. // make a quad clockwise
  557. vertices.push_back(center - up * subplane_size + right * subplane_size);
  558. vertices.push_back(center - up * subplane_size - right * subplane_size);
  559. vertices.push_back(center + up * subplane_size - right * subplane_size);
  560. vertices.push_back(center + up * subplane_size + right * subplane_size);
  561. for (int j = 0; j < p_planes.size(); j++) {
  562. if (j == i)
  563. continue;
  564. Vector<Vector3> new_vertices;
  565. Plane clip = p_planes[j];
  566. if (clip.normal.dot(p.normal) > 0.95)
  567. continue;
  568. if (vertices.size() < 3)
  569. break;
  570. for (int k = 0; k < vertices.size(); k++) {
  571. int k_n = (k + 1) % vertices.size();
  572. Vector3 edge0_A = vertices[k];
  573. Vector3 edge1_A = vertices[k_n];
  574. real_t dist0 = clip.distance_to(edge0_A);
  575. real_t dist1 = clip.distance_to(edge1_A);
  576. if (dist0 <= 0) { // Behind plane.
  577. new_vertices.push_back(vertices[k]);
  578. }
  579. // Check for different sides and non coplanar.
  580. if ((dist0 * dist1) < 0) {
  581. // Calculate intersection.
  582. Vector3 rel = edge1_A - edge0_A;
  583. real_t den = clip.normal.dot(rel);
  584. if (Math::is_zero_approx(den))
  585. continue; // Point too short.
  586. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
  587. Vector3 inters = edge0_A + rel * dist;
  588. new_vertices.push_back(inters);
  589. }
  590. }
  591. vertices = new_vertices;
  592. }
  593. if (vertices.size() < 3)
  594. continue;
  595. // Result is a clockwise face.
  596. MeshData::Face face;
  597. // Add face indices.
  598. for (int j = 0; j < vertices.size(); j++) {
  599. int idx = -1;
  600. for (int k = 0; k < mesh.vertices.size(); k++) {
  601. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001) {
  602. idx = k;
  603. break;
  604. }
  605. }
  606. if (idx == -1) {
  607. idx = mesh.vertices.size();
  608. mesh.vertices.push_back(vertices[j]);
  609. }
  610. face.indices.push_back(idx);
  611. }
  612. face.plane = p;
  613. mesh.faces.push_back(face);
  614. // Add edge.
  615. for (int j = 0; j < face.indices.size(); j++) {
  616. int a = face.indices[j];
  617. int b = face.indices[(j + 1) % face.indices.size()];
  618. bool found = false;
  619. for (int k = 0; k < mesh.edges.size(); k++) {
  620. if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
  621. found = true;
  622. break;
  623. }
  624. if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
  625. found = true;
  626. break;
  627. }
  628. }
  629. if (found)
  630. continue;
  631. MeshData::Edge edge;
  632. edge.a = a;
  633. edge.b = b;
  634. mesh.edges.push_back(edge);
  635. }
  636. }
  637. return mesh;
  638. }
  639. PoolVector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {
  640. PoolVector<Plane> planes;
  641. planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
  642. planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
  643. planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
  644. planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
  645. planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
  646. planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
  647. return planes;
  648. }
  649. PoolVector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  650. PoolVector<Plane> planes;
  651. for (int i = 0; i < p_sides; i++) {
  652. Vector3 normal;
  653. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  654. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  655. planes.push_back(Plane(normal, p_radius));
  656. }
  657. Vector3 axis;
  658. axis[p_axis] = 1.0;
  659. planes.push_back(Plane(axis, p_height * 0.5));
  660. planes.push_back(Plane(-axis, p_height * 0.5));
  661. return planes;
  662. }
  663. PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  664. PoolVector<Plane> planes;
  665. Vector3 axis;
  666. axis[p_axis] = 1.0;
  667. Vector3 axis_neg;
  668. axis_neg[(p_axis + 1) % 3] = 1.0;
  669. axis_neg[(p_axis + 2) % 3] = 1.0;
  670. axis_neg[p_axis] = -1.0;
  671. for (int i = 0; i < p_lons; i++) {
  672. Vector3 normal;
  673. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_lons);
  674. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_lons);
  675. planes.push_back(Plane(normal, p_radius));
  676. for (int j = 1; j <= p_lats; j++) {
  677. // FIXME: This is stupid.
  678. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  679. Vector3 pos = angle * p_radius;
  680. planes.push_back(Plane(pos, angle));
  681. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  682. }
  683. }
  684. return planes;
  685. }
  686. PoolVector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  687. PoolVector<Plane> planes;
  688. Vector3 axis;
  689. axis[p_axis] = 1.0;
  690. Vector3 axis_neg;
  691. axis_neg[(p_axis + 1) % 3] = 1.0;
  692. axis_neg[(p_axis + 2) % 3] = 1.0;
  693. axis_neg[p_axis] = -1.0;
  694. for (int i = 0; i < p_sides; i++) {
  695. Vector3 normal;
  696. normal[(p_axis + 1) % 3] = Math::cos(i * (2.0 * Math_PI) / p_sides);
  697. normal[(p_axis + 2) % 3] = Math::sin(i * (2.0 * Math_PI) / p_sides);
  698. planes.push_back(Plane(normal, p_radius));
  699. for (int j = 1; j <= p_lats; j++) {
  700. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  701. Vector3 pos = axis * p_height * 0.5 + angle * p_radius;
  702. planes.push_back(Plane(pos, angle));
  703. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  704. }
  705. }
  706. return planes;
  707. }
  708. struct _AtlasWorkRect {
  709. Size2i s;
  710. Point2i p;
  711. int idx;
  712. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
  713. };
  714. struct _AtlasWorkRectResult {
  715. Vector<_AtlasWorkRect> result;
  716. int max_w;
  717. int max_h;
  718. };
  719. void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  720. // Super simple, almost brute force scanline stacking fitter.
  721. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  722. // resulting atlas is somehow square. This is necessary because video cards have limits.
  723. // On texture size (usually 2048 or 4096), so the more square a texture, the more chances.
  724. // It will work in every hardware.
  725. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  726. // 256x8192 atlas (won't work anywhere).
  727. ERR_FAIL_COND(p_rects.size() == 0);
  728. Vector<_AtlasWorkRect> wrects;
  729. wrects.resize(p_rects.size());
  730. for (int i = 0; i < p_rects.size(); i++) {
  731. wrects.write[i].s = p_rects[i];
  732. wrects.write[i].idx = i;
  733. }
  734. wrects.sort();
  735. int widest = wrects[0].s.width;
  736. Vector<_AtlasWorkRectResult> results;
  737. for (int i = 0; i <= 12; i++) {
  738. int w = 1 << i;
  739. int max_h = 0;
  740. int max_w = 0;
  741. if (w < widest)
  742. continue;
  743. Vector<int> hmax;
  744. hmax.resize(w);
  745. for (int j = 0; j < w; j++)
  746. hmax.write[j] = 0;
  747. // Place them.
  748. int ofs = 0;
  749. int limit_h = 0;
  750. for (int j = 0; j < wrects.size(); j++) {
  751. if (ofs + wrects[j].s.width > w) {
  752. ofs = 0;
  753. }
  754. int from_y = 0;
  755. for (int k = 0; k < wrects[j].s.width; k++) {
  756. if (hmax[ofs + k] > from_y)
  757. from_y = hmax[ofs + k];
  758. }
  759. wrects.write[j].p.x = ofs;
  760. wrects.write[j].p.y = from_y;
  761. int end_h = from_y + wrects[j].s.height;
  762. int end_w = ofs + wrects[j].s.width;
  763. if (ofs == 0)
  764. limit_h = end_h;
  765. for (int k = 0; k < wrects[j].s.width; k++) {
  766. hmax.write[ofs + k] = end_h;
  767. }
  768. if (end_h > max_h)
  769. max_h = end_h;
  770. if (end_w > max_w)
  771. max_w = end_w;
  772. if (ofs == 0 || end_h > limit_h) // While h limit not reached, keep stacking.
  773. ofs += wrects[j].s.width;
  774. }
  775. _AtlasWorkRectResult result;
  776. result.result = wrects;
  777. result.max_h = max_h;
  778. result.max_w = max_w;
  779. results.push_back(result);
  780. }
  781. // Find the result with the best aspect ratio.
  782. int best = -1;
  783. real_t best_aspect = 1e20;
  784. for (int i = 0; i < results.size(); i++) {
  785. real_t h = next_power_of_2(results[i].max_h);
  786. real_t w = next_power_of_2(results[i].max_w);
  787. real_t aspect = h > w ? h / w : w / h;
  788. if (aspect < best_aspect) {
  789. best = i;
  790. best_aspect = aspect;
  791. }
  792. }
  793. r_result.resize(p_rects.size());
  794. for (int i = 0; i < p_rects.size(); i++) {
  795. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  796. }
  797. r_size = Size2(results[best].max_w, results[best].max_h);
  798. }
  799. 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) {
  800. using namespace ClipperLib;
  801. ClipType op = ctUnion;
  802. switch (p_op) {
  803. case OPERATION_UNION: op = ctUnion; break;
  804. case OPERATION_DIFFERENCE: op = ctDifference; break;
  805. case OPERATION_INTERSECTION: op = ctIntersection; break;
  806. case OPERATION_XOR: op = ctXor; break;
  807. }
  808. Path path_a, path_b;
  809. // Need to scale points (Clipper's requirement for robust computation).
  810. for (int i = 0; i != p_polypath_a.size(); ++i) {
  811. path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR);
  812. }
  813. for (int i = 0; i != p_polypath_b.size(); ++i) {
  814. path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR);
  815. }
  816. Clipper clp;
  817. clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0.
  818. clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip.
  819. Paths paths;
  820. if (is_a_open) {
  821. PolyTree tree; // Needed to populate polylines.
  822. clp.Execute(op, tree);
  823. OpenPathsFromPolyTree(tree, paths);
  824. } else {
  825. clp.Execute(op, paths); // Works on closed polygons only.
  826. }
  827. // Have to scale points down now.
  828. Vector<Vector<Point2> > polypaths;
  829. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  830. Vector<Vector2> polypath;
  831. const Path &scaled_path = paths[i];
  832. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  833. polypath.push_back(Point2(
  834. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  835. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  836. }
  837. polypaths.push_back(polypath);
  838. }
  839. return polypaths;
  840. }
  841. Vector<Vector<Point2> > Geometry::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  842. using namespace ClipperLib;
  843. JoinType jt = jtSquare;
  844. switch (p_join_type) {
  845. case JOIN_SQUARE: jt = jtSquare; break;
  846. case JOIN_ROUND: jt = jtRound; break;
  847. case JOIN_MITER: jt = jtMiter; break;
  848. }
  849. EndType et = etClosedPolygon;
  850. switch (p_end_type) {
  851. case END_POLYGON: et = etClosedPolygon; break;
  852. case END_JOINED: et = etClosedLine; break;
  853. case END_BUTT: et = etOpenButt; break;
  854. case END_SQUARE: et = etOpenSquare; break;
  855. case END_ROUND: et = etOpenRound; break;
  856. }
  857. ClipperOffset co(2.0, 0.25 * SCALE_FACTOR); // Defaults from ClipperOffset.
  858. Path path;
  859. // Need to scale points (Clipper's requirement for robust computation).
  860. for (int i = 0; i != p_polypath.size(); ++i) {
  861. path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR);
  862. }
  863. co.AddPath(path, jt, et);
  864. Paths paths;
  865. co.Execute(paths, p_delta * SCALE_FACTOR); // Inflate/deflate.
  866. // Have to scale points down now.
  867. Vector<Vector<Point2> > polypaths;
  868. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  869. Vector<Vector2> polypath;
  870. const Path &scaled_path = paths[i];
  871. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  872. polypath.push_back(Point2(
  873. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  874. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  875. }
  876. polypaths.push_back(polypath);
  877. }
  878. return polypaths;
  879. }
  880. Vector<Vector3> Geometry::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count) {
  881. Vector<Vector3> points;
  882. // Iterate through every unique combination of any three planes.
  883. for (int i = p_plane_count - 1; i >= 0; i--) {
  884. for (int j = i - 1; j >= 0; j--) {
  885. for (int k = j - 1; k >= 0; k--) {
  886. // Find the point where these planes all cross over (if they
  887. // do at all).
  888. Vector3 convex_shape_point;
  889. if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
  890. // See if any *other* plane excludes this point because it's
  891. // on the wrong side.
  892. bool excluded = false;
  893. for (int n = 0; n < p_plane_count; n++) {
  894. if (n != i && n != j && n != k) {
  895. real_t dp = p_planes[n].normal.dot(convex_shape_point);
  896. if (dp - p_planes[n].d > CMP_EPSILON) {
  897. excluded = true;
  898. break;
  899. }
  900. }
  901. }
  902. // Only add the point if it passed all tests.
  903. if (!excluded) {
  904. points.push_back(convex_shape_point);
  905. }
  906. }
  907. }
  908. }
  909. }
  910. return points;
  911. }