Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created November 14, 2022 15:04
Show Gist options
  • Select an option

  • Save unitycoder/48d715fdca1b614c157fa690a7d03024 to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/48d715fdca1b614c157fa690a7d03024 to your computer and use it in GitHub Desktop.
Delauny triangulations with Bowyer-Watson algorithm
// https://forum.unity.com/threads/delauny-triangulations-with-bowyer-watson-algorithm-produces-inconsistent-result.1361107/
///<summary>
/// Compute the Delauny triangulation given a list of vertices/points using the bowyer-watson algorithm.
///</summary>
public static HashSet<Triangle> DelaunyTriangulation(List<Vector2> vertices)
{
// Initialize super triangle. Just a placeholder for now.
Triangle superTriangle = new Triangle(new Vector2(-100, -100f), new Vector2(100, -100f), new Vector2(0f, 100f));
List<Triangle> badTriangles = new List<Triangle>();
HashSet<Triangle> triangles = new HashSet<Triangle>() { superTriangle };
HashSet<Edge> edgeBuffer = new HashSet<Edge>();
foreach (Vector3 vertex in vertices)
{
// Check if the current vertex is contained inside triangles
// circum Circle, if true then mark those triangles as "bad triangles".
foreach (Triangle triangle in triangles)
{
Circle2D circle = triangle.circumCircle;
if (circle.ContainsPoint(vertex))
badTriangles.Add(triangle);
}
// For each edge in a bad triangle check if it is shared by at least 1 another bad triangle.
// If the edge is not shared then add it to the edge buffer.
foreach (Triangle triangle in badTriangles)
foreach (Edge edge in triangle.edges)
{
bool sharedEdge = false;
foreach (Triangle otherTriangle in badTriangles)
{
if (triangle.Equals(otherTriangle))
continue;
sharedEdge = otherTriangle.ContainsEdge(edge);
if (sharedEdge)
break;
}
if (!sharedEdge)
edgeBuffer.Add(edge);
}
// Remove bad triangle from the triangle list
foreach (Triangle triangle in badTriangles)
triangles.Remove(triangle);
// Create new triangles using edge points and vertex point.
foreach (Edge edge in edgeBuffer)
triangles.Add(new Triangle(edge.a.position, edge.b.position, vertex));
// Clear bad triangles and edge buffers.
edgeBuffer.Clear();
badTriangles.Clear();
}
// Remove triangles which share at least one vertex with the super triangle.
List<Triangle> toRemove = new List<Triangle>();
foreach (Triangle triangle in triangles)
{
foreach (Vertex vertex in superTriangle.vertices)
if (triangle.ContainsVertex(vertex))
{
toRemove.Add(triangle);
break;
}
}
foreach (Triangle discarded in toRemove)
triangles.Remove(discarded);
return triangles;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment