home *** CD-ROM | disk | FTP | other *** search
/ Club Amiga de Montreal - CAM / CAM_CD_1.iso / files / 505a.lha / GrapicsGems / NearestPoint.c < prev    next >
C/C++ Source or Header  |  1991-05-01  |  12KB  |  473 lines

  1. /*
  2. Solving the Nearest Point-on-Curve Problem 
  3. and
  4. A Bezier Curve-Based Root-Finder
  5. by Philip J. Schneider
  6. from "Graphics Gems", Academic Press, 1990
  7. */
  8.  
  9.  /*    point_on_curve.c    */        
  10.                                     
  11. #include <stdio.h>
  12. #include <malloc.h>
  13. #include <math.h>
  14. #include "GraphicsGems.h"
  15.  
  16. #define TESTMODE
  17.  
  18. /*
  19.  *  Forward declarations
  20.  */
  21. Point2  NearestPointOnCurve();
  22. static    int    FindRoots();
  23. static    Point2    *ConvertToBezierForm();
  24. static    double    ComputeXIntercept();
  25. static    int    ControlPolygonFlatEnough();
  26. static    int    CrossingCount();
  27. static    Point2    Bezier();
  28. static    Vector2    V2ScaleII();
  29.  
  30. int        MAXDEPTH = 64;    /*  Maximum depth for recursion */
  31.  
  32. #define    EPSILON    (ldexp(1.0,-MAXDEPTH-1)) /*Flatness control value */
  33. #define    DEGREE    3            /*  Cubic Bezier curve        */
  34. #define    W_DEGREE 5            /*  Degree of eqn to find roots of */
  35.  
  36. #ifdef TESTMODE
  37. /*
  38.  *  main :
  39.  *    Given a cubic Bezier curve (i.e., its control points), and some
  40.  *    arbitrary point in the plane, find the point on the curve
  41.  *    closest to that arbitrary point.
  42.  */
  43. main()
  44. {
  45.    
  46.  static Point2 bezCurve[4] = {    /*  A cubic Bezier curve    */
  47.     { 0.0, 0.0 },
  48.     { 1.0, 2.0 },
  49.     { 3.0, 3.0 },
  50.     { 4.0, 2.0 },
  51.     };
  52.     static Point2 arbPoint = { 3.5, 2.0 }; /*Some arbitrary point*/
  53.     Point2    pointOnCurve;         /*  Nearest point on the curve */
  54.  
  55.     /*  Find the closest point */
  56.     pointOnCurve = NearestPointOnCurve(arbPoint, bezCurve);
  57.     printf("pointOnCurve : (%4.4f, %4.4f)\n", pointOnCurve.x,
  58.         pointOnCurve.y);
  59. }
  60. #endif /* TESTMODE */
  61.  
  62.  
  63. /*
  64.  *  NearestPointOnCurve :
  65.  *      Compute the parameter value of the point on a Bezier
  66.  *        curve segment closest to some arbtitrary, user-input point.
  67.  *        Return the point on the curve at that parameter value.
  68.  *
  69.  */
  70. Point2 NearestPointOnCurve(P, V)
  71.     Point2     P;            /* The user-supplied point      */
  72.     Point2     *V;            /* Control points of cubic Bezier */
  73. {
  74.     Point2    *w;            /* Ctl pts for 5th-degree eqn    */
  75.     double     t_candidate[W_DEGREE];    /* Possible roots        */     
  76.     int     n_solutions;        /* Number of roots found    */
  77.     double    t;            /* Parameter value of closest pt*/
  78.  
  79.     /*  Convert problem to 5th-degree Bezier form    */
  80.     w = ConvertToBezierForm(P, V);
  81.  
  82.     /* Find all possible roots of 5th-degree equation */
  83.     n_solutions = FindRoots(w, W_DEGREE, t_candidate, 0);
  84.     free((char *)w);
  85.  
  86.     /* Compare distances of P to all candidates, and to t=0, and t=1 */
  87.     {
  88.         double     dist, new_dist;
  89.         Point2     p;
  90.         Vector2  v;
  91.         int        i;
  92.  
  93.     
  94.     /* Check distance to beginning of curve, where t = 0    */
  95.         dist = V2SquaredLength(V2Sub(&P, &V[0], &v));
  96.             t = 0.0;
  97.  
  98.     /* Find distances for candidate points    */
  99.         for (i = 0; i < n_solutions; i++) {
  100.             p = Bezier(V, DEGREE, t_candidate[i], NULL, NULL);
  101.             new_dist = V2SquaredLength(V2Sub(&P, &p, &v));
  102.             if (new_dist < dist) {
  103.                     dist = new_dist;
  104.                     t = t_candidate[i];
  105.             }
  106.         }
  107.  
  108.     /* Finally, look at distance to end point, where t = 1.0 */
  109.         new_dist = V2SquaredLength(V2Sub(&P, &V[DEGREE], &v));
  110.             if (new_dist < dist) {
  111.                 dist = new_dist;
  112.             t = 1.0;
  113.         }
  114.     }
  115.  
  116.     /*  Return the point on the curve at parameter value t */
  117.     printf("t : %4.12f\n", t);
  118.     return (Bezier(V, DEGREE, t, NULL, NULL));
  119. }
  120.  
  121.  
  122. /*
  123.  *  ConvertToBezierForm :
  124.  *        Given a point and a Bezier curve, generate a 5th-degree
  125.  *        Bezier-format equation whose solution finds the point on the
  126.  *      curve nearest the user-defined point.
  127.  */
  128. static Point2 *ConvertToBezierForm(P, V)
  129.     Point2     P;            /* The point to find t for    */
  130.     Point2     *V;            /* The control points        */
  131. {
  132.     int     i, j, k, m, n, ub, lb;    
  133.     double     t;            /* Value of t for point P    */
  134.     int     row, column;        /* Table indices        */
  135.     Vector2     c[DEGREE+1];        /* V(i)'s - P            */
  136.     Vector2     d[DEGREE];        /* V(i+1) - V(i)        */
  137.     Point2     *w;            /* Ctl pts of 5th-degree curve  */
  138.     double     cdTable[3][4];        /* Dot product of c, d        */
  139.     static double z[3][4] = {    /* Precomputed "z" for cubics    */
  140.     {1.0, 0.6, 0.3, 0.1},
  141.     {0.4, 0.6, 0.6, 0.4},
  142.     {0.1, 0.3, 0.6, 1.0},
  143.     };
  144.  
  145.  
  146.     /*Determine the c's -- these are vectors created by subtracting*/
  147.     /* point P from each of the control points                */
  148.     for (i = 0; i <= DEGREE; i++) {
  149.         V2Sub(&V[i], &P, &c[i]);
  150.     }
  151.     /* Determine the d's -- these are vectors created by subtracting*/
  152.     /* each control point from the next                    */
  153.     for (i = 0; i <= DEGREE - 1; i++) { 
  154.         d[i] = V2ScaleII(V2Sub(&V[i+1], &V[i], &d[i]), 3.0);
  155.     }
  156.  
  157.     /* Create the c,d table -- this is a table of dot products of the */
  158.     /* c's and d's                            */
  159.     for (row = 0; row <= DEGREE - 1; row++) {
  160.         for (column = 0; column <= DEGREE; column++) {
  161.             cdTable[row][column] = V2Dot(&d[row], &c[column]);
  162.         }
  163.     }
  164.  
  165.     /* Now, apply the z's to the dot products, on the skew diagonal*/
  166.     /* Also, set up the x-values, making these "points"        */
  167.     w = (Point2 *)malloc((unsigned)(W_DEGREE+1) * sizeof(Point2));
  168.     for (i = 0; i <= W_DEGREE; i++) {
  169.         w[i].y = 0.0;
  170.         w[i].x = (double)(i) / W_DEGREE;
  171.     }
  172.  
  173.     n = DEGREE;
  174.     m = DEGREE-1;
  175.     for (k = 0; k <= n + m; k++) {
  176.         lb = MAX(0, k - m);
  177.         ub = MIN(k, n);
  178.         for (i = lb; i <= ub; i++) {
  179.             j = k - i;
  180.             w[i+j].y += cdTable[j][i] * z[j][i];
  181.         }
  182.     }
  183.  
  184.     return (w);
  185. }
  186.  
  187.  
  188. /*
  189.  *  FindRoots :
  190.  *    Given a 5th-degree equation in Bernstein-Bezier form, find
  191.  *    all of the roots in the interval [0, 1].  Return the number
  192.  *    of roots found.
  193.  */
  194. static int FindRoots(w, degree, t, depth)
  195.     Point2     *w;            /* The control points        */
  196.     int     degree;        /* The degree of the polynomial    */
  197.     double     *t;            /* RETURN candidate t-values    */
  198.     int     depth;        /* The depth of the recursion    */
  199. {  
  200.     int     i;
  201.     Point2     Left[W_DEGREE+1],    /* New left and right         */
  202.               Right[W_DEGREE+1];    /* control polygons        */
  203.     int     left_count,        /* Solution count from        */
  204.         right_count;        /* children            */
  205.     double     left_t[W_DEGREE+1],    /* Solutions from kids        */
  206.                right_t[W_DEGREE+1];
  207.  
  208.     switch (CrossingCount(w, degree)) {
  209.            case 0 : {    /* No solutions here    */
  210.          return 0;    
  211.          break;
  212.     }
  213.     case 1 : {    /* Unique solution    */
  214.         /* Stop recursion when the tree is deep enough    */
  215.         /* if deep enough, return 1 solution at midpoint     */
  216.         if (depth >= MAXDEPTH) {
  217.             t[0] = (w[0].x + w[W_DEGREE].x) / 2.0;
  218.             return 1;
  219.         }
  220.         if (ControlPolygonFlatEnough(w, degree)) {
  221.             t[0] = ComputeXIntercept(w, degree);
  222.             return 1;
  223.         }
  224.         break;
  225.     }
  226. }
  227.  
  228.     /* Otherwise, solve recursively after    */
  229.     /* subdividing control polygon        */
  230.     Bezier(w, degree, 0.5, Left, Right);
  231.     left_count  = FindRoots(Left,  degree, left_t, depth+1);
  232.     right_count = FindRoots(Right, degree, right_t, depth+1);
  233.  
  234.  
  235.     /* Gather solutions together    */
  236.     for (i = 0; i < left_count; i++) {
  237.         t[i] = left_t[i];
  238.     }
  239.     for (i = 0; i < right_count; i++) {
  240.          t[i+left_count] = right_t[i];
  241.     }
  242.  
  243.     /* Send back total number of solutions    */
  244.     return (left_count+right_count);
  245. }
  246.  
  247.  
  248. /*
  249.  * CrossingCount :
  250.  *    Count the number of times a Bezier control polygon 
  251.  *    crosses the 0-axis. This number is >= the number of roots.
  252.  *
  253.  */
  254. static int CrossingCount(V, degree)
  255.     Point2    *V;            /*  Control pts of Bezier curve    */
  256.     int        degree;            /*  Degreee of Bezier curve     */
  257. {
  258.     int     i;    
  259.     int     n_crossings = 0;    /*  Number of zero-crossings    */
  260.     int        sign, old_sign;        /*  Sign of coefficients    */
  261.  
  262.     sign = old_sign = SGN(V[0].y);
  263.     for (i = 1; i <= degree; i++) {
  264.         sign = SGN(V[i].y);
  265.         if (sign != old_sign) n_crossings++;
  266.         old_sign = sign;
  267.     }
  268.     return n_crossings;
  269. }
  270.  
  271.  
  272.  
  273. /*
  274.  *  ControlPolygonFlatEnough :
  275.  *    Check if the control polygon of a Bezier curve is flat enough
  276.  *    for recursive subdivision to bottom out.
  277.  *
  278.  */
  279. static int ControlPolygonFlatEnough(V, degree)
  280.     Point2    *V;        /* Control points    */
  281.     int     degree;        /* Degree of polynomial    */
  282. {
  283.     int     i;            /* Index variable        */
  284.     double     *distance;        /* Distances from pts to line    */
  285.     double     max_distance_above;    /* maximum of these        */
  286.     double     max_distance_below;
  287.     double     error;            /* Precision of root        */
  288.     Vector2     t;            /* Vector from V[0] to V[degree]*/
  289.     double     intercept_1,
  290.                intercept_2,
  291.                left_intercept,
  292.                right_intercept;
  293.     double     a, b, c;        /* Coefficients of implicit    */
  294.                         /* eqn for line from V[0]-V[deg]*/
  295.  
  296.     /* Find the  perpendicular distance        */
  297.     /* from each interior control point to     */
  298.     /* line connecting V[0] and V[degree]    */
  299.     distance = (double *)malloc((unsigned)(degree + 1) *                     sizeof(double));
  300.     {
  301.     double    abSquared;
  302.  
  303.     /* Derive the implicit equation for line connecting first *'
  304.     /*  and last control points */
  305.     a = V[0].y - V[degree].y;
  306.     b = V[degree].x - V[0].x;
  307.     c = V[0].x * V[degree].y - V[degree].x * V[0].y;
  308.  
  309.     abSquared = (a * a) + (b * b);
  310.  
  311.         for (i = 1; i < degree; i++) {
  312.         /* Compute distance from each of the points to that line    */
  313.             distance[i] = a * V[i].x + b * V[i].y + c;
  314.             if (distance[i] > 0.0) {
  315.                 distance[i] = (distance[i] * distance[i]) / abSquared;
  316.             }
  317.             if (distance[i] < 0.0) {
  318.                 distance[i] = -((distance[i] * distance[i]) /                         abSquared);
  319.             }
  320.         }
  321.     }
  322.  
  323.  
  324.     /* Find the largest distance    */
  325.     max_distance_above = 0.0;
  326.     max_distance_below = 0.0;
  327.     for (i = 1; i < degree; i++) {
  328.         if (distance[i] < 0.0) {
  329.             max_distance_below = MIN(max_distance_below, distance[i]);
  330.         };
  331.         if (distance[i] > 0.0) {
  332.             max_distance_above = MAX(max_distance_above, distance[i]);
  333.         }
  334.     }
  335.     free((char *)distance);
  336.  
  337.     {
  338.     double    det, dInv;
  339.     double    a1, b1, c1, a2, b2, c2;
  340.  
  341.     /*  Implicit equation for zero line */
  342.     a1 = 0.0;
  343.     b1 = 1.0;
  344.     c1 = 0.0;
  345.  
  346.     /*  Implicit equation for "above" line */
  347.     a2 = a;
  348.     b2 = b;
  349.     c2 = c + max_distance_above;
  350.  
  351.     det = a1 * b2 - a2 * b1;
  352.     dInv = 1.0/det;
  353.     
  354.     intercept_1 = (b1 * c2 - b2 * c1) * dInv;
  355.  
  356.     /*  Implicit equation for "below" line */
  357.     a2 = a;
  358.     b2 = b;
  359.     c2 = c + max_distance_below;
  360.     
  361.     det = a1 * b2 - a2 * b1;
  362.     dInv = 1.0/det;
  363.     
  364.     intercept_2 = (b1 * c2 - b2 * c1) * dInv;
  365.     }
  366.  
  367.     /* Compute intercepts of bounding box    */
  368.     left_intercept = MIN(intercept_1, intercept_2);
  369.     right_intercept = MAX(intercept_1, intercept_2);
  370.  
  371.     error = 0.5 * (right_intercept-left_intercept);    
  372.     if (error < EPSILON) {
  373.         return 1;
  374.     }
  375.     else {
  376.         return 0;
  377.     }
  378. }
  379.  
  380.  
  381.  
  382. /*
  383.  *  ComputeXIntercept :
  384.  *    Compute intersection of chord from first control point to last
  385.  *      with 0-axis.
  386.  * 
  387.  */
  388. static double ComputeXIntercept(V, degree)
  389.     Point2     *V;            /*  Control points    */
  390.     int        degree;         /*  Degree of curve    */
  391. {
  392.     double    XLK, YLK, XNM, YNM, XMK, YMK;
  393.     double    det, detInv;
  394.     double    S, T;
  395.     double    X, Y;
  396.  
  397.     XLK = 1.0 - 0.0;
  398.     YLK = 0.0 - 0.0;
  399.     XNM = V[degree].x - V[0].x;
  400.     YNM = V[degree].y - V[0].y;
  401.     XMK = V[0].x - 0.0;
  402.     YMK = V[0].y - 0.0;
  403.  
  404.     det = XNM*YLK - YNM*XLK;
  405.     detInv = 1.0/det;
  406.  
  407.     S = (XNM*YMK - YNM*XMK) * detInv;
  408.     T = (XLK*YMK - YLK*XMK) * detInv;
  409.     
  410.     X = 0.0 + XLK * S;
  411.     Y = 0.0 + YLK * S;
  412.  
  413.     return X;
  414. }
  415.  
  416.  
  417. /*
  418.  *  Bezier : 
  419.  *    Evaluate a Bezier curve at a particular parameter value
  420.  *      Fill in control points for resulting sub-curves if "Left" and
  421.  *    "Right" are non-null.
  422.  * 
  423.  */
  424. static Point2 Bezier(V, degree, t, Left, Right)
  425.     int     degree;        /* Degree of bezier curve    */
  426.     Point2     *V;            /* Control pts            */
  427.     double     t;            /* Parameter value        */
  428.     Point2     *Left;        /* RETURN left half ctl pts    */
  429.     Point2     *Right;        /* RETURN right half ctl pts    */
  430. {
  431.     int     i, j;        /* Index variables    */
  432.     Point2     Vtemp[W_DEGREE+1][W_DEGREE+1];
  433.  
  434.  
  435.     /* Copy control points    */
  436.     for (j =0; j <= degree; j++) {
  437.         Vtemp[0][j] = V[j];
  438.     }
  439.  
  440.     /* Triangle computation    */
  441.     for (i = 1; i <= degree; i++) {    
  442.         for (j =0 ; j <= degree - i; j++) {
  443.             Vtemp[i][j].x =
  444.                   (1.0 - t) * Vtemp[i-1][j].x + t * Vtemp[i-1][j+1].x;
  445.             Vtemp[i][j].y =
  446.                   (1.0 - t) * Vtemp[i-1][j].y + t * Vtemp[i-1][j+1].y;
  447.         }
  448.     }
  449.     
  450.     if (Left != NULL) {
  451.         for (j = 0; j <= degree; j++) {
  452.             Left[j]  = Vtemp[j][0];
  453.         }
  454.     }
  455.     if (Right != NULL) {
  456.         for (j = 0; j <= degree; j++) {
  457.             Right[j] = Vtemp[degree-j][j];
  458.         }
  459.     }
  460.  
  461.     return (Vtemp[degree][0]);
  462. }
  463.  
  464. static Vector2 V2ScaleII(v, s)
  465.     Vector2    *v;
  466.     double    s;
  467. {
  468.     Vector2 result;
  469.  
  470.     result.x = v->x * s; result.y = v->y * s;
  471.     return (result);
  472. }
  473.