This commit is contained in:
Ming 2010-09-13 03:09:23 +00:00
parent 40b6d8500a
commit 7ac911f120
32 changed files with 148 additions and 5398 deletions

View File

@ -1,124 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
static void
update(int ticks)
{
int steps = 3;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static void
add_box()
{
const cpFloat size = 10.0f;
const cpFloat mass = 1.0f;
cpVect verts[] = {
cpv(-size,-size),
cpv(-size, size),
cpv( size, size),
cpv( size,-size),
};
cpFloat radius = cpvlength(cpv(size, size));
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts, cpvzero)));
body->p = cpv(frand()*(640 - 2*radius) - (320 - radius), frand()*(480 - 2*radius) - (240 - radius));
body->v = cpvmult(cpv(2*frand() - 1, 2*frand() - 1), 200);
cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 4, verts, cpvzero));
shape->e = 1.0f; shape->u = 0.0f;
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
cpSpaceResizeActiveHash(space, 30.0f, 1000);
space->iterations = 10;
cpShape *shape;
// Create segments around the edge of the screen.
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
for(int i=0; i<10; i++)
add_box();
cpBody *body = cpSpaceAddBody(space, cpBodyNew(100.0f, 10000.0f));
shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, cpv(-75,0), cpv(75,0), 5.0f));
shape->e = 1.0f; shape->u = 1.0f;
cpSpaceAddConstraint(space, cpPivotJointNew2(body, staticBody, cpvzero, cpvzero));
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Bounce = {
"Bounce",
NULL,
init,
update,
destroy,
};

View File

@ -1,48 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
struct chipmunkDemo;
typedef cpSpace *(*demoInitFunc)(void);
typedef void (*demoUpdateFunc)(int ticks);
typedef void (*demoDestroyFunc)(void);
typedef struct chipmunkDemo {
char *name;
drawSpaceOptions *drawOptions;
demoInitFunc initFunc;
demoUpdateFunc updateFunc;
demoDestroyFunc destroyFunc;
} chipmunkDemo;
static inline cpFloat
frand(void)
{
return (cpFloat)rand()/(cpFloat)RAND_MAX;
}
extern cpVect arrowDirection;
extern char messageString[1024];
#define GRABABLE_MASK_BIT (1<<31)
#define NOT_GRABABLE_MASK (~GRABABLE_MASK_BIT)

View File

