AS3 2.1 Port (Alchemy), WCK Update and Kinematic Demos

Hi.

Could someone plz help me setup the debugdraw ? I am using flex and debugdraw in this port seems not to work in the same way with the "native" port. And c++ version manual doesnt help in this issue.

I was also wondering why there is an error in the DebugDraw.as class. It uses the reserved term static in lines 20 and 70 (trying to color the static objects as I understood). Wont this affect its use?

Thanks in advance.
See the "TestBed" folder for examples of using DebugDraw. It compiles fine in Flash - does Flex not like "static" being used as an object key?
mayobutter wrote:
See the "TestBed" folder for examples of using DebugDraw. It compiles fine in Flash - does Flex not like "static" being used as an object key?


Thanks for the quick answer mayo.

So, after seeing the testbed examples it seems that debugdraw is easier to use it in your port. Seems like I only need to instantiate it and update it in an enterframe event. However I can't make it work even in simple example of just creating a ground body part. Could someone check what I am doing wrong and I cannot see my static body? (probably some silly noob mistake..)
Code:
package {
   import flash.events.Event;
   import Box2DAS.Collision.Shapes.b2PolygonShape;
   import Box2DAS.Common.*;
   import Box2DAS.Dynamics.*;
   
   import flash.display.Sprite;

   /**
    * @author kti
    */
   public class Zztest extends Sprite {
      
      public static var debug:b2DebugDraw;
      public static var myWorld : b2World;
      public static const RATIO:Number = 30;
      
      public function Zztest() {
         
         setupWorld();
         createGround();
         
         b2Base.initialize();
         debug = new b2DebugDraw();
         addChild(debug);
         
         
         addEventListener(Event.ENTER_FRAME,goWorld);
         
      }

      

      private function goWorld(event : Event) : void {
         myWorld.Step(1/60, 10,10);
         debug.graphics.clear();
         debug.world = myWorld;
         debug.scale = RATIO;
         debug.Draw();
         
      }

      private function createGround() : void {
         
         var groundFixture:b2FixtureDef = new b2FixtureDef();
         var groundBodyDef : b2BodyDef = new b2BodyDef();
         groundBodyDef.type = b2Body.b2_staticBody;
         groundBodyDef.position.v2 = new V2(0 / RATIO, 390.0 / RATIO);
         var groundBody:b2Body = myWorld.CreateBody(groundBodyDef);
         
         var myShape:b2PolygonShape = new b2PolygonShape();
         var vertices:Vector.<V2> = new Vector.<V2>;
         vertices[0] = new V2(0/RATIO,400/RATIO);
         vertices[1] = new V2(550/RATIO,400/RATIO);
         vertices[2] = new V2(550/RATIO,350/RATIO);
         vertices[3] = new V2(0 / RATIO, 350 / RATIO);
         myShape.Set(vertices);
            
         groundFixture.shape = myShape;
         groundFixture.friction = 0.5;
         groundFixture.restitution = 0.3;
         groundFixture.density = 0.0;
         groundBody = myWorld.CreateBody(groundBodyDef);
         
      }

      private function setupWorld() : void {
         
         var gravity:V2 = new V2(0,9.8);
         
         var doSleep:Boolean = true;
      
         myWorld = new b2World(gravity, doSleep);
      
      }
   }
}


Btw it seems that the debugdraw class compiles fine, so just ignore my previous observation 🙂

I would really like starting using this port. It seems faster, more up2date and it will be more up2date since it compiles directly from the original c++ one. Plus i like its syntax better.
Very impressive job setting this up. It's a bit of a pain figuring out Alchemy but now I have a cygwin terminal via puttycyg, and a bash script to build and copy the swc to my project folder. I can make a change in C and see it in my running SWF in under a minute. Very sweet, works perfectly, and is much faster than Boris's fine port. I'd say this has made the need for the AS port of box2d obsolete, for my needs at least. It took me 4 hours to convert a large project (http://www.jetpackhq.com/blog/ - new swf not posted yet) to use this, it was a relatively easy task because I had already wrapped most of box2d for portability.

Changes I had to make to get this working in Flex/FlashDevelop:

