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 cpBodyIsSleepThresholdExceeded(const cpBody *body, const cpShape *shape)
139 return body->sleeping.idleTime > shape->space->sleepTimeThreshold;
143 cpBodyGetType(cpBody *body)
145 if(body->sleeping.idleTime == INFINITY){
146 return CP_BODY_TYPE_STATIC;
147 } else if(body->m == INFINITY){
148 return CP_BODY_TYPE_KINEMATIC;
150 return CP_BODY_TYPE_DYNAMIC;
155 cpBodySetType(cpBody *body, cpBodyType type)
157 cpBodyType oldType = cpBodyGetType(body);
158 if(oldType == type) return;
160 // Static bodies have their idle timers set to infinity.
161 // Non-static bodies should have their idle timer reset.
162 body->sleeping.idleTime = (type == CP_BODY_TYPE_STATIC ? INFINITY : 0.0f);
164 if(type == CP_BODY_TYPE_DYNAMIC){
165 body->m = body->i = 0.0f;
166 body->m_inv = body->i_inv = INFINITY;
168 cpBodyAccumulateMassFromShapes(body);
170 body->m = body->i = INFINITY;
171 body->m_inv = body->i_inv = 0.0f;
177 // If the body is added to a space already, we'll need to update some space data structures.
178 cpSpace *space = cpBodyGetSpace(body);
180 cpAssertSpaceUnlocked(space);
182 if(oldType == CP_BODY_TYPE_STATIC){
183 // TODO This is probably not necessary
184 // cpBodyActivateStatic(body, NULL);
186 cpBodyActivate(body);
189 // Move the bodies to the correct array.
190 cpArray *fromArray = cpSpaceArrayForBodyType(space, oldType);
191 cpArray *toArray = cpSpaceArrayForBodyType(space, type);
192 if(fromArray != toArray){
193 cpArrayDeleteObj(fromArray, body);
194 cpArrayPush(toArray, body);
197 // Move the body's shapes to the correct spatial index.
198 cpSpatialIndex *fromIndex = (oldType == CP_BODY_TYPE_STATIC ? space->staticShapes : space->dynamicShapes);
199 cpSpatialIndex *toIndex = (type == CP_BODY_TYPE_STATIC ? space->staticShapes : space->dynamicShapes);
200 if(fromIndex != toIndex){
201 CP_BODY_FOREACH_SHAPE(body, shape){
202 cpSpatialIndexRemove(fromIndex, shape, shape->hashid);
203 cpSpatialIndexInsert(toIndex, shape, shape->hashid);
211 // Should *only* be called when shapes with mass info are modified, added or removed.
213 cpBodyAccumulateMassFromShapes(cpBody *body)
215 if(body == NULL || cpBodyGetType(body) != CP_BODY_TYPE_DYNAMIC) return;
217 // Reset the body's mass data.
218 body->m = body->i = 0.0f;
221 // Cache the position to realign it at the end.
222 cpVect pos = cpBodyGetPosition(body);
224 // Accumulate mass from shapes.
225 CP_BODY_FOREACH_SHAPE(body, shape){
226 struct cpShapeMassInfo *info = &shape->massInfo;
230 cpFloat msum = body->m + m;
232 body->i += m*info->i + cpvdistsq(body->cog, info->cog)*(m*body->m)/msum;
233 body->cog = cpvlerp(body->cog, info->cog, m/msum);
238 // Recalculate the inverses.
239 body->m_inv = 1.0f/body->m;
240 body->i_inv = 1.0f/body->i;
242 // Realign the body since the CoG has probably moved.
243 cpBodySetPosition(body, pos);
244 cpAssertSaneBody(body);
248 cpBodyGetSpace(const cpBody *body)
254 cpBodyGetMass(const cpBody *body)
260 cpBodySetMass(cpBody *body, cpFloat mass)
262 cpAssertHard(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC, "You cannot set the mass of kinematic or static bodies.");
263 cpAssertHard(0.0f <= mass && mass < INFINITY, "Mass must be positive and finite.");
265 cpBodyActivate(body);
267 body->m_inv = mass == 0.0f ? INFINITY : 1.0f/mass;
268 cpAssertSaneBody(body);
272 cpBodyGetMoment(const cpBody *body)
278 cpBodySetMoment(cpBody *body, cpFloat moment)
280 cpAssertHard(moment >= 0.0f, "Moment of Inertia must be positive.");
282 cpBodyActivate(body);
284 body->i_inv = moment == 0.0f ? INFINITY : 1.0f/moment;
285 cpAssertSaneBody(body);
289 cpBodyGetRotation(const cpBody *body)
291 return cpv(body->transform.a, body->transform.b);
295 cpBodyAddShape(cpBody *body, cpShape *shape)
297 cpShape *next = body->shapeList;
298 if(next) next->prev = shape;
301 body->shapeList = shape;
303 if(shape->massInfo.m > 0.0f){
304 cpBodyAccumulateMassFromShapes(body);
309 cpBodyRemoveShape(cpBody *body, cpShape *shape)
311 cpShape *prev = shape->prev;
312 cpShape *next = shape->next;
317 body->shapeList = next;
327 if(cpBodyGetType(body) == CP_BODY_TYPE_DYNAMIC && shape->massInfo.m > 0.0f){
328 cpBodyAccumulateMassFromShapes(body);
332 static cpConstraint *
333 filterConstraints(cpConstraint *node, cpBody *body, cpConstraint *filter)
336 return cpConstraintNext(node, body);
337 } else if(node->a == body){
338 node->next_a = filterConstraints(node->next_a, body, filter);
340 node->next_b = filterConstraints(node->next_b, body, filter);
347 cpBodyRemoveConstraint(cpBody *body, cpConstraint *constraint)
349 body->constraintList = filterConstraints(body->constraintList, body, constraint);
352 // 'p' is the position of the CoG
354 SetTransform(cpBody *body, cpVect p, cpFloat a)
356 cpVect rot = cpvforangle(a);
357 cpVect c = body->cog;
359 body->transform = cpTransformNewTranspose(
360 rot.x, -rot.y, p.x - (c.x*rot.x - c.y*rot.y),
361 rot.y, rot.x, p.y - (c.x*rot.y + c.y*rot.x)
365 static inline cpFloat
366 SetAngle(cpBody *body, cpFloat a)
369 cpAssertSaneBody(body);
375 cpBodyGetPosition(const cpBody *body)
377 return cpTransformPoint(body->transform, cpvzero);
381 cpBodySetPosition(cpBody *body, cpVect position)
383 cpBodyActivate(body);
384 cpVect p = body->p = cpvadd(cpTransformVect(body->transform, body->cog), position);
385 cpAssertSaneBody(body);
387 SetTransform(body, p, body->a);
391 cpBodyGetCenterOfGravity(const cpBody *body)
397 cpBodySetCenterOfGravity(cpBody *body, cpVect cog)
399 cpBodyActivate(body);
401 cpAssertSaneBody(body);
405 cpBodyGetVelocity(const cpBody *body)
411 cpBodySetVelocity(cpBody *body, cpVect velocity)
413 cpBodyActivate(body);
415 cpAssertSaneBody(body);
419 cpBodyGetForce(const cpBody *body)
425 cpBodySetForce(cpBody *body, cpVect force)
427 cpBodyActivate(body);
429 cpAssertSaneBody(body);
433 cpBodyGetAngle(const cpBody *body)
439 cpBodySetAngle(cpBody *body, cpFloat angle)
441 cpBodyActivate(body);
442 SetAngle(body, angle);
444 SetTransform(body, body->p, angle);
448 cpBodyGetAngularVelocity(const cpBody *body)
454 cpBodySetAngularVelocity(cpBody *body, cpFloat angularVelocity)
456 cpBodyActivate(body);
457 body->w = angularVelocity;
458 cpAssertSaneBody(body);
462 cpBodyGetTorque(const cpBody *body)
468 cpBodySetTorque(cpBody *body, cpFloat torque)
470 cpBodyActivate(body);
472 cpAssertSaneBody(body);
476 cpBodyGetUserData(const cpBody *body)
478 return body->userData;
482 cpBodySetUserData(cpBody *body, cpDataPointer userData)
484 body->userData = userData;
488 cpBodySetVelocityUpdateFunc(cpBody *body, cpBodyVelocityFunc velocityFunc)
490 body->velocity_func = velocityFunc;
494 cpBodySetPositionUpdateFunc(cpBody *body, cpBodyPositionFunc positionFunc)
496 body->position_func = positionFunc;
500 cpBodyUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
502 // Skip kinematic bodies.
503 if(cpBodyGetType(body) == CP_BODY_TYPE_KINEMATIC) return;
505 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);
507 body->v = cpvadd(cpvmult(body->v, damping), cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), dt));
508 body->w = body->w*damping + body->t*body->i_inv*dt;
514 cpAssertSaneBody(body);
518 cpBodyUpdatePosition(cpBody *body, cpFloat dt)
520 cpVect p = body->p = cpvadd(body->p, cpvmult(cpvadd(body->v, body->v_bias), dt));
521 cpFloat a = SetAngle(body, body->a + (body->w + body->w_bias)*dt);
522 SetTransform(body, p, a);
524 body->v_bias = cpvzero;
527 cpAssertSaneBody(body);
531 cpBodyLocalToWorld(const cpBody *body, const cpVect point)
533 return cpTransformPoint(body->transform, point);
537 cpBodyWorldToLocal(const cpBody *body, const cpVect point)
539 return cpTransformPoint(cpTransformRigidInverse(body->transform), point);
543 cpBodyApplyForceAtWorldPoint(cpBody *body, cpVect force, cpVect point)
545 cpBodyActivate(body);
546 body->f = cpvadd(body->f, force);
548 cpVect r = cpvsub(point, cpTransformPoint(body->transform, body->cog));
549 body->t += cpvcross(r, force);
553 cpBodyApplyForceAtLocalPoint(cpBody *body, cpVect force, cpVect point)
555 cpBodyApplyForceAtWorldPoint(body, cpTransformVect(body->transform, force), cpTransformPoint(body->transform, point));
559 cpBodyApplyImpulseAtWorldPoint(cpBody *body, cpVect impulse, cpVect point)
561 cpBodyActivate(body);
563 cpVect r = cpvsub(point, cpTransformPoint(body->transform, body->cog));
564 apply_impulse(body, impulse, r);
568 cpBodyApplyImpulseAtLocalPoint(cpBody *body, cpVect impulse, cpVect point)
570 cpBodyApplyImpulseAtWorldPoint(body, cpTransformVect(body->transform, impulse), cpTransformPoint(body->transform, point));
574 cpBodyGetVelocityAtLocalPoint(const cpBody *body, cpVect point)
576 cpVect r = cpTransformVect(body->transform, cpvsub(point, body->cog));
577 return cpvadd(body->v, cpvmult(cpvperp(r), body->w));
581 cpBodyGetVelocityAtWorldPoint(const cpBody *body, cpVect point)
583 cpVect r = cpvsub(point, cpTransformPoint(body->transform, body->cog));
584 return cpvadd(body->v, cpvmult(cpvperp(r), body->w));
588 cpBodyKineticEnergy(const cpBody *body)
590 // Need to do some fudging to avoid NaNs
591 cpFloat vsq = cpvdot(body->v, body->v);
592 cpFloat wsq = body->w*body->w;
593 return (vsq ? vsq*body->m : 0.0f) + (wsq ? wsq*body->i : 0.0f);
597 cpBodyEachShape(cpBody *body, cpBodyShapeIteratorFunc func, void *data)
599 cpShape *shape = body->shapeList;
601 cpShape *next = shape->next;
602 func(body, shape, data);
608 cpBodyEachConstraint(cpBody *body, cpBodyConstraintIteratorFunc func, void *data)
610 cpConstraint *constraint = body->constraintList;
612 cpConstraint *next = cpConstraintNext(constraint, body);
613 func(body, constraint, data);
619 cpBodyEachArbiter(cpBody *body, cpBodyArbiterIteratorFunc func, void *data)
621 cpArbiter *arb = body->arbiterList;
623 cpArbiter *next = cpArbiterNext(arb, body);
625 cpBool swapped = arb->swapped; {
626 arb->swapped = (body == arb->body_b);
627 func(body, arb, data);
628 } arb->swapped = swapped;