GeometriCS/intersections/IntersectionLine2ToLine2.cs

88 lines
2.8 KiB
C#
Raw Permalink Normal View History

namespace GeometriCS
{
/// <summary>
/// Intersection between two two-dimensional lines.
/// </summary>
public class IntersectionLine2ToLine2d
{
/// <summary>
/// Possible statuses the intersection can be.
/// </summary>
public enum Statuses
{
/// <summary>
/// Intersection is valid.
/// </summary>
SUCCESS,
/// <summary>
/// The two lines are parallel.
/// </summary>
PARALLEL,
/// <summary>
/// The two lines are colinear and intersect on their whole length.
/// </summary>
COLINEAR,
}
/// <summary>
/// First of the intersecting lines.
/// </summary>
public Line2d Line1 { get; }
/// <summary>
/// The second intersecting line.
/// </summary>
public Line2d Line2 { get; }
/// <summary>
/// Status of the intersection.
/// </summary>
public Statuses Status { get; }
/// <summary>
/// The point of the intersection between the two lines.
/// </summary>
public Vector2d? Result { get; }
/// <summary>
/// Constructor for Line2d to Line2d intersection.
/// </summary>
/// <param name="line1">First of the intersecting lines.</param>
/// <param name="line1">Second of the intersecting lines.</param>
public IntersectionLine2ToLine2d(Line2d line1, Line2d line2)
{
// Set the intersector references
Line1 = line1;
Line2 = line2;
// Check if lines are parallel
// TODO: Check what happens if coeff_B == 0
if(Utils.DoubleEquals(line1.Coeff_A / line1.Coeff_B, line2.Coeff_A / line2.Coeff_B))
{
// Null result
Result = null;
// Check if lines are coincidental
if (Utils.DoubleEquals(line1.Coeff_A / line2.Coeff_A, line1.Coeff_B / line2.Coeff_B) &&
Utils.DoubleEquals(line1.Coeff_A / line2.Coeff_A, line1.Coeff_C / line2.Coeff_C))
{
Status = Statuses.COLINEAR;
}
else
{
Status = Statuses.PARALLEL;
}
return;
}
// Perform the intersection calculation
double divisor = line1.Coeff_A * line2.Coeff_B - line2.Coeff_A * line1.Coeff_B;
double x0 = (line1.Coeff_B * line2.Coeff_C - line2.Coeff_B * line1.Coeff_C) / divisor;
double y0 = (line1.Coeff_C * line2.Coeff_A - line2.Coeff_C * line1.Coeff_A) / divisor;
Result = new Vector2d(x0, y0);
Status = Statuses.SUCCESS;
}
}
}