collision detection for polygons goes wrong

Greetings!

I'm new to b2d and so i've used this demo to start with. Since i'm interested in polygonal physics, i've created a simple "constructor"-like demo (which allows user to create rigid bodies just by point-and-click'in') hopin' b2d would simulate it correctly. But i was wrong.

b2d says: "polygon should give it's vertices in counter-clockwise order". I've made simple check: if one has its vertices in non-CCW order (x2 > x1 && y2 > y1), then i just reverse its vertex array and only then create body. seems weird when i draw two polies in CCW and non-CCW orders and both of 'em fail each through another.

Is it a new bug detected or i'm just stupid enough? =)

P.S.: one can try demo from here
P.P.S.: sorry for my incorrect english - i'm not good with it at all =P
I'm not sure I understand the question. Are you saying that two polygons with opposite windings fail to intersect? If so, that's to be expected, I think. Or are you saying that two CCW-wound polygons fail to intersect?

Also, if things aren't working as expected, you might double-check whatever algorithm you're using to determine the winding. Comparing coordinates as in your example won't work in the general case; for example, an edge where x2 > x1 and y2 > y1 could be part of either a CCW- or CW-wound polygon.

Determining the winding of a convex 2-d polygon is straightforward though. One method is to compute the perp-dot product of two consecutive edges; assuming the edges are not collinear, the winding can be determined from the sign of the result.
shybovycha wrote:
Are you saying that two polygons with opposite windings fail to intersect? If so, that's to be expected, I think. Or are you saying that two CCW-wound polygons fail to intersect?


Both of these examples fail.

shybovycha wrote:
Also, if things aren't working as expected, you might double-check whatever algorithm you're using to determine the winding. Comparing coordinates as in your example won't work in the general case; for example, an edge where x2 > x1 and y2 > y1 could be part of either a CCW- or CW-wound polygon.


Algorithm is checked more than twice 😉 Also, i used simple way to check this run-time - just printing to the terminal whenever polygon is CCW or not backgrounds. =)

If you won't trust me, you may look over my source code below.
NOTES:
  • This application uses SFML. So, you should have a valid copy of this in order to compile code shown below.
  • SFML is open-source.
  • This application was successfully build and tested with MSVC++ 2008 Express.
  • Application was successfully tested with Windows 7 x64, Windows XP x86 and Windows Vista (unknown architecture 🙂
    ).
  • Application should work with any systems, supported by Box2D and SFML.

Code:
#include <stdio.h>

#include <Box2D/Box2D.h>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>

#pragma comment(lib, "glu32.lib")
#pragma comment(lib, "Box2D.lib")
#pragma comment(lib, "sfml-system.lib")
#pragma comment(lib, "sfml-window-s.lib")
#pragma comment(lib, "sfml-graphics.lib")

#define M_PI 3.14f

#define PIXELS_PER_METER 64.f
#define METERS_PER_PIXEL (1.f / PIXELS_PER_METER)

#define PPM PIXELS_PER_METER
#define MPP METERS_PER_PIXEL

#define x_cor 2.f * METERS_PER_PIXEL
#define y_cor METERS_PER_PIXEL

// My algorithm
bool CheckPolygonIfCCW(const std::vector<sf::Vector2f> &v)
{
   if (v.size() > 1)
      return (v[1].x > v[0].x && v[1].y > v[0].y); else
         return true;
}

// This function is taken from B2D sources
bool CheckPolygonIfConvex(const std::vector<sf::Vector2f> &v)
{
   for (size_t t = 0; t < v.size(); ++t)
   {
      int32 i1 = t;
      int32 i2 = t + 1 < v.size() ? t + 1 : 0;
      b2Vec2 edge = b2Vec2(v[i2].x, v[i2].y) - b2Vec2(v[i1].x, v[i1].y);

      for (size_t j = 0; j < v.size(); ++j)
      {
         if (j == i1 || j == i2)
         {
            continue;
         }
         
         b2Vec2 r = b2Vec2(v[j].x, v[j].y) - b2Vec2(v[i1].x, v[i1].y);

         float32 s = b2Cross(edge, r);

         if (!(s > 0.0f))
            return false;
      }
   }

   return true;
}

// Thanks to bobasaurus =)
class DebugDraw : public b2DebugDraw
{
public:
   DebugDraw(sf::RenderWindow *renderWindow)
   {
      window = renderWindow;
   }

   void DrawPolygon(const b2Vec2 *vertices, int32 vertexCount, const b2Color &color)
   {
      sf::Shape polygon;

      for (int32 i = 0; i < vertexCount; i++)
      {
         b2Vec2 vertex = vertices[i];
         polygon.AddPoint(vertex.x * PIXELS_PER_METER, window->GetHeight() - (vertex.y * PIXELS_PER_METER), sf::Color(0, 0, 0, 0), B2SFColor(color));
      }

      window->Draw(polygon);
   }

