calling b2World functions from ContactListener object

Hi,

I have a problem regarding my bContactListener, bodies, and a dynamically created distancejoint. I was hoping to join the bodies together with a distance joint upon a collision event, but this is not possible due to a programming structural error (?). So there's a high chance that this might not even be a problem with the box2d class... Although I hope it is. So here it goes.

In my main .as file I have created my world/ bodies/and a contact listener objects. Upon collision I have added this code into the bContact Listener class;

public class bContactListener extends b2ContactListener
{
override public function Add(point:b2ContactPoint):void {
createJoint(point.shape1.GetBody(), point.shape2.GetBody());
}

public function createJoint(body1:b2Body,body2:b2Body){
var djd:b2DistanceJointDef = new b2DistanceJointDef();
djd.Initialize(body1, body2, new b2Vec2(0,0),new b2Vec2(0,30));
djd.collideConnected = true;
var distJoint:b2DistanceJoint = m_world.CreateJoint(djd); <--HERE BE THE OFFENSIVE CODE
}
... etc...
}

The problem is that m_world cannot be accessed from the b2ContactListener class. Is there any way around this?

Also I noticed that the add function is called highly frequently. As such, I'm wondering if the creation of a joint definition within the add function is the best place, and whether there is a better place I can do this?

Help would be greatly appreciated
Basic mistake. You shouldn't modify the b2World from the contact callback. There is some talk about how to improve the contact API as this mistake is made quite often, and the callback is not that userfriendly.

In your case you should store some kind of list of contacts that happened, and handle them after the world.step function is finished.
Thanks for the quick reply Daid. I'm trying to get my head around the world.step event. I'm assuming that is the step that happens after the 'add' function is called.

So... I thought that the Remove function might be a route i could pursue. I changed the void output setting on the remove function to b2distanceJoint, so that I could output a B2distanceJoint object to my real m_world object and create my connection from there on. However I get an incompatibile override error.

I suspect my interpretation of your world.step might be slightly off? How do I know when the world.step function has finished?
Obviously, stepping is over when Step returns. All events currently are called inbetween the time you call step, and the time it returns, so all of them require caching.
You should have your program loop something like this:
for(;;){
myWorld.Step();
ProcessEvents();
UpdateGraphics();
}

where ProcessEvents goes over a list of events you've stored from the contact listener. As Daid said, this is not ideal and we are aware of it, but current design does have some sense behind it: As it is not valid to access the bodies at the time, it is safe for Box2D to do behind the scenes optimizations.
For AS3, replace "for (;;)" with "private function onEnterFrame(event: Event): void" and register it as a listener somewhere. 😉
Alright. You've given me enough material to play with so I'll have a stab at it in the morning and post some code when/if I get it sorted. Thanks for the tips
ok.. I've made an attempt at this and I think it's a fair shot. Only problem is the way I've done this is pretty ungraceful. So forgive me on that.

There are two fairly major changes I made. the first is in the bcontact listener class and the second is in the main.as:

Part 1: In the bContactListener Class I have created 2 array objects that correspond with point.shape1 and point.shape2.

public var shapeOne:Array; // these can be accessed by m_world in the parent holder
public var shapeTwo:Array;

override public function Add(point:b2ContactPoint):void
{
if ( (point.shape1.GetBody().GetUserData().name == "boundary") || (point.shape2.GetBody().GetUserData().name=="boundary") )
{
//if collision is between the ground 'boundary' then DONT list this to the array. we don't want joints to be formed with the ground.
} else {
if(i==0)
shapeOne[i]= point.shape1.GetBody();
shapeTwo[i]= point.shape2.GetBody();

}
//if shape1 and shape2 are the same collision as the first collision don't note this down either
if ( (point.shape1.GetBody()==shapeOne[i-1]) && (point.shape2.GetBody()==shapeTwo[i-1])){
//don't do anything
} else {
shapeOne[i]=point.shape1.GetBody();
shapeTwo[i]=point.shape2.GetBody();
i++;
}

}
//trace(i);
}

