BoxCutter

ElectroDruid wrote:
Hiya,

I've just got round to updating my Box2D libraries to the latest SVN version so I could have a play about with this. I'm confused about this line, in the top of CheckPolyShape():

Code:
b2Vec2 m_normals[poly->vertexCount];


I don't see how that can compile for you. C++ doesn't do dynamic array allocation like that, you'd need b2Vec2* m_normals = new b2Vec2[poly->vertexCount], and then remember to delete[] m_normals before returning from the function. Is this what the code is supposed to do, or am I missing something?
That might be a GCC feature, or a new C++ feature, not sure. I'm 100% positive that it compiles for me, under gcc-mingw.
You learn something new every day. I've been coding in C/C++ for 8 years now, used maybe 10 different compilers, and I've never seen that 🙄

I looked it up, and apparently the C99 standard says that you can define arrays that way, so GCC can do it, but Visual Studio can't (and I have no idea about any other compilers). So yeah, your code is standards-compliant, but perhaps not the most portable thing in the world.
There seems to be a problem sometimes with the cutter, when the line segment passes through a corner of a shape:

Image

(This is a screenshot of me dragging one of the boxes into a position where the BoxCutter won't cut it).

The problem seems to be that the entry (or exit, depending on how the box is angled) point is being calculated slightly wrongly, and so appears to be a small amount outside the box, rather than on its edge/corner. It then fails tests in CheckPolyShape (the shape comes out as being nonconvex, or not having anticlockwise vertices, etc), and so just throws the shapes away and refuses to do the cut. I'm not really sure if the problem is with the LineSegment checking, or if it's how you're generating the entry/exit points based in its results (I don't know how LineSegments work, exactly).

Any idea what this could be? I can probably build you a test case to reproduce the problem, but it's pretty easy to do just in your testcode, once you know how to position the box.
I think because you cut on an exact corner that you will a wrong poly because of floating point inaccuracies. You always have slight inaccuracies. I think this could cause the resulting polygon not be be convex, or with a 'core shape' which won't work.

For example, while you cut slightly above the corner, the resulting vertex is below it and then it won't cut because the poly check fails.

A solution might be to check if two vertexes are very close to each other and then make only a single vertex of it.
Your advice worked, and I've managed to mostly fix the problem by adding this stuff to the final loop in SplitShape():

Code:
   for(int n=0;n<2;n++)
      {
         const float Epsilon = 0.1f;
         for (int32 thisVert = 0; thisVert < newPolygon[n].vertexCount && newPolygon[n].vertexCount > 3; ++thisVert)
         {
            for (int32 otherVert = 0; otherVert < newPolygon[n].vertexCount && newPolygon[n].vertexCount > 3; ++otherVert)
            {
               if(thisVert != otherVert)
               {
                  if(fabs(newPolygon[n].vertices[thisVert].x - newPolygon[n].vertices[otherVert].x) < Epsilon
                     && fabs(newPolygon[n].vertices[thisVert].y - newPolygon[n].vertices[otherVert].y) < Epsilon)
                  {
                     // Duplicate vertex - remove the second one

                     for (int shiftVerts = otherVert+1; shiftVerts < newPolygon[n].vertexCount; ++shiftVerts)
                     {
                        newPolygon[n].vertices[shiftVerts-1] = newPolygon[n].vertices[shiftVerts];
                     }

                     --newPolygon[n].vertexCount;
                  }
               }
            }
         }

         if (CheckPolyShape(&newPolygon[n]))
            return -1;
      }


