I have a good understanding of linear interpolation, but I found it difficult to grasp the complexity of the maths of splines. That is why I was looking for a library of some sort that would provide an abstraction to hide the difficult maths. The following function turned out to be sufficient for my needs. This is based on an equation found at http://www.mvps.org/directx/articles/catmull/ , but luckily you don't need to understand how it works. Just remember that unlike linear interpolation where you only need two points to start with, Catmull-Rom spline interpolation uses an extra point at either end. So if you want a spline that passes through 10 points, you need 12.
This function demonstrates Catmull-Rom spline interpolation in one dimension. (For 2 or 3 dimensions simply repeat using Y or Z values.) This function will give us a point on the spline between p1 and p2, where t is the proportion of the distance between the two.
public class SplineTest {
// Catmull-Rom spline interpolation function
public static double q(double t, double p0, double p1, double p2, double p3) {
return 0.5 * ((2 * p1) + (-p0 + p2) * t
+ (2 * p0 - 5 * p1 + 4 * p2 - p3) * (t * t) + (-p0 + 3 * p1 - 3
* p2 + p3)
* (t * t * t));
}
public static void main(String[] args) {
double t = 0.0;
while (t <= 1.0) {
System.out.println(q(t, 5, 10, 20, 10));
t += 0.1;
}
}
}
This program outputs:
10.0
10.887500000000001
12.0
13.2625
14.6
15.9375
17.2
18.3125
19.2
19.7875
20.000000000000004