Source: https://paulbourke.net/geometry/pointlineplane/
- We could use native AutoCAD methods to further simplify - this is just a 'hello world' proof of concept.
[CommandMethod("TestCoordinates2")]
public void TestCoordinates2()
{
Point3d p0 = new Point3d(0, 2, 0); // plane points
Point3d p1 = new Point3d(0, 2, 1); // plane points
Point3d p2 = new Point3d(3, 4, 0); // plane points
Point3d la = new Point3d(1, 0, 0); // line point a
Point3d lb = new Point3d(1, 2, 0); // line point b
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
try
{
Point3d intersectionPoint = PointOfIntersection(la, lb, p0, p1, p2);
ed.WriteMessage(intersectionPoint.ToString());
}
catch (System.Exception)
{
ed.WriteMessage("Not applicable: the line is parallel to or on the plane itself.");
}
}
private double getC(Vector3d xVector, Vector3d aVector)
{
return xVector.LengthSqrd / (aVector.DotProduct(xVector));
}
public static Point3d PointOfIntersection(Point3d La, Point3d Lb, Point3d P0, Point3d P1, Point3d P2)
{
//thanks to Paul Bourke and Bryan Hanson
//la,Lb constitute the line. P0,P1,P2 constitute the plane
Point3d N = CrossProduct(P0, P1, P2); //N is the normal of the plane
double n = DotProduct(N, new Point3d(P2.X - La.X, P2.Y - La.Y, P2.Z - La.Z));
Point3d LbMinusLa = new Point3d(Lb.X - La.X, Lb.Y - La.Y, Lb.Z - La.Z);
double d = DotProduct(N, LbMinusLa);
if (d == 0) { throw new ArgumentNullException(); } //Line is parallel to or in the plane
double u = n / d;
if ((u >= 0.0) && (u <= 1.0))
{//Plane is between the two points
}//can be used for checking but does not influence the outcome
Point3d IntersectingPoint = new Point3d(La.X + u * LbMinusLa.X, La.Y + u * LbMinusLa.Y, La.Z + u * LbMinusLa.Z);
return IntersectingPoint;
}
public static Point3d CrossProduct(Point3d p0, Point3d p1, Point3d p2) //3 points constituting the plane
{//parallel planes have the same normal
Point3d A = new Point3d(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
Point3d B = new Point3d(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
double X = A.Y * B.Z - A.Z * B.Y;
double Y = A.Z * B.X - A.X * B.Z;
double Z = A.X * B.Y - A.Y * B.X;
return new Point3d(X, Y, Z);
}
public static Point3d CrossProduct(Point3d A, Point3d B) //A and B are vectors ie magnitude and direction same as Point3D
{
double X = A.Y * B.Z - A.Z * B.Y;
double Y = A.Z * B.X - A.X * B.Z;
double Z = A.X * B.Y - A.Y * B.X;
return new Point3d(X, Y, Z);
}
public static double DotProduct(Point3d A, Point3d B)
{
double answer = A.X * B.X + A.Y * B.Y + A.Z * B.Z;
return answer;
}