Table of Contents

Class BSpline2D

Namespace
CADability.Curve2D
Assembly
CADability.dll

A non-uniform rational B-spline curve (NURBS) in 2d. It is mostly used as a curve in the parameter space of a surface (e.g. as part of the outline of a Face) or as the projection of a 3d BSpline onto a plane. The curve is defined by its poles (control points), optional weights (a rational spline has one weight per pole), the knots with their multiplicities, the degree and a start and end parameter. The underlying NURBS is always clamped, the periodic flag only records how the spline was created. Like every ICurve2D it is addressed by a normalized parameter running from 0.0 (start point) to 1.0 (end point).

public class BSpline2D : GeneralCurve2D, ICurve2D, IQuadTreeInsertable, ISerializable, IDeserializationCallback, IExplicitPCurve2D
Inheritance
BSpline2D
Implements
Inherited Members

Constructors

BSpline2D(GeoPoint2D[], GeoVector2D[], int, bool)

Constructs a non-rational spline of the given degree that interpolates the points and has the given tangent directions at them. Both arrays must have the same length. The degree is reduced to the number of points minus one when necessary.

public BSpline2D(GeoPoint2D[] throughpoints, GeoVector2D[] throughdirections, int degree, bool periodic)

Parameters

throughpoints GeoPoint2D[]

the points to interpolate

throughdirections GeoVector2D[]

the direction of the curve at each point

degree int

the degree of the spline

periodic bool

true for a closed, periodic spline

BSpline2D(GeoPoint2D[], double[], double[], int[], int, bool, double, double)

Constructs a BSpline2D (NURBS) from its main data

public BSpline2D(GeoPoint2D[] poles, double[] weights, double[] knots, int[] multiplicities, int degree, bool periodic, double startParam, double endParam)

Parameters

poles GeoPoint2D[]

the poles

weights double[]

the weigts or null if not rational

knots double[]

the knot vector

multiplicities int[]

the multiplicities vector for the knot vector (same size)

degree int

the degree

periodic bool

true for periodic (closed) false otherwise

startParam double

startparameter

endParam double

endparameter

BSpline2D(GeoPoint2D[], int, bool)

Constructs a non-rational spline of the given degree that interpolates the points in their order. The degree is reduced to the number of points minus one when necessary (two points give a line). A periodic spline is closed and smooth across the first point; the first point need not be repeated at the end. The knot values at which the points are interpolated are kept for PositionOf(GeoPoint2D) and similar methods.

public BSpline2D(GeoPoint2D[] throughpoints, int degree, bool periodic)

Parameters

throughpoints GeoPoint2D[]

the points to interpolate, at least two

degree int

the degree of the spline, typically 3

periodic bool

true for a closed, periodic spline

BSpline2D(GeoPoint2D[], int, bool, double[])

Constructs a BSpline2D (NURBS) by a set of points, that will be interpolated.

public BSpline2D(GeoPoint2D[] throughpoints, int degree, bool periodic, double[] throughpointsparam)

Parameters

throughpoints GeoPoint2D[]

the points to be interpolated

degree int

the degree of the BSpline2D

periodic bool

true for periodic (closed) false otherwise

throughpointsparam double[]

receives the positions at which the curve passes through the provided points, normalized to 0...1 so that they can be handed to PointAt(double) directly; the array must have the same length as throughpoints

BSpline2D(SerializationInfo, StreamingContext)

Constructor required by deserialization

protected BSpline2D(SerializationInfo info, StreamingContext context)

Parameters

info SerializationInfo

SerializationInfo

context StreamingContext

StreamingContext

Properties

Degree

Gets the degree of the BSpline (NURBS)

public int Degree { get; }

Property Value

int

EndDirection

Overrides EndDirection. Usually the derivative at the end. Where that vanishes (coinciding last poles, see CADability.Curve2D.BSpline2D.NegligibleDerivative) it says nothing about the direction, and the unit vector of the tangent there is returned instead.

public override GeoVector2D EndDirection { get; }

Property Value

GeoVector2D

EndParam

The parameter in the knot space at which the curve ends (see StartParam).

public double EndParam { get; }

Property Value

double

EndPoint

