b2PolygonShape.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. // Copy vertices into local buffer
  112. b2Vec2 ps[b2_maxPolygonVertices];
  113. for (int32 i = 0; i < n; ++i)
  114. {
  115. ps[i] = vertices[i];
  116. }
  117. // Create the convex hull using the Gift wrapping algorithm
  118. // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm
  119. // Find the right most point on the hull
  120. int32 i0 = 0;
  121. float32 x0 = ps[0].x;
  122. for (int32 i = 1; i < count; ++i)
  123. {
  124. float32 x = ps[i].x;
  125. if (x > x0 || (x == x0 && ps[i].y < ps[i0].y))
  126. {
  127. i0 = i;
  128. x0 = x;
  129. }
  130. }
  131. int32 hull[b2_maxPolygonVertices];
  132. int32 m = 0;
  133. int32 ih = i0;
  134. for (;;)
  135. {
  136. hull[m] = ih;
  137. int32 ie = 0;
  138. for (int32 j = 1; j < n; ++j)
  139. {
  140. if (ie == ih)
  141. {
  142. ie = j;
  143. continue;
  144. }
  145. b2Vec2 r = ps[ie] - ps[hull[m]];
  146. b2Vec2 v = ps[j] - ps[hull[m]];
  147. float32 c = b2Cross(r, v);
  148. if (c < 0.0f)
  149. {
  150. ie = j;
  151. }
  152. // Collinearity check
  153. if (c == 0.0f && v.LengthSquared() > r.LengthSquared())
  154. {
  155. ie = j;
  156. }
  157. }
  158. ++m;
  159. ih = ie;
  160. if (ie == i0)
  161. {
  162. break;
  163. }
  164. }
  165. m_count = m;
  166. // Copy vertices.
  167. for (int32 i = 0; i < m; ++i)
  168. {
  169. m_vertices[i] = ps[hull[i]];
  170. }
  171. // Compute normals. Ensure the edges have non-zero length.
  172. for (int32 i = 0; i < m; ++i)
  173. {
  174. int32 i1 = i;
  175. int32 i2 = i + 1 < m ? i + 1 : 0;
  176. b2Vec2 edge = m_vertices[i2] - m_vertices[i1];
  177. b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon);
  178. m_normals[i] = b2Cross(edge, 1.0f);
  179. m_normals[i].Normalize();
  180. }
  181. // Compute the polygon centroid.
  182. m_centroid = ComputeCentroid(m_vertices, m);
  183. }
  184. bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const
  185. {
  186. b2Vec2 pLocal = b2MulT(xf.q, p - xf.p);
  187. for (int32 i = 0; i < m_count; ++i)
  188. {
  189. float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]);
  190. if (dot > 0.0f)
  191. {
  192. return false;
  193. }
  194. }
  195. return true;
  196. }
  197. bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input,
  198. const b2Transform& xf, int32 childIndex) const
  199. {
  200. B2_NOT_USED(childIndex);
  201. // Put the ray into the polygon's frame of reference.
  202. b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p);
  203. b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p);
  204. b2Vec2 d = p2 - p1;
  205. float32 lower = 0.0f, upper = input.maxFraction;
  206. int32 index = -1;
  207. for (int32 i = 0; i < m_count; ++i)
  208. {
  209. // p = p1 + a * d
  210. // dot(normal, p - v) = 0
  211. // dot(normal, p1 - v) + a * dot(normal, d) = 0
  212. float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1);
  213. float32 denominator = b2Dot(m_normals[i], d);
  214. if (denominator == 0.0f)
  215. {
  216. if (numerator < 0.0f)
  217. {
  218. return false;
  219. }
  220. }
  221. else
  222. {
  223. // Note: we want this predicate without division:
  224. // lower < numerator / denominator, where denominator < 0
  225. // Since denominator < 0, we have to flip the inequality:
  226. // lower < numerator / denominator <==> denominator * lower > numerator.
  227. if (denominator < 0.0f && numerator < lower * denominator)
  228. {
  229. // Increase lower.
  230. // The segment enters this half-space.
  231. lower = numerator / denominator;
  232. index = i;
  233. }
  234. else if (denominator > 0.0f && numerator < upper * denominator)
  235. {
  236. // Decrease upper.
  237. // The segment exits this half-space.
  238. upper = numerator / denominator;
  239. }
  240. }
  241. // The use of epsilon here causes the assert on lower to trip
  242. // in some cases. Apparently the use of epsilon was to make edge
  243. // shapes work, but now those are handled separately.
  244. //if (upper < lower - b2_epsilon)
  245. if (upper < lower)
  246. {
  247. return false;
  248. }
  249. }
  250. b2Assert(0.0f <= lower && lower <= input.maxFraction);
  251. if (index >= 0)
  252. {
  253. output->fraction = lower;
  254. output->normal = b2Mul(xf.q, m_normals[index]);
  255. return true;
  256. }
  257. return false;
  258. }
  259. void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const
  260. {
  261. B2_NOT_USED(childIndex);
  262. b2Vec2 lower = b2Mul(xf, m_vertices[0]);
  263. b2Vec2 upper = lower;
  264. for (int32 i = 1; i < m_count; ++i)
  265. {
  266. b2Vec2 v = b2Mul(xf, m_vertices[i]);
  267. lower = b2Min(lower, v);
  268. upper = b2Max(upper, v);
  269. }
  270. b2Vec2 r(m_radius, m_radius);
  271. aabb->lowerBound = lower - r;
  272. aabb->upperBound = upper + r;
  273. }
  274. void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const
  275. {
  276. // Polygon mass, centroid, and inertia.
  277. // Let rho be the polygon density in mass per unit area.
  278. // Then:
  279. // mass = rho * int(dA)
  280. // centroid.x = (1/mass) * rho * int(x * dA)
  281. // centroid.y = (1/mass) * rho * int(y * dA)
  282. // I = rho * int((x*x + y*y) * dA)
  283. //
  284. // We can compute these integrals by summing all the integrals
  285. // for each triangle of the polygon. To evaluate the integral
  286. // for a single triangle, we make a change of variables to
  287. // the (u,v) coordinates of the triangle:
  288. // x = x0 + e1x * u + e2x * v
  289. // y = y0 + e1y * u + e2y * v
  290. // where 0 <= u && 0 <= v && u + v <= 1.
  291. //
  292. // We integrate u from [0,1-v] and then v from [0,1].
  293. // We also need to use the Jacobian of the transformation:
  294. // D = cross(e1, e2)
  295. //
  296. // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3)
  297. //
  298. // The rest of the derivation is handled by computer algebra.
  299. b2Assert(m_count >= 3);
  300. b2Vec2 center; center.Set(0.0f, 0.0f);
  301. float32 area = 0.0f;
  302. float32 I = 0.0f;
  303. // s is the reference point for forming triangles.
  304. // It's location doesn't change the result (except for rounding error).
  305. b2Vec2 s(0.0f, 0.0f);
  306. // This code would put the reference point inside the polygon.
  307. for (int32 i = 0; i < m_count; ++i)
  308. {
  309. s += m_vertices[i];
  310. }
  311. s *= 1.0f / m_count;
  312. const float32 k_inv3 = 1.0f / 3.0f;
  313. for (int32 i = 0; i < m_count; ++i)
  314. {
  315. // Triangle vertices.
  316. b2Vec2 e1 = m_vertices[i] - s;
  317. b2Vec2 e2 = i + 1 < m_count ? m_vertices[i+1] - s : m_vertices[0] - s;
  318. float32 D = b2Cross(e1, e2);
  319. float32 triangleArea = 0.5f * D;
  320. area += triangleArea;
  321. // Area weighted centroid
  322. center += triangleArea * k_inv3 * (e1 + e2);
  323. float32 ex1 = e1.x, ey1 = e1.y;
  324. float32 ex2 = e2.x, ey2 = e2.y;
  325. float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2;
  326. float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2;
  327. I += (0.25f * k_inv3 * D) * (intx2 + inty2);
  328. }
  329. // Total mass
  330. massData->mass = density * area;
  331. // Center of mass
  332. b2Assert(area > b2_epsilon);
  333. center *= 1.0f / area;
  334. massData->center = center + s;
  335. // Inertia tensor relative to the local origin (point s).
  336. massData->I = density * I;
  337. // Shift to center of mass then to original body origin.
  338. massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center));
  339. }
  340. bool b2PolygonShape::Validate() const
  341. {
  342. for (int32 i = 0; i < m_count; ++i)
  343. {
  344. int32 i1 = i;
  345. int32 i2 = i < m_count - 1 ? i1 + 1 : 0;
  346. b2Vec2 p = m_vertices[i1];
  347. b2Vec2 e = m_vertices[i2] - p;
  348. for (int32 j = 0; j < m_count; ++j)
  349. {
  350. if (j == i1 || j == i2)
  351. {
  352. continue;
  353. }
  354. b2Vec2 v = m_vertices[j] - p;
  355. float32 c = b2Cross(e, v);
  356. if (c < 0.0f)
  357. {
  358. return false;
  359. }
  360. }
  361. }
  362. return true;
  363. }