geometry_2d.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /**************************************************************************/
  2. /* geometry_2d.h */
  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. #ifndef GEOMETRY_2D_H
  31. #define GEOMETRY_2D_H
  32. #include "core/math/delaunay_2d.h"
  33. #include "core/math/math_funcs.h"
  34. #include "core/math/triangulate.h"
  35. #include "core/math/vector2.h"
  36. #include "core/math/vector2i.h"
  37. #include "core/math/vector3.h"
  38. #include "core/math/vector3i.h"
  39. #include "core/templates/vector.h"
  40. class Geometry2D {
  41. public:
  42. static real_t get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) {
  43. Vector2 d1 = q1 - p1; // Direction vector of segment S1.
  44. Vector2 d2 = q2 - p2; // Direction vector of segment S2.
  45. Vector2 r = p1 - p2;
  46. real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative.
  47. real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative.
  48. real_t f = d2.dot(r);
  49. real_t s, t;
  50. // Check if either or both segments degenerate into points.
  51. if (a <= (real_t)CMP_EPSILON && e <= (real_t)CMP_EPSILON) {
  52. // Both segments degenerate into points.
  53. c1 = p1;
  54. c2 = p2;
  55. return Math::sqrt((c1 - c2).dot(c1 - c2));
  56. }
  57. if (a <= (real_t)CMP_EPSILON) {
  58. // First segment degenerates into a point.
  59. s = 0.0;
  60. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  61. t = CLAMP(t, 0.0f, 1.0f);
  62. } else {
  63. real_t c = d1.dot(r);
  64. if (e <= (real_t)CMP_EPSILON) {
  65. // Second segment degenerates into a point.
  66. t = 0.0;
  67. s = CLAMP(-c / a, 0.0f, 1.0f); // t = 0 => s = (b*t - c) / a = -c / a
  68. } else {
  69. // The general nondegenerate case starts here.
  70. real_t b = d1.dot(d2);
  71. real_t denom = a * e - b * b; // Always nonnegative.
  72. // If segments not parallel, compute closest point on L1 to L2 and
  73. // clamp to segment S1. Else pick arbitrary s (here 0).
  74. if (denom != 0.0f) {
  75. s = CLAMP((b * f - c * e) / denom, 0.0f, 1.0f);
  76. } else {
  77. s = 0.0;
  78. }
  79. // Compute point on L2 closest to S1(s) using
  80. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  81. t = (b * s + f) / e;
  82. //If t in [0,1] done. Else clamp t, recompute s for the new value
  83. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  84. // and clamp s to [0, 1].
  85. if (t < 0.0f) {
  86. t = 0.0;
  87. s = CLAMP(-c / a, 0.0f, 1.0f);
  88. } else if (t > 1.0f) {
  89. t = 1.0;
  90. s = CLAMP((b - c) / a, 0.0f, 1.0f);
  91. }
  92. }
  93. }
  94. c1 = p1 + d1 * s;
  95. c2 = p2 + d2 * t;
  96. return Math::sqrt((c1 - c2).dot(c1 - c2));
  97. }
  98. static Vector2 get_closest_point_to_segment(const Vector2 &p_point, const Vector2 *p_segment) {
  99. Vector2 p = p_point - p_segment[0];
  100. Vector2 n = p_segment[1] - p_segment[0];
  101. real_t l2 = n.length_squared();
  102. if (l2 < 1e-20f) {
  103. return p_segment[0]; // Both points are the same, just give any.
  104. }
  105. real_t d = n.dot(p) / l2;
  106. if (d <= 0.0f) {
  107. return p_segment[0]; // Before first point.
  108. } else if (d >= 1.0f) {
  109. return p_segment[1]; // After first point.
  110. } else {
  111. return p_segment[0] + n * d; // Inside.
  112. }
  113. }
  114. static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
  115. Vector2 an = a - s;
  116. Vector2 bn = b - s;
  117. Vector2 cn = c - s;
  118. bool orientation = an.cross(bn) > 0;
  119. if ((bn.cross(cn) > 0) != orientation) {
  120. return false;
  121. }
  122. return (cn.cross(an) > 0) == orientation;
  123. }
  124. static Vector2 get_closest_point_to_segment_uncapped(const Vector2 &p_point, const Vector2 *p_segment) {
  125. Vector2 p = p_point - p_segment[0];
  126. Vector2 n = p_segment[1] - p_segment[0];
  127. real_t l2 = n.length_squared();
  128. if (l2 < 1e-20f) {
  129. return p_segment[0]; // Both points are the same, just give any.
  130. }
  131. real_t d = n.dot(p) / l2;
  132. return p_segment[0] + n * d; // Inside.
  133. }
  134. // Disable False Positives in MSVC compiler; we correctly check for 0 here to prevent a division by 0.
  135. // See: https://github.com/godotengine/godot/pull/44274
  136. #ifdef _MSC_VER
  137. #pragma warning(disable : 4723)
  138. #endif
  139. static bool line_intersects_line(const Vector2 &p_from_a, const Vector2 &p_dir_a, const Vector2 &p_from_b, const Vector2 &p_dir_b, Vector2 &r_result) {
  140. // See http://paulbourke.net/geometry/pointlineplane/
  141. const real_t denom = p_dir_b.y * p_dir_a.x - p_dir_b.x * p_dir_a.y;
  142. if (Math::is_zero_approx(denom)) { // Parallel?
  143. return false;
  144. }
  145. const Vector2 v = p_from_a - p_from_b;
  146. const real_t t = (p_dir_b.x * v.y - p_dir_b.y * v.x) / denom;
  147. r_result = p_from_a + t * p_dir_a;
  148. return true;
  149. }
  150. // Re-enable division by 0 warning
  151. #ifdef _MSC_VER
  152. #pragma warning(default : 4723)
  153. #endif
  154. static bool segment_intersects_segment(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b, Vector2 *r_result) {
  155. Vector2 B = p_to_a - p_from_a;
  156. Vector2 C = p_from_b - p_from_a;
  157. Vector2 D = p_to_b - p_from_a;
  158. real_t ABlen = B.dot(B);
  159. if (ABlen <= 0) {
  160. return false;
  161. }
  162. Vector2 Bn = B / ABlen;
  163. C = Vector2(C.x * Bn.x + C.y * Bn.y, C.y * Bn.x - C.x * Bn.y);
  164. D = Vector2(D.x * Bn.x + D.y * Bn.y, D.y * Bn.x - D.x * Bn.y);
  165. // Fail if C x B and D x B have the same sign (segments don't intersect).
  166. if ((C.y < (real_t)-CMP_EPSILON && D.y < (real_t)-CMP_EPSILON) || (C.y > (real_t)CMP_EPSILON && D.y > (real_t)CMP_EPSILON)) {
  167. return false;
  168. }
  169. // Fail if segments are parallel or colinear.
  170. // (when A x B == zero, i.e (C - D) x B == zero, i.e C x B == D x B)
  171. if (Math::is_equal_approx(C.y, D.y)) {
  172. return false;
  173. }
  174. real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y);
  175. // Fail if segment C-D crosses line A-B outside of segment A-B.
  176. if ((ABpos < 0) || (ABpos > 1)) {
  177. return false;
  178. }
  179. // Apply the discovered position to line A-B in the original coordinate system.
  180. if (r_result) {
  181. *r_result = p_from_a + B * ABpos;
  182. }
  183. return true;
  184. }
  185. static inline bool is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  186. return p_point.distance_squared_to(p_circle_pos) <= p_circle_radius * p_circle_radius;
  187. }
  188. static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  189. Vector2 line_vec = p_to - p_from;
  190. Vector2 vec_to_line = p_from - p_circle_pos;
  191. // Create a quadratic formula of the form ax^2 + bx + c = 0
  192. real_t a, b, c;
  193. a = line_vec.dot(line_vec);
  194. b = 2 * vec_to_line.dot(line_vec);
  195. c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
  196. // Solve for t.
  197. real_t sqrtterm = b * b - 4 * a * c;
  198. // If the term we intend to square root is less than 0 then the answer won't be real,
  199. // so it definitely won't be t in the range 0 to 1.
  200. if (sqrtterm < 0) {
  201. return -1;
  202. }
  203. // If we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection)
  204. // then the following can be skipped and we can just return the equivalent of res1.
  205. sqrtterm = Math::sqrt(sqrtterm);
  206. real_t res1 = (-b - sqrtterm) / (2 * a);
  207. real_t res2 = (-b + sqrtterm) / (2 * a);
  208. if (res1 >= 0 && res1 <= 1) {
  209. return res1;
  210. }
  211. if (res2 >= 0 && res2 <= 1) {
  212. return res2;
  213. }
  214. return -1;
  215. }
  216. enum PolyBooleanOperation {
  217. OPERATION_UNION,
  218. OPERATION_DIFFERENCE,
  219. OPERATION_INTERSECTION,
  220. OPERATION_XOR
  221. };
  222. enum PolyJoinType {
  223. JOIN_SQUARE,
  224. JOIN_ROUND,
  225. JOIN_MITER
  226. };
  227. enum PolyEndType {
  228. END_POLYGON,
  229. END_JOINED,
  230. END_BUTT,
  231. END_SQUARE,
  232. END_ROUND
  233. };
  234. static Vector<Vector<Point2>> merge_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  235. return _polypaths_do_operation(OPERATION_UNION, p_polygon_a, p_polygon_b);
  236. }
  237. static Vector<Vector<Point2>> clip_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  238. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polygon_a, p_polygon_b);
  239. }
  240. static Vector<Vector<Point2>> intersect_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  241. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polygon_a, p_polygon_b);
  242. }
  243. static Vector<Vector<Point2>> exclude_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  244. return _polypaths_do_operation(OPERATION_XOR, p_polygon_a, p_polygon_b);
  245. }
  246. static Vector<Vector<Point2>> clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  247. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polyline, p_polygon, true);
  248. }
  249. static Vector<Vector<Point2>> intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  250. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polyline, p_polygon, true);
  251. }
  252. static Vector<Vector<Point2>> offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
  253. return _polypath_offset(p_polygon, p_delta, p_join_type, END_POLYGON);
  254. }
  255. static Vector<Vector<Point2>> offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  256. ERR_FAIL_COND_V_MSG(p_end_type == END_POLYGON, Vector<Vector<Point2>>(), "Attempt to offset a polyline like a polygon (use offset_polygon instead).");
  257. return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type);
  258. }
  259. static Vector<int> triangulate_delaunay(const Vector<Vector2> &p_points) {
  260. Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points);
  261. Vector<int> triangles;
  262. for (int i = 0; i < tr.size(); i++) {
  263. triangles.push_back(tr[i].points[0]);
  264. triangles.push_back(tr[i].points[1]);
  265. triangles.push_back(tr[i].points[2]);
  266. }
  267. return triangles;
  268. }
  269. static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) {
  270. Vector<int> triangles;
  271. if (!Triangulate::triangulate(p_polygon, triangles)) {
  272. return Vector<int>(); //fail
  273. }
  274. return triangles;
  275. }
  276. static bool is_polygon_clockwise(const Vector<Vector2> &p_polygon) {
  277. int c = p_polygon.size();
  278. if (c < 3) {
  279. return false;
  280. }
  281. const Vector2 *p = p_polygon.ptr();
  282. real_t sum = 0;
  283. for (int i = 0; i < c; i++) {
  284. const Vector2 &v1 = p[i];
  285. const Vector2 &v2 = p[(i + 1) % c];
  286. sum += (v2.x - v1.x) * (v2.y + v1.y);
  287. }
  288. return sum > 0.0f;
  289. }
  290. // Alternate implementation that should be faster.
  291. static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  292. int c = p_polygon.size();
  293. if (c < 3) {
  294. return false;
  295. }
  296. const Vector2 *p = p_polygon.ptr();
  297. Vector2 further_away(-1e20, -1e20);
  298. Vector2 further_away_opposite(1e20, 1e20);
  299. for (int i = 0; i < c; i++) {
  300. further_away.x = MAX(p[i].x, further_away.x);
  301. further_away.y = MAX(p[i].y, further_away.y);
  302. further_away_opposite.x = MIN(p[i].x, further_away_opposite.x);
  303. further_away_opposite.y = MIN(p[i].y, further_away_opposite.y);
  304. }
  305. // Make point outside that won't intersect with points in segment from p_point.
  306. further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312);
  307. int intersections = 0;
  308. for (int i = 0; i < c; i++) {
  309. const Vector2 &v1 = p[i];
  310. const Vector2 &v2 = p[(i + 1) % c];
  311. Vector2 res;
  312. if (segment_intersects_segment(v1, v2, p_point, further_away, &res)) {
  313. intersections++;
  314. if (res.is_equal_approx(p_point)) {
  315. // Point is in one of the polygon edges.
  316. return true;
  317. }
  318. }
  319. }
  320. return (intersections & 1);
  321. }
  322. static bool is_segment_intersecting_polygon(const Vector2 &p_from, const Vector2 &p_to, const Vector<Vector2> &p_polygon) {
  323. int c = p_polygon.size();
  324. const Vector2 *p = p_polygon.ptr();
  325. for (int i = 0; i < c; i++) {
  326. const Vector2 &v1 = p[i];
  327. const Vector2 &v2 = p[(i + 1) % c];
  328. if (segment_intersects_segment(p_from, p_to, v1, v2, nullptr)) {
  329. return true;
  330. }
  331. }
  332. return false;
  333. }
  334. static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) {
  335. return (real_t)(A.x - O.x) * (B.y - O.y) - (real_t)(A.y - O.y) * (B.x - O.x);
  336. }
  337. // Returns a list of points on the convex hull in counter-clockwise order.
  338. // Note: the last point in the returned list is the same as the first one.
  339. static Vector<Point2> convex_hull(Vector<Point2> P) {
  340. int n = P.size(), k = 0;
  341. Vector<Point2> H;
  342. H.resize(2 * n);
  343. // Sort points lexicographically.
  344. P.sort();
  345. // Build lower hull.
  346. for (int i = 0; i < n; ++i) {
  347. while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
  348. k--;
  349. }
  350. H.write[k++] = P[i];
  351. }
  352. // Build upper hull.
  353. for (int i = n - 2, t = k + 1; i >= 0; i--) {
  354. while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
  355. k--;
  356. }
  357. H.write[k++] = P[i];
  358. }
  359. H.resize(k);
  360. return H;
  361. }
  362. static Vector<Point2i> bresenham_line(const Point2i &p_start, const Point2i &p_end) {
  363. Vector<Point2i> points;
  364. Vector2i delta = (p_end - p_start).abs() * 2;
  365. Vector2i step = (p_end - p_start).sign();
  366. Vector2i current = p_start;
  367. if (delta.x > delta.y) {
  368. int err = delta.x / 2;
  369. for (; current.x != p_end.x; current.x += step.x) {
  370. points.push_back(current);
  371. err -= delta.y;
  372. if (err < 0) {
  373. current.y += step.y;
  374. err += delta.x;
  375. }
  376. }
  377. } else {
  378. int err = delta.y / 2;
  379. for (; current.y != p_end.y; current.y += step.y) {
  380. points.push_back(current);
  381. err -= delta.x;
  382. if (err < 0) {
  383. current.x += step.x;
  384. err += delta.y;
  385. }
  386. }
  387. }
  388. points.push_back(current);
  389. return points;
  390. }
  391. static Vector<Vector<Vector2>> decompose_polygon_in_convex(Vector<Point2> polygon);
  392. static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
  393. static Vector<Vector3i> partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size);
  394. private:
  395. static Vector<Vector<Point2>> _polypaths_do_operation(PolyBooleanOperation p_op, const Vector<Point2> &p_polypath_a, const Vector<Point2> &p_polypath_b, bool is_a_open = false);
  396. static Vector<Vector<Point2>> _polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type);
  397. };
  398. #endif // GEOMETRY_2D_H