home *** CD-ROM | disk | FTP | other *** search
/ PC Pro 2002 April / pcpro0402.iso / essentials / graphics / Gimp / gimp-src-20001226.exe / src / gimp / plug-ins / sel2path / fit.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-22  |  70.9 KB  |  1,952 lines

  1. /* fit.c: turn a bitmap representation of a curve into a list of splines.
  2.    Some of the ideas, but not the code, comes from the Phoenix thesis. 
  3.    See README for the reference.
  4.  
  5. Copyright (C) 1992 Free Software Foundation, Inc.
  6.  
  7. This program is free software; you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation; either version 2, or (at your option)
  10. any later version.
  11.  
  12. This program is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. GNU General Public License for more details.
  16.  
  17. You should have received a copy of the GNU General Public License
  18. along with this program; if not, write to the Free Software
  19. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  20.  
  21. #include <float.h>
  22. #include <math.h>
  23. #include <assert.h>
  24.  
  25. #include <glib.h>
  26.  
  27. #include "global.h"
  28. #include "spline.h"
  29. #include "vector.h"
  30.  
  31. #include "curve.h"
  32. #include "fit.h"
  33. #include "pxl-outline.h"
  34.  
  35. /* If two endpoints are closer than this, they are made to be equal.
  36.    (-align-threshold)  */ 
  37. real align_threshold = 0.5;
  38.  
  39. /* If the angle defined by a point and its predecessors and successors
  40.    is smaller than this, it's a corner, even if it's within
  41.    `corner_surround' pixels of a point with a smaller angle. 
  42.    (-corner-always-threshold)  */
  43. real corner_always_threshold = 60.0;
  44.  
  45. /* Number of points to consider when determining if a point is a corner
  46.    or not.  (-corner-surround)  */
  47. unsigned corner_surround = 4;
  48.  
  49. /* If a point, its predecessors, and its successors define an angle 
  50.     smaller than this, it's a corner.  Should be in range 0..180.
  51.    (-corner-threshold)  */
  52. real corner_threshold = 100.0;
  53.  
  54. /* Amount of error at which a fitted spline is unacceptable.  If any
  55.    pixel is further away than this from the fitted curve, we try again.
  56.    (-error-threshold) */
  57. /* real error_threshold = .8; ALT */
  58. real error_threshold = .4;
  59.  
  60. /* A second number of adjacent points to consider when filtering.
  61.    (-filter-alternative-surround)  */
  62. unsigned filter_alternative_surround = 1;
  63.  
  64. /* If the angles between the vectors produced by filter_surround and
  65.    filter_alternative_surround points differ by more than this, use
  66.    the one from filter_alternative_surround.  (-filter-epsilon)  */
  67. real filter_epsilon = 10.0;
  68.  
  69. /* Number of times to smooth original data points.  Increasing this
  70.    number dramatically---to 50 or so---can produce vastly better
  71.    results.  But if any points that ``should'' be corners aren't found,
  72.    the curve goes to hell around that point.  (-filter-iterations)  */
  73. /* unsigned filter_iteration_count = 4; ALT */
  74. unsigned filter_iteration_count = 4;
  75.  
  76. /* To produce the new point, use the old point plus this times the
  77.    neighbors.  (-filter-percent)  */
  78. real filter_percent = .33;
  79.  
  80. /* Number of adjacent points to consider if `filter_surround' points
  81.    defines a straight line.  (-filter-secondary-surround)  */
  82. unsigned filter_secondary_surround = 3;
  83.  
  84. /* Number of adjacent points to consider when filtering.
  85.   (-filter-surround)  */
  86. unsigned filter_surround = 2;
  87.  
  88. /* Says whether or not to remove ``knee'' points after finding the outline. 
  89.    (See the comments at `remove_knee_points'.)  (-remove-knees).  */
  90. boolean keep_knees = false;
  91.  
  92. /* If a spline is closer to a straight line than this, it remains a
  93.    straight line, even if it would otherwise be changed back to a curve.
  94.    This is weighted by the square of the curve length, to make shorter
  95.    curves more likely to be reverted.  (-line-reversion-threshold)  */
  96. real line_reversion_threshold = .01;
  97.  
  98. /* How many pixels (on the average) a spline can diverge from the line
  99.    determined by its endpoints before it is changed to a straight line.
  100.    (-line-threshold) */
  101. /* real line_threshold = 1.0; ALT */
  102. real line_threshold = 0.5;
  103.  
  104. /* If reparameterization doesn't improve the fit by this much percent,
  105.    stop doing it.  (-reparameterize-improve)  */
  106. /* real reparameterize_improvement = .10; ALT */
  107. real reparameterize_improvement = .01;
  108.  
  109. /* Amount of error at which it is pointless to reparameterize.  This
  110.    happens, for example, when we are trying to fit the outline of the
  111.    outside of an `O' with a single spline.  The initial fit is not good
  112.    enough for the Newton-Raphson iteration to improve it.  It may be
  113.    that it would be better to detect the cases where we didn't find any
  114.    corners.  (-reparameterize-threshold)  */
  115. /* real reparameterize_threshold = 30.0; ALT */
  116. real reparameterize_threshold = 1.0;
  117.  
  118. /* Percentage of the curve away from the worst point to look for a
  119.    better place to subdivide.  (-subdivide-search)  */
  120. real subdivide_search = .1;
  121.  
  122. /* Number of points to consider when deciding whether a given point is a
  123.    better place to subdivide.  (-subdivide-surround)  */
  124. unsigned subdivide_surround = 4;
  125.  
  126. /* How many pixels a point can diverge from a straight line and still be
  127.    considered a better place to subdivide.  (-subdivide-threshold) */
  128. real subdivide_threshold = .03;
  129.  
  130. /* Number of points to look at on either side of a point when computing
  131.    the approximation to the tangent at that point.  (-tangent-surround)  */
  132. unsigned tangent_surround = 3;
  133.  
  134.  
  135. /* We need to manipulate lists of array indices.  */
  136.  
  137. typedef struct index_list
  138. {
  139.   unsigned *data;
  140.   unsigned length;
  141. } index_list_type;
  142.  
  143. /* The usual accessor macros.  */
  144. #define GET_INDEX(i_l, n)  ((i_l).data[n])
  145. #define INDEX_LIST_LENGTH(i_l)  ((i_l).length)
  146. #define GET_LAST_INDEX(i_l)  ((i_l).data[INDEX_LIST_LENGTH (i_l) - 1])
  147.  
  148. static void append_index (index_list_type *, unsigned);
  149. static void free_index_list (index_list_type *);
  150. static index_list_type new_index_list ();
  151. static void remove_adjacent_corners (index_list_type *, unsigned);
  152.  
  153. static void align (spline_list_type *);
  154. static void change_bad_lines (spline_list_type *);
  155. static void filter (curve_type);
  156. static real filter_angle (vector_type, vector_type);
  157. static void find_curve_vectors
  158.   (unsigned, curve_type, unsigned, vector_type *, vector_type *, unsigned *);
  159. static unsigned find_subdivision (curve_type, unsigned initial);
  160. static void find_vectors
  161.   (unsigned, pixel_outline_type, vector_type *, vector_type *);
  162. static index_list_type find_corners (pixel_outline_type);
  163. static real find_error (curve_type, spline_type, unsigned *);
  164. static vector_type find_half_tangent (curve_type, boolean start, unsigned *);
  165. static void find_tangent (curve_type, boolean, boolean);
  166. static spline_type fit_one_spline (curve_type);
  167. static spline_list_type *fit_curve (curve_type);
  168. static spline_list_type fit_curve_list (curve_list_type);
  169. static spline_list_type *fit_with_least_squares (curve_type);
  170. static spline_list_type *fit_with_line (curve_type);
  171. static void remove_knee_points (curve_type, boolean);
  172. static boolean reparameterize (curve_type, spline_type);
  173. static void set_initial_parameter_values (curve_type);
  174. static boolean spline_linear_enough (spline_type *, curve_type);
  175. static curve_list_array_type split_at_corners (pixel_outline_list_type);
  176. static boolean test_subdivision_point (curve_type, unsigned, vector_type *);
  177.  
  178. /* The top-level call that transforms the list of pixels in the outlines
  179.    of the original character to a list of spline lists fitted to those
  180.    pixels.  */
  181.  
  182. spline_list_array_type
  183. fitted_splines (pixel_outline_list_type pixel_outline_list)
  184. {
  185.   unsigned this_list;
  186.   unsigned total = 0;
  187.   spline_list_array_type char_splines = new_spline_list_array ();
  188.   curve_list_array_type curve_array = split_at_corners (pixel_outline_list);
  189.  
  190.   for (this_list = 0; this_list < CURVE_LIST_ARRAY_LENGTH (curve_array);
  191.        this_list++)
  192.     {
  193.       spline_list_type curve_list_splines;
  194.       curve_list_type curves = CURVE_LIST_ARRAY_ELT (curve_array, this_list);
  195.  
  196.       curve_list_splines = fit_curve_list (curves);
  197.       append_spline_list (&char_splines, curve_list_splines);
  198.  
  199. /*       REPORT ("* "); */
  200.     }
  201.  
  202.   free_curve_list_array (&curve_array);
  203.  
  204.   for (this_list = 0; this_list < SPLINE_LIST_ARRAY_LENGTH (char_splines);
  205.        this_list++)
  206.     total
  207.       += SPLINE_LIST_LENGTH (SPLINE_LIST_ARRAY_ELT (char_splines, this_list)); 
  208.  
  209. /*   REPORT1 ("=%u", total); */
  210.  
  211.   return char_splines;
  212. }
  213.  
  214. /* Set up the internal parameters from the external ones */
  215.  
  216. void
  217. fit_set_params(SELVALS *selVals)
  218. {
  219.   align_threshold = selVals->align_threshold;
  220.   corner_always_threshold = selVals->corner_always_threshold;
  221.   corner_surround = selVals->corner_surround;
  222.   corner_threshold = selVals->corner_threshold;
  223.   error_threshold = selVals->error_threshold;
  224.   filter_alternative_surround = selVals->filter_alternative_surround;
  225.   filter_epsilon = selVals->filter_epsilon;
  226.   filter_iteration_count = selVals->filter_iteration_count;
  227.   filter_percent = selVals->filter_percent;
  228.   filter_secondary_surround = selVals->filter_secondary_surround;
  229.   filter_surround = selVals->filter_surround;
  230.   keep_knees = selVals->keep_knees;
  231.   line_reversion_threshold = selVals->line_reversion_threshold;
  232.   line_threshold = selVals->line_threshold;
  233.   reparameterize_improvement = selVals->reparameterize_improvement;
  234.   reparameterize_threshold = selVals->reparameterize_threshold;
  235.   subdivide_search = selVals->subdivide_search;
  236.   subdivide_surround = selVals->subdivide_surround;
  237.   subdivide_threshold = selVals->subdivide_threshold;
  238.   tangent_surround = selVals->tangent_surround;
  239. }
  240.  
  241. void
  242. fit_set_default_params(SELVALS *selVals)
  243. {
  244.   selVals->align_threshold = align_threshold;
  245.   selVals->corner_always_threshold = corner_always_threshold;
  246.   selVals->corner_surround = corner_surround;
  247.   selVals->corner_threshold = corner_threshold;
  248.   selVals->error_threshold = error_threshold;
  249.   selVals->filter_alternative_surround = filter_alternative_surround;
  250.   selVals->filter_epsilon = filter_epsilon;
  251.   selVals->filter_iteration_count = filter_iteration_count;
  252.   selVals->filter_percent = filter_percent;
  253.   selVals->filter_secondary_surround = filter_secondary_surround;
  254.   selVals->filter_surround = filter_surround;
  255.   selVals->keep_knees = keep_knees;
  256.   selVals->line_reversion_threshold = line_reversion_threshold;
  257.   selVals->line_threshold = line_threshold; 
  258.   selVals->reparameterize_improvement = reparameterize_improvement;
  259.   selVals->reparameterize_threshold = reparameterize_threshold;
  260.   selVals->subdivide_search = subdivide_search;
  261.   selVals->subdivide_surround = subdivide_surround;
  262.   selVals->subdivide_threshold = subdivide_threshold;
  263.   selVals->tangent_surround = tangent_surround;
  264. }
  265.  
  266. /* Fit the list of curves CURVE_LIST to a list of splines, and return
  267.    it.  CURVE_LIST represents a single closed paths, e.g., either the
  268.    inside or outside outline of an `o'.  */
  269.  
  270. static spline_list_type
  271. fit_curve_list (curve_list_type curve_list)
  272. {
  273.   curve_type curve;
  274.   unsigned this_curve, this_spline;
  275.   unsigned curve_list_length = CURVE_LIST_LENGTH (curve_list);
  276.   spline_list_type curve_list_splines = *new_spline_list ();
  277.  
  278.   /* Remove the extraneous ``knee'' points before filtering.  Since the
  279.      corners have already been found, we don't need to worry about
  280.      removing a point that should be a corner.  */
  281.   if (!keep_knees)
  282.     {
  283. /*       LOG ("\nRemoving knees:\n"); */
  284.       for (this_curve = 0; this_curve < curve_list_length; this_curve++)
  285.         {
  286. /*           LOG1 ("#%u:", this_curve); */
  287.           remove_knee_points (CURVE_LIST_ELT (curve_list, this_curve),
  288.                               CURVE_LIST_CLOCKWISE (curve_list));
  289.         }
  290.     }
  291.  
  292.   /* We filter all the curves in CURVE_LIST at once; otherwise, we would
  293.      look at an unfiltered curve when computing tangents.  */
  294. /*   LOG ("\nFiltering curves:\n"); */
  295.   for (this_curve = 0; this_curve < curve_list.length; this_curve++)
  296.     {
  297. /*       LOG1 ("#%u: ", this_curve); */
  298.       filter (CURVE_LIST_ELT (curve_list, this_curve));
  299. /*       REPORT ("f"); */
  300.     }
  301.  
  302.   /* Make the first point in the first curve also be the last point in
  303.      the last curve, so the fit to the whole curve list will begin and
  304.      end at the same point.  This may cause slight errors in computing
  305.      the tangents and t values, but it's worth it for the continuity.
  306.      Of course we don't want to do this if the two points are already
  307.      the same, as they are if the curve is cyclic.  (We don't append it
  308.      earlier, in `split_at_corners', because that confuses the
  309.      filtering.)  Finally, we can't append the point if the curve is
  310.      exactly three points long, because we aren't adding any more data,
  311.      and three points isn't enough to determine a spline.  Therefore,
  312.      the fitting will fail.  */
  313.   curve = CURVE_LIST_ELT (curve_list, 0);
  314.   if (CURVE_CYCLIC (curve) && CURVE_LENGTH (curve) != 3)
  315.     append_point (curve, CURVE_POINT (curve, 0));
  316.  
  317.   /* Finally, fit each curve in the list to a list of splines.  */
  318.   for (this_curve = 0; this_curve < curve_list_length; this_curve++)
  319.     {
  320.       spline_list_type *curve_splines;
  321.       curve_type current_curve = CURVE_LIST_ELT (curve_list, this_curve);
  322.  
  323. /*       REPORT1 (" %u", this_curve); */
  324. /*       LOG1 ("\nFitting curve #%u:\n", this_curve); */
  325.  
  326.       curve_splines = fit_curve (current_curve);
  327.       if (curve_splines == NULL)
  328.         printf("Could not fit curve #%u", this_curve);
  329.       else
  330.         {
  331. /*           LOG1 ("Fitted splines for curve #%u:\n", this_curve); */
  332.           for (this_spline = 0;
  333.                this_spline < SPLINE_LIST_LENGTH (*curve_splines); 
  334.                this_spline++)
  335.             {
  336. /*               LOG1 ("  %u: ", this_spline); */
  337. /*               if (logging) */
  338. /*                 print_spline (log_
  339. file, */
  340. /*                               SPLINE_LIST_ELT (*curve_splines, this_spline)); */
  341.             }
  342.  
  343.           /* After fitting, we may need to change some would-be lines
  344.              back to curves, because they are in a list with other
  345.              curves.  */
  346.           change_bad_lines (curve_splines);
  347.  
  348.           concat_spline_lists (&curve_list_splines, *curve_splines);
  349. /*           REPORT1 ("(%u)", SPLINE_LIST_LENGTH (*curve_splines)); */
  350.         }
  351.     }
  352.  
  353.  
  354.   /* We do this for each outline's spline list because when a point
  355.      is changed, it needs to be changed in both segments in which it
  356.      appears---and the segments might be in different curves.  */
  357.   align (&curve_list_splines);
  358.  
  359.   return curve_list_splines;
  360. }
  361.  
  362.  
  363. /* Transform a set of locations to a list of splines (the fewer the
  364.    better).  We are guaranteed that CURVE does not contain any corners.
  365.    We return NULL if we cannot fit the points at all.  */
  366.  
  367. static spline_list_type *
  368. fit_curve (curve_type curve)
  369. {
  370.   spline_list_type *fitted_splines;
  371.  
  372.   if (CURVE_LENGTH (curve) < 2)
  373.     {
  374.       printf ("Tried to fit curve with less than two points");
  375.       return NULL;
  376.     }
  377.  
  378.   /* Do we have enough points to fit with a spline?  */
  379.   fitted_splines = CURVE_LENGTH (curve) < 4
  380.                    ? fit_with_line (curve) 
  381.                    : fit_with_least_squares (curve);
  382.  
  383.   return fitted_splines;
  384. }
  385.  
  386. /* As mentioned above, the first step is to find the corners in
  387.    PIXEL_LIST, the list of points.  (Presumably we can't fit a single
  388.    spline around a corner.)  The general strategy is to look through all
  389.    the points, remembering which we want to consider corners.  Then go
  390.    through that list, producing the curve_list.  This is dictated by the
  391.    fact that PIXEL_LIST does not necessarily start on a corner---it just
  392.    starts at the character's first outline pixel, going left-to-right,
  393.    top-to-bottom.  But we want all our splines to start and end on real
  394.    corners.
  395.  
  396.    For example, consider the top of a capital `C' (this is in cmss20):
  397.                      x
  398.                      ***********
  399.                   ******************
  400.  
  401.    PIXEL_LIST will start at the pixel below the `x'.  If we considered
  402.    this pixel a corner, we would wind up matching a very small segment
  403.    from there to the end of the line, probably as a straight line, which
  404.    is certainly not what we want.  
  405.  
  406.    PIXEL_LIST has one element for each closed outline on the character.
  407.    To preserve this information, we return an array of curve_lists, one
  408.    element (which in turn consists of several curves, one between each
  409.    pair of corners) for each element in PIXEL_LIST.  */
  410.  
  411. static curve_list_array_type
  412. split_at_corners (pixel_outline_list_type pixel_list)
  413. {
  414.   unsigned this_pixel_o;
  415.   curve_list_array_type curve_array = new_curve_list_array ();
  416.  
  417. /*   LOG ("\nFinding corners:\n"); */
  418.  
  419.   for (this_pixel_o = 0; this_pixel_o < O_LIST_LENGTH (pixel_list);
  420.        this_pixel_o++)
  421.     {
  422.       curve_type curve, first_curve;
  423.       index_list_type corner_list;
  424.       unsigned p, this_corner;
  425.       curve_list_type curve_list = new_curve_list ();
  426.       pixel_outline_type pixel_o = O_LIST_OUTLINE (pixel_list, this_pixel_o);
  427.  
  428.       CURVE_LIST_CLOCKWISE (curve_list) = O_CLOCKWISE (pixel_o);
  429.       
  430. /*       LOG1 ("#%u:", this_pixel_o); */
  431.  
  432.       /* If the outline does not have enough points, we can't do
  433.          anything.  The endpoints of the outlines are automatically
  434.          corners.  We need at least `corner_surround' more pixels on
  435.          either side of a point before it is conceivable that we might
  436.          want another corner.  */
  437.       if (O_LENGTH (pixel_o) > corner_surround * 2 + 2)
  438.         corner_list = find_corners (pixel_o);
  439.       else
  440.         corner_list.length = 0;
  441.  
  442.       /* Remember the first curve so we can make it be the `next' of the
  443.          last one.  (And vice versa.)  */
  444.       first_curve = new_curve ();
  445.  
  446.       curve = first_curve;
  447.  
  448.       if (corner_list.length == 0)
  449.         { /* No corners.  Use all of the pixel outline as the curve.  */
  450.           for (p = 0; p < O_LENGTH (pixel_o); p++)
  451.             append_pixel (curve, O_COORDINATE (pixel_o, p));
  452.  
  453.           /* This curve is cyclic.  */
  454.           CURVE_CYCLIC (curve) = true;
  455.         }
  456.       else
  457.         { /* Each curve consists of the points between (inclusive) each pair
  458.              of corners.  */
  459.           for (this_corner = 0; this_corner < corner_list.length - 1;
  460.                this_corner++)
  461.             {
  462.               curve_type previous_curve = curve;
  463.               unsigned corner = GET_INDEX (corner_list, this_corner);
  464.               unsigned next_corner = GET_INDEX (corner_list, this_corner + 1);
  465.  
  466.               for (p = corner; p <= next_corner; p++)
  467.                 append_pixel (curve, O_COORDINATE (pixel_o, p));
  468.  
  469.               append_curve (&curve_list, curve);
  470.               curve = new_curve ();
  471.               NEXT_CURVE (previous_curve) = curve;
  472.               PREVIOUS_CURVE (curve) = previous_curve;
  473.             }
  474.  
  475.           /* The last curve is different.  It consists of the points
  476.              (inclusive) between the last corner and the end of the list,
  477.              and the beginning of the list and the first corner.  */
  478.           for (p = GET_LAST_INDEX (corner_list); p < O_LENGTH (pixel_o);
  479.                p++)
  480.             append_pixel (curve, O_COORDINATE (pixel_o, p));
  481.  
  482.           for (p = 0; p <= GET_INDEX (corner_list, 0); p++)
  483.             append_pixel (curve, O_COORDINATE (pixel_o, p));
  484.         }
  485.  
  486. /*       LOG1 (" [%u].\n", corner_list.length); */
  487.  
  488.       /* Add `curve' to the end of the list, updating the pointers in
  489.          the chain.  */
  490.       append_curve (&curve_list, curve);
  491.       NEXT_CURVE (curve) = first_curve;
  492.       PREVIOUS_CURVE (first_curve) = curve;
  493.  
  494.       /* And now add the just-completed curve list to the array.  */
  495.       append_curve_list (&curve_array, curve_list);
  496.     }                /* End of considering each pixel outline.  */
  497.  
  498.   return curve_array;
  499. }
  500.  
  501.  
  502. /* We consider a point to be a corner if (1) the angle defined by the
  503.    `corner_surround' points coming into it and going out from it is less
  504.    than `corner_threshold' degrees, and no point within
  505.    `corner_surround' points has a smaller angle; or (2) the angle is less
  506.    than `corner_always_threshold' degrees.
  507.  
  508.    Because of the different cases, it is convenient to have the
  509.    following macro to append a corner on to the list we return.  The
  510.    character argument C is simply so that the different cases can be
  511.    distinguished in the log file.  */
  512.  
  513. #define APPEND_CORNER(index, angle, c)                    \
  514.   do                                    \
  515.     {                                    \
  516.       append_index (&corner_list, index);                \
  517.       /*LOG4 (" (%d,%d)%c%.3f",    */                    \
  518.       /*      O_COORDINATE (pixel_outline, index).x,*/            \
  519.       /*      O_COORDINATE (pixel_outline, index).y,*/            \
  520.       /*      c, angle);*/                            \
  521.     }                                    \
  522.   while (0)
  523.  
  524. static index_list_type
  525. find_corners (pixel_outline_type pixel_outline)
  526. {
  527.   unsigned p;
  528.   index_list_type corner_list = new_index_list ();
  529.  
  530.   /* Consider each pixel on the outline in turn.  */
  531.   for (p = 0; p < O_LENGTH (pixel_outline); p++)
  532.     {
  533.       real corner_angle;
  534.       vector_type in_vector, out_vector;
  535.  
  536.       /* Check if the angle is small enough.  */
  537.       find_vectors (p, pixel_outline, &in_vector, &out_vector);
  538.       corner_angle = Vangle (in_vector, out_vector);
  539.  
  540.       if (fabs (corner_angle) <= corner_threshold)
  541.         {
  542.           /* We want to keep looking, instead of just appending the
  543.              first pixel we find with a small enough angle, since there
  544.              might be another corner within `corner_surround' pixels, with
  545.              a smaller angle.  If that is the case, we want that one.  */
  546.           real best_corner_angle = corner_angle;
  547.           unsigned best_corner_index = p;
  548.           index_list_type equally_good_list = new_index_list ();
  549.           /* As we come into the loop, `p' is the index of the point
  550.              that has an angle less than `corner_angle'.  We use `i' to
  551.              move through the pixels next to that, and `q' for moving
  552.              through the adjacent pixels to each `p'.  */
  553.           unsigned q = p;
  554.           unsigned i = p + 1;
  555.  
  556.           while (true)
  557.             {
  558.               /* Perhaps the angle is sufficiently small that we want to
  559.                  consider this a corner, even if it's not the best
  560.                  (unless we've already wrapped around in the search,
  561.                  i.e., `q<i', in which case we have already added the
  562.                  corner, and we don't want to add it again).  We want to
  563.                  do this check on the first candidate we find, as well
  564.                  as the others in the loop, hence this comes before the
  565.                  stopping condition.  */
  566.               if (corner_angle <= corner_always_threshold && q >= p)
  567.                 APPEND_CORNER (q, corner_angle, '\\');
  568.  
  569.               /* Exit the loop if we've looked at `corner_surround'
  570.                  pixels past the best one we found, or if we've looked
  571.                  at all the pixels.  */
  572.               if (i >= best_corner_index + corner_surround
  573.                   || i >= O_LENGTH (pixel_outline))
  574.                 break;
  575.  
  576.               /* Check the angle.  */
  577.               q = i % O_LENGTH (pixel_outline);
  578.               find_vectors (q, pixel_outline, &in_vector, &out_vector);
  579.               corner_angle = Vangle (in_vector, out_vector);
  580.  
  581.               /* If we come across a corner that is just as good as the
  582.                  best one, we should make it a corner, too.  This
  583.                  happens, for example, at the points on the `W' in some
  584.                  typefaces, where the ``points'' are flat.  */
  585.               if (epsilon_equal (corner_angle, best_corner_angle))
  586.                 append_index (&equally_good_list, q);
  587.  
  588.               else if (corner_angle < best_corner_angle)
  589.                 {
  590.                   best_corner_angle = corner_angle;
  591.                   /* We want to check `corner_surround' pixels beyond the
  592.                      new best corner.  */
  593.                   i = best_corner_index = q;
  594.                   free_index_list (&equally_good_list);
  595.                   equally_good_list = new_index_list ();
  596.                 }
  597.  
  598.               i++;
  599.             }
  600.  
  601.           /* After we exit the loop, `q' is the index of the last point
  602.              we checked.  We have already added the corner if
  603.              `best_corner_angle' is less than `corner_always_threshold'.
  604.              Again, if we've already wrapped around, we don't want to
  605.              add the corner again.  */
  606.           if (best_corner_angle > corner_always_threshold
  607.               && best_corner_index >= p)
  608.             {
  609.               unsigned i;
  610.  
  611.               APPEND_CORNER (best_corner_index, best_corner_angle, '/');
  612.  
  613.               for (i = 0; i < INDEX_LIST_LENGTH (equally_good_list); i++)
  614.                 APPEND_CORNER (GET_INDEX (equally_good_list, i),
  615.                                best_corner_angle, '@');
  616.               free_index_list (&equally_good_list);
  617.             }
  618.  
  619.           /* If we wrapped around in our search, we're done; otherwise,
  620.              we don't want the outer loop to look at the pixels that we
  621.              already looked at in searching for the best corner.  */
  622.           p = (q < p) ? O_LENGTH (pixel_outline) : q;
  623.         }            /* End of searching for the best corner.  */
  624.     }                /* End of considering each pixel.  */
  625.  
  626.   if (INDEX_LIST_LENGTH (corner_list) > 0)
  627.     /* We never want two corners next to each other, since the
  628.        only way to fit such a ``curve'' would be with a straight
  629.        line, which usually interrupts the continuity dreadfully.  */
  630.     remove_adjacent_corners (&corner_list, O_LENGTH (pixel_outline) - 1);
  631.           
  632.   return corner_list;
  633. }
  634.  
  635.  
  636. /* Return the difference vectors coming in and going out of the outline
  637.    OUTLINE at the point whose index is TEST_INDEX.  In Phoenix,
  638.    Schneider looks at a single point on either side of the point we're
  639.    considering.  That works for him because his points are not touching.
  640.    But our points *are* touching, and so we have to look at
  641.    `corner_surround' points on either side, to get a better picture of
  642.    the outline's shape.  */
  643.  
  644. static void
  645. find_vectors (unsigned test_index, pixel_outline_type outline,
  646.               vector_type *in, vector_type *out)
  647. {
  648.   int i;
  649.   unsigned n_done;
  650.   coordinate_type candidate = O_COORDINATE (outline, test_index);
  651.  
  652.   in->dx = 0.0;
  653.   in->dy = 0.0;
  654.   out->dx = 0.0;
  655.   out->dy = 0.0;
  656.  
  657.   /* Add up the differences from p of the `corner_surround' points
  658.      before p.  */ 
  659.   for (i = O_PREV (outline, test_index), n_done = 0; n_done < corner_surround;
  660.        i = O_PREV (outline, i), n_done++)
  661.     *in = Vadd (*in, IPsubtract (O_COORDINATE (outline, i), candidate));
  662.  
  663. #if 0
  664.   /* We don't need this code any more, because now we create the pixel
  665.      outline from the corners of the pixels, rather than the edges.  */
  666.  
  667.   /* To see why we need this test, consider the following
  668.      case: four pixels stacked vertically with no other adjacent pixels,
  669.      i.e.,   *
  670.              *x
  671.              *
  672.              *
  673.             *** (etc.) We are considering the pixel marked `x' for cornerhood.
  674.      The out vector at this point is going to be the zero vector (if
  675.      `corner_surround' is 3), because the first
  676.      pixel on the outline is the one above the x, the second pixel x
  677.      itself, and the third the one below x.  (Remember that we go
  678.      around the edges of the pixels to find the outlines, not the
  679.      pixels themselves.)  */
  680.   if (magnitude (*in) == 0.0)
  681.     {
  682.       WARNING ("Zero magnitude in");
  683.       return corner_threshold + 1.0;
  684.     }
  685. #endif /* 0 */
  686.  
  687.   /* And the points after p.  */
  688.   for (i = O_NEXT (outline, test_index), n_done = 0; n_done < corner_surround;
  689.        i = O_NEXT (outline, i), n_done++)
  690.     *out = Vadd (*out, IPsubtract (O_COORDINATE (outline, i), candidate));
  691.  
  692. #if 0
  693.   /* As with the test for the in vector, we don't need this any more.  */
  694.   if (magnitude (*out) == 0.0)
  695.     {
  696.       WARNING ("Zero magnitude out");
  697.       return corner_threshold + 1.0;
  698.     }
  699. #endif /* 0 */
  700. }
  701.  
  702.  
  703. /* Remove adjacent points from the index list LIST.  We do this by first
  704.    sorting the list and then running through it.  Since these lists are
  705.    quite short, a straight selection sort (e.g., p.139 of the Art of
  706.    Computer Programming, vol.3) is good enough.  LAST_INDEX is the index
  707.    of the last pixel on the outline, i.e., the next one is the first
  708.    pixel.  We need this for checking the adjacency of the last corner.
  709.    
  710.    We need to do this because the adjacent corners turn into
  711.    two-pixel-long curves, which can only be fit by straight lines.  */
  712.  
  713. static void
  714. remove_adjacent_corners (index_list_type *list, unsigned last_index)
  715. {
  716.   unsigned j;
  717.   unsigned last;
  718.   index_list_type new = new_index_list ();
  719.   
  720.   for (j = INDEX_LIST_LENGTH (*list) - 1; j > 0; j--)
  721.     {
  722.       unsigned search;
  723.       unsigned temp;
  724.       /* Find maximal element below `j'.  */
  725.       unsigned max_index = j;
  726.       
  727.       for (search = 0; search < j; search++)
  728.         if (GET_INDEX (*list, search) > GET_INDEX (*list, max_index))
  729.           max_index = search;
  730.           
  731.       if (max_index != j)
  732.         {
  733.           temp = GET_INDEX (*list, j);
  734.           GET_INDEX (*list, j) = GET_INDEX (*list, max_index);
  735.           GET_INDEX (*list, max_index) = temp;
  736.           printf ("needed exchange"); /* xx -- really have to sort?  */
  737.         }
  738.     }
  739.   
  740.   /* The list is sorted.  Now look for adjacent entries.  Each time
  741.      through the loop we insert the current entry and, if appropriate,
  742.      the next entry.  */
  743.   for (j = 0; j < INDEX_LIST_LENGTH (*list) - 1; j++)
  744.     {
  745.       unsigned current = GET_INDEX (*list, j);
  746.       unsigned next = GET_INDEX (*list, j + 1);
  747.       
  748.       /* We should never have inserted the same element twice.  */
  749.       assert (current != next);
  750.       
  751.       append_index (&new, current);
  752.       if (next == current + 1)
  753.         j++;
  754.     }
  755.   
  756.   /* Don't append the last element if it is 1) adjacent to the previous
  757.      one; or 2) adjacent to the very first one.  */
  758.   last = GET_LAST_INDEX (*list);
  759.   if (INDEX_LIST_LENGTH (new) == 0
  760.       || !(last == GET_LAST_INDEX (new) + 1
  761.            || (last == last_index && GET_INDEX (*list, 0) == 0)))
  762.     append_index (&new, last);
  763.   
  764.   free_index_list (list);
  765.   *list = new;
  766. }
  767.  
  768. /* A ``knee'' is a point which forms a ``right angle'' with its
  769.    predecessor and successor.  See the documentation (the `Removing
  770.    knees' section) for an example and more details.
  771.  
  772.    The argument CLOCKWISE tells us which direction we're moving.  (We
  773.    can't figure that information out from just the single segment with
  774.    which we are given to work.)
  775.    
  776.    We should never find two consecutive knees.
  777.    
  778.    Since the first and last points are corners (unless the curve is
  779.    cyclic), it doesn't make sense to remove those.  */
  780.  
  781. /* This evaluates to true if the vector V is zero in one direction and
  782.    nonzero in the other.  */
  783. #define ONLY_ONE_ZERO(v)                        \
  784.   (((v).dx == 0.0 && (v).dy != 0.0) || ((v).dy == 0.0 && (v).dx != 0.0))
  785.  
  786.  
  787. /* There are four possible cases for knees, one for each of the four
  788.    corners of a rectangle; and then the cases differ depending on which
  789.    direction we are going around the curve.  The tests are listed here
  790.    in the order of upper left, upper right, lower right, lower left.
  791.    Perhaps there is some simple pattern to the
  792.    clockwise/counterclockwise differences, but I don't see one.  */
  793. #define CLOCKWISE_KNEE(prev_delta, next_delta)                \
  794.   ((prev_delta.dx == -1.0 && next_delta.dy == 1.0)            \
  795.    || (prev_delta.dy == 1.0 && next_delta.dx == 1.0)            \
  796.    || (prev_delta.dx == 1.0 && next_delta.dy == -1.0)            \
  797.    || (prev_delta.dy == -1.0 && next_delta.dx == -1.0))
  798.  
  799. #define COUNTERCLOCKWISE_KNEE(prev_delta, next_delta)            \
  800.   ((prev_delta.dy == 1.0 && next_delta.dx == -1.0)            \
  801.    || (prev_delta.dx == 1.0 && next_delta.dy == 1.0)            \
  802.    || (prev_delta.dy == -1.0 && next_delta.dx == 1.0)            \
  803.    || (prev_delta.dx == -1.0 && next_delta.dy == -1.0))
  804.  
  805. static void
  806. remove_knee_points (curve_type curve, boolean clockwise)
  807. {
  808.   int i;
  809.   unsigned offset = CURVE_CYCLIC (curve) ? 0 : 1;
  810.   coordinate_type previous
  811.     = real_to_int_coord (CURVE_POINT (curve, CURVE_PREV (curve, offset))); 
  812.   curve_type trimmed_curve = copy_most_of_curve (curve);
  813.   
  814.   if (!CURVE_CYCLIC (curve))
  815.     append_pixel (trimmed_curve, real_to_int_coord (CURVE_POINT (curve, 0)));
  816.  
  817.   for (i = offset; i < CURVE_LENGTH (curve) - offset; i++)
  818.     {
  819.       coordinate_type current
  820.         = real_to_int_coord (CURVE_POINT (curve, i));
  821.       coordinate_type next
  822.         = real_to_int_coord (CURVE_POINT (curve, CURVE_NEXT (curve, i)));
  823.       vector_type prev_delta = IPsubtract (previous, current);
  824.       vector_type next_delta = IPsubtract (next, current);
  825.  
  826.       if (ONLY_ONE_ZERO (prev_delta) && ONLY_ONE_ZERO (next_delta)
  827.           && ((clockwise && CLOCKWISE_KNEE (prev_delta, next_delta))
  828.               || (!clockwise
  829.                   && COUNTERCLOCKWISE_KNEE (prev_delta, next_delta))))
  830.     {
  831.       /* LOG2 (" (%d,%d)", current.x, current.y); */
  832.     }
  833.       else
  834.         {
  835.           previous = current;
  836.           append_pixel (trimmed_curve, current);
  837.         }
  838.     }
  839.  
  840.   if (!CURVE_CYCLIC (curve))
  841.     append_pixel (trimmed_curve, real_to_int_coord (LAST_CURVE_POINT (curve)));
  842.  
  843. /*   if (CURVE_LENGTH (trimmed_curve) == CURVE_LENGTH (curve)) */
  844. /*     LOG (" (none)"); */
  845.  
  846. /*   LOG (".\n"); */
  847.  
  848.   free_curve (curve);
  849.   *curve = *trimmed_curve;
  850. }
  851.  
  852. /* Smooth the curve by adding in neighboring points.  Do this
  853.    `filter_iteration_count' times.  But don't change the corners.  */
  854.  
  855. #if 0
  856. /* Computing the new point based on a single neighboring point and with
  857.    constant percentages, as the `SMOOTH' macro did, isn't quite good
  858.    enough.  For example, at the top of an `o' the curve might well have
  859.    three consecutive horizontal pixels, even though there isn't really a
  860.    straight there.  With this code, the middle point would remain
  861.    unfiltered.  */
  862.  
  863. #define SMOOTH(axis)                            \
  864.   CURVE_POINT (curve, this_point).axis                    \
  865.     = ((1.0 - center_percent) / 2)                    \
  866.        * CURVE_POINT (curve, CURVE_PREV (curve, this_point)).axis       \
  867.       + center_percent * CURVE_POINT (curve, this_point).axis        \
  868.       + ((1.0 - center_percent) / 2)                    \
  869.         * CURVE_POINT (curve, CURVE_NEXT (curve, this_point)).axis
  870. #endif /* 0 */
  871.  
  872. /* We sometimes need to change the information about the filtered point.
  873.    This macro assigns to the relevant variables.  */
  874. #define FILTER_ASSIGN(new)                        \
  875.   do                                    \
  876.     {                                    \
  877.       in = in_##new;                            \
  878.       out = out_##new;                            \
  879.       count = new##_count;                        \
  880.       angle = angle_##new;                        \
  881.     }                                    \
  882.   while (0)
  883.  
  884. static void
  885. filter (curve_type curve)
  886. {
  887.   unsigned iteration, this_point;
  888.   unsigned offset = CURVE_CYCLIC (curve) ? 0 : 1;
  889.  
  890.   /* We must have at least three points---the previous one, the current
  891.      one, and the next one.  But if we don't have at least five, we will
  892.      probably collapse the curve down onto a single point, which means
  893.      we won't be able to fit it with a spline.  */
  894.   if (CURVE_LENGTH (curve) < 5)
  895.     {
  896. /*       LOG1 ("Length is %u, not enough to filter.\n", CURVE_LENGTH (curve)); */
  897.       return;
  898.     }
  899.  
  900.   for (iteration = 0; iteration < filter_iteration_count; iteration++)
  901.     {
  902.       curve_type new_curve = copy_most_of_curve (curve);
  903.       
  904.       /* Keep the first point on the curve.  */
  905.       if (offset)
  906.         append_point (new_curve, CURVE_POINT (curve, 0));
  907.  
  908.       for (this_point = offset; this_point < CURVE_LENGTH (curve) - offset;
  909.            this_point++)
  910.         {
  911.           real angle, angle_alt;
  912.           vector_type in, in_alt, out, out_alt, sum;
  913.           unsigned count, alt_count;
  914.           real_coordinate_type new_point;
  915.  
  916.           /* Find the angle using the usual number of surrounding points
  917.              on the curve. */
  918.           find_curve_vectors (this_point, curve, filter_surround,
  919.                               &in, &out, &count);
  920.           angle = filter_angle (in, out);
  921.  
  922.           /* Find the angle using the alternative (presumably smaller)
  923.              number.  */ 
  924.           find_curve_vectors (this_point, curve, filter_alternative_surround,
  925.                               &in_alt, &out_alt, &alt_count);
  926.           angle_alt = filter_angle (in_alt, out_alt);
  927.  
  928.           /* If the alternate angle is enough larger than the usual one
  929.              and neither of the components of the sum are zero, use it.
  930.              (We don't use absolute value here, since if the alternate
  931.              angle is smaller, we don't particularly care, since that
  932.              means the curve is pretty flat around the current point,
  933.              anyway.)  This helps keep small features from disappearing
  934.              into the surrounding curve.  */
  935.           sum = Vadd (in_alt, out_alt);
  936.           if (angle_alt - angle >= filter_epsilon
  937.               && sum.dx != 0 && sum.dy != 0)
  938.             FILTER_ASSIGN (alt);
  939.  
  940. #if 0
  941. /* This code isn't needed anymore, since we do the filtering in a
  942.    somewhat more general way.  */
  943.           /* If we're left with an angle of zero, don't stop yet; we
  944.              might be at a straight which really isn't one (as in the `o'
  945.              discussed above).  */
  946.           if (epsilon_equal (angle, 0.0))
  947.             {
  948.               real angle_secondary;
  949.               vector_type in_secondary, out_secondary;
  950.               unsigned in_secondary_count, out_secondary_count;
  951.  
  952.               find_curve_vectors (this_point, curve, filter_secondary_surround,
  953.                                   &in_secondary, &out_secondary,
  954.                                   &in_secondary_count, &out_secondary_count);
  955.               angle_secondary = filter_angle (in_secondary, out_secondary);
  956.               if (!epsilon_equal (angle_secondary, 0.0))
  957.                 FILTER_ASSIGN (secondary);
  958.             }
  959. #endif /* 0 */
  960.  
  961.           /* Start with the old point.  */
  962.           new_point = CURVE_POINT (curve, this_point);
  963.           sum = Vadd (in, out);
  964.           new_point.x += sum.dx * filter_percent / count;
  965.           new_point.y += sum.dy * filter_percent / count;
  966.  
  967.           /* Put the newly computed point into a separate curve, so it
  968.              doesn't affect future computation (on this iteration).  */
  969.           append_point (new_curve, new_point);
  970.        }
  971.      
  972.      /* Just as with the first point, we have to keep the last point.  */
  973.      if (offset)
  974.        append_point (new_curve, LAST_CURVE_POINT (curve));
  975.        
  976.      /* Set the original curve to the newly filtered one, and go again.  */
  977.      free_curve (curve);
  978.      *curve = *new_curve;
  979.     }
  980.  
  981. /*   log_curve (curve, false); */
  982. /*   display_curve (curve); */
  983. }
  984.  
  985.  
  986. /* Return the vectors IN and OUT, computed by looking at SURROUND points
  987.    on either side of TEST_INDEX.  Also return the number of points in
  988.    the vectors in COUNT (we make sure they are the same).  */
  989.  
  990. static void
  991. find_curve_vectors (unsigned test_index, curve_type curve,
  992.                     unsigned surround,
  993.                     vector_type *in, vector_type *out, unsigned *count)
  994. {
  995.   int i;
  996.   unsigned in_count, out_count;
  997.   unsigned n_done;
  998.   real_coordinate_type candidate = CURVE_POINT (curve, test_index);
  999.  
  1000.   /* Add up the differences from p of the `surround' points
  1001.      before p.  */ 
  1002.  
  1003.   in->dx = 0.0;
  1004.   in->dy = 0.0;
  1005.  
  1006.   for (i = CURVE_PREV (curve, test_index), n_done = 0;
  1007.        i >= 0 && n_done < surround;  /* Do not wrap around.  */
  1008.        i = CURVE_PREV (curve, i), n_done++)
  1009.     *in = Vadd (*in, Psubtract (CURVE_POINT (curve, i), candidate));
  1010.   in_count = n_done;
  1011.  
  1012.   /* And the points after p.  Don't use more points after p than we
  1013.      ended up with before it.  */
  1014.   out->dx = 0.0;
  1015.   out->dy = 0.0;
  1016.  
  1017.   for (i = CURVE_NEXT (curve, test_index), n_done = 0;
  1018.        i < CURVE_LENGTH (curve) && n_done < surround && n_done < in_count;
  1019.        i = CURVE_NEXT (curve, i), n_done++)
  1020.     *out = Vadd (*out, Psubtract (CURVE_POINT (curve, i), candidate));
  1021.   out_count = n_done;
  1022.   
  1023.   /* If we used more points before p than after p, we have to go back
  1024.      and redo it.  (We could just subtract the ones that were missing,
  1025.      but for this few of points, efficiency doesn't matter.)  */
  1026.   if (out_count < in_count)
  1027.     {
  1028.       in->dx = 0.0;
  1029.       in->dy = 0.0;
  1030.  
  1031.       for (i = CURVE_PREV (curve, test_index), n_done = 0;
  1032.            i >= 0 && n_done < out_count;
  1033.            i = CURVE_PREV (curve, i), n_done++)
  1034.         *in = Vadd (*in, Psubtract (CURVE_POINT (curve, i), candidate));
  1035.       in_count = n_done;
  1036.     }
  1037.   
  1038.   assert (in_count == out_count);
  1039.   *count = in_count;
  1040. }
  1041.  
  1042.  
  1043. /* Find the angle between the vectors IN and OUT, and bring it into the
  1044.    range [0,45].  */
  1045.  
  1046. static real
  1047. filter_angle (vector_type in, vector_type out)
  1048. {
  1049.   real angle = Vangle (in, out);
  1050.   
  1051.   /* What we want to do between 90 and 180 is the same as what we
  1052.      want to do between 0 and 90.  */
  1053.   angle = fmod (angle, 1990.0);
  1054.  
  1055.   /* And what we want to do between 45 and 90 is the same as
  1056.      between 0 and 45, only reversed.  */
  1057.   if (angle > 45.0) angle = 90.0 - angle;
  1058.  
  1059.   return angle;
  1060. }
  1061.  
  1062. /* This routine returns the curve fitted to a straight line in a very
  1063.    simple way: make the first and last points on the curve be the
  1064.    endpoints of the line.  This simplicity is justified because we are
  1065.    called only on very short curves.  */
  1066.  
  1067. static spline_list_type *
  1068. fit_with_line (curve_type curve)
  1069. {
  1070.   spline_type line = new_spline ();
  1071.  
  1072. /*   LOG ("Fitting with straight line:\n"); */
  1073. /*   REPORT ("l"); */
  1074.  
  1075.   SPLINE_DEGREE (line) = LINEAR;
  1076.   START_POINT (line) = CONTROL1 (line) = CURVE_POINT (curve, 0);
  1077.   END_POINT (line) = CONTROL2 (line) = LAST_CURVE_POINT (curve);
  1078.   
  1079.   /* Make sure that this line is never changed to a cubic.  */
  1080.   SPLINE_LINEARITY (line) = 0;
  1081.  
  1082. /*   if (logging) */
  1083. /*     { */
  1084. /*       LOG ("  "); */
  1085. /*       print_spline (log_file, line); */
  1086. /*     } */
  1087.  
  1088.   return init_spline_list (line);
  1089. }
  1090.  
  1091. /* The least squares method is well described in Schneider's thesis.
  1092.    Briefly, we try to fit the entire curve with one spline.  If that fails,
  1093.    we try reparameterizing, i.e., finding new, and supposedly better,
  1094.    t values.  If that still fails, we subdivide the curve.  */
  1095.  
  1096. static spline_list_type *
  1097. fit_with_least_squares (curve_type curve)
  1098. {
  1099.   real error, best_error = FLT_MAX;
  1100.   spline_type spline, best_spline;
  1101.   spline_list_type *spline_list;
  1102.   unsigned worst_point;
  1103.   unsigned iteration = 0;
  1104.   real previous_error = FLT_MAX;
  1105.   real improvement = FLT_MAX;
  1106.   
  1107. /*   LOG ("\nFitting with least squares:\n"); */
  1108.  
  1109.   /* Phoenix reduces the number of points with a ``linear spline
  1110.      technique''.  But for fitting letterforms, that is
  1111.      inappropriate.  We want all the points we can get.  */
  1112.  
  1113.   /* It makes no difference whether we first set the `t' values or
  1114.      find the tangents.  This order makes the documentation a little
  1115.      more coherent.  */
  1116.  
  1117. /*   LOG ("Finding tangents:\n"); */
  1118.   find_tangent (curve, /* to_start */ true,  /* cross_curve */ false);
  1119.   find_tangent (curve, /* to_start */ false, /* cross_curve */ false);
  1120.  
  1121.   set_initial_parameter_values (curve);
  1122.  
  1123.   /* Now we loop, reparameterizing and/or subdividing, until CURVE has
  1124.      been fit.  */
  1125.   while (true)
  1126.     {
  1127. /*       LOG ("  fitted to spline:\n"); */
  1128.  
  1129.       spline = fit_one_spline (curve);
  1130.  
  1131. /*       if (logging) */
  1132. /*         { */
  1133. /*           LOG ("    "); */
  1134. /*           print_spline (log_file, spline); */
  1135. /*         } */
  1136.  
  1137.       error = find_error (curve, spline, &worst_point);
  1138.       if (error > previous_error)
  1139.     {
  1140. /*       LOG ("Reparameterization made it worse.\n"); */
  1141.       /* Just fall through; we will subdivide.  */
  1142.     }
  1143.       else
  1144.         {
  1145.           best_error = error;
  1146.           best_spline = spline;
  1147.         }
  1148.  
  1149.       improvement = 1.0 - error / previous_error;
  1150.  
  1151.       /* Don't exit, even if the error is less than `error_threshold',
  1152.          since we might be able to improve the fit with further
  1153.          reparameterization.  If the reparameterization made it worse,
  1154.          we will exit here, since `improvement' will be negative.  */
  1155.       if (improvement < reparameterize_improvement
  1156.           || error > reparameterize_threshold)
  1157.     break;
  1158.  
  1159.       iteration++;
  1160. /*       LOG3 ("Reparameterization #%u (error was %.3f, a %u%% improvement):\n", */
  1161. /*             iteration, error, ((unsigned) (improvement * 100.0))); */
  1162.  
  1163.       /* The reparameterization might fail, if the initial fit was
  1164.          better than `reparameterize_threshold', yet worse than the
  1165.          Newton-Raphson algorithm could handle.  */
  1166.       if (!reparameterize (curve, spline))
  1167.     break;
  1168.  
  1169.       previous_error = error;
  1170.     }
  1171.  
  1172.   /* Go back to the best fit.  */
  1173.   spline = best_spline;
  1174.   error = best_error;
  1175.  
  1176.   if (error < error_threshold)
  1177.     {
  1178.       /* The points were fitted with a (possibly reparameterized)
  1179.          spline.  We end up here whenever a fit is accepted.  We have
  1180.          one more job: see if the ``curve'' that was fit should really
  1181.          be a straight line. */
  1182.       if (spline_linear_enough (&spline, curve))
  1183.         {
  1184.           SPLINE_DEGREE (spline) = LINEAR;
  1185. /*           LOG ("Changed to line.\n"); */
  1186.         }
  1187.       spline_list = init_spline_list (spline);
  1188. /*       LOG1 ("Accepted error of %.3f.\n", error); */
  1189.     }
  1190.   else
  1191.     {
  1192.       /* We couldn't fit the curve acceptably, so subdivide.  */
  1193.       unsigned subdivision_index;
  1194.       spline_list_type *left_spline_list;
  1195.       spline_list_type *right_spline_list;
  1196.       curve_type left_curve = new_curve ();
  1197.       curve_type right_curve = new_curve ();
  1198.  
  1199.       /* Keep the linked list of curves intact.  */
  1200.       NEXT_CURVE (right_curve) = NEXT_CURVE (curve);
  1201.       PREVIOUS_CURVE (right_curve) = left_curve;
  1202.       NEXT_CURVE (left_curve) = right_curve;
  1203.       PREVIOUS_CURVE (left_curve) = curve;
  1204.       NEXT_CURVE (curve) = left_curve;
  1205.  
  1206. /*       REPORT ("s"); */
  1207. /*       LOG1 ("\nSubdividing (error %.3f):\n", error); */
  1208. /*       LOG3 ("  Original point: (%.3f,%.3f), #%u.\n", */
  1209. /*             CURVE_POINT (curve, worst_point).x, */
  1210. /*             CURVE_POINT (curve, worst_point).y, worst_point); */
  1211.       subdivision_index = find_subdivision (curve, worst_point);
  1212. /*       LOG3 ("  Final point: (%.3f,%.3f), #%u.\n", */
  1213. /*             CURVE_POINT (curve, subdivision_index).x, */
  1214. /*             CURVE_POINT (curve, subdivision_index).y, subdivision_index); */
  1215. /*       display_subdivision (CURVE_POINT (curve, subdivision_index)); */
  1216.       
  1217.       /* The last point of the left-hand curve will also be the first
  1218.          point of the right-hand curve.  */
  1219.       CURVE_LENGTH (left_curve) = subdivision_index + 1;
  1220.       CURVE_LENGTH (right_curve) = CURVE_LENGTH (curve) - subdivision_index;
  1221.       left_curve->point_list = curve->point_list;
  1222.       right_curve->point_list = curve->point_list + subdivision_index;
  1223.  
  1224.       /* We want to use the tangents of the curve which we are
  1225.          subdividing for the start tangent for left_curve and the
  1226.          end tangent for right_curve.  */
  1227.       CURVE_START_TANGENT (left_curve) = CURVE_START_TANGENT (curve);
  1228.       CURVE_END_TANGENT (right_curve) = CURVE_END_TANGENT (curve);
  1229.  
  1230.       /* We have to set up the two curves before finding the tangent at
  1231.          the subdivision point.  The tangent at that point must be the
  1232.          same for both curves, or noticeable bumps will occur in the
  1233.          character.  But we want to use information on both sides of the
  1234.          point to compute the tangent, hence cross_curve = true.  */
  1235.       find_tangent (left_curve, /* to_start_point: */ false,
  1236.                     /* cross_curve: */ true);
  1237.       CURVE_START_TANGENT (right_curve) = CURVE_END_TANGENT (left_curve);
  1238.  
  1239.       /* Now that we've set up the curves, we can fit them.  */
  1240.       left_spline_list = fit_curve (left_curve);
  1241.       right_spline_list = fit_curve (right_curve);
  1242.  
  1243.       /* Neither of the subdivided curves could be fit, so fail.  */
  1244.       if (left_spline_list == NULL && right_spline_list == NULL)
  1245.         return NULL;
  1246.  
  1247.       /* Put the two together (or whichever of them exist).  */
  1248.       spline_list = new_spline_list ();
  1249.  
  1250.       if (left_spline_list == NULL)
  1251.         {
  1252.           WARNING ("could not fit left spline list");
  1253. /*           LOG1 ("Could not fit spline to left curve (%x).\n", */
  1254. /*                 (unsigned) left_curve); */
  1255.         }
  1256.       else
  1257.         concat_spline_lists (spline_list, *left_spline_list);
  1258.  
  1259.       if (right_spline_list == NULL)
  1260.         {
  1261.           WARNING ("could not fit right spline list");
  1262. /*           LOG1 ("Could not fit spline to right curve (%x).\n", */
  1263. /*                 (unsigned) right_curve); */
  1264.         }
  1265.       else
  1266.         concat_spline_lists (spline_list, *right_spline_list);
  1267.     }
  1268.  
  1269.   return spline_list;
  1270. }
  1271.  
  1272.  
  1273. /* Our job here is to find alpha1 (and alpha2), where t1_hat (t2_hat) is
  1274.    the tangent to CURVE at the starting (ending) point, such that:
  1275.  
  1276.    control1 = alpha1*t1_hat + starting point
  1277.    control2 = alpha2*t2_hat + ending_point
  1278.  
  1279.    and the resulting spline (starting_point .. control1 and control2 ..
  1280.    ending_point) minimizes the least-square error from CURVE.
  1281.    
  1282.    See pp.57--59 of the Phoenix thesis.
  1283.    
  1284.    The B?(t) here corresponds to B_i^3(U_i) there.
  1285.    The Bernshte\u in polynomials of degree n are defined by
  1286.    B_i^n(t) = { n \choose i } t^i (1-t)^{n-i}, i = 0..n  */
  1287.  
  1288. #define B0(t) CUBE (1 - (t))
  1289. #define B1(t) (3.0 * (t) * SQUARE (1 - (t)))
  1290. #define B2(t) (3.0 * SQUARE (t) * (1 - (t)))
  1291. #define B3(t) CUBE (t)
  1292.  
  1293. #define U(i) CURVE_T (curve, i)
  1294.  
  1295. static spline_type
  1296. fit_one_spline (curve_type curve)
  1297. {
  1298.   /* Since our arrays are zero-based, the `C0' and `C1' here correspond
  1299.      to `C1' and `C2' in the paper.  */
  1300.   real X_C1_det, C0_X_det, C0_C1_det;
  1301.   real alpha1, alpha2;
  1302.   spline_type spline;
  1303.   vector_type start_vector, end_vector;
  1304.   unsigned i;
  1305.   vector_type t1_hat = *CURVE_START_TANGENT (curve);
  1306.   vector_type t2_hat = *CURVE_END_TANGENT (curve);
  1307.   real C[2][2] = { { 0.0, 0.0 }, { 0.0, 0.0 } };
  1308.   real X[2] = { 0.0, 0.0 };
  1309.   int Alen = CURVE_LENGTH (curve);
  1310.   vector_type *A; 
  1311.   
  1312.   A = g_new0 (vector_type, Alen * 2);
  1313.  
  1314.   START_POINT (spline) = CURVE_POINT (curve, 0);
  1315.   END_POINT (spline) = LAST_CURVE_POINT (curve);
  1316.   start_vector = make_vector (START_POINT (spline));
  1317.   end_vector = make_vector (END_POINT (spline));
  1318.  
  1319.   for (i = 0; i < CURVE_LENGTH (curve); i++)
  1320.     {
  1321.       A[i*2+0] = Vmult_scalar (t1_hat, B1 (U (i)));
  1322.       A[i*2+1] = Vmult_scalar (t2_hat, B2 (U (i)));
  1323.     }
  1324.  
  1325.   for (i = 0; i < CURVE_LENGTH (curve); i++)
  1326.     {
  1327.       vector_type temp, temp0, temp1, temp2, temp3;
  1328.       vector_type *Ai = &A[i*2];
  1329.  
  1330.       C[0][0] += Vdot (Ai[0], Ai[0]);
  1331.       C[0][1] += Vdot (Ai[0], Ai[1]);
  1332.       /* C[1][0] = C[0][1] (this is assigned outside the loop)  */
  1333.       C[1][1] += Vdot (Ai[1], Ai[1]);
  1334.  
  1335.       /* Now the right-hand side of the equation in the paper.  */
  1336.       temp0 = Vmult_scalar (start_vector, B0 (U (i)));
  1337.       temp1 = Vmult_scalar (start_vector, B1 (U (i)));
  1338.       temp2 = Vmult_scalar (end_vector, B2 (U (i)));
  1339.       temp3 = Vmult_scalar (end_vector, B3 (U (i)));
  1340.  
  1341.       temp = make_vector (Vsubtract_point (CURVE_POINT (curve, i),
  1342.               Vadd (temp0, Vadd (temp1, Vadd (temp2, temp3)))));
  1343.  
  1344.       X[0] += Vdot (temp, Ai[0]);
  1345.       X[1] += Vdot (temp, Ai[1]);
  1346.     }
  1347.  
  1348.   C[1][0] = C[0][1];
  1349.  
  1350.   X_C1_det = X[0] * C[1][1] - X[1] * C[0][1];
  1351.   C0_X_det = C[0][0] * X[1] - C[0][1] * X[0];
  1352.   C0_C1_det = C[0][0] * C[1][1] - C[1][0] * C[0][1];
  1353.   if (C0_C1_det == 0.0)
  1354.     FATAL ("zero determinant of C0*C1");
  1355.  
  1356.   alpha1 = X_C1_det / C0_C1_det;
  1357.   alpha2 = C0_X_det / C0_C1_det;
  1358.  
  1359.   CONTROL1 (spline) = Vadd_point (START_POINT (spline),
  1360.                                   Vmult_scalar (t1_hat, alpha1));
  1361.   CONTROL2 (spline) = Vadd_point (END_POINT (spline),
  1362.                                   Vmult_scalar (t2_hat, alpha2));
  1363.   SPLINE_DEGREE (spline) = CUBIC;
  1364.  
  1365.   g_free (A);
  1366.   
  1367.   return spline;
  1368. }
  1369.  
  1370. /* Find closer-to-optimal t values for the given x,y's and control
  1371.    points, using Newton-Raphson iteration.  A good description of this
  1372.    is in Plass & Stone.  This routine performs one step in the
  1373.    iteration, not the whole thing.  */
  1374.  
  1375. static boolean
  1376. reparameterize (curve_type curve, spline_type S)
  1377. {
  1378.   unsigned p, i;
  1379.   spline_type S1, S2;        /* S' and S''.  */
  1380.  
  1381. /*   REPORT ("r"); */
  1382.  
  1383.   /* Find the first and second derivatives of S.  To make
  1384.      `evaluate_spline' work, we fill the beginning points (i.e., the first
  1385.      two for a linear spline and the first three for a quadratic one),
  1386.      even though this is at odds with the rest of the program.  */
  1387.   for (i = 0; i < 3; i++)
  1388.     {
  1389.       S1.v[i].x = 3.0 * (S.v[i + 1].x - S.v[i].x);
  1390.       S1.v[i].y = 3.0 * (S.v[i + 1].y - S.v[i].y);
  1391.     }
  1392.   S1.v[i].x = S1.v[i].y = -1.0;    /* These will never be accessed.  */
  1393.   SPLINE_DEGREE (S1) = QUADRATIC;
  1394.  
  1395.   for (i = 0; i < 2; i++)
  1396.     {
  1397.       S2.v[i].x = 2.0 * (S1.v[i + 1].x - S1.v[i].x);
  1398.       S2.v[i].y = 2.0 * (S1.v[i + 1].y - S1.v[i].y);
  1399.     }
  1400.   S2.v[2].x = S2.v[2].y = S2.v[3].x = S2.v[3].y = -1.0;
  1401.   SPLINE_DEGREE (S2) = LINEAR;
  1402.  
  1403.   for (p = 0; p < CURVE_LENGTH (curve); p++)
  1404.     {
  1405.       real new_distance, old_distance;
  1406.       real_coordinate_type new_point;
  1407.       real_coordinate_type point = CURVE_POINT (curve, p);
  1408.       real t = CURVE_T (curve, p);
  1409.  
  1410.       /* Find the points at this t on S, S', and S''.  */
  1411.       real_coordinate_type S_t = evaluate_spline (S, t);
  1412.       real_coordinate_type S1_t = evaluate_spline (S1, t);
  1413.       real_coordinate_type S2_t = evaluate_spline (S2, t);
  1414.  
  1415.       /* The differences in x and y (Q1(t) on p.62 of Schneider's thesis).  */
  1416.       real_coordinate_type d;
  1417.       real numerator;
  1418.       real denominator;
  1419.  
  1420.       d.x = S_t.x - point.x;
  1421.       d.y = S_t.y - point.y;
  1422.  
  1423.       /* The step size, f(t)/f'(t).  */
  1424.       numerator = d.x * S1_t.x + d.y * S1_t.y;
  1425.       denominator = (SQUARE (S1_t.x) + d.x * S2_t.x
  1426.              + SQUARE (S1_t.y) + d.y * S2_t.y);
  1427.  
  1428.       /* We compute the distances only to be able to check that we
  1429.          really are moving closer.  I don't know how this condition can
  1430.          be reliably checked for in advance, but I know what it means in
  1431.          practice: the original fit was not good enough for the
  1432.          Newton-Raphson iteration to converge.  Therefore, we need to
  1433.          abort the reparameterization, and subdivide.  */
  1434.       old_distance = distance (S_t, point);
  1435.       CURVE_T (curve, p) -= numerator / denominator;
  1436.       new_point = evaluate_spline (S, CURVE_T (curve, p));
  1437.       new_distance = distance (new_point, point);
  1438.  
  1439.       if (new_distance > old_distance)
  1440.     {
  1441. /*       REPORT ("!"); */
  1442. /*       LOG3 ("  Stopped reparameterizing; %.3f > %.3f at point %u.\n", */
  1443. /*         new_distance, old_distance, p); */
  1444.       return false;
  1445.     }
  1446.  
  1447.       /* The t value might be negative or > 1, if the choice of control
  1448.          points wasn't so great.  We have no difficulty in evaluating
  1449.          a spline at a t outside the range zero to one, though, so it
  1450.          doesn't matter.  (Although it is a little unconventional.)  */
  1451.     }
  1452. /*   LOG ("  reparameterized curve:\n   "); */
  1453. /*   log_curve (curve, true); */
  1454.  
  1455.   return true;
  1456. }
  1457.  
  1458. /* This routine finds the best place to subdivide the curve CURVE,
  1459.    somewhere near to the point whose index is INITIAL.  Originally,
  1460.    curves were always subdivided at the point of worst error, which is
  1461.    intuitively appealing, but doesn't always give the best results.  For
  1462.    example, at the end of a serif that tapers into the stem, the best
  1463.    subdivision point is at the point where they join, even if the worst
  1464.    point is a little ways into the serif.
  1465.    
  1466.    We return the index of the point at which to subdivide.  */
  1467.          
  1468. static unsigned
  1469. find_subdivision (curve_type curve, unsigned initial)
  1470. {
  1471.   unsigned i, n_done;
  1472.   int best_point = -1;
  1473.   vector_type best = { FLT_MAX, FLT_MAX };
  1474.   unsigned search = subdivide_search * CURVE_LENGTH (curve);
  1475.  
  1476. /*   LOG1 ("  Number of points to search: %u.\n", search); */
  1477.   
  1478.   /* We don't want to find the first (or last) point in the curve.  */
  1479.   for (i = initial, n_done = 0; i > 0 && n_done < search;
  1480.        i = CURVE_PREV (curve, i), n_done++)
  1481.     {
  1482.       if (test_subdivision_point (curve, i, &best))
  1483.         {
  1484.           best_point = i;
  1485. /*           LOG3 ("    Better point: (%.3f,%.3f), #%u.\n", */
  1486. /*                CURVE_POINT (curve, i).x, CURVE_POINT (curve, i).y, i); */
  1487.         }
  1488.     }
  1489.  
  1490.   /* If we found a good one, let's take it.  */
  1491.   if (best_point != -1)
  1492.     return best_point;
  1493.  
  1494.   for (i = CURVE_NEXT (curve, initial), n_done = 0;
  1495.        i < CURVE_LENGTH (curve) - 1 && n_done < search;
  1496.        i = CURVE_NEXT (curve, i), n_done++)
  1497.     {
  1498.       if (test_subdivision_point (curve, i, &best))
  1499.         {
  1500.           best_point = i;
  1501. /*           LOG3 ("    Better point at (%.3f,%.3f), #%u.\n", */
  1502. /*                CURVE_POINT (curve, i).x, CURVE_POINT (curve, i).y, i); */
  1503.         }
  1504.     }
  1505.  
  1506.   /* If we didn't find any better point, return the original.  */
  1507.   return best_point == -1 ? initial : best_point;
  1508. }
  1509.  
  1510.  
  1511. /* Here are some macros that decide whether or not we're at a
  1512.    ``join point'', as described above.  */ 
  1513. #define ONLY_ONE_LESS(v)                        \
  1514.   (((v).dx < subdivide_threshold && (v).dy > subdivide_threshold)    \
  1515.    || ((v).dy < subdivide_threshold && (v).dx > subdivide_threshold))
  1516.  
  1517. #define BOTH_GREATER(v)                            \
  1518.   ((v).dx > subdivide_threshold && (v).dy > subdivide_threshold)
  1519.  
  1520. /* We assume that the vectors V1 and V2 are nonnegative.  */
  1521. #define JOIN(v1, v2)                            \
  1522.     ((ONLY_ONE_LESS (v1) && BOTH_GREATER (v2))                \
  1523.      || (ONLY_ONE_LESS (v2) && BOTH_GREATER (v1)))
  1524.  
  1525. /* If the component D of the vector V is smaller than the best so far,
  1526.    update the best point.  */
  1527. #define UPDATE_BEST(v, d)                        \
  1528.   do                                    \
  1529.     {                                    \
  1530.       if ((v).d < subdivide_threshold && (v).d < best->d)        \
  1531.         best->d = (v).d;                        \
  1532.     }                                    \
  1533.   while (0)
  1534.  
  1535.  
  1536. /* If the point INDEX in the curve CURVE is the best subdivision point
  1537.    we've found so far, update the vector BEST.  */
  1538.  
  1539. static boolean
  1540. test_subdivision_point (curve_type curve, unsigned index, vector_type *best)
  1541. {
  1542.   unsigned count;
  1543.   vector_type in, out;
  1544.   boolean join = false;
  1545.  
  1546.   find_curve_vectors (index, curve, subdivide_surround, &in, &out, &count);
  1547.   
  1548.   /* We don't want to subdivide at points which are very close to the
  1549.      endpoints, so if the vectors aren't computed from as many points as
  1550.      we asked for, don't bother checking this point.  */
  1551.   if (count == subdivide_surround)
  1552.     {
  1553.       in = Vabs (in);
  1554.       out = Vabs (out);
  1555.  
  1556.       join = JOIN (in, out);
  1557.       if (join)
  1558.         {
  1559.           UPDATE_BEST (in, dx);
  1560.           UPDATE_BEST (in, dy);
  1561.           UPDATE_BEST (out, dx);
  1562.           UPDATE_BEST (out, dy);
  1563.         }
  1564.     }
  1565.   
  1566.   return join;
  1567. }
  1568.  
  1569. /* Find reasonable values for t for each point on CURVE.  The method is
  1570.    called chord-length parameterization, which is described in Plass &
  1571.    Stone.  The basic idea is just to use the distance from one point to
  1572.    the next as the t value, normalized to produce values that increase
  1573.    from zero for the first point to one for the last point.  */
  1574.  
  1575. static void
  1576. set_initial_parameter_values (curve_type curve)
  1577. {
  1578.   unsigned p;
  1579.  
  1580. /*   LOG ("\nAssigning initial t values:\n  "); */
  1581.  
  1582.   CURVE_T (curve, 0) = 0.0;
  1583.  
  1584.   for (p = 1; p < CURVE_LENGTH (curve); p++)
  1585.     {
  1586.       real_coordinate_type point = CURVE_POINT (curve, p),
  1587.                            previous_p = CURVE_POINT (curve, p - 1);
  1588.       real d = distance (point, previous_p);
  1589.       CURVE_T (curve, p) = CURVE_T (curve, p - 1) + d;
  1590.     }
  1591.  
  1592.   assert (LAST_CURVE_T (curve) != 0.0);
  1593.  
  1594.   for (p = 1; p < CURVE_LENGTH (curve); p++)
  1595.     CURVE_T (curve, p) = CURVE_T (curve, p) / LAST_CURVE_T (curve);
  1596.  
  1597. /*   log_entire_curve (curve); */
  1598. }
  1599.  
  1600. /* Find an approximation to the tangent to an endpoint of CURVE (to the
  1601.    first point if TO_START_POINT is true, else the last).  If
  1602.    CROSS_CURVE is true, consider points on the adjacent curve to CURVE.
  1603.  
  1604.    It is important to compute an accurate approximation, because the
  1605.    control points that we eventually decide upon to fit the curve will
  1606.    be placed on the half-lines defined by the tangents and
  1607.    endpoints...and we never recompute the tangent after this.  */
  1608.  
  1609. static void
  1610. find_tangent (curve_type curve, boolean to_start_point, boolean cross_curve)
  1611. {
  1612.   vector_type tangent;
  1613.   vector_type **curve_tangent = to_start_point ? &(CURVE_START_TANGENT (curve))
  1614.                                                : &(CURVE_END_TANGENT (curve));
  1615.   unsigned n_points = 0;
  1616.   
  1617. /*   LOG1 ("  tangent to %s: ", to_start_point ? "start" : "end"); */
  1618.  
  1619.   if (*curve_tangent == NULL)
  1620.     {
  1621.       *curve_tangent = g_new (vector_type, 1);
  1622.       tangent = find_half_tangent (curve, to_start_point, &n_points);
  1623.  
  1624.       if (cross_curve)
  1625.         {
  1626.           curve_type adjacent_curve
  1627.             = to_start_point ? PREVIOUS_CURVE (curve) : NEXT_CURVE (curve);
  1628.           vector_type tangent2
  1629.             = find_half_tangent (adjacent_curve, !to_start_point, &n_points);
  1630.           
  1631. /*           LOG2 ("(adjacent curve half tangent (%.3f,%.3f)) ", */
  1632. /*                 tangent2.dx, tangent2.dy); */
  1633.           tangent = Vadd (tangent, tangent2);
  1634.         }
  1635.  
  1636.       assert (n_points > 0);
  1637.       **curve_tangent = Vmult_scalar (tangent, 1.0 / n_points);
  1638.     }
  1639.   else
  1640.     {
  1641. /*       LOG ("(already computed) "); */
  1642.     }
  1643.  
  1644. /*   LOG2 ("(%.3f,%.3f).\n", (*curve_tangent)->dx, (*curve_tangent)->dy); */
  1645. }
  1646.  
  1647.  
  1648. /* Find the change in y and change in x for `tangent_surround' (a global)
  1649.    points along CURVE.  Increment N_POINTS by the number of points we
  1650.    actually look at.  */
  1651.  
  1652. static vector_type
  1653. find_half_tangent (curve_type c, boolean to_start_point, unsigned *n_points)
  1654. {
  1655.   unsigned p;
  1656.   int factor = to_start_point ? 1 : -1;
  1657.   unsigned tangent_index = to_start_point ? 0 : c->length - 1;
  1658.   real_coordinate_type tangent_point = CURVE_POINT (c, tangent_index);
  1659.   vector_type tangent;
  1660.  
  1661.   tangent.dx = 0.0;
  1662.   tangent.dy = 0.0;
  1663.  
  1664.   for (p = 1; p <= tangent_surround; p++)
  1665.     {
  1666.       int this_index = p * factor + tangent_index;
  1667.       real_coordinate_type this_point;
  1668.  
  1669.       if (this_index < 0 || this_index >= c->length)
  1670.     break;
  1671.  
  1672.       this_point = CURVE_POINT (c, p * factor + tangent_index);
  1673.  
  1674.       /* Perhaps we should weight the tangent from `this_point' by some
  1675.          factor dependent on the distance from the tangent point.  */
  1676.       tangent = Vadd (tangent,
  1677.               Vmult_scalar (Psubtract (this_point, tangent_point),
  1678.                     factor));
  1679.       (*n_points)++;
  1680.     }
  1681.  
  1682.   return tangent;
  1683. }
  1684.  
  1685. /* When this routine is called, we have computed a spline representation
  1686.    for the digitized curve.  The question is, how good is it?  If the
  1687.    fit is very good indeed, we might have an error of zero on each
  1688.    point, and then WORST_POINT becomes irrelevant.  But normally, we
  1689.    return the error at the worst point, and the index of that point in
  1690.    WORST_POINT.  The error computation itself is the Euclidean distance
  1691.    from the original curve CURVE to the fitted spline SPLINE.  */
  1692.  
  1693. static real
  1694. find_error (curve_type curve, spline_type spline, unsigned *worst_point)
  1695. {
  1696.   unsigned this_point;
  1697.   real total_error = 0.0;
  1698.   real worst_error = FLT_MIN;
  1699.   
  1700.   *worst_point = CURVE_LENGTH (curve) + 1;   /* A sentinel value.  */
  1701.   
  1702.   for (this_point = 0; this_point < CURVE_LENGTH (curve); this_point++)
  1703.     {
  1704.       real_coordinate_type curve_point = CURVE_POINT (curve, this_point);
  1705.       real t = CURVE_T (curve, this_point);
  1706.       real_coordinate_type spline_point = evaluate_spline (spline, t);
  1707.       real this_error = distance (curve_point, spline_point);
  1708.  
  1709.       if (this_error > worst_error)
  1710.         {
  1711.           *worst_point = this_point;
  1712.           worst_error = this_error;
  1713.         }
  1714.       total_error += this_error;
  1715.     }
  1716.  
  1717.   if (*worst_point == CURVE_LENGTH (curve) + 1)
  1718.     { /* Didn't have any ``worst point''; the error should be zero.  */
  1719.       if (epsilon_equal (total_error, 0.0))
  1720.     {
  1721. /*       LOG ("  Every point fit perfectly.\n"); */
  1722.     }
  1723.       else
  1724.     printf ("No worst point found; something is wrong");
  1725.     }
  1726.   else
  1727.     {
  1728. /*       LOG4 ("  Worst error (at (%.3f,%.3f), point #%u) was %.3f.\n", */
  1729. /*             CURVE_POINT (curve, *worst_point).x, */
  1730. /*             CURVE_POINT (curve, *worst_point).y, *worst_point, worst_error); */
  1731. /*       LOG1 ("  Total error was %.3f.\n", total_error); */
  1732. /*       LOG2 ("  Average error (over %u points) was %.3f.\n", */
  1733. /*             CURVE_LENGTH (curve), total_error / CURVE_LENGTH (curve)); */
  1734.     }
  1735.  
  1736.   return worst_error;
  1737. }
  1738.  
  1739. /* Supposing that we have accepted the error, another question arises:
  1740.    would we be better off just using a straight line?  */
  1741.  
  1742. static boolean
  1743. spline_linear_enough (spline_type *spline, curve_type curve)
  1744. {
  1745.   real A, B, C, slope;
  1746.   unsigned this_point;
  1747.   real distance = 0.0;
  1748.  
  1749. /*   LOG ("Checking linearity:\n"); */
  1750.   
  1751.   /* For a line described by Ax + By + C = 0, the distance d from a
  1752.      point (x0,y0) to that line is:
  1753.  
  1754.      d = | Ax0 + By0 + C | / sqrt (A^2 + B^2).
  1755.  
  1756.      We can find A, B, and C from the starting and ending points,
  1757.      unless the line defined by those two points is vertical.  */
  1758.      
  1759.   if (epsilon_equal (START_POINT (*spline).x, END_POINT (*spline).x))
  1760.     {
  1761.       A = 1;
  1762.       B = 0;
  1763.       C = -START_POINT (*spline).x;
  1764.     }
  1765.   else
  1766.     {
  1767.       /* Plug the spline's starting and ending points into the two-point
  1768.      equation for a line, that is,
  1769.  
  1770.      (y - y1) = ((y2 - y1)/(x2 - x1)) * (x - x1)
  1771.  
  1772.      to get the values for A, B, and C.  */
  1773.  
  1774.       slope = ((END_POINT (*spline).y - START_POINT (*spline).y)
  1775.            / (END_POINT (*spline).x - START_POINT (*spline).x));
  1776.       A = -slope;
  1777.       B = 1;
  1778.       C = slope * START_POINT (*spline).x - START_POINT (*spline).y;
  1779.     }
  1780. /*   LOG3 ("  Line is %.3fx + %.3fy + %.3f = 0.\n", A, B, C); */
  1781.   
  1782.   for (this_point = 0; this_point < CURVE_LENGTH (curve); this_point++)
  1783.     {
  1784.       real t = CURVE_T (curve, this_point);
  1785.       real_coordinate_type spline_point = evaluate_spline (*spline, t);
  1786.       
  1787.       distance += fabs (A * spline_point.x + B * spline_point.y + C)
  1788.                    / sqrt (A * A + B * B);
  1789.     }
  1790. /*   LOG1 ("  Total distance is %.3f, ", distance); */
  1791.  
  1792.   distance /= CURVE_LENGTH (curve);
  1793. /*   LOG1 ("which is %.3f normalized.\n", distance); */
  1794.   
  1795.   /* We want reversion of short curves to splines to be more likely than
  1796.      reversion of long curves, hence the second division by the curve
  1797.      length, for use in `change_bad_lines'.  */
  1798.   SPLINE_LINEARITY (*spline) = distance / CURVE_LENGTH (curve);
  1799. /*   LOG1 ("  Final linearity: %.3f.\n", SPLINE_LINEARITY (*spline)); */
  1800.   
  1801.   return distance < line_threshold;
  1802. }
  1803.  
  1804.  
  1805. /* Unfortunately, we cannot tell in isolation whether a given spline
  1806.    should be changed to a line or not.  That can only be known after the
  1807.    entire curve has been fit to a list of splines.  (The curve is the
  1808.    pixel outline between two corners.)  After subdividing the curve, a
  1809.    line may very well fit a portion of the curve just as well as the
  1810.    spline---but unless a spline is truly close to being a line, it
  1811.    should not be combined with other lines.  */
  1812.  
  1813. static void
  1814. change_bad_lines (spline_list_type *spline_list)
  1815. {
  1816.   unsigned this_spline;
  1817.   boolean found_cubic = false;
  1818.   unsigned length = SPLINE_LIST_LENGTH (*spline_list);
  1819.   
  1820. /*   LOG1 ("\nChecking for bad lines (length %u):\n", length); */
  1821.   
  1822.   /* First see if there are any splines in the fitted shape.  */
  1823.   for (this_spline = 0; this_spline < length; this_spline++)  
  1824.     {
  1825.       if (SPLINE_DEGREE (SPLINE_LIST_ELT (*spline_list, this_spline)) == CUBIC)
  1826.         {
  1827.           found_cubic = true;
  1828.           break;
  1829.         }
  1830.     }
  1831.   
  1832.   /* If so, change lines back to splines (we haven't done anything to
  1833.      their control points, so we only have to change the degree) unless
  1834.      the spline is close enough to being a line.  */
  1835.   if (found_cubic)
  1836.     for (this_spline = 0; this_spline < length; this_spline++)
  1837.       {
  1838.         spline_type s = SPLINE_LIST_ELT (*spline_list, this_spline);
  1839.         
  1840.         if (SPLINE_DEGREE (s) == LINEAR)
  1841.           {
  1842. /*             LOG1 ("  #%u: ", this_spline); */
  1843.             if (SPLINE_LINEARITY (s) > line_reversion_threshold)
  1844.               {
  1845. /*                 LOG ("reverted, "); */
  1846.                 SPLINE_DEGREE (SPLINE_LIST_ELT (*spline_list, this_spline))
  1847.                   = CUBIC;
  1848.               }
  1849. /*             LOG1 ("linearity %.3f.\n", SPLINE_LINEARITY (s)); */
  1850.           }
  1851.       }
  1852.     else
  1853.       {
  1854. /*     LOG ("  No lines.\n"); */
  1855.       }
  1856. }
  1857.  
  1858. /* When we have finished fitting an entire pixel outline to a spline
  1859.    list L, we go through L to ensure that any endpoints that are ``close
  1860.    enough'' (i.e., within `align_threshold') to being the same really
  1861.    are the same.  */
  1862.  
  1863. /* This macro adjusts the AXIS axis on the starting and ending points on
  1864.    a particular spline if necessary.  */
  1865. #define TRY_AXIS(axis)                            \
  1866.   do                                    \
  1867.     {                                    \
  1868.       real delta = fabs (end.axis - start.axis);            \
  1869.                                     \
  1870.       if (!epsilon_equal (delta, 0.0) && delta <= align_threshold)    \
  1871.         {                                \
  1872.           spline_type *next = &NEXT_SPLINE_LIST_ELT (*l, this_spline);    \
  1873.           spline_type *prev = &PREV_SPLINE_LIST_ELT (*l, this_spline);    \
  1874.                                     \
  1875.           START_POINT (*s).axis = END_POINT (*s).axis            \
  1876.             = END_POINT (*prev).axis = START_POINT (*next).axis        \
  1877.             = (start.axis + end.axis) / 2;                \
  1878.           spline_change = true;                        \
  1879.         }                                \
  1880.     }                                    \
  1881.   while (0)
  1882.  
  1883. static void
  1884. align (spline_list_type *l)
  1885. {
  1886.   boolean change;
  1887.   unsigned this_spline;
  1888.   unsigned length = SPLINE_LIST_LENGTH (*l);
  1889.   
  1890. /*   LOG1 ("\nAligning spline list (length %u):\n", length); */
  1891.   
  1892.   do
  1893.     {
  1894.       change = false;
  1895.       
  1896. /*       LOG ("  "); */
  1897.       
  1898.       for (this_spline = 0; this_spline < length; this_spline++) 
  1899.         {
  1900.           boolean spline_change = false;
  1901.           spline_type *s = &SPLINE_LIST_ELT (*l, this_spline);
  1902.           real_coordinate_type start = START_POINT (*s);
  1903.           real_coordinate_type end = END_POINT (*s);
  1904.           
  1905.           TRY_AXIS (x);
  1906.           TRY_AXIS (y);
  1907.           if (spline_change)
  1908.             {
  1909. /*               LOG1 ("%u ", this_spline); */
  1910.               change |= spline_change;
  1911.             }
  1912.         }
  1913. /*       LOG ("\n"); */
  1914.     }
  1915.   while (change);
  1916. }
  1917.  
  1918. /* Lists of array indices (well, that is what we use it for).  */
  1919.  
  1920. static index_list_type
  1921. new_index_list ()
  1922. {
  1923.   index_list_type index_list;
  1924.  
  1925.   index_list.data = NULL;
  1926.   INDEX_LIST_LENGTH (index_list) = 0;
  1927.  
  1928.   return index_list;
  1929. }
  1930.  
  1931.  
  1932. static void
  1933. free_index_list (index_list_type *index_list)
  1934. {
  1935.   if (INDEX_LIST_LENGTH (*index_list) > 0)
  1936.     {
  1937.       g_free (index_list->data);
  1938.       index_list->data = NULL;
  1939.       INDEX_LIST_LENGTH (*index_list) = 0;
  1940.     }
  1941. }
  1942.  
  1943.  
  1944. static void
  1945. append_index (index_list_type *list, unsigned new_index)
  1946. {
  1947.   INDEX_LIST_LENGTH (*list)++;
  1948.   list->data = (unsigned *)g_realloc(list->data,(INDEX_LIST_LENGTH (*list)) * sizeof(unsigned));
  1949. /*   XRETALLOC (list->data, INDEX_LIST_LENGTH (*list), unsigned); */
  1950.   list->data[INDEX_LIST_LENGTH (*list) - 1] = new_index;
  1951. }
  1952.