I spent some time solving equations for evaluating points along a cubic Bézier curve. What I find particularly elegant about Bézier curves is that they can be calculated with recursive/nested linear interpolations. It gets 100 geek points just for the phrases “recursive” and “linear interpolation” — it also wins my appreciation for how comparatively simple it is to solve by hand!
I had come up with an equation a while back for doing this same task, but it wasn’t as tight as it could be. For one thing, it required evaluating the coefficients for each curve every time a point was evaluated.
So, I excercised my inner geek and reworked the equations to simplify it into a 4-term equation (t^[0..3]), which means 4 coefficients, and they can all be calculated at the time the curve is defined, and re-used to evaluate points along the curve! Yay!
Here’s the equation I came up with for a cubic Bézier curve going from A to D, with knots B and C, as T runs from 0 to 1:
A + (-3A + 3B)T + (3A – 6B + 3C)T2 + (-A + 3B – C3 + D)T3
or, as I wrote it in my ruby script:
a + (a*(-3) + b*3)*(t) + (a*3 - b*6 + c*3)*(t**2) + (-a + b*3 - c*3 + d)*(t**3)
Now, I can calculate
(a*(-3) + b*3) and the other coefficients just one time, and then multiply them to new values of t!
Bonus for using a dynamically-typed programming language: one method will work for integers, floats, vectors, and anything else that implements addition, subtraction, and multiplication by an integer. No need to maintain cubicBezi, cubicBezf, and cubicBezv, like I would have to do in C! (Even C++, with its operator overloading, would need 3 functions, all identical except for the types of the arguments and return value.)