Part 2: Back in the main.as I have used this code within the function called from a onEnterFrame listener:

m_world.Step(1/30, 10);
//this is where I need to create new joints.
//run through the collisions list. Make joints between collisions.

//the following joint vars are defined as global.
djd = new b2DistanceJointDef();
//create joints between two bodies from shapeOne and shapeTwo arrays.

for (var j:uint=0;j<myListener.shapeOne.length; j++)
{
djd.Initialize(myListener.shapeOne[j], myListener.shapeTwo[j],
new b2Vec2(myListener.shapeTwo[j].x,myListener.shapeTwo[j].y),
new b2Vec2(myListener.shapeTwo[j].GetPosition().x,myListener.shapeTwo[j].y.GetPosition().y));
//Define whether the two objects will be allowed to collide with each other.
djd.collideConnected = true;
m_world.CreateJoint(djd);
}

THIS WORKS! for about 5 objects, before the whole process grinds to a miserable halt.

I know where this is going wrong though. Part 1. I've traced the index variable i- whcih udpates the arrays' lengths. And it's numbers soar when more than 3 objects are colliding. So this is somethign to do with creating the array list elements, which are converted to joints between (shape1 <--> shape2) and (shape2<-->shape1) in the main.as step() updates. Especially when, realisitically, they should be the same single joint... Now, is there an easier way that I can reduce the collision list without using heinously detailed conditionals? My comp sci really isn't up to par.

I've been scouring the forum for tips and for some reason I recall a 'hash table' being of relevance. Can't find that post though damnit! If i'm correct could someone point me towards the direction of the most dumbed down hash table synopsis out there?
The easiest way of storing the contact events for later is just to keep a whole copy of the b2ContactPoint. Then iterate over them later. You don't need make up your own storage schemes as you've done here.

That said, I don't see anything massively wrong with your event handling. I don't seem any "heinously detailed conditionals". Could it be that your code is grinding to a halt as you are making many many distance joints? I don't see any code stopping a joint being made multiple times on the same pair. Your distance code cannot compile in it's current state, anyway, so it's hard for me to tell.

Hash tables in flash are easy (with strings as keys), you already know them by a different name:
var myHashTable = {};
myHashTable['foo']=1;
myHashTable['bar']=2;
Boris, you seem to be on every topic in this forum and, without sounding like a kissarse, the work you do is greatly appreciated.

I think my problem is, as you mentioned, that I'm creating an exponential amount of joints. How might I be able to filter through these contact points and say... 'no don't make a joint from this contact point' and 'yes this contact point is good for creating a joint'

Should I store every contact point in an array as I have done (minus the conditionals)? ie have them separated as ShapeOne[] and ShapeTwo[].but review them afterwards in the main.as? I can put them in a nested for loop:

for (uint i -> shapeOne.length)
{
for (uint j-> shapeOne.length)
if (shapeOne i =shapeOne j)
{

if (shapeOne[i] = shapeTwo[j]) { DO NOTHING};
else {MAKE A JOINT}

}
}
Something similar to the above... I'd have to incorporate some sort of conditional to check whether joint A>B is the same as B>A too.
I'm afraid this might be quite a large array to syphon through though. I have 20 objects falling from the sky. By the time my player object has caught 5 objects the speed of the program reduces dramatically. By 8 the program is so slow it doesn't really run.

... a light just went on in my head. Do I even need to store the b2ContactPoint in an array? or is there a function within the b2contactpoint class that will let me scan through the contact list anyway? Then again.. Even if I could, I suppose it wouldn't make much of a difference with regards to post processign.

Adrian
You need to sort out how you are going to do it for yourself. You probably want to maintain a hash object associated with each body, which contains the list of what body you've already joined to it. That is quick to check.

But it seems a bit overkill. In flash, you are not going to be able to make huge amounts of distance joints, so I don't see what is wrong with iterating over every joint a body has to check if one already exists for the given pair

I think you need to sit down, and decide what it is you want to do, as it doesn't sound you've got it entirely straight.

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