geometry.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  1. /**************************************************************************/
  2. /* geometry.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.h"
  31. #include "core/local_vector.h"
  32. #include "core/print_string.h"
  33. #include "thirdparty/misc/clipper.hpp"
  34. #include "thirdparty/misc/triangulator.h"
  35. #define STB_RECT_PACK_IMPLEMENTATION
  36. #include "thirdparty/stb_rect_pack/stb_rect_pack.h"
  37. #define SCALE_FACTOR 100000.0 // Based on CMP_EPSILON.
  38. void Geometry::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) {
  39. // Based on David Eberly's Computation of Distance Between Line Segments algorithm.
  40. Vector3 p = p_p1 - p_p0;
  41. Vector3 q = p_q1 - p_q0;
  42. Vector3 r = p_p0 - p_q0;
  43. real_t a = p.dot(p);
  44. real_t b = p.dot(q);
  45. real_t c = q.dot(q);
  46. real_t d = p.dot(r);
  47. real_t e = q.dot(r);
  48. real_t s = 0.0f;
  49. real_t t = 0.0f;
  50. real_t det = a * c - b * b;
  51. if (det > CMP_EPSILON) {
  52. // Non-parallel segments
  53. real_t bte = b * e;
  54. real_t ctd = c * d;
  55. if (bte <= ctd) {
  56. // s <= 0.0f
  57. if (e <= 0.0f) {
  58. // t <= 0.0f
  59. s = (-d >= a ? 1 : (-d > 0.0f ? -d / a : 0.0f));
  60. t = 0.0f;
  61. } else if (e < c) {
  62. // 0.0f < t < 1
  63. s = 0.0f;
  64. t = e / c;
  65. } else {
  66. // t >= 1
  67. s = (b - d >= a ? 1 : (b - d > 0.0f ? (b - d) / a : 0.0f));
  68. t = 1;
  69. }
  70. } else {
  71. // s > 0.0f
  72. s = bte - ctd;
  73. if (s >= det) {
  74. // s >= 1
  75. if (b + e <= 0.0f) {
  76. // t <= 0.0f
  77. s = (-d <= 0.0f ? 0.0f : (-d < a ? -d / a : 1));
  78. t = 0.0f;
  79. } else if (b + e < c) {
  80. // 0.0f < t < 1
  81. s = 1;
  82. t = (b + e) / c;
  83. } else {
  84. // t >= 1
  85. s = (b - d <= 0.0f ? 0.0f : (b - d < a ? (b - d) / a : 1));
  86. t = 1;
  87. }
  88. } else {
  89. // 0.0f < s < 1
  90. real_t ate = a * e;
  91. real_t btd = b * d;
  92. if (ate <= btd) {
  93. // t <= 0.0f
  94. s = (-d <= 0.0f ? 0.0f : (-d >= a ? 1 : -d / a));
  95. t = 0.0f;
  96. } else {
  97. // t > 0.0f
  98. t = ate - btd;
  99. if (t >= det) {
  100. // t >= 1
  101. s = (b - d <= 0.0f ? 0.0f : (b - d >= a ? 1 : (b - d) / a));
  102. t = 1;
  103. } else {
  104. // 0.0f < t < 1
  105. s /= det;
  106. t /= det;
  107. }
  108. }
  109. }
  110. }
  111. } else {
  112. // Parallel segments
  113. if (e <= 0.0f) {
  114. s = (-d <= 0.0f ? 0.0f : (-d >= a ? 1 : -d / a));
  115. t = 0.0f;
  116. } else if (e >= c) {
  117. s = (b - d <= 0.0f ? 0.0f : (b - d >= a ? 1 : (b - d) / a));
  118. t = 1;
  119. } else {
  120. s = 0.0f;
  121. t = e / c;
  122. }
  123. }
  124. r_ps = (1 - s) * p_p0 + s * p_p1;
  125. r_qt = (1 - t) * p_q0 + t * p_q1;
  126. }
  127. real_t Geometry::get_closest_distance_between_segments(const Vector3 &p_p0, const Vector3 &p_p1, const Vector3 &p_q0, const Vector3 &p_q1) {
  128. Vector3 ps;
  129. Vector3 qt;
  130. get_closest_points_between_segments(p_p0, p_p1, p_q0, p_q1, ps, qt);
  131. Vector3 st = qt - ps;
  132. return st.length();
  133. }
  134. void Geometry::OccluderMeshData::clear() {
  135. faces.clear();
  136. vertices.clear();
  137. }
  138. void Geometry::MeshData::clear() {
  139. faces.clear();
  140. edges.clear();
  141. vertices.clear();
  142. }
  143. void Geometry::MeshData::optimize_vertices() {
  144. Map<int, int> vtx_remap;
  145. for (int i = 0; i < faces.size(); i++) {
  146. for (int j = 0; j < faces[i].indices.size(); j++) {
  147. int idx = faces[i].indices[j];
  148. if (!vtx_remap.has(idx)) {
  149. int ni = vtx_remap.size();
  150. vtx_remap[idx] = ni;
  151. }
  152. faces.write[i].indices.write[j] = vtx_remap[idx];
  153. }
  154. }
  155. for (int i = 0; i < edges.size(); i++) {
  156. int a = edges[i].a;
  157. int b = edges[i].b;
  158. if (!vtx_remap.has(a)) {
  159. int ni = vtx_remap.size();
  160. vtx_remap[a] = ni;
  161. }
  162. if (!vtx_remap.has(b)) {
  163. int ni = vtx_remap.size();
  164. vtx_remap[b] = ni;
  165. }
  166. edges.write[i].a = vtx_remap[a];
  167. edges.write[i].b = vtx_remap[b];
  168. }
  169. Vector<Vector3> new_vertices;
  170. new_vertices.resize(vtx_remap.size());
  171. for (int i = 0; i < vertices.size(); i++) {
  172. if (vtx_remap.has(i)) {
  173. new_vertices.write[vtx_remap[i]] = vertices[i];
  174. }
  175. }
  176. vertices = new_vertices;
  177. }
  178. struct _FaceClassify {
  179. struct _Link {
  180. int face;
  181. int edge;
  182. void clear() {
  183. face = -1;
  184. edge = -1;
  185. }
  186. _Link() {
  187. face = -1;
  188. edge = -1;
  189. }
  190. };
  191. bool valid;
  192. int group;
  193. _Link links[3];
  194. Face3 face;
  195. _FaceClassify() {
  196. group = -1;
  197. valid = false;
  198. };
  199. };
  200. static bool _connect_faces(_FaceClassify *p_faces, int len, int p_group) {
  201. // Connect faces, error will occur if an edge is shared between more than 2 faces.
  202. // Clear connections.
  203. bool error = false;
  204. for (int i = 0; i < len; i++) {
  205. for (int j = 0; j < 3; j++) {
  206. p_faces[i].links[j].clear();
  207. }
  208. }
  209. for (int i = 0; i < len; i++) {
  210. if (p_faces[i].group != p_group) {
  211. continue;
  212. }
  213. for (int j = i + 1; j < len; j++) {
  214. if (p_faces[j].group != p_group) {
  215. continue;
  216. }
  217. for (int k = 0; k < 3; k++) {
  218. Vector3 vi1 = p_faces[i].face.vertex[k];
  219. Vector3 vi2 = p_faces[i].face.vertex[(k + 1) % 3];
  220. for (int l = 0; l < 3; l++) {
  221. Vector3 vj2 = p_faces[j].face.vertex[l];
  222. Vector3 vj1 = p_faces[j].face.vertex[(l + 1) % 3];
  223. if (vi1.distance_to(vj1) < 0.00001f &&
  224. vi2.distance_to(vj2) < 0.00001f) {
  225. if (p_faces[i].links[k].face != -1) {
  226. ERR_PRINT("already linked\n");
  227. error = true;
  228. break;
  229. }
  230. if (p_faces[j].links[l].face != -1) {
  231. ERR_PRINT("already linked\n");
  232. error = true;
  233. break;
  234. }
  235. p_faces[i].links[k].face = j;
  236. p_faces[i].links[k].edge = l;
  237. p_faces[j].links[l].face = i;
  238. p_faces[j].links[l].edge = k;
  239. }
  240. }
  241. if (error) {
  242. break;
  243. }
  244. }
  245. if (error) {
  246. break;
  247. }
  248. }
  249. if (error) {
  250. break;
  251. }
  252. }
  253. for (int i = 0; i < len; i++) {
  254. p_faces[i].valid = true;
  255. for (int j = 0; j < 3; j++) {
  256. if (p_faces[i].links[j].face == -1) {
  257. p_faces[i].valid = false;
  258. }
  259. }
  260. }
  261. return error;
  262. }
  263. static bool _group_face(_FaceClassify *p_faces, int len, int p_index, int p_group) {
  264. if (p_faces[p_index].group >= 0) {
  265. return false;
  266. }
  267. p_faces[p_index].group = p_group;
  268. for (int i = 0; i < 3; i++) {
  269. ERR_FAIL_INDEX_V(p_faces[p_index].links[i].face, len, true);
  270. _group_face(p_faces, len, p_faces[p_index].links[i].face, p_group);
  271. }
  272. return true;
  273. }
  274. PoolVector<PoolVector<Face3>> Geometry::separate_objects(PoolVector<Face3> p_array) {
  275. PoolVector<PoolVector<Face3>> objects;
  276. int len = p_array.size();
  277. PoolVector<Face3>::Read r = p_array.read();
  278. const Face3 *arrayptr = r.ptr();
  279. PoolVector<_FaceClassify> fc;
  280. fc.resize(len);
  281. PoolVector<_FaceClassify>::Write fcw = fc.write();
  282. _FaceClassify *_fcptr = fcw.ptr();
  283. for (int i = 0; i < len; i++) {
  284. _fcptr[i].face = arrayptr[i];
  285. }
  286. bool error = _connect_faces(_fcptr, len, -1);
  287. ERR_FAIL_COND_V_MSG(error, PoolVector<PoolVector<Face3>>(), "Invalid geometry.");
  288. // Group connected faces in separate objects.
  289. int group = 0;
  290. for (int i = 0; i < len; i++) {
  291. if (!_fcptr[i].valid) {
  292. continue;
  293. }
  294. if (_group_face(_fcptr, len, i, group)) {
  295. group++;
  296. }
  297. }
  298. // Group connected faces in separate objects.
  299. for (int i = 0; i < len; i++) {
  300. _fcptr[i].face = arrayptr[i];
  301. }
  302. if (group >= 0) {
  303. objects.resize(group);
  304. PoolVector<PoolVector<Face3>>::Write obw = objects.write();
  305. PoolVector<Face3> *group_faces = obw.ptr();
  306. for (int i = 0; i < len; i++) {
  307. if (!_fcptr[i].valid) {
  308. continue;
  309. }
  310. if (_fcptr[i].group >= 0 && _fcptr[i].group < group) {
  311. group_faces[_fcptr[i].group].push_back(_fcptr[i].face);
  312. }
  313. }
  314. }
  315. return objects;
  316. }
  317. /*** GEOMETRY WRAPPER ***/
  318. enum _CellFlags {
  319. _CELL_SOLID = 1,
  320. _CELL_EXTERIOR = 2,
  321. _CELL_STEP_MASK = 0x1C,
  322. _CELL_STEP_NONE = 0 << 2,
  323. _CELL_STEP_Y_POS = 1 << 2,
  324. _CELL_STEP_Y_NEG = 2 << 2,
  325. _CELL_STEP_X_POS = 3 << 2,
  326. _CELL_STEP_X_NEG = 4 << 2,
  327. _CELL_STEP_Z_POS = 5 << 2,
  328. _CELL_STEP_Z_NEG = 6 << 2,
  329. _CELL_STEP_DONE = 7 << 2,
  330. _CELL_PREV_MASK = 0xE0,
  331. _CELL_PREV_NONE = 0 << 5,
  332. _CELL_PREV_Y_POS = 1 << 5,
  333. _CELL_PREV_Y_NEG = 2 << 5,
  334. _CELL_PREV_X_POS = 3 << 5,
  335. _CELL_PREV_X_NEG = 4 << 5,
  336. _CELL_PREV_Z_POS = 5 << 5,
  337. _CELL_PREV_Z_NEG = 6 << 5,
  338. _CELL_PREV_FIRST = 7 << 5,
  339. };
  340. 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) {
  341. AABB aabb(Vector3(x, y, z), Vector3(len_x, len_y, len_z));
  342. aabb.position = aabb.position * voxelsize;
  343. aabb.size = aabb.size * voxelsize;
  344. if (!p_face.intersects_aabb(aabb)) {
  345. return;
  346. }
  347. if (len_x == 1 && len_y == 1 && len_z == 1) {
  348. p_cell_status[x][y][z] = _CELL_SOLID;
  349. return;
  350. }
  351. int div_x = len_x > 1 ? 2 : 1;
  352. int div_y = len_y > 1 ? 2 : 1;
  353. int div_z = len_z > 1 ? 2 : 1;
  354. #define _SPLIT(m_i, m_div, m_v, m_len_v, m_new_v, m_new_len_v) \
  355. if (m_div == 1) { \
  356. m_new_v = m_v; \
  357. m_new_len_v = 1; \
  358. } else if (m_i == 0) { \
  359. m_new_v = m_v; \
  360. m_new_len_v = m_len_v / 2; \
  361. } else { \
  362. m_new_v = m_v + m_len_v / 2; \
  363. m_new_len_v = m_len_v - m_len_v / 2; \
  364. }
  365. int new_x;
  366. int new_len_x;
  367. int new_y;
  368. int new_len_y;
  369. int new_z;
  370. int new_len_z;
  371. for (int i = 0; i < div_x; i++) {
  372. _SPLIT(i, div_x, x, len_x, new_x, new_len_x);
  373. for (int j = 0; j < div_y; j++) {
  374. _SPLIT(j, div_y, y, len_y, new_y, new_len_y);
  375. for (int k = 0; k < div_z; k++) {
  376. _SPLIT(k, div_z, z, len_z, new_z, new_len_z);
  377. _plot_face(p_cell_status, new_x, new_y, new_z, new_len_x, new_len_y, new_len_z, voxelsize, p_face);
  378. }
  379. }
  380. }
  381. }
  382. 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) {
  383. if (p_cell_status[x][y][z] & 3) {
  384. return; // Nothing to do, already used and/or visited.
  385. }
  386. p_cell_status[x][y][z] = _CELL_PREV_FIRST;
  387. while (true) {
  388. uint8_t &c = p_cell_status[x][y][z];
  389. if ((c & _CELL_STEP_MASK) == _CELL_STEP_NONE) {
  390. // Haven't been in here, mark as outside.
  391. p_cell_status[x][y][z] |= _CELL_EXTERIOR;
  392. }
  393. if ((c & _CELL_STEP_MASK) != _CELL_STEP_DONE) {
  394. // If not done, increase step.
  395. c += 1 << 2;
  396. }
  397. if ((c & _CELL_STEP_MASK) == _CELL_STEP_DONE) {
  398. // Go back.
  399. switch (c & _CELL_PREV_MASK) {
  400. case _CELL_PREV_FIRST: {
  401. return;
  402. } break;
  403. case _CELL_PREV_Y_POS: {
  404. y++;
  405. ERR_FAIL_COND(y >= len_y);
  406. } break;
  407. case _CELL_PREV_Y_NEG: {
  408. y--;
  409. ERR_FAIL_COND(y < 0);
  410. } break;
  411. case _CELL_PREV_X_POS: {
  412. x++;
  413. ERR_FAIL_COND(x >= len_x);
  414. } break;
  415. case _CELL_PREV_X_NEG: {
  416. x--;
  417. ERR_FAIL_COND(x < 0);
  418. } break;
  419. case _CELL_PREV_Z_POS: {
  420. z++;
  421. ERR_FAIL_COND(z >= len_z);
  422. } break;
  423. case _CELL_PREV_Z_NEG: {
  424. z--;
  425. ERR_FAIL_COND(z < 0);
  426. } break;
  427. default: {
  428. ERR_FAIL();
  429. }
  430. }
  431. continue;
  432. }
  433. int next_x = x, next_y = y, next_z = z;
  434. uint8_t prev = 0;
  435. switch (c & _CELL_STEP_MASK) {
  436. case _CELL_STEP_Y_POS: {
  437. next_y++;
  438. prev = _CELL_PREV_Y_NEG;
  439. } break;
  440. case _CELL_STEP_Y_NEG: {
  441. next_y--;
  442. prev = _CELL_PREV_Y_POS;
  443. } break;
  444. case _CELL_STEP_X_POS: {
  445. next_x++;
  446. prev = _CELL_PREV_X_NEG;
  447. } break;
  448. case _CELL_STEP_X_NEG: {
  449. next_x--;
  450. prev = _CELL_PREV_X_POS;
  451. } break;
  452. case _CELL_STEP_Z_POS: {
  453. next_z++;
  454. prev = _CELL_PREV_Z_NEG;
  455. } break;
  456. case _CELL_STEP_Z_NEG: {
  457. next_z--;
  458. prev = _CELL_PREV_Z_POS;
  459. } break;
  460. default:
  461. ERR_FAIL();
  462. }
  463. if (next_x < 0 || next_x >= len_x) {
  464. continue;
  465. }
  466. if (next_y < 0 || next_y >= len_y) {
  467. continue;
  468. }
  469. if (next_z < 0 || next_z >= len_z) {
  470. continue;
  471. }
  472. if (p_cell_status[next_x][next_y][next_z] & 3) {
  473. continue;
  474. }
  475. x = next_x;
  476. y = next_y;
  477. z = next_z;
  478. p_cell_status[x][y][z] |= prev;
  479. }
  480. }
  481. 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) {
  482. ERR_FAIL_INDEX(x, len_x);
  483. ERR_FAIL_INDEX(y, len_y);
  484. ERR_FAIL_INDEX(z, len_z);
  485. if (p_cell_status[x][y][z] & _CELL_EXTERIOR) {
  486. return;
  487. }
  488. #define vert(m_idx) Vector3(((m_idx)&4) >> 2, ((m_idx)&2) >> 1, (m_idx)&1)
  489. static const uint8_t indices[6][4] = {
  490. { 7, 6, 4, 5 },
  491. { 7, 3, 2, 6 },
  492. { 7, 5, 1, 3 },
  493. { 0, 2, 3, 1 },
  494. { 0, 1, 5, 4 },
  495. { 0, 4, 6, 2 },
  496. };
  497. for (int i = 0; i < 6; i++) {
  498. Vector3 face_points[4];
  499. int disp_x = x + ((i % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  500. int disp_y = y + (((i - 1) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  501. int disp_z = z + (((i - 2) % 3) == 0 ? ((i < 3) ? 1 : -1) : 0);
  502. bool plot = false;
  503. if (disp_x < 0 || disp_x >= len_x) {
  504. plot = true;
  505. }
  506. if (disp_y < 0 || disp_y >= len_y) {
  507. plot = true;
  508. }
  509. if (disp_z < 0 || disp_z >= len_z) {
  510. plot = true;
  511. }
  512. if (!plot && (p_cell_status[disp_x][disp_y][disp_z] & _CELL_EXTERIOR)) {
  513. plot = true;
  514. }
  515. if (!plot) {
  516. continue;
  517. }
  518. for (int j = 0; j < 4; j++) {
  519. face_points[j] = vert(indices[i][j]) + Vector3(x, y, z);
  520. }
  521. p_faces.push_back(
  522. Face3(
  523. face_points[0],
  524. face_points[1],
  525. face_points[2]));
  526. p_faces.push_back(
  527. Face3(
  528. face_points[2],
  529. face_points[3],
  530. face_points[0]));
  531. }
  532. }
  533. PoolVector<Face3> Geometry::wrap_geometry(PoolVector<Face3> p_array, real_t *p_error) {
  534. #define _MIN_SIZE 1.0f
  535. #define _MAX_LENGTH 20
  536. int face_count = p_array.size();
  537. PoolVector<Face3>::Read facesr = p_array.read();
  538. const Face3 *faces = facesr.ptr();
  539. AABB global_aabb;
  540. for (int i = 0; i < face_count; i++) {
  541. if (i == 0) {
  542. global_aabb = faces[i].get_aabb();
  543. } else {
  544. global_aabb.merge_with(faces[i].get_aabb());
  545. }
  546. }
  547. global_aabb.grow_by(0.01f); // Avoid numerical error.
  548. // Determine amount of cells in grid axis.
  549. int div_x, div_y, div_z;
  550. if (global_aabb.size.x / _MIN_SIZE < _MAX_LENGTH) {
  551. div_x = (int)(global_aabb.size.x / _MIN_SIZE) + 1;
  552. } else {
  553. div_x = _MAX_LENGTH;
  554. }
  555. if (global_aabb.size.y / _MIN_SIZE < _MAX_LENGTH) {
  556. div_y = (int)(global_aabb.size.y / _MIN_SIZE) + 1;
  557. } else {
  558. div_y = _MAX_LENGTH;
  559. }
  560. if (global_aabb.size.z / _MIN_SIZE < _MAX_LENGTH) {
  561. div_z = (int)(global_aabb.size.z / _MIN_SIZE) + 1;
  562. } else {
  563. div_z = _MAX_LENGTH;
  564. }
  565. Vector3 voxelsize = global_aabb.size;
  566. voxelsize.x /= div_x;
  567. voxelsize.y /= div_y;
  568. voxelsize.z /= div_z;
  569. // Create and initialize cells to zero.
  570. uint8_t ***cell_status = memnew_arr(uint8_t **, div_x);
  571. for (int i = 0; i < div_x; i++) {
  572. cell_status[i] = memnew_arr(uint8_t *, div_y);
  573. for (int j = 0; j < div_y; j++) {
  574. cell_status[i][j] = memnew_arr(uint8_t, div_z);
  575. for (int k = 0; k < div_z; k++) {
  576. cell_status[i][j][k] = 0;
  577. }
  578. }
  579. }
  580. // Plot faces into cells.
  581. for (int i = 0; i < face_count; i++) {
  582. Face3 f = faces[i];
  583. for (int j = 0; j < 3; j++) {
  584. f.vertex[j] -= global_aabb.position;
  585. }
  586. _plot_face(cell_status, 0, 0, 0, div_x, div_y, div_z, voxelsize, f);
  587. }
  588. // Determine which cells connect to the outside by traversing the outside and recursively flood-fill marking.
  589. for (int i = 0; i < div_x; i++) {
  590. for (int j = 0; j < div_y; j++) {
  591. _mark_outside(cell_status, i, j, 0, div_x, div_y, div_z);
  592. _mark_outside(cell_status, i, j, div_z - 1, div_x, div_y, div_z);
  593. }
  594. }
  595. for (int i = 0; i < div_z; i++) {
  596. for (int j = 0; j < div_y; j++) {
  597. _mark_outside(cell_status, 0, j, i, div_x, div_y, div_z);
  598. _mark_outside(cell_status, div_x - 1, j, i, div_x, div_y, div_z);
  599. }
  600. }
  601. for (int i = 0; i < div_x; i++) {
  602. for (int j = 0; j < div_z; j++) {
  603. _mark_outside(cell_status, i, 0, j, div_x, div_y, div_z);
  604. _mark_outside(cell_status, i, div_y - 1, j, div_x, div_y, div_z);
  605. }
  606. }
  607. // Build faces for the inside-outside cell divisors.
  608. PoolVector<Face3> wrapped_faces;
  609. for (int i = 0; i < div_x; i++) {
  610. for (int j = 0; j < div_y; j++) {
  611. for (int k = 0; k < div_z; k++) {
  612. _build_faces(cell_status, i, j, k, div_x, div_y, div_z, wrapped_faces);
  613. }
  614. }
  615. }
  616. // Transform face vertices to global coords.
  617. int wrapped_faces_count = wrapped_faces.size();
  618. PoolVector<Face3>::Write wrapped_facesw = wrapped_faces.write();
  619. Face3 *wrapped_faces_ptr = wrapped_facesw.ptr();
  620. for (int i = 0; i < wrapped_faces_count; i++) {
  621. for (int j = 0; j < 3; j++) {
  622. Vector3 &v = wrapped_faces_ptr[i].vertex[j];
  623. v = v * voxelsize;
  624. v += global_aabb.position;
  625. }
  626. }
  627. // clean up grid
  628. for (int i = 0; i < div_x; i++) {
  629. for (int j = 0; j < div_y; j++) {
  630. memdelete_arr(cell_status[i][j]);
  631. }
  632. memdelete_arr(cell_status[i]);
  633. }
  634. memdelete_arr(cell_status);
  635. if (p_error) {
  636. *p_error = voxelsize.length();
  637. }
  638. return wrapped_faces;
  639. }
  640. Vector<Vector<Vector2>> Geometry::decompose_polygon_in_convex(Vector<Point2> polygon) {
  641. Vector<Vector<Vector2>> decomp;
  642. List<TriangulatorPoly> in_poly, out_poly;
  643. TriangulatorPoly inp;
  644. inp.Init(polygon.size());
  645. for (int i = 0; i < polygon.size(); i++) {
  646. inp.GetPoint(i) = polygon[i];
  647. }
  648. inp.SetOrientation(TRIANGULATOR_CCW);
  649. in_poly.push_back(inp);
  650. TriangulatorPartition tpart;
  651. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  652. ERR_PRINT("Convex decomposing failed!");
  653. return decomp;
  654. }
  655. decomp.resize(out_poly.size());
  656. int idx = 0;
  657. for (List<TriangulatorPoly>::Element *I = out_poly.front(); I; I = I->next()) {
  658. TriangulatorPoly &tp = I->get();
  659. decomp.write[idx].resize(tp.GetNumPoints());
  660. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  661. decomp.write[idx].write[i] = tp.GetPoint(i);
  662. }
  663. idx++;
  664. }
  665. return decomp;
  666. }
  667. Geometry::MeshData Geometry::build_convex_mesh(const PoolVector<Plane> &p_planes) {
  668. MeshData mesh;
  669. #define SUBPLANE_SIZE 1024.0
  670. real_t subplane_size = 1024.0; // Should compute this from the actual plane.
  671. for (int i = 0; i < p_planes.size(); i++) {
  672. Plane p = p_planes[i];
  673. Vector3 ref = Vector3(0.0, 1.0, 0.0);
  674. if (ABS(p.normal.dot(ref)) > 0.95f) {
  675. ref = Vector3(0.0, 0.0, 1.0); // Change axis.
  676. }
  677. Vector3 right = p.normal.cross(ref).normalized();
  678. Vector3 up = p.normal.cross(right).normalized();
  679. Vector<Vector3> vertices;
  680. Vector3 center = p.get_any_point();
  681. // make a quad clockwise
  682. vertices.push_back(center - up * subplane_size + right * subplane_size);
  683. vertices.push_back(center - up * subplane_size - right * subplane_size);
  684. vertices.push_back(center + up * subplane_size - right * subplane_size);
  685. vertices.push_back(center + up * subplane_size + right * subplane_size);
  686. for (int j = 0; j < p_planes.size(); j++) {
  687. if (j == i) {
  688. continue;
  689. }
  690. Vector<Vector3> new_vertices;
  691. Plane clip = p_planes[j];
  692. if (clip.normal.dot(p.normal) > 0.95f) {
  693. continue;
  694. }
  695. if (vertices.size() < 3) {
  696. break;
  697. }
  698. for (int k = 0; k < vertices.size(); k++) {
  699. int k_n = (k + 1) % vertices.size();
  700. Vector3 edge0_A = vertices[k];
  701. Vector3 edge1_A = vertices[k_n];
  702. real_t dist0 = clip.distance_to(edge0_A);
  703. real_t dist1 = clip.distance_to(edge1_A);
  704. if (dist0 <= 0) { // Behind plane.
  705. new_vertices.push_back(vertices[k]);
  706. }
  707. // Check for different sides and non coplanar.
  708. if ((dist0 * dist1) < 0) {
  709. // Calculate intersection.
  710. Vector3 rel = edge1_A - edge0_A;
  711. real_t den = clip.normal.dot(rel);
  712. if (Math::is_zero_approx(den)) {
  713. continue; // Point too short.
  714. }
  715. real_t dist = -(clip.normal.dot(edge0_A) - clip.d) / den;
  716. Vector3 inters = edge0_A + rel * dist;
  717. new_vertices.push_back(inters);
  718. }
  719. }
  720. vertices = new_vertices;
  721. }
  722. if (vertices.size() < 3) {
  723. continue;
  724. }
  725. // Result is a clockwise face.
  726. MeshData::Face face;
  727. // Add face indices.
  728. for (int j = 0; j < vertices.size(); j++) {
  729. int idx = -1;
  730. for (int k = 0; k < mesh.vertices.size(); k++) {
  731. if (mesh.vertices[k].distance_to(vertices[j]) < 0.001f) {
  732. idx = k;
  733. break;
  734. }
  735. }
  736. if (idx == -1) {
  737. idx = mesh.vertices.size();
  738. mesh.vertices.push_back(vertices[j]);
  739. }
  740. face.indices.push_back(idx);
  741. }
  742. face.plane = p;
  743. mesh.faces.push_back(face);
  744. // Add edge.
  745. for (int j = 0; j < face.indices.size(); j++) {
  746. int a = face.indices[j];
  747. int b = face.indices[(j + 1) % face.indices.size()];
  748. bool found = false;
  749. for (int k = 0; k < mesh.edges.size(); k++) {
  750. if (mesh.edges[k].a == a && mesh.edges[k].b == b) {
  751. found = true;
  752. break;
  753. }
  754. if (mesh.edges[k].b == a && mesh.edges[k].a == b) {
  755. found = true;
  756. break;
  757. }
  758. }
  759. if (found) {
  760. continue;
  761. }
  762. MeshData::Edge edge;
  763. edge.a = a;
  764. edge.b = b;
  765. mesh.edges.push_back(edge);
  766. }
  767. }
  768. return mesh;
  769. }
  770. PoolVector<Plane> Geometry::build_box_planes(const Vector3 &p_extents) {
  771. PoolVector<Plane> planes;
  772. planes.push_back(Plane(Vector3(1, 0, 0), p_extents.x));
  773. planes.push_back(Plane(Vector3(-1, 0, 0), p_extents.x));
  774. planes.push_back(Plane(Vector3(0, 1, 0), p_extents.y));
  775. planes.push_back(Plane(Vector3(0, -1, 0), p_extents.y));
  776. planes.push_back(Plane(Vector3(0, 0, 1), p_extents.z));
  777. planes.push_back(Plane(Vector3(0, 0, -1), p_extents.z));
  778. return planes;
  779. }
  780. PoolVector<Plane> Geometry::build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis) {
  781. ERR_FAIL_INDEX_V(p_axis, 3, PoolVector<Plane>());
  782. PoolVector<Plane> planes;
  783. for (int i = 0; i < p_sides; i++) {
  784. Vector3 normal;
  785. normal[(p_axis + 1) % 3] = Math::cos(i * (real_t)(2.0 * Math_PI) / p_sides);
  786. normal[(p_axis + 2) % 3] = Math::sin(i * (real_t)(2.0 * Math_PI) / p_sides);
  787. planes.push_back(Plane(normal, p_radius));
  788. }
  789. Vector3 axis;
  790. axis[p_axis] = 1.0;
  791. planes.push_back(Plane(axis, p_height * 0.5f));
  792. planes.push_back(Plane(-axis, p_height * 0.5f));
  793. return planes;
  794. }
  795. PoolVector<Plane> Geometry::build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis) {
  796. ERR_FAIL_INDEX_V(p_axis, 3, PoolVector<Plane>());
  797. PoolVector<Plane> planes;
  798. Vector3 axis;
  799. axis[p_axis] = 1;
  800. Vector3 axis_neg;
  801. axis_neg[(p_axis + 1) % 3] = 1;
  802. axis_neg[(p_axis + 2) % 3] = 1;
  803. axis_neg[p_axis] = -1;
  804. for (int i = 0; i < p_lons; i++) {
  805. Vector3 normal;
  806. normal[(p_axis + 1) % 3] = Math::cos(i * (real_t)(2.0 * Math_PI) / p_lons);
  807. normal[(p_axis + 2) % 3] = Math::sin(i * (real_t)(2.0 * Math_PI) / p_lons);
  808. planes.push_back(Plane(normal, p_radius));
  809. for (int j = 1; j <= p_lats; j++) {
  810. // FIXME: This is stupid.
  811. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  812. Vector3 pos = angle * p_radius;
  813. planes.push_back(Plane(pos, angle));
  814. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  815. }
  816. }
  817. return planes;
  818. }
  819. PoolVector<Plane> Geometry::build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis) {
  820. ERR_FAIL_INDEX_V(p_axis, 3, PoolVector<Plane>());
  821. PoolVector<Plane> planes;
  822. Vector3 axis;
  823. axis[p_axis] = 1;
  824. Vector3 axis_neg;
  825. axis_neg[(p_axis + 1) % 3] = 1;
  826. axis_neg[(p_axis + 2) % 3] = 1;
  827. axis_neg[p_axis] = -1;
  828. for (int i = 0; i < p_sides; i++) {
  829. Vector3 normal;
  830. normal[(p_axis + 1) % 3] = Math::cos(i * (real_t)(2.0 * Math_PI) / p_sides);
  831. normal[(p_axis + 2) % 3] = Math::sin(i * (real_t)(2.0 * Math_PI) / p_sides);
  832. planes.push_back(Plane(normal, p_radius));
  833. for (int j = 1; j <= p_lats; j++) {
  834. Vector3 angle = normal.linear_interpolate(axis, j / (real_t)p_lats).normalized();
  835. Vector3 pos = axis * p_height * 0.5f + angle * p_radius;
  836. planes.push_back(Plane(pos, angle));
  837. planes.push_back(Plane(pos * axis_neg, angle * axis_neg));
  838. }
  839. }
  840. return planes;
  841. }
  842. struct _AtlasWorkRect {
  843. Size2i s;
  844. Point2i p;
  845. int idx;
  846. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; }
  847. };
  848. struct _AtlasWorkRectResult {
  849. Vector<_AtlasWorkRect> result;
  850. int max_w;
  851. int max_h;
  852. };
  853. void Geometry::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  854. // Super simple, almost brute force scanline stacking fitter.
  855. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  856. // resulting atlas is somehow square. This is necessary because video cards have limits.
  857. // On texture size (usually 2048 or 4096), so the more square a texture, the more chances.
  858. // It will work in every hardware.
  859. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  860. // 256x8192 atlas (won't work anywhere).
  861. ERR_FAIL_COND(p_rects.size() == 0);
  862. for (int i = 0; i < p_rects.size(); i++) {
  863. ERR_FAIL_COND(p_rects[i].width <= 0);
  864. ERR_FAIL_COND(p_rects[i].height <= 0);
  865. }
  866. Vector<_AtlasWorkRect> wrects;
  867. wrects.resize(p_rects.size());
  868. for (int i = 0; i < p_rects.size(); i++) {
  869. wrects.write[i].s = p_rects[i];
  870. wrects.write[i].idx = i;
  871. }
  872. wrects.sort();
  873. int widest = wrects[0].s.width;
  874. Vector<_AtlasWorkRectResult> results;
  875. for (int i = 0; i <= 12; i++) {
  876. int w = 1 << i;
  877. int max_h = 0;
  878. int max_w = 0;
  879. if (w < widest) {
  880. continue;
  881. }
  882. Vector<int> hmax;
  883. hmax.resize(w);
  884. for (int j = 0; j < w; j++) {
  885. hmax.write[j] = 0;
  886. }
  887. // Place them.
  888. int ofs = 0;
  889. int limit_h = 0;
  890. for (int j = 0; j < wrects.size(); j++) {
  891. if (ofs + wrects[j].s.width > w) {
  892. ofs = 0;
  893. }
  894. int from_y = 0;
  895. for (int k = 0; k < wrects[j].s.width; k++) {
  896. if (hmax[ofs + k] > from_y) {
  897. from_y = hmax[ofs + k];
  898. }
  899. }
  900. wrects.write[j].p.x = ofs;
  901. wrects.write[j].p.y = from_y;
  902. int end_h = from_y + wrects[j].s.height;
  903. int end_w = ofs + wrects[j].s.width;
  904. if (ofs == 0) {
  905. limit_h = end_h;
  906. }
  907. for (int k = 0; k < wrects[j].s.width; k++) {
  908. hmax.write[ofs + k] = end_h;
  909. }
  910. if (end_h > max_h) {
  911. max_h = end_h;
  912. }
  913. if (end_w > max_w) {
  914. max_w = end_w;
  915. }
  916. if (ofs == 0 || end_h > limit_h) { // While h limit not reached, keep stacking.
  917. ofs += wrects[j].s.width;
  918. }
  919. }
  920. _AtlasWorkRectResult result;
  921. result.result = wrects;
  922. result.max_h = max_h;
  923. result.max_w = max_w;
  924. results.push_back(result);
  925. }
  926. // Find the result with the best aspect ratio.
  927. int best = -1;
  928. real_t best_aspect = 1e20;
  929. for (int i = 0; i < results.size(); i++) {
  930. real_t h = next_power_of_2(results[i].max_h);
  931. real_t w = next_power_of_2(results[i].max_w);
  932. real_t aspect = h > w ? h / w : w / h;
  933. if (aspect < best_aspect) {
  934. best = i;
  935. best_aspect = aspect;
  936. }
  937. }
  938. r_result.resize(p_rects.size());
  939. for (int i = 0; i < p_rects.size(); i++) {
  940. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  941. }
  942. r_size = Size2(results[best].max_w, results[best].max_h);
  943. }
  944. 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) {
  945. using namespace ClipperLib;
  946. ClipType op = ctUnion;
  947. switch (p_op) {
  948. case OPERATION_UNION:
  949. op = ctUnion;
  950. break;
  951. case OPERATION_DIFFERENCE:
  952. op = ctDifference;
  953. break;
  954. case OPERATION_INTERSECTION:
  955. op = ctIntersection;
  956. break;
  957. case OPERATION_XOR:
  958. op = ctXor;
  959. break;
  960. }
  961. Path path_a, path_b;
  962. // Need to scale points (Clipper's requirement for robust computation).
  963. for (int i = 0; i != p_polypath_a.size(); ++i) {
  964. path_a << IntPoint(p_polypath_a[i].x * (real_t)SCALE_FACTOR, p_polypath_a[i].y * (real_t)SCALE_FACTOR);
  965. }
  966. for (int i = 0; i != p_polypath_b.size(); ++i) {
  967. path_b << IntPoint(p_polypath_b[i].x * (real_t)SCALE_FACTOR, p_polypath_b[i].y * (real_t)SCALE_FACTOR);
  968. }
  969. Clipper clp;
  970. clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0.
  971. clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip.
  972. Paths paths;
  973. if (is_a_open) {
  974. PolyTree tree; // Needed to populate polylines.
  975. clp.Execute(op, tree);
  976. OpenPathsFromPolyTree(tree, paths);
  977. } else {
  978. clp.Execute(op, paths); // Works on closed polygons only.
  979. }
  980. // Have to scale points down now.
  981. Vector<Vector<Point2>> polypaths;
  982. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  983. Vector<Vector2> polypath;
  984. const Path &scaled_path = paths[i];
  985. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  986. polypath.push_back(Point2(
  987. static_cast<real_t>(scaled_path[j].X) / (real_t)SCALE_FACTOR,
  988. static_cast<real_t>(scaled_path[j].Y) / (real_t)SCALE_FACTOR));
  989. }
  990. polypaths.push_back(polypath);
  991. }
  992. return polypaths;
  993. }
  994. Vector<Vector<Point2>> Geometry::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  995. using namespace ClipperLib;
  996. JoinType jt = jtSquare;
  997. switch (p_join_type) {
  998. case JOIN_SQUARE:
  999. jt = jtSquare;
  1000. break;
  1001. case JOIN_ROUND:
  1002. jt = jtRound;
  1003. break;
  1004. case JOIN_MITER:
  1005. jt = jtMiter;
  1006. break;
  1007. }
  1008. EndType et = etClosedPolygon;
  1009. switch (p_end_type) {
  1010. case END_POLYGON:
  1011. et = etClosedPolygon;
  1012. break;
  1013. case END_JOINED:
  1014. et = etClosedLine;
  1015. break;
  1016. case END_BUTT:
  1017. et = etOpenButt;
  1018. break;
  1019. case END_SQUARE:
  1020. et = etOpenSquare;
  1021. break;
  1022. case END_ROUND:
  1023. et = etOpenRound;
  1024. break;
  1025. }
  1026. ClipperOffset co(2.0f, 0.25f * (real_t)SCALE_FACTOR); // Defaults from ClipperOffset.
  1027. Path path;
  1028. // Need to scale points (Clipper's requirement for robust computation).
  1029. for (int i = 0; i != p_polypath.size(); ++i) {
  1030. path << IntPoint(p_polypath[i].x * (real_t)SCALE_FACTOR, p_polypath[i].y * (real_t)SCALE_FACTOR);
  1031. }
  1032. co.AddPath(path, jt, et);
  1033. Paths paths;
  1034. co.Execute(paths, p_delta * (real_t)SCALE_FACTOR); // Inflate/deflate.
  1035. // Have to scale points down now.
  1036. Vector<Vector<Point2>> polypaths;
  1037. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  1038. Vector<Vector2> polypath;
  1039. const Path &scaled_path = paths[i];
  1040. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  1041. polypath.push_back(Point2(
  1042. static_cast<real_t>(scaled_path[j].X) / (real_t)SCALE_FACTOR,
  1043. static_cast<real_t>(scaled_path[j].Y) / (real_t)SCALE_FACTOR));
  1044. }
  1045. polypaths.push_back(polypath);
  1046. }
  1047. return polypaths;
  1048. }
  1049. real_t Geometry::calculate_convex_hull_volume(const Geometry::MeshData &p_md) {
  1050. if (!p_md.vertices.size()) {
  1051. return 0;
  1052. }
  1053. // find center
  1054. Vector3 center;
  1055. for (int n = 0; n < p_md.vertices.size(); n++) {
  1056. center += p_md.vertices[n];
  1057. }
  1058. center /= p_md.vertices.size();
  1059. Face3 fa;
  1060. real_t volume = 0.0;
  1061. // volume of each cone is 1/3 * height * area of face
  1062. for (int f = 0; f < p_md.faces.size(); f++) {
  1063. const Geometry::MeshData::Face &face = p_md.faces[f];
  1064. real_t height = 0.0;
  1065. real_t face_area = 0.0;
  1066. for (int c = 0; c < face.indices.size() - 2; c++) {
  1067. fa.vertex[0] = p_md.vertices[face.indices[0]];
  1068. fa.vertex[1] = p_md.vertices[face.indices[c + 1]];
  1069. fa.vertex[2] = p_md.vertices[face.indices[c + 2]];
  1070. if (!c) {
  1071. // calculate height
  1072. Plane plane(fa.vertex[0], fa.vertex[1], fa.vertex[2]);
  1073. height = -plane.distance_to(center);
  1074. }
  1075. face_area += Math::sqrt(fa.get_twice_area_squared());
  1076. }
  1077. volume += face_area * height;
  1078. }
  1079. volume *= (real_t)((1.0 / 3.0) * 0.5);
  1080. return volume;
  1081. }
  1082. // note this function is slow, because it builds meshes etc. Not ideal to use in realtime.
  1083. // Planes must face OUTWARD from the center of the convex hull, by convention.
  1084. bool Geometry::convex_hull_intersects_convex_hull(const Plane *p_planes_a, int p_plane_count_a, const Plane *p_planes_b, int p_plane_count_b) {
  1085. if (!p_plane_count_a || !p_plane_count_b) {
  1086. return false;
  1087. }
  1088. // OR alternative approach, we can call compute_convex_mesh_points()
  1089. // with both sets of planes, to get an intersection. Not sure which method is
  1090. // faster... this may be faster with more complex hulls.
  1091. // the usual silliness to get from one vector format to another...
  1092. PoolVector<Plane> planes_a;
  1093. PoolVector<Plane> planes_b;
  1094. {
  1095. planes_a.resize(p_plane_count_a);
  1096. PoolVector<Plane>::Write w = planes_a.write();
  1097. memcpy(w.ptr(), p_planes_a, p_plane_count_a * sizeof(Plane));
  1098. }
  1099. {
  1100. planes_b.resize(p_plane_count_b);
  1101. PoolVector<Plane>::Write w = planes_b.write();
  1102. memcpy(w.ptr(), p_planes_b, p_plane_count_b * sizeof(Plane));
  1103. }
  1104. Geometry::MeshData md_A = build_convex_mesh(planes_a);
  1105. Geometry::MeshData md_B = build_convex_mesh(planes_b);
  1106. // hull can't be built
  1107. if (!md_A.vertices.size() || !md_B.vertices.size()) {
  1108. return false;
  1109. }
  1110. // first check the points against the planes
  1111. for (int p = 0; p < p_plane_count_a; p++) {
  1112. const Plane &plane = p_planes_a[p];
  1113. for (int n = 0; n < md_B.vertices.size(); n++) {
  1114. if (!plane.is_point_over(md_B.vertices[n])) {
  1115. return true;
  1116. }
  1117. }
  1118. }
  1119. for (int p = 0; p < p_plane_count_b; p++) {
  1120. const Plane &plane = p_planes_b[p];
  1121. for (int n = 0; n < md_A.vertices.size(); n++) {
  1122. if (!plane.is_point_over(md_A.vertices[n])) {
  1123. return true;
  1124. }
  1125. }
  1126. }
  1127. // now check edges
  1128. for (int n = 0; n < md_A.edges.size(); n++) {
  1129. const Vector3 &pt_a = md_A.vertices[md_A.edges[n].a];
  1130. const Vector3 &pt_b = md_A.vertices[md_A.edges[n].b];
  1131. if (segment_intersects_convex(pt_a, pt_b, p_planes_b, p_plane_count_b, nullptr, nullptr)) {
  1132. return true;
  1133. }
  1134. }
  1135. for (int n = 0; n < md_B.edges.size(); n++) {
  1136. const Vector3 &pt_a = md_B.vertices[md_B.edges[n].a];
  1137. const Vector3 &pt_b = md_B.vertices[md_B.edges[n].b];
  1138. if (segment_intersects_convex(pt_a, pt_b, p_planes_a, p_plane_count_a, nullptr, nullptr)) {
  1139. return true;
  1140. }
  1141. }
  1142. return false;
  1143. }
  1144. Vector<Vector3> Geometry::compute_convex_mesh_points(const Plane *p_planes, int p_plane_count, real_t p_epsilon) {
  1145. Vector<Vector3> points;
  1146. // Iterate through every unique combination of any three planes.
  1147. for (int i = p_plane_count - 1; i >= 0; i--) {
  1148. for (int j = i - 1; j >= 0; j--) {
  1149. for (int k = j - 1; k >= 0; k--) {
  1150. // Find the point where these planes all cross over (if they
  1151. // do at all).
  1152. Vector3 convex_shape_point;
  1153. if (p_planes[i].intersect_3(p_planes[j], p_planes[k], &convex_shape_point)) {
  1154. // See if any *other* plane excludes this point because it's
  1155. // on the wrong side.
  1156. bool excluded = false;
  1157. for (int n = 0; n < p_plane_count; n++) {
  1158. if (n != i && n != j && n != k) {
  1159. real_t dist = p_planes[n].distance_to(convex_shape_point);
  1160. if (dist > p_epsilon) {
  1161. excluded = true;
  1162. break;
  1163. }
  1164. }
  1165. }
  1166. // Only add the point if it passed all tests.
  1167. if (!excluded) {
  1168. points.push_back(convex_shape_point);
  1169. }
  1170. }
  1171. }
  1172. }
  1173. }
  1174. return points;
  1175. }
  1176. Vector<Geometry::PackRectsResult> Geometry::partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size) {
  1177. Vector<stbrp_node> nodes;
  1178. nodes.resize(p_atlas_size.width);
  1179. memset(nodes.ptrw(), 0, sizeof(stbrp_node) * nodes.size());
  1180. stbrp_context context;
  1181. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  1182. Vector<stbrp_rect> rects;
  1183. rects.resize(p_sizes.size());
  1184. for (int i = 0; i < p_sizes.size(); i++) {
  1185. rects.write[i].id = i;
  1186. rects.write[i].w = p_sizes[i].width;
  1187. rects.write[i].h = p_sizes[i].height;
  1188. rects.write[i].x = 0;
  1189. rects.write[i].y = 0;
  1190. rects.write[i].was_packed = 0;
  1191. }
  1192. stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  1193. Vector<PackRectsResult> ret;
  1194. ret.resize(p_sizes.size());
  1195. for (int i = 0; i < p_sizes.size(); i++) {
  1196. ret.write[rects[i].id] = { rects[i].x, rects[i].y, static_cast<bool>(rects[i].was_packed) };
  1197. }
  1198. return ret;
  1199. }
  1200. // Expects polygon as a triangle fan
  1201. real_t Geometry::find_polygon_area(const Vector3 *p_verts, int p_num_verts) {
  1202. if (!p_verts || (p_num_verts < 3)) {
  1203. return 0.0;
  1204. }
  1205. Face3 f;
  1206. f.vertex[0] = p_verts[0];
  1207. f.vertex[1] = p_verts[1];
  1208. f.vertex[2] = p_verts[1];
  1209. real_t area = 0.0;
  1210. for (int n = 2; n < p_num_verts; n++) {
  1211. f.vertex[1] = f.vertex[2];
  1212. f.vertex[2] = p_verts[n];
  1213. area += Math::sqrt(f.get_twice_area_squared());
  1214. }
  1215. return area * 0.5f;
  1216. }
  1217. // adapted from:
  1218. // https://stackoverflow.com/questions/6989100/sort-points-in-clockwise-order
  1219. void Geometry::sort_polygon_winding(Vector<Vector2> &r_verts, bool p_clockwise) {
  1220. // sort winding order of a (primarily convex) polygon.
  1221. // It can handle some concave polygons, but not
  1222. // where a vertex 'goes back on' a previous vertex ..
  1223. // i.e. it will change the shape in some concave cases.
  1224. struct ElementComparator {
  1225. Vector2 center;
  1226. bool operator()(const Vector2 &a, const Vector2 &b) const {
  1227. if (a.x - center.x >= 0 && b.x - center.x < 0) {
  1228. return true;
  1229. }
  1230. if (a.x - center.x < 0 && b.x - center.x >= 0) {
  1231. return false;
  1232. }
  1233. if (a.x - center.x == 0 && b.x - center.x == 0) {
  1234. if (a.y - center.y >= 0 || b.y - center.y >= 0) {
  1235. return a.y > b.y;
  1236. }
  1237. return b.y > a.y;
  1238. }
  1239. // compute the cross product of vectors (center -> a) x (center -> b)
  1240. real_t det = (a.x - center.x) * (b.y - center.y) - (b.x - center.x) * (a.y - center.y);
  1241. if (det < 0) {
  1242. return true;
  1243. }
  1244. if (det > 0) {
  1245. return false;
  1246. }
  1247. // points a and b are on the same line from the center
  1248. // check which point is closer to the center
  1249. real_t d1 = (a.x - center.x) * (a.x - center.x) + (a.y - center.y) * (a.y - center.y);
  1250. real_t d2 = (b.x - center.x) * (b.x - center.x) + (b.y - center.y) * (b.y - center.y);
  1251. return d1 > d2;
  1252. }
  1253. };
  1254. int npoints = r_verts.size();
  1255. if (!npoints) {
  1256. return;
  1257. }
  1258. // first calculate center
  1259. Vector2 center;
  1260. for (int n = 0; n < npoints; n++) {
  1261. center += r_verts[n];
  1262. }
  1263. center /= npoints;
  1264. SortArray<Vector2, ElementComparator> sorter;
  1265. sorter.compare.center = center;
  1266. sorter.sort(r_verts.ptrw(), r_verts.size());
  1267. // if not clockwise, reverse order
  1268. if (!p_clockwise) {
  1269. r_verts.invert();
  1270. }
  1271. }
  1272. bool Geometry::verify_indices(const int *p_indices, int p_num_indices, int p_num_vertices) {
  1273. ERR_FAIL_NULL_V(p_indices, false);
  1274. ERR_FAIL_COND_V(p_num_indices < 0, false);
  1275. ERR_FAIL_COND_V(p_num_vertices < 0, false);
  1276. for (int n = 0; n < p_num_indices; n++) {
  1277. if ((unsigned int)p_indices[n] >= (unsigned int)p_num_vertices) {
  1278. return false;
  1279. }
  1280. }
  1281. return true;
  1282. }