Plane-Curve intersection from algebraic point of view is quiet similar to **Plane-Line intersection** which we discussed in previous post. In this post I would like to take the same approach in finding the Plane-Curve intersection which involves root finding techniques, and in the next post we will also look at **Face-Curve intersection** method and we will use to implement a method for Plane-Curve intersection. If you are looking for a robust and fast solution , then feel free to jump to my next post . If by any chance you are interested in differential geometry and mathematics like me 😉 then please continue reading…

Let’s have a look again at the plane and curve parameterization:

Equation * (1)* represent a plane with normal vector n which passes through point

*and Equation*

**p₀***is the parametric formulation of curve*

**(2)***with parameter*

**C***.*

**t***is a function which maps a real number to a position vector in 3d space. In this form*

**C****is called natural parameter of curve**

*t***.**

*C**represents the point on plane and the point on the curve in both equations, just like the Plane-Line intersection we replace the point*

**P***in equation*

**p***by its value from equation*

**(1)***and we solve the new equation for*

**(2)***.*

**t**In order to solve above equation we need to know about the function * C* in Revit API. There are two methods which can be used to evaluate the curve with given natural or normal parameter which are listed below

The first method simply evaluate the curve at given parameter and return the point on the curve. The second method is far more better, since it returns the potion of the point along with its derivatives which are useful in root finding technique which we will discuss later. Please read documentation for `ComputeDerivatives() `

as I’m not going to cover all details here.

The equation * (3)* has one unknown

*and if the curve is smooth and differentiable then the equation is also differentiable which means we can use newton method for root finding . Although there are several roof finding algorithms which can be used in this case, but I have selected the newton method as it is easy to implement and has quadratic convergence rate. As I mentioned above you may not use this algorithm for your code where the Plane-Curve intersection is used expensively and instead, please refer my next post on this topic.*

**(t)**The newton method requires to have the first derivative of equation * (3)* with respect to the unknown

*. Here we shall write:*

**(t)**

Expanding above we get :

The second part is constant with respect to the ** t** , therefore it is eliminated

Expanding the * (4-2)* using the derivative of the dot-product we obtain:

Again the right expression is constant with respect to the (t) therefore we can eliminate and write :

In equation ** (4-3)** we only need to the derivative of the function

*with respect to the parameter*

**C***and then compute the dot product of it with plane normal. As already mentioned above the*

**t**`ComputeDerivatives()`

method returns the first derivative of the function *in the BasisX vector of the resulted transformation matrix. This derivative can be also interpreted as the tangent vector to the curve at parameter*

**C***. Now we have both requirements for Newton method, first the evaluation of the equation*

**t****which we call it function**

*(3)***from now on and the first derivative of the function**

*f(t)**at parameter*

**f****which is written as**

*t***:**

*df*// compute C(t) and C'(t) tr = cc.ComputeDerivatives(t, false); //compute the objective function f(t) f = (tr.Origin - q.Origin).DotProduct(q.Normal); // compute the derivative of function f(t) df = tr.BasisX.DotProduct(q.Normal);

I’m not going to discuss the newton method in full detail , The most basic version starts with a single-variable function ** f** defined for a real variable

**, the function’s derivative**

*x**, and an initial guess*

**f**′**for a root of**

*x**₀***. If the function satisfies sufficient assumptions and the initial guess is close, then:**

*f*The algorithm is pretty simple, we start with initial guess * t *and in each iteration we compute the step size

**dx =***The*

**-f(t)/f'(t) .***parameter*

*is moved to the new position and the function*

**t***is evaluated again. This loop continues till either the value of function*

**f***is close to zero or the number of iteration exceeds a maximum value (here 100 iterations) . Below shows the implementation assuming the interval*

**f***is the curve domain.*

**[t₁,t₂]**//Newton method for finding the root of the function f(t) double f;// the value of the function in each iteration double df; // the first derivative of the function f at each iteration double dx = 0; // step size (delta x) int I = 0; // number of iterations Transform tr;//= Transform.Identity; do { t += dx; // move t to the new position // ensure the parameter is within the limits if (t < t1) { t = t1; } if (t > t2) { t = t2; } I++; // compute C(t) and C'(t) tr = cc.ComputeDerivatives(t, false); //compute the objective function f(t) f = (tr.Origin - q.Origin).DotProduct(q.Normal); // compute the derivative of function f(t) df = tr.BasisX.DotProduct(q.Normal); // find the step dx = -f / df; rootFound = Math.Abs(f) < epsilon; // check if f is small enough } while ( I < 100 // stop if more than 100 iterations is done && !rootFound // stop if root is found );