@ -1,296 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
static cpBody *
addBall(cpVect pos, cpVect boxOffset)
{
cpFloat radius = 15.0f;
cpFloat mass = 1.0f;
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero)));
body->p = cpvadd(pos, boxOffset);
cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero));
shape->e = 0.0f; shape->u = 0.7f;
return body;
}
static cpBody *
addLever(cpVect pos, cpVect boxOffset)
{
cpFloat mass = 1.0f;
cpVect a = cpv(0, 15);
cpVect b = cpv(0, -15);
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b)));
body->p = cpvadd(pos, cpvadd(boxOffset, cpv(0, -15)));
cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f));
shape->e = 0.0f; shape->u = 0.7f;
return body;
}
static cpBody *
addBar(cpVect pos, cpVect boxOffset)
{
cpFloat mass = 2.0f;
cpVect a = cpv(0, 30);
cpVect b = cpv(0, -30);
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b)));
body->p = cpvadd(pos, boxOffset);
cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 5.0f));
shape->e = 0.0f; shape->u = 0.7f;
return body;
}
static cpBody *
addWheel(cpVect pos, cpVect boxOffset)
{
cpFloat radius = 15.0f;
cpFloat mass = 1.0f;
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero)));
body->p = cpvadd(pos, boxOffset);
cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero));
shape->e = 0.0f; shape->u = 0.7f;
shape->group = 1; // use a group to keep the car parts from colliding
return body;
}
static cpBody *
addChassis(cpVect pos, cpVect boxOffset)
{
int num = 4;
cpVect verts[] = {
cpv(-40,-15),
cpv(-40, 15),
cpv( 40, 15),
cpv( 40,-15),
};
cpFloat mass = 5.0f;
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, num, verts, cpvzero)));
body->p = cpvadd(pos, boxOffset);
cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, num, verts, cpvzero));
shape->e = 0.0f; shape->u = 0.7f;
shape->group = 1; // use a group to keep the car parts from colliding
return body;
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
space = cpSpaceNew();
space->iterations = 10;
space->gravity = cpv(0, -100);
cpShape *shape;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,120), cpv(320,120), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,0), cpv(320,0), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-120), cpv(320,-120), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-160,-240), cpv(-160,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(0,-240), cpv(0,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(160,-240), cpv(160,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
cpVect boxOffset;
cpBody *body1, *body2;
cpVect posA = cpv( 50, 60);
cpVect posB = cpv(110, 60);
#define POS_A cpvadd(boxOffset, posA)
#define POS_B cpvadd(boxOffset, posB)
// Pin Joints - Link shapes with a solid bar or pin.
// Keeps the anchor points the same distance apart from when the joint was created.
boxOffset = cpv(-320, -240);
body1 = addBall(posA, boxOffset);
body2 = addBall(posB, boxOffset);
cpSpaceAddConstraint(space, cpPinJointNew(body1, body2, cpv(15,0), cpv(-15,0)));
// Slide Joints - Like pin joints but with a min/max distance.
// Can be used for a cheap approximation of a rope.
boxOffset = cpv(-160, -240);
body1 = addBall(posA, boxOffset);
body2 = addBall(posB, boxOffset);
cpSpaceAddConstraint(space, cpSlideJointNew(body1, body2, cpv(15,0), cpv(-15,0), 20.0f, 40.0f));
// Pivot Joints - Holds the two anchor points together. Like a swivel.
boxOffset = cpv(0, -240);
body1 = addBall(posA, boxOffset);
body2 = addBall(posB, boxOffset);
cpSpaceAddConstraint(space, cpPivotJointNew(body1, body2, cpvadd(boxOffset, cpv(80,60))));
// cpPivotJointNew() takes it's anchor parameter in world coordinates. The anchors are calculated from that
// cpPivotJointNew2() lets you specify the two anchor points explicitly
// Groove Joints - Like a pivot joint, but one of the anchors is a line segment that the pivot can slide in
boxOffset = cpv(160, -240);
body1 = addBall(posA, boxOffset);
body2 = addBall(posB, boxOffset);
cpSpaceAddConstraint(space, cpGrooveJointNew(body1, body2, cpv(30,30), cpv(30,-30), cpv(-30,0)));
// Damped Springs
boxOffset = cpv(-320, -120);
body1 = addBall(posA, boxOffset);
body2 = addBall(posB, boxOffset);
cpSpaceAddConstraint(space, cpDampedSpringNew(body1, body2, cpv(15,0), cpv(-15,0), 20.0f, 5.0f, 0.3f));
// Damped Rotary Springs
boxOffset = cpv(-160, -120);
body1 = addBar(posA, boxOffset);
body2 = addBar(posB, boxOffset);
// Add some pin joints to hold the circles in place.
cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A));
cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B));
cpSpaceAddConstraint(space, cpDampedRotarySpringNew(body1, body2, 0.0f, 3000.0f, 60.0f));
// Rotary Limit Joint
boxOffset = cpv(0, -120);
body1 = addLever(posA, boxOffset);
body2 = addLever(posB, boxOffset);
// Add some pin joints to hold the circles in place.
cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A));
cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B));
// Hold their rotation within 90 degrees of each other.
cpSpaceAddConstraint(space, cpRotaryLimitJointNew(body1, body2, -(cpFloat)M_PI_2, (cpFloat)M_PI_2));
// Ratchet Joint - A rotary ratchet, like a socket wrench
boxOffset = cpv(160, -120);
body1 = addLever(posA, boxOffset);
body2 = addLever(posB, boxOffset);
// Add some pin joints to hold the circles in place.
cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A));
cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B));
// Ratchet every 90 degrees
cpSpaceAddConstraint(space, cpRatchetJointNew(body1, body2, 0.0f, (cpFloat)M_PI_2));
// Gear Joint - Maintain a specific angular velocity ratio
boxOffset = cpv(-320, 0);
body1 = addBar(posA, boxOffset);
body2 = addBar(posB, boxOffset);
// Add some pin joints to hold the circles in place.
cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A));
cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B));
// Force one to sping 2x as fast as the other
cpSpaceAddConstraint(space, cpGearJointNew(body1, body2, 0.0f, 2.0f));
// Simple Motor - Maintain a specific angular relative velocity
boxOffset = cpv(-160, 0);
body1 = addBar(posA, boxOffset);
body2 = addBar(posB, boxOffset);
// Add some pin joints to hold the circles in place.
cpSpaceAddConstraint(space, cpPivotJointNew(body1, staticBody, POS_A));
cpSpaceAddConstraint(space, cpPivotJointNew(body2, staticBody, POS_B));
// Make them spin at 1/2 revolution per second in relation to each other.
cpSpaceAddConstraint(space, cpSimpleMotorNew(body1, body2, (cpFloat)M_PI));
// Make a car with some nice soft suspension
boxOffset = cpv(0, 0);
cpBody *wheel1 = addWheel(posA, boxOffset);
cpBody *wheel2 = addWheel(posB, boxOffset);
cpBody *chassis = addChassis(cpv(80, 100), boxOffset);
cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel1, cpv(-30, -10), cpv(-30, -40), cpvzero));
cpSpaceAddConstraint(space, cpGrooveJointNew(chassis, wheel2, cpv( 30, -10), cpv( 30, -40), cpvzero));
cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel1, cpv(-30, 0), cpvzero, 50.0f, 20.0f, 1.5f));
cpSpaceAddConstraint(space, cpDampedSpringNew(chassis, wheel2, cpv( 30, 0), cpvzero, 50.0f, 20.0f, 1.5f));
return space;
}
static void
update(int ticks)
{
cpSpaceStep(space, 1.0f/60.0f);
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Joints = {
"Joints and Constraints",
NULL,
init,
update,
destroy,
};

View File

@ -1,152 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static const int image_width = 188;
static const int image_height = 35;
static const int image_row_length = 24;
static const unsigned char image_bitmap[] = {
15,-16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-64,15,63,-32,-2,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,31,-64,15,127,-125,-1,-128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,127,-64,15,127,15,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-2,
31,-1,-64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-1,-64,0,-4,63,-1,-32,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,1,-1,-64,15,-8,127,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,-1,-64,0,-8,-15,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,-31,-1,-64,15,-8,-32,
-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,7,-15,-1,-64,9,-15,-32,-1,-32,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,31,-15,-1,-64,0,-15,-32,-1,-32,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,63,-7,-1,-64,9,-29,-32,127,-61,-16,63,15,-61,-1,-8,31,-16,15,-8,126,7,-31,
-8,31,-65,-7,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13,
-4,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-2,63,-8,31,-4,-1,15,-13,
-2,63,-1,-3,-1,-64,9,-29,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13,
-2,63,-33,-1,-1,-32,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13,
-1,63,-33,-1,-1,-16,9,-25,-32,0,7,-8,127,-97,-25,-1,-1,63,-4,63,-4,-1,15,-13,
-1,63,-49,-1,-1,-8,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13,
-1,-65,-49,-1,-1,-4,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13,
-1,-65,-57,-1,-1,-2,9,-57,-32,0,7,-8,127,-97,-25,-8,-1,63,-2,127,-4,-1,15,-13,
-1,-1,-57,-1,-1,-1,9,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1,
-1,-61,-1,-1,-1,-119,-57,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1,
-1,-61,-1,-1,-1,-55,-49,-32,0,7,-1,-1,-97,-25,-8,-1,63,-1,-1,-4,-1,15,-13,-1,
-1,-63,-1,-1,-1,-23,-49,-32,127,-57,-1,-1,-97,-25,-1,-1,63,-1,-1,-4,-1,15,-13,
-1,-1,-63,-1,-1,-1,-16,-49,-32,-1,-25,-1,-1,-97,-25,-1,-1,63,-33,-5,-4,-1,15,
-13,-1,-1,-64,-1,-9,-1,-7,-49,-32,-1,-25,-8,127,-97,-25,-1,-1,63,-33,-5,-4,-1,
15,-13,-1,-1,-64,-1,-13,-1,-32,-49,-32,-1,-25,-8,127,-97,-25,-1,-2,63,-49,-13,
-4,-1,15,-13,-1,-1,-64,127,-7,-1,-119,-17,-15,-1,-25,-8,127,-97,-25,-1,-2,63,
-49,-13,-4,-1,15,-13,-3,-1,-64,127,-8,-2,15,-17,-1,-1,-25,-8,127,-97,-25,-1,
-8,63,-49,-13,-4,-1,15,-13,-3,-1,-64,63,-4,120,0,-17,-1,-1,-25,-8,127,-97,-25,
-8,0,63,-57,-29,-4,-1,15,-13,-4,-1,-64,63,-4,0,15,-17,-1,-1,-25,-8,127,-97,
-25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,-1,-64,31,-2,0,0,103,-1,-1,-57,-8,127,-97,
-25,-8,0,63,-57,-29,-4,-1,-1,-13,-4,127,-64,31,-2,0,15,103,-1,-1,-57,-8,127,
-97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,127,-64,15,-8,0,0,55,-1,-1,-121,-8,
127,-97,-25,-8,0,63,-61,-61,-4,127,-1,-29,-4,63,-64,15,-32,0,0,23,-1,-2,3,-16,
63,15,-61,-16,0,31,-127,-127,-8,31,-1,-127,-8,31,-128,7,-128,0,0
};
static inline int
get_pixel(int x, int y)
{
return (image_bitmap[(x>>3) + y*image_row_length]>>(~x&0x7)) & 1;
}
static cpSpace *space;
static void
update(int ticks)
{
int steps = 1;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static cpShape *
make_ball(cpFloat x, cpFloat y)
{
cpBody *body = cpBodyNew(1.0f, INFINITY);
body->p = cpv(x, y);
cpShape *shape = cpCircleShapeNew(body, 0.95f, cpvzero);
shape->e = 0.0f; shape->u = 0.0f;
return shape;
}
static cpSpace *
init(void)
{
space = cpSpaceNew();
cpSpaceResizeActiveHash(space, 2.0f, 10000);
space->iterations = 1;
cpBody *body;
cpShape *shape;
for(int y=0; y<image_height; y++){
for(int x=0; x<image_width; x++){
if(!get_pixel(x, y)) continue;
cpFloat x_jitter = 0.05f*frand();
cpFloat y_jitter = 0.05f*frand();
shape = make_ball(2*(x - image_width/2 + x_jitter), 2*(image_height/2 - y + y_jitter));
cpSpaceAddBody(space, shape->body);
cpSpaceAddShape(space, shape);
}
}
body = cpSpaceAddBody(space, cpBodyNew(INFINITY, INFINITY));
body->p = cpv(-1000.0f, -10.0f);
body->v = cpv(400.0f, 0.0f);
shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 8.0f, cpvzero));
shape->e = 0.0f; shape->u = 0.0f;
shape->layers = NOT_GRABABLE_MASK;
return space;
}
static void
destroy(void)
{
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
drawSpaceOptions draw_options = {
0, 0, 0, 2.0f, 3.0f, 0.0f,
};
chipmunkDemo LogoSmash = {
"Logo Smash",
&draw_options,
init,
update,
destroy,
};

View File

@ -1,506 +0,0 @@
// This Demo was written by Juan Pablo Carbajal. Nov 2008.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <string.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
#define WIDTH 600
#define HEIGHT 400
#define SINGMAX 10 // Maximum number of singularities per body
#define NMAG 10 // Number of magnets
#define NCHG 10 // Number of charged bodies
#define NMIX 10 // Number of charged magnets
#define COU_MKS 8.987551787e9 // Some physical constants
#define MAG_MKS 1e-7
// Prototypes
struct DataforForce;
typedef void (*SingForceFunc)(struct DataforForce* data);
// Structures
// Singularities
typedef struct ActorSingularity{
// Number of singularities
int Nsing;
// Value of the singularities
cpFloat value[SINGMAX];
// Type of the singularities
char type[SINGMAX][100];
// Global position of the singularities
cpVect Gpos[SINGMAX];
// Local position of the singularities
cpVect position[SINGMAX];
// Angle of the singularities measured in the body axes
cpFloat angle[SINGMAX];
// Angle of the singularities measured from x
cpFloat Gangle[SINGMAX];
// Force function
SingForceFunc force_func[SINGMAX];
// Force function
SingForceFunc torque_func[SINGMAX];
}Sing;
// Data for the force functions
typedef struct DataforForce{
//Everything in global coordinates
// Position of the source
cpVect p0;
// Observed position
cpVect p;
// Relative position source-observed
cpVect relp;
// distance, disntace^2, ditance ^3
cpFloat r[3];
// angle of the source
cpFloat ang0;
// angle of the observed singularity
cpFloat ang;
// Foce value
cpVect F;
// Torque value
cpFloat T;
}ForceData;
// Global Varibales
static cpSpace *space;
static cpBody *staticBody;
// **** Forces ****** //
// Calculate the forces between two bodies. all this functions requieres
// a pointer to an structure with the necessary fields.
// forces between charges
static void
CoulombForce(ForceData* data){
data->F=cpvmult(cpvnormalize(data->relp),(cpFloat)COU_MKS/data->r[1]);
}
// forces between magnets
static void
MagDipoleForce(ForceData* data){
static cpFloat phi,alpha,beta,Fr,Fphi;
// Angle of the relative position vector
phi=cpvtoangle(data->relp);
alpha=data->ang0;
beta=data->ang;
alpha =phi - alpha;
beta = phi - beta;
// Components in polar coordinates
Fr=((cpFloat)2.0e0*cpfcos(alpha)*cpfcos(beta) - cpfsin(alpha)*cpfsin(beta));
Fphi=cpfsin(alpha+beta);
// printf("%g %g %g %g %g\n",phi,alpha,beta,Fphi);
// Cartesian coordinates
data->F=cpv(Fr*cpfcos(phi)-Fphi*cpfsin(phi),Fr*cpfsin(phi)+Fphi*cpfcos(phi));
data->F=cpvmult(data->F,(cpFloat)-3.e0*(cpFloat)MAG_MKS/(data->r[1]*data->r[1]));
}
static void
MagDipoleTorque(ForceData* data){
static cpFloat phi,alpha,beta;
phi=cpvtoangle(data->relp);
alpha=data->ang0;
beta=data->ang;
alpha =phi - alpha;
beta = phi - beta;
// Torque. Though we could use a component of F to save some space,
// we use another variables for the sake of clarity.
data->T=((cpFloat)MAG_MKS/data->r[2])*((cpFloat)3.0e0*cpfcos(alpha)*cpfsin(beta) + cpfsin(alpha-beta));
}
// ******* //
// This function fills the data structure for the force functions
// The structure Sing has the information about the singularity (charge or magnet)
static void
FillForceData(Sing* source,int inds, Sing* obs,int indo, ForceData* data)
{
// Global Position and orientation of the source singularity
data->p0=source->Gpos[inds];
data->ang0=source->Gangle[inds];
// Global Position and orientation of the observed singularity
data->p=obs->Gpos[indo];
data->ang=obs->Gangle[indo];
// Derived magnitudes
data->relp=cpvsub(data->p,data->p0); //Relative position
data->r[0]=cpvlength(data->relp); // Distance
data->r[1]=cpvlengthsq(data->relp); // Square Distance
data->r[2]=data->r[0]*data->r[1]; // Cubic distance
source->force_func[inds](data); // The value of the force
data->F= cpvmult(data->F,source->value[inds]*obs->value[indo]);
}
// Calculation of the interaction
static void
LRangeForceApply(cpBody *a, cpBody *b){
Sing* aux = (Sing*)a->data;
Sing* aux2 = (Sing*)b->data;
cpVect delta;
// General data needed to calculate interaction
static ForceData fdata;
fdata.F=cpvzero;
// Calculate the forces between the charges of different bodies
for (int i=0; i<aux->Nsing; i++)
{
for (int j=0; j<aux2->Nsing; j++)
{
if(!strcmp(aux->type[i],aux2->type[j]))
{
//printf("%s %s\n",aux->type[i],aux2->type[j]);
FillForceData (aux2,j,aux,i,&fdata);
//Force applied to body A
delta=cpvsub(aux->Gpos[i], a->p);
cpBodyApplyForce(a,fdata.F, delta);
if(aux->torque_func[i] != NULL)
{
//Torque on A
aux->torque_func[i](&fdata);
a->t += aux->value[i]*aux2->value[j]*fdata.T;
}
}
}
}
}
// function for the integration of the positions
// The following functions are variations to the starndrd integration in Chipmunk
// you can go ack to the standard ones by doing the appropiate changes.
static void
ChargedBodyUpdatePositionVerlet(cpBody *body, cpFloat dt)
{
// Long range interaction
cpArray *bodies = space->bodies;
static cpBody* B;
Sing* aux=(Sing*)body->data;
Sing* aux2;
// General data needed to calculate interaction
static ForceData fdata;
fdata.F=cpvzero;
for(int i=0; i< bodies->num; i++)
{
B=(cpBody*)bodies->arr[i];
aux2=(Sing*)B->data;
if(B != body)
{
// Calculate the forces between the singularities of different bodies
LRangeForceApply(body, B);
}
}
cpVect dp = cpvmult(cpvadd(body->v, body->v_bias), dt);
dp = cpvadd(dp,cpvmult(cpvmult(body->f, body->m_inv), (cpFloat)0.5e0*dt*dt));
body->p = cpvadd(body->p, dp);
cpBodySetAngle(body, body->a + (body->w + body->w_bias)*dt
+ 0.5f*body->t*body->i_inv*dt*dt);
// Update position of the singularities
aux = (Sing*)body->data;
for (int i=0; i<aux->Nsing; i++)
{
aux->Gpos[i]=cpvadd(body->p,cpvrotate(cpv(aux->position[i].x,
aux->position[i].y), body->rot));
aux->Gangle[i]= aux->angle[i] + body->a;
}
body->v_bias = cpvzero;
body->w_bias = 0.0f;
}
// function for the integration of the velocities
static void
ChargedBodyUpdateVelocityVerlet(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
{
body->v = cpvadd(body->v, cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), (cpFloat)0.5e0*dt));
body->w = body->w + body->t*body->i_inv*(cpFloat)0.5e0*dt;
body->f = cpvzero;
body->t = 0;
// Long range interaction
cpArray *bodies = space->bodies;
static cpBody* B;
// General data needed to calculate interaction
static ForceData fdata;
fdata.F=cpvzero;
for(int i=0; i< bodies->num; i++)
{
B=(cpBody*)bodies->arr[i];
if(B != body)
{
// Calculate the forces between the singularities of different bodies
LRangeForceApply(body, B);
}
}
body->v = cpvadd(cpvmult(body->v,damping), cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), (cpFloat)0.5e0*dt));
body->w = body->w*damping + body->t*body->i_inv*(cpFloat)0.5e0*dt;
}
static void
update(int ticks)
{
int steps = 10;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
cpArray *bodies = space->bodies;
for(int i=0; i< bodies->num; i++)
cpBodyResetForces((cpBody*)bodies->arr[i]);
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static void
make_mag(cpVect p, cpFloat ang, cpFloat mag)
{
int nverts=6;
cpVect verts[] = {
cpv(-10,-10),
cpv(-10, 10),
cpv( 10, 10),
cpv( 15, 5),
cpv( 15, -5),
cpv( 10,-10)
};
cpBody *body = cpBodyNew(1, cpMomentForPoly(1, nverts, verts, cpvzero));
body->p = p;
body->v = cpvzero;
cpBodySetAngle(body, ang);
body->w = 0;
// Load the singularities
Sing *magnet=(Sing*)cpmalloc(sizeof(Sing));
magnet->Nsing=1;
magnet->value[0]=mag;
sprintf(magnet->type[0],"magdipole");
// The position and angle could be different form the one of the body
magnet->position[0]=cpvzero;
magnet->Gpos[0]=cpvadd(p,magnet->position[0]);
magnet->angle[0]=0.0f;
magnet->Gangle[0]=ang;
magnet->force_func[0]=MagDipoleForce;
magnet->torque_func[0]=MagDipoleTorque;
body->data=magnet;
body->position_func=ChargedBodyUpdatePositionVerlet;
body->velocity_func=ChargedBodyUpdateVelocityVerlet;
cpSpaceAddBody(space, body);
cpShape *shape = cpPolyShapeNew(body, nverts, verts, cpvzero);
shape->e = 0; shape->u = 0.7f;
cpSpaceAddShape(space, shape);
}
static void
make_charged(cpVect p, cpFloat chg)
{
int nverts=4;
cpVect verts[] = {
cpv(-10,-10),
cpv(-10, 10),
cpv( 10, 10),
cpv( 10,-10)
};
cpBody *body = cpBodyNew(1, cpMomentForPoly(1, nverts, verts, cpvzero));
body->p = p;
body->v = cpvzero;
cpBodySetAngle(body, 0);
body->w = 0;
// Load the singularities
Sing *charge=(Sing*)cpmalloc(sizeof(Sing));;
charge->Nsing=1;
charge->value[0]=chg;
sprintf(charge->type[0],"electrical");
// The position and angle could be different form the one of the body
charge->position[0]=cpvzero;
charge->Gpos[0]=cpvadd(p,charge->position[0]);
charge->Gangle[0]=0;
charge->force_func[0]=CoulombForce;
charge->torque_func[0]=NULL;
body->data=charge;
body->position_func=ChargedBodyUpdatePositionVerlet;
body->velocity_func=ChargedBodyUpdateVelocityVerlet;
cpSpaceAddBody(space, body);
cpShape *shape = cpPolyShapeNew(body, nverts, verts, cpvzero);
shape->e = 0; shape->u = 0.7f;
cpSpaceAddShape(space, shape);
}
void
make_mix(cpVect p, cpFloat ang, cpFloat mag,cpFloat chg)
{
int nverts=5;
cpVect verts[] = {
cpv(-10,-10),
cpv(-10, 10),
cpv( 10, 10),
cpv( 20, 0),
cpv( 10,-10)
};
cpBody *body = cpBodyNew(1, cpMomentForPoly(1, nverts, verts, cpvzero));
body->p = p;
body->v = cpvzero;
cpBodySetAngle(body, ang);
body->w = 0;
// Load the singularities
Sing *mix=(Sing*)cpmalloc(sizeof(Sing));;
mix->Nsing=2;
mix->value[0]=mag;
mix->value[1]=chg;
sprintf(mix->type[0],"magdipole");
sprintf(mix->type[1],"electrical");
// The position and angle could be different form the one of the body
mix->position[0]=cpvzero;
mix->Gpos[0]=cpvadd(p,mix->position[0]);
mix->position[1]=cpvzero;
mix->Gpos[1]=cpvadd(p,mix->position[1]);
mix->Gangle[0]=ang;
mix->Gangle[1]=ang;
mix->force_func[0]=MagDipoleForce;
mix->force_func[1]=CoulombForce;
mix->torque_func[0]=MagDipoleTorque;
mix->torque_func[1]=NULL;
body->data=mix;
body->position_func=ChargedBodyUpdatePositionVerlet;
body->velocity_func=ChargedBodyUpdateVelocityVerlet;
cpSpaceAddBody(space, body);
cpShape *shape = cpPolyShapeNew(body, nverts, verts, cpvzero);
shape->e = 0; shape->u = 0.7f;
cpSpaceAddShape(space, shape);
}
static cpSpace*
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->iterations = 5;
space->gravity = cpvzero; //cpv(0,-100);
cpSpaceResizeActiveHash(space, 30, 2999);
// Screen border
/* shape = cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f);
shape->e = 1.0; shape->u = 1.0;
cpSpaceAddStaticShape(space, shape);
shape = cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f);
shape->e = 1.0; shape->u = 1.0;
cpSpaceAddStaticShape(space, shape);
shape = cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f);
shape->e = 1.0; shape->u = 1.0;
cpSpaceAddStaticShape(space, shape);
// Reference line
// Does not collide with other objects, we just want to draw it.
shape = cpSegmentShapeNew(staticBody, cpv(-320,0), cpv(320,0), 0.0f);
shape->collision_type = 1;
cpSpaceAddStaticShape(space, shape);
// Add a collision pair function to filter collisions
cpSpaceAddCollisionPairFunc(space, 0, 1, NULL, NULL);
*/
srand(time(NULL));
cpVect p;
cpFloat ang;
// Create magnets
for(int i=0; i<NMAG; i++)
{
p.x=(2*rand()/((cpFloat)RAND_MAX) - 1)*WIDTH/2.0f;
p.y=(2*rand()/((cpFloat)RAND_MAX) - 1)*HEIGHT/2.0f;
ang=(2*rand()/((cpFloat)RAND_MAX) - 1)*(cpFloat)3.1415;
make_mag(p, ang,(cpFloat)1.0e7);
}
// Create charged objects
for(int i=0; i<NCHG; i++)
{
p.x=(2*rand()/((cpFloat)RAND_MAX) - 1)*WIDTH/2.0f;
p.y=(2*rand()/((cpFloat)RAND_MAX) - 1)*HEIGHT/2.0f;
ang=(2*rand()/((cpFloat)RAND_MAX) - 1)* (cpFloat)3.1415;
make_charged(p,(cpFloat)1.0e-3*cpfpow( (float)-1,(float)(i%2) ));
}
// Create charged magnets objects
for(int i=0; i<NMIX; i++)
{
p.x=(2*rand()/((cpFloat)RAND_MAX) - 1)*WIDTH/2.0f;
p.y=(2*rand()/((cpFloat)RAND_MAX) - 1)*HEIGHT/2.0f;
ang=(2*rand()/((cpFloat)RAND_MAX) - 1)*(cpFloat)3.1415;
make_mix(p, ang,(cpFloat)1.0e7*cpfpow( (float)-1,(float)(i%2) ), (cpFloat)1.0e-3*cpfpow( (float)-1,(float)(i%2)) );
}
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo MagnetsElectric = {
"Magnets and Electric Charges (By: Juan Pablo Carbajal)",
NULL,
init,
update,
destroy,
};

View File

@ -1,152 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
typedef struct OneWayPlatform {
cpVect n; // direction objects may pass through
cpArray *passThruList; // list of objects passing through
} OneWayPlatform;
static OneWayPlatform platformInstance;
static int
preSolve(cpArbiter *arb, cpSpace *space, void *ignore)
{
CP_ARBITER_GET_SHAPES(arb, a, b);
OneWayPlatform *platform = (OneWayPlatform*)(a->data);
if(cpArrayContains(platform->passThruList, b)){
// The object is in the pass thru list, ignore it until separates.
return 0;
} else {
cpFloat dot = cpvdot(cpArbiterGetNormal(arb, 0), platform->n);
if(dot < 0){
// Add the object to the pass thrru list
cpArrayPush(platform->passThruList, b);
return 0;
} else {
return 1;
}
}
}
static void
separate(cpArbiter *arb, cpSpace *space, void *ignore)
{
CP_ARBITER_GET_SHAPES(arb, a, b);
// remove the object from the pass thru list
cpArrayDeleteObj(((OneWayPlatform *)a->data)->passThruList, b);
}
static void
update(int ticks)
{
int steps = 1;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->iterations = 10;
space->gravity = cpv(0, -100);
cpBody *body;
cpShape *shape;
// Create segments around the edge of the screen.
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
// Add our one way segment
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-160,-100), cpv(160,-100), 10.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->collision_type = 1;
shape->layers = NOT_GRABABLE_MASK;
// We'll use the data pointer for the OneWayPlatform struct
platformInstance.n = cpv(0, 1); // let objects pass upwards
platformInstance.passThruList = cpArrayNew(0);
shape->data = &platformInstance;
// Add a ball to make things more interesting
cpFloat radius = 15.0f;
body = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero)));
body->p = cpv(0, -200);
body->v = cpv(0, 170);
shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero));
shape->e = 0.0f; shape->u = 0.9f;
shape->collision_type = 2;
cpSpaceAddCollisionHandler(space, 1, 2, NULL, preSolve, NULL, separate, NULL);
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
cpArrayFree(platformInstance.passThruList);
}
chipmunkDemo OneWay = {
"One Way Platforms",
NULL,
init,
update,
destroy,
};

View File

@ -1,127 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
static void
update(int ticks)
{
int steps = 1;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
// Update the static body spin so that it looks like it's rotating.
cpBodyUpdatePosition(staticBody, dt);
}
}
static void
planetGravityVelocityFunc(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
{
cpVect p = body->p;
cpVect g = cpvmult(p, -50000.0f/cpvdot(p, p));
cpBodyUpdateVelocity(body, g, damping, dt);
}
static cpVect
rand_pos(cpFloat radius)
{
cpVect v;
do {
v = cpv(frand()*(640 - 2*radius) - (320 - radius), frand()*(480 - 2*radius) - (240 - radius));
} while(cpvlength(v) < 100.0f);
return v;
}
static void
add_box()
{
const cpFloat size = 10.0f;
const cpFloat mass = 1.0f;
cpVect verts[] = {
cpv(-size,-size),
cpv(-size, size),
cpv( size, size),
cpv( size,-size),
};
cpFloat radius = cpvlength(cpv(size, size));
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, 4, verts, cpvzero)));
body->velocity_func = planetGravityVelocityFunc;
body->p = rand_pos(radius);
body->v = cpvmult(cpv(2*frand() - 1, 2*frand() - 1), 200);
cpShape *shape = cpSpaceAddShape(space, cpPolyShapeNew(body, 4, verts, cpvzero));
shape->e = 0.0f; shape->u = 0.7f;
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
staticBody->w = 0.2f;
cpResetShapeIdCounter();
space = cpSpaceNew();
cpSpaceResizeActiveHash(space, 30.0f, 10000);
space->iterations = 20;
for(int i=0; i<30; i++)
add_box();
cpShape *shape = cpSpaceAddStaticShape(space, cpCircleShapeNew(staticBody, 70.0f, cpvzero));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Planet = {
"Planet",
NULL,
init,
update,
destroy,
};

View File

