geometry_2d.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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 real_t get_distance_to_segment(const Vector2 &p_point, const Vector2 *p_segment) {
  115. return p_point.distance_to(get_closest_point_to_segment(p_point, p_segment));
  116. }
  117. static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
  118. Vector2 an = a - s;
  119. Vector2 bn = b - s;
  120. Vector2 cn = c - s;
  121. bool orientation = an.cross(bn) > 0;
  122. if ((bn.cross(cn) > 0) != orientation) {
  123. return false;
  124. }
  125. return (cn.cross(an) > 0) == orientation;
  126. }
  127. static Vector2 get_closest_point_to_segment_uncapped(const Vector2 &p_point, const Vector2 *p_segment) {
  128. Vector2 p = p_point - p_segment[0];
  129. Vector2 n = p_segment[1] - p_segment[0];
  130. real_t l2 = n.length_squared();
  131. if (l2 < 1e-20f) {
  132. return p_segment[0]; // Both points are the same, just give any.
  133. }
  134. real_t d = n.dot(p) / l2;
  135. return p_segment[0] + n * d; // Inside.
  136. }
  137. // Disable False Positives in MSVC compiler; we correctly check for 0 here to prevent a division by 0.
  138. // See: https://github.com/godotengine/godot/pull/44274
  139. #ifdef _MSC_VER
  140. #pragma warning(disable : 4723)
  141. #endif
  142. 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) {
  143. // See http://paulbourke.net/geometry/pointlineplane/
  144. const real_t denom = p_dir_b.y * p_dir_a.x - p_dir_b.x * p_dir_a.y;
  145. if (Math::is_zero_approx(denom)) { // Parallel?
  146. return false;
  147. }
  148. const Vector2 v = p_from_a - p_from_b;
  149. const real_t t = (p_dir_b.x * v.y - p_dir_b.y * v.x) / denom;
  150. r_result = p_from_a + t * p_dir_a;
  151. return true;
  152. }
  153. // Re-enable division by 0 warning
  154. #ifdef _MSC_VER
  155. #pragma warning(default : 4723)
  156. #endif
  157. 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) {
  158. Vector2 B = p_to_a - p_from_a;
  159. Vector2 C = p_from_b - p_from_a;
  160. Vector2 D = p_to_b - p_from_a;
  161. real_t ABlen = B.dot(B);
  162. if (ABlen <= 0) {
  163. return false;
  164. }
  165. Vector2 Bn = B / ABlen;
  166. C = Vector2(C.x * Bn.x + C.y * Bn.y, C.y * Bn.x - C.x * Bn.y);
  167. D = Vector2(D.x * Bn.x + D.y * Bn.y, D.y * Bn.x - D.x * Bn.y);
  168. // Fail if C x B and D x B have the same sign (segments don't intersect).
  169. 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)) {
  170. return false;
  171. }
  172. // Fail if segments are parallel or colinear.
  173. // (when A x B == zero, i.e (C - D) x B == zero, i.e C x B == D x B)
  174. if (Math::is_equal_approx(C.y, D.y)) {
  175. return false;
  176. }
  177. real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y);
  178. // Fail if segment C-D crosses line A-B outside of segment A-B.
  179. if ((ABpos < 0) || (ABpos > 1)) {
  180. return false;
  181. }
  182. // Apply the discovered position to line A-B in the original coordinate system.
  183. if (r_result) {
  184. *r_result = p_from_a + B * ABpos;
  185. }
  186. return true;
  187. }
  188. static inline bool is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  189. return p_point.distance_squared_to(p_circle_pos) <= p_circle_radius * p_circle_radius;
  190. }
  191. static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  192. Vector2 line_vec = p_to - p_from;
  193. Vector2 vec_to_line = p_from - p_circle_pos;
  194. // Create a quadratic formula of the form ax^2 + bx + c = 0
  195. real_t a, b, c;
  196. a = line_vec.dot(line_vec);
  197. b = 2 * vec_to_line.dot(line_vec);
  198. c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
  199. // Solve for t.
  200. real_t sqrtterm = b * b - 4 * a * c;
  201. // If the term we intend to square root is less than 0 then the answer won't be real,
  202. // so it definitely won't be t in the range 0 to 1.
  203. if (sqrtterm < 0) {
  204. return -1;
  205. }
  206. // If we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection)
  207. // then the following can be skipped and we can just return the equivalent of res1.
  208. sqrtterm = Math::sqrt(sqrtterm);
  209. real_t res1 = (-b - sqrtterm) / (2 * a);
  210. real_t res2 = (-b + sqrtterm) / (2 * a);
  211. if (res1 >= 0 && res1 <= 1) {
  212. return res1;
  213. }
  214. if (res2 >= 0 && res2 <= 1) {
  215. return res2;
  216. }
  217. return -1;
  218. }
  219. static bool segment_intersects_rect(const Vector2 &p_from, const Vector2 &p_to, const Rect2 &p_rect) {
  220. if (p_rect.has_point(p_from) || p_rect.has_point(p_to)) {
  221. return true;
  222. }
  223. const Vector2 rect_points[4] = {
  224. p_rect.position,
  225. p_rect.position + Vector2(p_rect.size.x, 0),
  226. p_rect.position + p_rect.size,
  227. p_rect.position + Vector2(0, p_rect.size.y)
  228. };
  229. // Check if any of the rect's edges intersect the segment.
  230. for (int i = 0; i < 4; i++) {
  231. if (segment_intersects_segment(p_from, p_to, rect_points[i], rect_points[(i + 1) % 4], nullptr)) {
  232. return true;
  233. }
  234. }
  235. return false;
  236. }
  237. enum PolyBooleanOperation {
  238. OPERATION_UNION,
  239. OPERATION_DIFFERENCE,
  240. OPERATION_INTERSECTION,
  241. OPERATION_XOR
  242. };
  243. enum PolyJoinType {
  244. JOIN_SQUARE,
  245. JOIN_ROUND,
  246. JOIN_MITER
  247. };
  248. enum PolyEndType {
  249. END_POLYGON,
  250. END_JOINED,
  251. END_BUTT,
  252. END_SQUARE,
  253. END_ROUND
  254. };
  255. static Vector<Vector<Point2>> merge_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  256. return _polypaths_do_operation(OPERATION_UNION, p_polygon_a, p_polygon_b);
  257. }
  258. static Vector<Vector<Point2>> clip_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  259. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polygon_a, p_polygon_b);
  260. }
  261. static Vector<Vector<Point2>> intersect_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  262. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polygon_a, p_polygon_b);
  263. }
  264. static Vector<Vector<Point2>> exclude_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  265. return _polypaths_do_operation(OPERATION_XOR, p_polygon_a, p_polygon_b);
  266. }
  267. static Vector<Vector<Point2>> clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  268. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polyline, p_polygon, true);
  269. }
  270. static Vector<Vector<Point2>> intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  271. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polyline, p_polygon, true);
  272. }
  273. static Vector<Vector<Point2>> offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
  274. return _polypath_offset(p_polygon, p_delta, p_join_type, END_POLYGON);
  275. }
  276. static Vector<Vector<Point2>> offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  277. 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).");
  278. return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type);
  279. }
  280. static Vector<int> triangulate_delaunay(const Vector<Vector2> &p_points) {
  281. Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points);
  282. Vector<int> triangles;
  283. triangles.resize(3 * tr.size());
  284. int *ptr = triangles.ptrw();
  285. for (int i = 0; i < tr.size(); i++) {
  286. *ptr++ = tr[i].points[0];
  287. *ptr++ = tr[i].points[1];
  288. *ptr++ = tr[i].points[2];
  289. }
  290. return triangles;
  291. }
  292. static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) {
  293. Vector<int> triangles;
  294. if (!Triangulate::triangulate(p_polygon, triangles)) {
  295. return Vector<int>(); //fail
  296. }
  297. return triangles;
  298. }
  299. // Assumes cartesian coordinate system with +x to the right, +y up.
  300. // If using screen coordinates (+x to the right, +y down) the result will need to be flipped.
  301. static bool is_polygon_clockwise(const Vector<Vector2> &p_polygon) {
  302. int c = p_polygon.size();
  303. if (c < 3) {
  304. return false;
  305. }
  306. const Vector2 *p = p_polygon.ptr();
  307. real_t sum = 0;
  308. for (int i = 0; i < c; i++) {
  309. const Vector2 &v1 = p[i];
  310. const Vector2 &v2 = p[(i + 1) % c];
  311. sum += (v2.x - v1.x) * (v2.y + v1.y);
  312. }
  313. return sum > 0.0f;
  314. }
  315. // Alternate implementation that should be faster.
  316. static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  317. int c = p_polygon.size();
  318. if (c < 3) {
  319. return false;
  320. }
  321. const Vector2 *p = p_polygon.ptr();
  322. Vector2 further_away(-1e20, -1e20);
  323. Vector2 further_away_opposite(1e20, 1e20);
  324. for (int i = 0; i < c; i++) {
  325. further_away = further_away.max(p[i]);
  326. further_away_opposite = further_away_opposite.min(p[i]);
  327. }
  328. // Make point outside that won't intersect with points in segment from p_point.
  329. further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312);
  330. int intersections = 0;
  331. for (int i = 0; i < c; i++) {
  332. const Vector2 &v1 = p[i];
  333. const Vector2 &v2 = p[(i + 1) % c];
  334. Vector2 res;
  335. if (segment_intersects_segment(v1, v2, p_point, further_away, &res)) {
  336. intersections++;
  337. if (res.is_equal_approx(p_point)) {
  338. // Point is in one of the polygon edges.
  339. return true;
  340. }
  341. }
  342. }
  343. return (intersections & 1);
  344. }
  345. static bool is_segment_intersecting_polygon(const Vector2 &p_from, const Vector2 &p_to, const Vector<Vector2> &p_polygon) {
  346. int c = p_polygon.size();
  347. const Vector2 *p = p_polygon.ptr();
  348. for (int i = 0; i < c; i++) {
  349. const Vector2 &v1 = p[i];
  350. const Vector2 &v2 = p[(i + 1) % c];
  351. if (segment_intersects_segment(p_from, p_to, v1, v2, nullptr)) {
  352. return true;
  353. }
  354. }
  355. return false;
  356. }
  357. static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) {
  358. return (real_t)(A.x - O.x) * (B.y - O.y) - (real_t)(A.y - O.y) * (B.x - O.x);
  359. }
  360. // Returns a list of points on the convex hull in counter-clockwise order.
  361. // Note: the last point in the returned list is the same as the first one.
  362. static Vector<Point2> convex_hull(Vector<Point2> P) {
  363. int n = P.size(), k = 0;
  364. Vector<Point2> H;
  365. H.resize(2 * n);
  366. // Sort points lexicographically.
  367. P.sort();
  368. // Build lower hull.
  369. for (int i = 0; i < n; ++i) {
  370. while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
  371. k--;
  372. }
  373. H.write[k++] = P[i];
  374. }
  375. // Build upper hull.
  376. for (int i = n - 2, t = k + 1; i >= 0; i--) {
  377. while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
  378. k--;
  379. }
  380. H.write[k++] = P[i];
  381. }
  382. H.resize(k);
  383. return H;
  384. }
  385. static Vector<Point2i> bresenham_line(const Point2i &p_from, const Point2i &p_to) {
  386. Vector<Point2i> points;
  387. Vector2i delta = (p_to - p_from).abs() * 2;
  388. Vector2i step = (p_to - p_from).sign();
  389. Vector2i current = p_from;
  390. if (delta.x > delta.y) {
  391. int err = delta.x / 2;
  392. for (; current.x != p_to.x; current.x += step.x) {
  393. points.push_back(current);
  394. err -= delta.y;
  395. if (err < 0) {
  396. current.y += step.y;
  397. err += delta.x;
  398. }
  399. }
  400. } else {
  401. int err = delta.y / 2;
  402. for (; current.y != p_to.y; current.y += step.y) {
  403. points.push_back(current);
  404. err -= delta.x;
  405. if (err < 0) {
  406. current.x += step.x;
  407. err += delta.y;
  408. }
  409. }
  410. }
  411. points.push_back(current);
  412. return points;
  413. }
  414. static Vector<Vector<Vector2>> decompose_polygon_in_convex(const Vector<Point2> &polygon);
  415. static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
  416. static Vector<Vector3i> partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size);
  417. private:
  418. 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);
  419. static Vector<Vector<Point2>> _polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type);
  420. };
  421. #endif // GEOMETRY_2D_H