Rays Collide with Interior Edges

I am having a problem where b2World::RayCast() is returning a ray that collides with interior edges of compound shapes (passing directly through the outer edge). Sometimes it goes through an object completely.

In the attached image, the blue line is the ray. I would expect it to collide on the outside of the circle, but it falls into the interior. As I slide the ray around, it will alternate between correct behavior and missing the exterior collision (seemingly at random).

I made a testbed example, but to my dismay, I have been unable to reproduce it in the test application. This leads me to believe there is something wrong with my geometry. But apart from this, it behaves correctly. Anyone else seen this before? Any ideas what might cause a ray to collide with interior edges?
Don't get your hopes up! I can't help you at all, I'm afraid.

I actually write in the hopes of persuading you to post the code that does the actual raycasting. First, it might yield clues as to what is going wrong (for smarter people than me). Second, it's likely to shed some light on how to do raycasting at all (for me). 😳
A couple of questions:

1. Is your compound shape comprised of multiple 3-vertex polygons? (That's what your image would seem to indicate.)

2. If so, are the polygons wound consistently and correctly?

3. Does the object otherwise interact with the environment correctly? In other words, is it just the raycasting that's not working?
OK:
I have ruled out the geometry as the culprit here (it is wound consistently and behaves as expected in all regular collision responses; raycasting problem crops up regardless of using triangles or n-gons).

The problem is with my custom b2RayCastCallback and has to do with the way I am filtering the rays. If I remove the filtering from my callback (essentially making it like the default callback used in the testbed example), then the rays collide as expected. Of course, disabling filtering is not an option so I'm looking for a more stable solution.

Here is my b2RayCastCallback:

Code:
class MyRayCast : public b2RayCastCallback
{
public:
   MyRayCast (RaySystem *rSys)
   {
      m_fixture = NULL;
      raySys = rSys;
   }

   float32 ReportFixture(   b2Fixture* fixture, const b2Vec2& point,
      const b2Vec2& normal, float32 fraction)
   {
      //Get the b2Body wrapper class this ray has collided with.
      MyRigidBody *myBodyWrapper = static_cast<MyRigidBody*>(fixture->GetUserData());
      //Do bitwise AND operation to see if these should collide
      if ( (raySys->maskBits & myBodyWrapper->categoryBits) != 0 ) return 1;

      m_fixture = fixture;
      m_point = point;
      m_normal = normal;
      category = myBodyWrapper ->category;

      return fraction;
   }

   b2Fixture* m_fixture;
   b2Vec2 m_point;
   b2Vec2 m_normal;
   int category;
   RaySystem *raySys;
};


As you can see, my b2Body wrapper has a uInt16 variable that stores it's collision category in a binary format. I also have a RaySystem with a uInt16 member that store the categories that the ray should mask out.

Then inside the callback I get the body wrapper from the userdata of the fixtures. From this I get the category bits. Then I do a bitwise AND to see if this ray should collide with the given fixture.

The system "works" in the sense that rays don't collide with bodies they are masked against, but in the process it seems to screw everything up and return bogus collisions with interior edges!!

I hope that clarifies things a bit. Can anyone enlighten me on the *proper* way to do this?
Shouldn't this:

Code:
if ( (raySys->maskBits & myBodyWrapper->categoryBits) != 0 ) return 1;

Be:

Code:
if ( (raySys->maskBits & myBodyWrapper->categoryBits) == 0 ) return 1;

?
Jesse - I think this is correct. I want the ray to collide with everything by default, so I only specify those categories that I want to disable/mask/not collide with. So if I want the ray to only collide with category #3, I would set it to 00000000000000100 (binary) or 0x0004 (Hex).

Anyway, the ray masking is working as expected (it passes through masked objects and collides with those that aren't), it just that the ray *sometimes* returns points on interior edges and sometimes goes fully through an object.

Here is a testbed example showing a ray going through an object (I was unable to reproduce hitting an interior edge in the testbed). NOTE: this problem appears to crop up ONLY when the ray originates inside a masked fixture.

Code:
#ifndef RAYCASTBUG_H
#define RAYCASTBUG_H

// This test demonstrates a problem in the ray casting system.

class RayCastBugCallback : public b2RayCastCallback
{
public:
   RayCastBugCallback()
   {
      m_fixture = NULL;
   }

   float32 ReportFixture(   b2Fixture* fixture, const b2Vec2& point,
      const b2Vec2& normal, float32 fraction)
   {
      //Filter collisions using bit mask
      if ( (maskBits & fixture->GetFilterData().categoryBits) != 0 ) return 1;

      m_fixture = fixture;
      m_point = point;
      m_normal = normal;

      return fraction;
   }

   b2Fixture* m_fixture;
   b2Vec2 m_point;
   b2Vec2 m_normal;
   uint16 maskBits;
};

class RayCastBug : public Test
{
public:

   enum
   {
      e_maxBodies = 256,
   };

   RayCastBug()
   {
      // Ground body
      {
         b2BodyDef bd;
         b2Body* ground = m_world->CreateBody(&bd);

         b2PolygonShape polyShape;
         polyShape.SetAsEdge(b2Vec2(-200.0f, 0.0f), b2Vec2(200.0f, 0.0f));

         //Create a fixture with the polygon shape
         b2FixtureDef fixtureDef;
         fixtureDef.shape = &polyShape;
         //Set collision category #1
         fixtureDef.filter.categoryBits = 0x0001;//(...000001)
         //Add the polygon fixture to the body.
         ground->CreateFixture(&fixtureDef);
      }

      // Ceiling body
      {
         b2BodyDef bd;
         b2Body* ground = m_world->CreateBody(&bd);

         b2PolygonShape polyShape;
         polyShape.SetAsEdge(b2Vec2(-200.0f, 100.0f), b2Vec2(200.0f, 100.0f));

         //Create a fixture with the polygon shape
         b2FixtureDef fixtureDef;
         fixtureDef.shape = &polyShape;
         //Set collision category #1
         fixtureDef.filter.categoryBits = 0x0001;//(...000001)
         //Add the polygon fixture to the body.
         ground->CreateFixture(&fixtureDef);
      }

      //Large circle
      {
         b2BodyDef bd;
         b2Body* circle = m_world->CreateBody(&bd);

         b2Vec2 origin(100.0f,50.0f);
         float radius = 75.0f;
         float angle = 6.283185f / 40;
         for (int i=0; i<40; i++)
         {
            //Create a triangle
            b2Vec2 vertices[3];
            vertices[0] = origin;
            float xA = origin.x + radius * cos(angle*i);
            float yA = origin.y + radius * sin(angle*i);
            vertices[1].Set(xA,yA);
            float xB = origin.x + radius * cos(angle*(i+1));
            float yB = origin.y + radius * sin(angle*(i+1));
            vertices[2].Set(xB,yB);
            //Add it to the circle body
            b2PolygonShape polyShape;
            polyShape.Set(vertices,3);

            //Create a fixture with the polygon shape
            b2FixtureDef fixtureDef;
            fixtureDef.shape = &polyShape;
            //Set collision category #2
            fixtureDef.filter.categoryBits = 0x0002;//(...000010)
            //Add the polygon fixture to the body.
            circle->CreateFixture(&fixtureDef);
         }
      }

      //A circle body (MASKED OUT)
      {
         b2BodyDef bd;
         b2Body* circle = m_world->CreateBody(&bd);

         b2Vec2 origin(00.0f,20.0f);
         float radius = 15.0f;
         float angle = 6.283185f / 20;
         for (int i=0; i<20; i++)
         {
            //Create a triangle
            b2Vec2 vertices[3];
            vertices[0] = origin;
            float xA = origin.x + radius * cos(angle*i);
            float yA = origin.y + radius * sin(angle*i);
            vertices[1].Set(xA,yA);
            float xB = origin.x + radius * cos(angle*(i+1));
            float yB = origin.y + radius * sin(angle*(i+1));
            vertices[2].Set(xB,yB);
            //Add it to the circle body
            b2PolygonShape polyShape;
            polyShape.Set(vertices,3);

            //Create a fixture with the polygon shape
            b2FixtureDef fixtureDef;
            fixtureDef.shape = &polyShape;
            //Set collision category #3
            fixtureDef.filter.categoryBits = 0x0004; //(...000100)
            //Add the polygon fixture to the body.
            circle->CreateFixture(&fixtureDef);
         }
      }

      //A circle body to collide with (NOT MASKED)
      {
         b2BodyDef bd;
         b2Body* circle = m_world->CreateBody(&bd);

         b2Vec2 origin(0.0f,70.0f);
         float radius = 15.0f;
         float angle = 6.283185f / 20;
         for (int i=0; i<20; i++)
         {
            //Create a triangle
            b2Vec2 vertices[3];
            vertices[0] = origin;
            float xA = origin.x + radius * cos(angle*i);
            float yA = origin.y + radius * sin(angle*i);
            vertices[1].Set(xA,yA);
            float xB = origin.x + radius * cos(angle*(i+1));
            float yB = origin.y + radius * sin(angle*(i+1));
            vertices[2].Set(xB,yB);
            //Add it to the circle body
            b2PolygonShape polyShape;
            polyShape.Set(vertices,3);

            //Create a fixture with the polygon shape
            b2FixtureDef fixtureDef;
            fixtureDef.shape = &polyShape;
            //Set collision category #2
            fixtureDef.filter.categoryBits = 0x0002;//(...000010)
            //Add the polygon fixture to the body.
            circle->CreateFixture(&fixtureDef);
         }
      }
      m_angle = 0.0f;
   }

   void Step(Settings* settings)
   {
      Test::Step(settings);
      m_debugDraw.DrawString(5, m_textLine, "Zoom out, notice ray clips through large circle.");
      m_textLine += 15;

      float32 L = 500.0f;
      b2Vec2 point1(0.0f, 10.0f);
      b2Vec2 d(L * cosf(m_angle), L * sinf(m_angle));
      b2Vec2 point2 = point1 + d;

      RayCastBugCallback callback;
      callback.maskBits = 0xFFFC; //mask all except categorys #2 and #1 (1111111111111100)

      m_world->RayCast(&callback, point1, point2);

      if (callback.m_fixture)
      {
         m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f));

         m_debugDraw.DrawSegment(point1, callback.m_point, b2Color(0.8f, 0.8f, 0.8f));

         b2Vec2 head = callback.m_point + 0.5f * callback.m_normal;
         m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f));
      }
      else
      {
         m_debugDraw.DrawSegment(point1, point2, b2Color(0.8f, 0.8f, 0.8f));
      }

      //Cast another ray that doesn't originate inside a shape
      b2Vec2 startPoint(-100, 25);
      b2Vec2 endPoint(200, 5);
      m_world->RayCast(&callback, startPoint, endPoint);
      if (callback.m_fixture)
      {
         m_debugDraw.DrawPoint(callback.m_point, 5.0f, b2Color(0.4f, 0.9f, 0.4f));

         m_debugDraw.DrawSegment(startPoint, callback.m_point, b2Color(0.8f, 0.8f, 0.8f));

         b2Vec2 head = callback.m_point + 0.5f * callback.m_normal;
         m_debugDraw.DrawSegment(callback.m_point, head, b2Color(0.9f, 0.9f, 0.4f));
      }

      m_angle += 0.3f * b2_pi / 180.0f;
   }

   static Test* Create()
   {
      return new RayCastBug;
   }

   float32 m_angle;
};

#endif
Please file an issue for this here: http://code.google.com/p/box2d/issues/list

You may simply link to this topic.

Thanks!
Quote:
Jesse - I think this is correct. I want the ray to collide with everything by default, so I only specify those categories that I want to disable/mask/not collide with.
I see. (I was assuming you were using the same convention for collision filtering that Box2D does by default.)
Erin Catto: I sent this issue to the Google code site. You can read it here: http://code.google.com/p/box2d/issues/detail?id=65

Jesse: You're right, I'm specifying the mask opposite to how it works for the rigidbody collision filtering. For simplicity sake, I think I'll fix this in my own code. Thanks.

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