b2PolygonShape.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /*
  2. * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. * Permission is granted to anyone to use this software for any purpose,
  8. * including commercial applications, and to alter it and redistribute it
  9. * freely, subject to the following restrictions:
  10. * 1. The origin of this software must not be misrepresented; you must not
  11. * claim that you wrote the original software. If you use this software
  12. * in a product, an acknowledgment in the product documentation would be
  13. * appreciated but is not required.
  14. * 2. Altered source versions must be plainly marked as such, and must not be
  15. * misrepresented as being the original software.
  16. * 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include <Box2D/Collision/Shapes/b2PolygonShape.h>
  19. #include <new>
  20. b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const
  21. {
  22. void* mem = allocator->Allocate(sizeof(b2PolygonShape));
  23. b2PolygonShape* clone = new (mem) b2PolygonShape;
  24. *clone = *this;
  25. return clone;
  26. }
  27. void b2PolygonShape::SetAsBox(float32 hx, float32 hy)
  28. {
  29. m_count = 4;
  30. m_vertices[0].Set(-hx, -hy);
  31. m_vertices[1].Set( hx, -hy);
  32. m_vertices[2].Set( hx, hy);
  33. m_vertices[3].Set(-hx, hy);
  34. m_normals[0].Set(0.0f, -1.0f);
  35. m_normals[1].Set(1.0f, 0.0f);
  36. m_normals[2].Set(0.0f, 1.0f);
  37. m_normals[3].Set(-1.0f, 0.0f);
  38. m_centroid.SetZero();
  39. }
  40. void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle)
  41. {
  42. m_count = 4;
  43. m_vertices[0].Set(-hx, -hy);
  44. m_vertices[1].Set( hx, -hy);
  45. m_vertices[2].Set( hx, hy);
  46. m_vertices[3].Set(-hx, hy);
  47. m_normals[0].Set(0.0f, -1.0f);
  48. m_normals[1].Set(1.0f, 0.0f);
  49. m_normals[2].Set(0.0f, 1.0f);
  50. m_normals[3].Set(-1.0f, 0.0f);
  51. m_centroid = center;
  52. b2Transform xf;
  53. xf.p = center;
  54. xf.q.Set(angle);
  55. // Transform vertices and normals.
  56. for (int32 i = 0; i < m_count; ++i)
  57. {
  58. m_vertices[i] = b2Mul(xf, m_vertices[i]);
  59. m_normals[i] = b2Mul(xf.q, m_normals[i]);
  60. }
  61. }
  62. int32 b2PolygonShape::GetChildCount() const
  63. {
  64. return 1;
  65. }
  66. static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count)
  67. {
  68. b2Assert(count >= 3);
  69. b2Vec2 c; c.Set(0.0f, 0.0f);
  70. float32 area = 0.0f;
  71. // pRef is the reference point for forming triangles.
  72. // It's location doesn't change the result (except for rounding error).
  73. b2Vec2 pRef(0.0f, 0.0f);
  74. #if 0
  75. // This code would put the reference point inside the polygon.
  76. for (int32 i = 0; i < count; ++i)
  77. {
  78. pRef += vs[i];
  79. }
  80. pRef *= 1.0f / count;
  81. #endif
  82. const float32 inv3 = 1.0f / 3.0f;
  83. for (int32 i = 0; i < count; ++i)
  84. {
  85. // Triangle vertices.
  86. b2Vec2 p1 = pRef;
  87. b2Vec2 p2 = vs[i];
  88. b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0];
  89. b2Vec2 e1 = p2 - p1;
  90. b2Vec2 e2 = p3 - p1;
  91. float32 D = b2Cross(e1, e2);
  92. float32 triangleArea = 0.5f * D;
  93. area += triangleArea;
  94. // Area weighted centroid
  95. c += triangleArea * inv3 * (p1 + p2 + p3);
  96. }
  97. // Centroid
  98. b2Assert(area > b2_epsilon);
  99. c *= 1.0f / area;
  100. return c;
  101. }
  102. void b2PolygonShape::Set(const b2Vec2* vertices, int32 count)
  103. {
  104. b2Assert(3 <= count && count <= b2_maxPolygonVertices);
  105. if (count < 3)
  106. {
  107. SetAsBox(1.0f, 1.0f);
  108. return;
  109. }
  110. int32 n = b2Min(count, b2_maxPolygonVertices);
  111. // Perform welding and copy vertices into local buffer.
  112. b2Vec2 ps[b2_maxPolygonVertices];
  113. int32 tempCount = 0;
  114. for (int32 i = 0; i < n; ++i)
  115. {
  116. b2Vec2 v = vertices[i];
  117. bool unique = true;
  118. for (int32 j = 0; j < tempCount; ++j)
  119. {
  120. if (b2DistanceSquared(v, ps[j]) < 0.5f * b2_linearSlop)
  121. {
  122. unique = false;
  123. break;
  124. }
  125. }
  126. if (unique)
  127. {
  128. ps[tempCount++] = v;
  129. }
  130. }
  131. n = tempCount;
  132. if (n < 3)
  133. {
  134. // Polygon is degenerate.
  135. b2Assert(false);
  136. SetAsBox(1.0f, 1.0f);
  137. return;
  138. }
  139. // Create the convex hull using the Gift wrapping algorithm
  140. // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm
  141. // Find the right most point on the hull
  142. int32 i0 = 0;
  143. float32 x0 = ps[0].x;
  144. for (int32 i = 1; i < n; ++i)
  145. {
  146. float32 x = ps[i].x;
  147. if (x > x0 || (x == x0 && ps[i].y < ps[i0].y))
  148. {
  149. i0 = i;
  150. x0 = x;
  151. }
  152. }
  153. int32 hull[b2_maxPolygonVertices];
  154. int32 m = 0;
  155. int32 ih = i0;
  156. for (;;)
  157. {
  158. hull[m] = ih;
  159. int32 ie = 0;
  160. for (int32 j = 1; j < n; ++j)
  161. {
  162. if (ie == ih)
  163. {
  164. ie = j;
  165. continue;
  166. }
  167. b2Vec2 r = ps[ie] - ps[hull[m]];
  168. b2Vec2 v = ps[j] - ps[hull[m]];
  169. float32 c = b2Cross(r, v);
  170. if (c < 0.0f)
  171. {
  172. ie = j;
  173. }
  174. // Collinearity check
  175. if (c == 0.0f && v.LengthSquared() > r.LengthSquared())
  176. {
  177. ie = j;
  178. }
  179. }
  180. ++m;
  181. ih = ie;
  182. if (ie == i0)
  183. {
  184. break;
  185. }
  186. }
  187. m_count = m;
  188. // Copy vertices.
  189. for (int32 i = 0; i < m; ++i)
  190. {
  191. m_vertices[i] = ps[hull[i]];
  192. }
  193. // Compute normals. Ensure the edges have non-zero length.
  194. for (int32 i = 0; i < m; ++i)
  195. {
  196. int32 i1 = i;
  197. int32 i2 = i + 1 < m ? i + 1 : 0;
  198. b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
  199. b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon);
  200. m_normals[i] = b2Cross(edge, 1.0f);
  201. m_normals[i].Normalize();
  202. }
  203. // Compute the polygon centroid.
  204. m_centroid = ComputeCentroid(m_vertices, m);
  205. }
  206. bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
  207. {
  208. b2Vec2 pLocal = b2MulT(xf.q, p - xf.p);
  209. for (int32 i = 0; i < m_count; ++i)
  210. {
  211. float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
  212. if (dot > 0.0f)
  213. {
  214. return false;
  215. }
  216. }
  217. return true;
  218. }
  219. bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  220. const b2Transform& xf, int32 childIndex) const
  221. {
  222. B2_NOT_USED(childIndex);
  223. // Put the ray into the polygon's frame of reference.
  224. b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
  225. b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
  226. b2Vec2 d = p2 - p1;
  227. float32 lower = 0.0f, upper = input.maxFraction;
  228. int32 index = -1;
  229. for (int32 i = 0; i < m_count; ++i)
  230. {
  231. // p = p1 + a * d
  232. // dot(normal, p - v) = 0
  233. // dot(normal, p1 - v) + a * dot(normal, d) = 0
  234. float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
  235. float32 denominator = b2Dot(m_normals[i], d);
  236. if (denominator == 0.0f)
  237. {
  238. if (numerator < 0.0f)
  239. {
  240. return false;
  241. }
  242. }
  243. else
  244. {
  245. // Note: we want this predicate without division:
  246. // lower < numerator / denominator, where denominator < 0
  247. // Since denominator < 0, we have to flip the inequality:
  248. // lower < numerator / denominator <==> denominator * lower > numerator.
  249. if (denominator < 0.0f && numerator < lower * denominator)
  250. {
  251. // Increase lower.
  252. // The segment enters this half-space.
  253. lower = numerator / denominator;
  254. index = i;
  255. }
  256. else if (denominator > 0.0f && numerator < upper * denominator)
  257. {
  258. // Decrease upper.
  259. // The segment exits this half-space.
  260. upper = numerator / denominator;
  261. }
  262. }
  263. // The use of epsilon here causes the assert on lower to trip
  264. // in some cases. Apparently the use of epsilon was to make edge
  265. // shapes work, but now those are handled separately.
  266. //if (upper < lower - b2_epsilon)
  267. if (upper < lower)
  268. {
  269. return false;
  270. }
  271. }
  272. b2Assert(0.0f <= lower && lower <= input.maxFraction);
  273. if (index >= 0)
  274. {
  275. output->fraction = lower;
  276. output->normal = b2Mul(xf.q, m_normals[index]);
  277. return true;
  278. }
  279. return false;
  280. }
  281. void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
  282. {
  283. B2_NOT_USED(childIndex);
  284. b2Vec2 lower = b2Mul(xf, m_vertices[0]);
  285. b2Vec2 upper = lower;
  286. for (int32 i = 1; i < m_count; ++i)
  287. {
  288. b2Vec2 v = b2Mul(xf, m_vertices[i]);
  289. lower = b2Min(lower, v);
  290. upper = b2Max(upper, v);
  291. }
  292. b2Vec2 r(m_radius, m_radius);
  293. aabb->lowerBound = lower - r;
  294. aabb->upperBound = upper + r;
  295. }
  296. void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const
  297. {
  298. // Polygon mass, centroid, and inertia.
  299. // Let rho be the polygon density in mass per unit area.
  300. // Then:
  301. // mass = rho * int(dA)
  302. // centroid.x = (1/mass) * rho * int(x * dA)
  303. // centroid.y = (1/mass) * rho * int(y * dA)
  304. // I = rho * int((x*x + y*y) * dA)
  305. //
  306. // We can compute these integrals by summing all the integrals
  307. // for each triangle of the polygon. To evaluate the integral
  308. // for a single triangle, we make a change of variables to
  309. // the (u,v) coordinates of the triangle:
  310. // x = x0 + e1x * u + e2x * v
  311. // y = y0 + e1y * u + e2y * v
  312. // where 0 <= u && 0 <= v && u + v <= 1.
  313. //
  314. // We integrate u from [0,1-v] and then v from [0,1].
  315. // We also need to use the Jacobian of the transformation:
  316. // D = cross(e1, e2)
  317. //
  318. // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
  319. //
  320. // The rest of the derivation is handled by computer algebra.
  321. b2Assert(m_count >= 3);
  322. b2Vec2 center; center.Set(0.0f, 0.0f);
  323. float32 area = 0.0f;
  324. float32 I = 0.0f;
  325. // s is the reference point for forming triangles.
  326. // It's location doesn't change the result (except for rounding error).
  327. b2Vec2 s(0.0f, 0.0f);
  328. // This code would put the reference point inside the polygon.
  329. for (int32 i = 0; i < m_count; ++i)
  330. {
  331. s += m_vertices[i];
  332. }
  333. s *= 1.0f / m_count;
  334. const float32 k_inv3 = 1.0f / 3.0f;
  335. for (int32 i = 0; i < m_count; ++i)
  336. {
  337. // Triangle vertices.
  338. b2Vec2 e1 = m_vertices[i] - s;
  339. b2Vec2 e2 = i + 1 < m_count ? m_vertices[i+1] - s : m_vertices[0] - s;
  340. float32 D = b2Cross(e1, e2);
  341. float32 triangleArea = 0.5f * D;
  342. area += triangleArea;
  343. // Area weighted centroid
  344. center += triangleArea * k_inv3 * (e1 + e2);
  345. float32 ex1 = e1.x, ey1 = e1.y;
  346. float32 ex2 = e2.x, ey2 = e2.y;
  347. float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2;
  348. float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2;
  349. I += (0.25f * k_inv3 * D) * (intx2 + inty2);
  350. }
  351. // Total mass
  352. massData->mass = density * area;
  353. // Center of mass
  354. b2Assert(area > b2_epsilon);
  355. center *= 1.0f / area;
  356. massData->center = center + s;
  357. // Inertia tensor relative to the local origin (point s).
  358. massData->I = density * I;
  359. // Shift to center of mass then to original body origin.
  360. massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center));
  361. }
  362. bool b2PolygonShape::Validate() const
  363. {
  364. for (int32 i = 0; i < m_count; ++i)
  365. {
  366. int32 i1 = i;
  367. int32 i2 = i < m_count - 1 ? i1 + 1 : 0;
  368. b2Vec2 p = m_vertices[i1];
  369. b2Vec2 e = m_vertices[i2] - p;
  370. for (int32 j = 0; j < m_count; ++j)
  371. {
  372. if (j == i1 || j == i2)
  373. {
  374. continue;
  375. }
  376. b2Vec2 v = m_vertices[j] - p;
  377. float32 c = b2Cross(e, v);
  378. if (c < 0.0f)
  379. {
  380. return false;
  381. }
  382. }
  383. }
  384. return true;
  385. }