The end point of the curve (see EndPoint). This base implementation takes it from the last base point of the triangulation; setting it only replaces that base point and leaves the underlying geometry unchanged, which is acceptable for small corrections only. Curves with their own data override it.

public override GeoPoint2D EndPoint { get; set; }

Property Value

GeoPoint2D

Knots

Gets a copy of the knots defining the BSpline (NURBS)

public double[] Knots { get; }

Property Value

double[]

Length

The arc length of the curve, from its points. Derived classes, which know a closed form or the derivative, should override this. The length used to be taken from an approximation by arcs, which is short by up to some tenths of a percent (e.g. a sine curve, the unrolled miter cut of a tube).

public override double Length { get; }

Property Value

double

MiddleDirection

The direction of the curve at the parameter 0.5 (see MiddleDirection), computed by DirectionAt(double).

public override GeoVector2D MiddleDirection { get; }

Property Value

GeoVector2D

Multiplicities

Gets a copy of the multiplicities defining the BSpline (NURBS)

public int[] Multiplicities { get; }

Property Value

int[]

Poles

Gets a copy of the poles defining the BSpline (NURBS)

public GeoPoint2D[] Poles { get; }

Property Value

GeoPoint2D[]

StartDirection

Overrides StartDirection. Usually the derivative at the start. Where that vanishes (coinciding first poles, see CADability.Curve2D.BSpline2D.NegligibleDerivative) it says nothing about the direction, and the unit vector of the tangent there is returned instead.

public override GeoVector2D StartDirection { get; }

Property Value

GeoVector2D

StartParam

The parameter in the knot space at which the curve starts. The normalized parameter of ICurve2D maps linearly from 0.0 at StartParam to 1.0 at EndParam; TrimParam(double, double) works in the knot space.

public double StartParam { get; }

Property Value

double

StartPoint

The start point of the curve (see StartPoint). This base implementation takes it from the first base point of the triangulation; setting it only replaces that base point and leaves the underlying geometry unchanged, which is acceptable for small corrections only. Curves with their own data override it.

public override GeoPoint2D StartPoint { get; set; }

Property Value

GeoPoint2D

Sweep

The total signed change of direction along the curve in radians (see Sweep). This base implementation computes it from an approximation of the curve by circular arcs (Approximate(bool, double)), which is cached; curves with a closed form override it.

public override double Sweep { get; }

Property Value

double

Weights

Gets a copy of the weights defining the BSpline (NURBS)

public double[] Weights { get; }

Property Value

double[]

Methods

AddToGraphicsPath(GraphicsPath, bool)

Appends this curve to a GDI+ GraphicsPath, which is used for drawing and printing with GDI+.

public override void AddToGraphicsPath(GraphicsPath path, bool forward)

Parameters

path GraphicsPath

the path to append to

forward bool

true to append the curve in its own direction, false to append it reversed (from the end point to the start point)

AdjustPeriodic(GeoPoint2D[], double, double)

Makes a sequence of points in a periodic parameter space continuous: whenever a point differs from its predecessor by more than half a period in x (or y), it is shifted by the period so that the jump disappears; the following points are compared with the shifted point, so a whole tail of the sequence moves across the seam. The array is modified in place.

public static void AdjustPeriodic(GeoPoint2D[] points, double xPeriod, double yPeriod)

Parameters

points GeoPoint2D[]

the points in their order along the curve

xPeriod double

the period in x, or 0.0 (or less) if x is not periodic

yPeriod double

the period in y, or 0.0 (or less) if y is not periodic

Approximate(Func<double, GeoPoint2D>, double, double, double, int)

Approximates the provided curve by a cubic BSpline which interpolates the curve at adaptively chosen parameters. The deviation is checked at the quarter points of each interval between two interpolation parameters, and an interval that deviates more than precision is split into as many parts as the error order of cubic interpolation (h^4) predicts to be necessary. This is repeated until the deviation is less than precision everywhere or maxCount points are used, where the intervals with the largest deviation are refined first. Every curve point is calculated only once.

The parameter of the resulting BSpline2D is the parameter of the provided function: PointAt((par - minPar) / (maxPar - minPar)) is close to curve(par). precision bounds the geometric distance between the curve and the spline, the distance between the points with the same parameter may be larger where it is mostly tangential.