* I added helper functions to V2 and M22 to make the transition smoother, like Set, SetZero, SetV, NegativeSelf, Length, Add, etc
* note: new CircleShape() no longer takes radius as a parameter
* SetAsOrientedBox() => SetAsBox()
* SetAsVector() => Set() - I changed Set() to take an optional length parm for speed & simplicity - constantly resizing a vector / reallocating elements is slow
* SetPositionAndAngle() => SetTransform()
* SetAngle() => SetTransform()
* SetLocalPosition() => shape.m_p.x = 123
* ApplyLinearImpulse() => ApplyImpulse()
* manifold.m_normal => manifold.normal
* b2world.DrawDebugData() => b2debugdraw.Draw()
* on all my fixtures: m_reportBeginContact = m_reportEndContact = true;

Notes:

* The lack of customizable contact filter was a problem for me, what I need is additional complex contact filtering (run in AS) AFTER the regular filter determines there is a contact. To do this, I added ShouldCollide() to the WorldListener in box2d.h and had it call ShouldCollide in b2World.as, only when collide==true.

* I like to initialize a b2BodyDef/b2FixtureDef before each use, so I can set only non-default values. I give each a custom Init() function, but when setting b2FixtureDef.shape=null, there's an error in the setter. I changed it as follows. Not sure if this is valid:
public function set shape(v:b2Shape):void { mem._mw32(_ptr + 4, (v? v._ptr : 0)); _shape = v; }

* In b2World, you are calling getTimer() - the world simulation should not know anything about real time, only the time it is given. This was causing my world step to occasionally skip. I changed the line:
stepTime = getTimer(); to: stepTime += timeStep;

* The documentation on Alchemy is awful, but have you tried AS3_Shim? I wonder if it would make calls from C any faster. Or for that matter AS3_Proxy

* Dynamic objects (Object()) are extremely slow - I'm referring to b2Filter.filter. In my testing, get/set of a declared object member takes 1ns. For a dynamic member: 40ns get, 80ns set

* bug: in b2WorldManifold.Initialize(), if there are no points it returns and the normal may be null. In the C, the normal exists before that call so that doesn't happen. If you create the normal in the constructor (like the C), you can do math directly on it without allocating new V2's all the time (when reusing the manifold).

> If you instantiate a b2Vec2 and manipulate it, you're basically writing over random memory.

That seems like something that should have some protection built around it!

> I've been thinking about ways to merge the V2 / b2Vec2 classes together.

Instead of extending b2Base, why don't you give it a b2Base member (private via a custom namespace), and only communicate with the C++ when the base var is not null?
Thanks for the feedback! Here's my feedback to your feedback:

AdamAdept wrote:
Changes I had to make to get this working in Flex/FlashDevelop:

A lot of these are because the C++ version has changed. I try to keep the function definitions in sync with that version.

AdamAdept wrote:
* on all my fixtures: m_reportBeginContact = m_reportEndContact = true;

Waring: This means each contact will cause a jump from C++ to AS3 (to dispatch the contact event). These jumps are expensive and may slow things down. It's better to only flag the ones you need.

AdamAdept wrote:
The lack of customizable contact filter was a problem for me, what I need is additional complex contact filtering (run in AS) AFTER the regular filter determines there is a contact. To do this, I added ShouldCollide() to the WorldListener in box2d.h and had it call ShouldCollide in b2World.as, only when collide==true.

Again, this means each contact will cause a C++ to AS3 jump. By design I left customizable filtering out. It's unnecessary anyway: You can just listen for the begin contact event and disable the contact.

AdamAdept wrote:
* I like to initialize a b2BodyDef/b2FixtureDef before each use, so I can set only non-default values. I give each a custom Init() function, but when setting b2FixtureDef.shape=null, there's an error in the setter. I changed it as follows. Not sure if this is valid:
public function set shape(v:b2Shape):void { mem._mw32(_ptr + 4, (v? v._ptr : 0)); _shape = v; }

That's valid and will be added next commit.

AdamAdept wrote:
* In b2World, you are calling getTimer() - the world simulation should not know anything about real time, only the time it is given. This was causing my world step to occasionally skip. I changed the line:
stepTime = getTimer(); to: stepTime += timeStep;

stepTime isn't used at all to simulate physics, don't worry about that; it won't effect your timestep. It's just used internally to "id" a timestep so you can tell, in event listeners, different time steps apart. For example: ContactEvent used the step time to determine if it's cached World Manifold is out of date.

AdamAdept wrote:
* The documentation on Alchemy is awful, but have you tried AS3_Shim? I wonder if it would make calls from C any faster. Or for that matter AS3_Proxy

I did play around with those functions at some point... can't remember how they work but I didn't find anything groundbreaking.

