Debian Codegraph @

core/math/geometry_2d.h

raw symbols SCIP
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
31 #pragma once
32
33 #include "core/math/delaunay_2d.h"
34 #include "core/math/math_funcs.h"
35 #include "core/math/triangulate.h"
36 #include "core/math/vector2.h"
37 #include "core/math/vector2i.h"
38 #include "core/math/vector3.h"
39 #include "core/math/vector3i.h"
40 #include "core/templates/vector.h"
41
42 class Geometry2D {
43 public:
44 static real_t get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) {
45 Vector2 d1 = q1 - p1; // Direction vector of segment S1.
46 Vector2 d2 = q2 - p2; // Direction vector of segment S2.
47 Vector2 r = p1 - p2;
48 real_t a = d1.dot(d1); // Squared length of segment S1, always nonnegative.
49 real_t e = d2.dot(d2); // Squared length of segment S2, always nonnegative.
50 real_t f = d2.dot(r);
51 real_t s, t;
52 // Check if either or both segments degenerate into points.
53 if (a <= (real_t)CMP_EPSILON && e <= (real_t)CMP_EPSILON) {
54 // Both segments degenerate into points.
55 c1 = p1;
56 c2 = p2;
57 return Math::sqrt((c1 - c2).dot(c1 - c2));
58 }
59 if (a <= (real_t)CMP_EPSILON) {
60 // First segment degenerates into a point.
61 s = 0.0;
62 t = f / e; // s = 0 => t = (b*s + f) / e = f / e
63 t = CLAMP(t, 0.0f, 1.0f);
64 } else {
65 real_t c = d1.dot(r);
66 if (e <= (real_t)CMP_EPSILON) {
67 // Second segment degenerates into a point.
68 t = 0.0;
69 s = CLAMP(-c / a, 0.0f, 1.0f); // t = 0 => s = (b*t - c) / a = -c / a
70 } else {
71 // The general nondegenerate case starts here.
72 real_t b = d1.dot(d2);
73 real_t denom = a * e - b * b; // Always nonnegative.
74 // If segments not parallel, compute closest point on L1 to L2 and
75 // clamp to segment S1. Else pick arbitrary s (here 0).
76 if (denom != 0.0f) {
77 s = CLAMP((b * f - c * e) / denom, 0.0f, 1.0f);
78 } else {
79 s = 0.0;
80 }
81 // Compute point on L2 closest to S1(s) using
82 // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
83 t = (b * s + f) / e;
84
85 //If t in [0,1] done. Else clamp t, recompute s for the new value
86 // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
87 // and clamp s to [0, 1].
88 if (t < 0.0f) {
89 t = 0.0;
90 s = CLAMP(-c / a, 0.0f, 1.0f);
91 } else if (t > 1.0f) {
92 t = 1.0;
93 s = CLAMP((b - c) / a, 0.0f, 1.0f);
94 }
95 }
96 }
97 c1 = p1 + d1 * s;
98 c2 = p2 + d2 * t;
99 return Math::sqrt((c1 - c2).dot(c1 - c2));
100 }
101
102 #ifndef DISABLE_DEPRECATED
103 static Vector2 get_closest_point_to_segment(const Vector2 &p_point, const Vector2 *p_segment) {
104 return get_closest_point_to_segment(p_point, p_segment[0], p_segment[1]);
105 }
106 #endif // DISABLE_DEPRECATED
107
108 static Vector2 get_closest_point_to_segment(const Vector2 &p_point, const Vector2 &p_segment_a, const Vector2 &p_segment_b) {
109 Vector2 p = p_point - p_segment_a;
110 Vector2 n = p_segment_b - p_segment_a;
111 real_t l2 = n.length_squared();
112 if (l2 < 1e-20f) {
113 return p_segment_a; // Both points are the same, just give any.
114 }
115
116 real_t d = n.dot(p) / l2;
117
118 if (d <= 0.0f) {
119 return p_segment_a; // Before first point.
120 } else if (d >= 1.0f) {
121 return p_segment_b; // After first point.
122 } else {
123 return p_segment_a + n * d; // Inside.
124 }
125 }
126
127 #ifndef DISABLE_DEPRECATED
128 static real_t get_distance_to_segment(const Vector2 &p_point, const Vector2 *p_segment) {
129 return get_distance_to_segment(p_point, p_segment[0], p_segment[1]);
130 }
131 #endif // DISABLE_DEPRECATED
132
133 static real_t get_distance_to_segment(const Vector2 &p_point, const Vector2 &p_segment_a, const Vector2 &p_segment_b) {
134 return p_point.distance_to(get_closest_point_to_segment(p_point, p_segment_a, p_segment_b));
135 }
136
137 static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
138 Vector2 an = a - s;
139 Vector2 bn = b - s;
140 Vector2 cn = c - s;
141
142 bool orientation = an.cross(bn) > 0;
143
144 if ((bn.cross(cn) > 0) != orientation) {
145 return false;
146 }
147
148 return (cn.cross(an) > 0) == orientation;
149 }
150
151 #ifndef DISABLE_DEPRECATED
152 static Vector2 get_closest_point_to_segment_uncapped(const Vector2 &p_point, const Vector2 *p_segment) {
153 return get_closest_point_to_segment_uncapped(p_point, p_segment[0], p_segment[1]);
154 }
155 #endif // DISABLE_DEPRECATED
156
157 static Vector2 get_closest_point_to_segment_uncapped(const Vector2 &p_point, const Vector2 &p_segment_a, const Vector2 &p_segment_b) {
158 Vector2 p = p_point - p_segment_a;
159 Vector2 n = p_segment_b - p_segment_a;
160 real_t l2 = n.length_squared();
161 if (l2 < 1e-20f) {
162 return p_segment_a; // Both points are the same, just give any.
163 }
164
165 real_t d = n.dot(p) / l2;
166
167 return p_segment_a + n * d; // Inside.
168 }
169
170 GODOT_MSVC_WARNING_PUSH_AND_IGNORE(4723) // Potential divide by 0. False positive (see: GH-44274).
171
172 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) {
173 // See http://paulbourke.net/geometry/pointlineplane/
174
175 const real_t denom = p_dir_b.y * p_dir_a.x - p_dir_b.x * p_dir_a.y;
176 if (Math::is_zero_approx(denom)) { // Parallel?
177 return false;
178 }
179
180 const Vector2 v = p_from_a - p_from_b;
181 const real_t t = (p_dir_b.x * v.y - p_dir_b.y * v.x) / denom;
182 r_result = p_from_a + t * p_dir_a;
183 return true;
184 }
185
186 GODOT_MSVC_WARNING_POP
187
188 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) {
189 Vector2 B = p_to_a - p_from_a;
190 Vector2 C = p_from_b - p_from_a;
191 Vector2 D = p_to_b - p_from_a;
192
193 real_t ABlen = B.dot(B);
194 if (ABlen <= 0) {
195 return false;
196 }
197 Vector2 Bn = B / ABlen;
198 C = Vector2(C.x * Bn.x + C.y * Bn.y, C.y * Bn.x - C.x * Bn.y);
199 D = Vector2(D.x * Bn.x + D.y * Bn.y, D.y * Bn.x - D.x * Bn.y);
200
201 // Fail if C x B and D x B have the same sign (segments don't intersect).
202 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)) {
203 return false;
204 }
205
206 // Fail if segments are parallel or colinear.
207 // (when A x B == zero, i.e (C - D) x B == zero, i.e C x B == D x B)
208 if (Math::is_equal_approx(C.y, D.y)) {
209 return false;
210 }
211
212 real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y);
213
214 // Fail if segment C-D crosses line A-B outside of segment A-B.
215 if ((ABpos < 0) || (ABpos > 1)) {
216 return false;
217 }
218
219 // Apply the discovered position to line A-B in the original coordinate system.
220 if (r_result) {
221 *r_result = p_from_a + B * ABpos;
222 }
223
224 return true;
225 }
226
227 static inline bool is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) {
228 return p_point.distance_squared_to(p_circle_pos) <= p_circle_radius * p_circle_radius;
229 }
230
231 static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
232 Vector2 line_vec = p_to - p_from;
233 Vector2 vec_to_line = p_from - p_circle_pos;
234
235 // Create a quadratic formula of the form ax^2 + bx + c = 0
236 real_t a, b, c;
237
238 a = line_vec.dot(line_vec);
239 b = 2 * vec_to_line.dot(line_vec);
240 c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
241
242 // Solve for t.
243 real_t sqrtterm = b * b - 4 * a * c;
244
245 // If the term we intend to square root is less than 0 then the answer won't be real,
246 // so it definitely won't be t in the range 0 to 1.
247 if (sqrtterm < 0) {
248 return -1;
249 }
250
251 // If we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection)
252 // then the following can be skipped and we can just return the equivalent of res1.
253 sqrtterm = Math::sqrt(sqrtterm);
254 real_t res1 = (-b - sqrtterm) / (2 * a);
255 real_t res2 = (-b + sqrtterm) / (2 * a);
256
257 if (res1 >= 0 && res1 <= 1) {
258 return res1;
259 }
260 if (res2 >= 0 && res2 <= 1) {
261 return res2;
262 }
263 return -1;
264 }
265
266 static bool segment_intersects_rect(const Vector2 &p_from, const Vector2 &p_to, const Rect2 &p_rect) {
267 if (p_rect.has_point(p_from) || p_rect.has_point(p_to)) {
268 return true;
269 }
270
271 const Vector2 rect_points[4] = {
272 p_rect.position,
273 p_rect.position + Vector2(p_rect.size.x, 0),
274 p_rect.position + p_rect.size,
275 p_rect.position + Vector2(0, p_rect.size.y)
276 };
277
278 // Check if any of the rect's edges intersect the segment.
279 for (int i = 0; i < 4; i++) {
280 if (segment_intersects_segment(p_from, p_to, rect_points[i], rect_points[(i + 1) % 4], nullptr)) {
281 return true;
282 }
283 }
284
285 return false;
286 }
287
288 enum PolyBooleanOperation {
289 OPERATION_UNION,
290 OPERATION_DIFFERENCE,
291 OPERATION_INTERSECTION,
292 OPERATION_XOR
293 };
294 enum PolyJoinType {
295 JOIN_SQUARE,
296 JOIN_ROUND,
297 JOIN_MITER
298 };
299 enum PolyEndType {
300 END_POLYGON,
301 END_JOINED,
302 END_BUTT,
303 END_SQUARE,
304 END_ROUND
305 };
306
307 static Vector<Vector<Point2>> merge_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
308 return _polypaths_do_operation(OPERATION_UNION, p_polygon_a, p_polygon_b);
309 }
310
311 static Vector<Vector<Point2>> clip_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
312 return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polygon_a, p_polygon_b);
313 }
314
315 static Vector<Vector<Point2>> intersect_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
316 return _polypaths_do_operation(OPERATION_INTERSECTION, p_polygon_a, p_polygon_b);
317 }
318
319 static Vector<Vector<Point2>> exclude_polygons(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
320 return _polypaths_do_operation(OPERATION_XOR, p_polygon_a, p_polygon_b);
321 }
322
323 static Vector<Vector<Point2>> clip_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
324 return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polyline, p_polygon, true);
325 }
326
327 static Vector<Vector<Point2>> intersect_polyline_with_polygon(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
328 return _polypaths_do_operation(OPERATION_INTERSECTION, p_polyline, p_polygon, true);
329 }
330
331 static Vector<Vector<Point2>> offset_polygon(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
332 return _polypath_offset(p_polygon, p_delta, p_join_type, END_POLYGON);
333 }
334
335 static Vector<Vector<Point2>> offset_polyline(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
336 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).");
337
338 return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type);
339 }
340
341 static Vector<int> triangulate_delaunay(const Vector<Vector2> &p_points) {
342 Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points);
343 Vector<int> triangles;
344
345 triangles.resize(3 * tr.size());
346 int *ptr = triangles.ptrw();
347 for (int i = 0; i < tr.size(); i++) {
348 *ptr++ = tr[i].points[0];
349 *ptr++ = tr[i].points[1];
350 *ptr++ = tr[i].points[2];
351 }
352 return triangles;
353 }
354
355 static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) {
356 Vector<int> triangles;
357 if (!Triangulate::triangulate(p_polygon, triangles)) {
358 return Vector<int>(); //fail
359 }
360 return triangles;
361 }
362
363 // Assumes cartesian coordinate system with +x to the right, +y up.
364 // If using screen coordinates (+x to the right, +y down) the result will need to be flipped.
365 static bool is_polygon_clockwise(const Vector<Vector2> &p_polygon) {
366 int c = p_polygon.size();
367 if (c < 3) {
368 return false;
369 }
370 const Vector2 *p = p_polygon.ptr();
371 real_t sum = 0;
372 for (int i = 0; i < c; i++) {
373 const Vector2 &v1 = p[i];
374 const Vector2 &v2 = p[(i + 1) % c];
375 sum += (v2.x - v1.x) * (v2.y + v1.y);
376 }
377
378 return sum > 0.0f;
379 }
380
381 // Alternate implementation that should be faster.
382 static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
383 int c = p_polygon.size();
384 if (c < 3) {
385 return false;
386 }
387 const Vector2 *p = p_polygon.ptr();
388 Vector2 further_away(-1e20, -1e20);
389 Vector2 further_away_opposite(1e20, 1e20);
390
391 for (int i = 0; i < c; i++) {
392 further_away = further_away.max(p[i]);
393 further_away_opposite = further_away_opposite.min(p[i]);
394 }
395
396 // Make point outside that won't intersect with points in segment from p_point.
397 further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312);
398
399 int intersections = 0;
400 for (int i = 0; i < c; i++) {
401 const Vector2 &v1 = p[i];
402 const Vector2 &v2 = p[(i + 1) % c];
403
404 Vector2 res;
405 if (segment_intersects_segment(v1, v2, p_point, further_away, &res)) {
406 intersections++;
407 if (res.is_equal_approx(p_point)) {
408 // Point is in one of the polygon edges.
409 return true;
410 }
411 }
412 }
413
414 return (intersections & 1);
415 }
416
417 static bool is_segment_intersecting_polygon(const Vector2 &p_from, const Vector2 &p_to, const Vector<Vector2> &p_polygon) {
418 int c = p_polygon.size();
419 const Vector2 *p = p_polygon.ptr();
420 for (int i = 0; i < c; i++) {
421 const Vector2 &v1 = p[i];
422 const Vector2 &v2 = p[(i + 1) % c];
423 if (segment_intersects_segment(p_from, p_to, v1, v2, nullptr)) {
424 return true;
425 }
426 }
427 return false;
428 }
429
430 static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) {
431 return (real_t)(A.x - O.x) * (B.y - O.y) - (real_t)(A.y - O.y) * (B.x - O.x);
432 }
433
434 // Returns a list of points on the convex hull in counter-clockwise order.
435 // Note: the last point in the returned list is the same as the first one.
436 static Vector<Point2> convex_hull(Vector<Point2> P) {
437 int n = P.size(), k = 0;
438 Vector<Point2> H;
439 H.resize(2 * n);
440
441 // Sort points lexicographically.
442 P.sort();
443
444 // Build lower hull.
445 for (int i = 0; i < n; ++i) {
446 while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
447 k--;
448 }
449 H.write[k++] = P[i];
450 }
451
452 // Build upper hull.
453 for (int i = n - 2, t = k + 1; i >= 0; i--) {
454 while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0) {
455 k--;
456 }
457 H.write[k++] = P[i];
458 }
459
460 H.resize(k);
461 return H;
462 }
463
464 static Vector<Point2i> bresenham_line(const Point2i &p_from, const Point2i &p_to) {
465 Vector<Point2i> points;
466
467 Vector2i delta = (p_to - p_from).abs() * 2;
468 Vector2i step = (p_to - p_from).sign();
469 Vector2i current = p_from;
470
471 if (delta.x > delta.y) {
472 int err = delta.x / 2;
473
474 for (; current.x != p_to.x; current.x += step.x) {
475 points.push_back(current);
476
477 err -= delta.y;
478 if (err < 0) {
479 current.y += step.y;
480 err += delta.x;
481 }
482 }
483 } else {
484 int err = delta.y / 2;
485
486 for (; current.y != p_to.y; current.y += step.y) {
487 points.push_back(current);
488
489 err -= delta.x;
490 if (err < 0) {
491 current.x += step.x;
492 err += delta.y;
493 }
494 }
495 }
496
497 points.push_back(current);
498
499 return points;
500 }
501
502 static void merge_many_polygons(const Vector<Vector<Point2>> &p_polygons, Vector<Vector<Vector2>> &r_out_polygons, Vector<Vector<Vector2>> &r_out_holes);
503 static Vector<Vector<Vector2>> decompose_many_polygons_in_convex(const Vector<Vector<Point2>> &p_polygons, const Vector<Vector<Point2>> &p_holes);
504
505 static Vector<Vector<Vector2>> decompose_polygon_in_convex(const Vector<Point2> &p_polygon);
506
507 static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
508 static Vector<Vector3i> partial_pack_rects(const Vector<Vector2i> &p_sizes, const Size2i &p_atlas_size);
509
510 private:
511 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);
512 static Vector<Vector<Point2>> _polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type);
513 };