geometry.h 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. /*************************************************************************/
  2. /* geometry.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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. #ifndef GEOMETRY_H
  31. #define GEOMETRY_H
  32. #include "core/math/delaunay.h"
  33. #include "core/math/face3.h"
  34. #include "core/math/rect2.h"
  35. #include "core/math/triangulate.h"
  36. #include "core/math/vector3.h"
  37. #include "core/object.h"
  38. #include "core/pool_vector.h"
  39. #include "core/print_string.h"
  40. #include "core/vector.h"
  41. class Geometry {
  42. Geometry();
  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 <= CMP_EPSILON && e <= 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 <= 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.0, 1.0);
  64. } else {
  65. real_t c = d1.dot(r);
  66. if (e <= CMP_EPSILON) {
  67. // Second segment degenerates into a point.
  68. t = 0.0;
  69. s = CLAMP(-c / a, 0.0, 1.0); // 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.0) {
  77. s = CLAMP((b * f - c * e) / denom, 0.0, 1.0);
  78. } else
  79. s = 0.0;
  80. // Compute point on L2 closest to S1(s) using
  81. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  82. t = (b * s + f) / e;
  83. //If t in [0,1] done. Else clamp t, recompute s for the new value
  84. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  85. // and clamp s to [0, 1].
  86. if (t < 0.0) {
  87. t = 0.0;
  88. s = CLAMP(-c / a, 0.0, 1.0);
  89. } else if (t > 1.0) {
  90. t = 1.0;
  91. s = CLAMP((b - c) / a, 0.0, 1.0);
  92. }
  93. }
  94. }
  95. c1 = p1 + d1 * s;
  96. c2 = p2 + d2 * t;
  97. return Math::sqrt((c1 - c2).dot(c1 - c2));
  98. }
  99. static void get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2, Vector3 &c1, Vector3 &c2) {
  100. // Do the function 'd' as defined by pb. I think is is dot product of some sort.
  101. #define d_of(m, n, o, p) ((m.x - n.x) * (o.x - p.x) + (m.y - n.y) * (o.y - p.y) + (m.z - n.z) * (o.z - p.z))
  102. // Calculate the parametric position on the 2 curves, mua and mub.
  103. real_t mua = (d_of(p1, q1, q2, q1) * d_of(q2, q1, p2, p1) - d_of(p1, q1, p2, p1) * d_of(q2, q1, q2, q1)) / (d_of(p2, p1, p2, p1) * d_of(q2, q1, q2, q1) - d_of(q2, q1, p2, p1) * d_of(q2, q1, p2, p1));
  104. real_t mub = (d_of(p1, q1, q2, q1) + mua * d_of(q2, q1, p2, p1)) / d_of(q2, q1, q2, q1);
  105. // Clip the value between [0..1] constraining the solution to lie on the original curves.
  106. if (mua < 0) mua = 0;
  107. if (mub < 0) mub = 0;
  108. if (mua > 1) mua = 1;
  109. if (mub > 1) mub = 1;
  110. c1 = p1.linear_interpolate(p2, mua);
  111. c2 = q1.linear_interpolate(q2, mub);
  112. }
  113. static real_t get_closest_distance_between_segments(const Vector3 &p_from_a, const Vector3 &p_to_a, const Vector3 &p_from_b, const Vector3 &p_to_b) {
  114. Vector3 u = p_to_a - p_from_a;
  115. Vector3 v = p_to_b - p_from_b;
  116. Vector3 w = p_from_a - p_to_a;
  117. real_t a = u.dot(u); // Always >= 0
  118. real_t b = u.dot(v);
  119. real_t c = v.dot(v); // Always >= 0
  120. real_t d = u.dot(w);
  121. real_t e = v.dot(w);
  122. real_t D = a * c - b * b; // Always >= 0
  123. real_t sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  124. real_t tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  125. // Compute the line parameters of the two closest points.
  126. if (D < CMP_EPSILON) { // The lines are almost parallel.
  127. sN = 0.0; // Force using point P0 on segment S1
  128. sD = 1.0; // to prevent possible division by 0.0 later.
  129. tN = e;
  130. tD = c;
  131. } else { // Get the closest points on the infinite lines
  132. sN = (b * e - c * d);
  133. tN = (a * e - b * d);
  134. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible.
  135. sN = 0.0;
  136. tN = e;
  137. tD = c;
  138. } else if (sN > sD) { // sc > 1 => the s=1 edge is visible.
  139. sN = sD;
  140. tN = e + b;
  141. tD = c;
  142. }
  143. }
  144. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible.
  145. tN = 0.0;
  146. // Recompute sc for this edge.
  147. if (-d < 0.0)
  148. sN = 0.0;
  149. else if (-d > a)
  150. sN = sD;
  151. else {
  152. sN = -d;
  153. sD = a;
  154. }
  155. } else if (tN > tD) { // tc > 1 => the t=1 edge is visible.
  156. tN = tD;
  157. // Recompute sc for this edge.
  158. if ((-d + b) < 0.0)
  159. sN = 0;
  160. else if ((-d + b) > a)
  161. sN = sD;
  162. else {
  163. sN = (-d + b);
  164. sD = a;
  165. }
  166. }
  167. // Finally do the division to get sc and tc.
  168. sc = (Math::is_zero_approx(sN) ? 0.0 : sN / sD);
  169. tc = (Math::is_zero_approx(tN) ? 0.0 : tN / tD);
  170. // Get the difference of the two closest points.
  171. Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc)
  172. return dP.length(); // Return the closest distance.
  173. }
  174. static inline bool ray_intersects_triangle(const Vector3 &p_from, const Vector3 &p_dir, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) {
  175. Vector3 e1 = p_v1 - p_v0;
  176. Vector3 e2 = p_v2 - p_v0;
  177. Vector3 h = p_dir.cross(e2);
  178. real_t a = e1.dot(h);
  179. if (Math::is_zero_approx(a)) // Parallel test.
  180. return false;
  181. real_t f = 1.0 / a;
  182. Vector3 s = p_from - p_v0;
  183. real_t u = f * s.dot(h);
  184. if (u < 0.0 || u > 1.0)
  185. return false;
  186. Vector3 q = s.cross(e1);
  187. real_t v = f * p_dir.dot(q);
  188. if (v < 0.0 || u + v > 1.0)
  189. return false;
  190. // At this stage we can compute t to find out where
  191. // the intersection point is on the line.
  192. real_t t = f * e2.dot(q);
  193. if (t > 0.00001) { // ray intersection
  194. if (r_res)
  195. *r_res = p_from + p_dir * t;
  196. return true;
  197. } else // This means that there is a line intersection but not a ray intersection.
  198. return false;
  199. }
  200. static inline bool segment_intersects_triangle(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_v0, const Vector3 &p_v1, const Vector3 &p_v2, Vector3 *r_res = 0) {
  201. Vector3 rel = p_to - p_from;
  202. Vector3 e1 = p_v1 - p_v0;
  203. Vector3 e2 = p_v2 - p_v0;
  204. Vector3 h = rel.cross(e2);
  205. real_t a = e1.dot(h);
  206. if (Math::is_zero_approx(a)) // Parallel test.
  207. return false;
  208. real_t f = 1.0 / a;
  209. Vector3 s = p_from - p_v0;
  210. real_t u = f * s.dot(h);
  211. if (u < 0.0 || u > 1.0)
  212. return false;
  213. Vector3 q = s.cross(e1);
  214. real_t v = f * rel.dot(q);
  215. if (v < 0.0 || u + v > 1.0)
  216. return false;
  217. // At this stage we can compute t to find out where
  218. // the intersection point is on the line.
  219. real_t t = f * e2.dot(q);
  220. if (t > CMP_EPSILON && t <= 1.0) { // Ray intersection.
  221. if (r_res)
  222. *r_res = p_from + rel * t;
  223. return true;
  224. } else // This means that there is a line intersection but not a ray intersection.
  225. return false;
  226. }
  227. static inline bool segment_intersects_sphere(const Vector3 &p_from, const Vector3 &p_to, const Vector3 &p_sphere_pos, real_t p_sphere_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0) {
  228. Vector3 sphere_pos = p_sphere_pos - p_from;
  229. Vector3 rel = (p_to - p_from);
  230. real_t rel_l = rel.length();
  231. if (rel_l < CMP_EPSILON)
  232. return false; // Both points are the same.
  233. Vector3 normal = rel / rel_l;
  234. real_t sphere_d = normal.dot(sphere_pos);
  235. real_t ray_distance = sphere_pos.distance_to(normal * sphere_d);
  236. if (ray_distance >= p_sphere_radius)
  237. return false;
  238. real_t inters_d2 = p_sphere_radius * p_sphere_radius - ray_distance * ray_distance;
  239. real_t inters_d = sphere_d;
  240. if (inters_d2 >= CMP_EPSILON)
  241. inters_d -= Math::sqrt(inters_d2);
  242. // Check in segment.
  243. if (inters_d < 0 || inters_d > rel_l)
  244. return false;
  245. Vector3 result = p_from + normal * inters_d;
  246. if (r_res)
  247. *r_res = result;
  248. if (r_norm)
  249. *r_norm = (result - p_sphere_pos).normalized();
  250. return true;
  251. }
  252. static inline bool segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, real_t p_height, real_t p_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0) {
  253. Vector3 rel = (p_to - p_from);
  254. real_t rel_l = rel.length();
  255. if (rel_l < CMP_EPSILON)
  256. return false; // Both points are the same.
  257. // First check if they are parallel.
  258. Vector3 normal = (rel / rel_l);
  259. Vector3 crs = normal.cross(Vector3(0, 0, 1));
  260. real_t crs_l = crs.length();
  261. Vector3 z_dir;
  262. if (crs_l < CMP_EPSILON) {
  263. z_dir = Vector3(1, 0, 0); // Any x/y vector OK.
  264. } else {
  265. z_dir = crs / crs_l;
  266. }
  267. real_t dist = z_dir.dot(p_from);
  268. if (dist >= p_radius)
  269. return false; // Too far away.
  270. // Convert to 2D.
  271. real_t w2 = p_radius * p_radius - dist * dist;
  272. if (w2 < CMP_EPSILON)
  273. return false; // Avoid numerical error.
  274. Size2 size(Math::sqrt(w2), p_height * 0.5);
  275. Vector3 x_dir = z_dir.cross(Vector3(0, 0, 1)).normalized();
  276. Vector2 from2D(x_dir.dot(p_from), p_from.z);
  277. Vector2 to2D(x_dir.dot(p_to), p_to.z);
  278. real_t min = 0, max = 1;
  279. int axis = -1;
  280. for (int i = 0; i < 2; i++) {
  281. real_t seg_from = from2D[i];
  282. real_t seg_to = to2D[i];
  283. real_t box_begin = -size[i];
  284. real_t box_end = size[i];
  285. real_t cmin, cmax;
  286. if (seg_from < seg_to) {
  287. if (seg_from > box_end || seg_to < box_begin)
  288. return false;
  289. real_t length = seg_to - seg_from;
  290. cmin = (seg_from < box_begin) ? ((box_begin - seg_from) / length) : 0;
  291. cmax = (seg_to > box_end) ? ((box_end - seg_from) / length) : 1;
  292. } else {
  293. if (seg_to > box_end || seg_from < box_begin)
  294. return false;
  295. real_t length = seg_to - seg_from;
  296. cmin = (seg_from > box_end) ? (box_end - seg_from) / length : 0;
  297. cmax = (seg_to < box_begin) ? (box_begin - seg_from) / length : 1;
  298. }
  299. if (cmin > min) {
  300. min = cmin;
  301. axis = i;
  302. }
  303. if (cmax < max)
  304. max = cmax;
  305. if (max < min)
  306. return false;
  307. }
  308. // Convert to 3D again.
  309. Vector3 result = p_from + (rel * min);
  310. Vector3 res_normal = result;
  311. if (axis == 0) {
  312. res_normal.z = 0;
  313. } else {
  314. res_normal.x = 0;
  315. res_normal.y = 0;
  316. }
  317. res_normal.normalize();
  318. if (r_res)
  319. *r_res = result;
  320. if (r_norm)
  321. *r_norm = res_normal;
  322. return true;
  323. }
  324. static bool segment_intersects_convex(const Vector3 &p_from, const Vector3 &p_to, const Plane *p_planes, int p_plane_count, Vector3 *p_res, Vector3 *p_norm) {
  325. real_t min = -1e20, max = 1e20;
  326. Vector3 rel = p_to - p_from;
  327. real_t rel_l = rel.length();
  328. if (rel_l < CMP_EPSILON)
  329. return false;
  330. Vector3 dir = rel / rel_l;
  331. int min_index = -1;
  332. for (int i = 0; i < p_plane_count; i++) {
  333. const Plane &p = p_planes[i];
  334. real_t den = p.normal.dot(dir);
  335. if (Math::abs(den) <= CMP_EPSILON)
  336. continue; // Ignore parallel plane.
  337. real_t dist = -p.distance_to(p_from) / den;
  338. if (den > 0) {
  339. // Backwards facing plane.
  340. if (dist < max)
  341. max = dist;
  342. } else {
  343. // Front facing plane.
  344. if (dist > min) {
  345. min = dist;
  346. min_index = i;
  347. }
  348. }
  349. }
  350. if (max <= min || min < 0 || min > rel_l || min_index == -1) // Exit conditions.
  351. return false; // No intersection.
  352. if (p_res)
  353. *p_res = p_from + dir * min;
  354. if (p_norm)
  355. *p_norm = p_planes[min_index].normal;
  356. return true;
  357. }
  358. static Vector3 get_closest_point_to_segment(const Vector3 &p_point, const Vector3 *p_segment) {
  359. Vector3 p = p_point - p_segment[0];
  360. Vector3 n = p_segment[1] - p_segment[0];
  361. real_t l2 = n.length_squared();
  362. if (l2 < 1e-20)
  363. return p_segment[0]; // Both points are the same, just give any.
  364. real_t d = n.dot(p) / l2;
  365. if (d <= 0.0)
  366. return p_segment[0]; // Before first point.
  367. else if (d >= 1.0)
  368. return p_segment[1]; // After first point.
  369. else
  370. return p_segment[0] + n * d; // Inside.
  371. }
  372. static Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 *p_segment) {
  373. Vector3 p = p_point - p_segment[0];
  374. Vector3 n = p_segment[1] - p_segment[0];
  375. real_t l2 = n.length_squared();
  376. if (l2 < 1e-20)
  377. return p_segment[0]; // Both points are the same, just give any.
  378. real_t d = n.dot(p) / l2;
  379. return p_segment[0] + n * d; // Inside.
  380. }
  381. static Vector2 get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 *p_segment) {
  382. Vector2 p = p_point - p_segment[0];
  383. Vector2 n = p_segment[1] - p_segment[0];
  384. real_t l2 = n.length_squared();
  385. if (l2 < 1e-20)
  386. return p_segment[0]; // Both points are the same, just give any.
  387. real_t d = n.dot(p) / l2;
  388. if (d <= 0.0)
  389. return p_segment[0]; // Before first point.
  390. else if (d >= 1.0)
  391. return p_segment[1]; // After first point.
  392. else
  393. return p_segment[0] + n * d; // Inside.
  394. }
  395. static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
  396. Vector2 an = a - s;
  397. Vector2 bn = b - s;
  398. Vector2 cn = c - s;
  399. bool orientation = an.cross(bn) > 0;
  400. if ((bn.cross(cn) > 0) != orientation) return false;
  401. return (cn.cross(an) > 0) == orientation;
  402. }
  403. static Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 *p_segment) {
  404. Vector2 p = p_point - p_segment[0];
  405. Vector2 n = p_segment[1] - p_segment[0];
  406. real_t l2 = n.length_squared();
  407. if (l2 < 1e-20)
  408. return p_segment[0]; // Both points are the same, just give any.
  409. real_t d = n.dot(p) / l2;
  410. return p_segment[0] + n * d; // Inside.
  411. }
  412. static bool line_intersects_line_2d(const Vector2 &p_from_a, const Vector2 &p_dir_a, const Vector2 &p_from_b, const Vector2 &p_dir_b, Vector2 &r_result) {
  413. // See http://paulbourke.net/geometry/pointlineplane/
  414. const real_t denom = p_dir_b.y * p_dir_a.x - p_dir_b.x * p_dir_a.y;
  415. if (Math::is_zero_approx(denom)) { // Parallel?
  416. return false;
  417. }
  418. const Vector2 v = p_from_a - p_from_b;
  419. const real_t t = (p_dir_b.x * v.y - p_dir_b.y * v.x) / denom;
  420. r_result = p_from_a + t * p_dir_a;
  421. return true;
  422. }
  423. static bool segment_intersects_segment_2d(const Vector2 &p_from_a, const Vector2 &p_to_a, const Vector2 &p_from_b, const Vector2 &p_to_b, Vector2 *r_result) {
  424. Vector2 B = p_to_a - p_from_a;
  425. Vector2 C = p_from_b - p_from_a;
  426. Vector2 D = p_to_b - p_from_a;
  427. real_t ABlen = B.dot(B);
  428. if (ABlen <= 0)
  429. return false;
  430. Vector2 Bn = B / ABlen;
  431. C = Vector2(C.x * Bn.x + C.y * Bn.y, C.y * Bn.x - C.x * Bn.y);
  432. D = Vector2(D.x * Bn.x + D.y * Bn.y, D.y * Bn.x - D.x * Bn.y);
  433. if ((C.y < 0 && D.y < 0) || (C.y >= 0 && D.y >= 0))
  434. return false;
  435. real_t ABpos = D.x + (C.x - D.x) * D.y / (D.y - C.y);
  436. // Fail if segment C-D crosses line A-B outside of segment A-B.
  437. if (ABpos < 0 || ABpos > 1.0)
  438. return false;
  439. // (4) Apply the discovered position to line A-B in the original coordinate system.
  440. if (r_result)
  441. *r_result = p_from_a + B * ABpos;
  442. return true;
  443. }
  444. static inline bool point_in_projected_triangle(const Vector3 &p_point, const Vector3 &p_v1, const Vector3 &p_v2, const Vector3 &p_v3) {
  445. Vector3 face_n = (p_v1 - p_v3).cross(p_v1 - p_v2);
  446. Vector3 n1 = (p_point - p_v3).cross(p_point - p_v2);
  447. if (face_n.dot(n1) < 0)
  448. return false;
  449. Vector3 n2 = (p_v1 - p_v3).cross(p_v1 - p_point);
  450. if (face_n.dot(n2) < 0)
  451. return false;
  452. Vector3 n3 = (p_v1 - p_point).cross(p_v1 - p_v2);
  453. if (face_n.dot(n3) < 0)
  454. return false;
  455. return true;
  456. }
  457. static inline bool triangle_sphere_intersection_test(const Vector3 *p_triangle, const Vector3 &p_normal, const Vector3 &p_sphere_pos, real_t p_sphere_radius, Vector3 &r_triangle_contact, Vector3 &r_sphere_contact) {
  458. real_t d = p_normal.dot(p_sphere_pos) - p_normal.dot(p_triangle[0]);
  459. if (d > p_sphere_radius || d < -p_sphere_radius) // Not touching the plane of the face, return.
  460. return false;
  461. Vector3 contact = p_sphere_pos - (p_normal * d);
  462. /** 2nd) TEST INSIDE TRIANGLE **/
  463. if (Geometry::point_in_projected_triangle(contact, p_triangle[0], p_triangle[1], p_triangle[2])) {
  464. r_triangle_contact = contact;
  465. r_sphere_contact = p_sphere_pos - p_normal * p_sphere_radius;
  466. //printf("solved inside triangle\n");
  467. return true;
  468. }
  469. /** 3rd TEST INSIDE EDGE CYLINDERS **/
  470. const Vector3 verts[4] = { p_triangle[0], p_triangle[1], p_triangle[2], p_triangle[0] }; // for() friendly
  471. for (int i = 0; i < 3; i++) {
  472. // Check edge cylinder.
  473. Vector3 n1 = verts[i] - verts[i + 1];
  474. Vector3 n2 = p_sphere_pos - verts[i + 1];
  475. ///@TODO Maybe discard by range here to make the algorithm quicker.
  476. // Check point within cylinder radius.
  477. Vector3 axis = n1.cross(n2).cross(n1);
  478. axis.normalize();
  479. real_t ad = axis.dot(n2);
  480. if (ABS(ad) > p_sphere_radius) {
  481. // No chance with this edge, too far away.
  482. continue;
  483. }
  484. // Check point within edge capsule cylinder.
  485. /** 4th TEST INSIDE EDGE POINTS **/
  486. real_t sphere_at = n1.dot(n2);
  487. if (sphere_at >= 0 && sphere_at < n1.dot(n1)) {
  488. r_triangle_contact = p_sphere_pos - axis * (axis.dot(n2));
  489. r_sphere_contact = p_sphere_pos - axis * p_sphere_radius;
  490. // Point inside here.
  491. return true;
  492. }
  493. real_t r2 = p_sphere_radius * p_sphere_radius;
  494. if (n2.length_squared() < r2) {
  495. Vector3 n = (p_sphere_pos - verts[i + 1]).normalized();
  496. r_triangle_contact = verts[i + 1];
  497. r_sphere_contact = p_sphere_pos - n * p_sphere_radius;
  498. return true;
  499. }
  500. if (n2.distance_squared_to(n1) < r2) {
  501. Vector3 n = (p_sphere_pos - verts[i]).normalized();
  502. r_triangle_contact = verts[i];
  503. r_sphere_contact = p_sphere_pos - n * p_sphere_radius;
  504. return true;
  505. }
  506. break; // It's pointless to continue at this point, so save some CPU cycles.
  507. }
  508. return false;
  509. }
  510. static inline bool is_point_in_circle(const Vector2 &p_point, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  511. return p_point.distance_squared_to(p_circle_pos) <= p_circle_radius * p_circle_radius;
  512. }
  513. static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  514. Vector2 line_vec = p_to - p_from;
  515. Vector2 vec_to_line = p_from - p_circle_pos;
  516. // Create a quadratic formula of the form ax^2 + bx + c = 0
  517. real_t a, b, c;
  518. a = line_vec.dot(line_vec);
  519. b = 2 * vec_to_line.dot(line_vec);
  520. c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
  521. // Solve for t.
  522. real_t sqrtterm = b * b - 4 * a * c;
  523. // If the term we intend to square root is less than 0 then the answer won't be real,
  524. // so it definitely won't be t in the range 0 to 1.
  525. if (sqrtterm < 0) return -1;
  526. // If we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection)
  527. // then the following can be skipped and we can just return the equivalent of res1.
  528. sqrtterm = Math::sqrt(sqrtterm);
  529. real_t res1 = (-b - sqrtterm) / (2 * a);
  530. real_t res2 = (-b + sqrtterm) / (2 * a);
  531. if (res1 >= 0 && res1 <= 1) return res1;
  532. if (res2 >= 0 && res2 <= 1) return res2;
  533. return -1;
  534. }
  535. static inline Vector<Vector3> clip_polygon(const Vector<Vector3> &polygon, const Plane &p_plane) {
  536. enum LocationCache {
  537. LOC_INSIDE = 1,
  538. LOC_BOUNDARY = 0,
  539. LOC_OUTSIDE = -1
  540. };
  541. if (polygon.size() == 0)
  542. return polygon;
  543. int *location_cache = (int *)alloca(sizeof(int) * polygon.size());
  544. int inside_count = 0;
  545. int outside_count = 0;
  546. for (int a = 0; a < polygon.size(); a++) {
  547. real_t dist = p_plane.distance_to(polygon[a]);
  548. if (dist < -CMP_POINT_IN_PLANE_EPSILON) {
  549. location_cache[a] = LOC_INSIDE;
  550. inside_count++;
  551. } else {
  552. if (dist > CMP_POINT_IN_PLANE_EPSILON) {
  553. location_cache[a] = LOC_OUTSIDE;
  554. outside_count++;
  555. } else {
  556. location_cache[a] = LOC_BOUNDARY;
  557. }
  558. }
  559. }
  560. if (outside_count == 0) {
  561. return polygon; // No changes.
  562. } else if (inside_count == 0) {
  563. return Vector<Vector3>(); // Empty.
  564. }
  565. long previous = polygon.size() - 1;
  566. Vector<Vector3> clipped;
  567. for (int index = 0; index < polygon.size(); index++) {
  568. int loc = location_cache[index];
  569. if (loc == LOC_OUTSIDE) {
  570. if (location_cache[previous] == LOC_INSIDE) {
  571. const Vector3 &v1 = polygon[previous];
  572. const Vector3 &v2 = polygon[index];
  573. Vector3 segment = v1 - v2;
  574. real_t den = p_plane.normal.dot(segment);
  575. real_t dist = p_plane.distance_to(v1) / den;
  576. dist = -dist;
  577. clipped.push_back(v1 + segment * dist);
  578. }
  579. } else {
  580. const Vector3 &v1 = polygon[index];
  581. if ((loc == LOC_INSIDE) && (location_cache[previous] == LOC_OUTSIDE)) {
  582. const Vector3 &v2 = polygon[previous];
  583. Vector3 segment = v1 - v2;
  584. real_t den = p_plane.normal.dot(segment);
  585. real_t dist = p_plane.distance_to(v1) / den;
  586. dist = -dist;
  587. clipped.push_back(v1 + segment * dist);
  588. }
  589. clipped.push_back(v1);
  590. }
  591. previous = index;
  592. }
  593. return clipped;
  594. }
  595. enum PolyBooleanOperation {
  596. OPERATION_UNION,
  597. OPERATION_DIFFERENCE,
  598. OPERATION_INTERSECTION,
  599. OPERATION_XOR
  600. };
  601. enum PolyJoinType {
  602. JOIN_SQUARE,
  603. JOIN_ROUND,
  604. JOIN_MITER
  605. };
  606. enum PolyEndType {
  607. END_POLYGON,
  608. END_JOINED,
  609. END_BUTT,
  610. END_SQUARE,
  611. END_ROUND
  612. };
  613. static Vector<Vector<Point2> > merge_polygons_2d(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  614. return _polypaths_do_operation(OPERATION_UNION, p_polygon_a, p_polygon_b);
  615. }
  616. static Vector<Vector<Point2> > clip_polygons_2d(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  617. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polygon_a, p_polygon_b);
  618. }
  619. static Vector<Vector<Point2> > intersect_polygons_2d(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  620. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polygon_a, p_polygon_b);
  621. }
  622. static Vector<Vector<Point2> > exclude_polygons_2d(const Vector<Point2> &p_polygon_a, const Vector<Point2> &p_polygon_b) {
  623. return _polypaths_do_operation(OPERATION_XOR, p_polygon_a, p_polygon_b);
  624. }
  625. static Vector<Vector<Point2> > clip_polyline_with_polygon_2d(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  626. return _polypaths_do_operation(OPERATION_DIFFERENCE, p_polyline, p_polygon, true);
  627. }
  628. static Vector<Vector<Point2> > intersect_polyline_with_polygon_2d(const Vector<Vector2> &p_polyline, const Vector<Vector2> &p_polygon) {
  629. return _polypaths_do_operation(OPERATION_INTERSECTION, p_polyline, p_polygon, true);
  630. }
  631. static Vector<Vector<Point2> > offset_polygon_2d(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type) {
  632. return _polypath_offset(p_polygon, p_delta, p_join_type, END_POLYGON);
  633. }
  634. static Vector<Vector<Point2> > offset_polyline_2d(const Vector<Vector2> &p_polygon, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type) {
  635. ERR_FAIL_COND_V_MSG(p_end_type == END_POLYGON, Vector<Vector<Point2> >(), "Attempt to offset a polyline like a polygon (use offset_polygon_2d instead).");
  636. return _polypath_offset(p_polygon, p_delta, p_join_type, p_end_type);
  637. }
  638. static Vector<int> triangulate_delaunay_2d(const Vector<Vector2> &p_points) {
  639. Vector<Delaunay2D::Triangle> tr = Delaunay2D::triangulate(p_points);
  640. Vector<int> triangles;
  641. for (int i = 0; i < tr.size(); i++) {
  642. triangles.push_back(tr[i].points[0]);
  643. triangles.push_back(tr[i].points[1]);
  644. triangles.push_back(tr[i].points[2]);
  645. }
  646. return triangles;
  647. }
  648. static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) {
  649. Vector<int> triangles;
  650. if (!Triangulate::triangulate(p_polygon, triangles))
  651. return Vector<int>(); //fail
  652. return triangles;
  653. }
  654. static bool is_polygon_clockwise(const Vector<Vector2> &p_polygon) {
  655. int c = p_polygon.size();
  656. if (c < 3)
  657. return false;
  658. const Vector2 *p = p_polygon.ptr();
  659. real_t sum = 0;
  660. for (int i = 0; i < c; i++) {
  661. const Vector2 &v1 = p[i];
  662. const Vector2 &v2 = p[(i + 1) % c];
  663. sum += (v2.x - v1.x) * (v2.y + v1.y);
  664. }
  665. return sum > 0.0f;
  666. }
  667. // Alternate implementation that should be faster.
  668. static bool is_point_in_polygon(const Vector2 &p_point, const Vector<Vector2> &p_polygon) {
  669. int c = p_polygon.size();
  670. if (c < 3)
  671. return false;
  672. const Vector2 *p = p_polygon.ptr();
  673. Vector2 further_away(-1e20, -1e20);
  674. Vector2 further_away_opposite(1e20, 1e20);
  675. for (int i = 0; i < c; i++) {
  676. further_away.x = MAX(p[i].x, further_away.x);
  677. further_away.y = MAX(p[i].y, further_away.y);
  678. further_away_opposite.x = MIN(p[i].x, further_away_opposite.x);
  679. further_away_opposite.y = MIN(p[i].y, further_away_opposite.y);
  680. }
  681. // Make point outside that won't intersect with points in segment from p_point.
  682. further_away += (further_away - further_away_opposite) * Vector2(1.221313, 1.512312);
  683. int intersections = 0;
  684. for (int i = 0; i < c; i++) {
  685. const Vector2 &v1 = p[i];
  686. const Vector2 &v2 = p[(i + 1) % c];
  687. if (segment_intersects_segment_2d(v1, v2, p_point, further_away, NULL)) {
  688. intersections++;
  689. }
  690. }
  691. return (intersections & 1);
  692. }
  693. static PoolVector<PoolVector<Face3> > separate_objects(PoolVector<Face3> p_array);
  694. // Create a "wrap" that encloses the given geometry.
  695. static PoolVector<Face3> wrap_geometry(PoolVector<Face3> p_array, real_t *p_error = NULL);
  696. struct MeshData {
  697. struct Face {
  698. Plane plane;
  699. Vector<int> indices;
  700. };
  701. Vector<Face> faces;
  702. struct Edge {
  703. int a, b;
  704. };
  705. Vector<Edge> edges;
  706. Vector<Vector3> vertices;
  707. void optimize_vertices();
  708. };
  709. _FORCE_INLINE_ static int get_uv84_normal_bit(const Vector3 &p_vector) {
  710. int lat = Math::fast_ftoi(Math::floor(Math::acos(p_vector.dot(Vector3(0, 1, 0))) * 4.0 / Math_PI + 0.5));
  711. if (lat == 0) {
  712. return 24;
  713. } else if (lat == 4) {
  714. return 25;
  715. }
  716. int lon = Math::fast_ftoi(Math::floor((Math_PI + Math::atan2(p_vector.x, p_vector.z)) * 8.0 / (Math_PI * 2.0) + 0.5)) % 8;
  717. return lon + (lat - 1) * 8;
  718. }
  719. _FORCE_INLINE_ static int get_uv84_normal_bit_neighbors(int p_idx) {
  720. if (p_idx == 24) {
  721. return 1 | 2 | 4 | 8;
  722. } else if (p_idx == 25) {
  723. return (1 << 23) | (1 << 22) | (1 << 21) | (1 << 20);
  724. } else {
  725. int ret = 0;
  726. if ((p_idx % 8) == 0)
  727. ret |= (1 << (p_idx + 7));
  728. else
  729. ret |= (1 << (p_idx - 1));
  730. if ((p_idx % 8) == 7)
  731. ret |= (1 << (p_idx - 7));
  732. else
  733. ret |= (1 << (p_idx + 1));
  734. int mask = ret | (1 << p_idx);
  735. if (p_idx < 8)
  736. ret |= 24;
  737. else
  738. ret |= mask >> 8;
  739. if (p_idx >= 16)
  740. ret |= 25;
  741. else
  742. ret |= mask << 8;
  743. return ret;
  744. }
  745. }
  746. static real_t vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) {
  747. return (real_t)(A.x - O.x) * (B.y - O.y) - (real_t)(A.y - O.y) * (B.x - O.x);
  748. }
  749. // Returns a list of points on the convex hull in counter-clockwise order.
  750. // Note: the last point in the returned list is the same as the first one.
  751. static Vector<Point2> convex_hull_2d(Vector<Point2> P) {
  752. int n = P.size(), k = 0;
  753. Vector<Point2> H;
  754. H.resize(2 * n);
  755. // Sort points lexicographically.
  756. P.sort();
  757. // Build lower hull.
  758. for (int i = 0; i < n; ++i) {
  759. while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0)
  760. k--;
  761. H.write[k++] = P[i];
  762. }
  763. // Build upper hull.
  764. for (int i = n - 2, t = k + 1; i >= 0; i--) {
  765. while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0)
  766. k--;
  767. H.write[k++] = P[i];
  768. }
  769. H.resize(k);
  770. return H;
  771. }
  772. static Vector<Vector<Vector2> > decompose_polygon_in_convex(Vector<Point2> polygon);
  773. static MeshData build_convex_mesh(const PoolVector<Plane> &p_planes);
  774. static PoolVector<Plane> build_sphere_planes(real_t p_radius, int p_lats, int p_lons, Vector3::Axis p_axis = Vector3::AXIS_Z);
  775. static PoolVector<Plane> build_box_planes(const Vector3 &p_extents);
  776. static PoolVector<Plane> build_cylinder_planes(real_t p_radius, real_t p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z);
  777. static PoolVector<Plane> build_capsule_planes(real_t p_radius, real_t p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z);
  778. static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
  779. static Vector<Vector3> compute_convex_mesh_points(const Plane *p_planes, int p_plane_count);
  780. private:
  781. 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);
  782. static Vector<Vector<Point2> > _polypath_offset(const Vector<Point2> &p_polypath, real_t p_delta, PolyJoinType p_join_type, PolyEndType p_end_type);
  783. };
  784. #endif