Created
July 27, 2018 17:24
-
-
Save Const-me/bb3788d47bcd10cd16f970f06acbccde to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Windows; | |
// Base class for lines | |
abstract class LineBase | |
{ | |
// First and second point of the line | |
public readonly Point p0, p2; | |
public override string ToString() | |
{ | |
return $"{{ {p0} }} -> {{ {p2} }}"; | |
} | |
protected LineBase( Point a, Point b ) | |
{ | |
if( !( a - b ).LengthSquared.isNormal() ) | |
throw new ArgumentException( "The points are too close, they don't define a line." ); | |
p0 = a; | |
p2 = b; | |
} | |
// Test if the parameter is inside the line. | |
protected abstract bool isInside( double param ); | |
// Intersection algorithm goes here | |
public bool intersects( LineBase that, out double paramThis, out double paramThat ) { ... } | |
// Returns p0 * ( 1.0 - param ) + p2 * param | |
public Point at( double param ) { ... } | |
} | |
class Line : LineBase | |
{ | |
public Line( Point a, Point b ) : base( a, b ) { } | |
protected override bool isInside( double param ) | |
{ | |
// Lines are infinite in both directions | |
return true; | |
} | |
} | |
class Ray : LineBase | |
{ | |
public Ray( Point a, Point b ) : base( a, b ) { } | |
protected override bool isInside( double param ) | |
{ | |
// Rays are infinite in one direction | |
return param >= -0.0; | |
} | |
} | |
class Segment : LineBase | |
{ | |
public Segment( Point a, Point b ) : base( a, b ) { } | |
protected override bool isInside( double param ) | |
{ | |
// Segments are limited on both ends. | |
return param >= -0.0 && param <= 1.0; | |
} | |
} | |
static class LinesExt | |
{ | |
public static double? intersectionParam( this LineBase i, LineBase that ) | |
{ | |
bool res = i.intersects( that, out double m0, out double m2 ); | |
if( !res ) | |
return null; | |
return m0; | |
} | |
public static Point? intersectionPoint( this LineBase i, LineBase that ) | |
{ | |
bool res = i.intersects( that, out double m0, out double m2 ); | |
if( !res ) | |
return null; | |
return i.at( m0 ); | |
} | |
public static bool intersects( this LineBase i, LineBase that ) | |
{ | |
return i.intersects( that, out double m0, out double m2 ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment