Skip to main content
GameDev.net gamedev.net
🔒 Locked

Triangle-triangle overlap test (3D, same plane)

Started by Decrius Jul 16, 2009 at 4:13 PM 5 replies 4.9k views
Original Post
Decrius
Decrius
So, I have a convex shaped thingy, and a triangle, I need to test if both have overlap. So, I convert the convex to triangles (cake), then do triangle-to-triangle overlap tests. But, it's kind of slow compared to some other code... The other code is: http://jgt.akpeters.com/papers/GuigueDevillers03/triangle_triangle_intersection.html However, it has a very vital bug (or, unpleasant feature, w/e you want to call it) which makes that even if triangles just touch, it says they intersect. Mathematically non-sense and is not what I want. Tried to see if I could fix it, but the code is a horror to maintain (or even look at). I'm very jealous about it's speed though, and I'd be very interested if anyone knew if this technique had a name, so I could rebuild it properly (err, maintainably). My test is like this: I check whether triangle line-segments intersect, and I check if any of them has points in each other, or 3 points on the borders of the other (on the edge or on a vertex). It works, I'm proud, and it's quite faster then that SAT (separate axis theorem) method. Yes, so basically, I'm looking into optimizing the current code. Does anyone know what the technique is called or where it is described of the above link? This is the code I currently am using. Basically, I do line-line intersection tests, if they succeed, we got overlap. Then I check if either one point is inside, or 3 points are on the borders. If so, JACKPOT!
inline
unsigned int point_in_triangle(Vertex point, Vertex triangle[3])
{
    // from http://www.blackpawn.com/texts/pointinpoly/default.html

    Vertex v0 = triangle[2] - triangle[0];
    Vertex v1 = triangle[1] - triangle[0];
    Vertex v2 = point - triangle[0];

    double dot00 = dot(v0, v0);
    double dot01 = dot(v0, v1);
    double dot02 = dot(v0, v2);
    double dot11 = dot(v1, v1);
    double dot12 = dot(v1, v2);

    double invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
    double u = (dot11 * dot02 - dot01 * dot12) * invDenom;
    double v = (dot00 * dot12 - dot01 * dot02) * invDenom;

    if ((u > 0) && (v > 0) && (u + v < 1))
    {
        return 3;
    }
    else if ((u == 0) || (v == 0) || (u + v == 1))
    {
        return 1;
    }
    return 0;
}

inline
bool triangle_in_triangle(Vertex triangle1[3], Vertex triangle2[3])
{
    unsigned int a = 0, b = 0;
    for (unsigned int i = 0; i < 3; i++)
    {
        a += point_in_triangle(triangle1, triangle2);
        if (a > 2)
        {
            return true;
        }

        b += point_in_triangle(triangle2, triangle1);
        if (b > 2)
        {
            return true;
        }
    }
    return false;
}

inline
bool triangle_intersects_triangle(Vertex triangle1[3], Vertex triangle2[3])
{
    Vertex *a, *b, *c, *d;
    double s, s_denominator;
    double t, t_denominator;

    //unsigned int match = 0, touch = 0;
    for (unsigned int i = 0; i < 3; i++)
    {
        a = &triangle1
        if (i != 2)
        {
            b = &triangle1[i + 1];
        }
        else
        {
            b = &triangle1[0];
        }

        for (unsigned int j = 0; j < 3; j++)
        {
            c = &triangle2[j];
            if (j != 2)
            {
                d = &triangle2[j + 1];
            }
            else
            {
                d = &triangle2[0];
            }

            // since: a + s(b - a) = c + t(d - c) where t and s are scalars
            // from this vector equation follow 3 normal equations (x, y and z)
            // since we have 2 unknowns, we can scrap one equation for being dependant

            s_denominator = ((b->y - a->y) * (d->x - c->x) - (b->x - a->x) * (d->y - c->y));
            if (s_denominator)
            {
                s = ((c->y - a->y) * (d->x - c->x) + (a->x - c->x) * (d->y - c->y)) / s_denominator;
                if (s > 0 && s < 1)
                {
                    t_denominator = ((d->y - c->y) * (b->x - a->x) - (d->x - c->x) * (b->y - a->y));
                    if (t_denominator)
                    {
                        t = ((a->y - c->y) * (b->x - a->x) + (c->x - a->x) * (b->y - a->y)) / t_denominator;
                        if (t > 0 && t < 1)
                        {
                            return true; // edges intersect
                        }                        
                    }
                }
            }
        }
    }
    return false;
}

