Debian Codegraph @

doc-src/chipmunk-docs.textile

raw
1 !images/logo1_med.png! !{float:right;}images/hms_logo.png!:http://howlingmoonsoftware.com
2
3 <%= pop_open_div("Outline") %><%%= Node::Root.outline %></div></div>
4
5 <%= h 1, "Chipmunk2D 7.0.3", "Intro" %>
6
7 Chipmunk2D is a 2D rigid body physics library distributed under the MIT license. It is blazingly fast, portable, numerically stable, and easy to use. For this reason it has been used in hundreds of games across just about every system you can name. This includes top quality titles such as Night Sky for the Wii and many #1 sellers on the iPhone App Store! I've put thousands of hours of work over many years to make Chipmunk2D what it is today. If you find Chipmunk2D has saved you a lot of time, please consider "donating":https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6666552. You'll make an indie game developer very happy!
8
9 First of all, I would like to give a Erin Catto a big thank you, as Chipmunk2D's impulse solver was directly inspired by his example code way back in 2006. (Now a full fledged physics engine all its own: "Box2D.org":http://www.box2d.org/). His contact persistence idea allows for stable stacks of objects with very few iterations of the solver. My previous solver produced mushy piles of objects or required a large amount of CPU to operate stably.
10
11
12 <%= h 2, "Why a C Library?", "WhyC" %>
13
14 A lot of people ask me why I wrote Chipmunk2D in C instead of _pick your favorite language here_. I tend to get really excited about different programming languages. Depending on the month, take your pick of Scheme, OCaml, Ruby, Objective-C, ooc, Lua, Io... the list goes on. The one common factor between most any language is that they are usually dead simple to make bindings to C code. I also wanted Chipmunk2D to be fast, portable, easy to optimize and easy to debug. Writing Chipmunk2D in C made it simpler to achieve all of those goals.
15
16 That said, I've never developed a whole game in C and I probably never will. There are much more interesting and fun languages than C with all sorts of nice features like garbage collection, closures and all sorts of unique object oriented runtimes. Check out the "Bindings and Ports":http://chipmunk2d.net/bindingsAndPorts.php page to see if you can use Chipmunk2D from your language of choice. Because Chipmunk2D is written in a subset of C99 it compiles cleanly as C, C++, Objective-C and Objective-C++ code, making it easy to integrate into projects in those languages.
17
18
19 <%= h 2, "Limitations of a C API:", "Limitations" %>
20
21 Chipmunk does provide overloaded operators for @*@, @+@, and @-@ (unary and binary) if you are using C++, but falls back to using functions such as @cpvadd()@ and @cpvsub()@ for C code. This is a little harder to read, but works OK once you get used to it. Most of the interesting vector operations that are possible don't have a symbol for them anyway (at least not on a keyboard).
22
23 Another problem for a C API is access restriction. There are many structs, fields and functions in Chipmunk that are only meant to be used internally. To work around this, I have a separate header full of Chipmunk's private API, @chipmunk_private.h@. I also use a macro, @CP_PRIVATE()@ to mangle names in public structures. While you can feel free to include this header or use the macro in your own code to access the private API, be aware that the fields and functions may be renamed or disappear without warning and I have no plans to document or support usage of the private API.
24
25 <%= h 2, "Get it, Compile it:", "Compiling" %>
26
27 If you haven't downloaded it yet, you can always download the newest version of Chipmunk2D "here":http://chipmunk-physics.net/release/ChipmunkLatest.tgz. Inside you'll find a command line build script that works with "CMake":http://www.cmake.org/, a XCode project and project files for Visual Studio '09 and '10.
28
29
30 <%= h 3, "Debug or Release?", "DebugRelease" %>
31
32 Debug mode might be slightly slower, but will include a lot of error checking assertions that can help you find bugs quicker such as removing objects twice or doing things that might cause unsolvable collisions. I highly recommend you use a debug build until you are ready to ship the game and only then switch to a release build.
33
34
35 <%= h 3, "XCode (Mac/iPhone)", "XCode" %>
36
37 The included XCode project has targets for building a static library for the Mac or iOS. Additionally, you might want to just run the @xcode/iphonestatic.command@ or @xcode/macstatic.command@ to build you a directory with the headers and debug/release static libraries that you can just drop right into your projects. Including Chipmunk in your project with all the correct compiler flags applied couldn't be simpler. The iPhone script generates a "fat" library that can be used with both the iOS simulator and devices. The device version is compiled as release, and the simulator version is compiled as debug.
38
39
40 <%= h 3, "MSVC", "MSVC" %>
41
42 I rarely use MSVC, but others have chipped in to help me maintain Visual Studio project files. The MSVC 10 project should work, as I usually remember to test that before making a stable release. The MSVC 9 project may not as I don't have access to that version. Let me know if there are any issues.
43
44
45 <%= h 3, "Command Line", "CommandLine" %>
46
47 The CMake build script should work on any system (Unix/Win/Mac) as long as you have CMake installed. It can even generate XCode or MSVC projects if you want (see CMake's documentation for more information).
48
49 To compile a Chipmunk debug build on the command line, all you need to do is run:
50
51 <pre><code>cmake -D CMAKE_BUILD_TYPE=Debug .
52 make</code></pre>
53
54 If the @-D CMAKE_BUILD_TYPE=Debug@ option is left out, it will make a release build instead.
55
56 Why CMake? Somebody was kind enough to create the build scripts for me originally, and it seems to handle a lot of the cross-platform issues nicely. I know some people really hate having to install some random non-make build system in order to compile things, but it has saved me a lot of time and effort.
57
58 <%= h 2, "Hello Chipmunk (World)", "HelloChipmunk" %>
59
60 Hello world Chipmunk style. Create a simple simulation where a ball falls onto a static line segment, then rolls off. Print out the coordinates of the ball.
61
62 <%= pop_open_example "Hello Chipmunk" %>
63
64
65 <%= h 2, "Support:", "Support" %>
66
67 The best way to get support is to visit the "Chipmunk Forums":http://www.slembcke.net/forums/viewforum.php?f=1. There are plenty of people around using Chipmunk on the just about every platform I've ever heard of. If you are working on a commercial project, Howling Moon Software (my company) is "available for contracting":http://howlingmoonsoftware.com/contracting.php. We can help with implementing custom Chipmunk behaviors, as well as priority bug fixes and performance tuning.
68
69
70 <%= h 2, "Contact:", "ContactUS" %>
71
72 If you find any bugs in Chipmunk, errors or broken links in this document, or have a question or comment about Chipmunk you can contact me at slembcke(at)gmail(dot)com. (email or GTalk)
73
74
75 <%= h 2, "License:", "License" %>
76
77 Chipmunk is licensed under the MIT license.
78
79 <pre>
80 Copyright (c) 2007-2015 Scott Lembcke and Howling Moon Software
81
82 Permission is hereby granted, free of charge, to any person obtaining a copy
83 of this software and associated documentation files (the "Software"), to deal
84 in the Software without restriction, including without limitation the rights
85 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
86 copies of the Software, and to permit persons to whom the Software is
87 furnished to do so, subject to the following conditions:
88
89 The above copyright notice and this permission notice shall be included in
90 all copies or substantial portions of the Software.
91
92 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
93 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
94 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
95 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
96 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
97 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
98 SOFTWARE.
99 </pre>
100
101 This means that you do not have to buy a license or pay to use Chipmunk in commercial projects. (Though we really appreciate donations)
102
103
104 <%= h 2, "Links:", "Links" %>
105
106 * "Chipmunk Forums":http://chipmunk2d.net/forum - The official forum Chipmunk2D forum.
107 * "Howling Moon Software":http://howlingmoonsoftware.com/ - The software company I co-founded. (We are available for contract work!)
108 * "Games":http://chipmunk2d.net/games.php - A small list of games we know that use Chipmunk.
109
110
111 <%= h 1, "Chipmunk2D Basics:", "Basics" %>
112
113 <%= h 2, "Overview:", "Overview" %>
114
115 There are 4 basic object types you will use in Chipmunk.
116
117 * *Rigid Bodies:* A rigid body holds the physical properties of an object. (mass, position, rotation, velocity, etc.) It does not have a shape until you attach one or more collision shapes to it. If you’ve done physics with particles before, rigid bodies differ in that they are able to rotate. Rigid bodies generally tend to have a 1:1 correlation to sprites in a game. You should structure your game so that you use the position and rotation of the rigid body for drawing your sprite.
118 * *Collision Shapes:* By attaching shapes to bodies, you can define the a body’s shape. You can attach as many shapes to a single body as you need to in order to define a complex shape. Shapes contain the surface properties of an object such as how much friction or elasticity it has.
119 * *Constraints/Joints:* Constraints and joints describe how bodies are attached to each other.
120 * *Spaces:* Spaces are containers for simulating objects in Chipmunk. You add bodies, shapes and joints to a space and then update the space as a whole. They control how all the rigid bodies, shapes, and constraints interact together.
121
122 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, while a collision shape is an invisible property that defines how objects should collide. Both the sprite's and the collision shape's position and rotation are controlled by the motion of a rigid body. Generally you want to create a game object type that ties these things all together.
123
124
125 <%= h 2, "Memory Management the Chipmunk way:", "Memory" %>
126
127 For most of the structures you will use, Chipmunk uses a more or less standard and straightforward set of memory management functions. Take the "cpSpace":#cpSpace struct for example:
128
129 * @cpSpaceNew()@ - Allocates and initializes a @cpSpace@ struct. It calls @cpSpaceAlloc()@ then @cpSpaceInit()@.
130 * @cpSpaceFree(cpSpace *space)@ - Destroys and frees the @cpSpace@ struct.
131
132 You are responsible for freeing any structs that you allocate. Chipmunk does not do reference counting or garbage collection. If you call a @new@ function, you must call the matching @free@ function or you will leak memory.
133
134 Additionally if you need more control over allocation and initialization because you are allocating temporary structs on the stack, writting a language binding, or working in a low memory environment you can also use the following functions. _Most people will never have any need to use these functions._
135
136 * @cpSpaceAlloc()@ - Allocates but does not initialize a @cpSpace@ struct. All allocation functions look more or less like this: @return (cpSpace *)cpcalloc(1, sizeof(cpSpace));@ You can write your own allocation functions if you want. It is not a requirement that the memory be zeroed.
137 * @cpSpaceInit(cpSpace *space)@ - Initializes a @cpSpace@ struct.
138 * @cpSpaceDestroy(cpSpace *space)@ - Frees all memory allocated by @cpSpaceInit()@, but does not free the @cpSpace@ struct itself.
139
140 Like calls to the @new@ and @free@ functions. Any memory allocated by an @alloc@ function must be freed by @cpfree()@ or similar. Any call to an @init@ function must be matched with its @destroy@ function.
141
142 To further ease integration with garbage collectors or other memory management constraints, Chipmunk has a number of compile time defines (@cpcalloc()@, @cprealloc()@, and @cpfree()@) that can be overriden. If you aren't using Chipmunk from a garbage collected language, I'd highly recommend using libGC. It provides nearly transparent garbage collection for C based languages.
143
144 <%= h 2, "Basic Types:", "Types" %>
145
146 @chipmunk_types.h@ defines a number of basic types that Chipmunk uses. These can be changed at compile time to better suit your needs:
147 * @cpFloat@: Floating point type. Defaults to @double@.
148 * @cpVect@: 2D vector type. "cpVect documentation":#cpVect
149 * @cpBool@: Like every good C library that wants good cross language compatibility, you end up defining your own boolean type. :-\ Defaults to @int@.
150 * @cpDataPointer@: Pointer type defined for callbacks and the user definable data pointer on most Chipmunk structs. Defaults to @void*@.
151 * @cpCollisionType@: Unique identifier for collision shape types. Defaults to @unsigned int@. Defined type must support the @==@ operator.
152 * @cpGroup@: Unique identifier for collision groups. Defaults to @unsigned int@. A @CP_NO_GROUP@ value is defined that can be used when you don't want to specify a group. Defined type must support the equality @==@ operator.
153 * @cpBitmask@: Type used for collision filter categories and masks. Defaults to @unsigned int@. Defined type must support the bitwise AND @&@ operator.
154 * @cpTransform@: Type used for 2x3 affine transforms in Chipmunk.
155
156 If you are writting a game engine or language binding on top of Chipmunk, you might want to choose to use object references instead of integers for collision type and group. I often use class pointers for collision types and game object pointers for groups. It's much simpler than keeping a table of enumerations around.
157
158 *Note:* On the iPhone, @cpFloat@ is defined as @float@ and @cpVect@ is an alias for @CGPoint@ for performance and compatibility reasons.
159
160 <%= h 2, "Math the Chipmunk way:", "Math" %>
161
162 First of all, Chipmunk uses double precision floating point numbers throughout its calculations by default. This is likely to be faster on most modern desktop processors, and means you don't have to worry as much about floating point accuracy. You can change the floating point type used by Chipmunk when compiling the library. Look in @chipmunk_types.h@.
163
164 Chipmunk defines a number of aliases for common math functions so that you can choose to use floats or doubles for Chipmunk's floating point type. In your own code, there probably isn't a strong reason to use these aliases unless you expect you might want to change Chipmunk's floating point type later and a 2% performance hit from using the wrong float/double version of math functions will matter.
165
166 However, there are a few unique functions you will probably find very useful:
167
168 * @cpFloat cpfclamp(cpFloat f, cpFloat min, cpFloat max)@ - Clamp @f@ to be between @min@ and @max@.
169 * @cpFloat cpflerp(cpFloat f1, cpFloat f2, cpFloat t)@ - Linearly interpolate between @f1@ and @f2@.
170 * @cpFloat cpflerpconst(cpFloat f1, cpFloat f2, cpFloat d)@ - Linearly interpolate from @f1@ towards @f2@ by no more than @d@.
171
172 Floating point infinity is defined as @INFINITY@. This is defined by many math libraries, but is not actually part of the C standard library.
173
174 <%= h 1, "Chipmunk Vectors: @cpVect@", "cpVect" %>
175
176 <%= h 2, "Struct Definition, Constants and Constructors:", "Basics" %>
177
178 <pre><code>typedef struct cpVect{
179 cpFloat x, y;
180 } cpVect</code></pre>
181
182 p(expl). 2D vector packed into a struct. No surprises here.
183
184 <pre><code>static const cpVect cpvzero = {0.0f,0.0f};</code></pre>
185
186 p(expl). Constant for the zero vector.
187
188 <pre><code>cpVect cpv(const cpFloat x, const cpFloat y)</code></pre>
189
190 p(expl). Convenience constructor for creating new @cpVect@ structs.
191
192 <%= h 2, "Operations:", "Operations" %>
193
194 * @cpBool cpveql(const cpVect v1, const cpVect v2)@ - Check if two vectors are equal. Chipmunk provides an overloaded @==@ operator when used in C++ programs. _(Be careful when comparing floating point numbers!)_
195 * @cpVect cpvadd(const cpVect v1, const cpVect v2)@ - Add two vectors. Chipmunk provides an overloaded @+@ operator when used in C++ programs.
196 * @cpVect cpvsub(const cpVect v1, const cpVect v2)@ - Subtract two vectors. Chipmunk provides an overloaded @-@ operator when used in C++ programs.
197 * @cpVect cpvneg(const cpVect v)@ - Negate a vector. Chipmunk provides an overloaded unary negation operator @-@ when used in C++ programs.
198 * @cpVect cpvmult(const cpVect v, const cpFloat s)@ - Scalar multiplication. Chipmunk provides an overloaded @*@ operator when used in C++ programs.
199 * @cpFloat cpvdot(const cpVect v1, const cpVect v2)@ - Vector dot product.
200 * @cpFloat cpvcross(const cpVect v1, const cpVect v2)@ - 2D vector cross product analog. The cross product of 2D vectors results in a 3D vector with only a z component. This function returns the value along the z-axis.
201 * @cpVect cpvperp(const cpVect v)@ - Returns a perpendicular vector. (90 degree rotation)
202 * @cpVect cpvrperp(const cpVect v)@ - Returns a perpendicular vector. (-90 degree rotation)
203 * @cpVect cpvproject(const cpVect v1, const cpVect v2)@ - Returns the vector projection of @v1@ onto @v2@.
204 * @cpVect cpvrotate(const cpVect v1, const cpVect v2)@ - Uses complex multiplication to rotate @v1@ by @v2@. Scaling will occur if @v1@ is not a unit vector.
205 * @cpVect cpvunrotate(const cpVect v1, const cpVect v2)@ - Inverse of @cpvrotate()@.
206 * @cpFloat cpvlength(const cpVect v)@ - Returns the length of @v@.
207 * @cpFloat cpvlengthsq(const cpVect v)@ - Returns the squared length of @v@. Faster than @cpvlength()@ when you only need to compare lengths.
208 * @cpVect cpvlerp(const cpVect v1, const cpVect v2, const cpFloat t)@ - Linearly interpolate between @v1@ and @v2@.
209 * @cpVect cpvlerpconst(cpVect v1, cpVect v2, cpFloat d)@ - Linearly interpolate between @v1@ towards @v2@ by distance @d@.
210 * @cpVect cpvslerp(const cpVect v1, const cpVect v2, const cpFloat t)@ - Spherical linearly interpolate between @v1@ and @v2@.
211 * @cpVect cpvslerpconst(const cpVect v1, const cpVect v2, const cpFloat a)@ - Spherical linearly interpolate between @v1@ towards @v2@ by no more than angle @a@ in radians.
212 * @cpVect cpvnormalize(const cpVect v)@ - Returns a normalized copy of @v@. As a special case, it returns @cpvzero@ when called on @cpvzero@.
213 * @cpVect cpvclamp(const cpVect v, const cpFloat len)@ - Clamp @v@ to length @len@.
214 * @cpFloat cpvdist(const cpVect v1, const cpVect v2)@ - Returns the distance between @v1@ and @v2@.
215 * @cpFloat cpvdistsq(const cpVect v1, const cpVect v2)@ - Returns the squared distance between @v1@ and @v2@. Faster than @cpvdist()@ when you only need to compare distances.
216 * @cpBool cpvnear(const cpVect v1, const cpVect v2, const cpFloat dist)@ - Returns true if the distance between @v1@ and @v2@ is less than @dist@.
217 * @cpVect cpvforangle(const cpFloat a)@ - Returns the unit length vector for the given angle (in radians).
218 * @cpFloat cpvtoangle(const cpVect v)@ - Returns the angular direction @v@ is pointing in (in radians).
219
220
221 <%= h 1, "Chipmunk Axis Aligned Bounding Boxes: @cpBB@", "cpBB" %>
222
223 <%= h 2, "Struct Definition and Constructors:", "Basics" %>
224
225 <pre><code>typedef struct cpBB{
226 cpFloat l, b, r ,t;
227 } cpBB</code></pre>
228
229 p(expl). Simple bounding box struct. Stored as left, bottom, right, top values.
230
231 <pre><code>cpBB cpBBNew(const cpFloat l, const cpFloat b, const cpFloat r, const cpFloat t)</code></pre>
232
233 p(expl). Convenience constructor for @cpBB@ structs. Like @cpv()@ this function returns a copy and not a malloced pointer.
234
235 <pre><code>cpBB cpBBNewForExtents(const cpVect c, const cpFloat hw, const cpFloat hh)</code></pre>
236
237 p(expl). Convenience constructor for making a @cpBB@ fitting with a center point and half width and height.
238
239 <pre><code>cpBB cpBBNewForCircle(const cpVect p, const cpFloat r)</code></pre>
240
241 p(expl). Convenience constructor for making a @cpBB@ fitting a circle at position @p@ with radius @r@.
242
243
244 <%= h 2, "Operations:", "Operations" %>
245
246 * @cpBool cpBBIntersects(const cpBB a, const cpBB b)@ - Returns true if the bounding boxes intersect.
247 * @cpBool cpBBContainsBB(const cpBB bb, const cpBB other)@ - Returns true if @bb@ completely contains @other@.
248 * @cpBool cpBBContainsVect(const cpBB bb, const cpVect v)@ - Returns true if @bb@ contains @v@.
249 * @cpBB cpBBMerge(const cpBB a, const cpBB b)@ - Return the minimal bounding box that contains both @a@ and @b@.
250 * @cpBB cpBBExpand(const cpBB bb, const cpVect v)@ - Return the minimal bounding box that contains both @bb@ and @v@.
251 * @cpVect cpBBCenter(const cpBB bb)@ - Return the center of @bb@.
252 * @cpFloat cpBBArea(cpBB bb)@ - Return the area of @bb@.
253 * @cpFloat cpBBMergedArea(cpBB a, cpBB b)@ - Merges @a@ and @b@ then returns the area of the merged bounding box.
254 * @cpFloat cpBBSegmentQuery(cpBB bb, cpVect a, cpVect b)@ - Returns the fraction along the segment query the cpBB is hit. Returns INFINITY if it doesn't hit.
255 * @cpBool cpBBIntersectsSegment(cpBB bb, cpVect a, cpVect b)@ - Returns true if the segment defined by endpoints @a@ and @b@ intersect @bb@.
256 * @cpVect cpBBClampVect(const cpBB bb, const cpVect v)@ - Returns a copy of @v@ clamped to the bounding box.
257 * @cpVect cpBBWrapVect(const cpBB bb, const cpVect v)@ - Returns a copy of @v@ wrapped to the bounding box.
258
259
260 <%= h 1, "Chipmunk Rigid Bodies: @cpBody@", "cpBody" %>
261
262 <%= h 2, "Dynamic, Kinematic, and Static Bodies:", "BodyTypes" %>
263
264 Chipmunk supports three different types of bodies with unique behavioral and performance characteristics.
265
266 Dynamic bodies are the default body type. They react to collisions, are affected by forces and gravity, and have a finite amount of mass. These are the type of bodies that you want the physics engine to simulate for you. Dynamic bodies interact with all types of bodies and can generate collision callbacks.
267
268 Kinematic bodies are bodies that are controlled from your code instead of inside the physics engine. They arent affected by gravity and they have an infinite amount of mass so they don't react to collisions or forces with other bodies. Kinematic bodies are controlled by setting their velocity, which will cause them to move. Good examples of kinematic bodies might include things like moving platforms. Objects that are touching or jointed to a kinematic body are never allowed to fall asleep.
269
270 Static bodies are bodies that never (or rarely) move. Using static bodies for things like terrain offers a big performance boost over other body types- because Chipmunk doesn't need to check for collisions between static objects and it never needs to update their collision information. Additionally, because static bodies don't move, Chipmunk knows it's safe to let objects that are touching or jointed to them fall asleep. Generally all of your level geometry will be attached to a static body except for things like moving platforms or doors. Every space provide a built-in static body for your convenience. Static bodies can be moved, but there is a performance penalty as the collision information is recalculated. There is no penalty for having multiple static bodies, and it can be useful for simplifying your code by allowing different parts of your static geometry to be initialized or moved separately.
271
272 <%= h 2, "Movement, Teleportation, and Velocity:", "Movement" %>
273
274 A graphics engine only needs to know the position of an object for each frame that its drawn. For a physics engine, this isn't enough information to calculate a collision response. When you set the position of a body, you are effectively asking it to teleport itself. This means that it will instantly move to its new position instead of moving through space and time like a normal object. If you teleport an object so that it overlaps another one, the best the physics engine can do is to attempt to push the objects apart again since there is no information about their movement. This generally results in very mushy looking collisions. So instead of setting the position of an object, it's better to set its velocity and allow the physics engine to update the position. That way it can resolve any resulting colisions natuarally since it knows how the objects were moving. This is why kinematic bodies work the way they do. You set the velocity, and the physics updates their position so the two are never out of sync.
275
276
277 For dynamic bodies, setting the velocity explicitly every frame can cause problems. For example, a problem occurs when a light dynamic body (like a person) is pressed against a heavy dynamic body (like a car), and you set velocity of the small object so that it's pushing it into the big body. To the physics engine, the change in velocity is the same as applying a large impulse (a very short, very large force). Even if the velocity is low, the large force can allow the small body to push the big body, even when it normally wouldn't be able to. For example, a person walking into a car can overpower the car's friction and cause it to creep along the ground slowly. Additionally, when you set the velocity of an object that is already in contact, it can cause the two objects to overlap by a small amount. The easiest way to avoid both of these problems is to make smaller changes to the body's velocity, accelerating it over a fraction of a second instead of a single frame. An even better solution, which is covered more thoroughly later, is to use constraints to move the object.
278
279 <%= h 2, "Memory Management Functions:", "Memory" %>
280
281 <pre><code>cpBody *cpBodyAlloc(void)
282 cpBody *cpBodyInit(cpBody *body, cpFloat m, cpFloat i)
283 cpBody *cpBodyNew(cpFloat m, cpFloat i)
284
285 cpBody *cpBodyInitKinematic(cpBody *body)
286 cpBody *cpBodyNewKinematic()
287
288 cpBody *cpBodyInitStatic(cpBody *body)
289 cpBody *cpBodyNewStatic()
290
291 void cpBodyDestroy(cpBody *body)
292 void cpBodyFree(cpBody *body)</code></pre>
293
294 p(expl). Standard set of Chipmunk memory management functions. @m@ and @i@ are the mass and moment of inertia for the body. Guessing the mass for a body is usually fine, but guessing a moment of inertia can lead to a very poor simulation so it's recommended to use Chipmunk's moment calculations to estimate the moment for you. Be careful not to free a body before any shapes or constraints attached to it have been removed from a space.
295
296 <%= h 2, "Creating Dynamic Bodies:", "DynamicBodies" %>
297
298 There are two ways to set up a dynamic body. The easiest option is to create a body with a mass and moment of 0, and set the mass or density of each collision shape added to the body. Chipmunk will automatically calculate the mass, moment of inertia, and center of gravity for you. This is probably preferred in most cases.
299
300 TODO example
301
302 The other option is to set the mass of the body when it's created, and leave the mass of the shapes added to it as 0.0. This approach is more flexible, but is not as easy to use. *Don't* set the mass of both the body and the shapes. If you do so, it will recalculate and overwite your custom mass value when the shapes are added to the body.
303
304 TODO example
305
306
307 <%= h 2, "Properties:", "Properties" %>
308
309 Chipmunk provides getter/setter functions for a number of properties on rigid bodies. Setting most properties automatically wakes the rigid bodies up if they were sleeping. You can also set the fields directly on the cpBody struct if you wish. They are documented in the headers.
310
311 <pre><code>cpBodyType cpBodyGetType(const cpBody *body)
312 void cpBodySetType(cpBody *body, cpBodyType)</code></pre>
313
314 p(expl). Set the type of a body (dynamic, kinematic, static). See the section on "BodyTypes":#BodyTypes for more information. When changing an body to a dynamic body, the mass and moment of inertia are recalculated from the shapes added to the body. Custom calculated moments of inertia are not preseved when changing types. This function cannot be called directly in a collision callback. See "Post-Step Callbacks":#PostStep for more information.
315
316 <pre><code>cpSpace cpBodyGetSpace(const cpBody *body)</code></pre>
317
318 p(expl). The @cpSpace@ this body is currently added to, or @NULL@ if it is not currently added to a space.
319
320 <pre><code>cpFloat cpBodyGetMass(const cpBody *body)
321 void cpBodySetMass(cpBody *body, cpFloat m)</code></pre>
322
323 p(expl). Mass of the body.
324
325 <pre><code>cpFloat cpBodyGetMoment(const cpBody *body)
326 void cpBodySetMoment(cpBody *body, cpFloat i)</code></pre>
327
328 p(expl). Moment of inertia (MoI or sometimes just moment) of the body. The moment is like the rotational mass of a body. See below for function to help calculate the moment.
329
330 <pre><code>cpVect cpBodyGetPosition(const cpBody *body)
331 void cpBodySetPosition(cpBody *body, cpVect pos)</code></pre>
332
333 p(expl). Position of the body. When changing the position you may also want to call @cpSpaceReindexShapesForBody()@ to update the collision detection information for the attached shapes if plan to make any queries against the space.
334
335 <pre><code>cpVect cpBodyGetCenterOfGravity(const cpBody *body)
336 void cpBodySetCenterOfGravity(cpBody *body, cpVect cog)</code></pre>
337
338 p(expl). Location of the center of gravity in body local coordinates. The default value is @(0, 0)@, meaning the center of gravity is the same as the position of the body.
339
340 <pre><code>cpVect cpBodyGetVelocity(const cpBody *body)
341 void cpBodySetVelocity(cpBody *body, const cpVect value)</code></pre>
342
343 p(expl). Linear velocity of the center of gravity of the body.
344
345 <pre><code>cpVect cpBodyGetForce(const cpBody *body)
346 void cpBodySetForce(cpBody *body, const cpVect value)</code></pre>
347
348 p(expl). Force applied to the center of gravity of the body. This value is reset for every time step.
349
350 <pre><code>cpFloat cpBodyGetAngle(const cpBody *body)
351 void cpBodySetAngle(cpBody *body, cpFloat a)</code></pre>
352
353 p(expl). Rotation of the body in radians. When changing the rotation you may also want to call @cpSpaceReindexShapesForBody()@ to update the collision detection information for the attached shapes if plan to make any queries against the space. A body rotates around its center of gravity, not its position.
354
355 <pre><code>cpFloat cpBodyGetAngularVelocity(const cpBody *body)
356 void cpBodySetAngularVelocity(cpBody *body, const cpFloat value)</code></pre>
357
358 p(expl). The angular velocity of the body in radians per second.
359
360 <pre><code>cpFloat cpBodyGetTorque(const cpBody *body)
361 void cpBodySetTorque(cpBody *body, const cpFloat value)</code></pre>
362
363 p(expl). The torque applied to the body. This value is reset for every time step.
364
365 <pre><code>cpVect cpBodyGetRotation(const cpBody *body)</code></pre>
366
367 p(expl). The rotation vector for the body. Can be used with @cpvrotate()@ or @cpvunrotate()@ to perform fast rotations.
368
369 <pre><code>cpSpace* cpBodyGetSpace(const cpBody *body)</code></pre>
370
371 p(expl). Get the @cpSpace@ that @body@ has been added to.
372
373 <pre><code>cpDataPointer cpBodyGetUserData(const cpBody *body)
374 void cpBodySetUserData(cpBody *body, const cpDataPointer value)</code></pre>
375
376 p(expl). User data pointer. Use this pointer to get a reference to the game object that owns this body from callbacks.
377
378
379 <%= h 2, "Moment of Inertia and Area Helper Functions:", "Helpers" %>
380
381 Use the following functions to approximate the moment of inertia for your body, adding the results together if you want to use more than one.
382
383 * @cpFloat cpMomentForCircle(cpFloat m, cpFloat r1, cpFloat r2, cpVect offset)@ - Calculate the moment of inertia for a hollow circle, @r1@ and @r2@ are the inner and outer diameters in no particular order. _(A solid circle has an inner diameter of 0)_
384 * @cpFloat cpMomentForSegment(cpFloat m, cpVect a, cpVect b, cpFloat radius)@ - Calculate the moment of inertia for a line segment. The endpoints @a@ and @b@ are relative to the body.
385 * @cpFloat cpMomentForPoly(cpFloat m, int count, const cpVect *verts, cpVect offset, cpFloat radius)@ - Calculate the moment of inertia for a solid polygon shape assuming its center of gravity is at its centroid. The offset is added to each vertex.
386 * @cpFloat cpMomentForBox(cpFloat m, cpFloat width, cpFloat height)@ - Calculate the moment of inertia for a solid box centered on the body.
387
388 <!-- TODO poly examples -->
389
390 <%= pop_open_example "Moments" %>
391
392 Use the following functions to get the area for common Chipmunk shapes if you want to approximate masses or density or whatnot.
393
394 * @cpFloat cpAreaForCircle(cpFloat r1, cpFloat r2)@ - Area of a hollow circle.
395 * @cpFloat cpAreaForSegment(cpVect a, cpVect b, cpFloat r)@ - Area of a beveled segment. _(Will always be zero if radius is zero)_
396 * @cpFloat cpAreaForPoly(const int count, const cpVect *verts, cpFloat radius)@ - Signed area of a polygon shape. Returns a negative number for polygons with a clockwise winding.
397
398
399 <%= h 2, "Coordinate Conversion Functions:", "CoordinateConversion" %>
400
401 Many things are defined in coordinates local to a body meaning that the (0,0) is at the center of gravity of the body and the axis rotate along with the body.
402
403 * @cpVect cpBodyLocalToWorld(const cpBody *body, const cpVect v)@ - Convert from body local coordinates to world space coordinates.
404 * @cpVect cpBodyWorldToLocal(const cpBody *body, const cpVect v)@ - Convert from world space coordinates to body local coordinates.
405
406
407 <%= h 2, "Velocity Conversion Functions:", "VelocityConversion" %>
408
409 It's often useful to know the absolute velocity of a point on the surface of a body since the angular velocity affects everything except the center of gravity.
410
411 * @cpVect cpBodyVelocityAtWorldPoint(const cpBody *body, const point)@ - Get the absolute velocity of the rigid body at the given world point @point@.
412 * @cpVect cpBodyVelocityAtLocalPoint(const cpBody *body, const point)@ - Get the absolute velocity of the rigid body at the given body local point @point@.
413
414
415 <%= h 2, "Applying Forces and Torques:", "Forces" %>
416
417 People are sometimes confused by the difference between a force and an impulse. An impulse is a very large force applied over a very short period of time. Some examples are a ball hitting a wall or cannon firing. Chipmunk treats impulses as if they occur instantaneously by adding directly to the velocity of an object. Both impulses and forces are affected the mass of an object. Doubling the mass of the object will halve the effect.
418
419 * @void cpBodyApplyForceAtWorldPoint(cpBody *body, const cpVect force, const cpVect point)@ - Add the force @force@ to @body@ as if applied from the world point @point@.
420 * @void cpBodyApplyForceAtLocalPoint(cpBody *body, const cpVect force, const cpVect point)@ - Add the local force @force@ to @body@ as if applied from the body local point @point@.
421 * @void cpBodyApplyImpulseAtWorldPoint(cpBody *body, const cpVect impulse, const cpVect point)@ - Add the impulse @impulse@ to @body@ as if applied from the world point @point@.
422 * @void cpBodyApplyImpulseAtLocalPoint(cpBody *body, const cpVect impulse, const cpVect point)@ - Add the local impulse @impulse@ to @body@ as if applied from the body local point @point@.
423
424
425 <%= h 2, "Sleeping Functions:", "Sleeping" %>
426
427 Chipmunk supports a sleeping feature which improves performance by not simulating groups of objects that aren't moving. Read more about it in the "cpSpace section":#cpSpace-Sleeping.
428
429 * @cpBool cpBodyIsSleeping(const cpBody *body)@ - Returns true if @body@ is sleeping.
430 * @void cpBodyActivate(cpBody *body)@ - Reset the idle timer on a body. If it was sleeping, wake it and any other bodies it was touching.
431 * @void cpBodySleep(cpBody *body)@ - Forces a body to fall asleep immediately even if it's in midair. Cannot be called from a callback.
432 * @void cpBodyActivateStatic(cpBody *body, cpShape *filter)@ - Similar in function to @cpBodyActivate()@. Activates all bodies touching @body@. If @filter@ is not @NULL@, then only bodies touching through @filter@ will be awoken.
433
434 <pre><code>void cpBodySleepWithGroup(cpBody *body, cpBody *group)</code></pre>
435
436 p(expl). When objects in Chipmunk sleep, they sleep as a group of all objects that are touching or jointed together. When an object is woken up, all of the objects in its group are woken up. @cpBodySleepWithGroup()@ allows you group sleeping objects together. It acts identically to @cpBodySleep()@ if you pass @NULL@ as @group@ by starting a new group. If you pass a sleeping body for @group@, @body@ will be awoken when @group@ is awoken. You can use this to initialize levels and start stacks of objects in a pre-sleeping state.
437
438 <%= pop_open_example "Sleeping" %>
439
440 <%= h 2, "Iterators", "Iterators" %>
441
442 <pre><code>typedef void (*cpBodyShapeIteratorFunc)(cpBody *body, cpShape *shape, void *data)
443 void cpBodyEachShape(cpBody *body, cpBodyShapeIteratorFunc func, void *data)</code></pre>
444
445 p(expl). Call @func@ once for each shape that is attached to @body@ and added to a space. @data@ is passed along as a context value. It is safe to remove shapes using these callbacks.
446
447 <pre><code>typedef void (*cpBodyConstraintIteratorFunc)(cpBody *body, cpConstraint *constraint, void *data)
448 void cpBodyEachConstraint(cpBody *body, cpBodyConstraintIteratorFunc func, void *data)</code></pre>
449
450 p(expl). Call @func@ once for each constraint that is attached to @body@ and added to a space. @data@ is passed along as a context value. It is safe to remove constraints using thes callbacks.
451
452 <pre><code>typedef void (*cpBodyArbiterIteratorFunc)(cpBody *body, cpArbiter *arbiter, void *data)
453 void cpBodyEachArbiter(cpBody *body, cpBodyArbiterIteratorFunc func, void *data)</code></pre>
454
455 p(expl). This one is more interesting. Calls @func@ once for each collision pair that @body@ is involved in. Calling @cpArbiterGet[Bodies|Shapes]()@ or @CP_ARBITER_GET_[BODIES|SHAPES]()@ will return the body or shape for @body@ as the first argument. You can use this to check all sorts of collision information for a body like if it's touching the ground, another particular object, how much collision force is being applied to an object, etc. Sensor shapes and arbiters that have been rejected by a collision handler callback or @cpArbiterIgnore()@ are not tracked by the contact graph.
456
457 *Note:* If your compiler supports blocks (such as Clang), there are an alternate set of functions you can call. @cpBodyEachShape_b()@, etc. See @chipmunk.h@ for more information.
458
459 <%= pop_open_example "Crushing" %>
460
461
462 <%= h 2, "Integration Callbacks:", "Integration Callbacks" %>
463
464 This section is a stub. For now you can look at the Planet demo for an example of how to use integration callbacks to implement planetary gravity.
465
466 <!-- TODO document and examples -->
467
468
469 <%= h 1, "Chipmunk Collision Shapes: @cpShape@", "cpShape" %>
470
471 There are currently 3 collision shape types:
472
473 * *Circles*: Fastest and simplest collision shape.
474 * *Line segments*: Meant mainly as a static shape. Can be beveled in order to give them a thickness.
475 * *Convex polygons*: Slowest, but most flexible collision shape.
476
477 You can add as many shapes to a body as you wish. That is why the two types are separate. Combining multiple shapes gives you the flexibility to make any object you want as well as providing different areas of the same object with different friction, elasticity or callback values.
478
479 When creating different types of shapes, you will always be given a @cpShape*@ pointer back. This is because Chipmunk shapes are meant to be opaque types. Think of the specific collision types such as @cpCircleShape@, @cpSegmentShape@ and @cpPolyShape@ as private subclasses of @cpShape@. You can still read some properties from them using the getter functions, but you are not intended to cast @cpShape@ pointers to their specific types.
480
481 <%= h 2, "Properties:", "Properties" %>
482
483 Chipmunk provides getter/setter functions for a number of properties on collision shapes. Setting most properties will automatically wake the attached rigid body, if it's sleeping. You can also set some of the fields directly on the cpShape struct if you wish. They are documented in the headers.
484
485 <pre><code>cpBody * cpShapeGetBody(const cpShape *shape)
486 void cpShapeSetBody(cpShape *shape, cpBody *body)</code></pre>
487
488 p(expl). The rigid body the shape is attached to. Can only be set when the shape is not added to a space.
489
490 <pre><code>cpBB cpShapeGetBB(const cpShape *shape)</code></pre>
491
492 p(expl). The bounding box of the shape. Only guaranteed to be valid after @cpShapeCacheBB()@ or @cpSpaceStep()@ is called. Moving a body that a shape is connected to does not update its bounding box. For shapes used for queries that aren't attached to bodies, you can also use @cpShapeUpdate()@.
493
494 <pre><code>cpBool cpShapeGetSensor(const cpShape *shape)
495 void cpShapeSetSensor(cpShape *shape, cpBool value)</code></pre>
496
497 p(expl). A boolean value if this shape is a sensor or not. Sensors only call collision callbacks, and never generate real collisions.
498
499 <pre><code>cpFloat cpShapeGetElasticity(const cpShape *shape)
500 void cpShapeSetElasticity(cpShape *shape, cpFloat value)</code></pre>
501
502 p(expl). Elasticity of the shape. A value of 0.0 gives no bounce, while a value of 1.0 will give a "perfect" bounce. However due to inaccuracies in the simulation using 1.0 or greater is not recommended however. The elasticity for a collision is found by multiplying the elasticity of the individual shapes together.
503
504 <pre><code>cpFloat cpShapeGetFriction(const cpShape *shape)
505 void cpShapeSetFriction(cpShape *shape, cpFloat value)</code></pre>
506
507 p(expl). Friction coefficient. Chipmunk uses the Coulomb friction model, a value of 0.0 is frictionless. The friction for a collision is found by multiplying the friction of the individual shapes together. "Tables of friction coefficients":http://www.roymech.co.uk/Useful_Tables/Tribology/co_of_frict.htm.
508
509 <pre><code>cpVect cpShapeGetSurfaceVelocity(const cpShape *shape)
510 void cpShapeSetSurfaceVelocity(cpShape *shape, cpVect value)</code></pre>
511
512 p(expl). 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 resolving the collision.
513
514 <pre><code>cpCollisionType cpShapeGetCollisionType(const cpShape *shape)
515 void cpShapeSetCollisionType(cpShape *shape, cpCollisionType value)</code></pre>
516
517 p(expl). You can assign types to Chipmunk collision shapes that trigger callbacks when objects of certain types touch. See the "callbacks section":#Callbacks-Handlers for more information.
518
519 <pre><code>cpShapeFilter cpShapeGetFilter(const cpShape *shape)
520 void cpShapeSetFilter(cpShape *shape, cpShapeFilter filter)</code></pre>
521
522 p(expl). Set the collision filter for this shape. See "Filtering Collisions":#Filtering for more information.
523
524 <pre><code>cpSpace* cpShapeGetSpace(const cpShape *shape)</code></pre>
525
526 p(expl). Get the @cpSpace@ that @shape@ has been added to.
527
528 <pre><code>cpDataPointer cpShapeGetUserData(const cpShape *shape)
529 void cpShapeSetUserData(cpShape *shape, cpDataPointer value)</code></pre>
530
531 p(expl). A user definable data pointer. If you set this to point at the game object the shapes is for, then you can access your game object from Chipmunk callbacks.
532
533
534 <%= h 2, "Fast Collision Filtering using cpShapeFilter:", "Filtering" %>
535
536 Chipmunk has two primary means of ignoring collisions: groups and category masks.
537
538 *Groups* are used to ignore collisions between parts on a complex object. A ragdoll is a good example. When jointing an arm onto the torso, you'll want them to allow them to overlap. Groups allow you to do exactly that. Shapes that have the same group don't generate collisions. So by placing all of the shapes in a ragdoll in the same group, you'll prevent it from colliding against other parts of itself.
539
540 *Category masks* allow you to mark which categories an object belongs to and which categories it collidies with.
541
542 For example, a game has four collision categories: player (0), enemy (1), player bullet (2), and enemy bullet (3). Neither players nor enemies should not collide with their own bullets, and bullets should not collide with other bullets. However, players collide with enemy bullets, and enemies collide with player bullets.
543
544 | Object | Object Category | Category Mask |
545 | "Player" | 1 | 4, 5 |
546 | "Enemy" | 2 | 2, 3, 5 |
547 | "Player Bullet" | 3 | 1, 5 |
548 | "Enemy Bullet" | 4 | 2, 5 |
549 | "Walls" | 5 | 1, 2, 3, 4 |
550
551 Note that everything in this example collides with walls. Additionally, the enemies collide with eachother.
552
553 By default, objects exist in every category and collide with every category.
554
555 Objects can fall into multiple categories. For instance, you might have a category for a red team, and have a red player bullet. In the above example, each object only has one category. If you make use of multiple categories on an object, you may also wish to consider replacing the @cpShapeFilter@ struct and the @cpShapeFilterReject()@ function in @chipmunk_private.h@ to customize it to better suit your game's needs.
556
557 The default type of @categories@ and @mask@ in @cpShapeFilter@ is @unsigned int@ which has a resolution of 32 bits on most systems. You can redefine @cpBitmask@ in @chipmunk_types.h@ if you need more bits to work with.
558
559 There is one last way of filtering collisions using collision handlers. See the "section on callbacks":#Callbacks for more information. Collision handlers can be more flexible, but can be slower. Fast collision filtering rejects collisions before running the expensive collision detection code, so using groups or category masks is preferred.
560
561 <%= h 2, "Memory Management Functions:", "Memory" %>
562
563 <pre><code>void cpShapeDestroy(cpShape *shape)
564 void cpShapeFree(cpShape *shape)</code></pre>
565
566 p(expl). @Destroy@ and @Free@ functions are shared by all shape types. Allocation and initialization functions are specific to each shape type. See below.
567
568 <%= h 2, "Misc Functions:", "Misc" %>
569
570 * @cpBB cpShapeCacheBB(cpShape *shape)@ - Synchronizes @shape@ with the body its attached to.
571 * @cpBB cpShapeUpdate(cpShape *shape, cpVect pos, cpVect rot)@ - Sets the position and rotation of the shape to
572
573 <%= h 2, "Working With Circle Shapes:", "Circles" %>
574
575 <pre><code>cpCircleShape *cpCircleShapeAlloc(void)
576 cpCircleShape *cpCircleShapeInit(cpCircleShape *circle, cpBody *body, cpFloat radius, cpVect offset)
577 cpShape *cpCircleShapeNew(cpBody *body, cpFloat radius, cpVect offset)</code></pre>
578
579 p(expl). @body@ is the body to attach the circle to, @offset@ is the offset from the body's center of gravity in body local coordinates.
580
581 <pre><code>cpVect cpCircleShapeGetOffset(cpShape *circleShape)
582 cpFloat cpCircleShapeGetRadius(cpShape *circleShape)</code></pre>
583
584 p(expl). Getters for circle shape properties. Passing as non-circle shape will throw an assertion.
585
586 <%= h 2, "Working With Segment Shapes:", "Segments" %>
587
588 <pre><code>cpSegmentShape* cpSegmentShapeAlloc(void)
589 cpSegmentShape* cpSegmentShapeInit(cpSegmentShape *seg, cpBody *body, cpVect a, cpVect b, cpFloat radius)
590 cpShape* cpSegmentShapeNew(cpBody *body, cpVect a, cpVect b, cpFloat radius)</code></pre>
591
592 p(expl). @body@ is the body to attach the segment to, @a@ and @b@ are the endpoints, and @radius@ is the thickness of the segment.
593
594 <pre><code>cpVect cpSegmentShapeGetA(cpShape *shape)
595 cpVect cpSegmentShapeGetB(cpShape *shape)
596 cpVect cpSegmentShapeGetNormal(cpShape *shape)
597 cpFloat cpSegmentShapeGetRadius(cpShape *shape)</code></pre>
598
599 p(expl). Getters for segment shape properties. Passing a non-segment shape will throw an assertion.
600
601 <pre><code>void cpSegmentShapeSetNeighbors(cpShape *shape, cpVect prev, cpVect next)</code></pre>
602
603 p(expl). When you have a number of segment shapes that are all joined together, things can still collide with the "cracks" between the segments. By setting the neighbor segment endpoints you can tell Chipmunk to avoid colliding with the inner parts of the crack.
604
605 <%= h 2, "Working With Polygon Shapes:", "Polys" %>
606
607 <pre><code>cpPolyShape *cpPolyShapeAlloc(void)
608
609 cpPolyShape *cpPolyShapeInit(cpPolyShape *poly, cpBody *body, int count, const cpVect *verts, cpTransform transform, cpFloat radius)
610 cpShape *cpPolyShapeNew(cpBody *body, int numVerts, cpVect *verts, cpTransform transform, cpFloat radius)</code></pre>
611 p(expl). @body@ is the body to attach the poly to, @verts@ is an array of @cpVect@ structs, @transform@ will be applied to every vertex. A convex hull will be calculated from the vertexes automatically.
612 The polygon shape will be created with a @radius@, increasing the size of the shape.
613
614
615 <pre><code>cpPolyShape* cpPolyShapeInitRaw(cpPolyShape *poly, cpBody *body, int count, const cpVect *verts, cpFloat radius)
616 cpShape* cpPolyShapeNewRaw(cpBody *body, int count, const cpVect *verts, cpFloat radius)</code></pre>
617
618 Alternate constructors for poly shapes. This version does not apply a transform nor does it create a convex hull. Verticies _must_ be provided with a counter-clockwise winding.
619
620 <pre><code>int cpPolyShapeGetNumVerts(cpShape *shape)
621 cpVect cpPolyShapeGetVert(cpShape *shape, int index)
622 cpFloat cpPolyShapeGetRadius()</code></pre>
623
624 p(expl). Getters for poly shape properties. Passing a non-poly shape or an index that does not exist will throw an assertion.
625
626 <%= h 3, "Boxes:", "Boxes" %>
627
628 Because boxes are so common in physics games, Chipmunk provides shortcuts to create box shaped polygons. The boxes will always be centered at the center of gravity of the body you are attaching them to. Adding a small radius will bevel the corners and can significantly reduce problems where the box gets stuck on seams in your geometry. If you want to create an off-center box, you will need to use @cpPolyShapeNew()@ or @cpPolyShapeInit()@.
629
630 <pre><code>cpPolyShape *cpBoxShapeInit(cpPolyShape *poly, cpBody *body, cpFloat width, cpFloat height, cpFloat radius)
631 cpPolyShape *cpBoxShapeInit2(cpPolyShape *poly, cpBody *body, cpBB box, cpFloat radius)
632
633 cpShape *cpBoxShapeNew(cpBody *body, cpFloat width, cpFloat height, cpFloat radius)
634 cpShape *cpBoxShapeNew2(cpBody *body, cpBB box, cpFloat radius)</code></pre>
635
636 <%= h 3, "Poly Shape Helper Functions:", "PolyHelpers" %>
637
638 * @cpVect cpCentroidForPoly(const int count, const cpVect *verts)@ - Calculate the centroid for a polygon.
639
640 <%= h 3, "Convex Hull Helper Functions:", "ConvexHelpers" %>
641
642 <pre><code>int cpConvexHull(int count, cpVect *verts, cpVect *result, int *first, cpFloat tol)</code></pre>
643
644 p(expl). Calculate the convex hull of a given set of points. Returns the count of points in the hull. @result@ must be a pointer to a @cpVect@ array with at least @count@ elements. If @result@ is @NULL@, then @verts@ array wil be reduced instead. @first@ is an optional pointer to an integer to store where the first vertex in the hull came from (i.e. @verts[first] == result[0]@) @tol@ is the allowed amount to shrink the hull when simplifying it. A tolerance of 0.0 creates an exact hull.
645
646 <pre><code>#define CP_CONVEX_HULL(inputCount, inputVerts, outputCount_varName, outputVerts_varName)</code></pre>
647
648 p(expl). Convenience macro for using @cpConvexHull()@. Creates an array on the stack using @alloca()@ and then calls @cpConvexHull()@. Because the output array is created on the stack it doesn't need to be freed.
649
650 <%= pop_open_example "cpConvexHull" %>
651
652
653 <%= h 2, "Modifying cpShapes:", "Modifying" %>
654
655 The short answer is that you can't because the changes would be only picked up as a change to the position of the shape's surface, but not its velocity. The long answer is that you can using the "unsafe" API as long as you realize that doing so will result in unrealistic physical behavior. These extra functions are defined in a separate header @chipmunk_unsafe.h@.
656
657 <%= h 2, "Notes:", "Notes" %>
658
659 * You can attach multiple collision shapes to a rigid body. This should allow you to create almost any shape you could possibly need.
660 * Shapes attached to the same rigid body will never generate collisions. You don't have to worry about overlap when attaching multiple shapes to a rigid body.
661 * Make sure you add both the body and its collision shapes to a space.
662
663
664 <%= h 1, "Chipmunk Spaces: @cpSpace@", "cpSpace" %>
665
666 Spaces in Chipmunk are the basic unit of simulation. You add rigid bodies, shapes, and constraints to the space and then step them all forward through time together.
667
668 <%= h 2, "What Are Iterations, and Why Should I Care?", "Iterations" %>
669
670 Chipmunk uses an iterative solver to figure out the forces between objects in the space. What this means is that it builds a big list of all of the collisions, joints, and other constraints between the bodies and makes several passes over the list considering each one individually. The number of passes it makes is the iteration count, and each iteration makes the solution more accurate. If you use too many iterations, the physics should look nice and solid, but may use up too much CPU time. If you use too few iterations, the simulation may seem mushy or bouncy when the objects should be solid. Setting the number of iterations lets you balance between CPU usage and the accuracy of the physics. Chipmunk's default of 10 iterations is sufficient for most simple games.
671
672 <%= h 2, "Sleeping", "Sleeping" %>
673
674 Spaces can disable entire groups of objects that have stopped moving to save CPU time and battery life. In order to use this feature you must do two things. You must enable sleeping explicitly by choosing a time threshold value for @cpSpace.sleepTimeThreshold@. This threshold is the amount of time something must be idle before it falls asleep. @cpSpace.idleSpeedThreshold@ defines what is considered idle. If you do not set @cpSpace.idleSpeedThreshold@ explicitly, a value will be chosen automatically based on the current amount of gravity. Be mindful that objects cannot fall asleep if they are touching or jointed to a kinematic body.
675
676 <%= h 2, "Properties:", "Properties" %>
677
678 <pre><code>int cpSpaceGetIterations(const cpSpace *space)
679 void cpSpaceSetIterations(cpSpace *space, int value)</code></pre>
680
681 p(expl). Iterations allow you to control the accuracy of the solver. Defaults to 10. See "above":#cpSpace-Iterations for more information.
682
683 <pre><code>cpVect cpSpaceGetGravity(const cpSpace *space)
684 void cpSpaceSetGravity(cpSpace *space, cpVect value)</code></pre>
685
686 p(expl). Global gravity applied to the space. Defaults to @cpvzero@. Can be overridden on a per body basis by writing custom integration functions. Changing the gravity will activate all sleeping bodies in the space.
687
688 <pre><code>cpFloat cpSpaceGetDamping(const cpSpace *space)
689 void cpSpaceSetDamping(cpSpace *space, cpFloat value)</code></pre>
690
691 p(expl). Amount of simple damping to apply to the space. A value of 0.9 means that each body will lose 10% of its velocity per second. Defaults to 1. Like @gravity@, it can be overridden on a per body basis.
692
693 <pre><code>cpFloat cpSpaceGetIdleSpeedThreshold(const cpSpace *space)
694 void cpSpaceSetIdleSpeedThreshold(cpSpace *space, cpFloat value)</code></pre>
695
696 p(expl). Speed threshold for a body to be considered idle. The default value of 0 means the space estimates a good threshold based on gravity.
697
698 <pre><code>cpFloat cpSpaceGetSleepTimeThreshold(const cpSpace *space)
699 void cpSpaceSetSleepTimeThreshold(cpSpace *space, cpFloat value)</code></pre>
700
701 p(expl). Time a group of bodies must remain idle in order to fall asleep. The default value of @INFINITY@ disables the sleeping feature.
702
703 <pre><code>cpFloat cpSpaceGetCollisionSlop(const cpSpace *space)
704 void cpSpaceSetCollisionSlop(cpSpace *space, cpFloat value)</code></pre>
705
706 p(expl). Amount of overlap between shapes that is allowed. To improve stability, set this as high as you can without noticable overlapping. It defaults to 0.1.
707
708 <pre><code>cpFloat cpSpaceGetCollisionBias(const cpSpace *space)
709 void cpSpaceSetCollisionBias(cpSpace *space, cpFloat value)</code></pre>
710
711 p(expl). Chipmunk allows fast moving objects to overlap, then fixes the overlap over time. Overlapping objects are unavoidable even if swept collisions are supported, and this is an efficient and stable way to deal with overlapping objects. The bias value controls what percentage of overlap remains unfixed after a second and defaults to ~0.2%. Valid values are in the range from 0 to 1, but using 0 is not recommended for stability reasons. The default value is calculated as @cpfpow(1.0f - 0.1f, 60.0f)@ meaning that Chipmunk attempts to correct 10% of error ever 1/60th of a second. *Note:* Very very few games will need to change this value.
712
713 <pre><code>cpTimestamp cpSpaceGetCollisionPersistence(const cpSpace *space)
714 void cpSpaceSetCollisionPersistence(cpSpace *space, cpTimestamp value)</code></pre>
715
716 p(expl). The number of frames the space keeps collision solutions around for. Helps prevent jittering contacts from getting worse. This defaults to 3 and very very _very_ few games will need to change this value.
717
718 <pre><code>cpFloat cpSpaceGetCurrentTimeStep(const cpSpace *space)</code></pre>
719
720 p(expl). Retrieves the current (if you are in a callback from @cpSpaceStep()@) or most recent (outside of a @cpSpaceStep()@ call) timestep.
721
722 <pre><code>cpFloat cpSpaceIsLocked(const cpSpace *space)</code></pre>
723
724 p(expl). Returns true when you cannot add/remove objects from the space. In particular, spaces are locked when in a collision callback. Instead, run your code in a post-step callback instead.
725
726 <pre><code>cpDataPointer cpSpaceGetUserData(const cpSpace *space)
727 void cpSpaceSetUserData(cpSpace *space, cpDataPointer value)</code></pre>
728
729 p(expl). A user definable data pointer. It is often useful to point this at the gamestate object or scene management object that owns the space.
730
731 <pre><code>cpBody * cpSpaceGetStaticBody(const cpSpace *space)</code></pre>
732
733 p(expl). A dedicated static body for the space. You don't have to use it, but because its memory is managed automatically with the space its very convenient. You can set its user data pointer to something helpful if you want for callbacks.
734
735
736 <%= h 2, "Memory Management Functions:", "Memory" %>
737
738 <pre><code>cpSpace* cpSpaceAlloc(void)
739 cpSpace* cpSpaceInit(cpSpace *space)
740 cpSpace* cpSpaceNew()
741
742 void cpSpaceDestroy(cpSpace *space)
743 void cpSpaceFree(cpSpace *space)</code></pre>
744
745 p(expl). More standard Chipmunk memory functions.
746
747 <%= h 2, "Operations:", "Operations" %>
748
749 <pre><code>cpShape *cpSpaceAddShape(cpSpace *space, cpShape *shape)
750 cpBody *cpSpaceAddBody(cpSpace *space, cpBody *body)
751 cpConstraint *cpSpaceAddConstraint(cpSpace *space, cpConstraint *constraint)
752
753 void cpSpaceRemoveShape(cpSpace *space, cpShape *shape)
754 void cpSpaceRemoveBody(cpSpace *space, cpBody *body)
755 void cpSpaceRemoveConstraint(cpSpace *space, cpConstraint *constraint)
756
757 cpBool cpSpaceContainsShape(cpSpace *space, cpShape *shape)
758 cpBool cpSpaceContainsBody(cpSpace *space, cpBody *body)
759 cpBool cpSpaceContainsConstraint(cpSpace *space, cpConstraint *constraint)</code></pre>
760
761 p(expl). These functions add and remove shapes, bodies and constraints from @space@. The add/remove functions cannot be called from within a callback other than a @postStep()@ callback _(which is different than a postSolve() callback!)_. Attempting to add or remove objects from the space while @cpSpaceStep()@ is still executing will throw an assertion. See the "callbacks section":#Callbacks for more information. The add functions return the thing being added so that you can create and add something in one line. Be careful not to free bodies before removing shapes and constraints attached to them or you will cause crashes.. The contains functions allow you to check if an object has been added to the space or not.
762
763 <%= h 2, "Spatial Indexing:", "SpatialIndexing" %>
764
765 Occasionally, you might want to update the collision detection data for a shape. If you move a static shape or a static body you *must* do this to let Chipmunk know it needs to have its collision detection data updated. You may also want to manually update the collision data for normal shapes if you move them and still want to perform queries against them before the next call to @cpSpaceStep()@.
766
767 * @void cpSpaceReindexShape(cpSpace *space, cpShape *shape)@ - Reindex a specific shape.
768 * @void cpSpaceReindexShapesForBody(cpSpace *space, cpBody *body)@ - Reindex all the shapes for a certain body.
769 * @void cpSpaceReindexStatic(cpSpace *space)@ - Reindex all static shapes. Generally updating only the shapes that changed is faster.
770
771 <%= h 2, "Iterators:", "Iterators" %>
772
773 <pre><code>typedef void (*cpSpaceBodyIteratorFunc)(cpBody *body, void *data)
774 void cpSpaceEachBody(cpSpace *space, cpSpaceBodyIteratorFunc func, void *data)</code></pre>
775
776 p(expl). Call @func@ for each body in the space also passing along your data pointer. Sleeping bodies are included, but static and kinematic bodies are not as they aren't added to the space.
777
778 <%= pop_open_example "cpSpaceEachBody" %>
779
780 <pre><code>typedef void (*cpSpaceShapeIteratorFunc)(cpShape *shape, void *data)
781 void cpSpaceEachShape(cpSpace *space, cpSpaceShapeIteratorFunc func, void *data)</code></pre>
782
783 p(expl). Call @func@ for each shape in the space also passing along your data pointer. Sleeping and static shapes are included.
784
785 <pre><code>typedef void (*cpSpaceConstraintIteratorFunc)(cpConstraint *constraint, void *data)
786 void cpSpaceEachConstraint(cpSpace *space, cpSpaceConstraintIteratorFunc func, void *data)</code></pre>
787
788 p(expl). Call @func@ for each constraint in the space also passing along your data pointer.
789
790 *Note:* If your compiler supports blocks (such as Clang), there are an alternate set of functions you can call. @cpSpaceEachBody_b()@, etc. See @chipmunk.h@ for more information.
791
792 <%= h 2, "Simulating the Space:", "Simulating" %>
793
794 <pre><code>void cpSpaceStep(cpSpace *space, cpFloat dt)</code></pre>
795
796 p(expl). Update the space for the given time step. Using a fixed time step is _highly_ recommended. Doing so can greatly increase the quality of the simulation. The easiest way to do constant timesteps is to simple step forward by 1/60th of a second (or whatever your target framerate is) for each frame regardless of how long it took to render. This works fine for many games, but a better way to do it is to separate your physics timestep and rendering. "This":http://gafferongames.com/game-physics/fix-your-timestep/ is a good article on how to do that.
797
798
799 <%= h 2, "Enabling and Tuning the Spatial Hash:", "SpatialHash" %>
800
801 Chipmunk officially supports two spatial indexes. The default is an axis-aligned bounding box tree inspired by the one used in the Bullet Physics library, but caching of overlapping leaves was added to give it very good temporal coherence. The tree requires no tuning, and most games will find that they get the best performance using from the tree. The other available spatial index type available is a spatial hash, which can be much faster when you have a very large number (1000s) of objects that are all the same size. For smaller numbers of objects, or objects that vary a lot in size, the spatial hash is usually much slower. It also requires tuning (usually through experimentation) to get the best possible performance.
802
803 <pre><code>void cpSpaceUseSpatialHash(cpSpace *space, cpFloat dim, int count)</code></pre>
804
805 p(expl). Switch the space to use a spatial hash instead of the bounding box tree.
806
807 The spatial hash data is fairly size sensitive. @dim@ is the size of the hash cells. Setting @dim@ to the average collision shape size is likely to give the best performance. Setting @dim@ too small will cause the shape to be inserted into many cells, setting it too low will cause too many objects into the same hash slot.
808
809 @count@ is the _suggested_ minimum number of cells in the hash table. If there are too few cells, the spatial hash will return many false positives. Too many cells will be hard on the cache and waste memory. the Setting @count@ to ~10x the number of objects in the space is probably a good starting point. Tune from there if necessary.
810
811 Using the spatial has visualization in the demo program you can see what I mean. The grey squares represent cells in the spatial hash. The darker the cell, the more objects have been mapped into that cell. A good @dim@ size is when your objects fit nicely into the grid:
812
813 !images/hash_just_right.png!
814
815 Notice the light grey meaning that each cell doesn't have too many objects mapped onto it.
816
817 When you use too small a size, Chipmunk has to insert each object into a lot of cells. This can get expensive.
818
819 !images/hash_too_small.png!
820
821 Notice that the grey cells are very small compared to the collision shapes.
822
823 When you use too big of a size, a lot of shapes will fit into each cell. Each shape has to be checked against every other shape in the cell, so this makes for a lot of unnecessary collision checks.
824
825 !images/hash_too_big.png!
826
827 Notice the dark grey cells meaning that many objects are mapped onto them.
828
829
830 Chipmunk also has an experimental single axis sort and sweep implementation. It can be very efficient on mobile games if your world is very long and flat like a racing game. See the code for @cpSpaceUseSpatialHash()@ if you want to try enabling it.
831
832
833 <%= h 2, "Notes:", "Notes" %>
834
835 * 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.
836 * Using more iterations or smaller time steps will increase the physics quality, but also increase the CPU usage.
837 * Because static shapes are only rehashed when you request it, TODO: cpSpaceHashResize
838
839
840 <%= h 1, "Chipmunk Constraints: @cpConstraint@", "cpConstraint" %>
841
842 A constraint is something that describes how two bodies interact with each other. (how they constrain each other) Constraints can be simple joints that allow bodies to pivot around each other like the bones in your body, or they can be more abstract like the gear joint or motors.
843
844 <%= h 2, "What constraints are and what they are not:", "WhatAreConstraints" %>
845
846 Constraints in Chipmunk are all velocity based constraints. This means that they act primarily by synchronizing the velocity of two bodies. A pivot joint holds two anchor points on two separate bodies together by defining equations that say that the velocity of the anchor points must be the same and calculating impulses to apply to the bodies to try and keep it that way. A constraint takes a velocity as it's primary input and produces a velocity change as its output. Some constraints, (joints in particular) apply velocity changes to correct differences in positions. More about this in the next section.
847
848 A spring connected between two bodies is not a constraint. It's very constraint-like as it creates forces that affect the velocities of the two bodies, but a spring takes distances as input and produces forces as its output. If a spring is not a constraint, then why do I have two varieties of spring constraints you ask? The reason is because they are _damped springs_. The damping associated with the spring is a true constraint that creates velocity changes based on the relative velocities of the two bodies it links. As it is convenient to put a damper and a spring together most of the time, I figured I might as well just apply the spring force as part of the constraint instead of having a damper constraint and having the user calculate and apply their own spring forces separately.
849
850 <%= h 2, "Properties:", "Properties" %>
851
852 <pre><code>cpBody * cpConstraintGetA(const cpConstraint *constraint)
853 cpBody * cpConstraintGetB(const cpConstraint *constraint)</code></pre>
854
855 p(expl). Getters for the two bodies the constraint is attached to.
856
857 <pre><code>cpFloat cpConstraintGetMaxForce(const cpConstraint *constraint)
858 void cpConstraintSetMaxForce(cpConstraint *constraint, cpFloat value)</code></pre>
859
860 p(expl). The maximum force that the constraint can use to act on the two bodies. Defaults to INFINITY.
861
862 <pre><code>cpFloat cpConstraintGetErrorBias(const cpConstraint *constraint)
863 void cpConstraintSetErrorBias(cpConstraint *constraint, cpFloat value)</code></pre>
864
865 p(expl). The percentage of joint error that remains unfixed after a second. This works exactly the same as the collision bias property of a space, but applies to fixing error (stretching) of joints instead of overlapping collisions.
866
867 <pre><code>cpFloat cpConstraintGetMaxBias(const cpConstraint *constraint)
868 void cpConstraintSetMaxBias(cpConstraint *constraint, cpFloat value)</code></pre>
869
870 p(expl). The maximum speed at which the constraint can apply error correction. Defaults to INFINITY.
871
872 <pre><code>cpSpace* cpConstraintGetSpace(const cpConstraint *constraint)</code></pre>
873
874 p(expl). Get the @cpSpace@ that @constraint@ has been added to.
875
876 <pre><code>cpBool cpConstraintGetCollideBodies(const cpConstraint *constraint)
877 void cpConstraintSetCollideBodies(cpConstraint *constraint, cpBool collideBodies)</code></pre>
878
879 p(expl). Constraints can be used for filtering collisions too. When two bodies collide, Chipmunk ignores the collisions if this property is set to @cpFalse@ on any constraint that connects the two bodies. Defaults to @cpTrue@. This can be used to create a chain that self collides, but adjacent links in the chain do not collide.
880
881 <pre><code>cpDataPointer cpConstraintGetUserData(const cpConstraint *constraint)
882 void cpConstraintSetUserData(cpConstraint *constraint, cpDataPointer value)</code></pre>
883
884 p(expl). User data pointer. Use this pointer to get a reference to the game object that owns this constraint from callbacks.
885
886 <pre><code>cpFloat cpConstraintGetImpulse(cpConstraint *constraint)</code></pre>
887
888 p(expl). The most recent impulse that @constraint@ applied. To convert this to a force, divide by the timestep passed to @cpSpaceStep()@. You can use this to implement breakable joints to check if the force they attempted to apply exceeded a certain threshold.
889
890 <%= pop_open_example "BreakableJoint" %>
891
892 To access properties of specific joint types, use the getter and setter functions provided (ex: @cpPinJointGetanchorA()@). See the lists of properties for more information.
893
894 <%= h 2, "Error correction by Feedback:", "ErrorCorrection" %>
895
896 Joints in Chipmunk are not perfect. A pin joint can't maintain the exact correct distance between its anchor points, nor can a pivot joint hold its anchor points completely together. Instead, they are designed to deal with this by correcting themselves over time. Since Chipmunk 5, you have a fair amount of extra control over how joints correct themselves and can even use this ability to create physical effects that allow you to use joints in unique ways:
897
898 * Servo motors - Ex: open/close doors or rotate things without going over a maximum force.
899 * Winches - Pull one object towards another at a constant speed without going over a maximum force.
900 * Mouse manipulation - Interact with objects smoothly given coarse/shaky mouse input.
901
902 There are three properties of cpConstraint structs that control the error correction, @maxForce@, @maxBias@, and @biasCoef@. @maxForce@ is pretty self explanatory, a joint or constraint will not be able to use more than this amount of force in order to function. If it needs more force to be able to hold itself together, it will fall apart. @maxBias@ is the maximum speed at which error correction can be applied. If you change a property on a joint so that the joint will have to correct itself, it normally does so very quickly. By setting a maxSpeed you can make the joint work like a servo, correcting itself at a constant rate over a longer period of time. Lastly, @biasCoef@ is the percentage of error corrected every step before clamping to a maximum speed. You can use this to make joints correct themselves smoothly instead of at a constant speed, but is probably the least useful of the three properties by far.
903
904 <!-- TODO more examples -->
905
906 <%= pop_open_example "JointRecipies" %>
907
908 <%= h 2, "Constraints and Collision Shapes:", "Shapes" %>
909
910 Neither constraints or collision shapes have any knowledge of the other. When connecting joints to a body the anchor points don't need to be inside of any shapes attached to the body and it often makes sense that they shouldn't. Also, adding a constraint between two bodies doesn't prevent their collision shapes from colliding. In fact, this is the primary reason that the collision group property exists.
911
912 <%= h 2, "Video Tour of Current Joint Types. (Requires connection to YouTube)", "Video" %>
913
914 <object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/ZgJJZTS0aMM&amp;hl=en_US&amp;fs=1?rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/ZgJJZTS0aMM&amp;hl=en_US&amp;fs=1?rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>
915
916 <%= h 2, "Shared Memory Management Functions:", "Memory" %>
917
918 <pre><code>void cpConstraintDestroy(cpConstraint *constraint)
919 void cpConstraintFree(cpConstraint *constraint)</code></pre>
920
921 p(expl). @Destroy@ and @Free@ functions are shared by all joint types. Allocation and initialization functions are specific to each joint type.
922
923 <%= h 1, "Constraint Types:", "ConstraintTypes" %>
924
925 <%= h 2, "Pin Joints:", "cpPinJoint" %>
926
927 <pre><code>cpPinJoint *cpPinJointAlloc(void)
928 cpPinJoint *cpPinJointInit(cpPinJoint *joint, cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB)
929 cpConstraint *cpPinJointNew(cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB)</code></pre>
930
931 p(expl). @a@ and @b@ are the two bodies to connect, and @anchorA@ and @anchorB@ are the anchor points on those bodies. The distance between the two anchor points is measured when the joint is created. If you want to set a specific distance, use the setter function to override it.
932
933 <%= h 3, "Properties", "Properties" %>
934
935 * @cpVect cpPinJointGetanchorA(const cpConstraint *constraint)@
936 * @void cpPinJointSetanchorA(cpConstraint *constraint, cpVect value)@
937 * @cpVect cpPinJointGetanchorB(const cpConstraint *constraint)@
938 * @void cpPinJointSetanchorB(cpConstraint *constraint, cpVect value)@
939 * @cpFloat cpPinJointGetDist(const cpConstraint *constraint)@
940 * @void cpPinJointSetDist(cpConstraint *constraint, cpFloat value)@
941
942 <%= h 2, "Slide Joints:", "cpSlideJoint" %>
943
944 <pre><code>cpSlideJoint *cpSlideJointAlloc(void)
945
946 cpSlideJoint *cpSlideJointInit(
947 cpSlideJoint *joint, cpBody *a, cpBody *b,
948 cpVect anchorA, cpVect anchorB, cpFloat min, cpFloat max
949 )
950
951 cpConstraint *cpSlideJointNew(cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB, cpFloat min, cpFloat max)</code></pre>
952
953 p(expl). @a@ and @b@ are the two bodies to connect, @anchorA@ and @anchorB@ are the anchor points on those bodies, and @min@ and @max@ define the allowed distances of the anchor points.
954
955 <%= h 3, "Properties", "Properties" %>
956
957 * @cpVect cpSlideJointGetanchorA(const cpConstraint *constraint)@
958 * @void cpSlideJointSetanchorA(cpConstraint *constraint, cpVect value)@
959 * @cpVect cpSlideJointGetanchorB(const cpConstraint *constraint)@
960 * @void cpSlideJointSetanchorB(cpConstraint *constraint, cpVect value)@
961 * @cpFloat cpSlideJointGetMin(const cpConstraint *constraint)@
962 * @void cpSlideJointSetMin(cpConstraint *constraint, cpFloat value)@
963 * @cpFloat cpSlideJointGetMax(const cpConstraint *constraint)@
964 * @void cpSlideJointSetMax(cpConstraint *constraint, cpFloat value)@
965
966 <%= h 2, "Pivot Joints:", "cpPivotJoint" %>
967
968 <pre><code>cpPivotJoint *cpPivotJointAlloc(void)
969 cpPivotJoint *cpPivotJointInit(cpPivotJoint *joint, cpBody *a, cpBody *b, cpVect pivot)
970 cpConstraint *cpPivotJointNew(cpBody *a, cpBody *b, cpVect pivot)
971 cpConstraint *cpPivotJointNew2(cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB)</code></pre>
972
973 p(expl). @a@ and @b@ are the two bodies to connect, and @pivot@ 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. Alternatively you can specify the joint based on a pair of anchor points, but make sure you have the bodies in the right place as the joint will fix itself as soon as you start simulating the space.
974
975 <%= h 3, "Properties", "Properties" %>
976
977 * @cpVect cpPivotJointGetanchorA(const cpConstraint *constraint)@
978 * @void cpPivotJointSetanchorA(cpConstraint *constraint, cpVect value)@
979 * @cpVect cpPivotJointGetanchorB(const cpConstraint *constraint)@
980 * @void cpPivotJointSetanchorB(cpConstraint *constraint, cpVect value)@
981
982 <%= h 2, "Groove Joint:", "cpGrooveJoint" %>
983
984 <pre><code>cpGrooveJoint *cpGrooveJointAlloc(void)
985
986 cpGrooveJoint *cpGrooveJointInit(
987 cpGrooveJoint *joint, cpBody *a, cpBody *b,
988 cpVect groove_a, cpVect groove_b, cpVect anchorB
989 )
990
991 cpConstraint *cpGrooveJointNew(cpBody *a, cpBody *b, cpVect groove_a, cpVect groove_b, cpVect anchorB)</code></pre>
992
993 p(expl). The groove goes from @groov_a@ to @groove_b@ on body @a@, and the pivot is attached to @anchorB@ on body @b@. All coordinates are body local.
994
995 <%= h 3, "Properties", "Properties" %>
996
997 * @cpVect cpGrooveJointGetGrooveA(const cpConstraint *constraint)@
998 * @void cpGrooveJointSetGrooveA(cpConstraint *constraint, cpVect value)@
999 * @cpVect cpGrooveJointGetGrooveB(const cpConstraint *constraint)@
1000 * @void cpGrooveJointSetGrooveB(cpConstraint *constraint, cpVect value)@
1001 * @cpVect cpGrooveJointGetanchorB(const cpConstraint *constraint)@
1002 * @void cpGrooveJointSetanchorB(cpConstraint *constraint, cpVect value)@
1003
1004 <%= h 2, "Damped Spring:", "cpDampedSpring" %>
1005
1006 <pre><code>cpDampedSpring *cpDampedSpringAlloc(void)
1007
1008 cpDampedSpring *cpDampedSpringInit(
1009 cpDampedSpring *joint, cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB,
1010 cpFloat restLength, cpFloat stiffness, cpFloat damping
1011 )
1012
1013 cpConstraint *cpDampedSpringNew(
1014 cpBody *a, cpBody *b, cpVect anchorA, cpVect anchorB,
1015 cpFloat restLength, cpFloat stiffness, cpFloat damping
1016 )</code></pre>
1017
1018 p(expl). Defined much like a slide joint. @restLength@ is the distance the spring wants to be, @stiffness@ is the spring constant ("Young's modulus":http://en.wikipedia.org/wiki/Young's_modulus), and @damping@ is how soft to make the damping of the spring.
1019
1020 <%= h 3, "Properties", "Properties" %>
1021
1022 * @cpVect cpDampedSpringGetanchorA(const cpConstraint *constraint)@
1023 * @void cpDampedSpringSetanchorA(cpConstraint *constraint, cpVect value)@
1024 * @cpVect cpDampedSpringGetanchorB(const cpConstraint *constraint)@
1025 * @void cpDampedSpringSetanchorB(cpConstraint *constraint, cpVect value)@
1026 * @cpFloat cpDampedSpringGetRestLength(const cpConstraint *constraint)@
1027 * @void cpDampedSpringSetRestLength(cpConstraint *constraint, cpFloat value)@
1028 * @cpFloat cpDampedSpringGetStiffness(const cpConstraint *constraint)@
1029 * @void cpDampedSpringSetStiffness(cpConstraint *constraint, cpFloat value)@
1030 * @cpFloat cpDampedSpringGetDamping(const cpConstraint *constraint)@
1031 * @void cpDampedSpringSetDamping(cpConstraint *constraint, cpFloat value)@
1032
1033 <%= h 2, "Damped Rotary Spring:", "cpDampedRotarySpring" %>
1034
1035 <pre><code>cpDampedRotarySpring *cpDampedRotarySpringAlloc(void)
1036
1037 cpDampedRotarySpring *cpDampedRotarySpringInit(
1038 cpDampedRotarySpring *joint, cpBody *a, cpBody *b,
1039 cpFloat restAngle, cpFloat stiffness, cpFloat damping
1040 )
1041
1042 cpConstraint *cpDampedRotarySpringNew(cpBody *a, cpBody *b, cpFloat restAngle, cpFloat stiffness, cpFloat damping)</code></pre>
1043
1044 p(expl). Like a damped spring, but works in an angular fashion. @restAngle@ is the relative angle in radians that the bodies want to have, @stiffness@ and @damping@ work basically the same as on a damped spring.
1045
1046 <%= h 3, "Properties", "Properties" %>
1047
1048 * @cpFloat cpDampedRotarySpringGetRestAngle(const cpConstraint *constraint)@
1049 * @void cpDampedRotarySpringSetRestAngle(cpConstraint *constraint, cpFloat value)@
1050 * @cpFloat cpDampedRotarySpringGetStiffness(const cpConstraint *constraint)@
1051 * @void cpDampedRotarySpringSetStiffness(cpConstraint *constraint, cpFloat value)@
1052 * @cpFloat cpDampedRotarySpringGetDamping(const cpConstraint *constraint)@
1053 * @void cpDampedRotarySpringSetDamping(cpConstraint *constraint, cpFloat value)@
1054
1055 <%= h 2, "Rotary Limit Joint:", "cpRotaryLimitJoint" %>
1056
1057 <pre><code>cpRotaryLimitJoint *cpRotaryLimitJointAlloc(void)
1058 cpRotaryLimitJoint *cpRotaryLimitJointInit(cpRotaryLimitJoint *joint, cpBody *a, cpBody *b, cpFloat min, cpFloat max)
1059 cpConstraint *cpRotaryLimitJointNew(cpBody *a, cpBody *b, cpFloat min, cpFloat max)</code></pre>
1060
1061 p(expl). Constrains the relative rotations of two bodies. @min@ and @max@ are the angular limits in radians. It is implemented so that it's possible to for the range to be greater than a full revolution.
1062
1063 <%= h 3, "Properties", "Properties" %>
1064
1065 * @cpFloat cpRotaryLimitJointGetMin(const cpConstraint *constraint)@
1066 * @void cpRotaryLimitJointSetMin(cpConstraint *constraint, cpFloat value)@
1067 * @cpFloat cpRotaryLimitJointGetMax(const cpConstraint *constraint)@
1068 * @void cpRotaryLimitJointSetMax(cpConstraint *constraint, cpFloat value)@
1069
1070 <%= h 2, "Ratchet Joint:", "cpRatchetJoint" %>
1071
1072 <pre><code>cpRatchetJoint *cpRatchetJointAlloc(void);
1073 cpRatchetJoint *cpRatchetJointInit(cpRatchetJoint *joint, cpBody *a, cpBody *b, cpFloat phase, cpFloat ratchet);
1074 cpConstraint *cpRatchetJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloat ratchet);</code></pre>
1075
1076 p(expl). Works like a socket wrench. @ratchet@ is the distance between "clicks", @phase@ is the initial offset to use when deciding where the ratchet angles are.
1077
1078 <%= h 3, "Properties", "Properties" %>
1079
1080 * @cpFloat cpRatchetJointGetAngle(const cpConstraint *constraint)@
1081 * @void cpRatchetJointSetAngle(cpConstraint *constraint, cpFloat value)@
1082 * @cpFloat cpRatchetJointGetPhase(const cpConstraint *constraint)@
1083 * @void cpRatchetJointSetPhase(cpConstraint *constraint, cpFloat value)@
1084 * @cpFloat cpRatchetJointGetRatchet(const cpConstraint *constraint)@
1085 * @void cpRatchetJointSetRatchet(cpConstraint *constraint, cpFloat value)@
1086
1087 <%= h 2, "Gear Joint:", "cpGearJoint" %>
1088
1089 <pre><code>cpGearJoint *cpGearJointAlloc(void);
1090 cpGearJoint *cpGearJointInit(cpGearJoint *joint, cpBody *a, cpBody *b, cpFloat phase, cpFloat ratio);
1091 cpConstraint *cpGearJointNew(cpBody *a, cpBody *b, cpFloat phase, cpFloat ratio);</code></pre>
1092
1093 p(expl). Keeps the angular velocity ratio of a pair of bodies constant. @ratio@ is always measured in absolute terms. It is currently not possible to set the ratio in relation to a third body's angular velocity. @phase@ is the initial angular offset of the two bodies.
1094
1095 <%= h 3, "Properties", "Properties" %>
1096
1097 * @cpFloat cpGearJointGetPhase(const cpConstraint *constraint)@
1098 * @void cpGearJointSetPhase(cpConstraint *constraint, cpFloat value)@
1099 * @cpFloat cpGearJointGetRatio(const cpConstraint *constraint)@
1100 * @void cpGearJointSetRatio(cpConstraint *constraint, cpFloat value)@
1101
1102 <%= h 2, "Simple Motor:", "cpSimpleMotor" %>
1103
1104 <pre><code>cpSimpleMotor *cpSimpleMotorAlloc(void);
1105 cpSimpleMotor *cpSimpleMotorInit(cpSimpleMotor *joint, cpBody *a, cpBody *b, cpFloat rate);
1106 cpConstraint *cpSimpleMotorNew(cpBody *a, cpBody *b, cpFloat rate);</code></pre>
1107
1108 p(expl). Keeps the relative angular velocity of a pair of bodies constant. @rate@ is the desired relative angular velocity. You will usually want to set an force (torque) maximum for motors as otherwise they will be able to apply a nearly infinite torque to keep the bodies moving.
1109
1110 <%= h 3, "Properties", "Properties" %>
1111
1112 * @cpFloat cpSimpleMotorGetRate(const cpConstraint *constraint)@
1113 * @void cpSimpleMotorSetRate(cpConstraint *constraint, cpFloat value)@
1114
1115
1116 <%= h 2, "Notes:", "Notes" %>
1117
1118 * You can add multiple joints between two bodies, but make sure that they don't fight. Doing so can cause the bodies jitter or spin violently.
1119
1120
1121 <%= h 1, "Overview of Collision Detection in Chipmunk:", "CollisionDetection" %>
1122
1123 In order to make collision detection in Chipmunk as fast as possible, the process is broken down into several stages. While I've tried to keep it conceptually simple, the implementation can be a bit daunting. Fortunately as a user of the library, you don't need to understand everything about how it works. Though if you are trying to squeeze every bit of performance out of Chipmunk, understanding this section can be helpful.
1124
1125 <%= h 2, "Spatial Indexing:", "SpatialIndexing" %>
1126
1127 A for loop that checks every object against every other object in the scene would be _very_ slow. So the first stage of the collision detection, commonly called the broadphase, uses a high level spatial algorithm to decide which pairs of objects to check for collisions. Currently Chipmunk supports two spatial indexes, an axis-aligned bounding box tree and a spatial hash. These spatial indexes are able to quickly identify which pairs of shapes are near each other and should be checked for a collision.
1128
1129 <%= h 2, "Fast Collision Filtering:", "CollisionsFastFiltering" %>
1130
1131 After the spatial index figures out which pairs of shapes are likely to be near each other, it passes each pair back to the space using a callback to perform some additional filtering on the pairs. Before doing anything else, Chipmunk performs a few quick tests to check if shapes should collide.
1132
1133 * *Bounding Box Test:* The shapes are not colliding if their bounding boxes are not overlapping. Objects like diagonal line segments can trigger a lot of false positives here, but it's unlikely to be something you should worry about.
1134 * *Category Mask Test:* The categories of each shape are bitwise ANDed against the category mask of the other shape. If either result is 0, the shapes do not collide.
1135 * *Group Test:* Shapes shouldn't collide with other shapes in the same non-zero group.
1136
1137 <%= h 2, "Constraint Based Filtering:", "CollisionsConstraints" %>
1138
1139 After fast collision filtering, Chipmunk checks the list of joints on one of the bodies to see if it has a constraint that attaches it to the other body. If that constraint's @collideBodies@ property is false, the collision will be ignored. This check is often very fast since most scenes don't contain a lot of constraints.
1140
1141 <%= h 2, "Primitive Shape to Shape Collision Detection:", "PrimitiveTest" %>
1142
1143 The most expensive test is to actually check for overlap based on their geometry. Circle to circle and circle to line collisions are very fast. Segment to segment and poly to poly collisions are handled using the GJK/EPA algorithms, and get more expensive as the number of vertexes increases. Simpler shapes make for faster collisions, and often more important, fewer collision points for the solver to run. Chipmunk uses a small dispatch table to figure out which function to use to check if the shapes overlap.
1144
1145 Without going into too much detail, the GJK algorithm checks the distance between two objects, and the EPA algorithm checks how much they are overlapping. If you give you segment and poly shapes a small radius when creating them, the EPA algorithm can usually be skipped, speeding up the collision detection considerably. The radius should be at least as big as the amount of allowed collision slop.
1146
1147 <%= h 2, "Collision Handler Filtering:", "HandlerFiltering" %>
1148
1149 After checking if two shapes overlap Chipmunk will look to see if you have defined a collision handler for the collision types of the shapes. This is vital to process collisions events for the gameplay, but also gives you a very flexible way to filter out collisions. The return value of the @begin()@ and @preSolve()@ callbacks determines whether or not the colliding pair of shapes is discarded or not. Returning true will keep the pair, false will discard it. Rejecting a collision from a @begin()@ callback is permanent, rejecting it from the @preSolve()@ only applies to the step it occured in. If you don't define a handler for the given collision types, Chipmunk will call the space's default handler, which by default is defined to simply accept all collisions.
1150
1151 Wildcard collisions can also return a value, but they are handled in a more complicated way. When you create a collision handler between two specific collision types, it's your responsibility to decide when to call the wildcard handlers and what to do with their return values. Otherwise, the default is to call the wildcard handler for the first type, then the second type, and use a logical AND of their return values as filtering value. See @DefaultBegin()@ in @cpSpace.c@ for more information.
1152
1153 While using callbacks to filter collisions is the most flexible way, keep in mind that by the time your callback is called all of the most expensive collision detection has already been done. For simulations with a lot of colliding objects each frame, the time spent finding collisions is small compared to the time spent solving the physics for them so it may not be a big deal. Fast collision filtering should be preferred if possible.
1154
1155
1156 <%= h 1, "Collision Callbacks:", "CollisionCallbacks" %>
1157
1158 A physics library without any events or feedback would not be very useful for games. How would you know when the player bumped into an enemy so that you could take some health points away? How would you know how hard the car hit something so you don't play a loud crash noise when a pebble hits it? What if you need to decide if a collision should be ignored based on specific conditions, like implementing one way platforms? Chipmunk has a number of powerful callback systems that you can use to solve these problems.
1159
1160 <%= h 2, "Collision Handlers:", "Handlers" %>
1161
1162 A collision handler is a set of 4 function callbacks for the different collision events that Chipmunk recognizes. The event types are:
1163 * @begin()@: Two shapes just started touching for the first time this step. Return true from the callback to process the collision normally or false to cause Chipmunk to ignore the collision entirely. If you return false, the @preSolve()@ and @postSolve()@ callbacks will never be run, but you will still recieve a separate event when the shapes stop overlapping.
1164 * @preSolve()@: Two shapes are touching during this step. Return false from the callback to make Chipmunk ignore the collision this step or true to process it normally. Additionally, you may override collision values using @cpArbiterSetFriction()@, @cpArbiterSetElasticity()@ or @cpArbiterSetSurfaceVelocity()@ to provide custom friction, elasticity, or surface velocity values. See "cpArbiter":#cpArbiter for more info.
1165 * @postSolve()@: Two shapes are touching and their collision response has been processed. You can retrieve the collision impulse or kinetic energy at this time if you want to use it to calculate sound volumes or damage amounts. See "cpArbiter":#cpArbiter for more info.
1166 * @separate()@: Two shapes have just stopped touching for the first time this step. To ensure that begin()/separate() are always called in balanced pairs, it will also be called when removing a shape while its in contact with something or when deallocating the space.
1167
1168 Collision callbacks are closely associated with "cpArbiter":#cpArbiter structs. You should familiarize yourself with those as well.
1169
1170 *Note:* Shapes tagged as sensors (@cpShape.sensor == true@) never generate collisions that get processed, so collisions between sensors shapes and other shapes will never call the @postSolve()@ callback. They still generate @begin()@, and @separate()@ callbacks, and the @preSolve()@ callback is also called every frame even though there is no collision response.
1171
1172 *Note #2:* @preSolve()@ callbacks are called before the sleeping algorithm runs. If an object falls asleep, its @postSolve()@ callback won't be called until it's reawoken.
1173
1174 <%= h 2, "Collision Handler API:", "HandlerAPI" %>
1175
1176 <pre><code>typedef int (*cpCollisionBeginFunc)(cpArbiter *arb, struct cpSpace *space, cpDataPointer data)
1177 typedef int (*cpCollisionPreSolveFunc)(cpArbiter *arb, cpSpace *space, cpDataPointer data)
1178 typedef void (*cpCollisionPostSolveFunc)(cpArbiter *arb, cpSpace *space, cpDataPointer data)
1179 typedef void (*cpCollisionSeparateFunc)(cpArbiter *arb, cpSpace *space, cpDataPointer data)</code></pre>
1180
1181 p(expl). Collision handler function types. While all of them take an arbiter, space, and a user data pointer, only the @begin()@ and @preSolve()@ callbacks return a value. See above for more information.
1182
1183 <pre><code>
1184 struct cpCollisionHandler {
1185 cpCollisionType typeA, typeB;
1186 cpCollisionBeginFunc beginFunc;
1187 cpCollisionPreSolveFunc preSolveFunc;
1188 cpCollisionPostSolveFunc postSolveFunc;
1189 cpCollisionSeparateFunc separateFunc;
1190 cpDataPointer userData;
1191 };
1192 </code></pre>
1193
1194 p(expl). This collision handler processes collisions between objects of type @typeA@ and @typeB@. Fill the desired collision callback functions- they are documented above. A user definable context pointer @userData@ is included for your convenience. This pointer is provided as an argument in each callback function.
1195
1196 <pre><code>cpCollisionHandler *cpSpaceAddCollisionHandler(cpSpace *space, cpCollisionType a, cpCollisionType b)</code></pre>
1197
1198 p(expl). Add a @cpCollisionHandler@ for specific collision type pair or return the existing handler for the type pair. Whenever shapes with collision types (@cpShape.collision_type@) @a@ and @b@ collide, this handler will be used to process the collision events. When a new collision handler is created, the callbacks will all be set to builtin callbacks that perform the default behavior (call the wildcard handlers, and accept all collisions).
1199
1200 <%= pop_open_example "PlaySoundOnCollision" %>
1201
1202 <pre><code>cpCollisionHandler *cpSpaceAddWildcardHandler(cpSpace *space, cpCollisionType type)</code></pre>
1203
1204 p(expl). Add a wildcard collision handler for given collision type. This handler will be used any time an object with this type collides with another object, regardless of its type. A good example is a projectile that should be destroyed the first time it hits anything. There may be a specific collision handler and two wildcard handlers. It's up to the specific handler to decide if and when to call the wildcard handlers and what to do with their return values. (See @cpArbiterCallWildcard*()@ below) When a new wildcard handler is created, the callbacks will all be set to builtin callbacks that perform the default behavior. (accept all collisions in @begin()@ and @preSolve()@, or do nothing for @postSolve()@ and @separate()@.
1205
1206 <pre><code>cpCollisionHandler *cpSpaceAddDefaultCollisionHandler(cpSpace *space)</code></pre>
1207
1208 p(expl). Return a reference to the default collision handler or that is used to process all collisions that don't have a more specific handler. The default behavior for each of the callbacks is to call the wildcard handlers, ANDing their return values together if applicable.
1209
1210 <%= h 2, "Post-Step Callbacks:", "PostStep" %>
1211
1212 Post-step callbacks are the one place where you can break the rules about adding or removing objects from within a callback. In fact, their primary function is to help you safely remove objects from the space that you wanted to disable or destroy in a collision or query callback.
1213
1214 Post step callbacks are registered as a function and a pointer that is used as a key. You can only register one @postStep()@ callback per key. This prevents you from accidentally removing an object more than once. For instance, say that you get a collision callback between a bullet and object A. You want to destroy both the bullet and object A, so you register a @postStep()@ callback to safely remove them from your game. Then you get a second collision callback between the bullet and object B. You register a @postStep()@ callback to remove object B, and a second @postStep()@ callback to remove the bullet. Because you can only register one callback per key, the @postStep()@ callback for the bullet will only be called once and you can't accidentally try to remove it twice.
1215
1216 <pre><code>typedef void (*cpPostStepFunc)(cpSpace *space, void *obj, void *data)</code></pre>
1217
1218 p(expl). Function type used for @postStep()@ callbacks. @space@ is the space the callback was registered on, @obj@ is the pointer value you supplied as the key, and @data@ is a user definable pointer you can use to pass in as a context value.
1219
1220 <pre><code>cpBool cpSpaceAddPostStepCallback(cpSpace *space, cpPostStepFunc func, void *key, void *data);</code></pre>
1221
1222 p(expl). Add @func@ to be called before @cpSpaceStep()@ returns. @key@ and @data@ will be passed to your function. Only the first callback registered for any unique value of @key@ will be recorded. It returns @cpTrue@ if the callback is scheduled and @cpfalse@ when the @key@ has already been used. The behavior of adding a @postStep()@ callback from outside of a collision handler or query callback is undefined.
1223
1224 *Note:* Post-step callbacks are not run in any particular order. If you need to sequence a number of events, you'll need to put them in a single callback.
1225
1226 <%= h 2, "Examples:", "Examples" %>
1227
1228 See the "callback examples":examples.html#CollisionCallbacks for more information.
1229
1230 <%= h 1, "Chipmunk Collision Pairs: @cpArbiter@", "cpArbiter" %>
1231
1232 Chipmunk's @cpArbiter@ struct encapsulates a pair of colliding shapes and all of the data about their collision. cpArbiters are created when a collision starts, and persist until those shapes are no longer colliding.
1233
1234 Why are they called arbiters? The short answer is that I kept using the word "arbitrates" to describe the way that collisions were resolved and then I saw that Box2D actually called them arbiters way back in 2006 when I was looking at its solver. An arbiter is like a judge, a person that has authority to settle disputes between two people. It was a fun, fitting name and was shorter to type than CollisionPair which I had been using. It was originally meant to be a private internal structure only, but evolved to be useful from callbacks.
1235
1236 <%= h 2, "Memory Management:", "Memory" %>
1237
1238 You will never need to create or free an arbiter. More importantly, because they are entirely managed by the space you should *never* store a reference to an arbiter as you don't know when they will be freed or reused. Use them within the callback where they are given to you and then forget about them or copy out the information you need.
1239
1240 <%= h 2, "Properties:", "Properties" %>
1241
1242 <pre><code>cpFloat cpArbiterGetElasticity(const cpArbiter *arb)
1243 void cpArbiterSetElasticity(cpArbiter *arb, cpFloat value)</code></pre>
1244
1245 p(expl). The calculated elasticity for this collision pair. Setting the value in a @preSolve()@ callback will override the value calculated by the space. The default calculation multiplies the elasticity of the two shapes together.
1246
1247 <pre><code>cpFloat cpArbiterGetFriction(const cpArbiter *arb)
1248 void cpArbiterSetFriction(cpArbiter *arb, cpFloat value)</code></pre>
1249
1250 p(expl). The calculated friction for this collision pair. Setting the value in a @preSolve()@ callback will override the value calculated by the space. The default calculation multiplies the friction of the two shapes together.
1251
1252 <pre><code>cpVect cpArbiterGetSurfaceVelocity(const cpArbiter *arb)
1253 void cpArbiterSetSurfaceVelocity(cpArbiter *arb, cpVect value)</code></pre>
1254
1255 p(expl). The calculated surface velocity for this collision pair. Setting the value in a @preSolve()@ callback will override the value calculated by the space. the default calculation subtracts the surface velocity of the second shape from the first and then projects that onto the tangent of the collision. This is so that only friction is affected by default calculation. Using a custom calculation, you can make something that responds like a pinball bumper, or where the surface velocity is dependent on the location of the contact point.
1256
1257 <pre><code>cpDataPointer cpArbiterGetUserData(const cpArbiter *arb)
1258 void cpArbiterSetUserData(cpArbiter *arb, cpDataPointer data)</code></pre>
1259
1260 p(expl). A user definable context pointer. The value will persist until just after the @separate()@ callback is called for the pair.
1261
1262 *NOTE:* If you need to clean up this pointer, you should implement the @separate()@ callback to do it. Also be careful when destroying the space as there may be active collisions still. In order to trigger the @separate()@ callbacks and clean up your data, you'll need to remove all the shapes from the space before disposing of it. This is something I'd suggest doing anyway. See ChipmunkDemo.c:ChipmunkDemoFreeSpaceChildren() for an example of how to do it easily.
1263
1264
1265 <pre><code>int cpArbiterGetCount(const cpArbiter *arb)
1266 cpVect cpArbiterGetNormal(const cpArbiter *arb, int i)
1267 cpVect cpArbiterGetPoint(const cpArbiter *arb, int i)
1268 cpFloat cpArbiterGetDepth(const cpArbiter *arb, int i)</code></pre>
1269
1270 p(expl). Get the number of contacts tracked by this arbiter or the specific collision point, collision normal or penetration depth of a collision point. For the forseeable future, the maximum number of contacts will be two.
1271
1272 <pre><code>cpBool cpArbiterIsFirstContact(const cpArbiter *arb)</code></pre>
1273
1274 p(expl). Returns true if this is the first step the two shapes started touching. This can be useful for sound effects for instance. If its the first frame for a certain collision, check the energy of the collision in a @postStep()@ callbock and use that to determine the volume of a sound effect to play.
1275
1276 <pre><code>cpBool cpArbiterIsRemoval(const cpArbiter *arb)</code></pre>
1277
1278 p(expl). Returns @cpTrue@ during a @separate()@ callback if the callback was invoked due to an object removal.
1279
1280 <pre><code>void cpArbiterGetShapes(const cpArbiter *arb, cpShape **a, cpShape **b)
1281 void cpArbiterGetBodies(const cpArbiter *arb, cpBody **a, cpBody **b)</code></pre>
1282
1283 p(expl). Get the shapes or bodies in the order that they were defined in the collision handler associated with this arbiter. If you defined the handler as @cpSpaceAddCollisionHandler(space, 1, 2, ...)@, you you will find that @a->collision_type == 1@ and @b->collision_type == 2@.
1284
1285 <pre><code>cpBool cpArbiterCallWildcardBeginA(cpArbiter *arb, cpSpace *space)
1286 cpBool cpArbiterCallWildcardBeginB(cpArbiter *arb, cpSpace *space)
1287 cpBool cpArbiterCallWildcardPreSolveA(cpArbiter *arb, cpSpace *space)
1288 cpBool cpArbiterCallWildcardPreSolveB(cpArbiter *arb, cpSpace *space)
1289 void cpArbiterCallWildcardPostSolveA(cpArbiter *arb, cpSpace *space)
1290 void cpArbiterCallWildcardPostSolveB(cpArbiter *arb, cpSpace *space)
1291 void cpArbiterCallWildcardSeparateA(cpArbiter *arb, cpSpace *space)
1292 void cpArbiterCallWildcardSeparateB(cpArbiter *arb, cpSpace *space)</code></pre>
1293
1294 p(expl). These functions invoke the wildcard handlers for a given collision. For custom collision handlers between specific types or overriding the default handler, you must decide how to invoke the wildcard handlers since it may be important to call the wildcards first, last, or possibly skip them entirely. For the @begin()@ and @preSolve()@ callbacks, you also need to decide what to do with their return values since they may not agree with each other or the specific handler they were called from. Every collision handler is defined for two types, the "A" variants of these functions call the wildcard handler for the first type, and the "B" variants call the handler for the second type.
1295
1296 <%= pop_open_example "CollisionCallback" %>
1297
1298 <%= h 2, "Contact Point Sets:", "HelperFunctions" %>
1299
1300 Contact point sets make getting contact information simpler.
1301
1302 <pre><code>cpContactPointSet cpArbiterGetContactPointSet(const cpArbiter *arb)</code></pre>
1303
1304 p(expl). Get a contact point set struct from an arbiter.
1305
1306 You might do something like the following to get and process a contact point set:
1307
1308 <pre><code>cpContactPointSet set = cpArbiterGetContactPointSet(arbiter);
1309 for(int i=0; i<set.count; i++){
1310 // get and work with the collision point normal and penetration distance:
1311 set.points[i].point
1312 set.points[i].normal
1313 set.points[i].dist
1314 }</code></pre>
1315
1316 <pre><code>void cpArbiterSetContactPointSet(cpArbiter *arb, cpContactPointSet *set)</code></pre>
1317
1318 p(expl). Replace the contact point set of an Arbiter. You cannot change the number of contacts, but can change the location, normal or penetration distance. The "Sticky" demo uses this to allow objects to overlap an extra amount. You could also use it in a Pong style game to modify the normal of the collision based on the x-position of the collision even though the paddle is a flat shape.
1319
1320 <%= h 2, "Helper Functions:", "HelperFunctions" %>
1321
1322 <pre><code>void cpArbiterGetShapes(cpArbiter *arb, cpShape **a, cpShape **b)
1323 void cpArbiterGetBodies(const cpArbiter *arb, cpBody **a, cpBody **b)</code></pre>
1324
1325 p(expl). Get the shapes (or their bodies) in the order that they were defined in the collision handler associated with this arbiter. If you defined the handler as @cpSpaceAddCollisionHandler(space, 1, 2, ...)@, you you will find that @a->collision_type == 1@ and @b->collision_type == 2@. The convenience macro defines and initializes the two shape variables for you. The default collision handler doesn't use collision types so the order is undefined.
1326
1327 <pre><code>#define CP_ARBITER_GET_SHAPES(arb, a, b) cpShape *a, *b; cpArbiterGetShapes(arb, &a, &b)
1328 #define CP_ARBITER_GET_BODIES(arb, a, b) cpBody *a, *b; cpArbiterGetBodies(arb, &a, &b);</code></pre>
1329
1330 p(expl). Shortcut macros for defining variables for and retrieving the shapes/bodies for an arbiter.
1331
1332 <pre><code>cpVect cpArbiterTotalImpulseWithFriction(cpArbiter *arb);
1333 cpVect cpArbiterTotalImpulse(cpArbiter *arb);</code></pre>
1334
1335 p(expl). Returns the impulse that was applied this step to resolve the collision. These functions should only be called from a @postStep()@ or @cpBodyEachArbiter()@ callback, otherwise the result is undefined. If in doubt which function to use, use @cpArbiterTotalImpulseWithFriction()@.
1336
1337 <pre><code>cpFloat cpArbiterTotalKE(const cpArbiter *arb);</code></pre>
1338
1339 p(expl). Calculate the amount of energy lost in a collision including static, but not dynamic friction. This function should only be called from a @postSolve()@, @postStep()@ or @cpBodyEachArbiter()@ callback.
1340
1341
1342 <%= h 1, "Queries:", "Queries" %>
1343
1344 Chipmunk spaces support four kinds of spatial queries, nearest point, segment, shape and fast bounding box queries. Any type can be performed efficiently against an entire space, and point and segment queries can be performed against individual shapes. All types of queries take a collision group and layer that are used to filter matches out using the same rules used for filtering collisions between shapes. See "cpShape":#cpShape for more information. If you don't want to filter out any matches, use @CP_ALL_LAYERS@ for the layers and @CP_NO_GROUP@ as the group.
1345
1346 <%= h 2, "Nearest Point Queries:", "PointQueries" %>
1347
1348 Point queries are useful for things like mouse picking and simple sensors. They allow you to check if there are shapes within a certain distance of a point, find the closest point on a shape to a given point or find the closest shape to a point.
1349
1350 <pre><code>typedef struct cpPointQueryInfo {
1351 /// The nearest shape, NULL if no shape was within range.
1352 const cpShape *shape;
1353 /// The closest point on the shape's surface. (in world space coordinates)
1354 cpVect point;
1355 /// The distance to the point. The distance is negative if the point is inside the shape.
1356 cpFloat distance;
1357 /// The gradient of the signed distance function.
1358 /// The value should be similar to info.p/info.d, but accurate even for very small values of info.d.
1359 cpVect gradient;
1360 } cpPointQueryInfo;</code></pre>
1361
1362 p(expl). Nearest point queries return the point on the surface of the shape as well as the distance from the query point to the surface point.
1363
1364 <pre><code>cpFloat cpShapeNearestPointQuery(cpShape *shape, cpVect p, cpPointQueryInfo *out)</code></pre>
1365
1366 p(expl). Find the distance from @point@ to @shape@. If the point is inside of the shape, the distance will be negative and equal to the depth of the point.
1367
1368 <pre><code>typedef void (*cpSpaceNearestPointQueryFunc)(cpShape *shape, cpFloat distance, cpVect point, void *data);
1369
1370 void cpSpacePointQuery(
1371 cpSpace *space, cpVect point, cpFloat maxDistance,
1372 cpShapeFilter filter,
1373 cpSpaceNearestPointQueryFunc func, void *data
1374 )</code></pre>
1375
1376 p(expl). Query @space@ at @point@ for shapes within the given distance range. The @filter@ is applied to the query and follows the same rules as the collision detection. @func@ is called for each shape found along with the distance to the closest point on the shape's surface, the distance to that point and the @data@ argument passed to @cpSpaceNearestPointQuery()@. Sensor shapes are included. If a @maxDistance@ of @0.0@ is used, the point must lie inside a shape. Negative @maxDistance@ is also allowed meaning that the point must be a under a certain depth within a shape to be considered a match.
1377
1378 <pre><code>cpShape *cpSpacePointQueryNearest(cpSpace *space, cpVect point, cpFloat maxDistance, cpShapeFilter filter, cpPointQueryInfo *out)</code></pre>
1379
1380 p(expl). Query @space@ at @point@ and return the closest shape within @maxDistance@ units of distance. @out@ is an optional pointer to a @cpPointQueryInfo@ if you want additional information about the match.
1381
1382 <%= h 2, "Segment Queries:", "SegmentQueries" %>
1383
1384 Segment queries are like ray casting, but because not all spatial indexes allow processing infinitely long ray queries it is limited to segments. In practice this is still very fast and you don't need to worry too much about the performance as long as you aren't using extremely long segments for your queries.
1385
1386 <pre><code>typedef struct cpSegmentQueryInfo {
1387 /// The shape that was hit, or NULL if no collision occured.
1388 const cpShape *shape;
1389 /// The point of impact.
1390 cpVect point;
1391 /// The normal of the surface hit.
1392 cpVect normal;
1393 /// The normalized distance along the query segment in the range [0, 1].
1394 cpFloat alpha;
1395 } cpSegmentQueryInfo;</code></pre>
1396
1397 p(expl). Segment queries return more information than just a simple yes or no, they also return where a shape was hit and its surface normal at the hit point. @t@ is the percentage between the query start and end points. If you need the hit point in world space or the absolute distance from start, see the segment query helper functions farther down. If a segment query starts within a shape it will have @t = 0@ and @n = cpvzero@.
1398
1399 <pre><code>cpBool cpShapeSegmentQuery(cpShape *shape, cpVect a, cpVect b, cpFloat radius, cpSegmentQueryInfo *info)</code></pre>
1400
1401 p(expl). Perform a segment query from @a@ to @b@ with the given @radius@ against a single shape @shape@. @info@ must be a valid pointer to a @cpSegmentQueryInfo@ structure which will be initialized with the raycast info.
1402
1403 <pre><code>typedef void (*cpSpaceSegmentQueryFunc)(cpShape *shape, cpFloat t, cpVect n, void *data)
1404
1405 void cpSpaceSegmentQuery(
1406 cpSpace *space, cpVect start, cpVect end, cpFloat radius,
1407 cpShapeFilter filter,
1408 cpSpaceSegmentQueryFunc func, void *data
1409 )</code></pre>
1410
1411 p(expl). Query @space@ along the line segment from @start@ to @end@ with the given @radius@. The @filter@ is applied to the query and follows the same rules as the collision detection. @func@ is called with the normalized distance along the line and surface normal for each shape found along with the @data@ argument passed to @cpSpacePointQuery()@. Sensor shapes are included.
1412
1413 <pre><code>cpShape *cpSpaceSegmentQueryFirst(
1414 cpSpace *space, cpVect start, cpVect end, cpFloat radius,
1415 cpShapeFilter filter,
1416 cpSegmentQueryInfo *info
1417 )</code></pre>
1418
1419 p(expl). Query @space@ along the line segment from @start@ to @end@ with the given @radius@. The @filter@ is applied to the query and follows the same rules as the collision detection. Only the first shape encountered is returned and the search is short circuited. Returns @NULL@ if no shape was found. The info struct pointed to by @info@ will be initialized with the raycast info unless @info@ is NULL. Sensor shapes are ignored.
1420
1421 <%= h 2, "AABB Queries:", "AABBQueries" %>
1422
1423 AABB queries give you a fast way to check roughly which shapes are in an area.
1424
1425 <pre><code>typedef void (*cpSpaceBBQueryFunc)(cpShape *shape, void *data)
1426
1427 void cpSpaceBBQuery(
1428 cpSpace *space, cpBB bb,
1429 cpShapeFilter filter,
1430 cpSpaceBBQueryFunc func, void *data
1431 )</code></pre>
1432
1433 p(expl). Query @space@ to find all shapes near @bb@. The @filter@ is applied to the query and follows the same rules as the collision detection. @func@ is called for each shape whose bounding box overlaps @bb@ along with the @data@ argument passed to @cpSpaceBBQuery()@. Sensor shapes are included.
1434
1435 <%= h 2, "Shape Queries:", "ShapeQueries" %>
1436
1437 Shape queries allow you to check if shapes in a space are overlapping a specific area. You can use this to check if an object already exists at a location you want to add another shape, or to use as sensor queries for AI.
1438
1439 You can either create a body/shape pair before querying, or you can create a shape passing @NULL@ for the body and position the shape using @cpShapeUpdate()@ to set the position and rotation of the shape.
1440
1441 <pre><code>typedef void (*cpSpaceShapeQueryFunc)(cpShape *shape, cpContactPointSet *points, void *data);
1442
1443 cpBool cpSpaceShapeQuery(cpSpace *space, cpShape *shape, cpSpaceShapeQueryFunc func, void *data);</code></pre>
1444
1445 p(expl). Query @space@ to find all shapes overlapping @shape@. @func@ is called for each overlapping shape along with a pointer to a temporary cpContactPointSet and the @data@ argument passed to @cpSpaceBBQuery()@. Sensor shapes are included.
1446
1447 <%= h 2, "Blocks:", "Blocks" %>
1448
1449 If your compiler supports blocks (such as Clang), there are an alternate set of functions you can call. @cpSpaceNearestPointQuery_b()@, etc. See @chipmunk.h@ for more information.
1450
1451 <%= h 2, "Examples:", "Examples" %>
1452
1453 See the "query examples":examples.html#Query for more information.