Dynamically Disabled Collision Responses (Hacking Box2d)

I think Box2d is missing a very important feature: allowing client code to opt out of collision responses based on contact point Add events. This feature would be necessary for both breakable objects (when the cannonball hits the window, we want to queue the destruction of the window and disable collision response so the cannonball doesn't bounce off) and Mario-style platforms (if entering the platform polygon from the top, it should be solid; if entering from another side, it should remain insubstantial until you leave it, allowing you to walk under it or jump up through it.)

I seem to have something working. I added a new member variable to b2Contact (m_disabled:Boolean) and modified b2World's Solve() to skip contacts which have m_disabled set when looping through bodies' contacts and adding them to islands. Finally, I exposed the b2Contact object to ContactListener.Add() (by passing it as a second parameter) so that my own contact listener can set m_disabled. Yes, there are probably cleaner ways to do this.

So far, I'm pleased with the results! I think I'll try out platforms and breakables shortly. If anyone's interested I can post a diff patch of my rather simple changes to the library. Maybe example swfs too?

Has anyone else attempted this? Care to share pitfalls or success stories?
We are quite aware of this shortfall, though you've given a very perceptive summary. No one else has attempted this as far as I know, merely complained it's not there.

The general consensus was it would be attempted in the future, but no one immediately took a shot at it. It was also postponed pending a more in depth attack on the contact listener at all, as the event call backs would need to be changed before a "cleaner" API emerged, as you say.

Your work sounds like it works well, but only when CCD is disabled. The real difficulty, I gather, is doing the same modifications for SolveTOI, as there is the danger that the contact will still be used for TOI calculations, but as there is no collision, never removed, leading to an infinite loop of waiting for it to disappear.
Thanks for pointing out my glaring omission! I set my bodies as bullets and they no longer obeyed my m_disabled flag. I looked through b2World.SolveTOI(), and although I understand it even less than b2World.Solve(), I believe I figured out the two spots to check for my b2Contact flag. It seems to be working for my simple test case of boxes and circles bouncing around, with or without CCD!

I'm attaching my changes to Box2D in the form of a diff with context if anyone else wants to try this. If someone prefers another format, please ask and I'll see what I can do. If you find any problems with my approach, or have any suggestions, please let me know!
Here's a quick demo of Mario-style platforms with this hack:

http://www.zshare.net/flash/511187048c9f3ebb/

Only the tops of the platforms are supposed to be "solid" for the squares, and only if they approach from the outside. I'm doing this by checking the normal angle in my listener.Add() and disabling collisions if the platform is "down" from the square.

The square on the right is a bullet, the other is not. [EDIT: just to show that both work.]
I don't see any difference between the bullet and the nonbullet. Am I meant to?
The only semi bug I can find is around corners there's a bit of inconsistency. After I rotate enough, it disables the collision. Fine. But then I can move the boxes out of contact with each other, but keeping the AABBs overlapping, and it will "remember" the disabledness, even if I subsequently bring the box down in such a way that fresh, it wouldn't be disabled.

Other than that, very nice. I'm sure you'll see absolutely tons of people badgering you now to recreate the effect.
I've been doing this for a while now, here's my solution (in the contact listener):

Code:
var ce:b2ContactEdge = b2shape.m_body.m_contactList;
while(ce && !(((ce.contact.m_shape1 == b2shape) && (ce.contact.m_shape2 == b2other)) || ((ce.contact.m_shape2 == b2shape) && (ce.contact.m_shape1 == b2other)))) {
   ce = ce.next;
}
b2contact = ce.contact;
b2contact.m_flags |= b2Contact.e_nonSolidFlag;


So it first looks for the b2contact (this probably introduces a lot of overhead) that corresponds to the shape pair, then tells box2d to treat it like it would a sensor. I was just thinking today about making a request to have the b2contact be a property of the ContactPoint so the listener could act on it.

Your demo is very nice though... does it work with rotated platforms?
Excellent catch, Boris, thanks! I believe I've fixed that by resetting my flag if I get a listener.Remove() event when the b2Contact's m_manifoldCount is zero. I think this only happens when the last b2ContactPoint is removed from a b2Contact (although multiple Remove()s may fire, but that won't affect me.)

mayobutter, thank you for pointing out that there already is a flag that does exactly what I need! I've removed my m_disabled member variable and have exactly the same results using m_flags|e_nonSolidFlag. That simplifies my diff quite a lot (attached.)

Rotated platforms? Easy. In my demo I've hardcoded a normal angle range for platforms to respond only to shapes moving "down", but it would be trivial to specify normal ranges separately for individual shapes (via b2Shape.GetUserData.) I can't think of a reason why this approach shouldn't work for one-way doors, platform ramps, or even Sonic-style platform loops.

In summary, the only change needed to Box2D for this to be possible is to add the b2Contact to contact listener calls. And I suppose you could skip that and just use vanilla Box2D if you're willing to iterate over a contact list like mayobutter has been doing.

New demo with bugfix (thanks Boris!)

http://www.zshare.net/flash/511254675ef69f86/
I just manually applied your patch. This is definitely easier than looping through the body's contact list like I was doing. Well done.

Now on to deciphering your how-to-make-a-platform comments 🙂
Here's the code from my demo. Please excuse the angle math and user data naivety. Hope it helps!

Code:
   public class TestPlatformsContactListener extends b2ContactListener {
      
      override public function Add(point:b2ContactPoint, contact:b2Contact):void {
         AddOrPersist(point, contact);
      }
      
      override public function Persist(point:b2ContactPoint, contact:b2Contact):void {
         AddOrPersist(point, contact);
      }
      
      public function AddOrPersist(point:b2ContactPoint, contact:b2Contact):void {
         var shapeUserData1:String = point.shape1.GetUserData();
         var shapeUserData2:String = point.shape2.GetUserData();
         
         if ( shapeUserData1 == "creature" && shapeUserData2 == "platform" ) {
            ProcessCreatureVsPlatform( point, contact, 1, 90, 60 );
         }
         else if ( shapeUserData1 == "platform" && shapeUserData2 == "creature" ) {
            ProcessCreatureVsPlatform( point, contact, -1, 90, 60 );
         }
      }
      
      public function ProcessCreatureVsPlatform(point:b2ContactPoint, contact:b2Contact, reverse:Number, solidityAng:Number=90, solidityRange:Number=60):void {
         // if the contactPoint's normal is not within a 60 degree range from "down", disable collisions
         
         var normalAng:Number = Math.atan2( point.normal.y * reverse, point.normal.x * reverse );
         var deltaAng:Number = (normalAng - (solidityAng*Math.PI/180.0))
         
         // normalize angle
         deltaAng %= (Math.PI * 2)
         if (deltaAng < -Math.PI) { deltaAng += Math.PI * 2; }
         if (deltaAng > Math.PI) { deltaAng -= Math.PI * 2; }
         
         var platformIsBelowCreature:Boolean = ( Math.abs(deltaAng) < (solidityRange*Math.PI/180.0) );
         
         if ( !platformIsBelowCreature ) {
            // disable collisions between this shape pair while they remain in contact
            contact.m_flags |= b2Contact.e_nonSolidFlag;
         }
      }
      
      override public function Remove(point:b2ContactPoint, contact:b2Contact):void {
         // when the last contact point is removed, reset solidity (needed because AABBs will keep a b2Contact alive even when there are no b2ContactPoints)
         // NOTE: this simple approach lacks the smarts needed to behave properly with sensors!
         if ( contact.m_manifoldCount == 0 ) {
            contact.m_flags &= ~b2Contact.e_nonSolidFlag;
         }
      }
      
   }


EDIT: updated, see next post for reason
Chriswa, will your hack work with polygon shapes?

See this, try to interact with the hovering triangle which is a "platform".

http://www.minikin.com/temp/5/Main.html

Simply press "enter" button, and then use arrows to move around.
Up arrow to jump.

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