Box2D Java

Shame on me, I thought synchronized methods synchronize on method scope.
Thanks for the enlightenment.
makas, do you know if any of the lock coarsening stuff in the latest JVMs will help reduce synchronization costs when no concurrent accesses are possible?

In any case, though I think the idea of extending World is probably a pretty clean solution, I probably won't include it for now simply because it might imply that the entire engine is thread safe, which is not true (you could still do some damage by creating shapes while the broadphase is active for instance, and I am sure there is more that would need to be tracked down to make this truly safe).
The exceptions you talked about earlier are no strangers to me 😀 I can reproduce them in my code pretty consistently. Usually they come up after less than 5 minutes of play...give or take.

My application is single threaded and as discussed earlier i too have a contact listener but i don't create or destroy objects from within. i remeber the contacts and destroy the objects after the world.step() finishes.

The two exceptions i frequently get are:

Code:
java.lang.ArrayIndexOutOfBoundsException: 0
   at org.jbox2d.dynamics.World.solve(World.java:579)
   at org.jbox2d.dynamics.World.step(World.java:471)
   at de.mkoehler.js.client.Game.update(Game.java:218)
   at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:541)
   at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:350)
   at de.mkoehler.js.client.Client.main(Client.java:76)


line 579 of World corresponds to the line "stack[stackCount++] = seed;" in this block:

Code:
            // Reset island and stack.
            island.clear();
            int stackCount = 0;
            stack[stackCount++] = seed;
            seed.m_flags |= Body.e_islandFlag;


the second exception is:

Code:
java.lang.AssertionError
   at org.jbox2d.dynamics.Island.add(Island.java:81)
   at org.jbox2d.dynamics.World.solveTOI(World.java:803)
   at org.jbox2d.dynamics.World.step(World.java:476)
   at de.mkoehler.js.client.Game.update(Game.java:218)
   at org.newdawn.slick.GameContainer.updateAndRender(GameContainer.java:541)
   at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:350)
   at de.mkoehler.js.client.Client.main(Client.java:76)


Line 81 of Island corresponds to the assertion in this block:

Code:
    void add(Body body) {
        assert m_bodyCount < m_bodyCapacity;
        m_bodies[m_bodyCount++] = body;
    }


You should know that i excessively create and destroy objects in the simulation, because every shot fired from the spaceships is a box2D body that is destroyed either when it's lifetime (1.5 seconds) is exceeded or it collides with anything. The weapons on the spaceships have a rate of fire of up to 1200 shots per minute...so now you know what i mean with excessively 😀

Since both exceptions seem to be related to the body count (the size of the stack[] array is determined by m_bodyCount) my assumption is that this value gets corrupted somehow.