inline
bool triangle_overlaps_triangle(Vertex triangle1[3], Vertex triangle2[3])
{
    if (triangle_intersects_triangle(triangle1, triangle2))
    {
        return true;
    }
    else if (triangle_in_triangle(triangle1, triangle2))
    {
        return true;
    }
    return false;
}

bool triangle_overlaps_convex(Vertex triangle[3], Vertex *convex, unsigned int n)
{
    if (n > 2) // has it got any surface?
    {
        unsigned int changing = 0,  // next changing vertex of convex triangle
                     cw_i = 1,      // current vertex clockwise
                     ccw_i = n - 1; // current vertex counter clockwise

        Vertex convex_triangle[3] = {convex[0], convex[1], convex[n - 1]};
        bool is_cw[3] = {true, true, false}; // which convex triangle vertices do currently use cw or ccw value

        // go through all neccessary triangles within the convex to cover the whole convex
        for (unsigned int i = 0; i < (n - 2); i++) // n - 2 triangles
        {
            if (triangle_overlaps_triangle(triangle, convex_triangle))
            {
                return true;
            }

            if (i < (n - 3))
            {
                if (is_cw[changing])
                {
                    ccw_i--;
                    convex_triangle[changing] = convex[ccw_i];
                    is_cw[changing] = false;
                }
                else
                {
                    cw_i++;
                    convex_triangle[changing] = convex[cw_i];
                    is_cw[changing] = true;
                }

                changing++;
                if (changing == 3)
                {
                    changing = 0;
                }
            }
        }
    }
    return false;
}



This handles about 7mil tri-tri overlap tests per second. Thanks! PS: performance drops significant if the convex object has multiple triangle (that is, not linear). Gprof:
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total           
 time   seconds   seconds    calls  ns/call  ns/call  name    
 27.69      0.72     0.72  3000000   240.00   240.00  triangle_intersects_triangle(Vertex*, Vertex*)
 25.77      1.39     0.67 50000000    13.40    13.40  dot(Vertex const&, Vertex const&)
 16.92      1.83     0.44 30000000    14.67    20.67  Vertex::operator-(Vertex const&) const
 13.08      2.17     0.34 10000000    34.00   163.00  point_in_triangle(Vertex, Vertex*)
  6.92      2.35     0.18 30000042     6.00     6.00  Vertex::Vertex(double, double, double)
  3.85      2.45     0.10  3000000    33.33   850.00  triangle_overlaps_convex(Vertex*, Vertex*, unsigned int)
  3.46      2.54     0.09  2000000    45.00   860.00  triangle_in_triangle(Vertex*, Vertex*)
  1.15      2.57     0.03                             cross(Vertex const&, Vertex const&)
  0.77      2.59     0.02                             main
  0.38      2.60     0.01  3000000     3.33   816.67  triangle_overlaps_triangle(Vertex*, Vertex*)
  0.00      2.60     0.00        2     0.00     0.00  GetTime()

 %         the percentage of the total running time of the
time       program used by this function.

cumulative a running sum of the number of seconds accounted
 seconds   for by this function and those listed above it.

 self      the number of seconds accounted for by this
seconds    function alone.  This is the major sort for this
           listing.

calls      the number of times this function was invoked, if
           this function is profiled, else blank.
 
 self      the average number of milliseconds spent in this
ms/call    function per call, if this function is profiled,
	   else blank.

 total     the average number of milliseconds spent in this
ms/call    function and its descendents per call, if this 
	   function is profiled, else blank.

