geometry.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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 "dvector.h"
  33. #include "face3.h"
  34. #include "math_2d.h"
  35. #include "object.h"
  36. #include "print_string.h"
  37. #include "triangulate.h"
  38. #include "vector.h"
  39. #include "vector3.h"
  40. /**
  41. @author Juan Linietsky <reduzio@gmail.com>
  42. */
  43. class Geometry {
  44. Geometry();
  45. public:
  46. static float get_closest_points_between_segments(const Vector2 &p1, const Vector2 &q1, const Vector2 &p2, const Vector2 &q2, Vector2 &c1, Vector2 &c2) {
  47. Vector2 d1 = q1 - p1; // Direction vector of segment S1
  48. Vector2 d2 = q2 - p2; // Direction vector of segment S2
  49. Vector2 r = p1 - p2;
  50. float a = d1.dot(d1); // Squared length of segment S1, always nonnegative
  51. float e = d2.dot(d2); // Squared length of segment S2, always nonnegative
  52. float f = d2.dot(r);
  53. float s, t;
  54. // Check if either or both segments degenerate into points
  55. if (a <= CMP_EPSILON && e <= CMP_EPSILON) {
  56. // Both segments degenerate into points
  57. c1 = p1;
  58. c2 = p2;
  59. return Math::sqrt((c1 - c2).dot(c1 - c2));
  60. }
  61. if (a <= CMP_EPSILON) {
  62. // First segment degenerates into a point
  63. s = 0.0f;
  64. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  65. t = CLAMP(t, 0.0f, 1.0f);
  66. } else {
  67. float c = d1.dot(r);
  68. if (e <= CMP_EPSILON) {
  69. // Second segment degenerates into a point
  70. t = 0.0f;
  71. s = CLAMP(-c / a, 0.0f, 1.0f); // t = 0 => s = (b*t - c) / a = -c / a
  72. } else {
  73. // The general nondegenerate case starts here
  74. float b = d1.dot(d2);
  75. float denom = a * e - b * b; // Always nonnegative
  76. // If segments not parallel, compute closest point on L1 to L2 and
  77. // clamp to segment S1. Else pick arbitrary s (here 0)
  78. if (denom != 0.0f) {
  79. s = CLAMP((b * f - c * e) / denom, 0.0f, 1.0f);
  80. } else
  81. s = 0.0f;
  82. // Compute point on L2 closest to S1(s) using
  83. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  84. t = (b * s + f) / e;
  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.0f;
  90. s = CLAMP(-c / a, 0.0f, 1.0f);
  91. } else if (t > 1.0f) {
  92. t = 1.0f;
  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. static void get_closest_points_between_segments(const Vector3 &p1, const Vector3 &p2, const Vector3 &q1, const Vector3 &q2, Vector3 &c1, Vector3 &c2) {
  102. //do the function 'd' as defined by pb. I think is is dot product of some sort
  103. #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))
  104. //caluclate the parpametric position on the 2 curves, mua and mub
  105. float 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));
  106. float mub = (d_of(p1, q1, q2, q1) + mua * d_of(q2, q1, p2, p1)) / d_of(q2, q1, q2, q1);
  107. //clip the value between [0..1] constraining the solution to lie on the original curves
  108. if (mua < 0) mua = 0;
  109. if (mub < 0) mub = 0;
  110. if (mua > 1) mua = 1;
  111. if (mub > 1) mub = 1;
  112. c1 = p1.linear_interpolate(p2, mua);
  113. c2 = q1.linear_interpolate(q2, mub);
  114. }
  115. static float 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) {
  116. Vector3 u = p_to_a - p_from_a;
  117. Vector3 v = p_to_b - p_from_b;
  118. Vector3 w = p_from_a - p_to_a;
  119. real_t a = u.dot(u); // always >= 0
  120. real_t b = u.dot(v);
  121. real_t c = v.dot(v); // always >= 0
  122. real_t d = u.dot(w);
  123. real_t e = v.dot(w);
  124. real_t D = a * c - b * b; // always >= 0
  125. real_t sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  126. real_t tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  127. // compute the line parameters of the two closest points
  128. if (D < CMP_EPSILON) { // the lines are almost parallel
  129. sN = 0.0; // force using point P0 on segment S1
  130. sD = 1.0; // to prevent possible division by 0.0 later
  131. tN = e;
  132. tD = c;
  133. } else { // get the closest points on the infinite lines
  134. sN = (b * e - c * d);
  135. tN = (a * e - b * d);
  136. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  137. sN = 0.0;
  138. tN = e;
  139. tD = c;
  140. } else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  141. sN = sD;
  142. tN = e + b;
  143. tD = c;
  144. }
  145. }
  146. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  147. tN = 0.0;
  148. // recompute sc for this edge
  149. if (-d < 0.0)
  150. sN = 0.0;
  151. else if (-d > a)
  152. sN = sD;
  153. else {
  154. sN = -d;
  155. sD = a;
  156. }
  157. } else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  158. tN = tD;
  159. // recompute sc for this edge
  160. if ((-d + b) < 0.0)
  161. sN = 0;
  162. else if ((-d + b) > a)
  163. sN = sD;
  164. else {
  165. sN = (-d + b);
  166. sD = a;
  167. }
  168. }
  169. // finally do the division to get sc and tc
  170. sc = (Math::abs(sN) < CMP_EPSILON ? 0.0 : sN / sD);
  171. tc = (Math::abs(tN) < CMP_EPSILON ? 0.0 : tN / tD);
  172. // get the difference of the two closest points
  173. Vector3 dP = w + (sc * u) - (tc * v); // = S1(sc) - S2(tc)
  174. return dP.length(); // return the closest distance
  175. }
  176. 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) {
  177. Vector3 e1 = p_v1 - p_v0;
  178. Vector3 e2 = p_v2 - p_v0;
  179. Vector3 h = p_dir.cross(e2);
  180. real_t a = e1.dot(h);
  181. if (a > -CMP_EPSILON && a < CMP_EPSILON) // parallel test
  182. return false;
  183. real_t f = 1.0 / a;
  184. Vector3 s = p_from - p_v0;
  185. real_t u = f * s.dot(h);
  186. if (u < 0.0 || u > 1.0)
  187. return false;
  188. Vector3 q = s.cross(e1);
  189. real_t v = f * p_dir.dot(q);
  190. if (v < 0.0 || u + v > 1.0)
  191. return false;
  192. // at this stage we can compute t to find out where
  193. // the intersection point is on the line
  194. real_t t = f * e2.dot(q);
  195. if (t > 0.00001) { // ray intersection
  196. if (r_res)
  197. *r_res = p_from + p_dir * t;
  198. return true;
  199. } else // this means that there is a line intersection
  200. // but not a ray intersection
  201. return false;
  202. }
  203. 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) {
  204. Vector3 rel = p_to - p_from;
  205. Vector3 e1 = p_v1 - p_v0;
  206. Vector3 e2 = p_v2 - p_v0;
  207. Vector3 h = rel.cross(e2);
  208. real_t a = e1.dot(h);
  209. if (a > -CMP_EPSILON && a < CMP_EPSILON) // parallel test
  210. return false;
  211. real_t f = 1.0 / a;
  212. Vector3 s = p_from - p_v0;
  213. real_t u = f * s.dot(h);
  214. if (u < 0.0 || u > 1.0)
  215. return false;
  216. Vector3 q = s.cross(e1);
  217. real_t v = f * rel.dot(q);
  218. if (v < 0.0 || u + v > 1.0)
  219. return false;
  220. // at this stage we can compute t to find out where
  221. // the intersection point is on the line
  222. real_t t = f * e2.dot(q);
  223. if (t > CMP_EPSILON && t <= 1.0) { // ray intersection
  224. if (r_res)
  225. *r_res = p_from + rel * t;
  226. return true;
  227. } else // this means that there is a line intersection
  228. // but not a ray intersection
  229. return false;
  230. }
  231. 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) {
  232. Vector3 sphere_pos = p_sphere_pos - p_from;
  233. Vector3 rel = (p_to - p_from);
  234. float rel_l = rel.length();
  235. if (rel_l < CMP_EPSILON)
  236. return false; // both points are the same
  237. Vector3 normal = rel / rel_l;
  238. float sphere_d = normal.dot(sphere_pos);
  239. //Vector3 ray_closest=normal*sphere_d;
  240. float ray_distance = sphere_pos.distance_to(normal * sphere_d);
  241. if (ray_distance >= p_sphere_radius)
  242. return false;
  243. float inters_d2 = p_sphere_radius * p_sphere_radius - ray_distance * ray_distance;
  244. float inters_d = sphere_d;
  245. if (inters_d2 >= CMP_EPSILON)
  246. inters_d -= Math::sqrt(inters_d2);
  247. // check in segment
  248. if (inters_d < 0 || inters_d > rel_l)
  249. return false;
  250. Vector3 result = p_from + normal * inters_d;
  251. if (r_res)
  252. *r_res = result;
  253. if (r_norm)
  254. *r_norm = (result - p_sphere_pos).normalized();
  255. return true;
  256. }
  257. static inline bool segment_intersects_cylinder(const Vector3 &p_from, const Vector3 &p_to, float p_height, float p_radius, Vector3 *r_res = 0, Vector3 *r_norm = 0) {
  258. Vector3 rel = (p_to - p_from);
  259. float rel_l = rel.length();
  260. if (rel_l < CMP_EPSILON)
  261. return false; // both points are the same
  262. // first check if they are parallel
  263. Vector3 normal = (rel / rel_l);
  264. Vector3 crs = normal.cross(Vector3(0, 0, 1));
  265. float crs_l = crs.length();
  266. Vector3 z_dir;
  267. if (crs_l < CMP_EPSILON) {
  268. //blahblah parallel
  269. z_dir = Vector3(1, 0, 0); //any x/y vector ok
  270. } else {
  271. z_dir = crs / crs_l;
  272. }
  273. float dist = z_dir.dot(p_from);
  274. if (dist >= p_radius)
  275. return false; // too far away
  276. // convert to 2D
  277. float w2 = p_radius * p_radius - dist * dist;
  278. if (w2 < CMP_EPSILON)
  279. return false; //avoid numerical error
  280. Size2 size(Math::sqrt(w2), p_height * 0.5);
  281. Vector3 x_dir = z_dir.cross(Vector3(0, 0, 1)).normalized();
  282. Vector2 from2D(x_dir.dot(p_from), p_from.z);
  283. Vector2 to2D(x_dir.dot(p_to), p_to.z);
  284. float min = 0, max = 1;
  285. int axis = -1;
  286. for (int i = 0; i < 2; i++) {
  287. real_t seg_from = from2D[i];
  288. real_t seg_to = to2D[i];
  289. real_t box_begin = -size[i];
  290. real_t box_end = size[i];
  291. real_t cmin, cmax;
  292. if (seg_from < seg_to) {
  293. if (seg_from > box_end || seg_to < box_begin)
  294. return false;
  295. real_t length = seg_to - seg_from;
  296. cmin = (seg_from < box_begin) ? ((box_begin - seg_from) / length) : 0;
  297. cmax = (seg_to > box_end) ? ((box_end - seg_from) / length) : 1;
  298. } else {
  299. if (seg_to > box_end || seg_from < box_begin)
  300. return false;
  301. real_t length = seg_to - seg_from;
  302. cmin = (seg_from > box_end) ? (box_end - seg_from) / length : 0;
  303. cmax = (seg_to < box_begin) ? (box_begin - seg_from) / length : 1;
  304. }
  305. if (cmin > min) {
  306. min = cmin;
  307. axis = i;
  308. }
  309. if (cmax < max)
  310. max = cmax;
  311. if (max < min)
  312. return false;
  313. }
  314. // convert to 3D again
  315. Vector3 result = p_from + (rel * min);
  316. Vector3 res_normal = result;
  317. if (axis == 0) {
  318. res_normal.z = 0;
  319. } else {
  320. res_normal.x = 0;
  321. res_normal.y = 0;
  322. }
  323. res_normal.normalize();
  324. if (r_res)
  325. *r_res = result;
  326. if (r_norm)
  327. *r_norm = res_normal;
  328. return true;
  329. }
  330. 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) {
  331. real_t min = -1e20, max = 1e20;
  332. Vector3 rel = p_to - p_from;
  333. real_t rel_l = rel.length();
  334. if (rel_l < CMP_EPSILON)
  335. return false;
  336. Vector3 dir = rel / rel_l;
  337. int min_index = -1;
  338. for (int i = 0; i < p_plane_count; i++) {
  339. const Plane &p = p_planes[i];
  340. real_t den = p.normal.dot(dir);
  341. //printf("den is %i\n",den);
  342. if (Math::abs(den) <= CMP_EPSILON)
  343. continue; // ignore parallel plane
  344. real_t dist = -p.distance_to(p_from) / den;
  345. if (den > 0) {
  346. //backwards facing plane
  347. if (dist < max)
  348. max = dist;
  349. } else {
  350. //front facing plane
  351. if (dist > min) {
  352. min = dist;
  353. min_index = i;
  354. }
  355. }
  356. }
  357. if (max <= min || min < 0 || min > rel_l || min_index == -1) // exit conditions
  358. return false; // no intersection
  359. if (p_res)
  360. *p_res = p_from + dir * min;
  361. if (p_norm)
  362. *p_norm = p_planes[min_index].normal;
  363. return true;
  364. }
  365. static Vector3 get_closest_point_to_segment(const Vector3 &p_point, const Vector3 *p_segment) {
  366. Vector3 p = p_point - p_segment[0];
  367. Vector3 n = p_segment[1] - p_segment[0];
  368. float l = n.length();
  369. if (l < 1e-10)
  370. return p_segment[0]; // both points are the same, just give any
  371. n /= l;
  372. float d = n.dot(p);
  373. if (d <= 0.0)
  374. return p_segment[0]; // before first point
  375. else if (d >= l)
  376. return p_segment[1]; // after first point
  377. else
  378. return p_segment[0] + n * d; // inside
  379. }
  380. static Vector3 get_closest_point_to_segment_uncapped(const Vector3 &p_point, const Vector3 *p_segment) {
  381. Vector3 p = p_point - p_segment[0];
  382. Vector3 n = p_segment[1] - p_segment[0];
  383. float l = n.length();
  384. if (l < 1e-10)
  385. return p_segment[0]; // both points are the same, just give any
  386. n /= l;
  387. float d = n.dot(p);
  388. return p_segment[0] + n * d; // inside
  389. }
  390. static Vector2 get_closest_point_to_segment_2d(const Vector2 &p_point, const Vector2 *p_segment) {
  391. Vector2 p = p_point - p_segment[0];
  392. Vector2 n = p_segment[1] - p_segment[0];
  393. float l = n.length();
  394. if (l < 1e-10)
  395. return p_segment[0]; // both points are the same, just give any
  396. n /= l;
  397. float d = n.dot(p);
  398. if (d <= 0.0)
  399. return p_segment[0]; // before first point
  400. else if (d >= l)
  401. return p_segment[1]; // after first point
  402. else
  403. return p_segment[0] + n * d; // inside
  404. }
  405. static bool is_point_in_triangle(const Vector2 &s, const Vector2 &a, const Vector2 &b, const Vector2 &c) {
  406. int as_x = s.x - a.x;
  407. int as_y = s.y - a.y;
  408. bool s_ab = (b.x - a.x) * as_y - (b.y - a.y) * as_x > 0;
  409. if (((c.x - a.x) * as_y - (c.y - a.y) * as_x > 0) == s_ab) return false;
  410. if (((c.x - b.x) * (s.y - b.y) - (c.y - b.y) * (s.x - b.x) > 0) != s_ab) return false;
  411. return true;
  412. }
  413. static Vector2 get_closest_point_to_segment_uncapped_2d(const Vector2 &p_point, const Vector2 *p_segment) {
  414. Vector2 p = p_point - p_segment[0];
  415. Vector2 n = p_segment[1] - p_segment[0];
  416. float l = n.length();
  417. if (l < 1e-10)
  418. return p_segment[0]; // both points are the same, just give any
  419. n /= l;
  420. float d = n.dot(p);
  421. return p_segment[0] + n * d; // inside
  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. float 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. float 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 i could discard by range here to make the algorithm quicker? dunno..
  476. // check point within cylinder radius
  477. Vector3 axis = n1.cross(n2).cross(n1);
  478. axis.normalize(); // ugh
  479. float 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. float 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. //printf("solved inside edge\n");
  492. return true;
  493. }
  494. float r2 = p_sphere_radius * p_sphere_radius;
  495. if (n2.length_squared() < r2) {
  496. Vector3 n = (p_sphere_pos - verts[i + 1]).normalized();
  497. //r_triangle_contact=verts[i+1]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2));
  498. r_triangle_contact = verts[i + 1];
  499. r_sphere_contact = p_sphere_pos - n * p_sphere_radius;
  500. //printf("solved inside point segment 1\n");
  501. return true;
  502. }
  503. if (n2.distance_squared_to(n1) < r2) {
  504. Vector3 n = (p_sphere_pos - verts[i]).normalized();
  505. //r_triangle_contact=verts[i]+n*p_sphere_radius;p_sphere_pos+axis*(p_sphere_radius-axis.dot(n2));
  506. r_triangle_contact = verts[i];
  507. r_sphere_contact = p_sphere_pos - n * p_sphere_radius;
  508. //printf("solved inside point segment 1\n");
  509. return true;
  510. }
  511. break; // It's pointless to continue at this point, so save some cpu cycles
  512. }
  513. return false;
  514. }
  515. static real_t segment_intersects_circle(const Vector2 &p_from, const Vector2 &p_to, const Vector2 &p_circle_pos, real_t p_circle_radius) {
  516. Vector2 line_vec = p_to - p_from;
  517. Vector2 vec_to_line = p_from - p_circle_pos;
  518. /* create a quadratic formula of the form ax^2 + bx + c = 0 */
  519. real_t a, b, c;
  520. a = line_vec.dot(line_vec);
  521. b = 2 * vec_to_line.dot(line_vec);
  522. c = vec_to_line.dot(vec_to_line) - p_circle_radius * p_circle_radius;
  523. /* solve for t */
  524. real_t sqrtterm = b * b - 4 * a * c;
  525. /* if the term we intend to square root is less than 0 then the answer won't be real, so it definitely won't be t in the range 0 to 1 */
  526. if (sqrtterm < 0) return -1;
  527. /* if we can assume that the line segment starts outside the circle (e.g. for continuous time collision detection) 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. return (res1 >= 0 && res1 <= 1) ? res1 : -1;
  532. }
  533. static inline Vector<Vector3> clip_polygon(const Vector<Vector3> &polygon, const Plane &p_plane) {
  534. enum LocationCache {
  535. LOC_INSIDE = 1,
  536. LOC_BOUNDARY = 0,
  537. LOC_OUTSIDE = -1
  538. };
  539. if (polygon.size() == 0)
  540. return polygon;
  541. int *location_cache = (int *)alloca(sizeof(int) * polygon.size());
  542. int inside_count = 0;
  543. int outside_count = 0;
  544. for (int a = 0; a < polygon.size(); a++) {
  545. //float p_plane.d = (*this) * polygon[a];
  546. float dist = p_plane.distance_to(polygon[a]);
  547. if (dist < -CMP_POINT_IN_PLANE_EPSILON) {
  548. location_cache[a] = LOC_INSIDE;
  549. inside_count++;
  550. } else {
  551. if (dist > CMP_POINT_IN_PLANE_EPSILON) {
  552. location_cache[a] = LOC_OUTSIDE;
  553. outside_count++;
  554. } else {
  555. location_cache[a] = LOC_BOUNDARY;
  556. }
  557. }
  558. }
  559. if (outside_count == 0) {
  560. return polygon; // no changes
  561. } else if (inside_count == 0) {
  562. return Vector<Vector3>(); //empty
  563. }
  564. // long count = 0;
  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. double den = p_plane.normal.dot(segment);
  575. double 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. double den = p_plane.normal.dot(segment);
  585. double 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. static Vector<int> triangulate_polygon(const Vector<Vector2> &p_polygon) {
  596. Vector<int> triangles;
  597. if (!Triangulate::triangulate(p_polygon, triangles))
  598. return Vector<int>(); //fail
  599. return triangles;
  600. }
  601. static Vector<Vector<Vector2> > (*_decompose_func)(const Vector<Vector2> &p_polygon);
  602. static Vector<Vector<Vector2> > decompose_polygon(const Vector<Vector2> &p_polygon) {
  603. if (_decompose_func)
  604. return _decompose_func(p_polygon);
  605. return Vector<Vector<Vector2> >();
  606. }
  607. static DVector<DVector<Face3> > separate_objects(DVector<Face3> p_array);
  608. static DVector<Face3> wrap_geometry(DVector<Face3> p_array, float *p_error = NULL); ///< create a "wrap" that encloses the given geometry
  609. struct MeshData {
  610. struct Face {
  611. Plane plane;
  612. Vector<int> indices;
  613. };
  614. Vector<Face> faces;
  615. struct Edge {
  616. int a, b;
  617. };
  618. Vector<Edge> edges;
  619. Vector<Vector3> vertices;
  620. void optimize_vertices();
  621. };
  622. _FORCE_INLINE_ static int get_uv84_normal_bit(const Vector3 &p_vector) {
  623. int lat = Math::fast_ftoi(Math::floor(Math::acos(p_vector.dot(Vector3(0, 1, 0))) * 4.0 / Math_PI + 0.5));
  624. if (lat == 0) {
  625. return 24;
  626. } else if (lat == 4) {
  627. return 25;
  628. }
  629. 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;
  630. return lon + (lat - 1) * 8;
  631. }
  632. _FORCE_INLINE_ static int get_uv84_normal_bit_neighbors(int p_idx) {
  633. if (p_idx == 24) {
  634. return 1 | 2 | 4 | 8;
  635. } else if (p_idx == 25) {
  636. return (1 << 23) | (1 << 22) | (1 << 21) | (1 << 20);
  637. } else {
  638. int ret = 0;
  639. if ((p_idx % 8) == 0)
  640. ret |= (1 << (p_idx + 7));
  641. else
  642. ret |= (1 << (p_idx - 1));
  643. if ((p_idx % 8) == 7)
  644. ret |= (1 << (p_idx - 7));
  645. else
  646. ret |= (1 << (p_idx + 1));
  647. int mask = ret | (1 << p_idx);
  648. if (p_idx < 8)
  649. ret |= 24;
  650. else
  651. ret |= mask >> 8;
  652. if (p_idx >= 16)
  653. ret |= 25;
  654. else
  655. ret |= mask << 8;
  656. return ret;
  657. }
  658. }
  659. static double vec2_cross(const Point2 &O, const Point2 &A, const Point2 &B) {
  660. return (double)(A.x - O.x) * (B.y - O.y) - (double)(A.y - O.y) * (B.x - O.x);
  661. }
  662. // Returns a list of points on the convex hull in counter-clockwise order.
  663. // Note: the last point in the returned list is the same as the first one.
  664. static Vector<Point2> convex_hull_2d(Vector<Point2> P) {
  665. int n = P.size(), k = 0;
  666. Vector<Point2> H;
  667. H.resize(2 * n);
  668. // Sort points lexicographically
  669. P.sort();
  670. // Build lower hull
  671. for (int i = 0; i < n; ++i) {
  672. while (k >= 2 && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0)
  673. k--;
  674. H[k++] = P[i];
  675. }
  676. // Build upper hull
  677. for (int i = n - 2, t = k + 1; i >= 0; i--) {
  678. while (k >= t && vec2_cross(H[k - 2], H[k - 1], P[i]) <= 0)
  679. k--;
  680. H[k++] = P[i];
  681. }
  682. H.resize(k);
  683. return H;
  684. }
  685. static MeshData build_convex_mesh(const DVector<Plane> &p_planes);
  686. static DVector<Plane> build_sphere_planes(float p_radius, int p_lats, int p_lons, Vector3::Axis p_axis = Vector3::AXIS_Z);
  687. static DVector<Plane> build_box_planes(const Vector3 &p_extents);
  688. static DVector<Plane> build_cylinder_planes(float p_radius, float p_height, int p_sides, Vector3::Axis p_axis = Vector3::AXIS_Z);
  689. static DVector<Plane> build_capsule_planes(float p_radius, float p_height, int p_sides, int p_lats, Vector3::Axis p_axis = Vector3::AXIS_Z);
  690. static void make_atlas(const Vector<Size2i> &p_rects, Vector<Point2i> &r_result, Size2i &r_size);
  691. };
  692. #endif