Code archives/Graphics/Arbitrary-Control Bezier Curves

This code has been declared by its author to be Public Domain code.

Download source code

Arbitrary-Control Bezier Curves by ImaginaryHuman2009
This deceptively simple code allows for the calculation of a bezier curve with any number of control points, from 3 upwards.

The function calculates one point on a curve. You will need to call it multiple times with a varying `Position`, in the floating point range of 0.0 to 1.0, and then use the points for drawing - e.g. draw straight lines between each point.

Note, one of the only drawbacks besides speed is that the calculation destroys the contents of the arrays of control points, so if you are to calculate many points on a single curve you may want to make a copy of your control-point arrays before calling the function each time.

I have tested it with a 50 control-point bezier curve and made myself a nice spiral :-D With so many control points, the calculation gets much heavier, and thus slower, so it's dubious as to the usefulness of using so many points for a single curve when cubic beziers are usually good enough. However, 6-10 point beziers are quite interesting.

This generic function is about 1.4 times slower than a hand-coded approach to a specific number of control points, mainly due to the loop overhead.

Pass it an array of X coordinates and an array of Y coordinates, which define the control points. The point on the curve is returned in the variables PointX,PointY.

Replace all of the references to `Float` with `Double` for more accurate calculations.
Function CurvePointAny(X:Float[],Y:Float[],NumberOfControls:Int=3,Position:Float,PointX:Float Var,PointY:Float Var)
	'Calculate a point on a bezier curve with any number of control points using single-precision floating point math
	'Requires at least 3 control points with X and Y coordinates and a current position on the curve in the range 0..1
	'Can handle any number of control points >=3, but the more you add the more calculation is required
	'Coordinates are returned in PointX and PointY variables
	'Contents of X and Y arrays will be trashed by the calculations, so create copies if you need to preserve values

	'Calculate bezier curve with any number of control points
	Local OuterLoop:Int=NumberOfControls-1			'Total number of outer-loop iterations
	Local InnerLoop:Int
	While OuterLoop>0
		InnerLoop=0									'Start inner loop at 0
		While InnerLoop<OuterLoop
			X[InnerLoop]:+((X[InnerLoop+1]-X[InnerLoop])*Position)	'Calculate X point on the curve
			Y[InnerLoop]:+((Y[InnerLoop+1]-Y[InnerLoop])*Position)	'Calculate Y point on the curve
			InnerLoop:+1								'Next inner loop
		Wend
		OuterLoop:-1									'Next outer loop
	Wend	

	'Copy final position into return variables
	PointX=X[0]
	PointY=Y[0]
End Function

Comments

ImaginaryHuman2009
Someone please move this to the BlitzMax section, sorry ;-D


Code Archives Forum