name       the name of the function.  This is the minor sort
           for this listing. The index shows the location of
	   the function in the gprof listing. If the index is
	   in parenthesis it shows where it would appear in
	   the gprof listing if it were to be printed.

		     Call graph (explanation follows)


granularity: each sample hit covers 4 byte(s) for 0.38% of 2.60 seconds

index % time    self  children    called     name
                                                 <spontaneous>
[1]     98.8    0.02    2.55                 main [1]
                0.10    2.45 3000000/3000000     triangle_overlaps_convex(Vertex*, Vertex*, unsigned int) [2]
                0.00    0.00      42/30000042     Vertex::Vertex(double, double, double) [9]
                0.00    0.00       2/2           GetTime() [14]
-----------------------------------------------
                0.10    2.45 3000000/3000000     main [1]
[2]     98.1    0.10    2.45 3000000         triangle_overlaps_convex(Vertex*, Vertex*, unsigned int) [2]
                0.01    2.44 3000000/3000000     triangle_overlaps_triangle(Vertex*, Vertex*) [3]
-----------------------------------------------
                0.01    2.44 3000000/3000000     triangle_overlaps_convex(Vertex*, Vertex*, unsigned int) [2]
[3]     94.2    0.01    2.44 3000000         triangle_overlaps_triangle(Vertex*, Vertex*) [3]
                0.09    1.63 2000000/2000000     triangle_in_triangle(Vertex*, Vertex*) [4]
                0.72    0.00 3000000/3000000     triangle_intersects_triangle(Vertex*, Vertex*) [6]
-----------------------------------------------
                0.09    1.63 2000000/2000000     triangle_overlaps_triangle(Vertex*, Vertex*) [3]
[4]     66.2    0.09    1.63 2000000         triangle_in_triangle(Vertex*, Vertex*) [4]
                0.34    1.29 10000000/10000000     point_in_triangle(Vertex, Vertex*) [5]
-----------------------------------------------
                0.34    1.29 10000000/10000000     triangle_in_triangle(Vertex*, Vertex*) [4]
[5]     62.7    0.34    1.29 10000000         point_in_triangle(Vertex, Vertex*) [5]
                0.67    0.00 50000000/50000000     dot(Vertex const&, Vertex const&) [7]
                0.44    0.18 30000000/30000000     Vertex::operator-(Vertex const&) const [8]
-----------------------------------------------
                0.72    0.00 3000000/3000000     triangle_overlaps_triangle(Vertex*, Vertex*) [3]
[6]     27.7    0.72    0.00 3000000         triangle_intersects_triangle(Vertex*, Vertex*) [6]
-----------------------------------------------
                0.67    0.00 50000000/50000000     point_in_triangle(Vertex, Vertex*) [5]
[7]     25.8    0.67    0.00 50000000         dot(Vertex const&, Vertex const&) [7]
-----------------------------------------------
                0.44    0.18 30000000/30000000     point_in_triangle(Vertex, Vertex*) [5]
[8]     23.8    0.44    0.18 30000000         Vertex::operator-(Vertex const&) const [8]
                0.18    0.00 30000000/30000042     Vertex::Vertex(double, double, double) [9]
-----------------------------------------------
                0.00    0.00      42/30000042     main [1]
                0.18    0.00 30000000/30000042     Vertex::operator-(Vertex const&) const [8]
[9]      6.9    0.18    0.00 30000042         Vertex::Vertex(double, double, double) [9]
-----------------------------------------------
                                                 <spontaneous>
[10]     1.2    0.03    0.00                 cross(Vertex const&, Vertex const&) [10]
-----------------------------------------------
                0.00    0.00       2/2           main [1]