public static BSpline2D Approximate(Func<double, GeoPoint2D> curve, double precision, double minPar = 0, double maxPar = 1, int maxCount = 1000)

Parameters

curve Func<double, GeoPoint2D>

the curve to approximate, as a parameter to point function

precision double

the maximum deviation, 0.0: a small fraction of the extent of the curve

minPar double

the parameter where the curve starts

maxPar double

the parameter where the curve ends, must be greater than minPar

maxCount int

the maximum number of points to use

Returns

BSpline2D

the approximating BSpline, null if the parameter range is invalid or the interpolation fails

Clone()

Returns an independent copy of this curve of the same type. Modifying the copy does not affect this curve.

public override ICurve2D Clone()

Returns

ICurve2D

the copy

CloneReverse(bool)

Returns a copy of this curve (see Clone()) which is reversed when reverse is true, i.e. start point and end point are exchanged and the parameter runs the other way round.

public override ICurve2D CloneReverse(bool reverse)

Parameters

reverse bool

true to reverse the copy, false to copy it as it is

Returns

ICurve2D

the copy

Copy(ICurve2D)

Copies the data of the given object to this object. Both objects must be of the same type.

public override void Copy(ICurve2D toCopyFrom)

Parameters

toCopyFrom ICurve2D

Copies the data of this object

DirectionAt(double)

Returns the direction of the curve at the provided normalized position.

public override GeoVector2D DirectionAt(double Position)

Parameters

Position double

Where to get the direction

Returns

GeoVector2D

The direction

GetArea()

Returns the signed area swept by the line from the origin to the moving point of the curve, i.e. GetAreaFromPoint(GeoPoint2D) with the origin as reference point. For a closed curve this is the enclosed area, positive when the curve runs counterclockwise, negative when it runs clockwise.

public override double GetArea()

Returns

double

the signed area

Remarks

Always integrated (see CADability.Curve2D.BSpline2D.IntegratedArea), no longer taken in closed form from ExplicitPCurve2D. Its polynomials are written in the global knot parameter, so on a short knot span far from zero their coefficients grow with the inverse fifth power of the span width (for a quintic) and cancel each other only in exact arithmetic. In doubles a span of width 1e-3 next to u = 1 cost 1.5 percent of the area, and one of width 5e-7 - as reversing a spline with a short first span produces - turned a contour of a few square decimetres into 4.8e33. The plausibility check against a chord polygon could not catch it: the polygon was evaluated through the same polynomials and came out just as wrong. The integration evaluates the NURBS itself and is exact for a polynomial curve, so nothing is lost by taking it always.

GetAreaFromPoint(GeoPoint2D)

Overrides GetAreaFromPoint(GeoPoint2D).

Derived from GetArea() in closed form instead of going through the base class, which would take the area of an arc approximation. Written out, the reference point enters the integrand only linearly and its contribution telescopes to the end points: A(p) = A(0) - (p.x*(ey-sy) - p.y*(ex-sx)) / 2. For a CLOSED curve the shift vanishes, which is the statement that an enclosed area does not depend on where it is seen from.

public override double GetAreaFromPoint(GeoPoint2D p)

Parameters

p GeoPoint2D

Returns

double

GetExtent()

Returns the bounding rectangle of the curve (see GetExtent()). This base implementation takes the base points of the triangulation and adds the points where the direction of the curve changes its sign in x or y between two base points, found by a simple interpolation; the result may therefore be slightly imprecise.

public override BoundingRect GetExtent()

Returns

BoundingRect

the extent

GetFused(ICurve2D, double)

Returnes a new curve of the same type which is the fusion of this curve with the provided curve, e.g. two overlapping lines build a longer line. Returnes null if the fusion is not possible (e.g. a line and an arc or two lines with different direction)

public override ICurve2D GetFused(ICurve2D toFuseWith, double precision)

Parameters

toFuseWith ICurve2D

Curve to fuse with

precision double

the fused curve or null

Returns

ICurve2D

GetInflectionPoints()

