cpCollision.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. /* Copyright (c) 2013 Scott Lembcke and Howling Moon Software
  2. *
  3. * Permission is hereby granted, free of charge, to any person obtaining a copy
  4. * of this software and associated documentation files (the "Software"), to deal
  5. * in the Software without restriction, including without limitation the rights
  6. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. * copies of the Software, and to permit persons to whom the Software is
  8. * furnished to do so, subject to the following conditions:
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. *
  13. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. * SOFTWARE.
  20. */
  21. #include <stdio.h>
  22. #include <string.h>
  23. #include "chipmunk/chipmunk_private.h"
  24. #include "chipmunk/cpRobust.h"
  25. #if DEBUG && 0
  26. #include "ChipmunkDemo.h"
  27. #define DRAW_ALL 0
  28. #define DRAW_GJK (0 || DRAW_ALL)
  29. #define DRAW_EPA (0 || DRAW_ALL)
  30. #define DRAW_CLOSEST (0 || DRAW_ALL)
  31. #define DRAW_CLIP (0 || DRAW_ALL)
  32. #define PRINT_LOG 0
  33. #endif
  34. #define MAX_GJK_ITERATIONS 30
  35. #define MAX_EPA_ITERATIONS 30
  36. #define WARN_GJK_ITERATIONS 20
  37. #define WARN_EPA_ITERATIONS 20
  38. static inline void
  39. cpCollisionInfoPushContact(struct cpCollisionInfo *info, cpVect p1, cpVect p2, cpHashValue hash)
  40. {
  41. cpAssertSoft(info->count <= CP_MAX_CONTACTS_PER_ARBITER, "Internal error: Tried to push too many contacts.");
  42. struct cpContact *con = &info->arr[info->count];
  43. con->r1 = p1;
  44. con->r2 = p2;
  45. con->hash = hash;
  46. info->count++;
  47. }
  48. //MARK: Support Points and Edges:
  49. // Support points are the maximal points on a shape's perimeter along a certain axis.
  50. // The GJK and EPA algorithms use support points to iteratively sample the surface of the two shapes' minkowski difference.
  51. static inline int
  52. PolySupportPointIndex(const int count, const struct cpSplittingPlane *planes, const cpVect n)
  53. {
  54. cpFloat max = -INFINITY;
  55. int index = 0;
  56. for(int i=0; i<count; i++){
  57. cpVect v = planes[i].v0;
  58. cpFloat d = cpvdot(v, n);
  59. if(d > max){
  60. max = d;
  61. index = i;
  62. }
  63. }
  64. return index;
  65. }
  66. struct SupportPoint {
  67. cpVect p;
  68. // Save an index of the point so it can be cheaply looked up as a starting point for the next frame.
  69. cpCollisionID index;
  70. };
  71. static inline struct SupportPoint
  72. SupportPointNew(cpVect p, cpCollisionID index)
  73. {
  74. struct SupportPoint point = {p, index};
  75. return point;
  76. }
  77. typedef struct SupportPoint (*SupportPointFunc)(const cpShape *shape, const cpVect n);
  78. static inline struct SupportPoint
  79. CircleSupportPoint(const cpCircleShape *circle, const cpVect n)
  80. {
  81. return SupportPointNew(circle->tc, 0);
  82. }
  83. static inline struct SupportPoint
  84. SegmentSupportPoint(const cpSegmentShape *seg, const cpVect n)
  85. {
  86. if(cpvdot(seg->ta, n) > cpvdot(seg->tb, n)){
  87. return SupportPointNew(seg->ta, 0);
  88. } else {
  89. return SupportPointNew(seg->tb, 1);
  90. }
  91. }
  92. static inline struct SupportPoint
  93. PolySupportPoint(const cpPolyShape *poly, const cpVect n)
  94. {
  95. const struct cpSplittingPlane *planes = poly->planes;
  96. int i = PolySupportPointIndex(poly->count, planes, n);
  97. return SupportPointNew(planes[i].v0, i);
  98. }
  99. // A point on the surface of two shape's minkowski difference.
  100. struct MinkowskiPoint {
  101. // Cache the two original support points.
  102. cpVect a, b;
  103. // b - a
  104. cpVect ab;
  105. // Concatenate the two support point indexes.
  106. cpCollisionID id;
  107. };
  108. static inline struct MinkowskiPoint
  109. MinkowskiPointNew(const struct SupportPoint a, const struct SupportPoint b)
  110. {
  111. struct MinkowskiPoint point = {a.p, b.p, cpvsub(b.p, a.p), (a.index & 0xFF)<<8 | (b.index & 0xFF)};
  112. return point;
  113. }
  114. struct SupportContext {
  115. const cpShape *shape1, *shape2;
  116. SupportPointFunc func1, func2;
  117. };
  118. // Calculate the maximal point on the minkowski difference of two shapes along a particular axis.
  119. static inline struct MinkowskiPoint
  120. Support(const struct SupportContext *ctx, const cpVect n)
  121. {
  122. struct SupportPoint a = ctx->func1(ctx->shape1, cpvneg(n));
  123. struct SupportPoint b = ctx->func2(ctx->shape2, n);
  124. return MinkowskiPointNew(a, b);
  125. }
  126. struct EdgePoint {
  127. cpVect p;
  128. // Keep a hash value for Chipmunk's collision hashing mechanism.
  129. cpHashValue hash;
  130. };
  131. // Support edges are the edges of a polygon or segment shape that are in contact.
  132. struct Edge {
  133. struct EdgePoint a, b;
  134. cpFloat r;
  135. cpVect n;
  136. };
  137. static struct Edge
  138. SupportEdgeForPoly(const cpPolyShape *poly, const cpVect n)
  139. {
  140. int count = poly->count;
  141. int i1 = PolySupportPointIndex(poly->count, poly->planes, n);
  142. // TODO: get rid of mod eventually, very expensive on ARM
  143. int i0 = (i1 - 1 + count)%count;
  144. int i2 = (i1 + 1)%count;
  145. const struct cpSplittingPlane *planes = poly->planes;
  146. cpHashValue hashid = poly->shape.hashid;
  147. if(cpvdot(n, planes[i1].n) > cpvdot(n, planes[i2].n)){
  148. struct Edge edge = {{planes[i0].v0, CP_HASH_PAIR(hashid, i0)}, {planes[i1].v0, CP_HASH_PAIR(hashid, i1)}, poly->r, planes[i1].n};
  149. return edge;
  150. } else {
  151. struct Edge edge = {{planes[i1].v0, CP_HASH_PAIR(hashid, i1)}, {planes[i2].v0, CP_HASH_PAIR(hashid, i2)}, poly->r, planes[i2].n};
  152. return edge;
  153. }
  154. }
  155. static struct Edge
  156. SupportEdgeForSegment(const cpSegmentShape *seg, const cpVect n)
  157. {
  158. cpHashValue hashid = seg->shape.hashid;
  159. if(cpvdot(seg->tn, n) > 0.0){
  160. struct Edge edge = {{seg->ta, CP_HASH_PAIR(hashid, 0)}, {seg->tb, CP_HASH_PAIR(hashid, 1)}, seg->r, seg->tn};
  161. return edge;
  162. } else {
  163. struct Edge edge = {{seg->tb, CP_HASH_PAIR(hashid, 1)}, {seg->ta, CP_HASH_PAIR(hashid, 0)}, seg->r, cpvneg(seg->tn)};
  164. return edge;
  165. }
  166. }
  167. // Find the closest p(t) to (0, 0) where p(t) = a*(1-t)/2 + b*(1+t)/2
  168. // The range for t is [-1, 1] to avoid floating point issues if the parameters are swapped.
  169. static inline cpFloat
  170. ClosestT(const cpVect a, const cpVect b)
  171. {
  172. cpVect delta = cpvsub(b, a);
  173. return -cpfclamp(cpvdot(delta, cpvadd(a, b))/cpvlengthsq(delta), -1.0f, 1.0f);
  174. }
  175. // Basically the same as cpvlerp(), except t = [-1, 1]
  176. static inline cpVect
  177. LerpT(const cpVect a, const cpVect b, const cpFloat t)
  178. {
  179. cpFloat ht = 0.5f*t;
  180. return cpvadd(cpvmult(a, 0.5f - ht), cpvmult(b, 0.5f + ht));
  181. }
  182. // Closest points on the surface of two shapes.
  183. struct ClosestPoints {
  184. // Surface points in absolute coordinates.
  185. cpVect a, b;
  186. // Minimum separating axis of the two shapes.
  187. cpVect n;
  188. // Signed distance between the points.
  189. cpFloat d;
  190. // Concatenation of the id's of the minkoski points.
  191. cpCollisionID id;
  192. };
  193. // Calculate the closest points on two shapes given the closest edge on their minkowski difference to (0, 0)
  194. static inline struct ClosestPoints
  195. ClosestPointsNew(const struct MinkowskiPoint v0, const struct MinkowskiPoint v1)
  196. {
  197. // Find the closest p(t) on the minkowski difference to (0, 0)
  198. cpFloat t = ClosestT(v0.ab, v1.ab);
  199. cpVect p = LerpT(v0.ab, v1.ab, t);
  200. // Interpolate the original support points using the same 't' value as above.
  201. // This gives you the closest surface points in absolute coordinates. NEAT!
  202. cpVect pa = LerpT(v0.a, v1.a, t);
  203. cpVect pb = LerpT(v0.b, v1.b, t);
  204. cpCollisionID id = (v0.id & 0xFFFF)<<16 | (v1.id & 0xFFFF);
  205. // First try calculating the MSA from the minkowski difference edge.
  206. // This gives us a nice, accurate MSA when the surfaces are close together.
  207. cpVect delta = cpvsub(v1.ab, v0.ab);
  208. cpVect n = cpvnormalize(cpvrperp(delta));
  209. cpFloat d = cpvdot(n, p);
  210. if(d <= 0.0f || (-1.0f < t && t < 1.0f)){
  211. // If the shapes are overlapping, or we have a regular vertex/edge collision, we are done.
  212. struct ClosestPoints points = {pa, pb, n, d, id};
  213. return points;
  214. } else {
  215. // Vertex/vertex collisions need special treatment since the MSA won't be shared with an axis of the minkowski difference.
  216. cpFloat d2 = cpvlength(p);
  217. cpVect n2 = cpvmult(p, 1.0f/(d2 + CPFLOAT_MIN));
  218. struct ClosestPoints points = {pa, pb, n2, d2, id};
  219. return points;
  220. }
  221. }
  222. //MARK: EPA Functions
  223. static inline cpFloat
  224. ClosestDist(const cpVect v0,const cpVect v1)
  225. {
  226. return cpvlengthsq(LerpT(v0, v1, ClosestT(v0, v1)));
  227. }
  228. // Recursive implementation of the EPA loop.
  229. // Each recursion adds a point to the convex hull until it's known that we have the closest point on the surface.
  230. static struct ClosestPoints
  231. EPARecurse(const struct SupportContext *ctx, const int count, const struct MinkowskiPoint *hull, const int iteration)
  232. {
  233. int mini = 0;
  234. cpFloat minDist = INFINITY;
  235. // TODO: precalculate this when building the hull and save a step.
  236. // Find the closest segment hull[i] and hull[i + 1] to (0, 0)
  237. for(int j=0, i=count-1; j<count; i=j, j++){
  238. cpFloat d = ClosestDist(hull[i].ab, hull[j].ab);
  239. if(d < minDist){
  240. minDist = d;
  241. mini = i;
  242. }
  243. }
  244. struct MinkowskiPoint v0 = hull[mini];
  245. struct MinkowskiPoint v1 = hull[(mini + 1)%count];
  246. cpAssertSoft(!cpveql(v0.ab, v1.ab), "Internal Error: EPA vertexes are the same (%d and %d)", mini, (mini + 1)%count);
  247. // Check if there is a point on the minkowski difference beyond this edge.
  248. struct MinkowskiPoint p = Support(ctx, cpvperp(cpvsub(v1.ab, v0.ab)));
  249. #if DRAW_EPA
  250. cpVect verts[count];
  251. for(int i=0; i<count; i++) verts[i] = hull[i].ab;
  252. ChipmunkDebugDrawPolygon(count, verts, 0.0, RGBAColor(1, 1, 0, 1), RGBAColor(1, 1, 0, 0.25));
  253. ChipmunkDebugDrawSegment(v0.ab, v1.ab, RGBAColor(1, 0, 0, 1));
  254. ChipmunkDebugDrawDot(5, p.ab, LAColor(1, 1));
  255. #endif
  256. // The usual exit condition is a duplicated vertex.
  257. // Much faster to check the ids than to check the signed area.
  258. cpBool duplicate = (p.id == v0.id || p.id == v1.id);
  259. if(!duplicate && cpCheckPointGreater(v0.ab, v1.ab, p.ab) && iteration < MAX_EPA_ITERATIONS){
  260. // Rebuild the convex hull by inserting p.
  261. struct MinkowskiPoint *hull2 = (struct MinkowskiPoint *)alloca((count + 1)*sizeof(struct MinkowskiPoint));
  262. int count2 = 1;
  263. hull2[0] = p;
  264. for(int i=0; i<count; i++){
  265. int index = (mini + 1 + i)%count;
  266. cpVect h0 = hull2[count2 - 1].ab;
  267. cpVect h1 = hull[index].ab;
  268. cpVect h2 = (i + 1 < count ? hull[(index + 1)%count] : p).ab;
  269. if(cpCheckPointGreater(h0, h2, h1)){
  270. hull2[count2] = hull[index];
  271. count2++;
  272. }
  273. }
  274. return EPARecurse(ctx, count2, hull2, iteration + 1);
  275. } else {
  276. // Could not find a new point to insert, so we have found the closest edge of the minkowski difference.
  277. cpAssertWarn(iteration < WARN_EPA_ITERATIONS, "High EPA iterations: %d", iteration);
  278. return ClosestPointsNew(v0, v1);
  279. }
  280. }
  281. // Find the closest points on the surface of two overlapping shapes using the EPA algorithm.
  282. // EPA is called from GJK when two shapes overlap.
  283. // This is a moderately expensive step! Avoid it by adding radii to your shapes so their inner polygons won't overlap.
  284. static struct ClosestPoints
  285. EPA(const struct SupportContext *ctx, const struct MinkowskiPoint v0, const struct MinkowskiPoint v1, const struct MinkowskiPoint v2)
  286. {
  287. // TODO: allocate a NxM array here and do an in place convex hull reduction in EPARecurse?
  288. struct MinkowskiPoint hull[3] = {v0, v1, v2};
  289. return EPARecurse(ctx, 3, hull, 1);
  290. }
  291. //MARK: GJK Functions.
  292. // Recursive implementation of the GJK loop.
  293. static inline struct ClosestPoints
  294. GJKRecurse(const struct SupportContext *ctx, const struct MinkowskiPoint v0, const struct MinkowskiPoint v1, const int iteration)
  295. {
  296. if(iteration > MAX_GJK_ITERATIONS){
  297. cpAssertWarn(iteration < WARN_GJK_ITERATIONS, "High GJK iterations: %d", iteration);
  298. return ClosestPointsNew(v0, v1);
  299. }
  300. if(cpCheckPointGreater(v1.ab, v0.ab, cpvzero)){
  301. // Origin is behind axis. Flip and try again.
  302. return GJKRecurse(ctx, v1, v0, iteration);
  303. } else {
  304. cpFloat t = ClosestT(v0.ab, v1.ab);
  305. cpVect n = (-1.0f < t && t < 1.0f ? cpvperp(cpvsub(v1.ab, v0.ab)) : cpvneg(LerpT(v0.ab, v1.ab, t)));
  306. struct MinkowskiPoint p = Support(ctx, n);
  307. #if DRAW_GJK
  308. ChipmunkDebugDrawSegment(v0.ab, v1.ab, RGBAColor(1, 1, 1, 1));
  309. cpVect c = cpvlerp(v0.ab, v1.ab, 0.5);
  310. ChipmunkDebugDrawSegment(c, cpvadd(c, cpvmult(cpvnormalize(n), 5.0)), RGBAColor(1, 0, 0, 1));
  311. ChipmunkDebugDrawDot(5.0, p.ab, LAColor(1, 1));
  312. #endif
  313. if(cpCheckPointGreater(p.ab, v0.ab, cpvzero) && cpCheckPointGreater(v1.ab, p.ab, cpvzero)){
  314. // The triangle v0, p, v1 contains the origin. Use EPA to find the MSA.
  315. cpAssertWarn(iteration < WARN_GJK_ITERATIONS, "High GJK->EPA iterations: %d", iteration);
  316. return EPA(ctx, v0, p, v1);
  317. } else {
  318. if(cpCheckAxis(v0.ab, v1.ab, p.ab, n)){
  319. // The edge v0, v1 that we already have is the closest to (0, 0) since p was not closer.
  320. cpAssertWarn(iteration < WARN_GJK_ITERATIONS, "High GJK iterations: %d", iteration);
  321. return ClosestPointsNew(v0, v1);
  322. } else {
  323. // p was closer to the origin than our existing edge.
  324. // Need to figure out which existing point to drop.
  325. if(ClosestDist(v0.ab, p.ab) < ClosestDist(p.ab, v1.ab)){
  326. return GJKRecurse(ctx, v0, p, iteration + 1);
  327. } else {
  328. return GJKRecurse(ctx, p, v1, iteration + 1);
  329. }
  330. }
  331. }
  332. }
  333. }
  334. // Get a SupportPoint from a cached shape and index.
  335. static struct SupportPoint
  336. ShapePoint(const cpShape *shape, const int i)
  337. {
  338. switch(shape->klass->type){
  339. case CP_CIRCLE_SHAPE: {
  340. return SupportPointNew(((cpCircleShape *)shape)->tc, 0);
  341. } case CP_SEGMENT_SHAPE: {
  342. cpSegmentShape *seg = (cpSegmentShape *)shape;
  343. return SupportPointNew(i == 0 ? seg->ta : seg->tb, i);
  344. } case CP_POLY_SHAPE: {
  345. cpPolyShape *poly = (cpPolyShape *)shape;
  346. // Poly shapes may change vertex count.
  347. int index = (i < poly->count ? i : 0);
  348. return SupportPointNew(poly->planes[index].v0, index);
  349. } default: {
  350. return SupportPointNew(cpvzero, 0);
  351. }
  352. }
  353. }
  354. // Find the closest points between two shapes using the GJK algorithm.
  355. static struct ClosestPoints
  356. GJK(const struct SupportContext *ctx, cpCollisionID *id)
  357. {
  358. #if DRAW_GJK || DRAW_EPA
  359. int count1 = 1;
  360. int count2 = 1;
  361. switch(ctx->shape1->klass->type){
  362. case CP_SEGMENT_SHAPE: count1 = 2; break;
  363. case CP_POLY_SHAPE: count1 = ((cpPolyShape *)ctx->shape1)->count; break;
  364. default: break;
  365. }
  366. switch(ctx->shape2->klass->type){
  367. case CP_SEGMENT_SHAPE: count1 = 2; break;
  368. case CP_POLY_SHAPE: count2 = ((cpPolyShape *)ctx->shape2)->count; break;
  369. default: break;
  370. }
  371. // draw the minkowski difference origin
  372. cpVect origin = cpvzero;
  373. ChipmunkDebugDrawDot(5.0, origin, RGBAColor(1,0,0,1));
  374. int mdiffCount = count1*count2;
  375. cpVect *mdiffVerts = alloca(mdiffCount*sizeof(cpVect));
  376. for(int i=0; i<count1; i++){
  377. for(int j=0; j<count2; j++){
  378. cpVect v = cpvsub(ShapePoint(ctx->shape2, j).p, ShapePoint(ctx->shape1, i).p);
  379. mdiffVerts[i*count2 + j] = v;
  380. ChipmunkDebugDrawDot(2.0, v, RGBAColor(1, 0, 0, 1));
  381. }
  382. }
  383. cpVect *hullVerts = alloca(mdiffCount*sizeof(cpVect));
  384. int hullCount = cpConvexHull(mdiffCount, mdiffVerts, hullVerts, NULL, 0.0);
  385. ChipmunkDebugDrawPolygon(hullCount, hullVerts, 0.0, RGBAColor(1, 0, 0, 1), RGBAColor(1, 0, 0, 0.25));
  386. #endif
  387. struct MinkowskiPoint v0, v1;
  388. if(*id){
  389. // Use the minkowski points from the last frame as a starting point using the cached indexes.
  390. v0 = MinkowskiPointNew(ShapePoint(ctx->shape1, (*id>>24)&0xFF), ShapePoint(ctx->shape2, (*id>>16)&0xFF));
  391. v1 = MinkowskiPointNew(ShapePoint(ctx->shape1, (*id>> 8)&0xFF), ShapePoint(ctx->shape2, (*id )&0xFF));
  392. } else {
  393. // No cached indexes, use the shapes' bounding box centers as a guess for a starting axis.
  394. cpVect axis = cpvperp(cpvsub(cpBBCenter(ctx->shape1->bb), cpBBCenter(ctx->shape2->bb)));
  395. v0 = Support(ctx, axis);
  396. v1 = Support(ctx, cpvneg(axis));
  397. }
  398. struct ClosestPoints points = GJKRecurse(ctx, v0, v1, 1);
  399. *id = points.id;
  400. return points;
  401. }
  402. //MARK: Contact Clipping
  403. // Given two support edges, find contact point pairs on their surfaces.
  404. static inline void
  405. ContactPoints(const struct Edge e1, const struct Edge e2, const struct ClosestPoints points, struct cpCollisionInfo *info)
  406. {
  407. cpFloat mindist = e1.r + e2.r;
  408. if(points.d <= mindist){
  409. #ifdef DRAW_CLIP
  410. ChipmunkDebugDrawFatSegment(e1.a.p, e1.b.p, e1.r, RGBAColor(0, 1, 0, 1), LAColor(0, 0));
  411. ChipmunkDebugDrawFatSegment(e2.a.p, e2.b.p, e2.r, RGBAColor(1, 0, 0, 1), LAColor(0, 0));
  412. #endif
  413. cpVect n = info->n = points.n;
  414. // Distances along the axis parallel to n
  415. cpFloat d_e1_a = cpvcross(e1.a.p, n);
  416. cpFloat d_e1_b = cpvcross(e1.b.p, n);
  417. cpFloat d_e2_a = cpvcross(e2.a.p, n);
  418. cpFloat d_e2_b = cpvcross(e2.b.p, n);
  419. // TODO + min isn't a complete fix.
  420. cpFloat e1_denom = 1.0f/(d_e1_b - d_e1_a + CPFLOAT_MIN);
  421. cpFloat e2_denom = 1.0f/(d_e2_b - d_e2_a + CPFLOAT_MIN);
  422. // Project the endpoints of the two edges onto the opposing edge, clamping them as necessary.
  423. // Compare the projected points to the collision normal to see if the shapes overlap there.
  424. {
  425. cpVect p1 = cpvadd(cpvmult(n, e1.r), cpvlerp(e1.a.p, e1.b.p, cpfclamp01((d_e2_b - d_e1_a)*e1_denom)));
  426. cpVect p2 = cpvadd(cpvmult(n, -e2.r), cpvlerp(e2.a.p, e2.b.p, cpfclamp01((d_e1_a - d_e2_a)*e2_denom)));
  427. cpFloat dist = cpvdot(cpvsub(p2, p1), n);
  428. if(dist <= 0.0f){
  429. cpHashValue hash_1a2b = CP_HASH_PAIR(e1.a.hash, e2.b.hash);
  430. cpCollisionInfoPushContact(info, p1, p2, hash_1a2b);
  431. }
  432. }{
  433. cpVect p1 = cpvadd(cpvmult(n, e1.r), cpvlerp(e1.a.p, e1.b.p, cpfclamp01((d_e2_a - d_e1_a)*e1_denom)));
  434. cpVect p2 = cpvadd(cpvmult(n, -e2.r), cpvlerp(e2.a.p, e2.b.p, cpfclamp01((d_e1_b - d_e2_a)*e2_denom)));
  435. cpFloat dist = cpvdot(cpvsub(p2, p1), n);
  436. if(dist <= 0.0f){
  437. cpHashValue hash_1b2a = CP_HASH_PAIR(e1.b.hash, e2.a.hash);
  438. cpCollisionInfoPushContact(info, p1, p2, hash_1b2a);
  439. }
  440. }
  441. }
  442. }
  443. //MARK: Collision Functions
  444. typedef void (*CollisionFunc)(const cpShape *a, const cpShape *b, struct cpCollisionInfo *info);
  445. // Collide circle shapes.
  446. static void
  447. CircleToCircle(const cpCircleShape *c1, const cpCircleShape *c2, struct cpCollisionInfo *info)
  448. {
  449. cpFloat mindist = c1->r + c2->r;
  450. cpVect delta = cpvsub(c2->tc, c1->tc);
  451. cpFloat distsq = cpvlengthsq(delta);
  452. if(distsq < mindist*mindist){
  453. cpFloat dist = cpfsqrt(distsq);
  454. cpVect n = info->n = (dist ? cpvmult(delta, 1.0f/dist) : cpv(1.0f, 0.0f));
  455. cpCollisionInfoPushContact(info, cpvadd(c1->tc, cpvmult(n, c1->r)), cpvadd(c2->tc, cpvmult(n, -c2->r)), 0);
  456. }
  457. }
  458. static void
  459. CircleToSegment(const cpCircleShape *circle, const cpSegmentShape *segment, struct cpCollisionInfo *info)
  460. {
  461. cpVect seg_a = segment->ta;
  462. cpVect seg_b = segment->tb;
  463. cpVect center = circle->tc;
  464. // Find the closest point on the segment to the circle.
  465. cpVect seg_delta = cpvsub(seg_b, seg_a);
  466. cpFloat closest_t = cpfclamp01(cpvdot(seg_delta, cpvsub(center, seg_a))/cpvlengthsq(seg_delta));
  467. cpVect closest = cpvadd(seg_a, cpvmult(seg_delta, closest_t));
  468. // Compare the radii of the two shapes to see if they are colliding.
  469. cpFloat mindist = circle->r + segment->r;
  470. cpVect delta = cpvsub(closest, center);
  471. cpFloat distsq = cpvlengthsq(delta);
  472. if(distsq < mindist*mindist){
  473. cpFloat dist = cpfsqrt(distsq);
  474. // Handle coincident shapes as gracefully as possible.
  475. cpVect n = info->n = (dist ? cpvmult(delta, 1.0f/dist) : segment->tn);
  476. // Reject endcap collisions if tangents are provided.
  477. cpVect rot = cpBodyGetRotation(segment->shape.body);
  478. if(
  479. (closest_t != 0.0f || cpvdot(n, cpvrotate(segment->a_tangent, rot)) >= 0.0) &&
  480. (closest_t != 1.0f || cpvdot(n, cpvrotate(segment->b_tangent, rot)) >= 0.0)
  481. ){
  482. cpCollisionInfoPushContact(info, cpvadd(center, cpvmult(n, circle->r)), cpvadd(closest, cpvmult(n, -segment->r)), 0);
  483. }
  484. }
  485. }
  486. static void
  487. SegmentToSegment(const cpSegmentShape *seg1, const cpSegmentShape *seg2, struct cpCollisionInfo *info)
  488. {
  489. struct SupportContext context = {(cpShape *)seg1, (cpShape *)seg2, (SupportPointFunc)SegmentSupportPoint, (SupportPointFunc)SegmentSupportPoint};
  490. struct ClosestPoints points = GJK(&context, &info->id);
  491. #if DRAW_CLOSEST
  492. #if PRINT_LOG
  493. // ChipmunkDemoPrintString("Distance: %.2f\n", points.d);
  494. #endif
  495. ChipmunkDebugDrawDot(6.0, points.a, RGBAColor(1, 1, 1, 1));
  496. ChipmunkDebugDrawDot(6.0, points.b, RGBAColor(1, 1, 1, 1));
  497. ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1));
  498. ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1));
  499. #endif
  500. cpVect n = points.n;
  501. cpVect rot1 = cpBodyGetRotation(seg1->shape.body);
  502. cpVect rot2 = cpBodyGetRotation(seg2->shape.body);
  503. // If the closest points are nearer than the sum of the radii...
  504. if(
  505. points.d <= (seg1->r + seg2->r) && (
  506. // Reject endcap collisions if tangents are provided.
  507. (!cpveql(points.a, seg1->ta) || cpvdot(n, cpvrotate(seg1->a_tangent, rot1)) <= 0.0) &&
  508. (!cpveql(points.a, seg1->tb) || cpvdot(n, cpvrotate(seg1->b_tangent, rot1)) <= 0.0) &&
  509. (!cpveql(points.b, seg2->ta) || cpvdot(n, cpvrotate(seg2->a_tangent, rot2)) >= 0.0) &&
  510. (!cpveql(points.b, seg2->tb) || cpvdot(n, cpvrotate(seg2->b_tangent, rot2)) >= 0.0)
  511. )
  512. ){
  513. ContactPoints(SupportEdgeForSegment(seg1, n), SupportEdgeForSegment(seg2, cpvneg(n)), points, info);
  514. }
  515. }
  516. static void
  517. PolyToPoly(const cpPolyShape *poly1, const cpPolyShape *poly2, struct cpCollisionInfo *info)
  518. {
  519. struct SupportContext context = {(cpShape *)poly1, (cpShape *)poly2, (SupportPointFunc)PolySupportPoint, (SupportPointFunc)PolySupportPoint};
  520. struct ClosestPoints points = GJK(&context, &info->id);
  521. #if DRAW_CLOSEST
  522. #if PRINT_LOG
  523. // ChipmunkDemoPrintString("Distance: %.2f\n", points.d);
  524. #endif
  525. ChipmunkDebugDrawDot(3.0, points.a, RGBAColor(1, 1, 1, 1));
  526. ChipmunkDebugDrawDot(3.0, points.b, RGBAColor(1, 1, 1, 1));
  527. ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1));
  528. ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1));
  529. #endif
  530. // If the closest points are nearer than the sum of the radii...
  531. if(points.d - poly1->r - poly2->r <= 0.0){
  532. ContactPoints(SupportEdgeForPoly(poly1, points.n), SupportEdgeForPoly(poly2, cpvneg(points.n)), points, info);
  533. }
  534. }
  535. static void
  536. SegmentToPoly(const cpSegmentShape *seg, const cpPolyShape *poly, struct cpCollisionInfo *info)
  537. {
  538. struct SupportContext context = {(cpShape *)seg, (cpShape *)poly, (SupportPointFunc)SegmentSupportPoint, (SupportPointFunc)PolySupportPoint};
  539. struct ClosestPoints points = GJK(&context, &info->id);
  540. #if DRAW_CLOSEST
  541. #if PRINT_LOG
  542. // ChipmunkDemoPrintString("Distance: %.2f\n", points.d);
  543. #endif
  544. ChipmunkDebugDrawDot(3.0, points.a, RGBAColor(1, 1, 1, 1));
  545. ChipmunkDebugDrawDot(3.0, points.b, RGBAColor(1, 1, 1, 1));
  546. ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1));
  547. ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1));
  548. #endif
  549. cpVect n = points.n;
  550. cpVect rot = cpBodyGetRotation(seg->shape.body);
  551. if(
  552. // If the closest points are nearer than the sum of the radii...
  553. points.d - seg->r - poly->r <= 0.0 && (
  554. // Reject endcap collisions if tangents are provided.
  555. (!cpveql(points.a, seg->ta) || cpvdot(n, cpvrotate(seg->a_tangent, rot)) <= 0.0) &&
  556. (!cpveql(points.a, seg->tb) || cpvdot(n, cpvrotate(seg->b_tangent, rot)) <= 0.0)
  557. )
  558. ){
  559. ContactPoints(SupportEdgeForSegment(seg, n), SupportEdgeForPoly(poly, cpvneg(n)), points, info);
  560. }
  561. }
  562. static void
  563. CircleToPoly(const cpCircleShape *circle, const cpPolyShape *poly, struct cpCollisionInfo *info)
  564. {
  565. struct SupportContext context = {(cpShape *)circle, (cpShape *)poly, (SupportPointFunc)CircleSupportPoint, (SupportPointFunc)PolySupportPoint};
  566. struct ClosestPoints points = GJK(&context, &info->id);
  567. #if DRAW_CLOSEST
  568. ChipmunkDebugDrawDot(3.0, points.a, RGBAColor(1, 1, 1, 1));
  569. ChipmunkDebugDrawDot(3.0, points.b, RGBAColor(1, 1, 1, 1));
  570. ChipmunkDebugDrawSegment(points.a, points.b, RGBAColor(1, 1, 1, 1));
  571. ChipmunkDebugDrawSegment(points.a, cpvadd(points.a, cpvmult(points.n, 10.0)), RGBAColor(1, 0, 0, 1));
  572. #endif
  573. // If the closest points are nearer than the sum of the radii...
  574. if(points.d <= circle->r + poly->r){
  575. cpVect n = info->n = points.n;
  576. cpCollisionInfoPushContact(info, cpvadd(points.a, cpvmult(n, circle->r)), cpvadd(points.b, cpvmult(n, poly->r)), 0);
  577. }
  578. }
  579. static void
  580. CollisionError(const cpShape *circle, const cpShape *poly, struct cpCollisionInfo *info)
  581. {
  582. cpAssertHard(cpFalse, "Internal Error: Shape types are not sorted.");
  583. }
  584. static const CollisionFunc BuiltinCollisionFuncs[9] = {
  585. (CollisionFunc)CircleToCircle,
  586. CollisionError,
  587. CollisionError,
  588. (CollisionFunc)CircleToSegment,
  589. (CollisionFunc)SegmentToSegment,
  590. CollisionError,
  591. (CollisionFunc)CircleToPoly,
  592. (CollisionFunc)SegmentToPoly,
  593. (CollisionFunc)PolyToPoly,
  594. };
  595. static const CollisionFunc *CollisionFuncs = BuiltinCollisionFuncs;
  596. struct cpCollisionInfo
  597. cpCollide(const cpShape *a, const cpShape *b, cpCollisionID id, struct cpContact *contacts)
  598. {
  599. struct cpCollisionInfo info = {a, b, id, cpvzero, 0, contacts};
  600. // Make sure the shape types are in order.
  601. if(a->klass->type > b->klass->type){
  602. info.a = b;
  603. info.b = a;
  604. }
  605. CollisionFuncs[info.a->klass->type + info.b->klass->type*CP_NUM_SHAPES](info.a, info.b, &info);
  606. // if(0){
  607. // for(int i=0; i<info.count; i++){
  608. // cpVect r1 = info.arr[i].r1;
  609. // cpVect r2 = info.arr[i].r2;
  610. // cpVect mid = cpvlerp(r1, r2, 0.5f);
  611. //
  612. // ChipmunkDebugDrawSegment(r1, mid, RGBAColor(1, 0, 0, 1));
  613. // ChipmunkDebugDrawSegment(r2, mid, RGBAColor(0, 0, 1, 1));
  614. // }
  615. // }
  616. return info;
  617. }