[14]     0.0    0.00    0.00       2         GetTime() [14]
-----------------------------------------------

 This table describes the call tree of the program, and was sorted by
 the total amount of time spent in each function and its children.

 Each entry in this table consists of several lines.  The line with the
 index number at the left hand margin lists the current function.
 The lines above it list the functions that called this function,
 and the lines below it list the functions this one called.
 This line lists:
     index	A unique number given to each element of the table.
		Index numbers are sorted numerically.
		The index number is printed next to every function name so
		it is easier to look up where the function in the table.

     % time	This is the percentage of the `total' time that was spent
		in this function and its children.  Note that due to
		different viewpoints, functions excluded by options, etc,
		these numbers will NOT add up to 100%.

     self	This is the total amount of time spent in this function.

     children	This is the total amount of time propagated into this
		function by its children.

     called	This is the number of times the function was called.
		If the function called itself recursively, the number
		only includes non-recursive calls, and is followed by
		a `+' and the number of recursive calls.

     name	The name of the current function.  The index number is
		printed after it.  If the function is a member of a
		cycle, the cycle number is printed between the
		function's name and the index number.


 For the function's parents, the fields have the following meanings:

     self	This is the amount of time that was propagated directly
		from the function into this parent.

     children	This is the amount of time that was propagated from
		the function's children into this parent.

     called	This is the number of times this parent called the
		function `/' the total number of times the function
		was called.  Recursive calls to the function are not
		included in the number after the `/'.

     name	This is the name of the parent.  The parent's index
		number is printed after it.  If the parent is a
		member of a cycle, the cycle number is printed between
		the name and the index number.

 If the parents of the function cannot be determined, the word
 `<spontaneous>' is printed in the `name' field, and all the other
 fields are blank.

 For the function's children, the fields have the following meanings:

     self	This is the amount of time that was propagated directly
		from the child into the function.

     children	This is the amount of time that was propagated from the
		child's children to the function.

     called	This is the number of times the function called
		this child `/' the total number of times the child
		was called.  Recursive calls by the child are not
		listed in the number after the `/'.

     name	This is the name of the child.  The child's index
		number is printed after it.  If the child is a
		member of a cycle, the cycle number is printed
		between the name and the index number.

 If there are any cycles (circles) in the call graph, there is an
 entry for the cycle-as-a-whole.  This entry shows who called the
 cycle (as parents) and the members of the cycle (as children.)
 The `+' recursive calls entry shows the number of function calls that
 were internal to the cycle, and the calls entry for each member shows,
 for that member, how many times it was called from other members of
 the cycle.


Index by function name

   [5] point_in_triangle(Vertex, Vertex*) [6] triangle_intersects_triangle(Vertex*, Vertex*) [9] Vertex::Vertex(double, double, double)
   [4] triangle_in_triangle(Vertex*, Vertex*) [7] dot(Vertex const&, Vertex const&) [8] Vertex::operator-(Vertex const&) const
   [2] triangle_overlaps_convex(Vertex*, Vertex*, unsigned int) [10] cross(Vertex const&, Vertex const&) [1] main
   [3] triangle_overlaps_triangle(Vertex*, Vertex*) [14] GetTime()


[size="2"]SignatureShuffle: [size="2"]Random signature images on fora
Erik Rufelt
Erik Rufelt
Are your triangles dynamic?
If they are static, then it's a lot faster to check point/triangle intersection by pre-calculating the edge-planes or edge-lines. Is this in 2D?
In 2D it's 'ax + by + c = 0', and you check if a point is inside with:
bool inside(point p, edge triangle[3]) { for(int i=0;i<3;++i) {  if(dot(p, edge.ab) < edge.c)   return false; }  return true;}

You might need to use '>' or '<' when comparing to 'c', depending on how you calculate your edges.

Your edge-tests also seem to use way too many calculations. You can do edge-to-edge detections also with these edge-functions, simply checking if both edges have their end-points on opposite sides of the other edge, requiring much fewer operations, and no divisions (which are usually slow).

EDIT: I missed your title.. 3D, but in the same plane should work as 2D.. =)
Decrius
Decrius
Well, yes, it is a 2D problem, but it's in a 3D space, so I think I must get the plane it's in (cake) and then transform to a 2D system?

I'm a bit unsure what you mean with edge.ab and edge.c, but you did open my eyes a bit :P. I'm going to think of better 2D approaches.

PS: the triangles are fed through a map of a game, so yes, in the map it's static.
[size="2"]SignatureShuffle: [size="2"]Random signature images on fora
Erik Rufelt
Erik Rufelt
If you have a triangle in 3D, you can get the plane equation as follows:
vec3 triangle[3];vec3 normal = cross(triangle[0]-triangle[1], triangle[0]-triangle[2]);normal = normalize(normal);float a = normal.x;float b = normal.y;float c = normal.z;float d = dot(normal, triangle[0]);

The plane equation in that case is 'ax + by + cz - d = 0'. If you have a point and a plane, you can get the distance from the plane to that point with:
vec3 point;vec3 planeNormal;float planeD;distance = dot(point, planeNormal) - planeD;

This distance is positive in front of the plane, and negative behind the plane. You can check whether a point is inside a triangle by checking the distance to the plane at each of it's edges. If the point has a positive distance to each plane, then it is inside the triangle (if the positive side is inward).

In 2D you get the edge-equation 'ax + by - c = 0' of a line with two endpoints like so:
vec2 endPoints[2];vec2 normal = vec2(endPoints[1].y-endPoints[0].y, endPoints[0].x-endPoints[1].x);normal = normalize(normal);float a = normal.x;float b = normal.y;float c = dot(normal, endPoints[0]);

And the 2D-distance:
vec2 point;vec2 edgeNormal;float edgeC;distance = dot(point, edgeNormal) - edgeC;

Again, it's a signed distance, negative behind the line. You must remember to be consistent with the order of you points, so you always know which side is in front and behind.

If your convex shape really is convex, you don't need to convert it to triangles either, you can just test the same way, but against more edges. A point inside the convex has the same sign on the distance to all it's edges, and edge-tests can also be done the same way. Only if you have concave shapes do you need to make any more complex algorithm, for convex shapes you can just test with a loop through N points instead of 3.
Decrius
Decrius
Thanks for your elaborate reply! :)

I heard of that technique before, and it sounds very solid, I also thought of the following:

If you traverse the points one direction round, the cross product with the the line between 2 points of the convex, and the line from one of the points to the tested point (possibly) inside the convex, then the direction of this cross product must always be the same for all points of the convex. When cross product is 0, it's on the edge.

Thanks, Erik, I think I was thinking too difficult, hehe.
[size="2"]SignatureShuffle: [size="2"]Random signature images on fora
Decrius
Decrius
It's indeed faster, as I can leave out the convex-to-triangle code. Also the point-in-triangle code is indeed faster then the one I was using.

It's not much faster for tri-tri overlap tests, but when the convex is not a tri but a quad or higher, it goes linear up in time, not exponential like I had before, so that's a great increment in efficiency.

The tri-tri line segment intersection test is still the same (be it tri-convex now, not just tri-tri). I did think of a method to merge it with the theory you gave, but the intersection test is about 2 times faster (or actually, I do the tests in a certain order, when I do the intersection test before the points-in test, its 200% as fast as if I do it vice versa.

The whole code is now a bit more then 300% slower then the 'bugged' "fastest" tri-tri intersection test, but is linear with more triangles. So I think I can be happy :D

Thanks Erik!
[size="2"]SignatureShuffle: [size="2"]Random signature images on fora
Erik Rufelt
Erik Rufelt
Glad to help =)

If you want it even faster you should be able to use the fact that when you check point-in-triangle you do all the point-to-edge-distance checks, that are also used for edge-edge intersection testing. So avoiding recalculation, the entire thing would be 18 distance-checks, to get the distance for each of the points to the edges in the other triangle. (And early-out if a point is inside).

Also, once you know no points are inside a triangle, the only intersection case requires at least two edges of each triangle intersecting two edges in the other, so you should only need to test 4 edges, not 6, to guarantee to find an intersection if one exists. (If you do it in that order.. it probably depends on the probability of different intersections which is fastest)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.