geometry.cpp 26 KB

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