Overrides GetInflectionPoints(). The base class has to approximate the second derivative by a difference of DirectionAt; this class has it exactly from the NURBS evaluation, so the sign changes of x'*y'' - y'x'' are found without that error term. The scan runs over the knot spans, subdivided, because the curvature numerator of a span of degree d is a polynomial of degree 2d-3 and can change sign more than once inside one span.

public override double[] GetInflectionPoints()

Returns

double[]

GetModified(ModOp2D)

Returns a ICurve which is this curve modified by m. The curve can be of different type, e.g. a Circle may return an Ellpse

public override ICurve2D GetModified(ModOp2D m)

Parameters

m ModOp2D

Returns

ICurve2D

GetObjectData(SerializationInfo, StreamingContext)

Writes the data of this object for the legacy binary serialization (ISerializable). Files are written in the JSON format (IJsonSerialize) now; the binary format is still read.

public override void GetObjectData(SerializationInfo info, StreamingContext context)

Parameters

info SerializationInfo

receives the data

context StreamingContext

the destination of the serialization

GetSelfIntersections()

Returns pairs of double values. Each pair defines the two parameters of the curve of a self intersection. The result is either empty or has an even number of double values.

public override double[] GetSelfIntersections()

Returns

double[]

self intersection parameters

GetSimpleCurve(double, out ICurve2D)

Tries to replace the spline by a simpler curve that coincides with it within precision: a Line2D when the spline has degree 1 or all poles lie on the line from the start point to the end point, an Arc2D through start, middle and end point, or a Circle2D for a closed spline.

public bool GetSimpleCurve(double precision, out ICurve2D simpleCurve)

Parameters

precision double

the allowed deviation; 0.0 means eps

simpleCurve ICurve2D

the simpler curve, null when there is none

Returns

bool

true if a simpler curve was found

GetTriangulationBasis(out GeoPoint2D[], out GeoVector2D[], out double[])

Supplies the base points of the triangulation (see MakeTriangulation()): a list of parameters, ascending from 0.0 to 1.0, with the points and the directions of the curve at them. Between two consecutive base points the curve must be free of kinks, and it should bend to one side only, so that the triangle spanned by the two points and their tangents encloses that piece of the curve; the knots of a spline or the quadrant points of an arc are typical choices. GetInflectionPoints() and Length use the same basis to bracket their numerical work. The default implementation takes the parameters 0.0, 0.25, 0.5, 0.75 and 1.0 with the normalized DirectionAt(double).

protected override void GetTriangulationBasis(out GeoPoint2D[] points, out GeoVector2D[] directions, out double[] parameters)

Parameters

points GeoPoint2D[]

the base points on the curve

directions GeoVector2D[]

the directions of the curve at the base points

parameters double[]

the normalized parameters of the base points, ascending

Intersect(ICurve2D)

Calculates the intersection points of this curve with another curve. Each result carries the point and its parameters on both curves (par1 on this curve, par2 on IntersectWith). Depending on the types involved the result may also contain intersections on the extensions of the curves (e.g. of two lines, or of the full circles of two arcs), recognizable by parameters outside 0.0 to 1.0; use IsParameterOnCurve(double) to filter them. The result is not sorted.

public override GeoPoint2DWithParameter[] Intersect(ICurve2D IntersectWith)

Parameters

IntersectWith ICurve2D

the other curve

Returns

GeoPoint2DWithParameter[]

the intersection points, an empty array when there are none

Intersect(GeoPoint2D, GeoPoint2D)

Calculates the intersection points of this curve with the line from StartPoint to EndPoint. Same as Intersect(ICurve2D) with a Line2D: par2 is the parameter on that line (0.0 at StartPoint, 1.0 at EndPoint), and points on the extension of the line or of this curve may be included.

public override GeoPoint2DWithParameter[] Intersect(GeoPoint2D StartPoint, GeoPoint2D EndPoint)

Parameters

StartPoint GeoPoint2D

start point of the line

EndPoint GeoPoint2D

end point of the line

Returns

GeoPoint2DWithParameter[]

the intersection points, an empty array when there are none

IsValidParameter(double)

Determines, whether the given parameter is valid for this curve. Some curves are restricted to a parameterrange by their nature.

public override bool IsValidParameter(double par)

