geometry_2d.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /**************************************************************************/
  2. /* geometry_2d.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_2d.h"
  31. #include "thirdparty/clipper2/include/clipper2/clipper.h"
  32. #include "thirdparty/misc/polypartition.h"
  33. #define STB_RECT_PACK_IMPLEMENTATION
  34. #include "thirdparty/misc/stb_rect_pack.h"
  35. const int clipper_precision = 5; // Based on CMP_EPSILON.
  36. const double clipper_scale = Math::pow(10.0, clipper_precision);
  37. void Geometry2D::merge_many_polygons(const Vector<Vector<Vector2>> &p_polygons, Vector<Vector<Vector2>> &r_out_polygons, Vector<Vector<Vector2>> &r_out_holes) {
  38. using namespace Clipper2Lib;
  39. PathsD subjects;
  40. for (const Vector<Vector2> &polygon : p_polygons) {
  41. PathD path(polygon.size());
  42. for (int i = 0; i < polygon.size(); i++) {
  43. const Vector2 &point = polygon[i];
  44. path[i] = PointD(point.x, point.y);
  45. }
  46. subjects.push_back(path);
  47. }
  48. PathsD solution = Union(subjects, FillRule::NonZero);
  49. solution = SimplifyPaths(solution, 0.01);
  50. r_out_polygons.clear();
  51. r_out_holes.clear();
  52. for (PathsD::size_type i = 0; i < solution.size(); ++i) {
  53. PathD &path = solution[i];
  54. Vector<Point2> output_polygon;
  55. output_polygon.resize(path.size());
  56. for (PathsD::size_type j = 0; j < path.size(); ++j) {
  57. output_polygon.set(j, Vector2(static_cast<real_t>(path[j].x), static_cast<real_t>(path[j].y)));
  58. }
  59. if (IsPositive(path)) {
  60. r_out_polygons.push_back(output_polygon);
  61. } else {
  62. r_out_holes.push_back(output_polygon);
  63. }
  64. }
  65. }
  66. Vector<Vector<Vector2>> Geometry2D::decompose_many_polygons_in_convex(const Vector<Vector<Point2>> &p_polygons, const Vector<Vector<Point2>> &p_holes) {
  67. Vector<Vector<Vector2>> decomp;
  68. List<TPPLPoly> in_poly, out_poly;
  69. for (const Vector<Vector2> &polygon : p_polygons) {
  70. TPPLPoly inp;
  71. inp.Init(polygon.size());
  72. for (int i = 0; i < polygon.size(); i++) {
  73. inp.GetPoint(i) = polygon[i];
  74. }
  75. inp.SetOrientation(TPPL_ORIENTATION_CCW);
  76. in_poly.push_back(inp);
  77. }
  78. for (const Vector<Vector2> &polygon : p_holes) {
  79. TPPLPoly inp;
  80. inp.Init(polygon.size());
  81. for (int i = 0; i < polygon.size(); i++) {
  82. inp.GetPoint(i) = polygon[i];
  83. }
  84. inp.SetOrientation(TPPL_ORIENTATION_CW);
  85. inp.SetHole(true);
  86. in_poly.push_back(inp);
  87. }
  88. TPPLPartition tpart;
  89. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  90. ERR_PRINT("Convex decomposing failed!");
  91. return decomp;
  92. }
  93. decomp.resize(out_poly.size());
  94. int idx = 0;
  95. for (List<TPPLPoly>::Element *I = out_poly.front(); I; I = I->next()) {
  96. TPPLPoly &tp = I->get();
  97. decomp.write[idx].resize(tp.GetNumPoints());
  98. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  99. decomp.write[idx].write[i] = tp.GetPoint(i);
  100. }
  101. idx++;
  102. }
  103. return decomp;
  104. }
  105. Vector<Vector<Vector2>> Geometry2D::decompose_polygon_in_convex(const Vector<Point2> &p_polygon) {
  106. return Geometry2D::decompose_many_polygons_in_convex({ p_polygon }, {});
  107. }
  108. struct _AtlasWorkRect {
  109. Size2i s;
  110. Point2i p;
  111. int idx = 0;
  112. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; }
  113. };
  114. struct _AtlasWorkRectResult {
  115. Vector<_AtlasWorkRect> result;
  116. int max_w = 0;
  117. int max_h = 0;
  118. };
  119. void Geometry2D::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  120. // Super simple, almost brute force scanline stacking fitter.
  121. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  122. // resulting atlas is somehow square. This is necessary because video cards have limits
  123. // on texture size (usually 2048 or 4096), so the squarer a texture, the more the chances
  124. // that it will work in every hardware.
  125. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  126. // 256x8192 atlas (won't work anywhere).
  127. ERR_FAIL_COND(p_rects.is_empty());
  128. for (int i = 0; i < p_rects.size(); i++) {
  129. ERR_FAIL_COND(p_rects[i].width <= 0);
  130. ERR_FAIL_COND(p_rects[i].height <= 0);
  131. }
  132. Vector<_AtlasWorkRect> wrects;
  133. wrects.resize(p_rects.size());
  134. for (int i = 0; i < p_rects.size(); i++) {
  135. wrects.write[i].s = p_rects[i];
  136. wrects.write[i].idx = i;
  137. }
  138. wrects.sort();
  139. int widest = wrects[0].s.width;
  140. Vector<_AtlasWorkRectResult> results;
  141. for (int i = 0; i <= 12; i++) {
  142. int w = 1 << i;
  143. int max_h = 0;
  144. int max_w = 0;
  145. if (w < widest) {
  146. continue;
  147. }
  148. Vector<int> hmax;
  149. hmax.resize(w);
  150. for (int j = 0; j < w; j++) {
  151. hmax.write[j] = 0;
  152. }
  153. // Place them.
  154. int ofs = 0;
  155. int limit_h = 0;
  156. for (int j = 0; j < wrects.size(); j++) {
  157. if (ofs + wrects[j].s.width > w) {
  158. ofs = 0;
  159. }
  160. int from_y = 0;
  161. for (int k = 0; k < wrects[j].s.width; k++) {
  162. if (hmax[ofs + k] > from_y) {
  163. from_y = hmax[ofs + k];
  164. }
  165. }
  166. wrects.write[j].p.x = ofs;
  167. wrects.write[j].p.y = from_y;
  168. int end_h = from_y + wrects[j].s.height;
  169. int end_w = ofs + wrects[j].s.width;
  170. if (ofs == 0) {
  171. limit_h = end_h;
  172. }
  173. for (int k = 0; k < wrects[j].s.width; k++) {
  174. hmax.write[ofs + k] = end_h;
  175. }
  176. if (end_h > max_h) {
  177. max_h = end_h;
  178. }
  179. if (end_w > max_w) {
  180. max_w = end_w;
  181. }
  182. if (ofs == 0 || end_h > limit_h) { // While h limit not reached, keep stacking.
  183. ofs += wrects[j].s.width;
  184. }
  185. }
  186. _AtlasWorkRectResult result;
  187. result.result = wrects;
  188. result.max_h = max_h;
  189. result.max_w = max_w;
  190. results.push_back(result);
  191. }
  192. // Find the result with the best aspect ratio.
  193. int best = -1;
  194. real_t best_aspect = 1e20;
  195. for (int i = 0; i < results.size(); i++) {
  196. real_t h = next_power_of_2(results[i].max_h);
  197. real_t w = next_power_of_2(results[i].max_w);
  198. real_t aspect = h > w ? h / w : w / h;
  199. if (aspect < best_aspect) {
  200. best = i;
  201. best_aspect = aspect;
  202. }
  203. }
  204. r_result.resize(p_rects.size());
  205. for (int i = 0; i < p_rects.size(); i++) {
  206. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  207. }
  208. r_size = Size2(results[best].max_w, results[best].max_h);
  209. }
  210. Vector<Vector<Point2>> Geometry2D::_polypaths_do_operation(PolyBooleanOperation p_op, const Vector<Point2> &p_polypath_a, const Vector<Point2> &p_polypath_b, bool is_a_open) {
  211. using namespace Clipper2Lib;
  212. ClipType op = ClipType::Union;
  213. switch (p_op) {
  214. case OPERATION_UNION:
  215. op = ClipType::Union;
  216. break;
  217. case OPERATION_DIFFERENCE:
  218. op = ClipType::Difference;
  219. break;
  220. case OPERATION_INTERSECTION:
  221. op = ClipType::Intersection;
  222. break;
  223. case OPERATION_XOR:
  224. op = ClipType::Xor;
  225. break;
  226. }
  227. PathD path_a(p_polypath_a.size());
  228. for (int i = 0; i != p_polypath_a.size(); ++i) {
  229. path_a[i] = PointD(p_polypath_a[i].x, p_polypath_a[i].y);
  230. }
  231. PathD path_b(p_polypath_b.size());
  232. for (int i = 0; i != p_polypath_b.size(); ++i) {
  233. path_b[i] = PointD(p_polypath_b[i].x, p_polypath_b[i].y);
  234. }
  235. ClipperD clp(clipper_precision); // Scale points up internally to attain the desired precision.
  236. clp.PreserveCollinear(false); // Remove redundant vertices.
  237. if (is_a_open) {
  238. clp.AddOpenSubject({ path_a });
  239. } else {
  240. clp.AddSubject({ path_a });
  241. }
  242. clp.AddClip({ path_b });
  243. PathsD paths;
  244. if (is_a_open) {
  245. PolyTreeD tree; // Needed to populate polylines.
  246. clp.Execute(op, FillRule::EvenOdd, tree, paths);
  247. } else {
  248. clp.Execute(op, FillRule::EvenOdd, paths); // Works on closed polygons only.
  249. }
  250. Vector<Vector<Point2>> polypaths;
  251. for (PathsD::size_type i = 0; i < paths.size(); ++i) {
  252. const PathD &path = paths[i];
  253. Vector<Vector2> polypath;
  254. for (PathsD::size_type j = 0; j < path.size(); ++j) {
  255. polypath.push_back(Point2(static_cast<real_t>(path[j].x), static_cast<real_t>(path[j].y)));
  256. }
  257. polypaths.push_back(polypath);
  258. }
  259. return polypaths;
  260. }
  261. Vector<Vector<Point2>> Geometry2D::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  262. using namespace Clipper2Lib;
  263. JoinType jt = JoinType::Square;
  264. switch (p_join_type) {
  265. case JOIN_SQUARE:
  266. jt = JoinType::Square;
  267. break;
  268. case JOIN_ROUND:
  269. jt = JoinType::Round;
  270. break;
  271. case JOIN_MITER:
  272. jt = JoinType::Miter;
  273. break;
  274. }
  275. EndType et = EndType::Polygon;
  276. switch (p_end_type) {
  277. case END_POLYGON:
  278. et = EndType::Polygon;
  279. break;
  280. case END_JOINED:
  281. et = EndType::Joined;
  282. break;
  283. case END_BUTT:
  284. et = EndType::Butt;
  285. break;
  286. case END_SQUARE:
  287. et = EndType::Square;
  288. break;
  289. case END_ROUND:
  290. et = EndType::Round;
  291. break;
  292. }
  293. PathD polypath(p_polypath.size());
  294. for (int i = 0; i != p_polypath.size(); ++i) {
  295. polypath[i] = PointD(p_polypath[i].x, p_polypath[i].y);
  296. }
  297. // Inflate/deflate.
  298. PathsD paths = InflatePaths({ polypath }, p_delta, jt, et, 2.0, clipper_precision, 0.25 * clipper_scale);
  299. // Here the points are scaled up internally and
  300. // the arc_tolerance is scaled accordingly
  301. // to attain the desired precision.
  302. Vector<Vector<Point2>> polypaths;
  303. for (PathsD::size_type i = 0; i < paths.size(); ++i) {
  304. const PathD &path = paths[i];
  305. Vector<Vector2> polypath2;
  306. for (PathsD::size_type j = 0; j < path.size(); ++j) {
  307. polypath2.push_back(Point2(static_cast<real_t>(path[j].x), static_cast<real_t>(path[j].y)));
  308. }
  309. polypaths.push_back(polypath2);
  310. }
  311. return polypaths;
  312. }
  313. Vector<Vector3i> Geometry2D::partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size) {
  314. Vector<stbrp_node> nodes;
  315. nodes.resize(p_atlas_size.width);
  316. memset(nodes.ptrw(), 0, sizeof(stbrp_node) * nodes.size());
  317. stbrp_context context;
  318. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  319. Vector<stbrp_rect> rects;
  320. rects.resize(p_sizes.size());
  321. for (int i = 0; i < p_sizes.size(); i++) {
  322. rects.write[i].id = i;
  323. rects.write[i].w = p_sizes[i].width;
  324. rects.write[i].h = p_sizes[i].height;
  325. rects.write[i].x = 0;
  326. rects.write[i].y = 0;
  327. rects.write[i].was_packed = 0;
  328. }
  329. stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  330. Vector<Vector3i> ret;
  331. ret.resize(p_sizes.size());
  332. for (int i = 0; i < p_sizes.size(); i++) {
  333. ret.write[rects[i].id] = Vector3i(rects[i].x, rects[i].y, rects[i].was_packed != 0 ? 1 : 0);
  334. }
  335. return ret;
  336. }