I have two Line objects in C# WPF, and I'm trying to construct a method to work out the coordinates at which the lines intersect (if at all). After giving myself a headache reminding myself of high school maths to do this, I can't work out how to map it into programming format - anyone know how to do this?
Thanks very much,
Becky
I suppose your line objects are made up of two points. What you should do is get the equations of both lines.
Then you should solve the following equation:
equation-line1 = equation-line2
Calculate slope of a line:
float _slope = 1e+10;
if ((p2.x - p1.x) != 0)
_slope = (p2.y - p1.y) / (p2.x - p1.x);
p1 = Point 1 of your line
p2 = Point 2 of your line
Equation of a line:
y = ax + b
a = the slope you calculated
b = the intersect
Solving the equation:
a1 = p1.y - b1 * p1.x;
a2 = q1.y - b2 * q1.x;
x = (a1 - a2) / (b2 - b1);
y = a2 + b2 * x;
vars:
b1 = slope line 1
b2 = slop line 2
q1 = point 1 of your 2nd line
So, x and y are the coordinates of the point where the two lines intersect
This is more of a gee-whiz answer than a practical one, because if all you are doing is intersecting two lines it is very slow. However I thought it was worth a mention.
WPF has the ability to intersect any two shape outlines, including two lines, and tell you the location of the intersection.
Here is the general technique for intersecting two outlines (the edges, not the fill area):
var shape1 = ...;
var shape2 = ...;
var thinPen = new Pen(Brush.Transparent, 0.001);
var geometry1 = shape1.RenderedGeometry.GetWidenedPathGeometry(thinPen);
var geometry2 = shape2.RenderedGeometry.GetWidenedPathGeometry(thinPen);
var combined = Geometry.Combine(
geometry1,
geometry2,
GeometryCombineMode.Intersect,
shape2.TransformToVisual(shape1));
var bounds = combined.GetRenderBounds(thinPen);
If the shapes are known to have the same position the shape2.TransformToVisual(shape1) in the call to Geometry.Combine can be replaced with null.
This technique can be very useful, if, for example, you need to intersect a line with an arbitrary curve.
How to find intersection of two lines/segments/ray with rectangle
public class LineEquation{
public LineEquation(Point start, Point end){
Start = start;
End = end;
IsVertical = Math.Abs(End.X - start.X) < 0.00001f;
M = (End.Y - Start.Y)/(End.X - Start.X);
A = -M;
B = 1;
C = Start.Y - M*Start.X;
}
public bool IsVertical { get; private set; }
public double M { get; private set; }
public Point Start { get; private set; }
public Point End { get; private set; }
public double A { get; private set; }
public double B { get; private set; }
public double C { get; private set; }
public bool IntersectsWithLine(LineEquation otherLine, out Point intersectionPoint){
intersectionPoint = new Point(0, 0);
if (IsVertical && otherLine.IsVertical)
return false;
if (IsVertical || otherLine.IsVertical){
intersectionPoint = GetIntersectionPointIfOneIsVertical(otherLine, this);
return true;
}
double delta = A*otherLine.B - otherLine.A*B;
bool hasIntersection = Math.Abs(delta - 0) > 0.0001f;
if (hasIntersection){
double x = (otherLine.B*C - B*otherLine.C)/delta;
double y = (A*otherLine.C - otherLine.A*C)/delta;
intersectionPoint = new Point(x, y);
}
return hasIntersection;
}
private static Point GetIntersectionPointIfOneIsVertical(LineEquation line1, LineEquation line2){
LineEquation verticalLine = line2.IsVertical ? line2 : line1;
LineEquation nonVerticalLine = line2.IsVertical ? line1 : line2;
double y = (verticalLine.Start.X - nonVerticalLine.Start.X)*
(nonVerticalLine.End.Y - nonVerticalLine.Start.Y)/
((nonVerticalLine.End.X - nonVerticalLine.Start.X)) +
nonVerticalLine.Start.Y;
double x = line1.IsVertical ? line1.Start.X : line2.Start.X;
return new Point(x, y);
}
public bool IntersectWithSegementOfLine(LineEquation otherLine, out Point intersectionPoint){
bool hasIntersection = IntersectsWithLine(otherLine, out intersectionPoint);
if (hasIntersection)
return intersectionPoint.IsBetweenTwoPoints(otherLine.Start, otherLine.End);
return false;
}
public bool GetIntersectionLineForRay(Rect rectangle, out LineEquation intersectionLine){
if (Start == End){
intersectionLine = null;
return false;
}
IEnumerable<LineEquation> lines = rectangle.GetLinesForRectangle();
intersectionLine = new LineEquation(new Point(0, 0), new Point(0, 0));
var intersections = new Dictionary<LineEquation, Point>();
foreach (LineEquation equation in lines){
Point point;
if (IntersectWithSegementOfLine(equation, out point))
intersections[equation] = point;
}
if (!intersections.Any())
return false;
var intersectionPoints = new SortedDictionary<double, Point>();
foreach (var intersection in intersections){
if (End.IsBetweenTwoPoints(Start, intersection.Value) ||
intersection.Value.IsBetweenTwoPoints(Start, End)){
double distanceToPoint = Start.DistanceToPoint(intersection.Value);
intersectionPoints[distanceToPoint] = intersection.Value;
}
}
if (intersectionPoints.Count == 1){
Point endPoint = intersectionPoints.First().Value;
intersectionLine = new LineEquation(Start, endPoint);
return true;
}
if (intersectionPoints.Count == 2){
Point start = intersectionPoints.First().Value;
Point end = intersectionPoints.Last().Value;
intersectionLine = new LineEquation(start, end);
return true;
}
return false;
}
public override string ToString(){
return "[" + Start + "], [" + End + "]";
}
}
full sample is described here
Related
I can't find a way to drawing ARC between two lines. My constraint is : I have to calculate this Arc stroke points. Because i am using InkCanvas and i have to draw this arc point by point, i can't put any object to screen or canvas. So I know i can draw any arc with PATH object and use ArcSegment. With this method yes i can draw arc but it isn't stroke point on the Canvas. For this reason i cannot delete or save it.
Anyway i need calculate this arch point by point.
I have code for drawing circle on canvas like this :
Stroke GetCircleStroke(int centerX, int centerY, int radiusX, int radiusY,double angletoDraw=2.0)
{
StylusPointCollection strokePoints = new StylusPointCollection();
int numTotalSteps = 180;
for (int i = 0; i <= numTotalSteps; i++)
{
double angle = angletoDraw * Math.PI * (double)i / (double)numTotalSteps;
StylusPoint sp = new StylusPoint();
//compute x and y points
sp.X = centerX + Math.Cos(angle) * radiusX;
sp.Y = centerY - Math.Sin(angle) * radiusY;
//add to the collection
strokePoints.Add(sp);
}
Stroke newStroke = new Stroke(strokePoints);
return newStroke;
}
I can draw circle easly, but i couldn't find a way to draw an arc :(
We know center point X,Y and we know Line1 and Line2 coordinates. I just don't know what is that arc..
Could you please help me for calculate arc points like this way ?
You have a few concepts flying around like Line/Segment, Point, Circle, etc. Instead of making a mess of hard to understand code, let's try to breakdown the problem into smaller parts that are easier to digest.
You have a notion of Point, ok, lets implement one:
public struct Point2D //omitted equality logic
{
public double X { get; }
public double Y { get; }
public Point2D(double x, double y)
{
X = x;
Y = y;
}
public override string ToString() => $"{X:N3}; {Y:N3}";
}
Ok, we also have a notion of Segment or a delimitted Line:
public struct Segment2D
{
public Point2D Start { get; }
public Point2D End { get; }
public double Argument => Math.Atan2(End.Y - Start.Y , End.X - Start.X);
public Segment2D(Point2D start, Point2D end)
{
Start = start;
End = end;
}
}
And last, but not least, we have the notion of Circle:
public struct Circle2D
{
private const double FullCircleAngle = 2 * Math.PI;
public Point2D Center { get; }
public double Radius { get; }
public Circle2D(Point2D center, double radius)
{
if (radius <= 0)
throw new ArgumentOutOfRangeException(nameof(radius));
Center = center;
Radius = radius;
}
public IEnumerable<Point2D> GetPointsOfArch(int numberOfPoints, double startAngle, double endAngle)
{
double normalizedEndAngle;
if (startAngle < endAngle)
{
normalizedEndAngle = endAngle;
}
else
{
normalizedEndAngle = endAngle + FullCircleAngle;
}
var angleRange = normalizedEndAngle - startAngle;
angleRange = angleRange > FullCircleAngle ? FullCircleAngle : angleRange;
var step = angleRange / numberOfPoints;
var currentAngle = startAngle;
while (currentAngle <= normalizedEndAngle)
{
var x = Center.X + Radius * Math.Cos(currentAngle);
var y = Center.Y + Radius * Math.Sin(currentAngle);
yield return new Point2D(x, y);
currentAngle += step;
}
}
public IEnumerable<Point2D> GetPoints(int numberOfPoints)
=> GetPointsOfArch(numberOfPoints, 0, FullCircleAngle);
}
Study the implementation of GetPointsOfArch, it shouldn't be too hard to understand.
And now, to solve your problem, you would do:
var myCircle = new Circle2D(new Point2D(centerX, centerY), radius);
var line1 = ....
var line2 = ....
var archPoints = myCircle.GetPointsOfArch(number, line2.Argument, line1.Argument);
Isn't that much easier to read, follow and understand?
The application I'm maintaining has custom drawing functionality, which draws some king of "objects" on an Graphics surface. Object boundaries are described with Rectangle.
Sometimes I need to detect objects, whose rectangles are intersecting with given rectangle.
If the number of objects is large enough, simple iteration like this:
var objectsToManage = _objects.Where(_ => rc.IntersectsWith(_.InscribeRect));
obviously, too slow (_objects here is List<MyObjType>, IscribeRect is object boundaries, and rc is a given rectangle).
I'm thinking about how to do this much faster. First idea is to "sort" objects by theirs rectangles and put them into sorted set... But I'm suspecting, that I'm re-inventing the wheel.
Is there any well-known approaches to achieve what I want?
This is can be done using Quadtrees. You can find a c# implementation here: Virtualized WPF Canvas (the quadtree code is not strictly related to WPF), also lots of info here: ZoomableApplication2: A Million Items and another implementation here: PriorityQuadTree
#region FnLineMerginRectandLines
public static bool LineIntersectsRect(Point p1, Point p2, Rectangle r)
{
return LineIntersectsLine(p1, p2, new Point(r.X, r.Y), new Point(r.X + r.Width, r.Y)) ||
LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y), new Point(r.X + r.Width, r.Y + r.Height)) ||
LineIntersectsLine(p1, p2, new Point(r.X + r.Width, r.Y + r.Height), new Point(r.X, r.Y + r.Height)) ||
LineIntersectsLine(p1, p2, new Point(r.X, r.Y + r.Height), new Point(r.X, r.Y)) ||
(r.Contains(p1) && r.Contains(p2));
}
private static bool LineIntersectsLine(Point l1p1, Point l1p2, Point l2p1, Point l2p2)
{
float q = (l1p1.Y - l2p1.Y) * (l2p2.X - l2p1.X) - (l1p1.X - l2p1.X) * (l2p2.Y - l2p1.Y);
float d = (l1p2.X - l1p1.X) * (l2p2.Y - l2p1.Y) - (l1p2.Y - l1p1.Y) * (l2p2.X - l2p1.X);
if (d == 0)
{
return false;
}
float r = q / d;
q = (l1p1.Y - l2p1.Y) * (l1p2.X - l1p1.X) - (l1p1.X - l2p1.X) * (l1p2.Y - l1p1.Y);
float s = q / d;
if (r < 0 || r > 1 || s < 0 || s > 1)
{
return false;
}
return true;
}
#endregion
public class Line
{
private int Point1X;
private int Point1Y;
private int Point2X;
private int Point2Y;
public Point P1;
public Point P2;
public Line()
{
}
public Line(int left, int top, int width, int height)
{
this.Point1X = Convert.ToInt32(left);
this.Point1Y = Convert.ToInt32(top);
this.Point2X = Convert.ToInt32(width);
this.Point2Y = Convert.ToInt32(height);
P1 = new Point(Point1X, Point1Y);
P2 = new Point(Point2X, Point2Y);
}
public Line(string left, string top, string width, string height)
{
this.Point1X = Convert.ToInt32(left);
this.Point1Y = Convert.ToInt32(top);
this.Point2X = Convert.ToInt32(width);
this.Point2Y = Convert.ToInt32(height);
P1 = new Point(Point1X, Point1Y);
P2 = new Point(Point2X, Point2Y);
}
public Line(Point p1, Point P2)
{
this.P1 = p1;
this.P2 = P2;
}
}
public static List<Line>getfourborders(Rectangle RT)
{
Line topline = new Line(new Point(RT.Left,RT.Top),new Point(RT.Width+RT.Left,RT.Top));// Top Line
Line leftline = new Line((new Point(RT.Left,RT.Top)),new Point(RT.Left,RT.Top+RT.Height));// left Line
Line rightline = new Line((new Point(RT.Left+RT.Width,RT.Top)),new Point(RT.Left + RT.Width,RT.Top+RT.Height));// Right Line
Line bottomline = new Line((new Point(RT.Left,RT.Top+RT.Height)),new Point(RT.Left+RT.Width,RT.Top+RT.Height));//bottom line
List<Line> borderlines = new List<Line>();
borderlines.Add(leftline);
borderlines.Add(topline);
borderlines.Add(rightline);
borderlines.Add(bottomline);
return borderlines;
}
//YourObjectList() contains a rectangle type
public class myobject
{
public myobject(object S, Rectangle RT)
{
this.Rt = RT;
this.anyobjecttype= S;
}
public Rectangle Rt;
public object anyobjecttype ;
}
public List<myobject> CompareRectangles(List<myobject> Rect ,Rectangle GivenRectangle)
{
List<myobject> intersectingobjects = new List<myobject>();
Rectangle CompareWith = new Rectangle();//"_objects.Where(_ => rc.IntersectsWith(_.InscribeRect));"
foreach(myobject iterate in Rect)
{
List<Line> BorderLines = new List<Line>();
BorderLines.AddRange(getfourborders(iterate.Rt));
bool Intersects = BorderLines.Any(x=>LineIntersectsRect(x.P1,x.P2,CompareWith));
if (Intersects)
intersectingobjects.Add(iterate);
}
return intersectingobjects;
}
create another function to get all the border lines(get four points and create four lines from rectangle 1 ) and check if any of the line merges with another rectanglecompare using lineintersectsRect if any of that returns true then the rectangle 1 will intersect with your rectangle R, you can loop it to check rectangle 2 intersects with rectanglecompare and so on..
make sure that you don't pass divide by zero exception in line intersects with line
I have a single curve with circle points. Is it possible to set CurveItemPoints to a different fill color? I would set significantly points to different colors.
Short answer: no.
To do similar stuff I created additional SymbolObj class and added objects of that class to the pane to mark some significant points.
Here's some code for that:
internal class SymbolObj : ZedGraph.GraphObj
{
private ZedGraph.Symbol symbol;
public SymbolObj(ZedGraph.SymbolType type, Color color, PointF position, float size)
{
this.symbol = new ZedGraph.Symbol(type, color);
this.symbol.Size = size;
if((type== SymbolType.Plus || type == SymbolType.Star || type== SymbolType.HDash || type == SymbolType.XCross || type == SymbolType.VDash) && size >= 4)
this.symbol.Border.Width = 3f;
this.symbol.Fill.IsVisible = true;
this.symbol.Fill.Color = color;
this.Location.X = position.X;
this.Location.Y = position.Y;
}
public SymbolObj(SymbolObj rhs)
: base(rhs)
{
this.symbol = new Symbol(rhs.symbol);
}
public override void Draw(Graphics g, ZedGraph.PaneBase pane, float scaleFactor)
{
if (((GraphPane)pane).XAxis.Type == AxisType.Text)
{
if (Location.X > 0)
{
var xx = new double[(int)Location.X];
var yy = new double[(int)Location.X];
for (int i = 0; i < Location.X; i++)
{
xx[i] = i;
yy[i] = double.NegativeInfinity;
}
yy[yy.Count() - 1] = Location.Y;
LineItem line = new LineItem("Symbol", xx, yy, symbol.Fill.Color, SymbolType.None);
symbol.Draw(g, (GraphPane)pane, line, scaleFactor, false);
}
}
else
{
LineItem line = new LineItem("Symbol", new double[] { Location.X }, new double[] { Location.Y }, symbol.Fill.Color, SymbolType.None);
symbol.Draw(g, (GraphPane)pane, line, scaleFactor, false);
}
}
public override void GetCoords(ZedGraph.PaneBase pane, Graphics g, float scaleFactor, out string shape, out string coords)
{
shape = "point";
coords = this.Location.X.ToString() + ", " + this.Location.Y.ToString();
}
}
I have 2 lines. Both lines containing their 2 points of X and Y. This means they both have length.
I see 2 formulas, one using determinants and one using normal algebra. Which would be the most efficient to calculate and what does the formula looks like?
I'm having a hard time using matrices in code.
This is what I have so far, can it be more efficient?
public static Vector3 Intersect(Vector3 line1V1, Vector3 line1V2, Vector3 line2V1, Vector3 line2V2)
{
//Line1
float A1 = line1V2.Y - line1V1.Y;
float B1 = line1V1.X - line1V2.X;
float C1 = A1*line1V1.X + B1*line1V1.Y;
//Line2
float A2 = line2V2.Y - line2V1.Y;
float B2 = line2V1.X - line2V2.X;
float C2 = A2 * line2V1.X + B2 * line2V1.Y;
float det = A1*B2 - A2*B1;
if (det == 0)
{
return null;//parallel lines
}
else
{
float x = (B2*C1 - B1*C2)/det;
float y = (A1 * C2 - A2 * C1) / det;
return new Vector3(x,y,0);
}
}
Assuming you have two lines of the form Ax + By = C, you can find it pretty easily:
float delta = A1 * B2 - A2 * B1;
if (delta == 0)
throw new ArgumentException("Lines are parallel");
float x = (B2 * C1 - B1 * C2) / delta;
float y = (A1 * C2 - A2 * C1) / delta;
Pulled from here
I recently went back on paper to find a solution to this problem using basic algebra. We just need to solve the equations formed by the two lines and if a valid solution exist then there is an intersection.
You can check my Github repository for extended implementation handling potential precision issue with double and tests.
public struct Line
{
public double x1 { get; set; }
public double y1 { get; set; }
public double x2 { get; set; }
public double y2 { get; set; }
}
public struct Point
{
public double x { get; set; }
public double y { get; set; }
}
public class LineIntersection
{
// Returns Point of intersection if do intersect otherwise default Point (null)
public static Point FindIntersection(Line lineA, Line lineB, double tolerance = 0.001)
{
double x1 = lineA.x1, y1 = lineA.y1;
double x2 = lineA.x2, y2 = lineA.y2;
double x3 = lineB.x1, y3 = lineB.y1;
double x4 = lineB.x2, y4 = lineB.y2;
// equations of the form x=c (two vertical lines) with overlapping
if (Math.Abs(x1 - x2) < tolerance && Math.Abs(x3 - x4) < tolerance && Math.Abs(x1 - x3) < tolerance)
{
throw new Exception("Both lines overlap vertically, ambiguous intersection points.");
}
//equations of the form y=c (two horizontal lines) with overlapping
if (Math.Abs(y1 - y2) < tolerance && Math.Abs(y3 - y4) < tolerance && Math.Abs(y1 - y3) < tolerance)
{
throw new Exception("Both lines overlap horizontally, ambiguous intersection points.");
}
//equations of the form x=c (two vertical parallel lines)
if (Math.Abs(x1 - x2) < tolerance && Math.Abs(x3 - x4) < tolerance)
{
//return default (no intersection)
return default(Point);
}
//equations of the form y=c (two horizontal parallel lines)
if (Math.Abs(y1 - y2) < tolerance && Math.Abs(y3 - y4) < tolerance)
{
//return default (no intersection)
return default(Point);
}
//general equation of line is y = mx + c where m is the slope
//assume equation of line 1 as y1 = m1x1 + c1
//=> -m1x1 + y1 = c1 ----(1)
//assume equation of line 2 as y2 = m2x2 + c2
//=> -m2x2 + y2 = c2 -----(2)
//if line 1 and 2 intersect then x1=x2=x & y1=y2=y where (x,y) is the intersection point
//so we will get below two equations
//-m1x + y = c1 --------(3)
//-m2x + y = c2 --------(4)
double x, y;
//lineA is vertical x1 = x2
//slope will be infinity
//so lets derive another solution
if (Math.Abs(x1 - x2) < tolerance)
{
//compute slope of line 2 (m2) and c2
double m2 = (y4 - y3) / (x4 - x3);
double c2 = -m2 * x3 + y3;
//equation of vertical line is x = c
//if line 1 and 2 intersect then x1=c1=x
//subsitute x=x1 in (4) => -m2x1 + y = c2
// => y = c2 + m2x1
x = x1;
y = c2 + m2 * x1;
}
//lineB is vertical x3 = x4
//slope will be infinity
//so lets derive another solution
else if (Math.Abs(x3 - x4) < tolerance)
{
//compute slope of line 1 (m1) and c2
double m1 = (y2 - y1) / (x2 - x1);
double c1 = -m1 * x1 + y1;
//equation of vertical line is x = c
//if line 1 and 2 intersect then x3=c3=x
//subsitute x=x3 in (3) => -m1x3 + y = c1
// => y = c1 + m1x3
x = x3;
y = c1 + m1 * x3;
}
//lineA & lineB are not vertical
//(could be horizontal we can handle it with slope = 0)
else
{
//compute slope of line 1 (m1) and c2
double m1 = (y2 - y1) / (x2 - x1);
double c1 = -m1 * x1 + y1;
//compute slope of line 2 (m2) and c2
double m2 = (y4 - y3) / (x4 - x3);
double c2 = -m2 * x3 + y3;
//solving equations (3) & (4) => x = (c1-c2)/(m2-m1)
//plugging x value in equation (4) => y = c2 + m2 * x
x = (c1 - c2) / (m2 - m1);
y = c2 + m2 * x;
//verify by plugging intersection point (x, y)
//in orginal equations (1) & (2) to see if they intersect
//otherwise x,y values will not be finite and will fail this check
if (!(Math.Abs(-m1 * x + y - c1) < tolerance
&& Math.Abs(-m2 * x + y - c2) < tolerance))
{
//return default (no intersection)
return default(Point);
}
}
//x,y can intersect outside the line segment since line is infinitely long
//so finally check if x, y is within both the line segments
if (IsInsideLine(lineA, x, y) &&
IsInsideLine(lineB, x, y))
{
return new Point { x = x, y = y };
}
//return default (no intersection)
return default(Point);
}
// Returns true if given point(x,y) is inside the given line segment
private static bool IsInsideLine(Line line, double x, double y)
{
return (x >= line.x1 && x <= line.x2
|| x >= line.x2 && x <= line.x1)
&& (y >= line.y1 && y <= line.y2
|| y >= line.y2 && y <= line.y1);
}
}
How to find intersection of two lines/segments/ray with rectangle
public class LineEquation{
public LineEquation(Point start, Point end){
Start = start;
End = end;
IsVertical = Math.Abs(End.X - start.X) < 0.00001f;
M = (End.Y - Start.Y)/(End.X - Start.X);
A = -M;
B = 1;
C = Start.Y - M*Start.X;
}
public bool IsVertical { get; private set; }
public double M { get; private set; }
public Point Start { get; private set; }
public Point End { get; private set; }
public double A { get; private set; }
public double B { get; private set; }
public double C { get; private set; }
public bool IntersectsWithLine(LineEquation otherLine, out Point intersectionPoint){
intersectionPoint = new Point(0, 0);
if (IsVertical && otherLine.IsVertical)
return false;
if (IsVertical || otherLine.IsVertical){
intersectionPoint = GetIntersectionPointIfOneIsVertical(otherLine, this);
return true;
}
double delta = A*otherLine.B - otherLine.A*B;
bool hasIntersection = Math.Abs(delta - 0) > 0.0001f;
if (hasIntersection){
double x = (otherLine.B*C - B*otherLine.C)/delta;
double y = (A*otherLine.C - otherLine.A*C)/delta;
intersectionPoint = new Point(x, y);
}
return hasIntersection;
}
private static Point GetIntersectionPointIfOneIsVertical(LineEquation line1, LineEquation line2){
LineEquation verticalLine = line2.IsVertical ? line2 : line1;
LineEquation nonVerticalLine = line2.IsVertical ? line1 : line2;
double y = (verticalLine.Start.X - nonVerticalLine.Start.X)*
(nonVerticalLine.End.Y - nonVerticalLine.Start.Y)/
((nonVerticalLine.End.X - nonVerticalLine.Start.X)) +
nonVerticalLine.Start.Y;
double x = line1.IsVertical ? line1.Start.X : line2.Start.X;
return new Point(x, y);
}
public bool IntersectWithSegementOfLine(LineEquation otherLine, out Point intersectionPoint){
bool hasIntersection = IntersectsWithLine(otherLine, out intersectionPoint);
if (hasIntersection)
return intersectionPoint.IsBetweenTwoPoints(otherLine.Start, otherLine.End);
return false;
}
public bool GetIntersectionLineForRay(Rect rectangle, out LineEquation intersectionLine){
if (Start == End){
intersectionLine = null;
return false;
}
IEnumerable<LineEquation> lines = rectangle.GetLinesForRectangle();
intersectionLine = new LineEquation(new Point(0, 0), new Point(0, 0));
var intersections = new Dictionary<LineEquation, Point>();
foreach (LineEquation equation in lines){
Point point;
if (IntersectWithSegementOfLine(equation, out point))
intersections[equation] = point;
}
if (!intersections.Any())
return false;
var intersectionPoints = new SortedDictionary<double, Point>();
foreach (var intersection in intersections){
if (End.IsBetweenTwoPoints(Start, intersection.Value) ||
intersection.Value.IsBetweenTwoPoints(Start, End)){
double distanceToPoint = Start.DistanceToPoint(intersection.Value);
intersectionPoints[distanceToPoint] = intersection.Value;
}
}
if (intersectionPoints.Count == 1){
Point endPoint = intersectionPoints.First().Value;
intersectionLine = new LineEquation(Start, endPoint);
return true;
}
if (intersectionPoints.Count == 2){
Point start = intersectionPoints.First().Value;
Point end = intersectionPoints.Last().Value;
intersectionLine = new LineEquation(start, end);
return true;
}
return false;
}
public override string ToString(){
return "[" + Start + "], [" + End + "]";
}
}
full sample is described [here][1]
I'm looking for an algorithm that determines the near and far intersection points between a line segment and an axis-aligned box.
Here is my method definition:
public static Point3D[] IntersectionOfLineSegmentWithAxisAlignedBox(
Point3D rayBegin, Point3D rayEnd, Point3D boxCenter, Size3D boxSize)
If the line segment doesn't intersect the box, the method should return an empty Point3D array.
From my research so far, I've come across some research papers with highly optimized algorithms, but they all seem to be written in C++ and would require multiple long class files to be converted to C#. For my purposes, something that is reasonably efficient, easy to understand by someone who gets dot products and cross products, and simple/short would be preferred.
Here's what I ended up using:
public static List<Point3D> IntersectionOfLineSegmentWithAxisAlignedBox(
Point3D segmentBegin, Point3D segmentEnd, Point3D boxCenter, Size3D boxSize)
{
var beginToEnd = segmentEnd - segmentBegin;
var minToMax = new Vector3D(boxSize.X, boxSize.Y, boxSize.Z);
var min = boxCenter - minToMax / 2;
var max = boxCenter + minToMax / 2;
var beginToMin = min - segmentBegin;
var beginToMax = max - segmentBegin;
var tNear = double.MinValue;
var tFar = double.MaxValue;
var intersections = new List<Point3D>();
foreach (Axis axis in Enum.GetValues(typeof(Axis)))
{
if (beginToEnd.GetCoordinate(axis) == 0) // parallel
{
if (beginToMin.GetCoordinate(axis) > 0 || beginToMax.GetCoordinate(axis) < 0)
return intersections; // segment is not between planes
}
else
{
var t1 = beginToMin.GetCoordinate(axis) / beginToEnd.GetCoordinate(axis);
var t2 = beginToMax.GetCoordinate(axis) / beginToEnd.GetCoordinate(axis);
var tMin = Math.Min(t1, t2);
var tMax = Math.Max(t1, t2);
if (tMin > tNear) tNear = tMin;
if (tMax < tFar) tFar = tMax;
if (tNear > tFar || tFar < 0) return intersections;
}
}
if (tNear >= 0 && tNear <= 1) intersections.Add(segmentBegin + beginToEnd * tNear);
if (tFar >= 0 && tFar <= 1) intersections.Add(segmentBegin + beginToEnd * tFar);
return intersections;
}
public enum Axis
{
X,
Y,
Z
}
public static double GetCoordinate(this Point3D point, Axis axis)
{
switch (axis)
{
case Axis.X:
return point.X;
case Axis.Y:
return point.Y;
case Axis.Z:
return point.Z;
default:
throw new ArgumentException();
}
}
public static double GetCoordinate(this Vector3D vector, Axis axis)
{
switch (axis)
{
case Axis.X:
return vector.X;
case Axis.Y:
return vector.Y;
case Axis.Z:
return vector.Z;
default:
throw new ArgumentException();
}
}
Well, for an axis-aligned box it's pretty simple: you have to find intersection of your ray with 6 planes (defined by the box faces) and then check the points you found against the box vertices coordinates limits.
Optimized version of the answer. There is no reason to do allocations or lookups.
public struct Ray3
{
public Vec3 origin, direction;
public bool IntersectRayBox(Box3 box, out Vec3 point1, out Vec3 point2)
{
var min = (box.center - (box.size / 2)) - origin;
var max = (box.center + (box.size / 2)) - origin;
float near = float.MinValue;
float far = float.MaxValue;
// X
float t1 = min.x / direction.x;
float t2 = max.x / direction.x;
float tMin = Math.Min(t1, t2);
float tMax = Math.Max(t1, t2);
if (tMin > near) near = tMin;
if (tMax < far) far = tMax;
if (near > far || far < 0)
{
point1 = Vec3.zero;
point2 = Vec3.zero;
return false;
}
// Y
t1 = min.y / direction.y;
t2 = max.y / direction.y;
tMin = Math.Min(t1, t2);
tMax = Math.Max(t1, t2);
if (tMin > near) near = tMin;
if (tMax < far) far = tMax;
if (near > far || far < 0)
{
point1 = Vec3.zero;
point2 = Vec3.zero;
return false;
}
// Z
t1 = min.z / direction.z;
t2 = max.z / direction.z;
tMin = Math.Min(t1, t2);
tMax = Math.Max(t1, t2);
if (tMin > near) near = tMin;
if (tMax < far) far = tMax;
if (near > far || far < 0)
{
point1 = Vec3.zero;
point2 = Vec3.zero;
return false;
}
point1 = origin + direction * near;
point2 = origin + direction * far;
return true;
}
}