PageRenderTime 50ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/Cocos2d-x/Cocos2d-x/libs/chipmunk/chipmunk-docs.html

https://gitlab.com/Mr.Tomato/Cocos2d-X-text
HTML | 944 lines | 546 code | 398 blank | 0 comment | 0 complexity | 0b2a9816da4d8449b1200ad14fb9c245 MD5 | raw file
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  6. <title>Chipmunk Game Dynamics Documentation</title>
  7. <style type="text/css">
  8. h1 {
  9. text-align: center;
  10. font-size: 300%;
  11. }
  12. h2, h3 {
  13. background-color: BurlyWood;
  14. padding: 3px;
  15. }
  16. p {
  17. margin-left: 1em;
  18. }
  19. p.expl {
  20. margin-left: 2em;
  21. }
  22. pre {
  23. background-color: lightGrey;
  24. padding: 3px;
  25. margin-left: 1em;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <h1>Chipmunk Game Dynamics</h1>
  31. <h2>Introduction</h2>
  32. <p>First of all, Chipmunk is a 2D rigid body physics library distributed under the <span class="caps">MIT</span> license. Though not yet complete, it is intended to be fast, numerically stable, and easy to use.</p>
  33. <p>It&#8217;s been a long time in coming, but I&#8217;ve finally made a stable and usable physics implementation. While not feature complete yet, it&#8217;s well on it&#8217;s way. I would like to give a Erin Catto a big thank you, as the most of the ideas for the constraint solver come from his Box2D example code. (<a href="http://www.gphysics.com/">gPhysics Website</a>). His contact persistence idea allows for stable stacks of objects with very few iterations of the contact solution. Couldn&#8217;t have gotten that working without his help.</p>
  34. <h2>Overview</h2>
  35. <ul>
  36. <li><strong>rigid bodies:</strong> A rigid body holds the physical properties of an object. (mass, position, rotation, velocity, etc.) It does not have a shape by itself. If you&#8217;ve done physics with particles before, rigid bodies differ mostly in that they are able to rotate.</li>
  37. <li><strong>collision shapes:</strong> By attaching shapes to bodies, you can define the a body&#8217;s shape. You can attach many shapes to a single body to define a complex shape, or none if it doesn&#8217;t require a shape.</li>
  38. <li><strong>joints:</strong> You can attach joints between two bodies to constrain their behavior.</li>
  39. <li><strong>spaces:</strong> Spaces are the basic simulation unit in Chipmunk. You add bodies, shapes and joints to a space, and then update the space as a whole.</li>
  40. </ul>
  41. <p><strong>Rigid bodies, collision shapes and sprites:</strong></p>
  42. <p>There is often confusion between rigid bodies and their collision shapes in Chipmunk and how they relate to sprites. A sprite would be a visual representation of an object, the sprite is drawn at the position of the rigid body. The collision shape would be the material representation of the object, and how it should collide with other objects. A sprite and collision shape have little to do with one another other than you probably want the collision shape to match the sprite&#8217;s shape.</p>
  43. <h2><span class="caps">C API</span> Documentation</h2>
  44. <h3>Initializing Chipmunk</h3>
  45. <p>Initializing Chipmunk is an extremely complicated process. The following code snippet steps you through the process:</p>
  46. <pre><code>
  47. cpInitChipmunk(); /* Actually, that's pretty much it */
  48. </code></pre>
  49. <h3>Chipmunk memory management</h3>
  50. <p>For many of the structures you will use, Chipmunk uses a more or less standard set of memory management functions. For instance:</p>
  51. <ul>
  52. <li><code>cpSpaceAlloc()</code> allocates but does not initialize a <code>cpSpace</code> struct.</li>
  53. <li><code>cpSpaceInit(space, other_args)</code> initializes a <code>cpSpace</code> struct.</li>
  54. <li><code>cpSpaceNew(args)</code> allocates and initializes a <code>cpSpace</code> struct using <code>args</code>.</li>
  55. <li><code>cpSpaceDestroy(space)</code> frees all dependancies, but does not free the <code>cpSpace</code> struct.</li>
  56. <li><code>cpSpaceFree(space)</code> frees all dependancies and the <code>cpSpace</code> struct.</li>
  57. </ul>
  58. <p>While you will probably use the new/free versions exclusively, the others can be helpful when writing language extensions.</p>
  59. <p>In general, you are responsible for freeing any structs that you allocate. The only exception is that <code>cpShapeDestroy()</code> also destroys the specific shape struct that was passed to the constructor.</p>
  60. <h3>Chipmunk floats: <code>cpFloat</code></h3>
  61. <pre><code>
  62. typedef float cpFloat;
  63. </code></pre>
  64. <p>All Chipmunk code should be <code>double</code> safe, so feel free to redefine this.</p>
  65. <h3>Chipmunk vectors: <code>cpVect</code></h3>
  66. <p><strong>User accessible fields:</strong></p>
  67. <pre><code>
  68. typedef struct cpVect{
  69. cpFloat x,y;
  70. } cpVect
  71. </code></pre>
  72. <p class="expl">Simply a 2D vector packed into a struct. May change in the future to take advantage of <span class="caps">SIMD</span>.</p>
  73. <pre><code>
  74. #define cpvzero ((cpVect){0.0f, 0.0f})
  75. </code></pre>
  76. <p class="expl">Constant for the zero vector.</p>
  77. <pre><code>
  78. cpVect cpv(const cpFloat x, const cpFloat y)
  79. </code></pre>
  80. <p class="expl">Convenience constructor for creating new <code>cpVect</code> structs.</p>
  81. <pre><code>
  82. cpVect cpvadd(const cpVect v1, const cpVect v2)
  83. cpVect cpvsub(const cpVect v1, const cpVect v2)
  84. </code></pre>
  85. <p class="expl">Add or subtract two vectors.</p>
  86. <pre><code>
  87. cpVect cpvneg(const cpVect v)
  88. </code></pre>
  89. <p class="expl">Negate a vector.</p>
  90. <pre><code>
  91. cpVect cpvmult(const cpVect v, const cpFloat s)
  92. </code></pre>
  93. <p class="expl">Scalar multiplication.</p>
  94. <pre><code>
  95. cpFloat cpvdot(const cpVect v1, const cpVect v2)
  96. </code></pre>
  97. <p class="expl">Vector dot product.</p>
  98. <pre><code>
  99. cpFloat cpvcross(const cpVect v1, const cpVect v2)
  100. </code></pre>
  101. <p class="expl">2D vector cross product analog. The cross product of 2D vectors exists only in the z component, so only that value is returned.</p>
  102. <pre><code>
  103. cpVect cpvperp(const cpVect v)
  104. </code></pre>
  105. <p class="expl">Returns the perpendicular vector. (90 degree rotation)</p>
  106. <pre><code>
  107. cpVect cpvproject(const cpVect v1, const cpVect v2)
  108. </code></pre>
  109. <p class="expl">Returns the vector projection of <code>v1</code> onto <code>v2</code>.</p>
  110. <pre><code>
  111. cpVect cpvrotate(const cpVect v1, const cpVect v2)
  112. </code></pre>
  113. <p class="expl">Uses complex multiplication to rotate (and scale) <code>v1</code> by <code>v2</code>.</p>
  114. <pre><code>
  115. cpVect cpvunrotate(const cpVect v1, const cpVect v2)
  116. </code></pre>
  117. <p class="expl">Inverse of <code>cpvrotate()</code>.</p>
  118. <pre><code>
  119. cpFloat cpvlength(const cpVect v)
  120. </code></pre>
  121. <p class="expl">Returns the length of <code>v</code>.</p>
  122. <pre><code>
  123. cpFloat cpvlengthsq(const cpVect v)
  124. </code></pre>
  125. <p class="expl">Returns the squared length of <code>v</code>. Faster than <code>cpvlength()</code> when you only need to compare lengths.</p>
  126. <pre><code>
  127. cpVect cpvnormalize(const cpVect v)
  128. </code></pre>
  129. <p class="expl">Returns a normalized copy of <code>v</code>.</p>
  130. <pre><code>
  131. cpVect cpvforangle(const cpFloat a)
  132. </code></pre>
  133. <p class="expl">Returns the unit length vector for the given angle (in radians).</p>
  134. <pre><code>
  135. cpFloat cpvtoangle(const cpVect v)
  136. </code></pre>
  137. <p class="expl">Returns the angular direction <code>v</code> is pointing in (in radians).</p>
  138. <pre><code>
  139. *cpvstr(const cpVect v)
  140. </code></pre>
  141. <p class="expl">Returns a string representation of <code>v</code>. <strong><span class="caps">NOTE</span>:</strong> <em>The string points to a static local and is reset every time the function is called.</em></p>
  142. <h3>Chipmunk bounding boxes: <code>cpBB</code></h3>
  143. <p><strong>User accessible fields:</strong></p>
  144. <pre><code>
  145. typedef struct cpBB{
  146. cpFloat l, b, r ,t;
  147. } cpBB
  148. </code></pre>
  149. <p class="expl">Simple bounding box struct. Stored as left, bottom, right, top values.</p>
  150. <pre><code>
  151. cpBB cpBBNew(const cpFloat l, const cpFloat b, const cpFloat r, const cpFloat t)
  152. </code></pre>
  153. <p class="expl">Convenience constructor for <code>cpBB</code> structs.</p>
  154. <pre><code>
  155. int cpBBintersects(const cpBB a, const cpBB b)
  156. </code></pre>
  157. <p class="expl">Returns true if the bounding boxes intersect.</p>
  158. <pre><code>
  159. int cpBBcontainsBB(const cpBB bb, const cpBB other)
  160. </code></pre>
  161. <p class="expl">Returns true if <code>bb</code> completely contains <code>other</code>.</p>
  162. <pre><code>
  163. int cpBBcontainsVect(const cpBB bb, const cpVect v)
  164. </code></pre>
  165. <p class="expl">Returns true if <code>bb</code> contains <code>v</code>.</p>
  166. <pre><code>
  167. cpVect cpBBClampVect(const cpBB bb, const cpVect v)
  168. </code></pre>
  169. <p class="expl">Returns a copy of <code>v</code> clamped to the bounding box.</p>
  170. <pre><code>
  171. cpVect cpBBWrapVect(const cpBB bb, const cpVect v)
  172. </code></pre>
  173. <p class="expl">Returns a copy of <code>v</code> wrapped to the bounding box.</p>
  174. <h3>Chipmunk spatial hashes: <code>cpSpaceHash</code></h3>
  175. <p><em>The spatial hash isn&#8217;t yet ready for user use. However, it has been made in a generic manner that would allow it to be used for more than just Chipmunk&#8217;s collision detection needs.</em></p>
  176. <h3>Chipmunk rigid bodies: <code>cpBody</code></h3>
  177. <p><strong>User accessible fields:</strong></p>
  178. <pre><code>
  179. typedef struct cpBody{
  180. cpFloat m, m_inv;
  181. cpFloat i, i_inv;
  182. cpVect p, v, f;
  183. cpFloat a, w, t;
  184. cpVect rot;
  185. } cpBody
  186. </code></pre>
  187. <ul>
  188. <li><code>m</code>, and <code>m_inv</code> are the mass and its inverse.</li>
  189. <li><code>i</code>, and <code>i_inv</code> are the moment of inertia and its inverse.</li>
  190. <li><code>p</code>, <code>v</code>, and <code>f</code> are the position, velocity and force respectively.</li>
  191. <li><code>a</code>, <code>w</code>, and <code>t</code> are the angle (in radians), angular velocity (rad/sec), and torque respectively.</li>
  192. <li><code>rot</code> is the rotation of the body as a unit length vector. (can be used with <code>cpvrotate()</code>)</li>
  193. </ul>
  194. <pre><code>
  195. cpBody *cpBodyAlloc(void)
  196. cpBody *cpBodyInit(cpBody *body, cpFloat m, cpFloat i)
  197. cpBody *cpBodyNew(cpFloat m, cpFloat i)
  198. void cpBodyDestroy(cpBody *body)
  199. void cpBodyFree(cpBody *body)
  200. </code></pre>
  201. <p class="expl">Uses the standard suite of Chipmunk memory functions. <code>m</code> and <code>i</code> are the mass and moment of inertia for the body.</p>
  202. <pre><code>
  203. void cpBodySetMass(cpBody *body, cpFloat m);
  204. void cpBodySetMoment(cpBody *body, cpFloat i);
  205. void cpBodySetAngle(cpBody *body, cpFloat a);
  206. </code></pre>
  207. <p class="expl">Because several of the values are linked, (m/m_inv, i/i_inv, a/rot) don&#8217;t set them explicitly, use these setter functions instead.</p>
  208. <pre><code>
  209. cpVect cpBodyLocal2World(cpBody *body, cpVect v)
  210. </code></pre>
  211. <p class="expl">Convert from body local coordinates to world space coordinates.</p>
  212. <pre><code>
  213. cpVect cpBodyWorld2Local(cpBody *body, cpVect v)
  214. </code></pre>
  215. <p class="expl">Convert from world space coordinates to body local coordinates.</p>
  216. <pre><code>
  217. void cpBodyApplyImpulse(cpBody *body, cpVect j, cpVect r)
  218. </code></pre>
  219. <p class="expl">Apply the impulse <code>j</code> to <code>body</code> with offset <code>r</code>. Both <code>j</code> and <code>r</code> should be in world coordinates.</p>
  220. <pre><code>
  221. void cpBodyResetForces(cpBody *body)
  222. </code></pre>
  223. <p class="expl">Zero both the forces and torques accumulated on <code>body</code>.</p>
  224. <pre><code>
  225. void cpBodyApplyForce(cpBody *body, cpVect f, cpVect r)
  226. </code></pre>
  227. <p class="expl">Apply (accumulate) the force <code>f</code> on <code>body</code> with offset <code>r</code>. Both <code>f</code> and <code>r</code> should be in world coordinates.</p>
  228. <pre><code>
  229. void cpBodyUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
  230. </code></pre>
  231. <p class="expl">Updates the velocity of the body using Euler integration. You don&#8217;t need to call this unless you are managing the object manually instead of adding it to a <code>cpSpace</code>.</p>
  232. <pre><code>
  233. void cpBodyUpdatePosition(cpBody *body, cpFloat dt)
  234. </code></pre>
  235. <p class="expl">Updates the position of the body using Euler integration. Like <code>cpBodyUpdateVelocity()</code> you shouldn&#8217;t normally need to call this yourself.</p>
  236. <pre><code>
  237. void cpDampedSpring(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat rlen, cpFloat k, cpFloat dmp, cpFloat dt)
  238. </code></pre>
  239. <p class="expl">Apply a spring force between bodies <code>a</code> and <code>b</code> at anchors <code>anchr1</code> and <code>anchr2</code> respectively. <code>k</code> is the spring constant (force/distance), <code>rlen</code> is the rest length of the spring, <code>dmp</code> is the damping constant (force/velocity), and <code>dt</code> is the time step to apply the force over. <strong>Note:</strong> <em>not solving the damping forces in the impulse solver causes problems with large damping values. This function will eventually be replaced by a new constraint (joint) type.</em></p>
  240. <p><strong>Notes:</strong></p>
  241. <ul>
  242. <li>Use forces to modify the rigid bodies if possible. This is likely to be the most stable.</li>
  243. <li>Modifying a body&#8217;s velocity shouldn&#8217;t necessarily be avoided, but applying large changes can cause strange results in the simulation. Experiment freely, but be warned.</li>
  244. <li><strong>Don&#8217;t</strong> modify a body&#8217;s position every step unless you really know what you are doing. Otherwise you&#8217;re likely to get the position/velocity badly out of sync.</li>
  245. </ul>
  246. <h3>Chipmunk collision shapes: <code>cpShape</code></h3>
  247. <p>There are currently 3 possible collision shapes:</p>
  248. <ul>
  249. <li><strong>Circles</strong>: Fastest collision shape. They also roll smoothly.</li>
  250. <li><strong>Line segments</strong>: Meant mainly as a static shape. They can be attached to moving bodies, but they don&#8217;t generate collisions with other line segments.</li>
  251. <li><strong>Convex polygons</strong>: Slowest, but most flexible collision shape.</li>
  252. </ul>
  253. <p><strong>User accessible fields:</strong></p>
  254. <pre><code>
  255. typedef struct cpShape{
  256. cpBB bb;
  257. unsigned long collision_type;
  258. unsigned long group;
  259. unsigned long layers;
  260. void *data;
  261. cpBody *body;
  262. cpFloat e, u;
  263. cpVect surface_v;
  264. } cpShape;
  265. </code></pre>
  266. <ul>
  267. <li><code>bb</code>: The bounding box of the shape. Only guaranteed to be valid after <code>cpShapeCacheBB()</code> is called.</li>
  268. <li><code>collision_type</code>: A user definable field, see the collision pair function section below for more information.</li>
  269. <li><code>group</code>: Shapes in the same non-zero group do not generate collisions. Useful when creating an object out of many shapes that you don&#8217;t want to self collide. Defaults to <code>0</code>;</li>
  270. <li><code>layers</code>: Shapes only collide if they are in the same bit-planes. i.e. <code>(a-&gt;layers &#38; b-&gt;layers) != 0</code> By default, a shape occupies all 32 bit-planes.</li>
  271. <li><code>data</code>: A user definable field.</li>
  272. <li><code>body</code>: The rigid body the shape is attached to.</li>
  273. <li><code>e</code>: Elasticity of the shape. A value of 0.0 gives no bounce, while a value of 1.0 will give a &#8220;perfect&#8221; bounce. However due to inaccuracies in the simulation using 1.0 or greater is not recommended however. <em>See the notes at the end of the section.</em></li>
  274. <li><code>u</code>: Friction coefficient. Chipmunk uses the Coulomb friction model, a value of 0.0 is frictionless. <a href="http://www.roymech.co.uk/Useful_Tables/Tribology/co_of_frict.htm">Tables of friction coefficients</a>. <em>See the notes at the end of the section.</em></li>
  275. <li><code>surface_v</code>: The surface velocity of the object. Useful for creating conveyor belts or players that move around. This value is only used when calculating friction, not the collision.</li>
  276. </ul>
  277. <pre><code>
  278. void cpShapeDestroy(cpShape *shape)
  279. void cpShapeFree(cpShape *shape)
  280. </code></pre>
  281. <p class="expl"><code>Destroy</code> and <code>Free</code> functions are shared by all shape types.</p>
  282. <pre><code>
  283. cpBB cpShapeCacheBB(cpShape *shape)
  284. </code></pre>
  285. <p class="expl">Updates and returns the bounding box of <code>shape</code>.</p>
  286. <pre><code>
  287. void cpResetShapeIdCounter(void)
  288. </code></pre>
  289. <p class="expl">Chipmunk keeps a counter so that every new shape is given a unique hash value to be used in the spatial hash. Because this affects the order in which the collisions are found and handled, you should reset the shape counter every time you populate a space with new shapes. If you don&#8217;t, there might be (very) slight differences in the simulation.</p>
  290. <pre><code>
  291. cpCircleShape *cpCircleShapeAlloc(void)
  292. cpCircleShape *cpCircleShapeInit(cpCircleShape *circle, cpBody *body, cpVect offset, cpFloat radius)
  293. cpShape *cpCircleShapeNew(cpBody *body, cpVect offset, cpFloat radius)
  294. </code></pre>
  295. <p class="expl"><code>body</code> is the body to attach the circle to, <code>offset</code> is the offset from the body&#8217;s center of gravity in body local coordinates.</p>
  296. <pre><code>
  297. cpSegmentShape* cpSegmentShapeAlloc(void)
  298. cpSegmentShape* cpSegmentShapeInit(cpSegmentShape *seg, cpBody *body, cpVect a, cpVect b, cpFloat radius)
  299. cpShape* cpSegmentShapeNew(cpBody *body, cpVect a, cpVect b, cpFloat radius)
  300. </code></pre>
  301. <p class="expl"><code>body</code> is the body to attach the segment to, <code>a</code> and <code>b</code> are the endpoints, and <code>radius</code> is the thickness of the segment.</p>
  302. <pre><code>
  303. cpPolyShape *cpPolyShapeAlloc(void)
  304. cpPolyShape *cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int numVerts, cpVect *verts, cpVect offset)
  305. cpShape *cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpVect offset)
  306. </code></pre>
  307. <p class="expl"><code>body</code> is the body to attach the poly to, <code>verts</code> is an array of <code>cpVect</code>&#8217;s defining a convex hull with a counterclockwise winding, <code>offset</code> is the offset from the body&#8217;s center of gravity in body local coordinates.</p>
  308. <strong>Notes:</strong>
  309. <ul>
  310. <li>You can attach multiple collision shapes to a rigid body. This should allow you to create almost any shape you could possibly need.</li>
  311. <li>Shapes attached to the same rigid body will never generate collisions. You don&#8217;t have to worry about overlap when attaching multiple shapes to a rigid body.</li>
  312. <li>The amount of elasticity applied during a collision is determined by multiplying the elasticity of both shapes together. The same is done for determining the friction.</li>
  313. <li>Make sure you add both the body and it&#8217;s collision shapes to a space. The exception is when you want to have a static body or a body that you integrate yourself. In that case, only add the shape.</li>
  314. </ul>
  315. <h3>Chipmunk joints: <code>cpJoint</code></h3>
  316. <p>There are currently 4 kinds of joints:</p>
  317. <ul>
  318. <li><strong>Pin Joints</strong> connect two rigid bodies with a solid pin or rod. It keeps the anchor points at a set distance from one another.</li>
  319. <li><strong>Slide Joints</strong> are like pin joints, but have a minimum and maximum distance. A chain could be modeled using this joint. It keeps the anchor points from getting to far apart, but will allow them to get closer together.</li>
  320. <li><strong>Pivot Joints</strong> simply allow two objects to pivot about a single point.</li>
  321. <li><strong>Groove Joints</strong> attach a point on one body to a groove on the other. Think of it as a sliding pivot joint.</li>
  322. </ul>
  323. <pre><code>
  324. void cpJointDestroy(cpJoint *joint)
  325. void cpJointFree(cpJoint *joint)
  326. </code></pre>
  327. <p class="expl"><code>Destroy</code> and <code>Free</code> functions are shared by all joint types.</p>
  328. <pre><code>
  329. cpPinJoint *cpPinJointAlloc(void)
  330. cpPinJoint *cpPinJointInit(cpPinJoint *joint, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2)
  331. cpJoint *cpPinJointNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2)
  332. </code></pre>
  333. <p class="expl"><code>a</code> and <code>b</code> are the two bodies to connect, and <code>anchr1</code> and <code>anchr2</code> are the anchor points on those bodies.</p>
  334. <pre><code>
  335. cpSlideJoint *cpSlideJointAlloc(void)
  336. cpSlideJoint *cpSlideJointInit(cpSlideJoint *joint, cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat min, cpFloat max)
  337. cpJoint *cpSlideJointNew(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat min, cpFloat max)
  338. </code></pre>
  339. <p class="expl"><code>a</code> and <code>b</code> are the two bodies to connect, <code>anchr1</code> and <code>anchr2</code> are the anchor points on those bodies, and <code>min</code> and <code>max</code> define the allowed distances of the anchor points.</p>
  340. <pre><code>
  341. cpPivotJoint *cpPivotJointAlloc(void)
  342. cpPivotJoint *cpPivotJointInit(cpPivotJoint *joint, cpBody *a, cpBody *b, cpVect pivot)
  343. cpJoint *cpPivotJointNew(cpBody *a, cpBody *b, cpVect pivot)
  344. </code></pre>
  345. <p class="expl"><code>a</code> and <code>b</code> are the two bodies to connect, and <code>pivot</code> is the point in world coordinates of the pivot. Because the pivot location is given in world coordinates, you must have the bodies moved into the correct positions already.</p>
  346. <pre><code>
  347. cpGrooveJoint *cpGrooveJointAlloc(void)
  348. cpGrooveJoint *cpGrooveJointInit(cpGrooveJoint *joint, cpBody *a, cpBody *b, cpVect groove_a, cpVect groove_b, cpVect anchr2)
  349. cpJoint *cpGrooveJointNew(cpBody *a, cpBody *b, cpVect groove_a, cpVect groove_b, cpVect anchr2)
  350. </code></pre>
  351. <p class="expl">The groove goes from <em>groov_a</em> to <em>groove_b</em> on body <em>a_, and the pivot is attached to _anchr2</em> on body <em>b</em>. All coordinates are body local.</p>
  352. <p><strong>Notes:</strong></p>
  353. <ul>
  354. <li>You can add multiple joints between two bodies, but make sure that they don&#8217;t fight. It can cause the bodies to explode.</li>
  355. <li>Make sure you add both of the connected bodies and the joint to a space.</li>
  356. </ul>
  357. <h3>Chipmunk spaces: <code>cpSpace</code></h3>
  358. <p><strong>User accessible fields:</strong></p>
  359. <pre><code>
  360. typedef struct cpSpace{
  361. int iterations;
  362. cpVect gravity;
  363. cpFloat damping;
  364. int stamp;
  365. } cpSpace;
  366. </code></pre>
  367. <ul>
  368. <li><code>iterations</code>: The number of iterations to use when solving constraints (collisions and joints). Defaults to 10.</li>
  369. <li><code>gravity</code>: The amount of gravity applied to the system.</li>
  370. <li><code>damping</code>: The amount of viscous damping applied to the system.</li>
  371. <li><code>stamp</code>: The tick stamp. Incremented every time <code>cpSpaceStep()</code> is called. <em>read only</em></li>
  372. </ul>
  373. <pre><code>
  374. void cpSpaceFreeChildren(cpSpace *space)
  375. </code></pre>
  376. <p class="expl">Frees all bodies, shapes and joints added to the system.</p>
  377. <pre><code>
  378. cpSpace* cpSpaceAlloc(void)
  379. cpSpace* cpSpaceInit(cpSpace *space, int iterations)
  380. cpSpace* cpSpaceNew(int iterations)
  381. void cpSpaceDestroy(cpSpace *space)
  382. void cpSpaceFree(cpSpace *space)
  383. </code></pre>
  384. <p class="expl">More standard Chipmunk memory functions.</p>
  385. <pre><code>
  386. void cpSpaceFreeChildren(cpSpace *space)
  387. </code></pre>
  388. <p class="expl">This function will free all of the shapes, bodies and joints that have been added to <code>space</code>.</p>
  389. <pre><code>
  390. void cpSpaceAddShape(cpSpace *space, cpShape *shape)
  391. void cpSpaceAddStaticShape(cpSpace *space, cpShape *shape)
  392. void cpSpaceAddBody(cpSpace *space, cpBody *body)
  393. void cpSpaceAddJoint(cpSpace *space, cpJoint *joint)
  394. void cpSpaceRemoveShape(cpSpace *space, cpShape *shape)
  395. void cpSpaceRemoveStaticShape(cpSpace *space, cpShape *shape)
  396. void cpSpaceRemoveBody(cpSpace *space, cpBody *body)
  397. void cpSpaceRemoveJoint(cpSpace *space, cpJoint *joint)
  398. </code></pre>
  399. <p class="expl">These functions add and remove shapes, bodies and joints from <code>space</code>. Shapes added as static are assumed not to move. Static shapes should be be attached to a rigid body with an infinite mass and moment of inertia. Also, don&#8217;t add the rigid body used to the space, as that will cause it to fall under the effects of gravity.</p>
  400. <pre><code>
  401. void cpSpaceResizeStaticHash(cpSpace *space, cpFloat dim, int count)
  402. void cpSpaceResizeActiveHash(cpSpace *space, cpFloat dim, int count)
  403. </code></pre>
  404. <p class="expl">The spatial hashes used by Chipmunk&#8217;s collision detection are fairly size sensitive. <code>dim</code> is the size of the hash cells. Setting <code>dim</code> to the average objects size is likely to give the best performance.</p>
  405. <p class="expl"><code>count</code> is the suggested minimum number of cells in the hash table. Bigger is better, but only to a point. Setting <code>count</code> to ~10x the number of objects in the hash is probably a good starting point.</p>
  406. <p class="expl">By default, <code>dim</code> is 100.0, and <code>count</code> is 1000.</p>
  407. <pre><code>
  408. void cpSpaceRehashStatic(cpSpace *space)
  409. </code></pre>
  410. <p class="expl">Rehashes the shapes in the static spatial hash. You only need to call this if you move one of the static shapes.</p>
  411. <pre><code>
  412. void cpSpaceStep(cpSpace *space, cpFloat dt)
  413. </code></pre>
  414. <p class="expl">Update the space for the given time step. Using a fixed time step is <em>highly</em> recommended. Doing so will increase the efficiency of the contact persistence, requiring an order of magnitude fewer iterations to resolve the collisions in the usual case.</p>
  415. <p><strong>Notes:</strong></p>
  416. <ul>
  417. <li>When removing objects from the space, make sure you remove any other objects that reference it. For instance, when you remove a body, remove the joints and shapes attached to it.</li>
  418. <li>The number of iterations, and the size of the time step determine the quality of the simulation. More iterations, or smaller time steps increase the quality.</li>
  419. <li>Because static shapes are only rehashed when you request it, it&#8217;s possible to use a much higher <code>count</code> argument to <code>cpHashResizeStaticHash()</code> than to <code>cpHashResizeStaticHash()</code>. Doing so will use more memory though.</li>
  420. </ul>
  421. <h3>Miscellaneous.</h3>
  422. <pre><code>
  423. cpFloat cpMomentForCircle(cpFloat m, cpFloat r1, cpFloat r2, cpVect offset)
  424. </code></pre>
  425. <p class="expl">Calculate the moment of inertia for a circle. Arguments are similar to <code>cpCircleShapeInit()</code>. <em>m_ is the mass, _r1</em> and <em>r2</em> define an inner and outer radius, and <em>offset</em> is the offset of the center from the center of gravity of the rigid body.</p>
  426. <pre><code>
  427. cpFloat cpMomentForPoly(cpFloat m, int numVerts, cpVect *verts, cpVect offset)
  428. </code></pre>
  429. <p class="expl">Calculate the moment of inertia for a poly. Arguments are similar to <code>cpPolyShapeInit()</code> <em>m_ is the mass, _numVerts</em> is the number of vertexes in <em>verts</em>, and <em>offset</em> is the offset of the poly coordinates from the center of gravity of the rigid body.</p>
  430. <h3>Collision pair functions</h3>
  431. <p>Collision pair functions allow you to add callbacks for certain collision events. Each <code>cpShape</code> structure has a user definable <code>collision_type</code> field that is used to identify its type. For instance, you could define an enumeration of collision types such as bullets and players, and then register a collision pair function to reduce the players health when a collision is found between the two.</p>
  432. <p>Additionally, the return value of a collision pair function determines whether or not a collision will be processed. If the function returns false, the collision will be ignored. One use for this functionality is to allow a rock object to break a vase object. If the approximated energy of the collision is above a certain level, flag the vase to be removed from the space, apply an impulse to the rock to slow it down, and return false. After the <code>cpSpaceStep()</code> returns, remove the vase from the space.</p>
  433. <p><strong><span class="caps">WARNING</span>:</strong> <em>It is not safe for collision pair functions to remove or free shapes or bodies from a space. Doing so will likely end in a segfault as an earlier collision may already be referencing the shape or body. You must wait until after the <code>cpSpaceStep()</code> function returns.</em></p>
  434. <pre><code>
  435. typedef struct cpContact{
  436. cpVect p, n;
  437. cpFloat dist;
  438. cpFloat jnAcc, jtAcc;
  439. } cpContact;
  440. </code></pre>
  441. <p class="expl">An array of <code>cpContact</code> structs are passed to collision pair functions. Some user accessible fields include:</p>
  442. <ul>
  443. <li><code>p</code>: position of the collision.</li>
  444. <li><code>n</code>: normal of the collision.</li>
  445. <li><code>dist</code>: penetration distance of the collision.</li>
  446. <li><code>jnAcc</code> and <code>jtAcc</code>: The normal and tangential components of the accumulated (final) impulse applied to resolve the collision. Values will not be valid until after the call to <code>cpSpaceStep()</code> returns.</li>
  447. </ul>
  448. <pre><code>
  449. typedef int (*cpCollFunc)(cpShape *a, cpShape *b, cpContact *contacts, int numContacts, cpFloat normal_coef, void *data)
  450. </code></pre>
  451. <p class="expl">Prototype for a collision callback function. The two colliding shapes are passed as <code>a</code> and <code>b</code>, along with the contact points, and a user definable pointer are passed as arguments. The shapes are passed in the same order as their types were registered using <code>cpSpaceAddCollisionPairFunc()</code>. Because Chipmunk may swap the shapes to accommodate your collision pair function the normals may be backwards. Always multiply the normals by <em>normal_coef</em> before using the values. The <code>contacts</code> array may be freed on the next call to <code>cpSpaceStep()</code>.</p>
  452. <pre><code>
  453. void cpSpaceAddCollisionPairFunc(cpSpace *space, unsigned long a, unsigned long b, cpCollFunc func, void *data)
  454. </code></pre>
  455. <p class="expl">Register <code>func</code> to be called when a collision is found between a shapes with <code>collision_type</code> fields that match <code>a</code> and <code>b</code>. <code>data</code> is passed to <code>func</code> as a parameter. The ordering of the collision types will match the ordering passed to the callback function.</p>
  456. <p class="expl">Passing <code>NULL</code> for <code>func</code> will reject any collision with the given collision type pair.</p>
  457. <pre><code>
  458. void cpSpaceRemoveCollisionPairFunc(cpSpace *space, unsigned long a, unsigned long b)
  459. </code></pre>
  460. <p class="expl">Remove the function for the given collision type pair. The order of <code>a</code> and <code>b</code> must match the original order used with <code>cpSpaceAddCollisionPairFunc()</code>.</p>
  461. <pre><code>
  462. void cpSpaceSetDefaultCollisionPairFunc(cpSpace *space, cpCollFunc func, void *data)
  463. </code></pre>
  464. <p class="expl">The default function is called when no collision pair function is specified. By default, the default function simply accepts all collisions. Passing <code>NULL</code> for <code>func</code> will reset the default function back to the default. (You know what I mean.)</p>
  465. <p class="expl">Passing <code>NULL</code> for <code>func</code> will reject collisions by default.</p>
  466. <h2>Advanced topics</h2>
  467. <h3>Advanced collision processing</h3>
  468. <p>Using collision pair functions, it&#8217;s possible to get information about a collision such as the locations of the contact points and the normals, but you can&#8217;t get the impulse applied to each contact point at the time the callback is called. Because Chipmunk caches the impulses, it is possible to access them after the call to <code>cpSpaceStep()</code> returns.</p>
  469. <p>The impulse information is stored in the <code>jnAcc</code> and <code>jtAcc</code> fields of the <code>cpContact</code> structures passed to the collision pair function. So you must store a reference to the <code>contacts</code> array in the collision pair function so that you can access it later once the impulses have been calculated.</p>
  470. <pre><code>
  471. cpVect cpContactsSumImpulses(cpContact *contacts, int numContacts);
  472. cpVect cpContactsSumImpulsesWithFriction(cpContact *contacts, int numContacts);
  473. </code></pre>
  474. <p class="expl">Sums the impulses applied to the the given contact points. <code>cpContactsSumImpulses()</code> sums only the normal components, while <code>cpContactsSumImpulsesWithFriction()</code> sums the normal and tangential componets.</p>
  475. <p><strong>Notes:</strong></p>
  476. <ul>
  477. <li>The <code>contact</code> array will either be destroyed or out of date after the next call to <code>cpSpaceStep()</code>. If you need to store the collision information permanently, you&#8217;ll have to copy it.</li>
  478. </ul>
  479. <h3>Collision pair functions, groups, and layers</h3>
  480. <p>There are three ways that you can specify which shapes are allowed to collide in Chipmunk: collision pair functions, groups, and layers. What are their intended purposes?</p>
  481. <p><strong>Collision pair functions:</strong> More than just a callback, collision pair functions can conditionally allow a collision between two shapes. This is the only choice if you need to perform some logic based on the shapes or contact information before deciding to allow the collision.</p>
  482. <p><strong>Groups:</strong> Groups filter out collisions between objects in the same non-zero groups. A good example of when groups would be useful is to create a multi-body, multi-shape object such as a ragdoll. You don&#8217;t want the parts of the ragdoll to collide with itself, but you do want it to collide with other ragdolls.</p>
  483. <p><strong>Layers:</strong> Layers are another way of grouping shapes. Collision between shapes that don&#8217;t occupy one or more of the same layers are filtered out. Layers are implemented using a bitmask on an unsigned long, so there are up to 32 layers available.</p>
  484. <p>To be clear, for a collision to occur, all of the tests have to pass. Additionally, collisions between static shapes are not considered nor are collisions between shapes connected to the same rigid body.</p>
  485. <h3>Mysteries of <code>cpSpaceStep()</code> explained.</h3>
  486. <p>The <code>cpSpaceStep()</code> function is really the workhorse of Chipmunk. So what exactly does it do?</p>
  487. <ul>
  488. <li>Persistent contacts with a stamp that is out of date by more than <code>cp_contact_persistence</code> are filtered out.</li>
  489. <li>Velocities of all rigid bodies in the space are integrated using <code>cpBodyUpdateVelocity()</code>.</li>
  490. <li>All active shapes have their bounding boxes calculated and cached.</li>
  491. <li>Collisions between the active shapes and static shapes are found. (collision pair functions are called)</li>
  492. <li>Collisions between the active shapes are found. (collision pair functions are called)</li>
  493. <li>Information about all constraints (collisions and joints) is pre-calculated.</li>
  494. <li>Impulses are found and applied to solve all constraints (joints and collisions).</li>
  495. <li>Positions of all rigid bodies in the space are integrated using <code>cpBodyUpdatePosition()</code>.</li>
  496. </ul>
  497. <p>Chipmunk does a lot of processing on the shapes in the system in order to provide robust and fast collision detection, but the same is not true of the rigid bodies. Really all <code>cpSpaceStep()</code> does to the bodies in the system is to integrate them and apply impulses to them.</p>
  498. <p>The integration step is really just for convenience. If you integrate the velocity of your rigid bodies before calling <code>cpSpaceStep()</code> and integrate their positions afterward, you don&#8217;t have to add them to the space at all. In fact, there are good reasons for not doing so. All bodies in the space are integrated using the same gravity and damping, and this prevents you from providing interesting objects such as moving platforms.</p>
  499. <p>If you are going to do the integration for your rigid bodies manually, I would highly recommend that you use <code>cpBodyUpdatePosition()</code> to integrate the position of the objects and only integrate the velocity. <code>cpBodyUpdatePosition()</code> is a required step for penetration resolution, and weird things could happen if it&#8217;s not called. Chipmunk uses Euler integration, so calculating the velocity required to move a body to a specific position is trivial if that is what you wish to do.</p>
  500. <h3>Chipmunk globals.</h3>
  501. <p>Chipmunk was designed with multithreading in mind, so very few globals are used. This shouldn&#8217;t be a problem in most cases as it&#8217;s likely you&#8217;ll only need to set them on a per application basis (if at all).</p>
  502. <p><code>int cp_contact_persistence</code>: This determines how long contacts should persist. This number should be fairly small as the cached contacts will only be close for a short time. <code>cp_contact_persistence</code> defaults to 3 as it is large enough to help prevent oscillating contacts, but doesn&#8217;t allow stale contact information to be used.</p>
  503. <p><code>cpFloat cp_collision_slop</code>: The amount that shapes are allowed to penetrate. Setting this to zero will work just fine, but using a small positive amount will help prevent oscillating contacts. <code>cp_collision_slop</code> defaults to 0.1.</p>
  504. <p><code>cpFloat cp_bias_coef</code>: The amount of penetration to reduce in each step. Values should range from 0 to 1. Using large values will eliminate penetration in fewer steps, but can cause vibration. <code>cp_bias_coef</code> defaults to 0.1.</p>
  505. <p><code>cpFloat cp_joint_bias_coef</code>: Similar to <code>cp_bias_coef</code>, but for joints. Defaults to 0.1. <em>In the future, joints might have their own bias coefficient instead.</em></p>
  506. <h2>Known Problems</h2>
  507. <ul>
  508. <li>Fast moving objects sometimes pass right through one another. This is because I&#8217;m not doing swept volume collisions. Use smaller time steps if this is a problem.</li>
  509. <li>Pointy or thin polygons aren&#8217;t handled well. Collision points are generated at the poly&#8217;s vertexes. I haven&#8217;t decided what to do about this yet.</li>
  510. <li>Elastic shapes don&#8217;t stack well.</li>
  511. </ul>
  512. <h2>Performance/Quality tuning</h2>
  513. <p>There are a number of things you can do to increase the performance of Chipmunk:</p>
  514. <ul>
  515. <li>Use simpler collision shapes when possible. It&#8217;s easier on the collision detection, you&#8217;ll generate fewer contact points, and require fewer iterations.</li>
  516. <li>Make sure you have your spatial hashes tuned properly. It may take some experimenting to find the optimal dim/count parameters.</li>
  517. <li>Use fewer iterations.</li>
  518. <li>Use a larger time step.</li>
  519. <li>Use a fixed time step. This allows contact persistence to work properly, reducing the number of iterations you need by an order of magnitude.</li>
  520. </ul>
  521. <p>If you have problems with jittery or vibrating objects, you need to do mostly the opposite:</p>
  522. <ul>
  523. <li>Use simpler shapes. Simpler shapes generate fewer contacts, increasing the efficiency of each iteration.</li>
  524. <li>Use more iterations.</li>
  525. <li>Use a smaller time step.</li>
  526. <li>Use a fixed time step. By allowing the contact persistence to work properly, you can use more iterations without increasing the computational cost.</li>
  527. </ul>
  528. <h2>To do</h2>
  529. There are a number of things left on my todo list:
  530. <ul>
  531. <li>More joint types.</li>
  532. <li>Post collision queries. Being able to query for all the impulses that were applied to an object would be useful.</li>
  533. <li>Python binding. (possibly others if I can get help)</li>
  534. </ul>
  535. <h2>Contact information</h2>
  536. <p>Drop me a line. Tell me how great you think Chipmunk is or how terribly buggy it is. I&#8217;d love to hear about any project that people are using Chipmunk for.</p>
  537. <p><strong><span class="caps">AIM</span>:</strong> slembcke@mac.com</p>
  538. <p><strong>Email:</strong> lemb0029(at)morris(dot)umn(dot)edu or slembcke(at)gmail(dot)com</p>
  539. <p>I can also be found lurking about the <a href="http://www.idevgames.com">iDevGames</a> forums.</p>
  540. <h2>License</h2>
  541. <p>Copyright&#169; 2007 Scott Lembcke</p>
  542. <p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the &#8220;Software&#8221;), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</p>
  543. <p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</p>
  544. <span class="caps">THE SOFTWARE IS PROVIDED</span> &#8220;AS IS&#8221;, <span class="caps">WITHOUT WARRANTY OF ANY KIND</span>, EXPRESS <span class="caps">OR IMPLIED</span>, INCLUDING <span class="caps">BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY</span>, FITNESS <span class="caps">FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT</span>. IN <span class="caps">NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM</span>, DAMAGES <span class="caps">OR OTHER LIABILITY</span>, WHETHER <span class="caps">IN AN ACTION OF CONTRACT</span>, TORT <span class="caps">OR OTHERWISE</span>, ARISING <span class="caps">FROM</span>, OUT <span class="caps">OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE</span>.
  545. </body>
  546. </html>