Parameters

par double

the parameter to test

Returns

bool

true if valid

MakeCircle(GeoPoint2D, double)

Creates a full circle as a rational quadratic spline with nine poles (four spans of 90 degrees), running counterclockwise from the point in the direction of the positive x-axis. For cases where a circle has to be a BSpline2D; Circle2D is the exact and faster representation.

public static BSpline2D MakeCircle(GeoPoint2D center, double radius)

Parameters

center GeoPoint2D

center of the circle

radius double

radius of the circle

Returns

BSpline2D

the spline

MakeGeoObject(Plane)

Creates the 3d object that corresponds to this curve placed in the plane p: the 2d coordinates are taken as coordinates in the coordinate system of the plane (see ToGlobal(GeoPoint2D)). A Line2D yields a Line, a circle, arc or ellipse an Ellipse, a spline a BSpline, a path a Path and so on.

public override IGeoObject MakeGeoObject(Plane p)

Parameters

p Plane

the plane to place the curve in

Returns

IGeoObject

the 3d curve as an IGeoObject

MakeHyperbola(GeoPoint2D, GeoPoint2D, GeoPoint2D, GeoPoint2D)

Creates a (segment of a) hyperbola defined by its endpoints (startPoint, endPoint), the intersection-point of the tangents at the endpoints and a point located on the hyperbola where the hyperbola intersects with the line [midpoint(startPoint, endPoint), tangentIntersectionPoint]

public static BSpline2D MakeHyperbola(GeoPoint2D startPoint, GeoPoint2D endPoint, GeoPoint2D midPoint, GeoPoint2D tangentIntersectionPoint)

Parameters

startPoint GeoPoint2D
endPoint GeoPoint2D
midPoint GeoPoint2D
tangentIntersectionPoint GeoPoint2D

Returns

BSpline2D

MakeSpiral(GeoPoint2D, double, int)

Creates a spiral around center as a cubic spline interpolating eight points per turn: the radius grows linearly with the angle by offset per full turn, starting with radius 0 at the center. Used for the spiral hatch style.

public static BSpline2D MakeSpiral(GeoPoint2D center, double offset, int turns)

Parameters

center GeoPoint2D

center of the spiral

offset double

growth of the radius per turn, the distance between consecutive windings

turns int

number of full turns

Returns

BSpline2D

the spline

MinDistance(GeoPoint2D)

Overrides MinDistance(GeoPoint2D). The base class looks for perpendicular foot points. A corner (see CADability.Curve2D.BSpline2D.CornerKnots) has none for the points in front of it, the corner itself is the closest point there. And a point right at the corner is on the border of every test the search makes. So the corners are taken into account as well, they are points of the curve and can never make the distance too small.

public override double MinDistance(GeoPoint2D p)

Parameters

p GeoPoint2D

Returns

double

Move(double, double)

Move the curve by the given offset

public override void Move(double dx, double dy)

Parameters

dx double
dy double

Parallel(double, bool, double, double)

Returns the parallel (offset) curve at the distance Dist. A positive distance offsets to the right of the direction of the curve (for a counterclockwise arc: outward), a negative distance to the left. Curves which have no exact parallel of their own type (e.g. BSpline2D) are first approximated by lines and arcs when approxSpline is true, and throw an exception otherwise. For composed curves (Path2D, Polyline2D) the offset segments at a convex corner are joined by an arc when the inner angle of the corner is less than roundAngle, and are extended to their intersection otherwise. A line of zero length throws a Curve2DException.

public override ICurve2D Parallel(double Dist, bool approxSpline, double precision, double roundAngle)

Parameters

Dist double

the offset distance, positive to the right of the curve

approxSpline bool

true to allow replacing the curve by an approximation of lines and arcs

precision double

the maximal deviation of that approximation

roundAngle double

corners with an inner angle (in radians) below this value are rounded by an arc, others are extended to a sharp corner; 0.0 never rounds. A negative value is used with its absolute value and additionally removes offset segments that fold back onto their predecessor

Returns

ICurve2D

the parallel curve

PointAt(double)

Returns the point of the curve at the provided normalized position

public override GeoPoint2D PointAt(double Position)

Parameters

