Box2D Java

Thanks for the perspective.

I've been reading through "Programming in Scala" by Odersky et al. and I'm very impressed so far. It may take some effort to wrap my head around functional programming and away from imperative thinking, but I can see the merits in doing so. It's definitely a paradigm shift, but quite interesting. Scala is powerful!
ewjordan, I see you've done some more inlining, including fields in distance calculation to "avoid allocation on hot paths"

I wonder if the recent Java 1.6 Update 14 with Escape Analysis enabled will achieve similar effect? A previous version of JBox2D without these inlinings was about 15% speedier when turning that on. I haven't tried the current version as I'm updating it file-by-file (to see the differences I should repeat in Scala port) and it doesn't compile ATM.

With escape analysis, some objects that don't escape the method scope will not be allocated normally (they are allocated on the stack somehow).
Villane wrote:
ewjordan, I see you've done some more inlining, including fields in distance calculation to "avoid allocation on hot paths"

Yes, a lot of that is a contribution from JJC1138.

Quote:
I wonder if the recent Java 1.6 Update 14 with Escape Analysis enabled will achieve similar effect? A previous version of JBox2D without these inlinings was about 15% speedier when turning that on. I haven't tried the current version as I'm updating it file-by-file (to see the differences I should repeat in Scala port) and it doesn't compile ATM.

I've played around with 6u14, and I found that it helped a bit. Probably somewhere around 15% or so, as you mentioned, with an older version. I got the feeling that it wasn't really catching all the stuff it could have, though, so I decided that inlining was probably still the way to go.

Plus, I use a Mac, so I can't use 6u14 most of the time, and I don't think escape analysis (or rather, stack allocation/scalar replacement, which are really what we need - escape analysis was mostly put in to help coarsen locking, from what I understand) is going to be in the client JRE or turned on by default for quite some time, so while I think it's an awesome thing and I really hope it gets there, I don't think it's a full solution yet.

Quote:
With escape analysis, some objects that don't escape the method scope will not be allocated normally (they are allocated on the stack somehow).

"Somehow" is right - I don't know if you've ever taken a look through the JVM code, but it's a real beast. I have no idea how anyone manages to get a bit of work done on that thing, let alone put in sophisticated optimizations like this!
Was wondering if we could change the drawDebugData method to show sensors as a different color than the other shapes. I have them shown as yellow in my copy and it definitely helps.

Code:
if (b.isStatic()) {
    drawShape(s, xf, new Color3f(255f*0.5f, 255f*0.9f, 255f*0.5f), core);
} else if (b.isSleeping()) {
    drawShape(s, xf, new Color3f(255f*0.5f, 255f*0.5f, 255f*0.9f), core);
} else {
    drawShape(s, xf, new Color3f(255f*0.9f, 255f*0.9f, 255f*0.9f), core);
}

// to

if (b.isStatic()) {
    drawShape(s, xf, CLR_STATIC, core);
} else if (b.isSleeping()) {
    drawShape(s, xf, CLR_SLEEPING, core);
} else if (s.isSensor()) {
    drawShape(s, xf, CLR_SENSOR, core);
} else {
    drawShape(s, xf, CLR_DYNAMIC, core);
}

// where
private static final Color3f CLR_SENSOR = new Color3f(255f, 255f, 255f*0.5f); // Yellow
private static final Color3f CLR_STATIC = new Color3f(255f*0.5f, 255f*0.9f, 255f*0.5f); // Green
private static final Color3f CLR_SLEEPING = new Color3f(255f*0.5f, 255f*0.5f, 255f*0.9f);// Blue
private static final Color3f CLR_DYNAMIC = new Color3f(255f*0.9f, 255f*0.9f, 255f*0.9f);// Grey


Along the line of optimizations, I see there are quite a few places where constants could be used. For example, you create a new instance of the Color3f for every shape, every time, which also involves 3 multiplications. Not sure if there is compiler or runtime optimization of that, but never hurts to be more explicit (also easier to find them later).
I've been looking through the source for jbox2d, and I see a LOT of optimization opportunities. Not even structurally, just the mathematics within the methods (there are tons of unneeded and unnecessary allocations everywhere). I have begun to go through and optimize, it might take a day or two, but just with a few small changes I have been able to speed it up substantially. I'll keep it touch.

Also, these are not hacky and ugly optimizations, so the code will still be very readable.
May want to hold off for a little bit. Looks like big changes are coming http://www.box2d.org/forum/viewtopic.php?f=2&t=3201.

Perhaps we can help ewjordan do the port (although I haven't done C is over a decade).
Care to give an example of the math optimizations? What has given me most performance gain in the Scala port (quite similar to Java regarding performance) is manually inlining some of the vector/matrix operations. It makes the code uglier of course.
Villane wrote:
Care to give an example of the math optimizations? What has given me most performance gain in the Scala port (quite similar to Java regarding performance) is manually inlining some of the vector/matrix operations. It makes the code uglier of course.


Most of the math optimizations stem from adding "ToOut" methods in Vec2, Mat22, and XForm clases. Here is an excerpt from my optimized Vec2 class, and you can see the ToOut methods, along with many "final" modifiers for methods, with basically tells the compiler to inline those methods.
Code:
   public final static Vec2 cross(Vec2 a, float s) {
      return new Vec2(s * a.y, -s * a.x);
   }

   /* DMNOTE created */
   public final static void crossToOut(Vec2 a, float s, Vec2 out){
      float tempy = -s * a.x;
      out.x = s * a.y;
      out.y = tempy;
   }

   public final static Vec2 cross(float s, Vec2 a) {
      return new Vec2(-s * a.y, s * a.x);
   }

   /* DMNOTE created */
   public final static void crossToOut(float s, Vec2 a, Vec2 out){
      float tempY = s * a.x;
      out.x = -s * a.y;
      out.y = tempY;
   }

   public final static Vec2 min(Vec2 a, Vec2 b) {
      return new Vec2(a.x < b.x ? a.x : b.x, a.y < b.y ? a.y : b.y);
   }

   public final static Vec2 max(Vec2 a, Vec2 b) {
      return new Vec2(a.x > b.x ? a.x : b.x, a.y > b.y ? a.y : b.y);
   }

   /* DMNOTE created */
   public final static void minToOut(Vec2 a, Vec2 b, Vec2 out) {
      out.x = a.x < b.x ? a.x : b.x;
      out.y = a.y < b.y ? a.y : b.y;
   }

   /* DMNOTE created */
   public final static void maxToOut(Vec2 a, Vec2 b, Vec2 out) {
      out.x = a.x > b.x ? a.x : b.x;
      out.y = a.y > b.y ? a.y : b.y;
   }


This way, you don't have to create a new Vec2 object every time you call these methods. Another way to speed things up is to pool any temporary math objects so you don't need to do any allocation in the physics methods. This can be done with something like JStackAlloc (http://www.javagaming.org/index.php/topic,18843.0.html), which is very nice, or just have the pool objects created right there in the class (which is what I've been leaning towards while optimizing this).

Edge wrote:
May want to hold off for a little bit. Looks like big changes are coming http://www.box2d.org/forum/viewtopic.php?f=2&t=3201.


I am aware of the release, and I'm actually optimizing the most recent build.
Re: the big changes coming up, it sounds like it may yet be a while before those are stable enough in the C++ engine to port, and I think a lot of the action will really be happening in places where the vector math itself won't change (for instance, the broadphase, where there's very little vector stuff going on), so I think it's probably safe to do a bit of housecleaning optimization in the meantime.

I think it's a very good idea to add a full set of specialized versions of some of these operators that reuse existing objects (there are already some methods like this in there, but not all of them), from what I've seen you can often achieve results very close to inlining by doing this. The JVM appears to be quite adept at working with objects that already exist as quickly as it would work with local primitives, somehow (I've tested this, and while it depends on the situation, sometimes it's exactly as fast) - what it's bad at is creating/destroying large numbers of them, so I think these optimizations should be effective. This will preserve the code clarity quite a bit more than what I've done in most of the other places where I've fully inlined.

If we ever get to threading we may have to consider something like JStackAlloc, we'll see. I've been resisting that thus far for a few reasons, but multithreaded code would make pooling quite difficult in some cases - if those situations where it would matter can't be resolved by full inlining, then JStackAlloc is a very good solution. That's pretty far off in the future, though.
Villane wrote:
Care to give an example of the math optimizations? What has given me most performance gain in the Scala port (quite similar to Java regarding performance) is manually inlining some of the vector/matrix operations. It makes the code uglier of course.


Whoops, I misinterpreted this. I'm sure most optimizations will carry over, like ewjordan was talking about.

Optimizations wise, the changes are:
  • Basic java optimizations, like finalizing methods and reducing method calls (esp in the math library)
  • Adding non-allocation methods that populate a parameter instead of returning a new object
  • Pooling temporary math objects to local member variables that we can't avoid allocating
  • Straight mathematical inlining where it isn't too ugly (a bit faster than using pool objects)

I tried using JStackAlloc for the temporary math objects, but in most cases the performance hit of using that library was greater than the VM's allocation. But this massive amount of allocation still decreases performance makes the memory very unstable, which is also important for developers who have memory restrictions (like mobile devices). So we need to cut these allocations down.

ewjordan wrote:
If we ever get to threading we may have to consider something like JStackAlloc, we'll see. I've been resisting that thus far for a few reasons, but multithreaded code would make pooling quite difficult in some cases - if those situations where it would matter can't be resolved by full inlining, then JStackAlloc is a very good solution. That's pretty far off in the future, though.

As long as the methods with the pooled objects are called by a single thread, pooling the objects as local member variables should be fine. Other than that, I see no reason why it couldn't work. The hardest part would be figuring out what thread would do what in the engine, and I'm sure you have some ideas :)

Edit: The first pass of optimization for the common, collision, and the root dynamics packages is done and checked in, and there is a huge improvement in both Vec2 creations and performance. I still need to do the rest of the dynamics library, and the utils and tests if it's needed.

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