AdamAdept wrote:
* Dynamic objects (Object()) are extremely slow - I'm referring to b2Filter.filter. In my testing, get/set of a declared object member takes 1ns. For a dynamic member: 40ns get, 80ns set

Good point. I'll add a dedicated class.

AdamAdept wrote:
* bug: in b2WorldManifold.Initialize(), if there are no points it returns and the normal may be null. In the C, the normal exists before that call so that doesn't happen. If you create the normal in the constructor (like the C), you can do math directly on it without allocating new V2's all the time (when reusing the manifold).

Also good point.

AdamAdept wrote:
> I've been thinking about ways to merge the V2 / b2Vec2 classes together.
Instead of extending b2Base, why don't you give it a b2Base member (private via a custom namespace), and only communicate with the C++ when the base var is not null?

I'm worried about introducing even the tiniest amount of overhead to vector operations because they are used so much.
If anyone is interested, I added the alchemy generated AS3 code. This is what gets compiled into the Box2D.swc package. The first part of the code is the framework that allows C++ and AS3 to talk to each other. The second part is the C++ compiled into AS3 (it's pretty much unreadable). Might be handy if you need to look under the hood.

https://github.com/jesses/wck/raw/maste ... achacks.as
mayobutter wrote:
AdamAdept wrote:
Changes I had to make to get this working in Flex/FlashDevelop:

A lot of these are because the C++ version has changed. I try to keep the function definitions in sync with that version.


Yeah, I'm just trying to make the porting/adoption process faster - I wasn't sure if I'd be sticking with this version but its working great.

mayobutter wrote:
AdamAdept wrote:
* on all my fixtures: m_reportBeginContact = m_reportEndContact = true;

Waring: This means each contact will cause a jump from C++ to AS3 (to dispatch the contact event). These jumps are expensive and may slow things down. It's better to only flag the ones you need.


Unfortunately I think I need them all because different entities react with the environment in different ways. Maybe I can weed some of them out if more optimization is needed near the end of the project. It would be nice to batch all the contact reports in a single call, but this would require a big change to the C and I'm not even sure it would work.

mayobutter wrote:
AdamAdept wrote:
The lack of customizable contact filter was a problem for me, what I need is additional complex contact filtering (run in AS) AFTER the regular filter determines there is a contact. To do this, I added ShouldCollide() to the WorldListener in box2d.h and had it call ShouldCollide in b2World.as, only when collide==true.

Again, this means each contact will cause a C++ to AS3 jump. By design I left customizable filtering out. It's unnecessary anyway: You can just listen for the begin contact event and disable the contact.


I tried it that way at first, however I have situations where a body needs to change solidity in the middle of contact. Right now I change the contact mask, then just flag the body involved for refiltering and the contact will automatically add or remove. It would be an improvement however, if I could set the contact to act as a sensor, so I could still reference it but it wouldn't collide, and later set it solid again. Is there a way to do that? And if you disable the contact, can you still get the "remove contact" event?

mayobutter wrote:
AdamAdept wrote:
* In b2World, you are calling getTimer() - the world simulation should not know anything about real time, only the time it is given. This was causing my world step to occasionally skip. I changed the line:
stepTime = getTimer(); to: stepTime += timeStep;

stepTime isn't used at all to simulate physics, don't worry about that; it won't effect your timestep. It's just used internally to "id" a timestep so you can tell, in event listeners, different time steps apart. For example: ContactEvent used the step time to determine if it's cached World Manifold is out of date.


I know, and if the step ran in under 1ms, and I was running 2 steps in a row, it would use the cached manifold from the previous step 🙂
I'm not sure what the result of that was, but it was acting funny. It happened pretty often when there were only a few objects moving.

mayobutter wrote:
AdamAdept wrote:
* bug: in b2WorldManifold.Initialize(), if there are no points it returns and the normal may be null. In the C, the normal exists before that call so that doesn't happen. If you create the normal in the constructor (like the C), you can do math directly on it without allocating new V2's all the time (when reusing the manifold).

Also good point.


Also, I had a case of the switch (manifold.type) hitting the default a few times. I didn't look into what caused that, I just init the manifold when it happens. (I also init when (manifold.pointCount == 0), because I expect an Initialize function to initialize! - but that's out of your purview)

mayobutter wrote:
AdamAdept wrote:
> I've been thinking about ways to merge the V2 / b2Vec2 classes together.
Instead of extending b2Base, why don't you give it a b2Base member (private via a custom namespace), and only communicate with the C++ when the base var is not null?

