Cardinal spline

From Free net encyclopedia

A cardinal spline is a cubic Hermite spline whose tangents are defined by the points and a tension parameter.

Given n+1 points

p0, ..., pn,

to be interpolated with n cubic Hermite curve segments, for each curve we have a starting point pi and an ending point pi+1 with starting tangent mi and ending tangent mi+1 with the tangents defined by

<math> \mathbf{m}_i = (1-c)(\mathbf{p}_{i+1}-\mathbf{p}_{i-1}) </math>

where the first and last tangent m0 and mn are given and c is a constant that modifies the length of the tangent.

Code Example

This is a sample of a perl subroutine to render a cardinal spline. A reference to an array containing 4 sets of coordinates is fed to the formula as well as a tension and a point along the curve.

X and Y coordinates of the point are returned.

sub EvaluateCardinal2D
 {
 use Math::Matrix;
 my($ra_coords,$T,$u)    = @_;
 my $s                   = (1-$T)/2;
 my $u_matrix            = new Math::Matrix    # 4 x 1
     (                   # Matrix based off the point in the curve
      [($u ** 3),    ($u ** 2),    ($u),        (1)        ],
     );
 my $cardinal_matrix     = new Math::Matrix    # 4 x 4
     (                   # Guts of the Cardinal Spline formula
      [(-1 * $s),    (2 - $s),    ($s - 2),        ($s)        ],
      [(2 * $s),     ($s - 3),    (3-(2 * $s)),    (-1 * $s)   ],
      [(-1 * $s),    (0),         ($s),            (0)         ],
      [(0),          (1),         (0),             (0)         ],
     );
 my $x_matrix            = new Math::Matrix    # 1 x 4
     (                   # X coords for point:
      [${${$ra_coords}[0]}[0]],    # 1
      [${${$ra_coords}[1]}[0]],    # 2
      [${${$ra_coords}[2]}[0]],    # 3
      [${${$ra_coords}[3]}[0]],    # 4
     );
 my $y_matrix            = new Math::Matrix    # 1 x 4
     (                   # Y coords
      [${${$ra_coords}[0]}[1]],    # 1
      [${${$ra_coords}[1]}[1]],    # 2
      [${${$ra_coords}[2]}[1]],    # 3
      [${${$ra_coords}[3]}[1]],    # 4
     );
 my $xt    = int ($u_matrix * $cardinal_matrix * $x_matrix); # Compute for X
 my $yt    = int ($u_matrix * $cardinal_matrix * $y_matrix); # Compute for Y
 return($xt,$yt);
 }

What a cardinal spline looks like

This is a graphical plotting of a cardinal spline based off of 10 points on a canvas of 720x480. The line represents the curve, and the squares represent the points. Notice that the curve does not reach the first and last points, they do however effect the shape of the curve.

The points are:

023x024, 123x064, 167x200, 212x285, 293x297, 552x205, 537x071, 358x122, 262x130, 238x024

The tension is set to .1. To see the perl source code used to create this image, go to the image's wiki

Image:Cardinal Spline Example.JPG