Intersection points between Line and Mesh

2017-07-27_17-00-42.png

To check if a Line collides with a Mesh, you need to intersect all the Mesh triangles with the Line, by using the Segment3D.IntersectWith() method.
The function below avoids to intersect line and triangles that lie on the same plane, neither adds the duplicated points.

private void SegmentMeshIntersection(Mesh mesh, Segment3D segment, double tolerance, out List<Point3D> intersectedPoints, out List<IndexTriangle> intersectedTriangles)
{
  Point3D intersection;
intersectedPoints = new List<Point3D>();
intersectedTriangles = new List<IndexTriangle>();
 
for (int i = 0; i < mesh.Triangles.Length; i++)
  {
    IndexTriangle it = mesh.Triangles[i];

// if the segment lies on the triangle plane, then avoid the intersection
    if (!segment.IsInPlane(new Plane(mesh.Vertices[it.V1], mesh.Vertices[it.V2], mesh.Vertices[it.V3]), tolerance))
    {
      if (segment.IntersectWith(mesh.Vertices[it.V1], mesh.Vertices[it.V2], mesh.Vertices[it.V3], out intersection))
      {
        intersectedTriangles.Add(it);

// checks for duplicated points
        AddIfDifferent(intersectedPoints, intersection, tolerance);
      }
    }
  }
}

private void AddIfDifferent(List<Point3D> listToCheck, Point3D pointToAdd, double tolerance)
{
int count = 0;

if (listToCheck.Count == 0)
{
listToCheck.Add(pointToAdd);
return;
}

for (int i = 0; i < listToCheck.Count; i++)
{
if (listToCheck[i].DistanceTo(pointToAdd) <= tolerance)
{
count++;
    }
}

if (count == 0)
{
listToCheck.Add(pointToAdd);
}
}

Usage example:

List<Point3D> intersectedPoints;
List<IndexTriangle> intersectedTriangles;

ReadSTL reader = new ReadSTL("bunny.stl");
reader.DoWork();
Mesh bunnyMesh = (Mesh)reader.Entities[0];
Line line = new Line(new Point3D(-80, -15, 40), new Point3D(80, -15, 30));

Segment3D segment = new Segment3D(line.StartPoint, line.EndPoint);
SegmentMeshIntersection(bunnyMesh, segment, 0.01, out intersectedPoints, out intersectedTriangles);
Was this article helpful?
1 out of 1 found this helpful
Have more questions? Submit a request

Comments

1 comment
  • That will be fairly poor performance. You could create a spatial decomposition of the triangles in the mesh and then interrogate the tree to find a candidate set of triangles that might intersect the tree and then only test those triangles to see if they intersect. 

     

    See

     

    http://doc.cgal.org/latest/AABB_tree/index.html

Please sign in to leave a comment.