To implement the method we need a guess point, a point which grantees that algorithm finds a root. This depends on choice of ** t** and number of solution of equation

**. It is possible for a curve that intersect the plane in more than one point, this means we need to run the root finding algorithm in the intervals which we know one local solution is available. Almost all root finding algorithms finds only one solution near the guess point , therefore another algorithm must be implemented to find the intervals with only one root. This is generally called root isolating algorithm where in most cases require the original polynomial of the function**

*(3)**. Unfortunately we are not able to retrieve the polynomial function via Revit API. However there are methods in Revit API which allows to split an divide curves.*

**f(t)**Using MakeBound() we can create a curve from a sub-domain of the bigger curve * C*. Since we are using the curve parameter

*in function*

**t***dividing the curve*

**f(x)***at parameter*

**C***is the same as splitting the function*

**t***using line*

**f(x)***.*

**x=t**//Divide curve c with start and end parameter t1 & t2 at parameter t //into two segments try { Curve segment1 = c.Clone(); segment1.MakeBound(t1, t); } catch { } try { Curve segment2 = c.Clone(); segment2.MakeBound(t, t2); } catch { }

Some algorithm suggest to approximate the curve with retentively small segments and then run the root finding algorithm in each segment. Since with Revit API we can compute the curve length in each step, I’m going to take advantage of this known parameter. We start with subdividing the curves into half till a certain conditions are met. The first condition is that we ensure there is at least one root for function * f(t)* . We know that If

*has odd number of solutions then*

**f(t)=0***(the graphs on the left) and if the number of solution is even or has no solution then*

**f(0)*f(1) <0***holds (the graphs on the right).*

**f(0)*f(1) >0**So the algorithm starts with finding an interval like * [a,b]* as such that

**f(a)*f(b) <0.**We start with the

**parameter**

**t**somewhere with this interval (middle is a good choice

**t=(a+b)/2**)

*and then verify the stop criteria again for both sub-intervals*

*and*

**[a,t]**

**[t,b]***Note that function*

**.***is nothing but the signed distance of the point*

**f(t)***from the plane*

**c(t)***, hence we can use the extension method*

**Q***DistanceTo(Plane q,Point p, out projection)*which we discussed earlier.

public static void CurvePlaneIntersection(Curve c, Plane q, double t1, double t2, List<XYZ> intersectionPoints, double epsilon) { // create a new curve with in the given interval [t1,t2] Curve cc = c.Clone(); try { cc.MakeBound(t1, t2); } catch { return; } XYZ pp1, pp2;// projection of start and end point of the curve segment on the plane XYZ p1 = cc.GetEndPoint(0);// start point XYZ p2 = cc.GetEndPoint(1);// end point double h1 = DistanceTo(q, p1, out pp1);// signed distance of point p1 double h2 = DistanceTo(q, p2, out pp2);// signed distance of point p2 double t = (t1 + t2) / 2.0;// Curve parameter at the middle of the interval [t1,t2] if (h1 * h2 > 0) { // do not search for root here } else { // ------ root finding here ----- } // divide the domain to [t1,t] and [t,t2] and recall the method CurvePlaneIntersection(cc, q, t1, t, intersectionPoints, epsilon); CurvePlaneIntersection(cc, q, t, t2, intersectionPoints, epsilon); }

Below graph illustrates an imaginary function * f(t)* across the domain

*and we are interested in finding the roots. From the illustration you can see the function intersect the line*

**[t₁,t₂]****in 6 distinct positions. We first check the sign of**

*y=0**. since the sign is positive then we cannot insure if there is a root in domain*

**f(t₁)*f(t₂)***despite the fact that is obvious in the image. Therefore algorithm divides the interval*

**[t₁,t₂]***into two sub-domains*

**[t₁,t₂]***and*

**[t₁,t₃]***where*

**[t₁,t₂]***.*

**t₃ = (t₁+t₂) /2.0**Now algorithm runs again in each sub-domain and check for the sign of function in both ends. Again in the both domains we have ** f(t₁)*f(t₃)>0** &

*. Both domains are divided again and send it back as new inputs to our recursive algorithm.*

**f(t₃)f(t₂)>0**In the new domains * [t₁,t₄]* and

*we can see the*

**[t₄,t₃]***and*

**f(t₁)*f(t₄)<0***which means there is at least one root in each sub-domain. Algorithm shall now switch to root finding routine and find the nearest root to the guess point. To be consistent with the main algorithm we also use the mid point for our root finding algorithm and start the search from the point*

**f(t₄)*f(t₃)<0***and similarly for the interval*

**t₆ = (t₁+t₄)/2***from the point*

**[t₄,t₃]***. On the other side the interval*

**p₇***and*

**[t₃,t₅]***are yet have positive sign for in both ends so they must be divided further.*

**[t₅,t₂]**

Now that root finding algorithm found the two roots * r₁ *and

*should we continue the sub-division process? well , Yes! as it was shown before there could any odd number of roots in the interval and not only one. In this case we cannot sub-divide the domain from the middle as we may end up finding the same root again. One solution is to divide the domain at the position of the root. In this case the sign of*

**r₂****and**

*f(t₁)*f(r₁)***is not useful as it is always returns zero (**

*f(r₁)*f(t₄)**) . In this scenario we need to develop a new criteria to stop the search. looking at the below illustration for we can see a curve starts at point*

**f(r₁ ) = 0***on one side of the plane and ends on point*

**p***which is in the plane*

**r***. For this curve to intersect the line plane*

**Q****in more than one location it is necessary to be longer than the line connecting the point**

*Q**to point*

**p***.*

**r**The difference in length of the curve * C* and line

*cannot be less than Application.ShortCurveTolerance since this is the length of the shortest curve that is possible in Revit. Here we can update our criteria where at one side of the domain the function is zero.*

**l**// check if at one side of the domain f(t)=0 if (Math.Abs(h1) < epsilon || Math.Abs(h2) < epsilon) { // compute the length of the line connecting the p1 to p2 double lineLength = p1.DistanceTo(p2); // the difference in length is less than ShortCurveTolerance exit if (Math.Abs(lineLength - cc.Length) < app.ShortCurveTolerance) return;

}

else if (h1 * h2 > 0)

{

// do not search for root here

}

else

{

// —— root finding here —–

}

Still the recursive algorithm can end up in an infinite loop! because the subdivision can go on and on for the portion of curve that is not intersecting the plane as * f(a)*f(b)* is always positive. We could stop the recursion with the same condition however with both points

*and*

**f(a)***) on one side of*

**f(b****we can do a better job.**

*y=0*In below illustration the plane * Q’* is defined as a plane which contains to end points of the curve

*and perpendicular to the plane*

**C***. we would like to project the curve*

**Q***on plane*

**C***and proof that length of the projection curve*

**Q’***is shorter than the length of the original curve*

**S***.*

**C**Fist we write the length function L(s) and L(c) for both curves:

Above is equivalent to below which means all we need to proof is that the inner product of * S’ *is always smaller than inner product of

**C’**To find the projected curve we move all the points of the curve * C* along the normal direction of projection plane

*by the signed distance*

**(Q’)***. Note that the n is the normal of the projection Plane.*

**(Equation 3)**Below we compute the derivative of * S* with respect to curve parameter

*and its inner product*

**t**In equation number * (9)* it is obvious that inner product of

*is less than inner product of*

**S’***because the*

**C’**

**(C’.n)***is always positive , hence we proofed that*

**²**

**L(C) ≥ L(S)**Now instead of the actual Curve * C* we consider its projection on the plane

*and look for a point which curve*

**Q’***contacts the plane. In below illustration the length of the curve*

**S***is sum of the the length of Curve*

**S***and*

**S₁***hence we can write*

**S₂**We know that the shortest path between two points on a plane is always the straight line connecting them. therfore we can re-write equation * (10)* as below:

Let’s find the mirrored image of point * P₁* with respect to the line

*and call it point*

**y=0***and also point*

**p’****₁***find the projection of point*

**q***on the line connecting*

**p₂***to*

**p₁***We draw a line connecting*

**p’₁.***and*

**p₂***with length of*

**p’₁***. From the triangle inequality theorem , It is also known that in a triangle the sum of two edges is always greater or equal to the third edge. therefore :*

**l₃**Two triangles * q,p’₁,p₂* and

*are right angle, hence from Pythagorean theorem we can write :*

**q,p₂,p₁**By substituting the **c ₂** from the right equation we then achieve :

And finally we find a minimum length for the curve * C* , we can use this term as stop criteria

Notice that if one of the terms * h₁* or

*are zero our condition reduces to simple comparison between the curve length and line length which we used before, therefore it is not a bad idea to replace the previous condition with the new one. In below you can see that condition for both scenarios are combined into one.*

**h₂**// check if at one side of the domain f(t)=0 ot f(t1)*f(t2)>0 if (Math.Abs(h1) < epsilon || Math.Abs(h2) < epsilon || h1*h2>0) { // compute the length of the line connecting the p1 to p2 double d = p1.DistanceTo(p2); // Check if the curve C is long enought to make an intersection with the plane if (cc.Length < Math.Sqrt(4 * Math.Abs(h1) * Math.Abs(h2) + d * d) + tolerance) return; } else { // ------ root finding here ----- }

Now the algorithm stops when the sub-curve is not long enough to make an intersection with the plane. For example as shown in below illustration the curve segment between * p₉* and

*will be subdivide till the length of the seghemt reach the treshold given by equation*

**p₁₅**

**(11)**Below you can find the entire implementation of the method. This method works well for less number of intersections. When it comes to massive number of intersections it may suffer in performance, however you can increase the speed by making the search slightly less accurate and using bigger value for the epsilon (maximum distance from the point to the plane). In the next post we discuss a simpler but more robust method which uses some Revit API native methods to compute the intersection.

/// <summary> /// Search in domain[t1,t2] and finds the intersections of Curve c and Plane q within the given tolerance /// </summary> /// <param name="c">Input curve</param> /// <param name="q">Input plane</param> /// <param name="t1">Curve parameter at the start of domain. /// To start pass c.GetEndParameter(0)</param> /// <param name="t2">Curve parameter at the end of domain. /// To start pass c.GetEndParameter(1)</param> /// <param name="intersectionPoints">Empty list to store the intersection points</param> /// <param name="epsilon">Threshold for the distance of the point to the plane</param> /// <param name="tolerance">Use Application.ShortCurveTolerance</param> public static void Curve_PlaneIntersection4 (Curve c, Plane q, double t1, double t2, List<XYZ> intersectionPoints, double epsilon, double tolerance) { // create a new curve with in the given interval [t1,t2] Curve cc = c.Clone(); try { cc.MakeBound(t1, t2); } catch { return; // if the domain is too small do not continue }

XYZ pp1, pp2;// projection of start and end point of the curve segment on the plane

XYZ p1 = cc.GetEndPoint(0);// start point

XYZ p2 = cc.GetEndPoint(1);// end point

double h1 = DistanceTo(q, p1, out pp1);// signed distance of point p1

double h2 = DistanceTo(q, p2, out pp2);// signed distance of point p2

double t = (t1 + t2) / 2.0;// Curve parameter at the middle of the interval [t1,t2]

// check if at one side of the domain f(t)=0 ot f(t1)*f(t2)>0

if (Math.Abs(h1) < epsilon || Math.Abs(h2) < epsilon || h1 * h2 > 0)

{

// compute the length of the line connecting the p1 to p2

double d = p1.DistanceTo(p2);

// Check if the curve C is long enought to make an intersection with the plane

if (cc.Length < Math.Sqrt(4 * Math.Abs(h1) * Math.Abs(h2) + d * d) + tolerance)

return;

}

else

{

//Newton method for finding the root of the function f(t)

double f;// the value of the function in each iteration

double df; // the first derivative of the function f at each iteration

double dx = 0; // step size (delta x)

int I = 0; // number of iterations

Transform tr;//= Transform.Identity;

bool rootFound = false;// a flag to identify whether an intersection found or not

do

{

t += dx; // move t to the new position

// ensure the parameter is within the limits

if (t < t1)

{

t = t1;

}

if (t > t2)

{

t = t2;

}

I++;

// compute C(t) and C'(t)

tr = cc.ComputeDerivatives(t, false);

//compute the objective function f(t)

f = (tr.Origin – q.Origin).DotProduct(q.Normal);

// compute the derivative of function f(t)

df = tr.BasisX.DotProduct(q.Normal);

// find the step

dx = –f / df;

rootFound = Math.Abs(f) < epsilon; // check if f is small enough

} while (

I < 100 // stop if more than 100 iterations is done

&&

!rootFound // stop if root is found

);

if (rootFound)

{

intersectionPoints.Add(tr.Origin);

}

}

//divide the domain [t1,t2] into [t1,t] and [t,t2] and continue

Curve_PlaneIntersection4(cc, q, t1, t, intersectionPoints, epsilon, tolerance);

Curve_PlaneIntersection4(cc, q, t, t2, intersectionPoints, epsilon, tolerance);

}

## Recent Comments