   void DrawSolidPolygon(const b2Vec2 *vertices, int32 vertexCount, const b2Color &color)
   {
      sf::Shape polygon;

      for (int32 i = 0; i < vertexCount; i++)
      {
         b2Vec2 vertex = vertices[i];
         polygon.AddPoint(vertex.x * PIXELS_PER_METER, window->GetHeight() - (vertex.y * PIXELS_PER_METER), B2SFColor(color)); //need transparant outline?
      }

      window->Draw(polygon);
   }

   void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color)
   {
      sf::Shape circle = sf::Shape::Circle(center.x * PPM, window->GetHeight() - (center.y * PPM), radius * PPM, sf::Color(0, 0, 0, 0), 1.0f, B2SFColor(color));
      window->Draw(circle);
   }

   void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color)
   {
      sf::Shape circle = sf::Shape::Circle(center.x * PPM, window->GetHeight() - (center.y * PPM), radius * PPM, B2SFColor(color));
      window->Draw(circle);
   }

   void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) {}

   void DrawTransform(const b2Transform& xf) {}

private:
   sf::RenderWindow *window;

   sf::Color B2SFColor(const b2Color &color)
   {
      sf::Color result((sf::Uint8) (color.r * 255), (sf::Uint8) (color.g * 255), (sf::Uint8) (color.b * 255));

      return result;
   }
};

