How To Get a List of All Colliding Bodies?

In the game I'm trying to build, I have a flame gameplay effect. Its semantics are quite simple: Apply damage to all entities that are inside the flame.

Assume that the flame is described as a circle and never moves or changes in any way once created (other than being destroyed at the end of its lifetime). The only thing the flame cares about are all bodies/fixtures that are overlapping with the circle. What is the best way to get this information?

My first attempt was to simply perform queries every frame to see what is overlapping with the circle and apply damage to all those entities found during the query. This works, but the performance becomes quite slow once many flames overlap each other (flames have no effect on other flames). My second attempt was to make the flame a sensor, set a collision filter such that it ignores collisions with other flames, and each flame maintains a list of game entities that are overlapping. To maintain this list, I utilize the BeginContact() and EndContact() callbacks to add/remove from the list. However, I've found that there is a rare event which causes a serious logic error (and occasional invalid memory access) which I suspect is due to a race condition in my handling of the BeginContact() and EndContact() events. If this race condition does indeed exist and is the cause of my problems, I'm not even sure how to fix it without going to extraordinary lengths to rearchitect my code to avoid it.

Does Box2D already maintain a list of all overlapping bodies/fixtures for a particular body? It seems like Box2D would already have such a list and would be available for inspection by the client.
Having looked at the documentation more carefully, it appears each body has a contact list. Is this what I'm looking for? It appears that the contact list doesn't guarantee that two fixtures are actually touching and you must make more specific queries, but it seems like this is what I want?
The intended way to do this is the first one you tried, using BeginContact and EndContact to update a list of everything the flame is currently touching.
Contacts have an IsTouching() function which you can use to find out if they are actually touching, so you could loop over every contact, in every flame, in every time step, for an inefficient solution.

In my opinion though, what you really want to do is understand why this happens and fix it:
Dale Kim wrote:
... a serious logic error (and occasional invalid memory access) which I suspect is due to a race condition in my handling of the BeginContact() and EndContact() events.

If you are using multiple threads, remember that the world should not be altered during a Step call. Ideally you would only let one thread handle physics in the first place.
Do you mean my second attempt? My first was to simply have each flame perform its own Box2D AABB query and just work with the returned list of fixtures (effectively rebuilding the colliding set every frame for each flame). My second attempt was to utilize a sensor fixture and let the Box2D collision system tell me of changes to my colliding set (simply maintaining the colliding set by applying deltas as indicated by BeginContact() and EndContact()).

The game is entirely single threaded (SDL sets up its own threads, but my main game loop is completely single threaded). The nature of the race condition is due to the fact that I buffer the handling of all BeginContact() callbacks for future processing, but immediately handle all EndContact() callbacks. Let me illustrate with an example.

Suppose I have 3 bodies:

1. Flame
2. Bullet
3. Damageable

Let them be arranged in the world such that, in the same frame, the flame and damageable start colliding and the bullet and damageable start colliding. Denote such collision events as <Flame, Damageable> and <Bullet, Damageable>. Additionally, any EndContact() between two bodies/fixtures can be denoted with parentheses such as (Flame, Damageable) to indicate Flame and Damageable have separated. Assume that Flame has an initial collision set being empty (denoted Flame -> {}). Consider the following two cases.

Quote:
Case 1: Box2D generates the BeginContact() callbacks in this order [<Flame, Damageable>, <Bullet, Damageable>].

1. We step Box2D and generate two BeginContact() callbacks to give us the buffered contacts.
2. After stepping, we process each contact event. First is <Flame, Damageable>. We add Damageable to Flame's colliding set: Flame -> { Damageable }.
3. Process the next contact event <Bullet, Damageable>. Suppose the bullet does damage to the Damageable and causes it to be destroyed/disabled. EndContact()s are immediately generated.
4. Handle the generated EndContact()s. Order does not matter for this case in this illustration. Suppose that they are generated in the order [(Bullet, Damageable), (Flame, Damageable)]. (Bullet, Damageable) is a no-op. (Flame, Damageable) causes us to remove Damageable from Flame's colliding set: Flame -> {}.


At the end of the frame, we have the Flame's colliding set to be empty.

Quote:
Case 2: Box2D generates the BeginContact() callbacks in this order [<Bullet, Damageable>, <Flame, Damageable>].

1. Step Box2D and generate BeginContact()s.
2. Process <Bullet, Damageable>. We damage the Damageable and destroy/disable it immediately, generating an EndContact().
3. Handle (Bullet, Damageable). No-op.
4. Resume handling the BeginContacts(). Next is <Flame, Damageable>. We add Damageable to the Flame's colliding set: Flame -> { Damageable }.


At the end of the frame, we have Flame's colliding set to be { Damageable } which now potentially points to invalid memory.