@ -1,227 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
typedef struct PlayerStruct {
cpFloat u;
cpShape *shape;
cpVect groundNormal;
cpArray *groundShapes;
} PlayerStruct;
PlayerStruct playerInstance;
static int
begin(cpArbiter *arb, cpSpace *space, void *ignore)
{
CP_ARBITER_GET_SHAPES(arb, a, b);
PlayerStruct *player = (PlayerStruct*)(a->data);
cpVect n = cpvneg(cpArbiterGetNormal(arb, 0));
if(n.y > 0.0f){
cpArrayPush(player->groundShapes, b);
}
return 1;
}
static int
preSolve(cpArbiter *arb, cpSpace *space, void *ignore)
{
CP_ARBITER_GET_SHAPES(arb, a, b);
PlayerStruct *player = (PlayerStruct*)(a->data);
if(arb->stamp > 0){
a->u = player->u;
// pick the most upright jump normal each frame
cpVect n = cpvneg(cpArbiterGetNormal(arb, 0));
if(n.y >= player->groundNormal.y){
player->groundNormal = n;
}
}
return 1;
}
static void
separate(cpArbiter *arb, cpSpace *space, void *ignore)
{
CP_ARBITER_GET_SHAPES(arb, a, b);
PlayerStruct *player = (PlayerStruct*)(a->data);
cpArrayDeleteObj(player->groundShapes, b);
if(player->groundShapes->num == 0){
a->u = 0.0f;
}
}
static void
playerUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt)
{
cpBodyUpdateVelocity(body, gravity, damping, dt);
body->v.y = cpfmax(body->v.y, -700);
body->v.x = cpfclamp(body->v.x, -400, 400);
}
static void
update(int ticks)
{
static int lastJumpState = 0;
int jumpState = (arrowDirection.y > 0.0f);
cpVect groundNormal = playerInstance.groundNormal;
if(groundNormal.y > 0.0f){
playerInstance.shape->surface_v = cpvmult(cpvperp(groundNormal), 400.0f*arrowDirection.x);
} else {
playerInstance.shape->surface_v = cpvzero;
}
cpBody *body = playerInstance.shape->body;
// apply jump
if(jumpState && !lastJumpState && cpvlengthsq(groundNormal)){
// body->v = cpvmult(cpvslerp(groundNormal, cpv(0.0f, 1.0f), 0.5f), 500.0f);
body->v = cpvadd(body->v, cpvmult(cpvslerp(groundNormal, cpv(0.0f, 1.0f), 0.75f), 500.0f));
}
if(playerInstance.groundShapes->num == 0){
cpFloat air_accel = body->v.x + arrowDirection.x*(2000.0f);
body->f.x = body->m*air_accel;
// body->v.x = cpflerpconst(body->v.x, 400.0f*arrowDirection.x, 2000.0f/60.0f);
}
int steps = 3;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
playerInstance.groundNormal = cpvzero;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
lastJumpState = jumpState;
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->iterations = 10;
space->gravity = cpv(0, -1500);
cpBody *body;
cpShape *shape;
// Create segments around the edge of the screen.
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape->collision_type = 2;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape->collision_type = 2;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape->collision_type = 2;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,240), cpv(320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape->collision_type = 2;
// add some other segments to play with
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-220,-200), cpv(-220,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape->collision_type = 2;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(0,-240), cpv(320,-200), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape->collision_type = 2;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(200,-240), cpv(320,-100), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape->collision_type = 2;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-220,-80), cpv(200,-80), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape->collision_type = 2;
// Set up the player
cpFloat radius = 15.0f;
body = cpSpaceAddBody(space, cpBodyNew(10.0f, INFINITY));
body->p = cpv(0, -220);
body->velocity_func = playerUpdateVelocity;
shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero));
shape->e = 0.0f; shape->u = 2.0f;
shape->collision_type = 1;
playerInstance.u = shape->u;
playerInstance.shape = shape;
playerInstance.groundShapes = cpArrayNew(0);
shape->data = &playerInstance;
cpSpaceAddCollisionHandler(space, 1, 2, begin, preSolve, NULL, separate, NULL);
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
cpArrayFree(playerInstance.groundShapes);
}
chipmunkDemo Player = {
"Player",
NULL,
init,
update,
destroy,
};

View File

@ -1,126 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
// Iterate over all of the bodies and reset the ones that have fallen offscreen.
static void
eachBody(cpBody *body, void *unused)
{
if(body->p.y < -260 || fabsf(body->p.x) > 340){
cpFloat x = rand()/(cpFloat)RAND_MAX*640 - 320;
body->p = cpv(x, 260);
}
}
static void
update(int ticks)
{
int steps = 1;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
cpSpaceEachBody(space, &eachBody, NULL);
}
}
#define NUM_VERTS 5
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->iterations = 5;
space->gravity = cpv(0, -100);
cpSpaceResizeStaticHash(space, 40.0f, 999);
cpSpaceResizeActiveHash(space, 30.0f, 2999);
cpBody *body;
cpShape *shape;
// Create vertexes for a pentagon shape.
cpVect verts[NUM_VERTS];
for(int i=0; i<NUM_VERTS; i++){
cpFloat angle = -2*(cpFloat)M_PI*i/((cpFloat) NUM_VERTS);
verts[i] = cpv(10*cpfcos(angle), 10*cpfsin(angle));
}
// Vertexes for a triangle shape.
cpVect tris[] = {
cpv(-15,-15),
cpv( 0, 10),
cpv( 15,-15),
};
// Create the static triangles.
for(int i=0; i<9; i++){
for(int j=0; j<6; j++){
cpFloat stagger = (j%2)*40;
cpVect offset = cpv(i*80 - 320 + stagger, j*70 - 240);
shape = cpSpaceAddStaticShape(space, cpPolyShapeNew(staticBody, 3, tris, offset));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
}
}
// Add lots of pentagons.
for(int i=0; i<300; i++){
body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, NUM_VERTS, verts, cpvzero)));
cpFloat x = rand()/(cpFloat)RAND_MAX*640 - 320;
body->p = cpv(x, 350);
shape = cpSpaceAddShape(space, cpPolyShapeNew(body, NUM_VERTS, verts, cpvzero));
shape->e = 0.0f; shape->u = 0.4f;
}
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Plink = {
"Plink",
NULL,
init,
update,
destroy,
};

View File

@ -1,188 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
static cpConstraint *motor;
#define numBalls 5
static cpBody *balls[numBalls];
static void
update(int ticks)
{
cpFloat coef = (2.0f + arrowDirection.y)/3.0f;
cpFloat rate = arrowDirection.x*30.0f*coef;
cpSimpleMotorSetRate(motor, rate);
motor->maxForce = (rate) ? 1000000.0f : 0.0f;
int steps = 2;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
for(int i=0; i<numBalls; i++){
cpBody *ball = balls[i];
if(ball->p.x > 320.0f){
ball->v = cpvzero;
ball->p = cpv(-224.0f, 200.0f);
}
}
}
}
static cpBody *
add_ball(cpVect pos)
{
cpBody *body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForCircle(1.0f, 30, 0, cpvzero)));
body->p = pos;
cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 30, cpvzero));
shape->e = 0.0f; shape->u = 0.5f;
return body;
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
space = cpSpaceNew();
space->gravity = cpv(0, -600);
cpShape *shape;
// beveling all of the line segments helps prevent things from getting stuck on cracks
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-256,16), cpv(-256,240), 2.0f));
shape->e = 0.0f; shape->u = 0.5f; shape->layers = 1;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-256,16), cpv(-192,0), 2.0f));
shape->e = 0.0f; shape->u = 0.5f; shape->layers = 1;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-192,0), cpv(-192, -64), 2.0f));
shape->e = 0.0f; shape->u = 0.5f; shape->layers = 1;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-128,-64), cpv(-128,144), 2.0f));
shape->e = 0.0f; shape->u = 0.5f; shape->layers = 1;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-192,80), cpv(-192,176), 2.0f));
shape->e = 0.0f; shape->u = 0.5f; shape->layers = 1;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-192,176), cpv(-128,240), 2.0f));
shape->e = 0.0f; shape->u = 0.5f; shape->layers = 1;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-128,144), cpv(192,64), 2.0f));
shape->e = 0.0f; shape->u = 0.5f; shape->layers = 1;
shape->layers = NOT_GRABABLE_MASK;
cpVect verts[] = {
cpv(-30,-80),
cpv(-30, 80),
cpv( 30, 64),
cpv( 30,-80),
};
cpBody *plunger = cpSpaceAddBody(space, cpBodyNew(1.0f, INFINITY));
plunger->p = cpv(-160,-80);
shape = cpSpaceAddShape(space, cpPolyShapeNew(plunger, 4, verts, cpvzero));
shape->e = 1.0f; shape->u = 0.5f; shape->layers = 1;
// add balls to hopper
for(int i=0; i<numBalls; i++)
balls[i] = add_ball(cpv(-224,80 + 64*i));
// add small gear
cpBody *smallGear = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 80, 0, cpvzero)));
smallGear->p = cpv(-160,-160);
cpBodySetAngle(smallGear, (cpFloat)-M_PI_2);
shape = cpSpaceAddShape(space, cpCircleShapeNew(smallGear, 80.0f, cpvzero));
shape->layers = 0;
cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, smallGear, cpv(-160,-160), cpvzero));
// add big gear
cpBody *bigGear = cpSpaceAddBody(space, cpBodyNew(40.0f, cpMomentForCircle(40.0f, 160, 0, cpvzero)));
bigGear->p = cpv(80,-160);
cpBodySetAngle(bigGear, (cpFloat)M_PI_2);
shape = cpSpaceAddShape(space, cpCircleShapeNew(bigGear, 160.0f, cpvzero));
shape->layers = 0;
cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, bigGear, cpv(80,-160), cpvzero));
// connect the plunger to the small gear.
cpSpaceAddConstraint(space, cpPinJointNew(smallGear, plunger, cpv(80,0), cpv(0,0)));
// connect the gears.
cpSpaceAddConstraint(space, cpGearJointNew(smallGear, bigGear, (cpFloat)-M_PI_2, -2.0f));
// feeder mechanism
cpFloat bottom = -300.0f;
cpFloat top = 32.0f;
cpBody *feeder = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForSegment(1.0f, cpv(-224.0f, bottom), cpv(-224.0f, top))));
feeder->p = cpv(-224, (bottom + top)/2.0f);
cpFloat len = top - bottom;
cpSpaceAddShape(space, cpSegmentShapeNew(feeder, cpv(0.0f, len/2.0f), cpv(0.0f, -len/2.0f), 20.0f));
cpSpaceAddConstraint(space, cpPivotJointNew2(staticBody, feeder, cpv(-224.0f, bottom), cpv(0.0f, -len/2.0f)));
cpVect anchr = cpBodyWorld2Local(feeder, cpv(-224.0f, -160.0f));
cpSpaceAddConstraint(space, cpPinJointNew(feeder, smallGear, anchr, cpv(0.0f, 80.0f)));
// motorize the second gear
motor = cpSpaceAddConstraint(space, cpSimpleMotorNew(staticBody, bigGear, 3.0f));
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Pump = {
"Pump",
NULL,
init,
update,
destroy,
};

View File

@ -1,118 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
static void
update(int ticks)
{
int steps = 3;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->iterations = 20;
cpSpaceResizeStaticHash(space, 40.0f, 1000);
cpSpaceResizeActiveHash(space, 40.0f, 1000);
space->gravity = cpv(0, -100);
cpBody *body;
cpShape *shape;
int num = 4;
cpVect verts[] = {
cpv(-15,-15),
cpv(-15, 15),
cpv( 15, 15),
cpv( 15,-15),
};
// Create segments around the edge of the screen.
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
// Add lots of boxes.
for(int i=0; i<14; i++){
for(int j=0; j<=i; j++){
body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero));
body->p = cpv(j*32 - i*16, 300 - i*32);
cpSpaceAddBody(space, body);
shape = cpPolyShapeNew(body, num, verts, cpvzero);
shape->e = 0.0f; shape->u = 0.8f;
cpSpaceAddShape(space, shape);
}
}
// Add a ball to make things more interesting
cpFloat radius = 15.0f;
body = cpSpaceAddBody(space, cpBodyNew(10.0f, cpMomentForCircle(10.0f, 0.0f, radius, cpvzero)));
body->p = cpv(0, -240 + radius+5);
shape = cpSpaceAddShape(space, cpCircleShapeNew(body, radius, cpvzero));
shape->e = 0.0f; shape->u = 0.9f;
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo PyramidStack = {
"Pyramid Stack",
NULL,
init,
update,
destroy,
};

View File

@ -1,141 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
static void
update(int ticks)
{
int steps = 2;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++)
cpSpaceStep(space, dt);
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->iterations = 20;
cpSpaceResizeActiveHash(space, 30.0f, 2999);
cpSpaceResizeStaticHash(space, 30.0f, 999);
space->gravity = cpv(0, -300);
cpBody *body;
cpShape *shape;
// Vertexes for the dominos.
int num = 4;
cpVect verts[] = {
cpv(-3,-20),
cpv(-3, 20),
cpv( 3, 20),
cpv( 3,-20),
};
// Add a floor.
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-600,-240), cpv(600,-240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
// Shared friction constant.
cpFloat u = 0.6f;
// Add the dominoes. Skim over this. It doesn't do anything fancy, and it's hard to follow.
int n = 9;
for(int i=1; i<=n; i++){
cpVect offset = cpv(-i*60/2.0f, (n - i)*52);
for(int j=0; j<i; j++){
body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero)));
body->p = cpvadd(cpv(j*60, -220), offset);
shape = cpSpaceAddShape(space, cpPolyShapeNew(body, num, verts, cpvzero));
shape->e = 0.0f; shape->u = u;
body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero)));
body->p = cpvadd(cpv(j*60, -197), offset);
cpBodySetAngle(body, (cpFloat)M_PI/2.0f);
shape = cpSpaceAddShape(space, cpPolyShapeNew(body, num, verts, cpvzero));
shape->e = 0.0f; shape->u = u;
if(j == (i - 1)) continue;
body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero)));
body->p = cpvadd(cpv(j*60 + 30, -191), offset);
cpBodySetAngle(body, (cpFloat)M_PI/2.0f);
shape = cpSpaceAddShape(space, cpPolyShapeNew(body, num, verts, cpvzero));
shape->e = 0.0f; shape->u = u;
}
body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero)));
body->p = cpvadd(cpv(-17, -174), offset);
shape = cpSpaceAddShape(space, cpPolyShapeNew(body, num, verts, cpvzero));
shape->e = 0.0f; shape->u = u;
body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero)));
body->p = cpvadd(cpv((i - 1)*60 + 17, -174), offset);
shape = cpSpaceAddShape(space, cpPolyShapeNew(body, num, verts, cpvzero));
shape->e = 0.0f; shape->u = u;
}
// Give the last domino a little tap.
// body->w = -1;
// body->v = cpv(-body->w*20, 0);
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo PyramidTopple = {
"Pyramid Topple",
NULL,
init,
update,
destroy,
};

View File

@ -1,158 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
#include "chipmunk_unsafe.h"
extern cpSpace *space;
extern cpBody *staticBody;
extern cpVect mousePoint;
cpShape *querySeg = NULL;
static void
update(int ticks)
{
messageString[0] = '\0';
cpVect start = cpvzero;
cpVect end = /*cpv(0, 85);//*/mousePoint;
cpVect lineEnd = end;
{
char infoString[1024];
sprintf(infoString, "Query: Dist(%f) Point%s, ", cpvdist(start, end), cpvstr(end));
strcat(messageString, infoString);
}
cpSegmentQueryInfo info = {};
if(cpSpaceSegmentQueryFirst(space, start, end, -1, 0, &info)){
cpVect point = cpSegmentQueryHitPoint(start, end, info);
lineEnd = cpvadd(point, cpvzero);//cpvmult(info.n, 4.0f));
char infoString[1024];
sprintf(infoString, "Segment Query: Dist(%f) Normal%s", cpSegmentQueryHitDist(start, end, info), cpvstr(info.n));
strcat(messageString, infoString);
} else {
strcat(messageString, "Segment Query (None)");
}
cpSegmentShapeSetEndpoints(querySeg, cpvzero, lineEnd);
// normal other stuff.
int steps = 1;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->elasticIterations = 0;
space->iterations = 5;
cpSpaceResizeStaticHash(space, 40.0f, 999);
cpSpaceResizeActiveHash(space, 30.0f, 2999);
cpShape *shape;
// add a non-collidable segment as a quick and dirty way to draw the query line
shape = cpSegmentShapeNew(staticBody, cpvzero, cpv(100.0f, 0.0f), 4.0f);
cpSpaceAddStaticShape(space, shape);
shape->layers = 0;
querySeg = shape;
{ // add a fat segment
cpFloat mass = 1.0f;
cpFloat length = 100.0f;
cpVect a = cpv(-length/2.0f, 0.0f), b = cpv(length/2.0f, 0.0f);
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForSegment(mass, a, b)));
body->p = cpv(0.0f, 100.0f);
cpSpaceAddShape(space, cpSegmentShapeNew(body, a, b, 20.0f));
}
{ // add a static segment
cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(0, 300), cpv(300, 0), 0.0f));
}
{ // add a pentagon
cpFloat mass = 1.0f;
const int NUM_VERTS = 5;
cpVect verts[NUM_VERTS];
for(int i=0; i<NUM_VERTS; i++){
cpFloat angle = -2*(cpFloat)M_PI*i/((cpFloat) NUM_VERTS);
verts[i] = cpv(30*cpfcos(angle), 30*cpfsin(angle));
}
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForPoly(mass, NUM_VERTS, verts, cpvzero)));
body->p = cpv(50.0f, 50.0f);
cpSpaceAddShape(space, cpPolyShapeNew(body, NUM_VERTS, verts, cpvzero));
}
{ // add a circle
cpFloat mass = 1.0f;
cpFloat r = 20.0f;
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, r, cpvzero)));
body->p = cpv(100.0f, 100.0f);
cpSpaceAddShape(space, cpCircleShapeNew(body, r, cpvzero));
}
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
const chipmunkDemo Query = {
"Segment Query",
NULL,
init,
update,
destroy,
};

