home *** CD-ROM | disk | FTP | other *** search
/ Graphics Plus / Graphics Plus.iso / general / gems / g_gemsi.lha / GraphicsGems / FitCurves.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-04-10  |  14.1 KB  |  540 lines

  1. /*
  2. An Algorithm for Automatically Fitting Digitized Curves
  3. by Philip J. Schneider
  4. from "Graphics Gems", Academic Press, 1990
  5. */
  6.  
  7. #define TESTMODE
  8.  
  9. /*  fit_cubic.c    */                                    
  10. /*    Piecewise cubic fitting code    */
  11.  
  12. #include "GraphicsGems.h"                    
  13. #include <stdio.h>
  14. #include <malloc.h>
  15. #include <math.h>
  16.  
  17. typedef Point2 *BezierCurve;
  18.  
  19. /* Forward declarations */
  20.         void        FitCurve();
  21. static    void        FitCubic();
  22. static    double        *Reparameterize();
  23. static    double        NewtonRaphsonRootFind();
  24. static    Point2        Bezier();
  25. static    double         B0(), B1(), B2(), B3();
  26. static    Vector2        ComputeLeftTangent();
  27. static    Vector2        ComputeRightTangent();
  28. static    Vector2        ComputeCenterTangent();
  29. static    double        ComputeMaxError();
  30. static    double        *ChordLengthParameterize();
  31. static    BezierCurve    GenerateBezier();
  32. static    Vector2        V2AddII();
  33. static    Vector2        V2ScaleII();
  34. static    Vector2        V2Sub();
  35.  
  36. extern    Vector2        *V2Normalize();
  37.  
  38. #define MAXPOINTS    1000        /* The most points you can have */
  39.  
  40. #ifdef TESTMODE
  41.  
  42. DrawBezierCurve(n, curve)
  43. int n;
  44. BezierCurve curve;
  45. {
  46.     /* You'll have to write this yourself. */
  47. }
  48.  
  49. /*
  50.  *  main:
  51.  *    Example of how to use the curve-fitting code.  Given an array
  52.  *   of points and a tolerance (squared error between points and 
  53.  *    fitted curve), the algorithm will generate a piecewise
  54.  *    cubic Bezier representation that approximates the points.
  55.  *    When a cubic is generated, the routine "DrawBezierCurve"
  56.  *    is called, which outputs the Bezier curve just created
  57.  *    (arguments are the degree and the control points, respectively).
  58.  *    Users will have to implement this function themselves     
  59.  *   ascii output, etc. 
  60.  *
  61.  */
  62. main()
  63. {
  64.     static Point2 d[7] = {    /*  Digitized points */
  65.     { 0.0, 0.0 },
  66.     { 0.0, 0.5 },
  67.     { 1.1, 1.4 },
  68.     { 2.1, 1.6 },
  69.     { 3.2, 1.1 },
  70.     { 4.0, 0.2 },
  71.     { 4.0, 0.0 },
  72.     };
  73.     double    error = 4.0;        /*  Squared error */
  74.     FitCurve(d, 7, error);        /*  Fit the Bezier curves */
  75. }
  76. #endif                         /* TESTMODE */
  77.  
  78. /*
  79.  *  FitCurve :
  80.  *      Fit a Bezier curve to a set of digitized points 
  81.  */
  82. void FitCurve(d, nPts, error)
  83.     Point2    *d;            /*  Array of digitized points    */
  84.     int        nPts;        /*  Number of digitized points    */
  85.     double    error;        /*  User-defined error squared    */
  86. {
  87.     Vector2    tHat1, tHat2;    /*  Unit tangent vectors at endpoints */
  88.  
  89.     tHat1 = ComputeLeftTangent(d, 0);
  90.     tHat2 = ComputeRightTangent(d, nPts - 1);
  91.     FitCubic(d, 0, nPts - 1, tHat1, tHat2, error);
  92. }
  93.  
  94.  
  95.  
  96. /*
  97.  *  FitCubic :
  98.  *      Fit a Bezier curve to a (sub)set of digitized points
  99.  */
  100. static void FitCubic(d, first, last, tHat1, tHat2, error)
  101.     Point2    *d;            /*  Array of digitized points */
  102.     int        first, last;    /* Indices of first and last pts in region */
  103.     Vector2    tHat1, tHat2;    /* Unit tangent vectors at endpoints */
  104.     double    error;        /*  User-defined error squared       */
  105. {
  106.     BezierCurve    bezCurve; /*Control points of fitted Bezier curve*/
  107.     double    *u;        /*  Parameter values for point  */
  108.     double    *uPrime;    /*  Improved parameter values */
  109.     double    maxError;    /*  Maximum fitting error     */
  110.     int        splitPoint;    /*  Point to split point set at     */
  111.     int        nPts;        /*  Number of points in subset  */
  112.     double    iterationError; /*Error below which you try iterating  */
  113.     int        maxIterations = 4; /*  Max times to try iterating  */
  114.     Vector2    tHatCenter;       /* Unit tangent vector at splitPoint */
  115.     int        i;        
  116.  
  117.     iterationError = error * error;
  118.     nPts = last - first + 1;
  119.  
  120.     /*  Use heuristic if region only has two points in it */
  121.     if (nPts == 2) {
  122.         double dist = V2DistanceBetween2Points(&d[last], &d[first]) /             3.0;
  123.  
  124.         bezCurve = (Point2 *)malloc(4 * sizeof(Point2));
  125.         bezCurve[0] = d[first];
  126.         bezCurve[3] = d[last];
  127.         V2Add(&bezCurve[0], V2Scale(&tHat1, dist), &bezCurve[1]);
  128.         V2Add(&bezCurve[3], V2Scale(&tHat2, dist), &bezCurve[2]);
  129.         DrawBezierCurve(3, bezCurve);
  130.         return;
  131.     }
  132.  
  133.     /*  Parameterize points, and attempt to fit curve */
  134.     u = ChordLengthParameterize(d, first, last);
  135.     bezCurve = GenerateBezier(d, first, last, u, tHat1, tHat2);
  136.  
  137.     /*  Find max deviation of points to fitted curve */
  138.     maxError = ComputeMaxError(d, first, last, bezCurve, u,                     &splitPoint);
  139.     if (maxError < error) {
  140.         DrawBezierCurve(3, bezCurve);
  141.         return;
  142.     }
  143.  
  144.  
  145.     /*  If error not too large, try some reparameterization  */
  146.     /*  and iteration */
  147.     if (maxError < iterationError) {
  148.         for (i = 0; i < maxIterations; i++) {
  149.             uPrime = Reparameterize(d, first, last, u, bezCurve);
  150.             bezCurve = GenerateBezier(d, first, last, uPrime, tHat1,                 tHat2);
  151.             maxError = ComputeMaxError(d, first, last,
  152.                        bezCurve, uPrime, &splitPoint);
  153.             if (maxError < error) {
  154.             DrawBezierCurve(3, bezCurve);
  155.             return;
  156.         }
  157.         free((char *)u);
  158.         u = uPrime;
  159.     }
  160. }
  161.  
  162.     /* Fitting failed -- split at max error point and fit recursively */
  163.     tHatCenter = ComputeCenterTangent(d, splitPoint);
  164.     FitCubic(d, first, splitPoint, tHat1, tHatCenter, error);
  165.     V2Negate(&tHatCenter);
  166.     FitCubic(d, splitPoint, last, tHatCenter, tHat2, error);
  167. }
  168.  
  169.  
  170. /*
  171.  *  GenerateBezier :
  172.  *  Use least-squares method to find Bezier control points for region.
  173.  *
  174.  */
  175. static BezierCurve  GenerateBezier(d, first, last, uPrime, tHat1,                     tHat2)
  176.     Point2    *d;            /*  Array of digitized points    */
  177.     int        first, last;        /*  Indices defining region    */
  178.     double    *uPrime;        /*  Parameter values for region */
  179.     Vector2    tHat1, tHat2;    /*  Unit tangents at endpoints    */
  180. {
  181.     int     i;
  182.     Vector2     A[MAXPOINTS][2];    /* Precomputed rhs for eqn    */
  183.     int     nPts;            /* Number of pts in sub-curve */
  184.     double     C[2][2];            /* Matrix C            */
  185.     double     X[2];            /* Matrix X            */
  186.     double     det_C0_C1,        /* Determinants of matrices    */
  187.                det_C0_X,
  188.                det_X_C1;
  189.     double     alpha_l,        /* Alpha values, left and right    */
  190.                alpha_r;
  191.     Vector2     tmp;            /* Utility variable        */
  192.     BezierCurve    bezCurve;    /* RETURN bezier curve ctl pts    */
  193.  
  194.     bezCurve = (Point2 *)malloc(4 * sizeof(Point2));
  195.     nPts = last - first + 1;
  196.  
  197.  
  198.     /* Compute the A's    */
  199.     for (i = 0; i < nPts; i++) {
  200.         Vector2        v1, v2;
  201.         v1 = tHat1;
  202.         v2 = tHat2;
  203.         V2Scale(&v1, B1(uPrime[i]));
  204.         V2Scale(&v2, B2(uPrime[i]));
  205.         A[i][0] = v1;
  206.         A[i][1] = v2;
  207.     }
  208.  
  209.     /* Create the C and X matrices    */
  210.     C[0][0] = 0.0;
  211.     C[0][1] = 0.0;
  212.     C[1][0] = 0.0;
  213.     C[1][1] = 0.0;
  214.     X[0]    = 0.0;
  215.     X[1]    = 0.0;
  216.  
  217.     for (i = 0; i < nPts; i++) {
  218.         C[0][0] += V2Dot(&A[i][0], &A[i][0]);
  219.         C[0][1] += V2Dot(&A[i][0], &A[i][1]);
  220. /*                    C[1][0] += V2Dot(&A[i][0], &A[i][1]);*/    
  221.         C[1][0] = C[0][1];
  222.         C[1][1] += V2Dot(&A[i][1], &A[i][1]);
  223.  
  224.         tmp = V2Sub(d[first + i],
  225.             V2AddII(
  226.               V2ScaleII(d[first], B0(uPrime[i])),
  227.                 V2AddII(
  228.                       V2ScaleII(d[first], B1(uPrime[i])),
  229.                             V2AddII(
  230.                               V2ScaleII(d[last], B2(uPrime[i])),
  231.                                 V2ScaleII(d[last], B3(uPrime[i]))))));
  232.     
  233.  
  234.     X[0] += V2Dot(&A[i][0], &tmp);
  235.     X[1] += V2Dot(&A[i][1], &tmp);
  236.     }
  237.  
  238.     /* Compute the determinants of C and X    */
  239.     det_C0_C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1];
  240.     det_C0_X  = C[0][0] * X[1]    - C[0][1] * X[0];
  241.     det_X_C1  = X[0]    * C[1][1] - X[1]    * C[0][1];
  242.  
  243.     /* Finally, derive alpha values    */
  244.     if (det_C0_C1 == 0.0) {
  245.         det_C0_C1 = (C[0][0] * C[1][1]) * 10e-12;
  246.     }
  247.     alpha_l = det_X_C1 / det_C0_C1;
  248.     alpha_r = det_C0_X / det_C0_C1;
  249.  
  250.  
  251.     /*  If alpha negative, use the Wu/Barsky heuristic (see text) */
  252.     if (alpha_l < 0.0 || alpha_r < 0.0) {
  253.         double    dist = V2DistanceBetween2Points(&d[last], &d[first]) /
  254.                     3.0;
  255.  
  256.         bezCurve[0] = d[first];
  257.         bezCurve[3] = d[last];
  258.         V2Add(&bezCurve[0], V2Scale(&tHat1, dist), &bezCurve[1]);
  259.         V2Add(&bezCurve[3], V2Scale(&tHat2, dist), &bezCurve[2]);
  260.         return (bezCurve);
  261.     }
  262.  
  263.     /*  First and last control points of the Bezier curve are */
  264.     /*  positioned exactly at the first and last data points */
  265.     /*  Control points 1 and 2 are positioned an alpha distance out */
  266.     /*  on the tangent vectors, left and right, respectively */
  267.     bezCurve[0] = d[first];
  268.     bezCurve[3] = d[last];
  269.     V2Add(&bezCurve[0], V2Scale(&tHat1, alpha_l), &bezCurve[1]);
  270.     V2Add(&bezCurve[3], V2Scale(&tHat2, alpha_r), &bezCurve[2]);
  271.     return (bezCurve);
  272. }
  273.  
  274.  
  275. /*
  276.  *  Reparameterize:
  277.  *    Given set of points and their parameterization, try to find
  278.  *   a better parameterization.
  279.  *
  280.  */
  281. static double *Reparameterize(d, first, last, u, bezCurve)
  282.     Point2    *d;            /*  Array of digitized points    */
  283.     int        first, last;        /*  Indices defining region    */
  284.     double    *u;            /*  Current parameter values    */
  285.     BezierCurve    bezCurve;    /*  Current fitted curve    */
  286. {
  287.     int     nPts = last-first+1;    
  288.     int     i;
  289.     double    *uPrime;        /*  New parameter values    */
  290.  
  291.     uPrime = (double *)malloc(nPts * sizeof(double));
  292.     for (i = first; i <= last; i++) {
  293.         uPrime[i-first] = NewtonRaphsonRootFind(bezCurve, d[i], u[i-
  294.                     first]);
  295.     }
  296.     return (uPrime);
  297. }
  298.  
  299.  
  300.  
  301. /*
  302.  *  NewtonRaphsonRootFind :
  303.  *    Use Newton-Raphson iteration to find better root.
  304.  */
  305. static double NewtonRaphsonRootFind(Q, P, u)
  306.     BezierCurve    Q;            /*  Current fitted curve    */
  307.     Point2         P;        /*  Digitized point        */
  308.     double         u;        /*  Parameter value for "P"    */
  309. {
  310.     double         numerator, denominator;
  311.     Point2         Q1[3], Q2[2];    /*  Q' and Q''            */
  312.     Point2        Q_u, Q1_u, Q2_u; /*u evaluated at Q, Q', & Q''    */
  313.     double         uPrime;        /*  Improved u            */
  314.     int         i;
  315.     
  316.     /* Compute Q(u)    */
  317.     Q_u = Bezier(3, Q, u);
  318.     
  319.     /* Generate control vertices for Q'    */
  320.     for (i = 0; i <= 2; i++) {
  321.         Q1[i].x = (Q[i+1].x - Q[i].x) * 3.0;
  322.         Q1[i].y = (Q[i+1].y - Q[i].y) * 3.0;
  323.     }
  324.     
  325.     /* Generate control vertices for Q'' */
  326.     for (i = 0; i <= 1; i++) {
  327.         Q2[i].x = (Q1[i+1].x - Q1[i].x) * 2.0;
  328.         Q2[i].y = (Q1[i+1].y - Q1[i].y) * 2.0;
  329.     }
  330.     
  331.     /* Compute Q'(u) and Q''(u)    */
  332.     Q1_u = Bezier(2, Q1, u);
  333.     Q2_u = Bezier(1, Q2, u);
  334.     
  335.     /* Compute f(u)/f'(u) */
  336.     numerator = (Q_u.x - P.x) * (Q1_u.x) + (Q_u.y - P.y) * (Q1_u.y);
  337.     denominator = (Q1_u.x) * (Q1_u.x) + (Q1_u.y) * (Q1_u.y) +
  338.                     (Q_u.x - P.x) * (Q2_u.x) + (Q_u.y - P.y) * (Q2_u.y);
  339.     
  340.     /* u = u - f(u)/f'(u) */
  341.     uPrime = u - (numerator/denominator);
  342.     return (uPrime);
  343. }
  344.  
  345.     
  346.                
  347. /*
  348.  *  Bezier :
  349.  *      Evaluate a Bezier curve at a particular parameter value
  350.  * 
  351.  */
  352. static Point2 Bezier(degree, V, t)
  353.     int        degree;        /* The degree of the bezier curve    */
  354.     Point2     *V;        /* Array of control points        */
  355.     double     t;        /* Parametric value to find point for    */
  356. {
  357.     int     i, j;        
  358.     Point2     Q;            /* Point on curve at parameter t    */
  359.     Point2     *Vtemp;        /* Local copy of control points        */
  360.  
  361.     /* Copy array    */
  362.     Vtemp = (Point2 *)malloc((unsigned)((degree+1) 
  363.                 * sizeof (Point2)));
  364.     for (i = 0; i <= degree; i++) {
  365.         Vtemp[i] = V[i];
  366.     }
  367.  
  368.     /* Triangle computation    */
  369.     for (i = 1; i <= degree; i++) {    
  370.         for (j = 0; j <= degree-i; j++) {
  371.             Vtemp[j].x = (1.0 - t) * Vtemp[j].x + t * Vtemp[j+1].x;
  372.             Vtemp[j].y = (1.0 - t) * Vtemp[j].y + t * Vtemp[j+1].y;
  373.         }
  374.     }
  375.  
  376.     Q = Vtemp[0];
  377.     free((char *)Vtemp);
  378.     return Q;
  379. }
  380.  
  381.  
  382. /*
  383.  *  B0, B1, B2, B3 :
  384.  *    Bezier multipliers
  385.  */
  386. static double B0(u)
  387.     double    u;
  388. {
  389.     double tmp = 1.0 - u;
  390.     return (tmp * tmp * tmp);
  391. }
  392.  
  393.  
  394. static double B1(u)
  395.     double    u;
  396. {
  397.     double tmp = 1.0 - u;
  398.     return (3 * u * (tmp * tmp));
  399. }
  400.  
  401. static double B2(u)
  402.     double    u;
  403. {
  404.     double tmp = 1.0 - u;
  405.     return (3 * u * u * tmp);
  406. }
  407.  
  408. static double B3(u)
  409.     double    u;
  410. {
  411.     return (u * u * u);
  412. }
  413.  
  414.  
  415.  
  416. /*
  417.  * ComputeLeftTangent, ComputeRightTangent, ComputeCenterTangent :
  418.  *Approximate unit tangents at endpoints and "center" of digitized curve
  419.  */
  420. static Vector2 ComputeLeftTangent(d, end)
  421.     Point2    *d;            /*  Digitized points*/
  422.     int        end;        /*  Index to "left" end of region */
  423. {
  424.     Vector2    tHat1;
  425.     tHat1 = V2Sub(d[end+1], d[end]);
  426.     tHat1 = *V2Normalize(&tHat1);
  427.     return tHat1;
  428. }
  429.  
  430. static Vector2 ComputeRightTangent(d, end)
  431.     Point2    *d;            /*  Digitized points        */
  432.     int        end;        /*  Index to "right" end of region */
  433. {
  434.     Vector2    tHat2;
  435.     tHat2 = V2Sub(d[end-1], d[end]);
  436.     tHat2 = *V2Normalize(&tHat2);
  437.     return tHat2;
  438. }
  439.  
  440.  
  441. static Vector2 ComputeCenterTangent(d, center)
  442.     Point2    *d;            /*  Digitized points            */
  443.     int        center;        /*  Index to point inside region    */
  444. {
  445.     Vector2    V1, V2, tHatCenter;
  446.  
  447.     V1 = V2Sub(d[center-1], d[center]);
  448.     V2 = V2Sub(d[center], d[center+1]);
  449.     tHatCenter.x = (V1.x + V2.x)/2.0;
  450.     tHatCenter.y = (V1.y + V2.y)/2.0;
  451.     tHatCenter = *V2Normalize(&tHatCenter);
  452.     return tHatCenter;
  453. }
  454.  
  455.  
  456. /*
  457.  *  ChordLengthParameterize :
  458.  *    Assign parameter values to digitized points 
  459.  *    using relative distances between points.
  460.  */
  461. static double *ChordLengthParameterize(d, first, last)
  462.     Point2    *d;            /* Array of digitized points */
  463.     int        first, last;        /*  Indices defining region    */
  464. {
  465.     int        i;    
  466.     double    *u;            /*  Parameterization        */
  467.  
  468.     u = (double *)malloc((unsigned)(last-first+1) *                     sizeof(double));
  469.  
  470.     u[0] = 0.0;
  471.     for (i = first+1; i <= last; i++) {
  472.         u[i-first] = u[i-first-1] +
  473.                   V2DistanceBetween2Points(&d[i], &d[i-1]);
  474.     }
  475.  
  476.     for (i = first + 1; i <= last; i++) {
  477.         u[i-first] = u[i-first] / u[last-first];
  478.     }
  479.  
  480.     return(u);
  481. }
  482.  
  483.  
  484.  
  485.  
  486. /*
  487.  *  ComputeMaxError :
  488.  *    Find the maximum squared distance of digitized points
  489.  *    to fitted curve.
  490. */
  491. static double ComputeMaxError(d, first, last, bezCurve, u,                         splitPoint)
  492.     Point2    *d;            /*  Array of digitized points    */
  493.     int        first, last;        /*  Indices defining region    */
  494.     BezierCurve    bezCurve;        /*  Fitted Bezier curve        */
  495.     double    *u;            /*  Parameterization of points    */
  496.     int        *splitPoint;        /*  Point of maximum error    */
  497. {
  498.     int        i;
  499.     double    maxDist;        /*  Maximum error        */
  500.     double    dist;        /*  Current error        */
  501.     Point2    P;            /*  Point on curve        */
  502.     Vector2    v;            /*  Vector from point to curve    */
  503.  
  504.     *splitPoint = (last - first + 1)/2;
  505.     maxDist = 0.0;
  506.     for (i = first + 1; i < last; i++) {
  507.         P = Bezier(3, bezCurve, u[i-first]);
  508.         v = V2Sub(P, d[i]);
  509.         dist = V2SquaredLength(&v);
  510.         if (dist >= maxDist) {
  511.             maxDist = dist;
  512.             *splitPoint = i;
  513.         }
  514.     }
  515.     return (maxDist);
  516. }
  517. static Vector2 V2AddII(a, b)
  518.     Vector2 a, b;
  519. {
  520.     Vector2    c;
  521.     c.x = a.x + b.x;  c.y = a.y + b.y;
  522.     return (c);
  523. }
  524. static Vector2 V2ScaleII(v, s)
  525.     Vector2    v;
  526.     double    s;
  527. {
  528.     Vector2 result;
  529.     result.x = v.x * s; result.y = v.y * s;
  530.     return (result);
  531. }
  532.  
  533. static Vector2 V2Sub(a, b)
  534.     Vector2    a, b;
  535. {
  536.     Vector2    c;
  537.     c.x = a.x - b.x; c.y = a.y - b.y;
  538.     return (c);
  539. }
  540.