int main()
{
    sf::RenderWindow *App = new sf::RenderWindow(sf::VideoMode(800, 600, 32), "SFML + Box2D Test");
   App->UseVerticalSync(true);

   // ================= Init Physics ====================
   b2World *world = new b2World(b2Vec2(0.0f, -10.0f), true);

   DebugDraw *debugDraw = new DebugDraw(App);
   debugDraw->SetFlags(b2DebugDraw::e_shapeBit);
   world->SetDebugDraw(debugDraw);

   // Define the ground body.
   b2BodyDef groundBodyDef;
   groundBodyDef.position.Set(0.0f * x_cor, 0.0f * y_cor);

   b2Body* groundBody = world->CreateBody(&groundBodyDef);
   b2PolygonShape groundBox;
   groundBox.SetAsBox(500.f * x_cor, 10.0f * y_cor);
   groundBody->CreateFixture(&groundBox, 0.0f);
   // ====================================================

   // ====================================
   b2PolygonShape shape;
   shape.SetAsBox(5.f * x_cor, 5.f * x_cor);

   b2FixtureDef fd;
   fd.shape = &shape;
   fd.density = 1.0f;
   fd.friction = 0.3f;
   fd.restitution = 0.7f;

   b2BodyDef bd;
   bd.type = b2_dynamicBody;
   bd.angle = M_PI / 4.f;
   bd.position.Set(10.f * x_cor, 80.f * x_cor);
   b2Body* body = world->CreateBody(&bd);

   body->CreateFixture(&fd);
   // ====================================

    while (App->IsOpened())
    {
        sf::Event Event;
      static std::vector<sf::Vector2f> points;
      static sf::Color cl;
      bool nonConvex = false;

        while (App->GetEvent(Event))
        {
            if (Event.Type == sf::Event::Closed)
                App->Close();

            if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
                App->Close();

            if (Event.Type == sf::Event::Resized)
                glViewport(0, 0, Event.Size.Width, Event.Size.Height);

         // Deleting last vertex added
         if (Event.Type == sf::Event::MouseButtonPressed && Event.MouseButton.Button == sf::Mouse::Right)
         {
            points.pop_back();
         }

         // Creating a new polygon / Adding a new vertex to the list
         if (Event.Type == sf::Event::MouseButtonPressed && Event.MouseButton.Button == sf::Mouse::Left)
         {
            bool fl = false;

            // Polygon should consist more than 3 vertices
            if (points.size() < 3)
               cl = sf::Color(rand() % 255, rand() % 255, rand() % 255);

            // Paint polygon with red if it's not convex
            if (!CheckPolygonIfConvex(points))
            {
               cl = sf::Color(255, 0, 0);
               nonConvex = true;
            } else
            {
               if (nonConvex)
                  cl = sf::Color(rand() % 255, rand() % 255, rand() % 255);

               nonConvex = false;
            }

            // Check if user have selected one of existing vertices (to complete drawings)
            for (int i = 0; i < (int) points.size(); i++)
            {
               b2Vec2 v1((float32) App->GetInput().GetMouseX(), (float32) App->GetInput().GetMouseY());
               b2Vec2 v2((float32) points[i].x, (float32) points[i].y);
               b2Vec2 v = v2 - v1;

               if (v.Length() < 15.f)
               {
                  fl = true;
                  break;
               }
            }

            // If user just added a new vertex - push it to the list
            if (!fl)
            {
               points.push_back(sf::Vector2f((float32) App->GetInput().GetMouseX(), (float32) App->GetInput().GetMouseY()));
            } else
            // Else - create a new polygon, if we have enough vertices
            if (points.size() > 3)
            {
               //points.push_back(points[i]);
               points.push_back(sf::Vector2f((float32) App->GetInput().GetMouseX(), (float32) App->GetInput().GetMouseY()));

               b2PolygonShape shape;

               // Show how my algorithm works
               printf("===================\n");

               for (int i = 0; i < (int) points.size(); i++)
                  printf("%.3f\t%.3f\t\n", points[i].x * y_cor, (App->GetHeight() - points[i].y) * y_cor);

               printf(":::::::::::::::::::::\n");

               if (!CheckPolygonIfCCW(points))
               {
                  for (int i = 0; i < (int) points.size() / 2; i++)
                  {
                     sf::Vector2f v = points[points.size() - i - 1];
                     points[points.size() - i - 1] = points[i];
                     points[i] = v;
                  }

                  printf("NOT CCW\n");
               }

               for (int i = 0; i < (int) points.size(); i++)
                  printf("%.3f\t%.3f\t\n", points[i].x * y_cor, (App->GetHeight() - points[i].y) * y_cor);

               printf("===================\n");
                  
               // Convert SFML points to b2d ones
               b2Vec2 *ps = new b2Vec2[points.size()];

               if (CheckPolygonIfCCW(points))
               {
                  for (int i = 0; i < (int) points.size(); i++)
                     ps[i] = b2Vec2(points[i].x * y_cor, (App->GetHeight() - points[i].y) * y_cor);
               } else
               {
                  for (int i = points.size() - 1; i > -1; i--)
                     ps[i] = b2Vec2(points[i].x * y_cor, (App->GetHeight() - points[i].y) * y_cor);
               }

               // And create a body
               sf::Shape poly;

               for (int i = 0; i < (int) points.size(); i++)
                  poly.AddPoint(points[i].x, (App->GetHeight() - points[i].y));

               shape.Set(ps, points.size());

               b2FixtureDef fd;
               b2BodyDef bd;
               b2MassData md;

               fd.shape = &shape;
               fd.density = 10.0f;

               bd.type = b2_dynamicBody;
               bd.position.Set(poly.GetCenter().x * y_cor, poly.GetCenter().y * y_cor);
               b2Body* body = world->CreateBody(&bd);
               shape.ComputeMass(&md, fd.density);

               body->CreateFixture(&fd);
               body->SetMassData(&md);

               // When we've created our body, we should clear vertex list to make possible next creations
               points.clear();
            }
         }
        }

      world->Step(App->GetFrameTime(), 1024, 1024);
      world->ClearForces();

      App->Clear();

      // Draw instructions
      sf::String text1("left click - add vertex");
      sf::String text2("right click - delete last vertex");
      sf::String text3("any vertex click - complete figure");

      text1.SetPosition(10, 10);
      text2.SetPosition(10, 25);
      text3.SetPosition(10, 40);

      text1.SetSize(14);
      text2.SetSize(14);
      text3.SetSize(14);

      App->Draw(text1);
      App->Draw(text2);
      App->Draw(text3);

      // Draw the shape we'll create the body on
      if (points.size() > 0)
      {
         sf::Shape Polygon;

         if (points.size() == 1)
         {
            sf::Shape l1 = sf::Shape::Line(points[0].x, points[0].y, (float) App->GetInput().GetMouseX(), (float) App->GetInput().GetMouseY(), 2.f, sf::Color(255, 255, 255));

            App->Draw(l1);
         } else
         if (points.size() == 2)
         {
            sf::Shape l1 = sf::Shape::Line(points[1].x, points[1].y, (float) App->GetInput().GetMouseX(), (float) App->GetInput().GetMouseY(), 2.f, sf::Color(255, 255, 255));
            sf::Shape l2 = sf::Shape::Line(points[0].x, points[0].y, points[1].x, points[1].y, 2.f, sf::Color(255, 255, 255));
            
            App->Draw(l1);
            App->Draw(l2);
         } else
         {
            for (size_t i = 0; i < points.size(); i++)
            {
               Polygon.AddPoint(points[i].x, points[i].y);
               
               sf::Shape circle = sf::Shape::Circle(points[i].x, points[i].y, 5.f, sf::Color(100, 100, 100));

               App->Draw(circle);
            }

            sf::Shape l1 = sf::Shape::Line(points[points.size() - 1].x, points[points.size() - 1].y, (float) App->GetInput().GetMouseX(), (float) App->GetInput().GetMouseY(), 2.f, sf::Color(255, 255, 255));

            App->Draw(l1);

            Polygon.SetColor(cl);
            Polygon.SetOutlineWidth(2);
            Polygon.EnableFill(true);
            Polygon.EnableOutline(false);
         }

         App->Draw(Polygon);
      }

      // And draw all the stuff
      world->DrawDebugData();

      App->Display();
    }

    return 0;
}
shybovycha wrote:
Algorithm is checked more than twice 😉 Also, i used simple way to check this run-time - just printing to the terminal whenever polygon is CCW or not backgrounds. =)

I just asked because you mentioned comparing coordinates directly. But, if you're using the standard perp-dot method (which it looks like you are), there shouldn't be a problem.

I didn't look through all the code, but if you're encountering a case where two properly wound polygons do not interact, I would reproduce it in a testbed application and submit it as a bug.
Thanks a lot! =)

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