Python Box2D! (howto)

Discuss issues specific the Python port of Box2D
kne
Posts: 88
Joined: Mon Feb 18, 2008 12:30 am

Re: Python Box2D! (howto)

Postby kne » Fri Mar 07, 2008 8:29 pm

Just built version 2.0.0 and added some helper functions to allow access to the vertices and such. I wonder if I'm the only one still messing around with Python and Box2D? I can include my updated test application if anyone's interested, though it's nothing special.

Anyway, enjoy.

Contents of the zip:
Box2D_templ.i: This is the SWIG interface. You can use it to rebuild the SWIG output (.py)
Box2D2.py: put this in your application directory or (your Python 2.5 dir)\lib
_Box2D2.pyd: put this in (your Python 2.5 dir)\DLLs
Attachments
Box2D_v2.0.0_python.zip
Box2D v2.0.0 Python bindings and DLL (for Windows)
(225.74 KiB) Downloaded 3875 times

crazy-chris
Posts: 30
Joined: Thu Mar 13, 2008 9:27 am

Re: Python Box2D! (howto)

Postby crazy-chris » Fri Mar 14, 2008 6:45 am

Thanks for your excellent work! I'm doing a lot of Python related things and am currently trying to build the box2d swig wrapper for linux. Here's what I've done so far

[EDIT]Info outdated. Please see the wiki instead: Box2D with Python, Box2D with Linux[/EDIT]
Last edited by crazy-chris on Sat Mar 22, 2008 5:58 am, edited 1 time in total.

crazy-chris
Posts: 30
Joined: Thu Mar 13, 2008 9:27 am

Re: Python Box2D! (howto)

Postby crazy-chris » Fri Mar 14, 2008 7:48 am

And this is a 1 to 1 translation of the HelloWorld.cpp to Python (Hello.py) :)

Code: Select all

from Box2D2 import *

""" This is a simple example of building and running a simulation
    using Box2D. Here we create a large ground box and a small dynamic box
"""

# Define the size of the world. Simulation will still work
# if bodies reach the end of the world, but it will be slower.
worldAABB=b2AABB()
worldAABB.lowerBound.Set(-100.0, -100.0);
worldAABB.upperBound.Set(100.0, 100.0);

# Define the gravity vector.
gravity = b2Vec2(0.0, -10.0);

# Do we want to let bodies sleep?
doSleep = True

# Construct a world object, which will hold and simulate the rigid bodies.
world = b2World(worldAABB, gravity, doSleep)

# Define the ground body.
groundBodyDef = b2BodyDef();
groundBodyDef.position.Set(0.0, -10.0);

# Call the body factory which allocates memory for the ground body
# from a pool and creates the ground box shape (also from a pool).
# The body is also added to the world.
groundBody = world.CreateStaticBody(groundBodyDef);

# Define the ground box shape.
groundShapeDef = b2PolygonDef()

# The extents are the half-widths of the box.
groundShapeDef.SetAsBox(50.0, 10.0);

# Add the ground shape to the ground body.
groundBody.CreateShape(groundShapeDef);

# Define the dynamic body. We set its position and call the body factory.
bodyDef = b2BodyDef()
bodyDef.position.Set(0.0, 4.0);
body = world.CreateDynamicBody(bodyDef);

# Define another box shape for our dynamic body.
shapeDef = b2PolygonDef()
shapeDef.SetAsBox(1.0, 1.0);

# Set the box density to be non-zero, so it will be dynamic.
shapeDef.density = 1.0

# Override the default friction.
shapeDef.friction = 0.3;

# Add the shape to the body.
body.CreateShape(shapeDef);

# Now tell the dynamic body to compute it's mass properties base on its shape.
body.SetMassFromShapes();

# Prepare for simulation. Typically we use a time step of 1/60 of a
# second (60Hz) and 10 iterations. This provides a high quality simulation
# in most game scenarios.
timeStep = 1.0 / 60.0
iterations = 10

# This is our little game loop.
for i in range(60):
   # Instruct the world to perform a single step of simulation. It is
   # generally best to keep the time step and iterations fixed.
   world.Step(timeStep, iterations);

   # Now print the position and angle of the body.
   position = body.GetPosition();
   angle = body.GetAngle();

   print position.x, position.y, angle

kne
Posts: 88
Joined: Mon Feb 18, 2008 12:30 am

Re: Python Box2D! (howto)

Postby kne » Fri Mar 14, 2008 4:33 pm

Nice work, crazy-chris. :)

The next thing I've been trying to get working are the b2ContactListener callbacks. Pretty sure Swig can handle it, it's just a matter of getting the right settings in the interface. Anyone else messing around with it?

kne
Posts: 88
Joined: Mon Feb 18, 2008 12:30 am

Re: Python Box2D! (howto)

Postby kne » Fri Mar 21, 2008 8:29 pm

Continuing my conversation with myself, here's an updated version of the wrapper!