View File

@ -1,165 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
enum {
BALL_TYPE,
BLOCKING_SENSOR_TYPE,
CATCH_SENSOR_TYPE,
} CollisionTypes;
typedef struct Emitter {
int queue;
int blocked;
cpVect position;
} Emitter;
static Emitter emitterInstance;
static int
blockerBegin(cpArbiter *arb, cpSpace *space, void *unused)
{
CP_ARBITER_GET_SHAPES(arb, a, b);
Emitter *emitter = (Emitter*)(a->data);
emitter->blocked++;
return 0; // Return values from sensors callbacks are ignored,
}
static void
blockerSeparate(cpArbiter *arb, cpSpace *space, void *unused)
{
CP_ARBITER_GET_SHAPES(arb, a, b);
Emitter *emitter = (Emitter*)(a->data);
emitter->blocked--;
}
static void
postStepRemove(cpSpace *space, cpShape *shape, void *unused)
{
cpSpaceRemoveBody(space, shape->body);
cpBodyFree(shape->body);
cpSpaceRemoveShape(space, shape);
cpShapeFree(shape);
}
static int
catcherBarBegin(cpArbiter *arb, cpSpace *space, void *unused)
{
cpShape *a, *b; cpArbiterGetShapes(arb, &a, &b);
Emitter *emitter = (Emitter*)(a->data);
emitter->queue++;
cpSpaceAddPostStepCallback(space, (cpPostStepFunc)postStepRemove, b, NULL);
return 0;
}
static cpFloat frand_unit(){return 2.0f*((cpFloat)rand()/(cpFloat)RAND_MAX) - 1.0f;}
static void
update(int ticks)
{
int steps = 1;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
if(!emitterInstance.blocked && emitterInstance.queue){
emitterInstance.queue--;
cpBody *body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForCircle(1.0f, 15.0f, 0.0f, cpvzero)));
body->p = emitterInstance.position;
body->v = cpvmult(cpv(frand_unit(), frand_unit()), 100.0f);
cpShape *shape = cpSpaceAddShape(space, cpCircleShapeNew(body, 15.0f, cpvzero));
shape->collision_type = BALL_TYPE;
}
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->iterations = 10;
space->gravity = cpv(0, -100);
cpShape *shape;
// Data structure for our ball emitter
// We'll use two sensors for it, one to see if the emitter is blocked
// a second to catch the balls and add them back to the emitter
emitterInstance.queue = 5;
emitterInstance.blocked = 0;
emitterInstance.position = cpv(0, 150);
// Create our blocking sensor, so we know when the emitter is clear to emit another ball
shape = cpSpaceAddStaticShape(space, cpCircleShapeNew(staticBody, 15.0f, emitterInstance.position));
shape->sensor = 1;
shape->collision_type = BLOCKING_SENSOR_TYPE;
shape->data = &emitterInstance;
// Create our catch sensor to requeue the balls when they reach the bottom of the screen
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-2000, -200), cpv(2000, -200), 15.0f));
shape->sensor = 1;
shape->collision_type = CATCH_SENSOR_TYPE;
shape->data = &emitterInstance;
cpSpaceAddCollisionHandler(space, BLOCKING_SENSOR_TYPE, BALL_TYPE, blockerBegin, NULL, NULL, blockerSeparate, NULL);
cpSpaceAddCollisionHandler(space, CATCH_SENSOR_TYPE, BALL_TYPE, catcherBarBegin, NULL, NULL, NULL, NULL);
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Sensors = {
"Sensors",
NULL,
init,
update,
destroy,
};

View File

@ -1,115 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
// Init is called by the demo code to set up the demo.
static cpSpace *
init(void)
{
// Create an infinite mass body to attach ground segments and other static geometry to.
// We won't be adding this body to the space, because we don't want it to be simulated at all.
// Adding bodies to the space simulates them. (fall under the influence of gravity, etc)
// We want the static body to stay right where it is at all times.
staticBody = cpBodyNew(INFINITY, INFINITY);
// Create a space, a space is a simulation world. It simulates the motions of rigid bodies,
// handles collisions between them, and simulates the joints between them.
space = cpSpaceNew();
// Lets set some parameters of the space:
// More iterations make the simulation more accurate but slower
space->iterations = 10;
// These parameters tune the efficiency of the collision detection.
// For more info: http://code.google.com/p/chipmunk-physics/wiki/cpSpace
cpSpaceResizeStaticHash(space, 30.0f, 1000);
cpSpaceResizeActiveHash(space, 30.0f, 1000);
// Give it some gravity
space->gravity = cpv(0, -100);
// Create A ground segment along the bottom of the screen
cpShape *ground = cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f);
// Set some parameters of the shape.
// For more info: http://code.google.com/p/chipmunk-physics/wiki/cpShape
ground->e = 1.0f; ground->u = 1.0f;
ground->layers = NOT_GRABABLE_MASK; // Used by the Demo mouse grabbing code
// Add the shape to the space as a static shape
// If a shape never changes position, add it as static so Chipmunk knows it only needs to
// calculate collision information for it once when it is added.
// Do not change the postion of a static shape after adding it.
cpSpaceAddStaticShape(space, ground);
// Add a moving circle object.
cpFloat radius = 15.0f;
cpFloat mass = 10.0f;
// This time we need to give a mass and moment of inertia when creating the circle.
cpBody *ballBody = cpBodyNew(mass, cpMomentForCircle(mass, 0.0f, radius, cpvzero));
// Set some parameters of the body:
// For more info: http://code.google.com/p/chipmunk-physics/wiki/cpBody
ballBody->p = cpv(0, -240 + radius+5);
// Add the body to the space so it will be simulated and move around.
cpSpaceAddBody(space, ballBody);
// Add a circle shape for the ball.
// Shapes are always defined relative to the center of gravity of the body they are attached to.
// When the body moves or rotates, the shape will move with it.
// Additionally, all of the cpSpaceAdd*() functions return the thing they added so you can create and add in one go.
cpShape *ballShape = cpSpaceAddShape(space, cpCircleShapeNew(ballBody, radius, cpvzero));
ballShape->e = 0.0f; ballShape->u = 0.9f;
return space;
}
// Update is called by the demo code each frame.
static void
update(int ticks)
{
// Chipmunk allows you to use a different timestep each frame, but it works much better when you use a fixed timestep.
// An excellent article on why fixed timesteps for game logic can be found here: http://gafferongames.com/game-physics/fix-your-timestep/
cpSpaceStep(space, 1.0f/60.0f);
}
// destroy is called by the demo code to free all the memory we've allocated
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Simple = {
"Simple",
NULL,
init,
update,
destroy,
};

View File

