geometry_2d.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /*************************************************************************/
  2. /* geometry_2d.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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_2d.h"
  31. #include "thirdparty/misc/clipper.hpp"
  32. #include "thirdparty/misc/polypartition.h"
  33. #define STB_RECT_PACK_IMPLEMENTATION
  34. #include "thirdparty/misc/stb_rect_pack.h"
  35. #define SCALE_FACTOR 100000.0 // Based on CMP_EPSILON.
  36. Vector<Vector<Vector2>> Geometry2D::decompose_polygon_in_convex(Vector<Point2> polygon) {
  37. Vector<Vector<Vector2>> decomp;
  38. List<TPPLPoly> in_poly, out_poly;
  39. TPPLPoly inp;
  40. inp.Init(polygon.size());
  41. for (int i = 0; i < polygon.size(); i++) {
  42. inp.GetPoint(i) = polygon[i];
  43. }
  44. inp.SetOrientation(TPPL_ORIENTATION_CCW);
  45. in_poly.push_back(inp);
  46. TPPLPartition tpart;
  47. if (tpart.ConvexPartition_HM(&in_poly, &out_poly) == 0) { // Failed.
  48. ERR_PRINT("Convex decomposing failed!");
  49. return decomp;
  50. }
  51. decomp.resize(out_poly.size());
  52. int idx = 0;
  53. for (List<TPPLPoly>::Element *I = out_poly.front(); I; I = I->next()) {
  54. TPPLPoly &tp = I->get();
  55. decomp.write[idx].resize(tp.GetNumPoints());
  56. for (int64_t i = 0; i < tp.GetNumPoints(); i++) {
  57. decomp.write[idx].write[i] = tp.GetPoint(i);
  58. }
  59. idx++;
  60. }
  61. return decomp;
  62. }
  63. struct _AtlasWorkRect {
  64. Size2i s;
  65. Point2i p;
  66. int idx;
  67. _FORCE_INLINE_ bool operator<(const _AtlasWorkRect &p_r) const { return s.width > p_r.s.width; };
  68. };
  69. struct _AtlasWorkRectResult {
  70. Vector<_AtlasWorkRect> result;
  71. int max_w;
  72. int max_h;
  73. };
  74. void Geometry2D::make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size) {
  75. // Super simple, almost brute force scanline stacking fitter.
  76. // It's pretty basic for now, but it tries to make sure that the aspect ratio of the
  77. // resulting atlas is somehow square. This is necessary because video cards have limits.
  78. // On texture size (usually 2048 or 4096), so the more square a texture, the more chances.
  79. // It will work in every hardware.
  80. // For example, it will prioritize a 1024x1024 atlas (works everywhere) instead of a
  81. // 256x8192 atlas (won't work anywhere).
  82. ERR_FAIL_COND(p_rects.size() == 0);
  83. Vector<_AtlasWorkRect> wrects;
  84. wrects.resize(p_rects.size());
  85. for (int i = 0; i < p_rects.size(); i++) {
  86. wrects.write[i].s = p_rects[i];
  87. wrects.write[i].idx = i;
  88. }
  89. wrects.sort();
  90. int widest = wrects[0].s.width;
  91. Vector<_AtlasWorkRectResult> results;
  92. for (int i = 0; i <= 12; i++) {
  93. int w = 1 << i;
  94. int max_h = 0;
  95. int max_w = 0;
  96. if (w < widest) {
  97. continue;
  98. }
  99. Vector<int> hmax;
  100. hmax.resize(w);
  101. for (int j = 0; j < w; j++) {
  102. hmax.write[j] = 0;
  103. }
  104. // Place them.
  105. int ofs = 0;
  106. int limit_h = 0;
  107. for (int j = 0; j < wrects.size(); j++) {
  108. if (ofs + wrects[j].s.width > w) {
  109. ofs = 0;
  110. }
  111. int from_y = 0;
  112. for (int k = 0; k < wrects[j].s.width; k++) {
  113. if (hmax[ofs + k] > from_y) {
  114. from_y = hmax[ofs + k];
  115. }
  116. }
  117. wrects.write[j].p.x = ofs;
  118. wrects.write[j].p.y = from_y;
  119. int end_h = from_y + wrects[j].s.height;
  120. int end_w = ofs + wrects[j].s.width;
  121. if (ofs == 0) {
  122. limit_h = end_h;
  123. }
  124. for (int k = 0; k < wrects[j].s.width; k++) {
  125. hmax.write[ofs + k] = end_h;
  126. }
  127. if (end_h > max_h) {
  128. max_h = end_h;
  129. }
  130. if (end_w > max_w) {
  131. max_w = end_w;
  132. }
  133. if (ofs == 0 || end_h > limit_h) { // While h limit not reached, keep stacking.
  134. ofs += wrects[j].s.width;
  135. }
  136. }
  137. _AtlasWorkRectResult result;
  138. result.result = wrects;
  139. result.max_h = max_h;
  140. result.max_w = max_w;
  141. results.push_back(result);
  142. }
  143. // Find the result with the best aspect ratio.
  144. int best = -1;
  145. real_t best_aspect = 1e20;
  146. for (int i = 0; i < results.size(); i++) {
  147. real_t h = next_power_of_2(results[i].max_h);
  148. real_t w = next_power_of_2(results[i].max_w);
  149. real_t aspect = h > w ? h / w : w / h;
  150. if (aspect < best_aspect) {
  151. best = i;
  152. best_aspect = aspect;
  153. }
  154. }
  155. r_result.resize(p_rects.size());
  156. for (int i = 0; i < p_rects.size(); i++) {
  157. r_result.write[results[best].result[i].idx] = results[best].result[i].p;
  158. }
  159. r_size = Size2(results[best].max_w, results[best].max_h);
  160. }
  161. 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) {
  162. using namespace ClipperLib;
  163. ClipType op = ctUnion;
  164. switch (p_op) {
  165. case OPERATION_UNION:
  166. op = ctUnion;
  167. break;
  168. case OPERATION_DIFFERENCE:
  169. op = ctDifference;
  170. break;
  171. case OPERATION_INTERSECTION:
  172. op = ctIntersection;
  173. break;
  174. case OPERATION_XOR:
  175. op = ctXor;
  176. break;
  177. }
  178. Path path_a, path_b;
  179. // Need to scale points (Clipper's requirement for robust computation).
  180. for (int i = 0; i != p_polypath_a.size(); ++i) {
  181. path_a << IntPoint(p_polypath_a[i].x * SCALE_FACTOR, p_polypath_a[i].y * SCALE_FACTOR);
  182. }
  183. for (int i = 0; i != p_polypath_b.size(); ++i) {
  184. path_b << IntPoint(p_polypath_b[i].x * SCALE_FACTOR, p_polypath_b[i].y * SCALE_FACTOR);
  185. }
  186. Clipper clp;
  187. clp.AddPath(path_a, ptSubject, !is_a_open); // Forward compatible with Clipper 10.0.0.
  188. clp.AddPath(path_b, ptClip, true); // Polylines cannot be set as clip.
  189. Paths paths;
  190. if (is_a_open) {
  191. PolyTree tree; // Needed to populate polylines.
  192. clp.Execute(op, tree);
  193. OpenPathsFromPolyTree(tree, paths);
  194. } else {
  195. clp.Execute(op, paths); // Works on closed polygons only.
  196. }
  197. // Have to scale points down now.
  198. Vector<Vector<Point2>> polypaths;
  199. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  200. Vector<Vector2> polypath;
  201. const Path &scaled_path = paths[i];
  202. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  203. polypath.push_back(Point2(
  204. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  205. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  206. }
  207. polypaths.push_back(polypath);
  208. }
  209. return polypaths;
  210. }
  211. Vector<Vector<Point2>> Geometry2D::_polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  212. using namespace ClipperLib;
  213. JoinType jt = jtSquare;
  214. switch (p_join_type) {
  215. case JOIN_SQUARE:
  216. jt = jtSquare;
  217. break;
  218. case JOIN_ROUND:
  219. jt = jtRound;
  220. break;
  221. case JOIN_MITER:
  222. jt = jtMiter;
  223. break;
  224. }
  225. EndType et = etClosedPolygon;
  226. switch (p_end_type) {
  227. case END_POLYGON:
  228. et = etClosedPolygon;
  229. break;
  230. case END_JOINED:
  231. et = etClosedLine;
  232. break;
  233. case END_BUTT:
  234. et = etOpenButt;
  235. break;
  236. case END_SQUARE:
  237. et = etOpenSquare;
  238. break;
  239. case END_ROUND:
  240. et = etOpenRound;
  241. break;
  242. }
  243. ClipperOffset co(2.0, 0.25 * SCALE_FACTOR); // Defaults from ClipperOffset.
  244. Path path;
  245. // Need to scale points (Clipper's requirement for robust computation).
  246. for (int i = 0; i != p_polypath.size(); ++i) {
  247. path << IntPoint(p_polypath[i].x * SCALE_FACTOR, p_polypath[i].y * SCALE_FACTOR);
  248. }
  249. co.AddPath(path, jt, et);
  250. Paths paths;
  251. co.Execute(paths, p_delta * SCALE_FACTOR); // Inflate/deflate.
  252. // Have to scale points down now.
  253. Vector<Vector<Point2>> polypaths;
  254. for (Paths::size_type i = 0; i < paths.size(); ++i) {
  255. Vector<Vector2> polypath;
  256. const Path &scaled_path = paths[i];
  257. for (Paths::size_type j = 0; j < scaled_path.size(); ++j) {
  258. polypath.push_back(Point2(
  259. static_cast<real_t>(scaled_path[j].X) / SCALE_FACTOR,
  260. static_cast<real_t>(scaled_path[j].Y) / SCALE_FACTOR));
  261. }
  262. polypaths.push_back(polypath);
  263. }
  264. return polypaths;
  265. }
  266. Vector<Point2i> Geometry2D::pack_rects(const Vector<Size2i> &p_sizes, const Size2i &p_atlas_size) {
  267. Vector<stbrp_node> nodes;
  268. nodes.resize(p_atlas_size.width);
  269. stbrp_context context;
  270. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  271. Vector<stbrp_rect> rects;
  272. rects.resize(p_sizes.size());
  273. for (int i = 0; i < p_sizes.size(); i++) {
  274. rects.write[i].id = 0;
  275. rects.write[i].w = p_sizes[i].width;
  276. rects.write[i].h = p_sizes[i].height;
  277. rects.write[i].x = 0;
  278. rects.write[i].y = 0;
  279. rects.write[i].was_packed = 0;
  280. }
  281. int res = stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  282. if (res == 0) { //pack failed
  283. return Vector<Point2i>();
  284. }
  285. Vector<Point2i> ret;
  286. ret.resize(p_sizes.size());
  287. for (int i = 0; i < p_sizes.size(); i++) {
  288. Point2i r(rects[i].x, rects[i].y);
  289. ret.write[i] = r;
  290. }
  291. return ret;
  292. }
  293. Vector<Vector3i> Geometry2D::partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size) {
  294. Vector<stbrp_node> nodes;
  295. nodes.resize(p_atlas_size.width);
  296. zeromem(nodes.ptrw(), sizeof(stbrp_node) * nodes.size());
  297. stbrp_context context;
  298. stbrp_init_target(&context, p_atlas_size.width, p_atlas_size.height, nodes.ptrw(), p_atlas_size.width);
  299. Vector<stbrp_rect> rects;
  300. rects.resize(p_sizes.size());
  301. for (int i = 0; i < p_sizes.size(); i++) {
  302. rects.write[i].id = i;
  303. rects.write[i].w = p_sizes[i].width;
  304. rects.write[i].h = p_sizes[i].height;
  305. rects.write[i].x = 0;
  306. rects.write[i].y = 0;
  307. rects.write[i].was_packed = 0;
  308. }
  309. stbrp_pack_rects(&context, rects.ptrw(), rects.size());
  310. Vector<Vector3i> ret;
  311. ret.resize(p_sizes.size());
  312. for (int i = 0; i < p_sizes.size(); i++) {
  313. ret.write[rects[i].id] = Vector3i(rects[i].x, rects[i].y, rects[i].was_packed != 0 ? 1 : 0);
  314. }
  315. return ret;
  316. }