1 /* Copyright (c) 2013 Scott Lembcke and Howling Moon Software
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to deal
5 * in the Software without restriction, including without limitation the rights
6 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 * copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 #include "chipmunk/chipmunk_private.h"
30 return (cpBody *)cpcalloc(1, sizeof(cpBody));
34 cpBodyInit(cpBody *body, cpFloat mass, cpFloat moment)
37 body->shapeList = NULL;
38 body->arbiterList = NULL;
39 body->constraintList = NULL;
41 body->velocity_func = cpBodyUpdateVelocity;
42 body->position_func = cpBodyUpdatePosition;
44 body->sleeping.root = NULL;
45 body->sleeping.next = NULL;
46 body->sleeping.idleTime = 0.0f;
55 body->v_bias = cpvzero;
58 body->userData = NULL;
60 // Setters must be called after full initialization so the sanity checks don't assert on garbage data.
61 cpBodySetMass(body, mass);
62 cpBodySetMoment(body, moment);
63 cpBodySetAngle(body, 0.0f);
69 cpBodyNew(cpFloat mass, cpFloat moment)
71 return cpBodyInit(cpBodyAlloc(), mass, moment);
77 cpBody *body = cpBodyNew(0.0f, 0.0f);
78 cpBodySetType(body, CP_BODY_TYPE_KINEMATIC);
86 cpBody *body = cpBodyNew(0.0f, 0.0f);
87 cpBodySetType(body, CP_BODY_TYPE_STATIC);
92 void cpBodyDestroy(cpBody *body){}
95 cpBodyFree(cpBody *body)
104 #define cpAssertSaneBody(body)
106 static void cpv_assert_nan(cpVect v, char *message){cpAssertHard(v.x == v.x && v.y == v.y, message);}
107 static void cpv_assert_infinite(cpVect v, char *message){cpAssertHard(cpfabs(v.x) != INFINITY && cpfabs(v.y) != INFINITY, message);}
108 static void cpv_assert_sane(cpVect v, char *message){cpv_assert_nan(v, message); cpv_assert_infinite(v, message);}
111 cpBodySanityCheck(const cpBody *body)
113 cpAssertHard(body->m == body->m && body->m_inv == body->m_inv, "Body's mass is NaN.");
114 cpAssertHard(body->i == body->i && body->i_inv == body->i_inv, "Body's moment is NaN.");
115 cpAssertHard(body->m >= 0.0f, "Body's mass is negative.");
116 cpAssertHard(body->i >= 0.0f, "Body's moment is negative.");
118 cpv_assert_sane(body->p, "Body's position is invalid.");
119 cpv_assert_sane(body->v, "Body's velocity is invalid.");
120 cpv_assert_sane(body->f, "Body's force is invalid.");
122 cpAssertHard(body->a == body->a && cpfabs(body->a) != INFINITY, "Body's angle is invalid.");
123 cpAssertHard(body->w == body->w && cpfabs(body->w) != INFINITY, "Body's angular velocity is invalid.");
124 cpAssertHard(body->t == body->t && cpfabs(body->t) != INFINITY, "Body's torque is invalid.");
127 #define cpAssertSaneBody(body) cpBodySanityCheck(body)
131 cpBodyIsSleeping(const cpBody *body)
133 return (body->sleeping.root != ((cpBody*)0));
137 cpBodyGetType(cpBody *body)
139 if(body->sleeping.idleTime == INFINITY){
140 return CP_BODY_TYPE_STATIC;
141 } else if(body->m == INFINITY){
142 return CP_BODY_TYPE_KINEMATIC;
144 return CP_BODY_TYPE_DYNAMIC;
149 cpBodySetType(cpBody *body, cpBodyType type)
151 cpBodyType oldType = cpBodyGetType(body);
152 if(oldType == type) return;
154 // Static bodies have their idle timers set to infinity.
155 // Non-static bodies should have their idle timer reset.
156 body->sleeping.idleTime = (type == CP_BODY_TYPE_STATIC ? INFINITY : 0.0f);
158 if(type == CP_BODY_TYPE_DYNAMIC){
159 body->m = body->i = 0.0f;
160 body->m_inv = body->i_inv = INFINITY;
162 cpBodyAccumulateMassFromShapes(body);
164 body->m = body->i = INFINITY;
165 body->m_inv = body->i_inv = 0.0f;
171 // If the body is added to a space already, we'll need to update some space data structures.
172 cpSpace *space = cpBodyGetSpace(body);
174 cpAssertSpaceUnlocked(space);
176 if(oldType == CP_BODY_TYPE_STATIC){
177 // TODO This is probably not necessary
178 // cpBodyActivateStatic(body, NULL);
180 cpBodyActivate(body);
183 // Move the bodies to the correct array.
184 cpArray *fromArray = cpSpaceArrayForBodyType(space, oldType);
185 cpArray *toArray = cpSpaceArrayForBodyType(space, type);
186 if(fromArray != toArray){
187 cpArrayDeleteObj(fromArray, body);
188 cpArrayPush(toArray, body);
191 // Move the body's shapes to the correct spatial index.
192 cpSpatialIndex *fromIndex = (oldType == CP_BODY_TYPE_STATIC ? space->staticShapes : space->dynamicShapes);
193 cpSpatialIndex *toIndex = (type == CP_BODY_TYPE_STATIC ? space->staticShapes : space->dynamicShapes);
194 if(fromIndex != toIndex){
195 CP_BODY_FOREACH_SHAPE(body, shape){
196 cpSpatialIndexRemove(fromIndex, shape, shape->hashid);
197 cpSpatialIndexInsert(toIndex, shape, shape->hashid);
205 // Should *only* be called when shapes with mass info are modified, added or removed.
207 cpBodyAccumulateMassFromShapes(cpBody *body)
209 if(body == NULL || cpBodyGetType(body) != CP_BODY_TYPE_DYNAMIC) return;
211 // Reset the body's mass data.
212 body->m = body->i = 0.0f;
215 // Cache the position to realign it at the end.
216 cpVect pos = cpBodyGetPosition(body);
218 // Accumulate mass from shapes.
219 CP_BODY_FOREACH_SHAPE(body, shape){
220 struct cpShapeMassInfo *info = &shape->massInfo;
224 cpFloat msum = body->m + m;
226 body->i += m*info->i + cpvdistsq(body->cog, info->cog)*(m*body->m)/msum;
227 body->cog = cpvlerp(body->cog, info->cog, m/msum);
232 // Recalculate the inverses.
233 body->m_inv = 1.0f/body->m;
234 body->i_inv = 1.0f/body->i;
236 // Realign the body since the CoG has probably moved.
237 cpBodySetPosition(body, pos);
238 cpAssertSaneBody(body);
242 cpBodyGetSpace(const cpBody *body)
248 cpBodyGetMass(const cpBody *body)
254 cpBodySetMass(cpBody *body, cpFloat mass)
256 cpAssertHard(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC, "You cannot set the mass of kinematic or static bodies.");
257 cpAssertHard(0.0f <= mass && mass < INFINITY, "Mass must be positive and finite.");
259 cpBodyActivate(body);
261 body->m_inv = mass == 0.0f ? INFINITY : 1.0f/mass;
262 cpAssertSaneBody(body);
266 cpBodyGetMoment(const cpBody *body)
272 cpBodySetMoment(cpBody *body, cpFloat moment)
274 cpAssertHard(moment >= 0.0f, "Moment of Inertia must be positive.");
276 cpBodyActivate(body);
278 body->i_inv = moment == 0.0f ? INFINITY : 1.0f/moment;
279 cpAssertSaneBody(body);
283 cpBodyGetRotation(const cpBody *body)
285 return cpv(body->transform.a, body->transform.b);
289 cpBodyAddShape(cpBody *body, cpShape *shape)
291 cpShape *next = body->shapeList;
292 if(next) next->prev = shape;
295 body->shapeList = shape;
297 if(shape->massInfo.m > 0.0f){
298 cpBodyAccumulateMassFromShapes(body);
303 cpBodyRemoveShape(cpBody *body, cpShape *shape)
305 cpShape *prev = shape->prev;
306 cpShape *next = shape->next;
311 body->shapeList = next;
321 if(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC && shape->massInfo.m > 0.0f){
322 cpBodyAccumulateMassFromShapes(body);
326 static cpConstraint *
327 filterConstraints(cpConstraint *node, cpBody *body, cpConstraint *filter)
330 return cpConstraintNext(node, body);
331 } else if(node->a == body){
332 node->next_a = filterConstraints(node->next_a, body, filter);
334 node->next_b = filterConstraints(node->next_b, body, filter);
341 cpBodyRemoveConstraint(cpBody *body, cpConstraint *constraint)
343 body->constraintList = filterConstraints(body->constraintList, body, constraint);
346 // 'p' is the position of the CoG
348 SetTransform(cpBody *body, cpVect p, cpFloat a)
350 cpVect rot = cpvforangle(a);
351 cpVect c = body->cog;
353 body->transform = cpTransformNewTranspose(
354 rot.x, -rot.y, p.x - (c.x*rot.x - c.y*rot.y),
355 rot.y, rot.x, p.y - (c.x*rot.y + c.y*rot.x)
359 static inline cpFloat
360 SetAngle(cpBody *body, cpFloat a)
363 cpAssertSaneBody(body);
369 cpBodyGetPosition(const cpBody *body)
371 return cpTransformPoint(body->transform, cpvzero);
375 cpBodySetPosition(cpBody *body, cpVect position)
377 cpBodyActivate(body);
378 cpVect p = body->p = cpvadd(cpTransformVect(body->transform, body->cog), position);
379 cpAssertSaneBody(body);
381 SetTransform(body, p, body->a);
385 cpBodyGetCenterOfGravity(const cpBody *body)
391 cpBodySetCenterOfGravity(cpBody *body, cpVect cog)
393 cpBodyActivate(body);
395 cpAssertSaneBody(body);
399 cpBodyGetVelocity(const cpBody *body)
405 cpBodySetVelocity(cpBody *body, cpVect velocity)
407 cpBodyActivate(body);
409 cpAssertSaneBody(body);
413 cpBodyGetForce(const cpBody *body)
419 cpBodySetForce(cpBody *body, cpVect force)
421 cpBodyActivate(body);
423 cpAssertSaneBody(body);
427 cpBodyGetAngle(const cpBody *body)
433 cpBodySetAngle(cpBody *body, cpFloat angle)
435 cpBodyActivate(body);
436 SetAngle(body, angle);
438 SetTransform(body, body->p, angle);
442 cpBodyGetAngularVelocity(const cpBody *body)
448 cpBodySetAngularVelocity(cpBody *body, cpFloat angularVelocity)
450 cpBodyActivate(body);
451 body->w = angularVelocity;
452 cpAssertSaneBody(body);
456 cpBodyGetTorque(const cpBody *body)
462 cpBodySetTorque(cpBody *body, cpFloat torque)
464 cpBodyActivate(body);
466 cpAssertSaneBody(body);
470 cpBodyGetUserData(const cpBody *body)
472 return body->userData;
476 cpBodySetUserData(cpBody *body, cpDataPointer userData)
478 body->userData = userData;
482 cpBodySetVelocityUpdateFunc(cpBody *body, cpBodyVelocityFunc velocityFunc)
484 body->velocity_func = velocityFunc;
488 cpBodySetPositionUpdateFunc(cpBody *body, cpBodyPositionFunc positionFunc)
490 body->position_func = positionFunc;
494 cpBodyUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
496 // Skip kinematic bodies.
497 if(cpBodyGetType(body) == CP_BODY_TYPE_KINEMATIC) return;
499 cpAssertSoft(body->m > 0.0f && body->i > 0.0f, "Body's mass and moment must be positive to simulate. (Mass: %f Moment: %f)", body->m, body->i);
501 body->v = cpvadd(cpvmult(body->v, damping), cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), dt));
502 body->w = body->w*damping + body->t*body->i_inv*dt;
508 cpAssertSaneBody(body);
512 cpBodyUpdatePosition(cpBody *body, cpFloat dt)
514 cpVect p = body->p = cpvadd(body->p, cpvmult(cpvadd(body->v, body->v_bias), dt));
515 cpFloat a = SetAngle(body, body->a + (body->w + body->w_bias)*dt);
516 SetTransform(body, p, a);
518 body->v_bias = cpvzero;
521 cpAssertSaneBody(body);
525 cpBodyLocalToWorld(const cpBody *body, const cpVect point)
527 return cpTransformPoint(body->transform, point);
531 cpBodyWorldToLocal(const cpBody *body, const cpVect point)
533 return cpTransformPoint(cpTransformRigidInverse(body->transform), point);
537 cpBodyApplyForceAtWorldPoint(cpBody *body, cpVect force, cpVect point)
539 cpBodyActivate(body);
540 body->f = cpvadd(body->f, force);
542 cpVect r = cpvsub(point, cpTransformPoint(body->transform, body->cog));
543 body->t += cpvcross(r, force);
547 cpBodyApplyForceAtLocalPoint(cpBody *body, cpVect force, cpVect point)
549 cpBodyApplyForceAtWorldPoint(body, cpTransformVect(body->transform, force), cpTransformPoint(body->transform, point));
553 cpBodyApplyImpulseAtWorldPoint(cpBody *body, cpVect impulse, cpVect point)
555 cpBodyActivate(body);
557 cpVect r = cpvsub(point, cpTransformPoint(body->transform, body->cog));
558 apply_impulse(body, impulse, r);
562 cpBodyApplyImpulseAtLocalPoint(cpBody *body, cpVect impulse, cpVect point)
564 cpBodyApplyImpulseAtWorldPoint(body, cpTransformVect(body->transform, impulse), cpTransformPoint(body->transform, point));
568 cpBodyGetVelocityAtLocalPoint(const cpBody *body, cpVect point)
570 cpVect r = cpTransformVect(body->transform, cpvsub(point, body->cog));
571 return cpvadd(body->v, cpvmult(cpvperp(r), body->w));
575 cpBodyGetVelocityAtWorldPoint(const cpBody *body, cpVect point)
577 cpVect r = cpvsub(point, cpTransformPoint(body->transform, body->cog));
578 return cpvadd(body->v, cpvmult(cpvperp(r), body->w));
582 cpBodyKineticEnergy(const cpBody *body)
584 // Need to do some fudging to avoid NaNs
585 cpFloat vsq = cpvdot(body->v, body->v);
586 cpFloat wsq = body->w*body->w;
587 return (vsq ? vsq*body->m : 0.0f) + (wsq ? wsq*body->i : 0.0f);
591 cpBodyEachShape(cpBody *body, cpBodyShapeIteratorFunc func, void *data)
593 cpShape *shape = body->shapeList;
595 cpShape *next = shape->next;
596 func(body, shape, data);
602 cpBodyEachConstraint(cpBody *body, cpBodyConstraintIteratorFunc func, void *data)
604 cpConstraint *constraint = body->constraintList;
606 cpConstraint *next = cpConstraintNext(constraint, body);
607 func(body, constraint, data);
613 cpBodyEachArbiter(cpBody *body, cpBodyArbiterIteratorFunc func, void *data)
615 cpArbiter *arb = body->arbiterList;
617 cpArbiter *next = cpArbiterNext(arb, body);
619 cpBool swapped = arb->swapped; {
620 arb->swapped = (body == arb->body_b);
621 func(body, arb, data);
622 } arb->swapped = swapped;