Skip to content

Commit 513abad

Browse files
Minor improvement to the segment intersection algorithm #568
1 parent f4a4d33 commit 513abad

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

src/ImageSharp.Drawing/Shapes/PolygonClipper/ClipperUtils.cs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -184,17 +184,27 @@ public static bool GetIntersectPoint(Vector2 ln1a, Vector2 ln1b, Vector2 ln2a, V
184184
{
185185
Vector2 dxy1 = ln1b - ln1a;
186186
Vector2 dxy2 = ln2b - ln2a;
187-
float cp = CrossProduct(dxy1, dxy2);
188-
if (cp == 0F)
187+
float det = CrossProduct(dxy1, dxy2);
188+
if (det == 0F)
189189
{
190190
ip = default;
191191
return false;
192192
}
193193

194-
float q1 = CrossProduct(dxy1, ln1a);
195-
float q2 = CrossProduct(dxy2, ln2a);
194+
float t = (((ln1a.X - ln2a.X) * dxy2.Y) - ((ln1a.Y - ln2a.Y) * dxy2.X)) / det;
195+
if (t <= 0F)
196+
{
197+
ip = ln1a;
198+
}
199+
else if (t >= 1F)
200+
{
201+
ip = ln1b;
202+
}
203+
else
204+
{
205+
ip = ln1a + (t * dxy1);
206+
}
196207

197-
ip = ((dxy2 * q1) - (dxy1 * q2)) / cp;
198208
return true;
199209
}
200210

0 commit comments

Comments
 (0)