I'm worried about introducing even the tiniest amount of overhead to vector operations because they are used so much.


Yeah that's true. I really wish AS3 had macros. That's a tricky one. ... Actually your implementation does make a lot of sense. However, IMHO I would make a big change: Reverse V2 and b2Vec2. The current V2 exposes the interface everyone expects from b2Vec2, and the current b2Vec2 exposes a completely different interface, one of live synchronization. That would make the adoption process easier for people. That's just an opinion though and it works fine as is, also I'm already converted so it would be more work for me 🙂

Also a couple optimizations: isn't there a bit of overhead is involved in using a setter? I don't remember offhand. But the Set function could call mem._mwf() directly for x & y. Also every "get v2()" is creating an object - it might be a good optimization to cache the V2 as a private member of b2Vec2.
QueryPoint the slow point of my project now, I assume because of the callback to AS3. I'm trying to optimize it by keeping the callback in C, and populating an AS3 array with each fixture found. I also added a categoryBits filter to the call, to speed it up.
However when I get back to AS3, the array contains only ints. Here's what I'm doing in the callback:

Code:
       asm( "arr.push(%0)" : : "r" (fixture->m_userData) );


Any idea how to properly accomplish this? I haven't had much luck finding in-depth documentation on Alchemy.

Also, why is _ptr a Number, not an int?
OK, I made an optimized version of QueryPoint which very rarely needs to callback to AS3 (in my use cases anyway). I do this by allowing exclusion of a body and filtering by category:

Actionscript:
Code:
public function QueryPoint(callback:Function, p:V2, excludeBody:b2Body=null, categoryBits:int=0):void {
    lib.b2World_QueryPoint(_ptr, callback,
        p.x, p.y, excludeBody, categoryBits);
}


C++
Code:
class QueryPointCallback : public b2QueryCallback {
public:

    AS3_Val callback;
    b2Vec2 testPoint;
    b2Body* excludeBody;
    int categoryBits;

    bool ReportFixture(b2Fixture* fixture)
    {
       if(excludeBody && fixture->GetBody()!=excludeBody) return true;
        if(categoryBits)
        {
            const b2Filter& filter = fixture->GetFilterData();
            if(!(categoryBits & filter.categoryBits)) return true;
        }
        if(!fixture->TestPoint(testPoint)) return true;

        return AS3_IntValue(AS3_CallT(
            callback, NULL,
            "AS3ValType",
            (AS3_Val)fixture->m_userData
        )) == 1;
    }
};

AS3_Val b2World_QueryPoint(void* data, AS3_Val args) {
    // args
    b2World* world;
    AS3_Val callback;
    double posX, posY;
    b2Body* excludeBody;
    int categoryBits;
    AS3_ArrayValue(args, "PtrType, AS3ValType, DoubleType, DoubleType, PtrType, IntType",
        &world, &callback, &posX, &posY, &excludeBody, &categoryBits);

    // prepare
    QueryPointCallback callbackHandler;
    callbackHandler.callback = callback;
    callbackHandler.testPoint.Set(posX, posY);
    callbackHandler.excludeBody = excludeBody;
    callbackHandler.categoryBits = categoryBits;
    b2AABB aabb;
    aabb.lowerBound.x = posX-0.001;
    aabb.lowerBound.y = posY-0.001;
    aabb.upperBound.x = posX+0.001;
    aabb.upperBound.y = posY+0.001;

    // call
    world->QueryAABB(&callbackHandler, aabb);

    return AS3_Null();
}


With this code, most of the time I don't get a single callback to AS3. And the result? QueryPoint is still my bottleneck. So, I guess QueryPoint is just slow and the AS3 callback wasn't a big factor. Well that was fun.
Hi,

I've been using the Alchemy port for a bit now, and seeing how successful it is, I'm looking to port some various C++ libraries myself. The Box2D port has been an excellent reference so far, and I've gotten Alchemy to the point on my Windows machine with Cygwin where everything is compiling very smoothly.

However, I was wondering how the ActionScript interface classes are handled. Seeing as how Alchemy only makes the .swc, I assume those are written by hand. But stuff like "public function get m_flags():int { return mem._mru16(_ptr + 4); }" seems like it would be horribly tedious and error-prone to do manually. Is there a way that you have this code auto-generate?

Thanks!

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