There appear to be many ways for me to attempt to navigate around this issue, but they all seem quite difficult to get right. The key issue here is that I've introduced concurrency by allowing the EndContact() callback events to be handled immediately, which can be generated during handling of the BeginContact() events. A few months ago, I intended for the EndContact() events to be handled in the same way as the BeginContact() events by buffering them and then processing them all at once at a later time. However, I deemed this to be problematic since the EndContact() event could be generated due to a call to DestroyBody(). By the time I would process the EndContact() events, the bodies could already be destroyed, which would lead me to touching invalid memory. This could still be viable, but I would need to take care to copy data that I would be interested in. Implementing this would be tedious and difficult for me, I think.

Something else is that you may observe that case 2 is a problem because we've decided to add a dying object to the Flame's colliding set. One may suggest to avoid processing any callback which involves a game object which is about to die. This may help reduce the occurence of this specific error, but I'm not convinced that this solution is maintainable as now I need to be very careful to understand the exact ordering possibilities of my operations between collision events of any pair of bodies/fixtures.

Suggestions?
Yes, I meant your second attempt, sorry.

Why not have the damageable hold the collision set? Seems to me that it's the damageable that needs to know this information, not the flames or bullets.
When processing the contacts, if the damageable has both bullet and flame contacts, it can just ignore the flames.
How is that correct? This means any time something is in flames and gets hit by the bullet, I won't apply damage from the flame? This is not the behavior I want.

Additionally, moving the collision set to the damageable instead does not change the fact that I have this race condition in my code due to buffering BeginContact() events and handling EndContact() events immediately. I know that if I perform the BeginContact() logic immediately that my race condition disappears, but I prefer to buffer them all if possible since I have many objects that interact differently (some which change Box2D state and others that don't); I don't want to have to create special case code for each pair of objects to avoid race conditions... but if I'm forced into it, I will.

Is there a suggested methodology for handling the contact callbacks? The documentation is pretty brief about this and only mentions in passing the fact that you should buffer contact data and process immediately after stepping to prevent invalidating Box2D state during its step.
I was assuming that the bullet would completely destroy the damageable as in your case 1, so the flame could be ignored. But if the bullet does not destroy the damageable completely, there is no reason you could not still apply damage from the flame.
Maybe you could give another example of interactions that require this 'race condition' causing approach - the flame and bullet situation doesn't really need it as far as I can see.

The mention about processing things after the world step is only for things that will change the Box2D world. It's perfectly ok to do any other logic, like decrement the health of things getting hit by bullets, for example. Just don't actually destroy the body until the step is complete.
I don't feel like there is any other example to give. The one I gave with the two different orderings illustrate exactly the problem I have and is potentially the case for any Box2D contact callback processing I do. The core issue seems to be that the BeginContact() callbacks will be generated (and subsequently buffered), then when I process the buffered events, it could generate an EndContact() that may invalidate other BeginContact() events that I have not yet processed. This is possible for me since my processing of the collision events can change the Box2D state. Your suggestion then, is to avoid changing Box2D state in these callbacks completely? Only perform my game state update, then when I've finished processing all of my callbacks and am outside the Box2D step, perform whatever Box2D state changes are necessary?
Okay. I'll give an outline of how I would try to handle it, see what you think.

There are two types of damage, one-hit (bullet) and recurring (flame). For a one-hit damage you could decrement the health of the damageable immediately, any time. For the recurring damage you can update a list of touched flames in the damageable so that it can decrement its health every time step.

Contact callback:
Code:
// BeginContact
if ( bullet vs damageable ) {
    mark the bullet as finished
    decrement health of damageable
    play bullet hit damageable sound
}
if ( flame vs damageable ) {
    add the flame to the list held by the damageable
}

// EndContact:
if ( flame vs damageable ) {
    remove the flame from the list held by the damageable
}

After the time step:
Code:
for ( all damageables with non-empty flame list ) {
    decrement health of damageable according to touched flames
    update damageable burning sound etc
}

for ( all bullets marked as finished ) {
    destroy the bullet
}

for ( all damageables with health <= 0 ) {
    destroy the damageable
    play damageable died sound etc
}

When I say 'mark as ...', usually I find it's most efficient to add a pointer to that thing to a list or set, rather than setting a variable in the thing itself that you would then have to loop over all the things to check.

The key thing is to keep Box2D world state changing calls out of the contact listener, and not to rely on any b2Contact pointers being valid outside the contact listener. So it's not really the contact events themselves you want to be buffering, but rather information about anything you want to do as a result of those contacts, that would change the physics world. For example in BeginContact, you can do things like decrementing health and playing the bullet-hit-damageable sound immediately because that does not change the Box2D world, but if you wanted to say, give the damageable some impulse from the bullet you would need to do that after the step.
Yes, I think your example pretty much matches my current thinking of the "correct" way to handle the contact callbacks. It appears my original thinking for the callback processing from months ago was just wrong, and I didn't have the experience to understand the implications of my decision at the time.

Thanks for the help! I shall try switching some of my code over to this method of callback handling and see how it goes.

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