Coder Social home page Coder Social logo

ofxbox2d's Introduction

ofxBox2d

ofxBox2d

Introduction

This is a simple wrapper for box2d using Openframeworks. The examples below are still in progressive, but should be stable for the most part. Please open up a issue if you have suggestions or find bugs. The wrapper is using the version Box2D v2.3

Thanks, Todd

Installation

First, pick the branch that matches your version of openFrameworks:

Instructions

When making a vector of objects you need to be careful. You either need to make a vector of pointers of use the shared_ptr object.

Everytime you push into the vector circles the object is destroyed and the created. This causing issues for the b2dBody body object owned by box2d.

Incorrect way to store objects.

vector <ofxBox2dCircle> circles;
ofxBox2dCircle circle;
circles.push_back(circle);

Here is the how to create a vector of box2d objects.

// in your header files
vector <shared_ptr<ofxBox2dCircle> > circles;

// now add a circle to the vector
auto circle = std::make_shared<ofxBox2dCircle>();

// to grab the pointer you use the get() function of shared_ptr (std::shared_ptr)
circle->setPhysics(3.0, 0.53, 0.1);
circle->setup(box2d.getWorld(), 100, 100, 10);
circles.push_back(circle);

Installation

Place ofxBox2d within a folder in the apps folder of the OF dir tree:

openframeworks/addons/ofxBox2d

Compatibility

ofxBox2d is developed against the current version of OpenFramewroks.

If you are using a stable version (007, 0071, ...) of OpenFrameworks then you want to use a git tag of ofxBox2d for that version. You can select the tag in the Github "Current Branch" menu or clone and check it out using git.

For example, the following commands will clone ofxBox2d and switch to the OF 008 tagged version:

git clone git://github.com/vanderlin/ofxBox2d.git
cd ofxBox2d
git checkout 008

ofxbox2d's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ofxbox2d's Issues

applying a gradient from HSB fails ?

hi there-

for some reason, the box2d code won't let me apply a certain HSB gradient texture to a polygon (see code below). I did find a workaround though- just made a gradient from this:

double increment = TWO_PI/50;
double cx = 0;
double cy = 0;
glBegin(GL_POLYGON)
for (double angle = 0; angle < TWO_PI;angle += increment){
glColor4f(1, 1, 1, 0);
glVertex2d(cx,cy);
glColor4f(1, 1, 0,0);
glVertex2d(cx + cos(angle) * radius, cy + sin(angle) *radius);
glVertex2d(cs + cos(angle + increment) * radius, cy + sin(angle + increment) * radius);
}

glEnd();

here's the non-working gradient code- it works fine in testApp for example but not within the ofxBox2dCircle. WOuld love to know why!