And at least one of the exceptions (i don't remember which one it was) is not recoverable. by that i mean i put a try/catch around the world.step() and ignored the exception. When it first occured it continued to occur on every subsequent call of step().

If you would like me to log certain variables when the exceptions occur or something similar, just say the word.
For a start i just did a quick Screenshot from the Debugger. This shows the state of the JVM when the AssertionFailed Exception in Island:81 occurs.

regards
Max
@maxdreamland: Are you 100% sure that no bodies are being created off the main thread, which might happen as a result of input callbacks even if you don't explicitly create your own new threads? That assertion, as you noted, should only be triggered if the body count has been altered within the step, which shouldn't ever happen from within the engine.

Otherwise, is there any way you could get a minimal source example that causes this, or failing that, maybe share your game source (even if not publicly, maybe privately so that I can see what's going on - my email is my username here at gmail)? If there's a bug inside the engine I'd love to track it down, but I've never run across that issue myself - it sounds like it might be something similar to some problems coming up earlier that we were never able to really pin down, but your case sounds more reproducible (the other one was very rare).
Hi,

HINT: before you work through this rather lenghtly post, skip ahead because i solved the problem afterwards (read below)

i'll try to run you through the relevant code parts. I'm using Slick as the game engine, so naturally i have the init(), update() and render() methods where all the interesting code is located. I striped them from code that is not related to Box2D to increase readability.

Code:
   public void init(GameContainer container) throws SlickException {
      
      contacts = new ArrayList<ContactPoint>();
      
      // create physics engine
      worldAABB = new AABB();
      worldAABB.lowerBound = new Vec2(-150.0f, -150.0f);
      worldAABB.upperBound = new Vec2(universeDimension.x + 150.0f, universeDimension.y + 150.0f);
      Vec2 gravity = new Vec2(0.0f, 0.0f);
      boolean doSleep = true;
      world = new World(worldAABB, gravity, doSleep);

      // i have a second "world" that only holds my camera object. so the camera can "follow" my player
      // in a natural looking way, but i don't have to worry about the camera colliding with anything.
      // The camera is alone in this "world"
      AABB worldAABB1 = new AABB();
      worldAABB1.lowerBound = new Vec2(-150.0f, -150.0f);
      worldAABB1.upperBound = new Vec2(universeDimension.x + 150.0f, universeDimension.y + 150.0f);
      cameraWorld = new World(worldAABB1, gravity, doSleep);
      
      world.setContactListener(this);
      
      spawnPlayer();
      
      addSimulatedObject(new TwinCannon(Game.randomPositionInUniverse()));
      addSimulatedObject(new Sentry(new Weapon(300, Integer.MAX_VALUE, 5000, new Ammo(Ammo.STANDARD_VELOCITY,5.0), Weapon.MOUNT_TYPE_SINGLE ), 55.0, 2000, new Vec2( universeDimension.x/2-20, universeDimension.y/2) ));
      
      
      // define universe boundaries. place some boxes at the boundaries, so the player will
      // "bounce" off of them.
      Body worldBoundStaticBody = Game.createBodyAt( new Vec2(universeDimension.x / 2, universeDimension.y / 2) );
      worldBoundStaticBody.setUserData(this);
      
      PolygonDef westPolDef = new PolygonDef();
      westPolDef.setAsBox(50f, universeDimension.y/2 + 100, new Vec2( -universeDimension.x/2-50, 0.0f), 0.0f);
      worldBoundStaticBody.createShape(westPolDef);
      
      PolygonDef southPolDef = new PolygonDef();
      southPolDef.setAsBox(universeDimension.x/2+100, 50f, new Vec2(0.0f, -universeDimension.y/2-50), 0.0f);
      worldBoundStaticBody.createShape(southPolDef);
      
      PolygonDef eastPolDef = new PolygonDef();
      eastPolDef.setAsBox(50f, universeDimension.y/2+100, new Vec2(universeDimension.x/2+50, 0.0f), 0.0f);
      worldBoundStaticBody.createShape(eastPolDef);

      PolygonDef northPolDef = new PolygonDef();
      northPolDef.setAsBox(universeDimension.x/2+100, 50f, new Vec2(0.0f, universeDimension.y/2+50), 0.0f);
      worldBoundStaticBody.createShape(northPolDef);
      
      // populate camera system
      BodyDef camBodyDef = new BodyDef();
      camBodyDef.position.set( new Vec2(universeDimension.x/2,universeDimension.y/2) );
      camBodyDef.linearDamping = 1.0;
      camera = cameraWorld.createBody(camBodyDef);
      
      CircleDef circleDef = new CircleDef();
      circleDef.radius = 1.0f;
      circleDef.density = 1.0f;
      camera.createShape(circleDef);
      camera.setMassFromShapes();
      
      // spawn an AI Ship
      aiShip = new AIShip();
      aiShip.setPosition( new Vec2(universeDimension.x / 2 - 50, universeDimension.y / 2 +  50) );
      aiShip.setWaypoint( playerShip.getPosition().clone() );
      queueSimulatedObject(aiShip);
   }


The update() method:

Code:
   public void update(GameContainer container, int delta) throws SlickException {
      
      contacts.clear();
      
      // i'm aware of potential problems with variable timestep, but for now i like to keep it simple
      // and it has worked well until now
      world.step( (double)delta / 1000.0, iterations );
      cameraWorld.step( (double)delta / 1000.0, iterations );
      
      processContacts();
      
      // update all simulated objects
      // SimulatedObject is my wrapper or entity class (whatever you may call it) for everything that
      // moves around in my game. Most of them also have a box2D body encapsulated
      for( SimulatedObject o : simulatedObjects ) {
         if (o.isActive() ) {
            // this updates stuff like animations and some objects also
            // apply torque and force on themselfes, based on user input (turning and
            // accelerating the players ship e.g.). But nothing is created or destroyed
            // from inside this method. If that would be necessary i would use the
            // queueSimulatedObject() and disposeSimulatedObject() construct below, so not to
            // break my own for()-loop that i'm in right now.
            o.update(timestep);
         } else {
            disposeSimulatedObject(o);
         }
      }
      
      // remove disposable objects
      for( SimulatedObject o : disposable ) {
                  simulatedObjects.remove(o);
         if (o.getBody() != null) world.destroyBody( o.getBody() );
      }
      disposable.clear();
      
      // add queued objects. if it's necessary to create new SimulatedObjects this is done here,
      // outside of world.step() and my own SimulatedObject.update() loop
      for( SimulatedObject o : queuedSimulatedObjects ) {
         addSimulatedObject(o);
      }
      queuedSimulatedObjects.clear();
      
      // let the camera follow the player.
      camera.applyForce( new Vec2(-thrust * 400 * Math.sin(lookAt), thrust * 400 * Math.cos(lookAt)), camera.getWorldCenter());
      // position window centered on camera position
      screenCenterWorld = camera.getPosition();
      
   }


The render() method does not contain any Box2d related code, so i skip this one. here are some helper methods that were referenced from the code above.

The interface for the ContactListener:

Code:
   protected ArrayList<ContactPoint> contacts;

   public void add(ContactPoint point) {
      Object o1 = point.shape1.getBody().getUserData();
      Object o2 = point.shape2.getBody().getUserData();
      
      // ignore contacts without userdata
      if (o1 == null || o2 == null) return;
      
      //ignore Shot/Shot collisions
      if ( o1 instanceof Shot && o2 instanceof Shot) return;
      
      contacts.add(point);
      
   }
   public void persist(ContactPoint point) {}
   public void remove(ContactPoint point) {}
   public void result(ContactResult point) {}


The processing of the Contacts:

Code:
   protected void processContacts() {
      for(ContactPoint point : contacts) {
         
         Object o1 = point.shape1.getBody().getUserData();
         Object o2 = point.shape2.getBody().getUserData();
         
         // remove shots that hit the universe boundaries
         if ( (o1 instanceof Shot && o2 instanceof Game) ) {
            disposeSimulatedObject((SimulatedObject)o1);
         } else if ( (o2 instanceof Shot && o1 instanceof Game) ) {
            disposeSimulatedObject((SimulatedObject)o2);
         }
         
         // apply damage to anything that is Destructable
         if ( o1 instanceof DamagingObject && o2 instanceof Destructable ) {
            ((Destructable)o2).applyDamage( ((DamagingObject)o1).getDamage() );
            if (((DamagingObject)o1).disposesAfterApplyingDamage()) {
               disposeSimulatedObject((SimulatedObject)o1);
            }
         } else if ( o2 instanceof DamagingObject && o1 instanceof Destructable ) {
            ((Destructable)o1).applyDamage( ((DamagingObject)o2).getDamage() );
            if (((DamagingObject)o2).disposesAfterApplyingDamage()) {
               disposeSimulatedObject((SimulatedObject)o2);
            }
         }
         
      }
   }


Managing the list of SimulatedObjects.

Code:
   public static void addSimulatedObject(SimulatedObject o) {
      simulatedObjects.add(o);
   }
   
   public static void queueSimulatedObject(SimulatedObject o) {
      queuedSimulatedObjects.add(o);
   }
   
   public static void disposeSimulatedObject(SimulatedObject o) {
      disposable.add(o);
   }


And last but not least, to give you an example how a SimulatedObject wrapper-class creates it's underlying Box2D body, here is the constructor of the PlayerShip class (which is the Ship that the player controlls):

Code:
   public PlayerShip() {
      super();
      
      //create body definition
      BodyDef def = new BodyDef();
      def.position.set( getPosition() );
      def.linearDamping = 1.0;
      def.angularDamping = 2.0;
      
      // create the body
      body = Game.world.createBody(def);
      body.setBullet(true);
      
      // attach the front
      PolygonDef polDef1 = new PolygonDef();
      polDef1.clearVertices();
      polDef1.addVertex( new Vec2(0,3.1) );
      polDef1.addVertex( new Vec2(-.3,1.2) );
      polDef1.addVertex( new Vec2(.3,1.2) );
      polDef1.density = 1.0f;
      polDef1.friction = 0.3f;
      polDef1.restitution = 0.5f;
      body.createShape(polDef1);
      
      //attach the body
      PolygonDef polDef2 = new PolygonDef();
      polDef2.clearVertices();
      polDef2.addVertex( new Vec2(-.3,1.2) );
      polDef2.addVertex( new Vec2(-3.6,-2.1) );
      polDef2.addVertex( new Vec2(-3.8,-2.9) );
      polDef2.addVertex( new Vec2(3.8,-2.9) );
      polDef2.addVertex( new Vec2(3.6,-2.1) );
      polDef2.addVertex( new Vec2(.3,1.2) );
      polDef2.density = 1.0f;
      polDef2.friction = 0.3f;
      polDef2.restitution = 0.5f;
      body.createShape(polDef2);
      
      // update mass properties
      body.setMassFromShapes();
      
      body.setUserData(this);
   }


As far as i can tell that's all the Box2D related code in my project. If this doesn't help i may send you the code, but it's around 15MB (including resources like graphics), so probably a bit big for email. we'll see.

regards
Max
I think i solved the problem 😀

while reading through some other posts on the forum i stumbled upon this sentence from the user dc443:

Quote:
Yeah, I have to buffer any changes I plan to make and handle them after the timestep. (and even then, only want to modify each body once since there may be multiple events for each body)


The last part in the parenthesis got me thinking and i discovered that potentially i was disposing the same object twice (and therefore destroying the underlying Box2D body twice, too) between two calls of world.step() if i get more than one contact per body during the last world.step() call.

i had a quick look at world.destroyBody() and there seems to be no code that prevents double-destroying bodies. And as far as i can tell m_bodyCount gets screwed up afterwards, if you try to do this.

maybe thats something that could be tested (or asserted?) for in destroyBody() ?

Anywho...i removed this bug in my code by checking if the SimulatedObject i'm about to put into my "disposable"-List is already contained in that list, and skip it accordingly. I wasn't able to reproduce the exception since.

Sorry for bothering you with this , when it turned out to be my own fault 😳

but to look on the bright side, there is no bug in the engine 🙂

regards
Max
I experienced the same thing.
At least a warning when one tries to remove a body twice would be great and could save a lot of debugging time to Box2D users.
I believe what I used in my collision code was a stdext::hash_map<b2Body*,float> where the float stores the highest collision energy that the body was involved in, so that at the end it will choose the most energetic collision for each applicable body to perform operations with.

Looking at my code right now I couldnt really tell you how it works. It's too much work for me to figure it out right now. 😠 I'm just glad it worked the first time I attempted it.

IIRC an example Erin wrote in the manual was he used std::sort on an array of b2Body pointers in order to remove duplicates. I just used a hashmap instead.

I do know that I had to come up with this based on some thinking about inelastic collisions and physics equations.. this is what I use to determine the "power" of a collision.

Code:
float energy(float m1, float m2, float deltaV)
{
   if (m1 == 0.f)
      return 0.5f*deltaV*m2*deltaV;   // colliding with static body
   if (m2 == 0.f)
      return 0.5f*deltaV*m1*deltaV;
   float a = (m1/(m1+m2)*deltaV);
   float b = (m2/(m1+m2)*deltaV);
   return (a*a*m2 + b*b*m1)/2.0f;   
}
dc443 wrote:
Looking at my code right now I couldnt really tell you how it works.

A common problem to me, too... 😉 Well not really. I try to keep my code as tidy and understandable as possible, so it doesn't take much time to get into it again. Concerning the exceptions I came across, there's still a slight chance that they were related to some rare double-destroy case caused by self-written code that I've lost track of... However, as long as it's not reproducible, it's pretty much impossible to find out. 🙁

Anyway, I think it would be a good idea to provide a mechanism that prevents double deletions of bodies, shapes, joints, etc. One gets into trouble really easily with Box2D, because when bodies are connected through joints, dynamic interaction with bodies occurs (as usual for a game), then you have to apply a lot of modifications to your world. Normally, you'll soon notice when something goes wrong, but as Box2D complexities require somewhat complex code as well, the introduction of bugs is very likely to happen sooner or later. Obvious mistakes will be obvious, but it's possible to create rare-case hidden ones that will appear some day.

Of course, if you know what you're doing and where the pitfalls lie, you can programme around them and avoid those bugs, but it's not always easy.

Original thread: https://box2d.org/forum/viewtopic.php?t=36