However, 0.1f seems to be a very large Epsilon to need to use (I've tried smaller Epsilons, but even something like 0.01f fails to merge the vertices properly in quite a lot of cases. To need Epsilons that size implies that there's something more than just floating point inaccuracies happening. As I said, I don't know if the problem is with how the start and endpoints get generated, or whether there's something wrong with how lambda is actually calculated under certain circumstances. I'll look into it some more myself, but the inner workings of this stuff isn't something I'm really familiar with at the moment.
Any chance to get this work with 2.1.2?

Someone have idea how make this in the las version?
I recently updated the pybox2d testbed to work with it.

Source: http://code.google.com/p/pybox2d/source/browse/trunk/examples/test_BoxCutter.py

If the laser line is defined by two points (p1, p2), I do a raycast from p1 to p2, and then again from p2 to p1. I match up the points from each of the callbacks to get the points on the fixtures to cut. Whether or not it's the right or best way, I don't know, but it works.
Thanks kne!

I Really appreciated that! I Start your port to the actual Box2D - Cocos2D version! Soon as get ready i share here!

By now, i never work with pyton, so i get some problems to understand your port! can u help me with that?

What is the hitLoc1 in this function?

hitLoc1 = (1-lambda_)*segment1.p1+lambda_*segment1.p2


By now, i have the first user input and the last stored in a array:
Code:
-(void)cutBodyes
{
    CGPoint firstLocation = CGPointFromString([arrTouches objectAtIndex:0]);
    CGPoint secondLocation = CGPointFromString([arrTouches objectAtIndex:1]);
   
    firstLocation.x = firstLocation.x/PTM_RATIO;
    firstLocation.y = firstLocation.y/PTM_RATIO;
   
    secondLocation.x = secondLocation.x/PTM_RATIO;
    secondLocation.y = secondLocation.y/PTM_RATIO;
   
    b2Vec2 firstPoint(firstLocation.x, firstLocation.y);
    b2Vec2 secondPoint(secondLocation.x, secondLocation.y);
   
    RayCastMultipleCallback callback;
    world->RayCast(&callback ,firstPoint, secondPoint);
}


I Have a list of all hitting bodies between this 2 points:

Code:
for(int i = 0; i< callback.m_count;i++)
    {
        b2Body* tryBody = callback.m_body[i];
       
    }


Follow the path you follow!

I get the In point of Colision and Out point of colision:
Code:
// Get the Callback from In to Out
    RayCastMultipleCallback callbackIn;
    world->RayCast(&callbackIn ,firstPoint, secondPoint);
   
    // Get the Callback from Out to Ind
    RayCastMultipleCallback callbackOut;
    world->RayCast(&callbackOut ,secondPoint, firstPoint);
   
   
    fb2Body *tryBody = callbackIn.m_body[i];
        b2Vec2 inPointOfColision = callbackIn.m_points[i];
        b2Vec2 outPointOfColision = callbackOut.m_points[((callbackOut.m_count-1)-i)];
        //NSLog(@"Actual %i Reverse: %i",i,((callbackOut.m_count-1)-i));
        //NSLog(@"In at x:%f y:%f Exit at: x:%f y:%f",inPointOfColision.x,inPointOfColision.y,outPointOfColision.x,outPointOfColision.y);
       
       
       
        b2Vec2 localInPoint = tryBody->GetLocalPoint(inPointOfColision);
        b2Vec2 localOutPoint = tryBody->GetLocalPoint(outPointOfColision);


Ok, now i must create 2 objects!

I get stuck on this part now =/
Code:
for(int i = 0; i< callbackIn.m_count;i++)
    {
        b2Body *tryBody = callbackIn.m_body[i];
        b2Vec2 inPointOfColision = callbackIn.m_points[i];
        b2Vec2 outPointOfColision = callbackOut.m_points[((callbackOut.m_count-1)-i)];
        //NSLog(@"Actual %i Reverse: %i",i,((callbackOut.m_count-1)-i));
        //NSLog(@"In at x:%f y:%f Exit at: x:%f y:%f",inPointOfColision.x,inPointOfColision.y,outPointOfColision.x,outPointOfColision.y);
       
       
       
        b2Vec2 localInPoint = tryBody->GetLocalPoint(inPointOfColision);
        b2Vec2 localOutPoint = tryBody->GetLocalPoint(outPointOfColision);
       
        b2PolygonShape* bodyShape = (b2PolygonShape *)tryBody->GetFixtureList()->GetShape();
        int verticeCount = bodyShape->GetVertexCount();
        int cutAdded[2] = {0,0};
        int last = -1;
        b2Vec2 vertex1[4];
        int vertex1Count = 0;
       
        b2Vec2 vertex2[4];
        int vertex2Count = 0;
       
        b2PolygonShape newSquare[2];
       
        for(int v = 0; v < verticeCount; v++)
        {
            int n = -1;
            b2Vec2 targetVertice = bodyShape->GetVertex(v);
            if(b2Dot(b2Cross(localOutPoint - localInPoint, 1), targetVertice-localInPoint))
            {
                n = 0;
            }
            else
            {
                n = 1;
            }
            if(last != n)
            {
                if(last == 0)
                {
                    cutAdded[0] = 1;
                    vertex1[vertex1Count] = localOutPoint;
                    vertex1Count++;
                    vertex1[vertex1Count] = localInPoint;
                    vertex1Count++;
                }
                else if(last == 1)
                {
                    cutAdded[last] = 1;
                    vertex2[vertex2Count] = localInPoint;
                    vertex2Count++;
                    vertex2[vertex2Count] = localOutPoint;
                    vertex2Count++;
                }
            }
        }
    }
hitLoc1 looks as though it's the entry point, using TestSegment's results. Those entry/exit points are now coming from the raycasts.

You can pretty much follow the original C++ code instead of the Python code, just replacing where the points come from, and using fixtures instead of shapes.

I didn't read through your code thoroughly at all, but from a glance I can tell that you're using cut_added incorrectly -- that should indicate the index where the cut was added.
Ok! Good to know, i try to follow the C version!
sry about many questions, but i really don't understand the necessary to do this in box2d on my one!

New question is:

Things like this:
Code:
const b2Vec2* vertices = shape->GetVertices();


Don't existe anymore, what i must get here?
This?
Code:
/// Get the supporting vertex index in the given direction.
   int32 GetSupport(const b2Vec2& d) const;

This?
Code:
/// Get the supporting vertex in the given direction.
   const b2Vec2& GetSupportVertex(const b2Vec2& d) const;

Code:
/// Get a vertex by index.
   const b2Vec2& GetVertex(int32 index) const;


Or this?!

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