@ -1,175 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
static cpFloat
springForce(cpConstraint *spring, cpFloat dist)
{
cpFloat clamp = 20.0f;
return cpfclamp(cpDampedSpringGetRestLength(spring) - dist, -clamp, clamp)*cpDampedSpringGetStiffness(spring);
}
static cpConstraint *
new_spring(cpBody *a, cpBody *b, cpVect anchr1, cpVect anchr2, cpFloat restLength, cpFloat stiff, cpFloat damp)
{
cpConstraint *spring = cpDampedSpringNew(a, b, anchr1, anchr2, restLength, stiff, damp);
cpDampedSpringSetSpringForceFunc(spring, springForce);
return spring;
}
static void
update(int ticks)
{
int steps = 1;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static cpBody *
add_bar(cpVect a, cpVect b, int group)
{
cpVect center = cpvmult(cpvadd(a, b), 1.0f/2.0f);
cpFloat length = cpvlength(cpvsub(b, a));
cpFloat mass = length/160.0f;
cpBody *body = cpSpaceAddBody(space, cpBodyNew(mass, mass*length*length/12.0f));
body->p = center;
cpShape *shape = cpSpaceAddShape(space, cpSegmentShapeNew(body, cpvsub(a, center), cpvsub(b, center), 10.0f));
shape->group = group;
return body;
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
space = cpSpaceNew();
cpBody *body1 = add_bar(cpv(-240, 160), cpv(-160, 80), 1);
cpBody *body2 = add_bar(cpv(-160, 80), cpv( -80, 160), 1);
cpBody *body3 = add_bar(cpv( 0, 160), cpv( 80, 0), 0);
cpBody *body4 = add_bar(cpv( 160, 160), cpv( 240, 160), 0);
cpBody *body5 = add_bar(cpv(-240, 0), cpv(-160, -80), 2);
cpBody *body6 = add_bar(cpv(-160, -80), cpv( -80, 0), 2);
cpBody *body7 = add_bar(cpv( -80, 0), cpv( 0, 0), 2);
cpBody *body8 = add_bar(cpv( 0, -80), cpv( 80, -80), 0);
cpBody *body9 = add_bar(cpv( 240, 80), cpv( 160, 0), 3);
cpBody *body10 = add_bar(cpv( 160, 0), cpv( 240, -80), 3);
cpBody *body11 = add_bar(cpv(-240, -80), cpv(-160, -160), 4);
cpBody *body12 = add_bar(cpv(-160, -160), cpv( -80, -160), 0);
cpBody *body13 = add_bar(cpv( 0, -160), cpv( 80, -160), 0);
cpBody *body14 = add_bar(cpv( 160, -160), cpv( 240, -160), 0);
cpSpaceAddConstraint(space, cpPivotJointNew2( body1, body2, cpv( 40,-40), cpv(-40,-40)));
cpSpaceAddConstraint(space, cpPivotJointNew2( body5, body6, cpv( 40,-40), cpv(-40,-40)));
cpSpaceAddConstraint(space, cpPivotJointNew2( body6, body7, cpv( 40, 40), cpv(-40, 0)));
cpSpaceAddConstraint(space, cpPivotJointNew2( body9, body10, cpv(-40,-40), cpv(-40, 40)));
cpSpaceAddConstraint(space, cpPivotJointNew2(body11, body12, cpv( 40,-40), cpv(-40, 0)));
cpFloat stiff = 100.0f;
cpFloat damp = 0.5f;
cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 240), cpv(-40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body1, cpv(-160, 240), cpv(-40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv(-160, 240), cpv( 40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body2, cpv( 0, 240), cpv( 40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body3, cpv( 80, 240), cpv(-40, 80), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv( 80, 240), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body4, cpv( 320, 240), cpv( 40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body5, cpv(-320, 80), cpv(-40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body9, cpv( 320, 80), cpv( 40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv( 320, 0), cpv( 40,-40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body10, cpv( 320,-160), cpv( 40,-40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body11, cpv(-320,-160), cpv(-40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv(-240,-240), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body12, cpv( 0,-240), cpv( 40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv( 0,-240), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body13, cpv( 80,-240), cpv( 40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv( 80,-240), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv( 240,-240), cpv( 40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(staticBody, body14, cpv( 320,-160), cpv( 40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body1, body5, cpv( 40,-40), cpv(-40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body1, body6, cpv( 40,-40), cpv( 40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body2, body3, cpv( 40, 40), cpv(-40, 80), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body3, body4, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body3, body4, cpv( 40,-80), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body3, body7, cpv( 40,-80), cpv( 40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body3, body7, cpv(-40, 80), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body3, body8, cpv( 40,-80), cpv( 40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body3, body9, cpv( 40,-80), cpv(-40,-40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body4, body9, cpv( 40, 0), cpv( 40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body5, body11, cpv(-40, 40), cpv(-40, 40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body5, body11, cpv( 40,-40), cpv( 40,-40), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body7, body8, cpv( 40, 0), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body8, body12, cpv(-40, 0), cpv( 40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body8, body13, cpv(-40, 0), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body8, body13, cpv( 40, 0), cpv( 40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring( body8, body14, cpv( 40, 0), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(body10, body14, cpv( 40,-40), cpv(-40, 0), 0.0f, stiff, damp));
cpSpaceAddConstraint(space, new_spring(body10, body14, cpv( 40,-40), cpv(-40, 0), 0.0f, stiff, damp));
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Springies = {
"Springies",
NULL,
init,
update,
destroy,
};

View File

@ -1,181 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* The previous WalkBot demo I designed was fairly disappointing, so I implemented
* the mechanism that Theo Jansen uses in his kinetic sculptures. Brilliant.
* Read more here: http://en.wikipedia.org/wiki/Theo_Jansen
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
static cpConstraint *motor;
static void
update(int ticks)
{
cpFloat coef = (2.0f + arrowDirection.y)/3.0f;
cpFloat rate = arrowDirection.x*10.0f*coef;
cpSimpleMotorSetRate(motor, rate);
motor->maxForce = (rate) ? 100000.0f : 0.0f;
int steps = 3;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static cpFloat seg_radius = 3.0f;
static void
make_leg(cpFloat side, cpFloat offset, cpBody *chassis, cpBody *crank, cpVect anchor)
{
cpVect a, b;
cpShape *shape;
cpFloat leg_mass = 1.0f;
// make leg
a = cpvzero, b = cpv(0.0f, side);
cpBody *upper_leg = cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b));
upper_leg->p = cpv(offset, 0.0f);
cpSpaceAddBody(space, upper_leg);
cpSpaceAddShape(space, cpSegmentShapeNew(upper_leg, a, b, seg_radius));
cpSpaceAddConstraint(space, cpPivotJointNew2(chassis, upper_leg, cpv(offset, 0.0f), cpvzero));
// lower leg
a = cpvzero, b = cpv(0.0f, -1.0f*side);
cpBody *lower_leg = cpBodyNew(leg_mass, cpMomentForSegment(leg_mass, a, b));
lower_leg->p = cpv(offset, -side);
cpSpaceAddBody(space, lower_leg);
shape = cpSegmentShapeNew(lower_leg, a, b, seg_radius);
shape->group = 1;
cpSpaceAddShape(space, shape);
shape = cpCircleShapeNew(lower_leg, seg_radius*2.0f, b);
shape->group = 1;
shape->e = 0.0f; shape->u = 1.0f;
cpSpaceAddShape(space, shape);
cpSpaceAddConstraint(space, cpPinJointNew(chassis, lower_leg, cpv(offset, 0.0f), cpvzero));
cpSpaceAddConstraint(space, cpGearJointNew(upper_leg, lower_leg, 0.0f, 1.0f));
cpConstraint *constraint;
cpFloat diag = sqrtf(side*side + offset*offset);
constraint = cpPinJointNew(crank, upper_leg, anchor, cpv(0.0f, side));
cpPinJointSetDist(constraint, diag);
cpSpaceAddConstraint(space, constraint);
constraint = cpPinJointNew(crank, lower_leg, anchor, cpvzero);
cpPinJointSetDist(constraint, diag);
cpSpaceAddConstraint(space, constraint);
}
static cpSpace *
init(void)
{
space = cpSpaceNew();
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->iterations = 20;
space->gravity = cpv(0,-500);
cpShape *shape;
cpVect a, b;
// Create segments around the edge of the screen.
shape = cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f);
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
cpSpaceAddStaticShape(space, shape);
shape = cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f);
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
cpSpaceAddStaticShape(space, shape);
shape = cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f);
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
cpSpaceAddStaticShape(space, shape);
cpFloat offset = 30.0f;
// make chassis
cpFloat chassis_mass = 2.0f;
a = cpv(-offset, 0.0f), b = cpv(offset, 0.0f);
cpBody *chassis = cpBodyNew(chassis_mass, cpMomentForSegment(chassis_mass, a, b));
cpSpaceAddBody(space, chassis);
shape = cpSegmentShapeNew(chassis, a, b, seg_radius);
shape->group = 1;
cpSpaceAddShape(space, shape);
// make crank
cpFloat crank_mass = 1.0f;
cpFloat crank_radius = 13.0f;
cpBody *crank = cpBodyNew(crank_mass, cpMomentForCircle(crank_mass, crank_radius, 0.0f, cpvzero));
cpSpaceAddBody(space, crank);
shape = cpCircleShapeNew(crank, crank_radius, cpvzero);
shape->group = 1;
cpSpaceAddShape(space, shape);
cpSpaceAddConstraint(space, cpPivotJointNew2(chassis, crank, cpvzero, cpvzero));
cpFloat side = 30.0f;
int num_legs = 2;
for(int i=0; i<num_legs; i++){
make_leg(side, offset, chassis, crank, cpvmult(cpvforangle((cpFloat)(2*i+0)/(cpFloat)num_legs*(cpFloat)M_PI), crank_radius));
make_leg(side, -offset, chassis, crank, cpvmult(cpvforangle((cpFloat)(2*i+1)/(cpFloat)num_legs*(cpFloat)M_PI), crank_radius));
}
motor = cpSimpleMotorNew(chassis, crank, 6.0f);
cpSpaceAddConstraint(space, motor);
return space;
}
static void
destroy(void)
{
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo TheoJansen = {
"Theo Jansen Machine",
NULL,
init,
update,
destroy,
};

View File

@ -1,133 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
static void
update(int ticks)
{
int steps = 3;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
// Manually update the position of the static shape so that
// the box rotates.
cpBodyUpdatePosition(staticBody, dt);
// Because the box was added as a static shape and we moved it
// we need to manually rehash the static spatial hash.
cpSpaceRehashStatic(space);
}
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
cpSpaceResizeActiveHash(space, 40.0f, 999);
cpSpaceResizeStaticHash(space, 40.0f, 99);
space->gravity = cpv(0, -600);
cpBody *body;
cpShape *shape;
// Vertexes for the bricks
int num = 4;
cpVect verts[] = {
cpv(-30,-15),
cpv(-30, 15),
cpv( 30, 15),
cpv( 30,-15),
};
// Set up the static box.
cpVect a = cpv(-200, -200);
cpVect b = cpv(-200, 200);
cpVect c = cpv( 200, 200);
cpVect d = cpv( 200, -200);
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, a, b, 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, b, c, 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, c, d, 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, d, a, 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
// Give the box a little spin.
// Because staticBody is never added to the space, we will need to
// update it ourselves. (see above).
// NOTE: Normally you would want to add the segments as normal and not static shapes.
// I'm just doing it to demonstrate the cpSpaceRehashStatic() function.
staticBody->w = 0.4f;
// Add the bricks.
for(int i=0; i<3; i++){
for(int j=0; j<7; j++){
body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpvzero)));
body->p = cpv(i*60 - 150, j*30 - 150);
shape = cpSpaceAddShape(space, cpPolyShapeNew(body, num, verts, cpvzero));
shape->e = 0.0f; shape->u = 0.7f;
}
}
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo Tumble = {
"Tumble",
NULL,
init,
update,
destroy,
};

View File

@ -1,116 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "chipmunk.h"
#include "chipmunk_unsafe.h"
#include "drawSpace.h"
#include "ChipmunkDemo.h"
static cpSpace *space;
static cpBody *staticBody;
#define NUM_CIRCLES 30
cpShape *circles[NUM_CIRCLES];
cpFloat circleRadius = 30.0f;
static void
update(int ticks)
{
if(arrowDirection.y){
circleRadius = cpfmax(10.0f, circleRadius + arrowDirection.y);
for(int i=0; i<NUM_CIRCLES; i++){
circles[i]->body->m = cpMomentForCircle(1.0f, 0.0f, circleRadius, cpvzero);
cpCircleShapeSetRadius(circles[i], circleRadius);
}
}
int steps = 1;
cpFloat dt = 1.0f/60.0f/(cpFloat)steps;
for(int i=0; i<steps; i++){
cpSpaceStep(space, dt);
}
}
static cpSpace *
init(void)
{
staticBody = cpBodyNew(INFINITY, INFINITY);
cpResetShapeIdCounter();
space = cpSpaceNew();
space->iterations = 5;
space->gravity = cpv(0, -100);
cpSpaceResizeStaticHash(space, 40.0f, 999);
cpSpaceResizeActiveHash(space, 30.0f, 2999);
cpBody *body;
cpShape *shape;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(-320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(320,-240), cpv(320,240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
shape = cpSpaceAddStaticShape(space, cpSegmentShapeNew(staticBody, cpv(-320,-240), cpv(320,-240), 0.0f));
shape->e = 1.0f; shape->u = 1.0f;
shape->layers = NOT_GRABABLE_MASK;
for(int i=0; i<NUM_CIRCLES; i++){
body = cpSpaceAddBody(space, cpBodyNew(1.0f, cpMomentForCircle(1.0f, 0.0f, circleRadius, cpvzero)));
body->p = cpvmult(cpv(frand()*2.0f - 1.0f, frand()*2.0f - 1.0f), circleRadius*5.0f);
circles[i] = shape = cpSpaceAddShape(space, cpCircleShapeNew(body, circleRadius, cpvzero));
shape->e = 0.0f; shape->u = 1.0f;
}
strcat(messageString,
"chipmunk_unsafe.h Contains functions for changing shapes, but they can cause severe stability problems if used incorrectly.\n"
"Shape changes occur as instantaneous changes to position without an accompanying velocity change. USE WITH CAUTION!");
return space;
}
static void
destroy(void)
{
cpBodyFree(staticBody);
cpSpaceFreeChildren(space);
cpSpaceFree(space);
}
chipmunkDemo UnsafeOps = {
"Unsafe Operations",
NULL,
init,
update,
destroy,
};

View File

@ -1,486 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
IMPORTANT - READ ME!
This file sets up a simple interface that the individual demos can use to get
a Chipmunk space running and draw what's in it. In order to keep the Chipmunk
examples clean and simple, they contain no graphics code. All drawing is done
by accessing the Chipmunk structures at a very low level. It is NOT
recommended to write a game or application this way as it does not scale
beyond simple shape drawing and is very dependent on implementation details
about Chipmunk which may change with little to no warning.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include "cocos2d.h"
#include "cocos2dChipmunkDemo.h"
#define SLEEP_TICKS 16
//extern chipmunkDemo Test;
extern chipmunkDemo LogoSmash;
extern chipmunkDemo Simple;
extern chipmunkDemo PyramidStack;
extern chipmunkDemo Plink;
extern chipmunkDemo Tumble;
extern chipmunkDemo PyramidTopple;
extern chipmunkDemo Bounce;
extern chipmunkDemo Planet;
extern chipmunkDemo Springies;
extern chipmunkDemo Pump;
extern chipmunkDemo TheoJansen;
extern chipmunkDemo MagnetsElectric;
extern chipmunkDemo UnsafeOps;
extern chipmunkDemo Query;
extern chipmunkDemo OneWay;
extern chipmunkDemo Player;
extern chipmunkDemo Sensors;
extern chipmunkDemo Joints;
//extern chipmunkDemo Test;
static chipmunkDemo *demos[] = {
&LogoSmash,
&Simple,
&PyramidStack,
&Plink,
&Tumble,
&PyramidTopple,
&Bounce,
&Planet,
&Springies,
&Pump,
&TheoJansen,
&MagnetsElectric,
&UnsafeOps,
// &Query,
&OneWay,
&Player,
&Sensors,
&Joints,
};
static int maxDemos = sizeof(demos) / sizeof(demos[0]);
static const int demoCount = sizeof(demos)/sizeof(chipmunkDemo *);
static chipmunkDemo *currDemo = NULL;
static const int firstDemoIndex = 'a' - 'a';
static int ticks = 0;
static cpSpace *space;
cpVect mousePoint;
cpVect mousePoint_last;
cpBody *mouseBody = NULL;
cpConstraint *mouseJoint = NULL;
char messageString[1024] = {};
int key_up = 0;
int key_down = 0;
int key_left = 0;
int key_right = 0;
cpVect arrowDirection = {};
drawSpaceOptions options = {
0,
0,
1,
4.0f,
0.0f,
1.5f,
};
static void
drawString(int x, int y, char *str)
{
// implement me
}
static void
drawInstructions()
{
drawString(-300, 220,
"Controls:\n"
"A - * Switch demos. (return restarts)\n"
"Use the mouse to grab objects.\n"
"Arrow keys control some demos.\n"
"\\ enables anti-aliasing.\n"
"- toggles spatial hash visualization.\n"
"= toggles bounding boxes."
);
}
static int maxArbiters = 0;
static int maxPoints = 0;
static int maxConstraints = 0;
static void
drawInfo()
{
int arbiters = space->arbiters->num;
int points = 0;
for(int i=0; i<arbiters; i++)
points += ((cpArbiter *)(space->arbiters->arr[i]))->numContacts;
int constraints = (space->constraints->num + points)*(space->iterations + space->elasticIterations);
maxArbiters = arbiters > maxArbiters ? arbiters : maxArbiters;
maxPoints = points > maxPoints ? points : maxPoints;
maxConstraints = constraints > maxConstraints ? constraints : maxConstraints;
char buffer[1000];
char *format =
"Arbiters: %d (%d) - "
"Contact Points: %d (%d)\n"
"Other Constraints: %d, Iterations: %d\n"
"Constraints x Iterations: %d (%d)";
sprintf(buffer, format,
arbiters, maxArbiters,
points, maxPoints,
space->constraints->num, space->iterations + space->elasticIterations,
constraints, maxConstraints
);
drawString(0, 220, buffer);
}
static void
display(void)
{
// glClear(GL_COLOR_BUFFER_BIT);
//
// drawSpace(space, currDemo->drawOptions ? currDemo->drawOptions : &options);
// drawInstructions();
// drawInfo();
// drawString(-300, -210, messageString);
//
// glutSwapBuffers();
ticks++;
cpVect newPoint = cpvlerp(mousePoint_last, mousePoint, 0.25f);
mouseBody->p = newPoint;
mouseBody->v = cpvmult(cpvsub(newPoint, mousePoint_last), 60.0f);
mousePoint_last = newPoint;
currDemo->updateFunc(ticks);
}
static char *
demoTitle(chipmunkDemo *demo)
{
static char title[1024];
sprintf(title, "Demo: %s", demo->name);
return title;
}
static void
runDemo(chipmunkDemo *demo)
{
if(currDemo)
currDemo->destroyFunc();
currDemo = demo;
ticks = 0;
mouseJoint = NULL;
messageString[0] = '\0';
maxArbiters = 0;
maxPoints = 0;
maxConstraints = 0;
space = currDemo->initFunc();
// glutSetWindowTitle(demoTitle(currDemo));
}
static void
keyboard(unsigned char key, int x, int y)
{
int index = key - 'a';
if(0 <= index && index < demoCount){
runDemo(demos[index]);
} else if(key == '\r'){
runDemo(currDemo);
} else if(key == '-'){
options.drawHash = !options.drawHash;
} else if(key == '='){
options.drawBBs = !options.drawBBs;
} else if(key == '\\'){
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
}
}
static cpVect
mouseToSpace(int x, int y)
{
// GLdouble model[16];
// glGetDoublev(GL_MODELVIEW_MATRIX, model);
//
// GLdouble proj[16];
// glGetDoublev(GL_PROJECTION_MATRIX, proj);
//
// GLint view[4];
// glGetIntegerv(GL_VIEWPORT, view);
//
// GLdouble mx, my, mz;
// gluUnProject(x, glutGet(GLUT_WINDOW_HEIGHT) - y, 0.0f, model, proj, view, &mx, &my, &mz);
// return cpv(mx, my);
return cpv(x,y);
}
static void
mouse(int x, int y)
{
mousePoint = mouseToSpace(x, y);
}
static void
click(int button, int state, int x, int y)
{
// if(button == GLUT_LEFT_BUTTON){
// if(state == GLUT_DOWN){
// cpVect point = mouseToSpace(x, y);
//
// cpShape *shape = cpSpacePointQueryFirst(space, point, GRABABLE_MASK_BIT, 0);
// if(shape){
// cpBody *body = shape->body;
// mouseJoint = cpPivotJointNew2(mouseBody, body, cpvzero, cpBodyWorld2Local(body, point));
// mouseJoint->maxForce = 50000.0f;
// mouseJoint->biasCoef = 0.15f;
// cpSpaceAddConstraint(space, mouseJoint);
// }
// } else if(mouseJoint){
// cpSpaceRemoveConstraint(space, mouseJoint);
// cpConstraintFree(mouseJoint);
// mouseJoint = NULL;
// }
// }
}
static void
timercall(int value)
{
// glutTimerFunc(SLEEP_TICKS, timercall, 0);
//
// glutPostRedisplay();
}
static void
set_arrowDirection()
{
int x = 0, y = 0;
if(key_up) y += 1;
if(key_down) y -= 1;
if(key_right) x += 1;
if(key_left) x -= 1;
arrowDirection = cpv(x, y);
}
static void
arrowKeyDownFunc(int key, int x, int y)
{
// if(key == GLUT_KEY_UP) key_up = 1;
// else if(key == GLUT_KEY_DOWN) key_down = 1;
// else if(key == GLUT_KEY_LEFT) key_left = 1;
// else if(key == GLUT_KEY_RIGHT) key_right = 1;
set_arrowDirection();
}
static void
arrowKeyUpFunc(int key, int x, int y)
{
// if(key == GLUT_KEY_UP) key_up = 0;
// else if(key == GLUT_KEY_DOWN) key_down = 0;
// else if(key == GLUT_KEY_LEFT) key_left = 0;
// else if(key == GLUT_KEY_RIGHT) key_right = 0;
set_arrowDirection();
}
static void
idle(void)
{
// glutPostRedisplay();
}
static void
initGL(void)
{
// glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
//
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// glOrtho(-320.0f, 320.0f, -240.0f, 240.0f, -1.0f, 1.0f);
// glTranslatef(0.5f, 0.5f, 0.0f);
//
// glEnableClientState(GL_VERTEX_ARRAY);
}
static void
glutStuff(int argc, const char *argv[])
{
// glutInit(&argc, (char**)argv);
//
// glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
//
// glutInitWindowSize(640, 480);
// glutCreateWindow(demoTitle(demos[firstDemoIndex]));
//
// initGL();
//
// glutDisplayFunc(display);
//// glutIdleFunc(idle);
// glutTimerFunc(SLEEP_TICKS, timercall, 0);
//
// glutIgnoreKeyRepeat(1);
// glutKeyboardFunc(keyboard);
//
// glutSpecialFunc(arrowKeyDownFunc);
// glutSpecialUpFunc(arrowKeyUpFunc);
//
// glutMotionFunc(mouse);
// glutPassiveMotionFunc(mouse);
// glutMouseFunc(click);
}
//#include <sys/time.h>
//void time_trial(char index, int count)
//{
// currDemo = demos[index];
// space = currDemo->initFunc();
//
// struct timeval start_time, end_time;
// gettimeofday(&start_time, NULL);
//
// for(int i=0; i<count; i++)
// currDemo->updateFunc(i);
//
// gettimeofday(&end_time, NULL);
// long millisecs = (end_time.tv_sec - start_time.tv_sec)*1000;
// millisecs += (end_time.tv_usec - start_time.tv_usec)/1000;
//
// currDemo->destroyFunc();
//
// printf("Time(%c) = %ldms\n", index + 'a', millisecs);
//}
void ChipmunkTestScene::runThisTest()
{
// create layer
ChipmunkTestLayer* pLayer = new ChipmunkTestLayer();
pLayer->init();
pLayer->autorelease();
addChild(pLayer);
CCDirector::getSharedDirector()->replaceScene(this);
}
void ChipmunkTestLayer::init()
{
CCLayer::init();
CCLayer::setIsTouchEnabled(TRUE);
demoIndex = 0;
cpInitChipmunk();
mouseBody = cpBodyNew(INFINITY, INFINITY);
runDemo(demos[firstDemoIndex]);
label = CCLabel::labelWithString(demos[firstDemoIndex]->name, "Arial", 32);
label->setPosition( ccp(0, -300) );
label->setColor(ccBLACK);
addChild(label);
// [self schedule: @selector(step:)];
schedule( schedule_selector(ChipmunkTestLayer::step));
}
void ChipmunkTestLayer::onEnter()
{
CCLayer::onEnter();
glClearColor(1,1,1,1);
float factor = 1.0f;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// portraint
glOrthof(-320/factor, 320/factor, -480/factor, 480/factor, -1.0f, 1.0f);
// landscape
// glOrthof(-480/factor, 480/factor, -320/factor, 320/factor, 1.0f, -1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPointSize(3.0f);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
glLineWidth(1.5f);
}
void ChipmunkTestLayer::step(ccTime dt)
{
// call chipmunk demo c function
display();
}
void ChipmunkTestLayer::draw()
{
drawSpace(space, currDemo->drawOptions ? currDemo->drawOptions : &options);
}
void ChipmunkTestLayer::ccTouchesEnded(NSSet* touches, UIEvent *event)
{
demoIndex++;
if( demoIndex >= maxDemos )
demoIndex = 0;
runDemo(demos[demoIndex]);
label->setString( demos[demoIndex]->name );
}

View File

@ -1,79 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "chipmunk.h"
#include "drawSpace.h"
#include "testBasic.h"
struct chipmunkDemo;
typedef cpSpace *(*demoInitFunc)(void);
typedef void (*demoUpdateFunc)(int ticks);
typedef void (*demoDestroyFunc)(void);
typedef struct chipmunkDemo {
char *name;
drawSpaceOptions *drawOptions;
demoInitFunc initFunc;
demoUpdateFunc updateFunc;
demoDestroyFunc destroyFunc;
} chipmunkDemo;
static inline cpFloat
frand(void)
{
return (cpFloat)rand()/(cpFloat)RAND_MAX;
}
extern cpVect arrowDirection;
extern char messageString[1024];
#define GRABABLE_MASK_BIT (1<<31)
#define NOT_GRABABLE_MASK (~GRABABLE_MASK_BIT)
// cocos2d-x test interface decalre
class ChipmunkTestScene : public TestScene
{
public:
virtual void runThisTest();
};
class ChipmunkTestLayer : public CCLayer
{
protected:
std::string m_strTitle;
int demoIndex;
CCLabel *label;
public:
void init();
// virtual std::string title();
virtual void onEnter();
void step(ccTime dt);
void draw();
void ccTouchesEnded(NSSet* touches, UIEvent *event);
// void restartCallback(NSObject* pSender);
// void nextCallback(NSObject* pSender);
// void backCallback(NSObject* pSender);
};

View File

@ -1,527 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <limits.h>
#include <string.h>
#include "chipmunk.h"
#include "drawSpace.h"
#include "cocos2d.h"
/*
IMPORTANT - READ ME!
This file sets up a simple interface that the individual demos can use to get
a Chipmunk space running and draw what's in it. In order to keep the Chipmunk
examples clean and simple, they contain no graphics code. All drawing is done
by accessing the Chipmunk structures at a very low level. It is NOT
recommended to write a game or application this way as it does not scale
beyond simple shape drawing and is very dependent on implementation details
about Chipmunk which may change with little to no warning.
*/
#define LINE_COLOR 0.0f, 0.0f, 0.0f, 1.0f
#define COLLISION_COLOR 1.0f, 0.0f, 0.0f, 1.0f
#define BODY_COLOR 0.0f, 0.0f, 1.0f
using namespace cocos2d;
static void
glColor_from_pointer(void *ptr)
{
unsigned long val = (long)ptr;
// hash the pointer up nicely
val = (val+0x7ed55d16) + (val<<12);
val = (val^0xc761c23c) ^ (val>>19);
val = (val+0x165667b1) + (val<<5);
val = (val+0xd3a2646c) ^ (val<<9);
val = (val+0xfd7046c5) + (val<<3);
val = (val^0xb55a4f09) ^ (val>>16);
// GLfloat v = (GLfloat)val/(GLfloat)ULONG_MAX;
// v = 0.95f - v*0.15f;
//
// glColor3f(v, v, v);
GLubyte r = (val>>0) & 0xFF;
GLubyte g = (val>>8) & 0xFF;
GLubyte b = (val>>16) & 0xFF;
GLubyte max = r>g ? (r>b ? r : b) : (g>b ? g : b);
const int mult = 127;
const int add = 63;
r = (r*mult)/max + add;
g = (g*mult)/max + add;
b = (b*mult)/max + add;
glColor4ub(r, g, b, 255);
}
static const GLfloat circleVAR[] = {
0.0000f, 1.0000f,
0.2588f, 0.9659f,
0.5000f, 0.8660f,
0.7071f, 0.7071f,
0.8660f, 0.5000f,
0.9659f, 0.2588f,
1.0000f, 0.0000f,
0.9659f, -0.2588f,
0.8660f, -0.5000f,
0.7071f, -0.7071f,
0.5000f, -0.8660f,
0.2588f, -0.9659f,
0.0000f, -1.0000f,
-0.2588f, -0.9659f,
-0.5000f, -0.8660f,
-0.7071f, -0.7071f,
-0.8660f, -0.5000f,
-0.9659f, -0.2588f,
-1.0000f, -0.0000f,
-0.9659f, 0.2588f,
-0.8660f, 0.5000f,
-0.7071f, 0.7071f,
-0.5000f, 0.8660f,
-0.2588f, 0.9659f,
0.0000f, 1.0000f,
0.0f, 0.0f, // For an extra line to see the rotation.
};
static const int circleVAR_count = sizeof(circleVAR)/sizeof(GLfloat)/2;
static void
drawCircleShape(cpBody *body, cpCircleShape *circle)
{
glVertexPointer(2, GL_FLOAT, 0, circleVAR);
// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
// Needed states: GL_VERTEX_ARRAY,
// Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glPushMatrix(); {
cpVect center = cpvadd(body->p, cpvrotate(circle->c, body->rot));
glTranslatef(center.x, center.y, 0.0f);
glRotatef(body->a*180.0f/(cpFloat)M_PI, 0.0f, 0.0f, 1.0f);
glScalef(circle->r, circle->r, 1.0f);
if(!circle->shape.sensor){
glColor_from_pointer(circle);
glDrawArrays(GL_TRIANGLE_FAN, 0, circleVAR_count - 1);
}
glColor4f(LINE_COLOR);
glDrawArrays(GL_LINE_STRIP, 0, circleVAR_count);
} glPopMatrix();
// restore default GL state
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
static const GLfloat pillVAR[] = {
0.0000f, 1.0000f,
0.2588f, 0.9659f,
0.5000f, 0.8660f,
0.7071f, 0.7071f,
0.8660f, 0.5000f,
0.9659f, 0.2588f,
1.0000f, 0.0000f,
0.9659f, -0.2588f,
0.8660f, -0.5000f,
0.7071f, -0.7071f,
0.5000f, -0.8660f,
0.2588f, -0.9659f,
0.0000f, -1.0000f,
0.0000f, -1.0000f,
-0.2588f, -0.9659f,
-0.5000f, -0.8660f,
-0.7071f, -0.7071f,
-0.8660f, -0.5000f,
-0.9659f, -0.2588f,
-1.0000f, -0.0000f,
-0.9659f, 0.2588f,
-0.8660f, 0.5000f,
-0.7071f, 0.7071f,
-0.5000f, 0.8660f,
-0.2588f, 0.9659f,
0.0000f, 1.0000f,
};
static const int pillVAR_count = sizeof(pillVAR)/sizeof(GLfloat)/2;
static void
drawSegmentShape(cpBody *body, cpSegmentShape *seg)
{
cpVect a = cpvadd(body->p, cpvrotate(seg->a, body->rot));
cpVect b = cpvadd(body->p, cpvrotate(seg->b, body->rot));
if(seg->r){
cpVect delta = cpvsub(b, a);
cpFloat len = cpvlength(delta)/seg->r;
GLfloat VAR[pillVAR_count*2];
memcpy(VAR, pillVAR, sizeof(pillVAR));
for(int i=0, half=pillVAR_count; i<half; i+=2)
VAR[i] += len;
glVertexPointer(2, GL_FLOAT, 0, VAR);
// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
// Needed states: GL_VERTEX_ARRAY,
// Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glPushMatrix(); {
GLfloat x = a.x;
GLfloat y = a.y;
GLfloat cos = delta.x/len;
GLfloat sin = delta.y/len;
const GLfloat matrix[] = {
cos, sin, 0.0f, 0.0f,
-sin, cos, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 1.0f,
x, y, 0.0f, 1.0f,
};
glMultMatrixf(matrix);
if(!seg->shape.sensor){
glColor_from_pointer(seg);
glDrawArrays(GL_TRIANGLE_FAN, 0, pillVAR_count);
}
glColor4f(LINE_COLOR);
glDrawArrays(GL_LINE_LOOP, 0, pillVAR_count);
} glPopMatrix();
// Restore Default GL states
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
} else {
glColor4f(LINE_COLOR);
ccDrawLine(ccp(a.x, a.y),ccp(b.x, b.y));
}
}
static void
drawPolyShape(cpBody *body, cpPolyShape *poly)
{
int count = count=poly->numVerts;
//GLfloat VAR[count*2];
GLfloat *VAR = new GLfloat[count*2];
// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
// Needed states: GL_VERTEX_ARRAY,
// Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, VAR);
cpVect *verts = poly->verts;
for(int i=0; i<count; i++){
cpVect v = cpvadd(body->p, cpvrotate(verts[i], body->rot));
VAR[2*i ] = v.x;
VAR[2*i + 1] = v.y;
}
if(!poly->shape.sensor){
glColor_from_pointer(poly);
glDrawArrays(GL_TRIANGLE_FAN, 0, count);
}
glColor4f(LINE_COLOR);
glDrawArrays(GL_LINE_LOOP, 0, count);
// Restore Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
delete VAR;
}
static void
drawObject(void *ptr, void *unused)
{
cpShape *shape = (cpShape *)ptr;
cpBody *body = shape->body;
switch(shape->klass->type){
case CP_CIRCLE_SHAPE:
drawCircleShape(body, (cpCircleShape *)shape);
break;
case CP_SEGMENT_SHAPE:
drawSegmentShape(body, (cpSegmentShape *)shape);
break;
case CP_POLY_SHAPE:
drawPolyShape(body, (cpPolyShape *)shape);
break;
default:
// printf("Bad enumeration in drawObject().\n");
break;
}
}
static const GLfloat springVAR[] = {
0.00f, 0.0f,
0.20f, 0.0f,
0.25f, 3.0f,
0.30f,-6.0f,
0.35f, 6.0f,
0.40f,-6.0f,
0.45f, 6.0f,
0.50f,-6.0f,
0.55f, 6.0f,
0.60f,-6.0f,
0.65f, 6.0f,
0.70f,-3.0f,
0.75f, 6.0f,
0.80f, 0.0f,
1.00f, 0.0f,
};
static const int springVAR_count = sizeof(springVAR)/sizeof(GLfloat)/2;
static void
drawSpring(cpDampedSpring *spring, cpBody *body_a, cpBody *body_b)
{
cpVect a = cpvadd(body_a->p, cpvrotate(spring->anchr1, body_a->rot));
cpVect b = cpvadd(body_b->p, cpvrotate(spring->anchr2, body_b->rot));
glPointSize(5.0f);
ccDrawLine( ccp(a.x, a.y), ccp(b.x, b.y) );
cpVect delta = cpvsub(b, a);
// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
// Needed states: GL_VERTEX_ARRAY,
// Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, springVAR);
glPushMatrix(); {
GLfloat x = a.x;
GLfloat y = a.y;
GLfloat cos = delta.x;
GLfloat sin = delta.y;
GLfloat s = 1.0f/cpvlength(delta);
const GLfloat matrix[] = {
cos, sin, 0.0f, 0.0f,
-sin*s, cos*s, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 1.0f,
x, y, 0.0f, 1.0f,
};
glMultMatrixf(matrix);
glDrawArrays(GL_LINE_STRIP, 0, springVAR_count);
} glPopMatrix();
// Restore Default GL states
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
static void
drawConstraint(cpConstraint *constraint)
{
cpBody *body_a = constraint->a;
cpBody *body_b = constraint->b;
const cpConstraintClass *klass = constraint->klass;
if(klass == cpPinJointGetClass()){
cpPinJoint *joint = (cpPinJoint *)constraint;
cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot));
cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot));
glPointSize(5.0f);
ccDrawPoint( ccp(a.x, a.y) );
ccDrawPoint( ccp(b.x, b.y) );
ccDrawLine( ccp(a.x, a.y), ccp(b.x, b.y) );
} else if(klass == cpSlideJointGetClass()){
cpSlideJoint *joint = (cpSlideJoint *)constraint;
cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot));
cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot));
glPointSize(5.0f);
ccDrawPoint( ccp(a.x, a.y) );
ccDrawPoint( ccp(b.x, b.y) );
ccDrawLine( ccp(a.x, a.y), ccp(b.x, b.y) );
} else if(klass == cpPivotJointGetClass()){
cpPivotJoint *joint = (cpPivotJoint *)constraint;
cpVect a = cpvadd(body_a->p, cpvrotate(joint->anchr1, body_a->rot));
cpVect b = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot));
glPointSize(10.0f);
ccDrawPoint( ccp(a.x, a.y) );
ccDrawPoint( ccp(b.x, b.y) );
} else if(klass == cpGrooveJointGetClass()){
cpGrooveJoint *joint = (cpGrooveJoint *)constraint;
cpVect a = cpvadd(body_a->p, cpvrotate(joint->grv_a, body_a->rot));
cpVect b = cpvadd(body_a->p, cpvrotate(joint->grv_b, body_a->rot));
cpVect c = cpvadd(body_b->p, cpvrotate(joint->anchr2, body_b->rot));
glPointSize(5.0f);
ccDrawPoint( ccp(c.x, c.y) );
ccDrawLine( ccp(a.x, a.y), ccp(b.x, b.y) );
} else if(klass == cpDampedSpringGetClass()){
drawSpring((cpDampedSpring *)constraint, body_a, body_b);
} else {
// printf("Cannot draw constraint\n");
}
}
static void
drawBB(void *ptr, void *unused)
{
cpShape *shape = (cpShape *)ptr;
CGPoint vertices[] = {
ccp(shape->bb.l, shape->bb.b),
ccp(shape->bb.l, shape->bb.t),
ccp(shape->bb.r, shape->bb.t),
ccp(shape->bb.r, shape->bb.b),
};
ccDrawPoly(vertices, 4, false);
}
static void
drawCollisions(void *ptr, void *data)
{
cpArbiter *arb = (cpArbiter *)ptr;
CGPoint *aPoints = new CGPoint[arb->numContacts];
for(int i=0; i<arb->numContacts; i++){
aPoints[i] = CGPoint(arb->contacts[i].p.x, arb->contacts[i].p.y);
}
ccDrawPoints( aPoints, arb->numContacts );
delete aPoints;
}
// copied from cpSpaceHash.c
static inline cpHashValue
hash_func(cpHashValue x, cpHashValue y, cpHashValue n)
{
return (x*1640531513ul ^ y*2654435789ul) % n;
}
static void
drawSpatialHash(cpSpaceHash *hash)
{
cpBB bb = cpBBNew(-320, -240, 320, 240);
cpFloat dim = hash->celldim;
int n = hash->numcells;
int l = (int)floor(bb.l/dim);
int r = (int)floor(bb.r/dim);
int b = (int)floor(bb.b/dim);
int t = (int)floor(bb.t/dim);
for(int i=l; i<=r; i++){
for(int j=b; j<=t; j++){
int cell_count = 0;
int index = hash_func(i,j,n);
for(cpSpaceHashBin *bin = hash->table[index]; bin; bin = bin->next)
cell_count++;
GLfloat v = 1.0f - (GLfloat)cell_count/10.0f;
glColor4f(v,v,v,1.0f);
// glRectf(i*dim, j*dim, (i + 1)*dim, (j + 1)*dim);
}
}
}
void
drawSpace(cpSpace *space, drawSpaceOptions *options)
{
if(options->drawHash)
drawSpatialHash(space->activeShapes);
glLineWidth(1.0f);
if(options->drawBBs){
glColor4f(0.3f, 0.5f, 0.3f, 1.0f);
cpSpaceHashEach(space->activeShapes, &drawBB, NULL);
cpSpaceHashEach(space->staticShapes, &drawBB, NULL);
}
glLineWidth(options->lineThickness);
if(options->drawShapes){
cpSpaceHashEach(space->activeShapes, &drawObject, NULL);
cpSpaceHashEach(space->staticShapes, &drawObject, NULL);
}
cpArray *constraints = space->constraints;
glColor4f(0.5f, 1.0f, 0.5f, 1.0f);
for(int i=0, count = constraints->num; i<count; i++){
drawConstraint( (cpConstraint*)(constraints->arr[i]) );
}
if(options->bodyPointSize){
cpArray *bodies = space->bodies;
glPointSize(options->bodyPointSize);
glColor4f(LINE_COLOR);
CGPoint *aPoints = new CGPoint[bodies->num];
for(int i=0, count = bodies->num; i<count; i++){
cpBody *body = (cpBody *)bodies->arr[i];
aPoints[i] = CGPoint(body->p.x, body->p.y);
}
ccDrawPoints( aPoints, bodies->num );
delete aPoints;
}
if(options->collisionPointSize){
glPointSize(options->collisionPointSize);
glColor4f(COLLISION_COLOR);
cpArrayEach(space->arbiters, &drawCollisions, NULL);
}
}

View File

@ -1,36 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef _DRAW_SPACE_H_
#define _DRAW_SPACE_H_
typedef struct drawSpaceOptions {
int drawHash;
int drawBBs;
int drawShapes;
float collisionPointSize;
float bodyPointSize;
float lineThickness;
} drawSpaceOptions;
void drawSpace(cpSpace *space, drawSpaceOptions *options);
#endif //_DRAW_SPACE_H_

View File

@ -1,67 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
struct chipmunkDemo;
typedef cpSpace *(*demoInitFunc)(void);
typedef void (*demoUpdateFunc)(int ticks);
typedef void (*demoDestroyFunc)(void);
typedef struct chipmunkDemo {
char *name;
drawSpaceOptions *drawOptions;
demoInitFunc initFunc;
demoUpdateFunc updateFunc;
demoDestroyFunc destroyFunc;
} chipmunkDemo;
static inline cpFloat
frand(void)
{
return (cpFloat)rand()/(cpFloat)RAND_MAX;
}
extern cpVect arrowDirection;
extern char messageString[1024];
#define GRABABLE_MASK_BIT (1<<31)
#define NOT_GRABABLE_MASK (~GRABABLE_MASK_BIT)
//CLASS INTERFACE
#import "cocos2d.h"
@interface AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate>
{
UIWindow *window;
}
@end
@interface MainLayer : CCLayer
{
int demoIndex;
CCLabel *label;
}
@end

View File

@ -1,548 +0,0 @@
/* Copyright (c) 2007 Scott Lembcke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
IMPORTANT - READ ME!
This file sets up a simple interface that the individual demos can use to get
a Chipmunk space running and draw what's in it. In order to keep the Chipmunk
examples clean and simple, they contain no graphics code. All drawing is done
by accessing the Chipmunk structures at a very low level. It is NOT
recommended to write a game or application this way as it does not scale
beyond simple shape drawing and is very dependent on implementation details
about Chipmunk which may change with little to no warning.
*/
#import "cocos2d.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#ifdef __IPHONE_2_0
#endif
#include "chipmunk.h"
#include "drawSpace.h"
#include "cocos2dChipmunkDemo.h"
#define SLEEP_TICKS 16
//extern chipmunkDemo Test;
extern chipmunkDemo LogoSmash;
extern chipmunkDemo Simple;
extern chipmunkDemo PyramidStack;
extern chipmunkDemo Plink;
extern chipmunkDemo Tumble;
extern chipmunkDemo PyramidTopple;
extern chipmunkDemo Bounce;
extern chipmunkDemo Planet;
extern chipmunkDemo Springies;
extern chipmunkDemo Pump;
extern chipmunkDemo TheoJansen;
extern chipmunkDemo MagnetsElectric;
extern chipmunkDemo UnsafeOps;
extern chipmunkDemo Query;
extern chipmunkDemo OneWay;
extern chipmunkDemo Player;
extern chipmunkDemo Sensors;
extern chipmunkDemo Joints;
//extern chipmunkDemo Test;
static chipmunkDemo *demos[] = {
&LogoSmash,
&Simple,
&PyramidStack,
&Plink,
&Tumble,
&PyramidTopple,
&Bounce,
&Planet,
&Springies,
&Pump,
&TheoJansen,
&MagnetsElectric,
&UnsafeOps,
// &Query,
&OneWay,
&Player,
&Sensors,
&Joints,
};
static int maxDemos = sizeof(demos) / sizeof(demos[0]);
static const int demoCount = sizeof(demos)/sizeof(chipmunkDemo *);
static chipmunkDemo *currDemo = NULL;
static const int firstDemoIndex = 'a' - 'a';
static int ticks = 0;
static cpSpace *space;
cpVect mousePoint;
cpVect mousePoint_last;
cpBody *mouseBody = NULL;
cpConstraint *mouseJoint = NULL;
char messageString[1024] = {};
int key_up = 0;
int key_down = 0;
int key_left = 0;
int key_right = 0;
cpVect arrowDirection = {};
drawSpaceOptions options = {
0,
0,
1,
4.0f,
0.0f,
1.5f,
};
static void
drawString(int x, int y, char *str)
{
// implement me
}
static void
drawInstructions()
{
drawString(-300, 220,
"Controls:\n"
"A - * Switch demos. (return restarts)\n"
"Use the mouse to grab objects.\n"
"Arrow keys control some demos.\n"
"\\ enables anti-aliasing.\n"
"- toggles spatial hash visualization.\n"
"= toggles bounding boxes."
);
}
static int maxArbiters = 0;
static int maxPoints = 0;
static int maxConstraints = 0;
static void
drawInfo()
{
int arbiters = space->arbiters->num;
int points = 0;
for(int i=0; i<arbiters; i++)
points += ((cpArbiter *)(space->arbiters->arr[i]))->numContacts;
int constraints = (space->constraints->num + points)*(space->iterations + space->elasticIterations);
maxArbiters = arbiters > maxArbiters ? arbiters : maxArbiters;
maxPoints = points > maxPoints ? points : maxPoints;
maxConstraints = constraints > maxConstraints ? constraints : maxConstraints;
char buffer[1000];
char *format =
"Arbiters: %d (%d) - "
"Contact Points: %d (%d)\n"
"Other Constraints: %d, Iterations: %d\n"
"Constraints x Iterations: %d (%d)";
snprintf(buffer, 1000, format,
arbiters, maxArbiters,
points, maxPoints,
space->constraints->num, space->iterations + space->elasticIterations,
constraints, maxConstraints
);
drawString(0, 220, buffer);
}
static void
display(void)
{
// glClear(GL_COLOR_BUFFER_BIT);
//
// drawSpace(space, currDemo->drawOptions ? currDemo->drawOptions : &options);
// drawInstructions();
// drawInfo();
// drawString(-300, -210, messageString);
//
// glutSwapBuffers();
ticks++;
cpVect newPoint = cpvlerp(mousePoint_last, mousePoint, 0.25f);
mouseBody->p = newPoint;
mouseBody->v = cpvmult(cpvsub(newPoint, mousePoint_last), 60.0f);
mousePoint_last = newPoint;
currDemo->updateFunc(ticks);
}
static char *
demoTitle(chipmunkDemo *demo)
{
static char title[1024];
sprintf(title, "Demo: %s", demo->name);
return title;
}
static void
runDemo(chipmunkDemo *demo)
{
if(currDemo)
currDemo->destroyFunc();
currDemo = demo;
ticks = 0;
mouseJoint = NULL;
messageString[0] = '\0';
maxArbiters = 0;
maxPoints = 0;
maxConstraints = 0;
space = currDemo->initFunc();
// glutSetWindowTitle(demoTitle(currDemo));
}
static void
keyboard(unsigned char key, int x, int y)
{
int index = key - 'a';
if(0 <= index && index < demoCount){
runDemo(demos[index]);
} else if(key == '\r'){
runDemo(currDemo);
} else if(key == '-'){
options.drawHash = !options.drawHash;
} else if(key == '='){
options.drawBBs = !options.drawBBs;
} else if(key == '\\'){
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
}
}
static cpVect
mouseToSpace(int x, int y)
{
// GLdouble model[16];
// glGetDoublev(GL_MODELVIEW_MATRIX, model);
//
// GLdouble proj[16];
// glGetDoublev(GL_PROJECTION_MATRIX, proj);
//
// GLint view[4];
// glGetIntegerv(GL_VIEWPORT, view);
//
// GLdouble mx, my, mz;
// gluUnProject(x, glutGet(GLUT_WINDOW_HEIGHT) - y, 0.0f, model, proj, view, &mx, &my, &mz);
// return cpv(mx, my);
return cpv(x,y);
}
static void
mouse(int x, int y)
{
mousePoint = mouseToSpace(x, y);
}
static void
click(int button, int state, int x, int y)
{
// if(button == GLUT_LEFT_BUTTON){
// if(state == GLUT_DOWN){
// cpVect point = mouseToSpace(x, y);
//
// cpShape *shape = cpSpacePointQueryFirst(space, point, GRABABLE_MASK_BIT, 0);
// if(shape){
// cpBody *body = shape->body;
// mouseJoint = cpPivotJointNew2(mouseBody, body, cpvzero, cpBodyWorld2Local(body, point));
// mouseJoint->maxForce = 50000.0f;
// mouseJoint->biasCoef = 0.15f;
// cpSpaceAddConstraint(space, mouseJoint);
// }
// } else if(mouseJoint){
// cpSpaceRemoveConstraint(space, mouseJoint);
// cpConstraintFree(mouseJoint);
// mouseJoint = NULL;
// }
// }
}
static void
timercall(int value)
{
// glutTimerFunc(SLEEP_TICKS, timercall, 0);
//
// glutPostRedisplay();
}
static void
set_arrowDirection()
{
int x = 0, y = 0;
if(key_up) y += 1;
if(key_down) y -= 1;
if(key_right) x += 1;
if(key_left) x -= 1;
arrowDirection = cpv(x, y);
}
static void
arrowKeyDownFunc(int key, int x, int y)
{
// if(key == GLUT_KEY_UP) key_up = 1;
// else if(key == GLUT_KEY_DOWN) key_down = 1;
// else if(key == GLUT_KEY_LEFT) key_left = 1;
// else if(key == GLUT_KEY_RIGHT) key_right = 1;
set_arrowDirection();
}
static void
arrowKeyUpFunc(int key, int x, int y)
{
// if(key == GLUT_KEY_UP) key_up = 0;
// else if(key == GLUT_KEY_DOWN) key_down = 0;
// else if(key == GLUT_KEY_LEFT) key_left = 0;
// else if(key == GLUT_KEY_RIGHT) key_right = 0;
set_arrowDirection();
}
static void
idle(void)
{
// glutPostRedisplay();
}
static void
initGL(void)
{
// glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
//
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// glOrtho(-320.0f, 320.0f, -240.0f, 240.0f, -1.0f, 1.0f);
// glTranslatef(0.5f, 0.5f, 0.0f);
//
// glEnableClientState(GL_VERTEX_ARRAY);
}
static void
glutStuff(int argc, const char *argv[])
{
// glutInit(&argc, (char**)argv);
//
// glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
//
// glutInitWindowSize(640, 480);
// glutCreateWindow(demoTitle(demos[firstDemoIndex]));
//
// initGL();
//
// glutDisplayFunc(display);
//// glutIdleFunc(idle);
// glutTimerFunc(SLEEP_TICKS, timercall, 0);
//
// glutIgnoreKeyRepeat(1);
// glutKeyboardFunc(keyboard);
//
// glutSpecialFunc(arrowKeyDownFunc);
// glutSpecialUpFunc(arrowKeyUpFunc);
//
// glutMotionFunc(mouse);
// glutPassiveMotionFunc(mouse);
// glutMouseFunc(click);
}
//#include <sys/time.h>
//void time_trial(char index, int count)
//{
// currDemo = demos[index];
// space = currDemo->initFunc();
//
// struct timeval start_time, end_time;
// gettimeofday(&start_time, NULL);
//
// for(int i=0; i<count; i++)
// currDemo->updateFunc(i);
//
// gettimeofday(&end_time, NULL);
// long millisecs = (end_time.tv_sec - start_time.tv_sec)*1000;
// millisecs += (end_time.tv_usec - start_time.tv_usec)/1000;
//
// currDemo->destroyFunc();
//
// printf("Time(%c) = %ldms\n", index + 'a', millisecs);
//}
#pragma mark -
#pragma mark MainLayer
@implementation MainLayer
-(id) init
{
if( (self=[super init]) ) {
self.isTouchEnabled = YES;
cpInitChipmunk();
mouseBody = cpBodyNew(INFINITY, INFINITY);
runDemo(demos[firstDemoIndex]);
label = [CCLabel labelWithString:[NSString stringWithUTF8String:demos[firstDemoIndex]->name ] fontName:@"Marker Felt" fontSize:32];
label.position = ccp(0,-300);
label.color = ccBLACK;
[self addChild:label];
[self schedule: @selector(step:)];
}
return self;
}
-(void) onEnter
{
[super onEnter];
glClearColor(1,1,1,1);
float factor = 1.0f;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(-320/factor, 320/factor, -480/factor, 480/factor, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPointSize(3.0f);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
glLineWidth(1.5f);
}
-(void) step: (ccTime) dt
{
display();
}
-(void) draw
{
drawSpace(space, currDemo->drawOptions ? currDemo->drawOptions : &options);
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
demoIndex++;
if( demoIndex >= maxDemos )
demoIndex = 0;
runDemo(demos[demoIndex]);
[label setString: [NSString stringWithUTF8String:demos[demoIndex]->name ] ];
}
@end
#pragma mark -
#pragma mark AppController
@implementation AppController
- (void) applicationDidFinishLaunching:(UIApplication*)application
{
// CC_DIRECTOR_INIT()
//
// 1. Initializes an EAGLView with 0-bit depth format, and RGB565 render buffer
// 2. Attaches to the main window
// 3. Creates Display Link Director
// 3a. If it fails, it will use an NSTimer director
// 4. It will try to run at 60 FPS
// 4. Display FPS: NO
// 5. Device orientation: Portrait
// 6. Connect the director to the EAGLView
//
CC_DIRECTOR_INIT();
// Obtain the shared director in order to...
CCDirector *director = [CCDirector sharedDirector];
// Turn on display FPS
[director setDisplayFPS:YES];
CCScene *scene = [CCScene node];
MainLayer * mainLayer =[MainLayer node];
[scene addChild: mainLayer];
[director runWithScene: scene];
}
// getting a call, pause the game
-(void) applicationWillResignActive:(UIApplication *)application
{
[[CCDirector sharedDirector] pause];
}
// call got rejected
-(void) applicationDidBecomeActive:(UIApplication *)application
{
[[CCDirector sharedDirector] resume];
}
// next delta time will be zero
-(void) applicationSignificantTimeChange:(UIApplication *)application
{
[[CCDirector sharedDirector] setNextDeltaTimeZero:YES];
}
- (void) dealloc
{
[window release];
[super dealloc];
}
@end
int main(int argc, char *argv[]) {
NSAutoreleasePool *pool = [NSAutoreleasePool new];
UIApplicationMain(argc, argv, nil, @"AppController");
[pool release];
return 0;
}

View File

@ -1 +1,141 @@
this file need to run .tmk3 file to rebuild.
############################################################################
#
# Makefile for building : chipmunk_Arm.TMK3
# Created by TMK3_V2.3, please do not modify.
#
#############################################################################
TO_PROJECT_ROOT = ../../PRJ_TG3
OUTPUT_FILENAME = libchipmunk.so
include $(TO_PROJECT_ROOT)/MakeInclude/Makefile_Base_DynamicLib.ARM
include $(TO_PROJECT_ROOT)/MakeInclude/Makefile_TOPS_Def.ARM
DEFINES += -DCCX_UNDER_UPHONE
INCLUDE_PATH += -I. -I./Res \
-I../cocos2dx -I../cocos2dx/include \
-I./include -I./include/chipmunk -I./include/chipmunk/contains \
CC_FLAGS += -std=c99
OBJECTS_DIR = ./Debug-ARM
DESTDIR = $(TO_PROJECT_ROOT)/$(BIN_OUTPUT_DIR)
TARGET = $(DESTDIR)/$(OUTPUT_FILENAME)
DEL_FILE = rm -f
MKDIR = mkdir -p
first: all
OBJECTS = \
$(OBJECTS_DIR)/chipmunk.o \
$(OBJECTS_DIR)/cpArbiter.o \
$(OBJECTS_DIR)/cpArray.o \
$(OBJECTS_DIR)/cpBB.o \
$(OBJECTS_DIR)/cpBody.o \
$(OBJECTS_DIR)/cpCollision.o \
$(OBJECTS_DIR)/cpHashSet.o \
$(OBJECTS_DIR)/cpPolyShape.o \
$(OBJECTS_DIR)/cpShape.o \
$(OBJECTS_DIR)/cpSpace.o \
$(OBJECTS_DIR)/cpSpaceHash.o \
$(OBJECTS_DIR)/cpVect.o \
$(OBJECTS_DIR)/cpConstraint.o \
$(OBJECTS_DIR)/cpDampedRotarySpring.o \
$(OBJECTS_DIR)/cpDampedSpring.o \
$(OBJECTS_DIR)/cpGearJoint.o \
$(OBJECTS_DIR)/cpGrooveJoint.o \
$(OBJECTS_DIR)/cpPinJoint.o \
$(OBJECTS_DIR)/cpPivotJoint.o \
$(OBJECTS_DIR)/cpRatchetJoint.o \
$(OBJECTS_DIR)/cpRotaryLimitJoint.o \
$(OBJECTS_DIR)/cpSimpleMotor.o \
$(OBJECTS_DIR)/cpSlideJoint.o
ADD_OBJECTS +=
$(OBJECTS_DIR) :
$(MKDIR) $(OBJECTS_DIR)
$(DESTDIR) :
$(MKDIR) $(DESTDIR)
all : $(OBJECTS_DIR) $(DESTDIR) $(TARGET)
$(TARGET) : $(OBJECTS)
$(LINK) $(LINK_FLAGS) -o $(TARGET) $(SYS_OBJECTS) $(OBJECTS) $(ADD_OBJECTS) $(LIBS) $(SYS_LIBS)
clean :
-$(DEL_FILE) $(OBJECTS)
-$(DEL_FILE) $(TARGET)
$(OBJECTS_DIR)/chipmunk.o : ./src/chipmunk.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/chipmunk.o ./src/chipmunk.c
$(OBJECTS_DIR)/cpArbiter.o : ./src/cpArbiter.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpArbiter.o ./src/cpArbiter.c
$(OBJECTS_DIR)/cpArray.o : ./src/cpArray.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpArray.o ./src/cpArray.c
$(OBJECTS_DIR)/cpBB.o : ./src/cpBB.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpBB.o ./src/cpBB.c
$(OBJECTS_DIR)/cpBody.o : ./src/cpBody.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpBody.o ./src/cpBody.c
$(OBJECTS_DIR)/cpCollision.o : ./src/cpCollision.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpCollision.o ./src/cpCollision.c
$(OBJECTS_DIR)/cpHashSet.o : ./src/cpHashSet.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpHashSet.o ./src/cpHashSet.c
$(OBJECTS_DIR)/cpPolyShape.o : ./src/cpPolyShape.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpPolyShape.o ./src/cpPolyShape.c
$(OBJECTS_DIR)/cpShape.o : ./src/cpShape.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpShape.o ./src/cpShape.c
$(OBJECTS_DIR)/cpSpace.o : ./src/cpSpace.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpSpace.o ./src/cpSpace.c
$(OBJECTS_DIR)/cpSpaceHash.o : ./src/cpSpaceHash.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpSpaceHash.o ./src/cpSpaceHash.c
$(OBJECTS_DIR)/cpVect.o : ./src/cpVect.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpVect.o ./src/cpVect.c
$(OBJECTS_DIR)/cpConstraint.o : ./src/constraints/cpConstraint.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpConstraint.o ./src/constraints/cpConstraint.c
$(OBJECTS_DIR)/cpDampedRotarySpring.o : ./src/constraints/cpDampedRotarySpring.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpDampedRotarySpring.o ./src/constraints/cpDampedRotarySpring.c
$(OBJECTS_DIR)/cpDampedSpring.o : ./src/constraints/cpDampedSpring.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpDampedSpring.o ./src/constraints/cpDampedSpring.c
$(OBJECTS_DIR)/cpGearJoint.o : ./src/constraints/cpGearJoint.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpGearJoint.o ./src/constraints/cpGearJoint.c
$(OBJECTS_DIR)/cpGrooveJoint.o : ./src/constraints/cpGrooveJoint.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpGrooveJoint.o ./src/constraints/cpGrooveJoint.c
$(OBJECTS_DIR)/cpPinJoint.o : ./src/constraints/cpPinJoint.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpPinJoint.o ./src/constraints/cpPinJoint.c
$(OBJECTS_DIR)/cpPivotJoint.o : ./src/constraints/cpPivotJoint.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpPivotJoint.o ./src/constraints/cpPivotJoint.c
$(OBJECTS_DIR)/cpRatchetJoint.o : ./src/constraints/cpRatchetJoint.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpRatchetJoint.o ./src/constraints/cpRatchetJoint.c
$(OBJECTS_DIR)/cpRotaryLimitJoint.o : ./src/constraints/cpRotaryLimitJoint.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpRotaryLimitJoint.o ./src/constraints/cpRotaryLimitJoint.c
$(OBJECTS_DIR)/cpSimpleMotor.o : ./src/constraints/cpSimpleMotor.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpSimpleMotor.o ./src/constraints/cpSimpleMotor.c
$(OBJECTS_DIR)/cpSlideJoint.o : ./src/constraints/cpSlideJoint.c
$(CC) -c $(CC_FLAGS) $(INCLUDE_PATH) $(LAST_INCLUDE_PATH) -o $(OBJECTS_DIR)/cpSlideJoint.o ./src/constraints/cpSlideJoint.c

View File

@ -29,15 +29,19 @@ INCLUDE_TMK3=$(TO_PROJECT_ROOT)/MakeInclude/TG3_APP_Arm.TMK3 ;TOPS
;PRE_DEFINE=USE_MTAPI=1 ;使用 MTAPI 库,此时生成的 Makefile 会自动连接有关的LIB
;C、C++预定义宏可以使用多个DEFINES串也可以使用DEFINES1、DEFINES2等方式MakeFile中依据出现顺序(不是数字大小)排列
DEFINES=-D_MY_MARCO_ ;这里填入应用的自定义宏。注意ITOPS自己的所需定义会自动包含故此这里仅仅包含应用自己特有的定义即可
DEFINES=-DCCX_UNDER_UPHONE ;这里填入应用的自定义宏。注意ITOPS自己的所需定义会自动包含故此这里仅仅包含应用自己特有的定义即可
;DEFINES=-D__TG3_PURE_DLL__ ;生成的是纯动态库意思是不是TOPS应用但可以是TCOM组件
;DEFINES=-D__TCOM_SUPPORT__ ;生成的是TCOM组件注意TOPS应用也可以同时是TCOM组件
;包含路径可以使用多个INCLUDE_PATH串也可以使用INCLUDE_PATH1、INCLUDE_PATH2等方式MakeFile中依据出现顺序(不是数字大小)排列
INCLUDE_PATH= ;应用额外的包含路径。注意ITOPS自己的所有路径都会自动包含故此这里仅仅包含应用自己特有的路径即可
INCLUDE_PATH=-I../cocos2dx -I../cocos2dx/include
INCLUDE_PATH=-I./include -I./include/chipmunk -I./include/chipmunk/contains
INCLUDE_PATH=-I../test_uphone/tests
;连接的库文件可以使用多个LIBS串也可以使用LIBS1、LIBS2等方式MakeFile中依据出现顺序(不是数字大小)排列
LIBS=-lMyLib ;应用额外的连接库。注意ITOPS自己的所需库自动包含而且库包含路径也已经包含故此这里仅仅包含应用自己特有的库的名字即可
LIBS=-lcocos2d ;应用额外的连接库。注意ITOPS自己的所需库自动包含而且库包含路径也已经包含故此这里仅仅包含应用自己特有的库的名字即可
CC_FLAGS= -std=c99
;强制包含文件的名字,不能使用通配符,一定要使用相对或者绝对路径
;极力要求使用相对路径,多个文件之间使用“|”分隔
@ -50,4 +54,3 @@ INCLUDEFILE=
;只能对.c、.cpp文件进行排除
;如果要排除本目录的文件也要加入"./"
;可以使用多个EXCLUDEFILE串也可以使用EXCLUDEFILE1、EXCLUDEFILE2等方式MakeFile中依据出现顺序(不是数字大小)排列
EXCLUDEFILE=

View File

@ -1,82 +0,0 @@
/*!
* @file NewDeleteOp.cpp
* @author
* @brief
*
* @section Copyright
* =======================================================================<br>
* <br>
* Copyright (c) 2005-2010 Tranzda Technologies Co.,Ltd. <br>
* 2005-2010<br>
* <br>
* PROPRIETARY RIGHTS of Tranzda Technologies Co.,Ltd. are involved in <br>
* the subject matter of this material. All manufacturing, reproduction, <br>
* use, and sales rights pertaining to this subject matter are governed <br>
* by the license agreement. The recipient of this software implicitly <br>
* accepts the terms of the license. <br>
* 使<br>
* ,<br>
* <br>
* <a href="http://www.tranzda.com"> http://www.tranzda.com </a> <br>
* <a mailto="support@tranzda.com">support@tranzda.com</a> <br>
* =======================================================================<br>
*/
#include "ssTypes.h"
#include "TG3_Type.h"
#include "TG3_Memory.h"
#ifdef new
#undef new
#endif
#ifdef delete
#undef delete
#endif
#ifndef _WIN32
#define __cdecl
#endif
void * __cdecl operator new(unsigned int size)
{
return TMalloc(size);
}
void * __cdecl operator new[](unsigned int size)
{
return TMalloc(size);
}
void * __cdecl operator new(unsigned int size, const unsigned short * fileName, int lineNo)
{
return TMallocEx(size, fileName, lineNo);
}
void * __cdecl operator new[](unsigned int size, const unsigned short * fileName, int lineNo)
{
return TMallocEx(size, fileName, lineNo);
}
void __cdecl operator delete(void *p)
{
TFree(p);
}
void __cdecl operator delete[](void *p)
{
TFree(p);
}
void __cdecl operator delete(void *p, const unsigned short * fileName, int lineNo)
{
TFreeEx(p, fileName, lineNo);
}
void __cdecl operator delete[](void *p, const unsigned short * fileName, int lineNo)
{
TFreeEx(p, fileName, lineNo);
}

View File

@ -1,231 +0,0 @@
#include "ssGlobal.h"
#include "ssTsd.h"
#include "TG3_Type.h"
#include <stdio.h>
#include "TCOM.h"
#include "ssAppMgr.h"
#include "TG3AppDllEntry.h"
#ifdef __TCOM_SUPPORT__
#ifdef __cplusplus
extern "C" {
#endif
//实现TCOM所需要的DLL函数
//DLL提供的获取指定CLSID的指定接口
SS_EXPORT HRESULT TDllGetClassObject(TREFCLSID rclsid, TREFIID riid, LPVOID * ppv);
//DLL提供的查询DLL能否被Unload
SS_EXPORT HRESULT TDllCanUnloadNow(void);
//DLL提供的把DLL的TCOM信息加入到注册表
SS_EXPORT HRESULT TDllRegisterServer(void);
//DLL提供的把DLL的TCOM信息从注册表中删除
SS_EXPORT HRESULT TDllUnregisterServer(void);
#ifdef __cplusplus
}
#endif
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
#include <stdio.h>
#endif
//TCOM实现中需要用到的函数和数据
//实例对象被引用的次数
static Int32 __TCOM_ClsidInstanceRefCount;
//ClassFactory被Locked的次数
static Int32 __TCOM_CalssFactoryLockedCount;
//做必要的初始化
static Int32 __TCOM_Init()
{
__TCOM_ClsidInstanceRefCount = 0;
__TCOM_CalssFactoryLockedCount = 0;
return 0;
}
//做必要的清除工作
static Int32 __TCOM_DeInit()
{
return 0;
}
//DLL全局使用增加对象实例被引用次数
Int32 TCOM_AddClsidInstanceRefCount()
{
__TCOM_ClsidInstanceRefCount++;
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
SS_printf("[TCOM_SYSTEM] TCOM_AddClsidInstanceRefCount: address: %p, value: %d.\n",
&__TCOM_ClsidInstanceRefCount, __TCOM_ClsidInstanceRefCount);
#endif
if(__TCOM_ClsidInstanceRefCount <= 0)
{
return 0;
}
return __TCOM_ClsidInstanceRefCount;
}
//DLL全局使用减少对象实例被引用次数
Int32 TCOM_DecClsidInstanceRefCount()
{
__TCOM_ClsidInstanceRefCount--;
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
SS_printf("[TCOM_SYSTEM] TCOM_DecClsidInstanceRefCount: address: %p, value: %d.\n",
&__TCOM_ClsidInstanceRefCount, __TCOM_ClsidInstanceRefCount);
#endif
if(__TCOM_ClsidInstanceRefCount <= 0)
{
return 0;
}
return __TCOM_ClsidInstanceRefCount;
}
//DLL全局使用增加ClassFactory被Locked的次数
Int32 TCOM_AddCalssFactoryLockedCount()
{
__TCOM_CalssFactoryLockedCount++;
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
SS_printf("[TCOM_SYSTEM] TCOM_AddCalssFactoryLockedCount: address: %p, value: %d.\n",
&__TCOM_CalssFactoryLockedCount, __TCOM_CalssFactoryLockedCount);
#endif
if(__TCOM_CalssFactoryLockedCount <= 0)
{
return 0;
}
return __TCOM_CalssFactoryLockedCount;
}
//DLL全局使用减少ClassFactory被Locked的次数
Int32 TCOM_DecCalssFactoryLockedCount()
{
__TCOM_CalssFactoryLockedCount--;
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
SS_printf("[TCOM_SYSTEM] TCOM_DecCalssFactoryLockedCount: address: %p, value: %d.\n",
&__TCOM_CalssFactoryLockedCount, __TCOM_CalssFactoryLockedCount);
#endif
if(__TCOM_CalssFactoryLockedCount <= 0)
{
return 0;
}
return __TCOM_CalssFactoryLockedCount;
}
//实现TCOM所需要的DLL函数
//DLL提供的获取指定CLSID的指定接口
SS_EXPORT HRESULT TDllGetClassObject(TREFCLSID rclsid, TREFIID riid, LPVOID * ppv)
{
return TCOM_Srv_GetClassObject(rclsid, riid, ppv);
}
//DLL提供的查询DLL能否被Unload
SS_EXPORT HRESULT TDllCanUnloadNow(void)
{
#ifdef __TCOM_OUTPUT_DEBUG_INFO__
SS_printf("[TCOM_SYSTEM] TDllCanUnloadNow: address1: %p, address2: %p, value1: %d, value2: %d.\n",
&__TCOM_ClsidInstanceRefCount, &__TCOM_CalssFactoryLockedCount, __TCOM_ClsidInstanceRefCount,
__TCOM_CalssFactoryLockedCount);
#endif
if((__TCOM_ClsidInstanceRefCount <= 0) && (__TCOM_CalssFactoryLockedCount <= 0))
return TCOM_S_TRUE;
return TCOM_S_FALSE;
}
//DLL提供的把DLL的TCOM信息加入到注册表
SS_EXPORT HRESULT TDllRegisterServer(void)
{
return TCOM_Srv_RegisterServer();
}
//DLL提供的把DLL的TCOM信息从注册表中删除
SS_EXPORT HRESULT TDllUnregisterServer(void)
{
return TCOM_Srv_UnregisterServer();
}
#endif //__TCOM_SUPPORT__
#ifdef _WIN32
#ifndef SS_MAKEDLL
#error Error!!! SS_MAKEDLL Must defined!
#endif
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
//进程加载动态库进行的操作
#ifdef __TCOM_SUPPORT__
__TCOM_Init();
#endif
break;
case DLL_THREAD_ATTACH:
//线程加载动态库进行的操作
break;
case DLL_THREAD_DETACH:
//线程卸载动态库进行的操作
break;
case DLL_PROCESS_DETACH:
//进程卸载动态库进行的操作
#ifdef __TCOM_SUPPORT__
__TCOM_DeInit();
#endif
break;
}
return TRUE;
}
#else //linux
#ifndef SS_SHARED
#error Error!!! SS_SHARED Must defined!
#endif
void __attribute((constructor)) TG3_Dll_Attach()
{
//进程加载动态库进行的操作
#ifdef __TCOM_SUPPORT__
__TCOM_Init();
#endif
}
void __attribute((destructor)) TG3_Dll_Detach()
{
//进程卸载动态库进行的操作
#ifdef __TCOM_SUPPORT__
__TCOM_DeInit();
#endif
}
#endif
//如果不是作为TG3的动态库应用请在VC项目中和TMK3文件中定义 __TG3_PURE_DLL__ 宏
#ifndef __TG3_PURE_DLL__
//动态库应用使用的统一导出名字的入口函数
SS_EXPORT Int32 TDllTG3AppMain(const TUChar * pAppID, UInt32 nCmd, void * pCmdParam)
{
Int32 retValue;
//初始化TCOM
TCoInitialize(NULL);
retValue = TG3AppMain(pAppID, nCmd, pCmdParam);
//释放TCOM
TCoUninitialize();
return retValue;
}
#endif

View File

@ -1,53 +0,0 @@
#ifndef __TG3_APP_DLL_ENTRY_H__
#define __TG3_APP_DLL_ENTRY_H__
#ifndef __cplusplus
#error This file need C++ support
#endif
#if TG3_APP_ENTRY_MINIMUM_VERSION > 200
#error Please replace TG3AppDllEntry.h and TG3AppDllEntry.cpp to newest version!
#endif
#ifdef __TCOM_SUPPORT__
#include "TCOM.h"
//提供给DLL实现者调用的函数用于在全局记录实例和ClassFactory被引用的次数
//这两个计数影响DLL是否可能被从内存中卸载请大家在实例中内部实现计数的同时更新全局计数
//否则DLL很有可能会在实例还存在的时候被系统自动强制卸载
//DLL全局使用增加对象实例被引用次数
Int32 TCOM_AddClsidInstanceRefCount();
//DLL全局使用减少对象实例被引用次数
Int32 TCOM_DecClsidInstanceRefCount();
//DLL全局使用增加ClassFactory被Locked的次数
Int32 TCOM_AddCalssFactoryLockedCount();
//DLL全局使用减少ClassFactory被Locked的次数
Int32 TCOM_DecCalssFactoryLockedCount();
//应用DLL在支持TCOM的时候提供给导出函数使用的函数
//应用根据给出的CLSID和ClassFactory接口IID返回ClassFactory的接口
//返回值参考TCOM_S_系列宏定义
HRESULT TCOM_Srv_GetClassObject(TREFCLSID rclsid, TREFIID riid, LPVOID * ppv);
//应用提供的把TCOM信息加入到注册表
//返回值参考TCOM_S_系列宏定义
HRESULT TCOM_Srv_RegisterServer(void);
//应用提供的把TCOM信息从注册表中删除
//返回值参考TCOM_S_系列宏定义
HRESULT TCOM_Srv_UnregisterServer(void);
#endif //__TCOM_SUPPORT__
#endif //__TG3_APP_DLL_ENTRY_H__

View File

@ -1,10 +0,0 @@
// Unicode string resource scrip file,DOT NOT include it.
// Original file name: chipmunkUnicodeScript.h
// Generated by TOPS Builder:Project wizard,Date:2010-09-03
#define TZD_CONV(x, y)
TZD_CONV(AppName_chipmunk, "chipmunk")

View File

@ -1,26 +0,0 @@
// Unicode string resource file
// Original file name: chipmunkUnicodeScript_str.h
// Generated by TOPS Builder:Project wizard,Date:2010-09-03
#ifndef __chipmunk_STR_STR_H__
#define __chipmunk_STR_STR_H__
#define AppName_chipmunk__N \
"A\x00p\x00p\x00_\x00T\x00\x65\x00s\x00t\x00"
#define AppName_chipmunk__C \
AppName_chipmunk__N"\x00\x00"
#define AppName_chipmunk \
((const unsigned short *)(AppName_chipmunk__C))
#define AppName_chipmunk__N16 \
0x0041,0x0070,0x0070,0x005f,0x0054,0x0065,0x0073,0x0074
#define AppName_chipmunk_16 \
{AppName_chipmunk__N16,0x0000}
// ԭʼ´®ÐÅÏ¢£º
// chipmunk
#endif