Features:
  • Working userData with generic objects (access the data directly, don't use GetUserData() )
  • Working callbacks (yay) (only tested b2ContactListener)
  • Added functions to allow polygon's vertices to be accessed
  • Built-in vector addition (works on the Python b2Vec2 objects)
  • b2Vec2, b2Body, b2Shape, b2ContactPoint print prettily:
    e.g., print b2Vec2(1,2)
    output: b2Vec2(1,2)
    I'll take recommendations for formatting other classes print functions.
  • All functions are now automatically given docstrings by swig
  • No source code modifications necessary to compile

Added functions:
  • b2Vec2.tuple() returns the b2Vec2 as a tuple (x, y)
  • b2Shape.asCircle() typecasts the shape to a b2CircleShape so it can be accessed properly
  • b2Shape.asPolygon() typecasts the shape to a b2PolygonShape so it can be accessed properly
  • b2PolygonShape.getVertex(int vnum) returns vertex number vnum (as a b2Vec2)
  • b2PolygonDef.getVertex(int vnum) returns vertex number vnum (as a b2Vec2)
  • b2PolygonDef.setVertex(int vnum, b2Vec2 vec) sets vertex number vnum to vec

Contents of the zip:
  • Box2D_templ.i: This is the SWIG interface. You can use it to rebuild the SWIG output (.py)
  • Box2D2.py: put this in your application directory or (your Python 2.5 dir)\lib
  • _Box2D2.pyd: put this in (your Python 2.5 dir)\DLLs

Using the callbacks:
The definition:

Code: Select all

class kContactListener(b2ContactListener):
    def __init__(self): b2ContactListener.__init__(self)
    def Add(self, point):
        """Called when a contact point is created"""
        print "Add:", point
    def Persist(self, point):
        """Called when a contact point persists for more than a time step"""
        print "Persist:", point
    def Remove(self, point):
        """Called when a contact point is removed"""
        print "Remove:",point


Setting it:

Code: Select all

self.klistener = kContactListener()
self.world.SetListener( self.klistener )


Easy, eh?

I updated the wiki ( http://www.box2d.org/wiki/index.php?title=Box2D_with_Python ) but somehow cannot upload files to the forum, so I'll be hosting them on googlepages from now on.
Download: http://pybox2d.googlepages.com/

crazy-chris
Posts: 30
Joined: Thu Mar 13, 2008 9:27 am

Re: Python Box2D! (howto)

Postby crazy-chris » Sat Mar 22, 2008 4:07 am

Thanks for your good work kne!!!

It's a big help for all who start using Box2D with Python. And I'm sure, you're not talking with yourself --
the counter shows already around 800 views, and the interest is rising in the python dev communities :D

kne
Posts: 88
Joined: Mon Feb 18, 2008 12:30 am

Re: Python Box2D! (howto)

Postby kne » Sat Mar 22, 2008 4:49 am

Thanks for the reply, crazy-chris. :) At least there's the two of us posting around here.

Feel free to edit the interface and all, I'll be sure to toss it up in the next release!

crazy-chris
Posts: 30
Joined: Thu Mar 13, 2008 9:27 am

Re: Python Box2D! (howto)

Postby crazy-chris » Sat Mar 22, 2008 11:00 am

What would be really cool: If swig would raise python exceptions if box2d crashes somewhere! :)

For example, if I create a polygon, but the vertices are actually only forming a straight line, box2d will crash and so the python script. And I have no way to catch the exceptions...

I had a short look into SWIG exception handling, but coulnd't solve it so far. You think it's possible / easy?

* http://www.swig.org/Doc1.3/Customizatio ... zation_nn7
* http://docs.huihoo.com/swig/1.1/Exceptions.html
* http://www.google.com/search?q=swig+exception

kne
Posts: 88
Joined: Mon Feb 18, 2008 12:30 am

Re: Python Box2D! (howto)

Postby kne » Fri Mar 28, 2008 8:11 pm

Well, given the stance of the creator on exceptions, I don't think it'll be accepted into the main branch. While not impossible, it wouldn't be easy to implement the exceptions. I'd still like to see some verification functions on shapes before they are just rejected and the whole program crashes, but we're at the mercy of the creator here.

In any case, I've updated the bindings to 2.0.0 r2.
See the updated info here: http://www.box2d.org/wiki/index.php?tit ... ith_Python
Download here: http://pybox2d.googlepages.com/home
Features some fixes and new features making it a lot easier. I put my build script and my friend's modification of it for OSX on the site, also -- but they aren't anything special.

roman_m
Posts: 36
Joined: Sun Nov 25, 2007 1:43 pm

Re: Python Box2D! (howto)

Postby roman_m » Wed Apr 02, 2008 2:51 am

I've got a problem when tried to implement DebugDraw.

Code: Select all

class DebugDraw(b2DebugDraw):
        def __init__(self):
                super(DebugDraw, self).__init__()
        def DrawSolidPolygon(self, vertices, vertexCount, color):
                print "DrawSolidPolygon", vertices, vertexCount, color.r, color.g, color.b

debugDraw = DebugDraw()
debugDraw.SetFlags(debugDraw.e_shapeBit)
world.SetDebugDraw(debugDraw)

Problem: vertices variable that is passed to DrawSolidPoligon contain only first vertex of the polygon. I think convertion of pointer to array should be done by the wrapper, but I don't know how to use SWIG.


Return to “Python”



Who is online

Users browsing this forum: No registered users and 1 guest