void ofxBox2dCircle::setup(b2World * b2dworld, float x, float y, float rad, int type) {{
//create the circle in the setup method
int numPts  = 64;  
    float angle = 0.0;  
    float step  = TWO_PI / (float)(numPts-1); 
    for(int i = 0; i < numPts; i++){  

        //get the -1 to 1 values - we will use these for drawing our pts.   
        float px = cos(angle);  
        float py = sin(angle);  

        normCirclePts.push_back( ofPoint(px, py) );  

        //map the -1 to 1 range produced by cos/sin  
        //to the dimensions of the image we need for our texture coords  
        float tx = ofMap( px, -1.0, 1.0, 0, circleTexture.getWidth());  
        float ty = ofMap( py, -1.0, 1.0, 0, circleTexture.getHeight());  

        normCircleCoords.push_back( ofPoint(tx, ty) );  

        angle += step;  
    } 
//create the gradient texture
float w = 100;
        float h = 100;
        sqImg.allocate(w,h,OF_IMAGE_COLOR);
        float cx = w/2;
        float cy = h/2;
        float hue,sat,bri,angle,dist;
        ofColor c;
        float a = 0;
        ofSetColor(255);
        for (float y=0; y<h; y++) {
            for (a=0; a<w; a++) {
                angle = atan2(y-h/2,a-w/2)+PI;
                dist = ofDist(a,y,w/2,h/2);
                hue = angle/TWO_PI*55;
                sat = ofMap(dist,0,w,0,255,true);//ofMap(dist,0,w/4,0,255,true);
                bri = ofMap(dist,w/4,w/2,255,255,true);
                c = ofColor::fromHsb(hue,sat,bri);                  
                sqImg.setColor(a,y,c);
            }

        }   
        circleTexture.allocate(sqImg.width, sqImg.height, GL_RGB);   
        circleTexture.loadData(sqImg.getPixels(), sqImg.width, sqImg.height, GL_RGB);  

}


void ofxBox2dCircle::draw() {

    if(!isBody()) return;
    if (circleType == STAR_IMMOBILE ){      

        ofPushMatrix();

        ofTranslate(getPosition().x, getPosition().y, 0);

        ofRotate(getRotation(), 0, 0, 1);


        ofEnableAlphaBlending();
        ofSetColor(255);



        circleTexture.bind(); 
        //The gradient circleTexture created above shows only the solid color
        glBegin(GL_POLYGON);                  
        for(int i = 0; i < normCirclePts.size(); i++){  
            glTexCoord2f(normCircleCoords[i].x, normCircleCoords[i].y);  
            glVertex2f( normCirclePts[i].x * radius ,  normCirclePts[i].y * radius );  
        }  
                glEnd(); 

        circleTexture.unbind();  



        ofPopMatrix();
    }

}


Thanks for any pointers!!!  I just want to draw a radial gradient circle!!!
Cindy

weird ofxBox2dRect scaling behavior

Hey Todd,

I was trying to draw an ofImage inside a ofxBox2dRect and had to do some weird stuff to do it

I uploaded a simple test if you want to check it out
https://github.com/jvcleave/Box2dIssueExample

The first weird part is here:
https://github.com/jvcleave/Box2dIssueExample/blob/master/src/testApp.cpp#L77

And the second here:
https://github.com/jvcleave/Box2dIssueExample/blob/master/src/ImageBox.cpp#L16

Digging in I thought that this line may be a bug
https://github.com/vanderlin/ofxBox2d/blob/master/addon/ofxBox2d/src/ofxBox2dRect.cpp#L32

as OF_RECTMODE_CORNER will always return 0, I think this should be if(ofGetRectMode() == OF_RECTMODE_CORNER)

but changing that didn't fix my project. I have the workaround for now but am not sure if I am just misunderstanding something, if there is a box2D issue or if it could be an OF bug...

Hope all is well!

issue in ofBox2d.cpp in Ubuntu 11.04

i received this error at line 79, 80, 81 :../../../addons/ofxBox2d/src/ofxBox2d.cpp|79|error: no match for call to ‘(ofCoreEvents) ()’|

id est in ofxBox2d.cpp point to these lines in void ofxBox2d::registerGrabbing()
:

else

ofAddListener(ofEvents().mousePressed, this, &ofxBox2d::mousePressed);
ofAddListener(ofEvents().mouseDragged, this, &ofxBox2d::mouseDragged);
ofAddListener(ofEvents().mouseReleased, this, &ofxBox2d::mouseReleased);

endif

i solved the problem in this way:

else

ofAddListener(ofEvents.mousePressed, this, &ofxBox2d::mousePressed);
ofAddListener(ofEvents.mouseDragged, this, &ofxBox2d::mouseDragged);
ofAddListener(ofEvents.mouseReleased, this, &ofxBox2d::mouseReleased);

endif

just removing the paranthesis.

i don't know if this issues happens only in linux but can fixed easily.
cheers
Walter
p.s ofxBox2d is very funny!

"convex" poly shape

I found good use for having a convex polygon shape, to do stuff like this:

http://i.imgur.com/KLNVf.png

I've uploaded it here:

https://github.com/ofZach/ofxBox2d/blob/master/addon/ofxBox2d/src/ofxBox2dConvexPoly.h
https://github.com/ofZach/ofxBox2d/blob/master/addon/ofxBox2d/src/ofxBox2dConvexPoly.cpp

it has a VBO for fast drawing. this isn't clean enough for a pull request, but my thought is maybe the polygon object could be restructured to take convex as one option -- ie, don't break me into triangles, just get my convex hull and add that to box 2d.

Missing files?

While trying to compile in visual studio 2012 i get following errors complaining about missing files:

1> b2LineJoint.cpp
1>c1xx : fatal error C1083: Cannot open source file: '......\addons\ofxBox2d-master\libs\Box2D\Dynamics\Joints\b2LineJoint.cpp': No such file or directory
1> b2TOISolver.cpp
1>c1xx : fatal error C1083: Cannot open source file: '......\addons\ofxBox2d-master\libs\Box2D\Dynamics\Contacts\b2TOISolver.cpp': No such file or directory

//EDIT
Left overs from old project generated theese errors

ofxBox2dPolygon.cpp line 218

ofxBox2dPolygon.cpp line 218:

from
verts.assign(size()-1, b2Vec2());
to
verts.assign(size(), b2Vec2());

I got error 'vector subscript out of range' while running an example, but this fixed my the error.

I didn't analyze the whole structure, but it seems size()-1 should be size()
because verts[] are referred 0~size()-1, so the total length is size().

verts.assign(size()-1, b2Vec2());
for (int i=0; i<size(); i++) {
ofVec2f p = getVertices()[i] / OFX_BOX2D_SCALE;
verts[i] = b2Vec2(p.x, p.y);
}

Rectangle object rectmode bug

in ofxBox2dRect.h setup() you have

if (OF_RECTMODE_CORNER) {
w/=2; h/=2;
x += w; y += h;
}

That should read OF_RECTMODE_CENTER as right now when its in top left corner mode, you are halving the size and offsetting the position, but it should only do this for center mode.

Examples not compiling on code::blocks for windows

When I try to compile example-ComplexPolygon using code::blocks 12.11 and windows 7 I get the errors:

obj\release\addons\ofxBox2d\libs\Box2D\Dynamics\Contacts\b2TOISolver.o
No such file or directory 
obj\release\addons\ofxBox2d\libs\Box2D\Dynamics\Joints\b2LineJoint.o
No such file or directory 

The example compiles and runs fine on my mac with xcode. I`m relatively new to this whole "compiled code" thing, but aren't *.o files the RESULT of compilation? Perhaps I'm doing something very silly.

Array of dynamic size causing compiler error in Visual Studio

Compilation under Visual Studio generates these errors:

1>c:\users\coryba\source\openframeworks\of_prerelease_v007_vs2010\of_prerelease_v007_vs2010\addons\ofxbox2d\src\ofxbox2dpolygon.cpp(217): error C2057: expected constant expression
1>c:\users\coryba\source\openframeworks\of_prerelease_v007_vs2010\of_prerelease_v007_vs2010\addons\ofxbox2d\src\ofxbox2dpolygon.cpp(217): error C2466: cannot allocate an array of constant size 0
1>c:\users\coryba\source\openframeworks\of_prerelease_v007_vs2010\of_prerelease_v007_vs2010\addons\ofxbox2d\src\ofxbox2dpolygon.cpp(217): error C2133: 'verts' : unknown size

with the mouseover error of "function call is not allowed in a constant expression"

Rotating a ofxBox2d rect

Hi,

I want to build a simple Kinect demo and am using box2d rectangles to represent hand and body. For hand I intend to draw a rotated box using the slope of the line joining the shoulder and elbow joint.

Even when i set the rotation manually in the code. on calling box.draw() it does not draw the shape rotated.

Any suggestions?

ofxBox2d Custom Data deletion

I´m quite new to pointers in c++ so excuse me if I´m asking something obvious.

Reading a box2d Custom Data tutorial I found:

"Box2D does not delete any of your user data objects when you destroy a body/fixture/joint, so you must remember to clean these up yourself when they are no longer needed."

I was wondering if this also applies for ofxBox2d and checking ofxBox2dBaseShape::destroy() I can see a call to box2d DestroyBody but no Custom data deletion. I cannot find also a deleteCustomData function or something like that.

So when doing something like this for deleting ofxBox2dCircle:

void clearCircle(int circleIndex) {

circles[circleIndex].destroy();
circles.erase(circles.begin()+circleIndex);

}

when you have used setData(new CustomDataClass) before I guess that the Custom Data its not being deleted from memory.

Does the de ofxBox2dBaseShape::destroy() needs something like?

body->SetUserData(NULL);

it's not needed? or it's obvious to write it before calling destroy() ?

Best,

P.

How to add filters?

Is it possible to add a filter to avoid collision from a group of bodies?

I am trying .fixture.filter.groupIndex = -1; but the particles still collide with each other

doSleep as argument

Is it possible to pass the doSleep boolean as an argument in the init() function instead of hardcoded in the init function?

Besides, i love this project, I had it up and running within 5 minutes on my iPad. Great job!

grab shapes Events iPhone !

In iOS example i get this error message in registerGrabbing() function :

ofAddListener(ofEvents().touchDown, this, &ofxBox2d::touchDown);
ofAddListener(ofEvents().touchMoved, this, &ofxBox2d::touchMoved);
ofAddListener(ofEvents().touchUp, this, &ofxBox2d::touchUp);

Type 'ofCoreEvents' does not provide a call operator.

box2d question -- SIGABRT error

I'm working on a blob tracking project (using TSPS: http://opentsps.com/) that involves the Box2d addon. I am tracking hand gestures and forming the blobs into digital shadows. One of the gestures (when velocity.x=negative value) triangulates the blob into polygons.

The app was working fine until today when I was trying to break up the blob into smaller/nicer looking polys, rather than just using the center of the blob. Now I'm getting a SIGABRT error, which I have narrowed it down to 2 lines of code -- I know that this function is causing the error: GoodShape();

if(newTriangle.poly.isGoodShape()) {

newTriangle.poly.create(box2d.getWorld());

I have noticed that it will skip over "bad" shapes, but eventually it crashes the program and gives me the SIGABRT error. I could use some assistance to why this is happening..

Here is the functioning code -- triangulation based on the center of the blob:

WORKING CODE :::::

//get the contour from the blob, and make a bunch of triangles out of it

ofPolyline shadow;

//add all of the vertexes in the shadow to the outline

for (int j=0; j<blobs[i].myShape.contours.size(); j++){

shadow.addVertex(blobs[i].myShape.contours[j].x_ofGetWidth(), blobs[i].myShape.contours[j].y_ofGetHeight());

}

shadow.simplify(); //getting the outline ready to be broken apart

// save the outline of the shape

ofPolyline outline = shadow;

// resample shape

ofPolyline resampled = shadow.getResampledBySpacing(25); //25

// triangulate the shape, return am array of triangles

vector tris = triangulatePolygonWithOutline(resampled, outline);

// add some random points inside

addRandomPointsInside(shadow, 255);

// now loop through all the triangles and make polygons for each one

for (int z=0; z<tris.size(); z++) {

polygon newTriangle;

newTriangle.setup(myBlob.idNumber, blobs[i].color);

//set up the box2dpolygon inside our polygon object

newTriangle.poly.addTriangle(tris[z].a, tris[z].b, tris[z].c);

newTriangle.poly.setAsEdge(false);

if(newTriangle.poly.isGoodShape()) {

newTriangle.poly.create(box2d.getWorld());

polygons.push_back(newTriangle);

}

}
BROKEN CODE
And here is the code I am currently working on -- The app runs until it hits --> if(newTriangle.poly.isGoodShape()) ::

ofxBox2dPolygon poly;

for (int j=0; j<blobs[i].myShape.contours.size(); j++) {

ofPoint blobPt = blobs[i].myShape.contours[j];

blobPt.x *= ofGetWidth();

blobPt.y *= ofGetHeight();

poly.addVertex( blobPt);

}

poly.triangulate(20, 20);

for (int t=0; t<poly.triangles.size(); t++){

polygon newTriangle;

newTriangle.setup(myBlob.idNumber, blobs[i].color);

newTriangle.poly.addTriangle(poly.triangles[t].a, poly.triangles[t].b, poly.triangles[t].c);

newTriangle.poly.setAsEdge(false);

if(newTriangle.poly.isGoodShape()) {

//THIS IS KILLING THE APP

newTriangle.poly.create(box2d.getWorld());

polygons.push_back(newTriangle);

}

}
Please let me know if you have a solution :) Thanks!

VS 2010 Build Documentation

I'm not sure if it's worth mentioning, but ofxBox2d won't compile on a non-Linux system, due to certain headers being used in triangle_impl.hpp. Un-commenting line 235 in that file will relieve the strange linker errors (only applicable to Windows users).

It may save people some time to put that in your README. Just a suggestion :)

triangulatePolygon() return ofVec2f suggestions

hey todd

right now triangulatePolygon() returns a vector of ofVec2f. how do you feel about this suggestion, as I don't feel thats an obvious way to work with triangles.

Instead of using ofVec2f for all the returned points, how about having a triangle type i.e

struct triangleObject{
ofVec2f points[ 3 ];
ofVec2f centre;
};

That way a vector of those is easier to work with, and you don't have to calculate the centre each time you want to find it.

so instead of:
triangles.push_back(a);
triangles.push_back(b);
triangles.push_back(c);

i currently have...

    triangles.push_back( triangleObject() );
    triangles[triangles.size()-1].points[0] = a;
    triangles[triangles.size()-1].points[1] = b;
    triangles[triangles.size()-1].points[2] = c;
    triangles[triangles.size()-1].center = center;

its just a thought.

bodyDef.position.Set() not doing anything.

Hello!

first, thanks for wrapping this with ofx!

second, I'm creating static bodies for a room. By assigning density to 0.0 as argument on setPhysics() when creating my static bodies.

now I want them to update position, I'm trying by calling bodyDef.position.Set(); which gives no compile errors and I think should work from reading the box2d documentation.

I've noticed others having problem with bodyDef.fixedRotation= true;

could all this be related with a issue regarding bodyDef ?

Missed something important in my pull request (alive flags)

Hi Todd, I was worried this might fall through the cracks, since you closed my pull request #50

Thanks for cleaning up the unnecessary dead flag, but you missed the most important part of my pull request, which was the setting of the alive flag. If these three primitive types (Circle, Rect, Polygon) don't set the flag in their setup(), then when they get deleted, they won't call destroy(), won't remove themselves from the box2d world, and then will (or can) cause crashes.

It would be great if you could please add those few lines, so I don't have to maintain my own fork just for this fix. Thanks!

Remove warning in ofxBox2dBaseShape::setData()

Next time you're tidying up little things, could you please add a return NULL; at the end of ofxBox2dBaseShape::setData()? Otherwise, you get compiler warnings -- and in the off case that data is not NULL and the shape is not a body, who knows what random data will be returned? (Maybe that case can never happen, but at least you can get rid of the compiler warning.)

void* ofxBox2dBaseShape::setData(void*data) {

    if(data == NULL) {
        ofLog(OF_LOG_NOTICE, "ofxBox2dBaseShape:: - data is NULL -");
        return NULL;
    }

    if(isBody()) {
        ofLog(OF_LOG_NOTICE, "ofxBox2dBaseShape:: - custom data set %p", data);
        body->SetUserData(data);
        return data;
    }
    else {
        ofLog(OF_LOG_NOTICE, "ofxBox2dBaseShape:: - must have a valid body -");
    }
    return NULL;    // <----- add this!
}

Thanks.

fixedRotation not working

I'm trying to prevent my polygons from rotating, but this has no effect. Any ideas?

ofxBox2dPolygon p;

p.bodyDef.fixedRotation=true;

ofxBox2dPolygon getCenter

Hi Todd,
Thanks for the update!
I had a lot of issues with memory management and destroying objects.
So I'm really pleased to see that you improved this.

I'm testing the examples right now, and I think ofxBox2dPolygon must have missed a commit:

src/TextureShape.h:59:42: error: ‘class ofxBox2dPolygon’ has no member named ‘getCenter’

Could you check that?

Thank you!
Emmanuel

Scrolling

Is there any easy way to do a scrolling of the whole ofxBox2D world ?
Is there any camera control that can makes it ?

Thanks

setposition() on ofxBox2dPolygon, it is effective in term of collision but not graphically

Hi, I want to move Polygons I created, they are in a vector.
I use this code :

 int x = 0;
 int y = 1;

 for (int i = 0 ; i < _Poly.size()  ; i++) {

    ofPoint _Point;
    _Point =  _Poly[i].ofxBox2dBaseShape::getPosition();
    _Point.x = _Point.x+ x;
    _Point.y = _Point.y+ y;
    _Poly[i].setPosition( _Point.x, _Point.y); 

   }

The result is that objects around react as if polygons are moving but graphically, polygons are display at the same place.

PS: I am using ofxBox2dBaseShape::getPosition() as ofxBox2dPolydon::getPosition() is empty

lib to libs

Just a quick mention on a minor bug I experienced on Ubuntu 11.04, running a vanilla pre-release 007.

I cloned ofxBox2d git and moved the addon/ofxBox2d directory directly under addons/. After that I made a new project with the oF-linux createProject.py script and under that project's src-folder I copied ofxBox2dExample/src/*

Running make complains about the libs not being found. The quick fix is to rename "lib" in addons/ofxBox2d to "libs" :)

If this poses no issues on other platforms, I would suggest making "libs" default.

Thanks for the great addon!

setPosition freezes object

comment out this to make setPosition not permanently freeze the object.

  body->SetAwake(false); // this sounds backwards but that is what the doc says todo...

How to use sensors ?

Hi,

I would like to use sensors.
I am using this code on a Polygon :

Shape->body->GetFixtureList()->SetSensor(true);

Is there a special way to use it as the shape still perform collision with other objects...

Thanks

Thanks

Find the vector ID of a shape during a collision

Hi,

I am playing with collisions using the ContactListenerExample.
I wonder if it is possible to get the vector ID ( by vector ID, I mean for example: " circles[0] " 0 would be the ID of this circle. I am not sure to use the right term though ) to find out which shape have been hit.

here the code in the example:
if(e.a->GetType() == b2Shape::e_circle && e.b->GetType() == b2Shape::e_circle) {

}

is there any e.b->GetID() that would gave me the item number into the vector circle ?

Thanks very much.

Issues with Polyline (oF 0.8)

Hey,

I'm getting weird issues with polylines with oF 0.8 on OSX. It looks like the number of points is being capped at about 3, resulting in only a small section of the line being created. I've fixed it by caching the size() in ofxBox2dPolygon::create. I'll fork and add the fix. Is anyone else able to recreate this?

no match for call to '(ofCoreEvents) ()'|

Hi,

I am trying to build the ofxBox2d example with Code:blocks, win and 007 and get the following:

of_preRelease_v007_win_cb\addons_nonCore\ofxBox2d\src\ofxBox2d.cpp |79|error:no match for call to '(ofCoreEvents) ()'|

and the same for

ofAddListener(ofEvents().mousePressed, this, &ofxBox2d::mousePressed);
ofAddListener(ofEvents().mouseDragged, this, &ofxBox2d::mouseDragged);
ofAddListener(ofEvents().mouseReleased, this, &ofxBox2d::mouseReleased);

in ofxBox2d.cpp

Thanks

World size

Hi,
is there a way to create a world that is bigger then the actual window ?
If yes, is there any limitation?
Thanks

ofPolygon and ofxBox2dPolygon override conflict

line 203
you need to force the class get ofPolygon Vertices


if(bSetAsEdge) {
    for (int i=1; iCreateFixture(&fixture);
    }  
}
else {
    vectorverts;
    verts.assign(ofPolyline::getVertices().size()-1, b2Vec2());
    for (int i=0; iCreateFixture(&fixture);
}

Find the ofxBox2dPolygon associate to a collision

Hi,

I am trying to use SpriteContactStart() to find out which polygon have been touched.
But I can't manage to find the relation between e.a and e.b to my ofxBox2dPolygon item in the vector.

Thanks by the way for this addon, I really like to use it even if it is a bit tricky for me ;)

Here what my code look like:

void Layer::SpriteContactStart(ofxBox2dContactArgs &e){

if(e.a != NULL && e.b != NULL) { 

    ofxBox2dPolygon* poly1 = NULL;
    ofxBox2dPolygon* poly2 = NULL;


    for (int i = 0; i < _Poly(); i++) {
         if (_Poly[i]->body == e.a){
                poly1 = *_Poly[i];
               }
    }

    for (int i = 0; i < _Poly(); i++) {
         if (_Poly[i]->body == e.b)
                poly2 = *_Poly[i];
               }
    }

cout <<poly1<<" "<<poly2<<endl;
}

Thanks

ofxBox2dPolygon::clear() calls itself

If you call it, it just recurses until it blows up. You just need to change ofxBox2dPolygon::clear() to call ofPolyline::clear() instead of ofxBox2dPolygon::clear()

Polygon create doesn't like 3-sided polygons

This is just a very minor bug fix, next time you're patching things:

void ofxBox2dPolygon::create(b2World * b2dworld) {

    if(size() <= 3) {
        ofLog(OF_LOG_NOTICE, "need at least 3 points: %i\n", (int)size());
        return; 
    }
    // ...etc...

Just change the if test to be (to match the logic of the warning message):

    if(size() < 3) {

Three-sided polygons are perfectly valid; in fact some of my best friends are triangles! (-;

Thanks,
Glen.

Why isn't alive ever set to true for shapes?

I was having trouble with physics objects not being destroyed properly when I discovered that ofxBox2dBaseShape.alive is never set to true. Shouldn't this be done in the setup() for derived classes?

A move from Box2D 1.1 towards Box2D 2.3.0

Hey,

A few months ago when fixing up ofxBox2d to work with the new oF version, I tested a checkout of the cutting edge Box2D 2.3.0 and successfully achieved to build it with some major tweaks.

Now so far this 2.3.0 branch has been very basically tested.
I have all the examples working, however would like feedback before chasing up Vanderlin with a pull request.

Erin (Box2D author) has tweaked a lot of the code since 1.1, so there are likely more enhancements this ofx wrapper could benefit from.

My branch is:
https://github.com/danoli3/ofxBox2d/tree/Box2d-2.3

What needs to be done:

  • Testing around the ofBox2dPolygon
  • Environment testing
  • Memory leak testing
  • Add recent fixes and changes for ofxBox2d in recent months if applicable

What could be added

  • Better use of new Box2D 2.X class functions

Allow destroy() to be called by user without generating messages

We call destroy() to remove ofxBox2dBaseShape objects from the B2d world. Then, later, destroy() is called again, by the ofxBox2dBaseShape destructor, which results in the following messages:

[error] ofxBox2dBaseShape:: - body is not defined -
[notice] ofxBox2dBaseShape:: - must have a valid world -

This is because of two things. First, isBody() always logs a message when you're querying it and it isn't a body. I think it's safe (and logical) to remove that message:

bool ofxBox2dBaseShape::isBody() {
    if (body == NULL) {
        // Removed error message: why should we log something if we're not a
        // body, when the whole point of this method is just to query whether
        // we are one...?
        return false;
    }
    return true;
}

Secondly, in the BaseShape destructor, you always call destroy(), which causes that other "must have a valid world" message to trigger. The fix would be to only destroy() if we are/have a body:

ofxBox2dBaseShape::~ofxBox2dBaseShape() {
    ofLog(OF_LOG_VERBOSE, "~ofxBox2dBaseShape(%p)\n", body);
    if (isBody()) {
        destroy();
    }
}

I can submit a pull request, but we're unable to move to OF 0.8 for now, and so I'm working with a modified/hacked fork until we can move ahead -- but I am trying to stay in sync with your latest ofxBox2d code as much as possible. If you like, I can branch off your current master and submit this. Thanks!

P.S. You may ask why we don't just stop calling destroy() in our code, and just delete the C++ objects. Well, it's because we don't control when object deletion takes place. I'm running these C++ objects in Lua (ofxLua), so when they are "removed" from the scene, I call destroy() -- this is necessary, so they no longer have any physical effect in the B2d world. But the actual C++ instances aren't destroyed until the Lua garbage-collector decides to do it. (Well, I can force garbage collection, but this is not the best thing to do in an interactive app, every time a Box2d object is removed from the scene.)

issues compiling in Visual Studio

Main issues with triangle_impl.hpp
First issue defining sys/time.h, renamed to just time.h to fix this, then i get all these errors.

1>dpoint.hpp(634): warning C4244: 'return' : conversion from 'double' to 'float', possible loss of data
1>triangle_impl.hpp(3334): warning C4101: 'k' : unreferenced local variable
1>triangle_impl.hpp(3334): warning C4101: 'workstring' : unreferenced local variable
1>triangle_impl.hpp(12536): warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\string.h(105) : see declaration of 'strcpy'
1>triangle_impl.hpp(15374): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(234) : see declaration of 'fopen'
1>triangle_impl.hpp(15784): error C2079: 'tv0' uses undefined struct 'piyush::triangulate::timeval'
1>triangle_impl.hpp(15784): error C2079: 'tv1' uses undefined struct 'piyush::triangulate::timeval'
1>triangle_impl.hpp(15784): error C2079: 'tv2' uses undefined struct 'piyush::triangulate::timeval'
1>triangle_impl.hpp(15784): error C2079: 'tv3' uses undefined struct 'piyush::triangulate::timeval'
1>triangle_impl.hpp(15784): error C2079: 'tv4' uses undefined struct 'piyush::triangulate::timeval'
1>triangle_impl.hpp(15784): error C2079: 'tv5' uses undefined struct 'piyush::triangulate::timeval'
1>triangle_impl.hpp(15784): error C2079: 'tv6' uses undefined struct 'piyush::triangulate::timeval'
1>triangle_impl.hpp(15785): error C2079: 'tz' uses undefined struct 'piyush::triangulate::timezone'
1>triangle_impl.hpp(15789): error C3861: 'gettimeofday': identifier not found
1>triangle_impl.hpp(15810): error C3861: 'gettimeofday': identifier not found
1>triangle_impl.hpp(15837): error C3861: 'gettimeofday': identifier not found
1>triangle_impl.hpp(15843): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15843): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15844): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15844): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15869): error C3861: 'gettimeofday': identifier not found
1>triangle_impl.hpp(15872): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15872): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15873): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15873): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15902): error C3861: 'gettimeofday': identifier not found
1>triangle_impl.hpp(15904): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15904): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15905): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15905): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(15918): error C3861: 'gettimeofday': identifier not found
1>triangle_impl.hpp(16065): error C3861: 'gettimeofday': identifier not found
1>triangle_impl.hpp(16067): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(16067): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(16068): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(16068): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(16070): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(16070): error C2228: left of '.tv_sec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(16071): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'
1>triangle_impl.hpp(16071): error C2228: left of '.tv_usec' must have class/struct/union
1> type is 'int'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.