Position double

Where to get the direction

Returns

GeoPoint2D

The point

PositionAtLength(double)

Overrides PositionAtLength(double).

The base class answers position / Length, which assumes the curve is parameterized proportionally to its arc length. A line and an arc are; a spline is not. On a cubic spline through five points that assumption is off by eleven percent of the length, no matter how exactly Length itself is known - a measurement with the true arc length confirms the same eleven percent. Here the arc length integral is inverted instead.

public override double PositionAtLength(double position)

Parameters

position double

the arc length measured from the start point

Returns

double

the parameter of the point at that arc length, clamped to 0...1

Project(Plane, Plane)

The 2d-curve is assumed to reside in plane "fromPlane". It will be projected perpendicular onto the plane "toPlane".

public override ICurve2D Project(Plane fromPlane, Plane toPlane)

Parameters

fromPlane Plane

the containing plane

toPlane Plane

the projection plane

Returns

ICurve2D

the projected curve

Reverse()

Reverses the direction of this curve

public override void Reverse()

Split(double)

Splits the curve at the given normalized parameter. The curve itself remains unchanged.

public override ICurve2D[] Split(double Position)

Parameters

Position double

the parameter where to split

Returns

ICurve2D[]

two new curves, the part from 0.0 to Position and the part from Position to 1.0; a single copy of the whole curve when Position is not strictly between 0.0 and 1.0

ToString()

public override string ToString()

Returns

string

Trim(double, double)

Returns a new curve of the same type which is the part of this curve between the two normalized parameters. The curve itself remains unchanged. Normally StartPos is less than EndPos; for a closed curve (Circle2D, Ellipse2D) reversed parameters select the part that runs across the start point of the curve, for other curves the behaviour depends on the type (a Line2D or Arc2D returns the part in reversed direction).

public override ICurve2D Trim(double StartPos, double EndPos)

Parameters

StartPos double

parameter of the start of the part

EndPos double

parameter of the end of the part

Returns

ICurve2D

the trimmed curve, or null when the result would be degenerate (e.g. an arc with zero sweep)

TrimParam(double, double)

Trims this spline in place to the interval from startPar to endPar of the knot space (see StartParam, EndParam). Poles and knots are recomputed by knot insertion, so the trimmed spline is geometrically identical to that part of the original; a periodic spline becomes non-periodic.

public bool TrimParam(double startPar, double endPar)

Parameters

startPar double

start of the interval in the knot space

endPar double

end of the interval in the knot space

Returns

bool

true if the spline was changed, false if the interval already covers the whole spline

TryFindFootPoint(GeoPoint2D, double, double, out double, int, double, double)

Finds the foot point of p on this spline between the two (knot) parameters without a triangulation: Newton iterations on the squared distance, safeguarded by bisection of the interval.

public bool TryFindFootPoint(GeoPoint2D p, double uMin, double uMax, out double uFoot, int maxIter = 20, double tolU = 1E-12, double tolG = 1E-12)

Parameters

p GeoPoint2D

the point

uMin double

lower bound of the parameter interval

uMax double

upper bound of the parameter interval

uFoot double

the parameter of the foot point

maxIter int

maximum number of iterations

tolU double

tolerance of the parameter

tolG double

tolerance of the derivative of the squared distance

Returns

bool

true (the last iterate is returned when the iteration does not converge)

TryPointDeriv2At(double, out GeoPoint2D, out GeoVector2D, out GeoVector2D)

Returns the point and the first two derivatives of the curve with respect to the normalized parameter at position (see TryPointDeriv2At(double, out GeoPoint2D, out GeoVector2D, out GeoVector2D)). This base implementation only provides the point and DirectionAt(double) as first derivative, sets the second derivative to the null vector and returns false; curves that know their second derivative override it.

public override bool TryPointDeriv2At(double position, out GeoPoint2D point, out GeoVector2D deriv1, out GeoVector2D deriv2)

Parameters

position double

the normalized parameter

point GeoPoint2D

the point at the parameter

deriv1 GeoVector2D

the first derivative at the parameter

deriv2 GeoVector2D

the second derivative, the null vector when not available

Returns

bool

true if the second derivative is available, false otherwise