tizen 2.3.1 release
[framework/graphics/freetype.git] / src / autofit / aflatin.c
1 /***************************************************************************/
2 /*                                                                         */
3 /*  aflatin.c                                                              */
4 /*                                                                         */
5 /*    Auto-fitter hinting routines for latin writing system (body).        */
6 /*                                                                         */
7 /*  Copyright 2003-2014 by                                                 */
8 /*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
9 /*                                                                         */
10 /*  This file is part of the FreeType project, and may only be used,       */
11 /*  modified, and distributed under the terms of the FreeType project      */
12 /*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
13 /*  this file you indicate that you have read the license and              */
14 /*  understand and accept it fully.                                        */
15 /*                                                                         */
16 /***************************************************************************/
17
18
19 #include <ft2build.h>
20 #include FT_ADVANCES_H
21 #include FT_INTERNAL_DEBUG_H
22
23 #include "afglobal.h"
24 #include "afpic.h"
25 #include "aflatin.h"
26 #include "aferrors.h"
27
28
29 #ifdef AF_CONFIG_OPTION_USE_WARPER
30 #include "afwarp.h"
31 #endif
32
33
34   /*************************************************************************/
35   /*                                                                       */
36   /* The macro FT_COMPONENT is used in trace mode.  It is an implicit      */
37   /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log  */
38   /* messages during execution.                                            */
39   /*                                                                       */
40 #undef  FT_COMPONENT
41 #define FT_COMPONENT  trace_aflatin
42
43
44   /*************************************************************************/
45   /*************************************************************************/
46   /*****                                                               *****/
47   /*****            L A T I N   G L O B A L   M E T R I C S            *****/
48   /*****                                                               *****/
49   /*************************************************************************/
50   /*************************************************************************/
51
52
53   /* Find segments and links, compute all stem widths, and initialize */
54   /* standard width and height for the glyph with given charcode.     */
55
56   FT_LOCAL_DEF( void )
57   af_latin_metrics_init_widths( AF_LatinMetrics  metrics,
58                                 FT_Face          face )
59   {
60     /* scan the array of segments in each direction */
61     AF_GlyphHintsRec  hints[1];
62
63
64     FT_TRACE5(( "\n"
65                 "latin standard widths computation (style `%s')\n"
66                 "=====================================================\n"
67                 "\n",
68                 af_style_names[metrics->root.style_class->style] ));
69
70     af_glyph_hints_init( hints, face->memory );
71
72     metrics->axis[AF_DIMENSION_HORZ].width_count = 0;
73     metrics->axis[AF_DIMENSION_VERT].width_count = 0;
74
75     {
76       FT_Error            error;
77       FT_ULong            glyph_index;
78       FT_Long             y_offset;
79       int                 dim;
80       AF_LatinMetricsRec  dummy[1];
81       AF_Scaler           scaler = &dummy->root.scaler;
82
83 #ifdef FT_CONFIG_OPTION_PIC
84       AF_FaceGlobals  globals = metrics->root.globals;
85 #endif
86
87       AF_StyleClass   style_class  = metrics->root.style_class;
88       AF_ScriptClass  script_class = AF_SCRIPT_CLASSES_GET
89                                        [style_class->script];
90
91       FT_UInt32  standard_char;
92
93
94       /*
95        * We check more than a single standard character to catch features
96        * like `c2sc' (small caps from caps) that don't contain lowercase
97        * letters by definition, or other features that mainly operate on
98        * numerals.
99        */
100
101       standard_char = script_class->standard_char1;
102       af_get_char_index( &metrics->root,
103                          standard_char,
104                          &glyph_index,
105                          &y_offset );
106       if ( !glyph_index )
107       {
108         if ( script_class->standard_char2 )
109         {
110           standard_char = script_class->standard_char2;
111           af_get_char_index( &metrics->root,
112                              standard_char,
113                              &glyph_index,
114                              &y_offset );
115           if ( !glyph_index )
116           {
117             if ( script_class->standard_char3 )
118             {
119               standard_char = script_class->standard_char3;
120               af_get_char_index( &metrics->root,
121                                  standard_char,
122                                  &glyph_index,
123                                  &y_offset );
124               if ( !glyph_index )
125                 goto Exit;
126             }
127             else
128               goto Exit;
129           }
130         }
131         else
132           goto Exit;
133       }
134
135       FT_TRACE5(( "standard character: U+%04lX (glyph index %d)\n",
136                   standard_char, glyph_index ));
137
138       error = FT_Load_Glyph( face, glyph_index, FT_LOAD_NO_SCALE );
139       if ( error || face->glyph->outline.n_points <= 0 )
140         goto Exit;
141
142       FT_ZERO( dummy );
143
144       dummy->units_per_em = metrics->units_per_em;
145
146       scaler->x_scale = 0x10000L;
147       scaler->y_scale = 0x10000L;
148       scaler->x_delta = 0;
149       scaler->y_delta = 0;
150
151       scaler->face        = face;
152       scaler->render_mode = FT_RENDER_MODE_NORMAL;
153       scaler->flags       = 0;
154
155       af_glyph_hints_rescale( hints, (AF_StyleMetrics)dummy );
156
157       error = af_glyph_hints_reload( hints, &face->glyph->outline );
158       if ( error )
159         goto Exit;
160
161       for ( dim = 0; dim < AF_DIMENSION_MAX; dim++ )
162       {
163         AF_LatinAxis  axis    = &metrics->axis[dim];
164         AF_AxisHints  axhints = &hints->axis[dim];
165         AF_Segment    seg, limit, link;
166         FT_UInt       num_widths = 0;
167
168
169         error = af_latin_hints_compute_segments( hints,
170                                                  (AF_Dimension)dim );
171         if ( error )
172           goto Exit;
173
174         /*
175          *  We assume that the glyphs selected for the stem width
176          *  computation are `featureless' enough so that the linking
177          *  algorithm works fine without adjustments of its scoring
178          *  function.
179          */
180         af_latin_hints_link_segments( hints,
181                                       0,
182                                       NULL,
183                                       (AF_Dimension)dim );
184
185         seg   = axhints->segments;
186         limit = seg + axhints->num_segments;
187
188         for ( ; seg < limit; seg++ )
189         {
190           link = seg->link;
191
192           /* we only consider stem segments there! */
193           if ( link && link->link == seg && link > seg )
194           {
195             FT_Pos  dist;
196
197
198             dist = seg->pos - link->pos;
199             if ( dist < 0 )
200               dist = -dist;
201
202             if ( num_widths < AF_LATIN_MAX_WIDTHS )
203               axis->widths[num_widths++].org = dist;
204           }
205         }
206
207         /* this also replaces multiple almost identical stem widths */
208         /* with a single one (the value 100 is heuristic)           */
209         af_sort_and_quantize_widths( &num_widths, axis->widths,
210                                      dummy->units_per_em / 100 );
211         axis->width_count = num_widths;
212       }
213
214     Exit:
215       for ( dim = 0; dim < AF_DIMENSION_MAX; dim++ )
216       {
217         AF_LatinAxis  axis = &metrics->axis[dim];
218         FT_Pos        stdw;
219
220
221         stdw = ( axis->width_count > 0 ) ? axis->widths[0].org
222                                          : AF_LATIN_CONSTANT( metrics, 50 );
223
224         /* let's try 20% of the smallest width */
225         axis->edge_distance_threshold = stdw / 5;
226         axis->standard_width          = stdw;
227         axis->extra_light             = 0;
228
229 #ifdef FT_DEBUG_LEVEL_TRACE
230         {
231           FT_UInt  i;
232
233
234           FT_TRACE5(( "%s widths:\n",
235                       dim == AF_DIMENSION_VERT ? "horizontal"
236                                                : "vertical" ));
237
238           FT_TRACE5(( "  %d (standard)", axis->standard_width ));
239           for ( i = 1; i < axis->width_count; i++ )
240             FT_TRACE5(( " %d", axis->widths[i].org ));
241
242           FT_TRACE5(( "\n" ));
243         }
244 #endif
245       }
246     }
247
248     FT_TRACE5(( "\n" ));
249
250     af_glyph_hints_done( hints );
251   }
252
253
254   /* Find all blue zones.  Flat segments give the reference points, */
255   /* round segments the overshoot positions.                        */
256
257   static void
258   af_latin_metrics_init_blues( AF_LatinMetrics  metrics,
259                                FT_Face          face )
260   {
261     FT_Pos        flats [AF_BLUE_STRING_MAX_LEN];
262     FT_Pos        rounds[AF_BLUE_STRING_MAX_LEN];
263
264     FT_Int        num_flats;
265     FT_Int        num_rounds;
266
267     AF_LatinBlue  blue;
268     FT_Error      error;
269     AF_LatinAxis  axis = &metrics->axis[AF_DIMENSION_VERT];
270     FT_Outline    outline;
271
272     AF_StyleClass  sc = metrics->root.style_class;
273
274     AF_Blue_Stringset         bss = sc->blue_stringset;
275     const AF_Blue_StringRec*  bs  = &af_blue_stringsets[bss];
276
277
278     /* we walk over the blue character strings as specified in the */
279     /* style's entry in the `af_blue_stringset' array              */
280
281     FT_TRACE5(( "latin blue zones computation\n"
282                 "============================\n"
283                 "\n" ));
284
285     for ( ; bs->string != AF_BLUE_STRING_MAX; bs++ )
286     {
287       const char*  p = &af_blue_strings[bs->string];
288       FT_Pos*      blue_ref;
289       FT_Pos*      blue_shoot;
290
291
292 #ifdef FT_DEBUG_LEVEL_TRACE
293       {
294         FT_Bool  have_flag = 0;
295
296
297         FT_TRACE5(( "blue zone %d", axis->blue_count ));
298
299         if ( bs->properties )
300         {
301           FT_TRACE5(( " (" ));
302
303           if ( AF_LATIN_IS_TOP_BLUE( bs ) )
304           {
305             FT_TRACE5(( "top" ));
306             have_flag = 1;
307           }
308
309           if ( AF_LATIN_IS_NEUTRAL_BLUE( bs ) )
310           {
311             if ( have_flag )
312               FT_TRACE5(( ", " ));
313             FT_TRACE5(( "neutral" ));
314             have_flag = 1;
315           }
316
317           if ( AF_LATIN_IS_X_HEIGHT_BLUE( bs ) )
318           {
319             if ( have_flag )
320               FT_TRACE5(( ", " ));
321             FT_TRACE5(( "small top" ));
322             have_flag = 1;
323           }
324
325           if ( AF_LATIN_IS_LONG_BLUE( bs ) )
326           {
327             if ( have_flag )
328               FT_TRACE5(( ", " ));
329             FT_TRACE5(( "long" ));
330           }
331
332           FT_TRACE5(( ")" ));
333         }
334
335         FT_TRACE5(( ":\n" ));
336       }
337 #endif /* FT_DEBUG_LEVEL_TRACE */
338
339       num_flats  = 0;
340       num_rounds = 0;
341
342       while ( *p )
343       {
344         FT_ULong    ch;
345         FT_ULong    glyph_index;
346         FT_Long     y_offset;
347         FT_Pos      best_y;                            /* same as points.y */
348         FT_Int      best_point, best_contour_first, best_contour_last;
349         FT_Vector*  points;
350         FT_Bool     round = 0;
351
352
353         GET_UTF8_CHAR( ch, p );
354
355         /* load the character in the face -- skip unknown or empty ones */
356         af_get_char_index( &metrics->root, ch, &glyph_index, &y_offset );
357         if ( glyph_index == 0 )
358         {
359           FT_TRACE5(( "  U+%04lX unavailable\n", ch ));
360           continue;
361         }
362
363         error   = FT_Load_Glyph( face, glyph_index, FT_LOAD_NO_SCALE );
364         outline = face->glyph->outline;
365         if ( error || outline.n_points <= 0 )
366         {
367           FT_TRACE5(( "  U+%04lX contains no outlines\n", ch ));
368           continue;
369         }
370
371         /* now compute min or max point indices and coordinates */
372         points             = outline.points;
373         best_point         = -1;
374         best_y             = 0;  /* make compiler happy */
375         best_contour_first = 0;  /* ditto */
376         best_contour_last  = 0;  /* ditto */
377
378         {
379           FT_Int  nn;
380           FT_Int  first = 0;
381           FT_Int  last  = -1;
382
383
384           for ( nn = 0; nn < outline.n_contours; first = last + 1, nn++ )
385           {
386             FT_Int  old_best_point = best_point;
387             FT_Int  pp;
388
389
390             last = outline.contours[nn];
391
392             /* Avoid single-point contours since they are never rasterized. */
393             /* In some fonts, they correspond to mark attachment points     */
394             /* that are way outside of the glyph's real outline.            */
395             if ( last <= first )
396               continue;
397
398             if ( AF_LATIN_IS_TOP_BLUE( bs ) )
399             {
400               for ( pp = first; pp <= last; pp++ )
401                 if ( best_point < 0 || points[pp].y > best_y )
402                 {
403                   best_point = pp;
404                   best_y     = points[pp].y;
405                 }
406             }
407             else
408             {
409               for ( pp = first; pp <= last; pp++ )
410                 if ( best_point < 0 || points[pp].y < best_y )
411                 {
412                   best_point = pp;
413                   best_y     = points[pp].y;
414                 }
415             }
416
417             if ( best_point != old_best_point )
418             {
419               best_contour_first = first;
420               best_contour_last  = last;
421             }
422           }
423         }
424
425         /* now check whether the point belongs to a straight or round   */
426         /* segment; we first need to find in which contour the extremum */
427         /* lies, then inspect its previous and next points              */
428         if ( best_point >= 0 )
429         {
430           FT_Pos  best_x = points[best_point].x;
431           FT_Int  prev, next;
432           FT_Int  best_segment_first, best_segment_last;
433           FT_Int  best_on_point_first, best_on_point_last;
434           FT_Pos  dist;
435
436
437           best_segment_first = best_point;
438           best_segment_last  = best_point;
439
440           if ( FT_CURVE_TAG( outline.tags[best_point] ) == FT_CURVE_TAG_ON )
441           {
442             best_on_point_first = best_point;
443             best_on_point_last  = best_point;
444           }
445           else
446           {
447             best_on_point_first = -1;
448             best_on_point_last  = -1;
449           }
450
451           /* look for the previous and next points on the contour  */
452           /* that are not on the same Y coordinate, then threshold */
453           /* the `closeness'...                                    */
454           prev = best_point;
455           next = prev;
456
457           do
458           {
459             if ( prev > best_contour_first )
460               prev--;
461             else
462               prev = best_contour_last;
463
464             dist = FT_ABS( points[prev].y - best_y );
465             /* accept a small distance or a small angle (both values are */
466             /* heuristic; value 20 corresponds to approx. 2.9 degrees)   */
467             if ( dist > 5 )
468               if ( FT_ABS( points[prev].x - best_x ) <= 20 * dist )
469                 break;
470
471             best_segment_first = prev;
472
473             if ( FT_CURVE_TAG( outline.tags[prev] ) == FT_CURVE_TAG_ON )
474             {
475               best_on_point_first = prev;
476               if ( best_on_point_last < 0 )
477                 best_on_point_last = prev;
478             }
479
480           } while ( prev != best_point );
481
482           do
483           {
484             if ( next < best_contour_last )
485               next++;
486             else
487               next = best_contour_first;
488
489             dist = FT_ABS( points[next].y - best_y );
490             if ( dist > 5 )
491               if ( FT_ABS( points[next].x - best_x ) <= 20 * dist )
492                 break;
493
494             best_segment_last = next;
495
496             if ( FT_CURVE_TAG( outline.tags[next] ) == FT_CURVE_TAG_ON )
497             {
498               best_on_point_last = next;
499               if ( best_on_point_first < 0 )
500                 best_on_point_first = next;
501             }
502
503           } while ( next != best_point );
504
505           if ( AF_LATIN_IS_LONG_BLUE( bs ) )
506           {
507             /* If this flag is set, we have an additional constraint to  */
508             /* get the blue zone distance: Find a segment of the topmost */
509             /* (or bottommost) contour that is longer than a heuristic   */
510             /* threshold.  This ensures that small bumps in the outline  */
511             /* are ignored (for example, the `vertical serifs' found in  */
512             /* many Hebrew glyph designs).                               */
513
514             /* If this segment is long enough, we are done.  Otherwise,  */
515             /* search the segment next to the extremum that is long      */
516             /* enough, has the same direction, and a not too large       */
517             /* vertical distance from the extremum.  Note that the       */
518             /* algorithm doesn't check whether the found segment is      */
519             /* actually the one (vertically) nearest to the extremum.    */
520
521             /* heuristic threshold value */
522             FT_Pos  length_threshold = metrics->units_per_em / 25;
523
524
525             dist = FT_ABS( points[best_segment_last].x -
526                              points[best_segment_first].x );
527
528             if ( dist < length_threshold                       &&
529                  best_segment_last - best_segment_first + 2 <=
530                    best_contour_last - best_contour_first      )
531             {
532               /* heuristic threshold value */
533               FT_Pos  height_threshold = metrics->units_per_em / 4;
534
535               FT_Int   first;
536               FT_Int   last;
537               FT_Bool  hit;
538
539               /* we intentionally declare these two variables        */
540               /* outside of the loop since various compilers emit    */
541               /* incorrect warning messages otherwise, talking about */
542               /* `possibly uninitialized variables'                  */
543               FT_Int  p_first = 0;            /* make compiler happy */
544               FT_Int  p_last  = 0;
545
546               FT_Bool  left2right;
547
548
549               /* compute direction */
550               prev = best_point;
551
552               do
553               {
554                 if ( prev > best_contour_first )
555                   prev--;
556                 else
557                   prev = best_contour_last;
558
559                 if ( points[prev].x != best_x )
560                   break;
561
562               } while ( prev != best_point );
563
564               /* skip glyph for the degenerate case */
565               if ( prev == best_point )
566                 continue;
567
568               left2right = FT_BOOL( points[prev].x < points[best_point].x );
569
570               first = best_segment_last;
571               last  = first;
572               hit   = 0;
573
574               do
575               {
576                 FT_Bool  l2r;
577                 FT_Pos   d;
578
579
580                 if ( !hit )
581                 {
582                   /* no hit; adjust first point */
583                   first = last;
584
585                   /* also adjust first and last on point */
586                   if ( FT_CURVE_TAG( outline.tags[first] ) ==
587                          FT_CURVE_TAG_ON )
588                   {
589                     p_first = first;
590                     p_last  = first;
591                   }
592                   else
593                   {
594                     p_first = -1;
595                     p_last  = -1;
596                   }
597
598                   hit = 1;
599                 }
600
601                 if ( last < best_contour_last )
602                   last++;
603                 else
604                   last = best_contour_first;
605
606                 if ( FT_ABS( best_y - points[first].y ) > height_threshold )
607                 {
608                   /* vertical distance too large */
609                   hit = 0;
610                   continue;
611                 }
612
613                 /* same test as above */
614                 dist = FT_ABS( points[last].y - points[first].y );
615                 if ( dist > 5 )
616                   if ( FT_ABS( points[last].x - points[first].x ) <=
617                          20 * dist )
618                   {
619                     hit = 0;
620                     continue;
621                   }
622
623                 if ( FT_CURVE_TAG( outline.tags[last] ) == FT_CURVE_TAG_ON )
624                 {
625                   p_last = last;
626                   if ( p_first < 0 )
627                     p_first = last;
628                 }
629
630                 l2r = FT_BOOL( points[first].x < points[last].x );
631                 d   = FT_ABS( points[last].x - points[first].x );
632
633                 if ( l2r == left2right     &&
634                      d >= length_threshold )
635                 {
636                   /* all constraints are met; update segment after finding */
637                   /* its end                                               */
638                   do
639                   {
640                     if ( last < best_contour_last )
641                       last++;
642                     else
643                       last = best_contour_first;
644
645                     d = FT_ABS( points[last].y - points[first].y );
646                     if ( d > 5 )
647                       if ( FT_ABS( points[next].x - points[first].x ) <=
648                              20 * dist )
649                       {
650                         if ( last > best_contour_first )
651                           last--;
652                         else
653                           last = best_contour_last;
654                         break;
655                       }
656
657                     p_last = last;
658
659                     if ( FT_CURVE_TAG( outline.tags[last] ) ==
660                            FT_CURVE_TAG_ON )
661                     {
662                       p_last = last;
663                       if ( p_first < 0 )
664                         p_first = last;
665                     }
666
667                   } while ( last != best_segment_first );
668
669                   best_y = points[first].y;
670
671                   best_segment_first = first;
672                   best_segment_last  = last;
673
674                   best_on_point_first = p_first;
675                   best_on_point_last  = p_last;
676
677                   break;
678                 }
679
680               } while ( last != best_segment_first );
681             }
682           }
683
684           /* for computing blue zones, we add the y offset as returned */
685           /* by the currently used OpenType feature -- for example,    */
686           /* superscript glyphs might be identical to subscript glyphs */
687           /* with a vertical shift                                     */
688           best_y += y_offset;
689
690           FT_TRACE5(( "  U+%04lX: best_y = %5ld", ch, best_y ));
691
692           /* now set the `round' flag depending on the segment's kind: */
693           /*                                                           */
694           /* - if the horizontal distance between the first and last   */
695           /*   `on' point is larger than upem/8 (value 8 is heuristic) */
696           /*   we have a flat segment                                  */
697           /* - if either the first or the last point of the segment is */
698           /*   an `off' point, the segment is round, otherwise it is   */
699           /*   flat                                                    */
700           if ( best_on_point_first >= 0                               &&
701                best_on_point_last >= 0                                &&
702                (FT_UInt)( FT_ABS( points[best_on_point_last].x -
703                                   points[best_on_point_first].x ) ) >
704                  metrics->units_per_em / 8                            )
705             round = 0;
706           else
707             round = FT_BOOL(
708                       FT_CURVE_TAG( outline.tags[best_segment_first] ) !=
709                         FT_CURVE_TAG_ON                                   ||
710                       FT_CURVE_TAG( outline.tags[best_segment_last]  ) !=
711                         FT_CURVE_TAG_ON                                   );
712
713           if ( round && AF_LATIN_IS_NEUTRAL_BLUE( bs ) )
714           {
715             /* only use flat segments for a neutral blue zone */
716             FT_TRACE5(( " (round, skipped)\n" ));
717             continue;
718           }
719
720           FT_TRACE5(( " (%s)\n", round ? "round" : "flat" ));
721         }
722
723         if ( round )
724           rounds[num_rounds++] = best_y;
725         else
726           flats[num_flats++]   = best_y;
727       }
728
729       if ( num_flats == 0 && num_rounds == 0 )
730       {
731         /*
732          *  we couldn't find a single glyph to compute this blue zone,
733          *  we will simply ignore it then
734          */
735         FT_TRACE5(( "  empty\n" ));
736         continue;
737       }
738
739       /* we have computed the contents of the `rounds' and `flats' tables, */
740       /* now determine the reference and overshoot position of the blue -- */
741       /* we simply take the median value after a simple sort               */
742       af_sort_pos( num_rounds, rounds );
743       af_sort_pos( num_flats,  flats );
744
745       blue       = &axis->blues[axis->blue_count];
746       blue_ref   = &blue->ref.org;
747       blue_shoot = &blue->shoot.org;
748
749       axis->blue_count++;
750
751       if ( num_flats == 0 )
752       {
753         *blue_ref   =
754         *blue_shoot = rounds[num_rounds / 2];
755       }
756       else if ( num_rounds == 0 )
757       {
758         *blue_ref   =
759         *blue_shoot = flats[num_flats / 2];
760       }
761       else
762       {
763         *blue_ref   = flats [num_flats  / 2];
764         *blue_shoot = rounds[num_rounds / 2];
765       }
766
767       /* there are sometimes problems: if the overshoot position of top     */
768       /* zones is under its reference position, or the opposite for bottom  */
769       /* zones.  We must thus check everything there and correct the errors */
770       if ( *blue_shoot != *blue_ref )
771       {
772         FT_Pos   ref      = *blue_ref;
773         FT_Pos   shoot    = *blue_shoot;
774         FT_Bool  over_ref = FT_BOOL( shoot > ref );
775
776
777         if ( AF_LATIN_IS_TOP_BLUE( bs ) ^ over_ref )
778         {
779           *blue_ref   =
780           *blue_shoot = ( shoot + ref ) / 2;
781
782           FT_TRACE5(( "  [overshoot smaller than reference,"
783                       " taking mean value]\n" ));
784         }
785       }
786
787       blue->flags = 0;
788       if ( AF_LATIN_IS_TOP_BLUE( bs ) )
789         blue->flags |= AF_LATIN_BLUE_TOP;
790       if ( AF_LATIN_IS_NEUTRAL_BLUE( bs ) )
791         blue->flags |= AF_LATIN_BLUE_NEUTRAL;
792
793       /*
794        * The following flag is used later to adjust the y and x scales
795        * in order to optimize the pixel grid alignment of the top of small
796        * letters.
797        */
798       if ( AF_LATIN_IS_X_HEIGHT_BLUE( bs ) )
799         blue->flags |= AF_LATIN_BLUE_ADJUSTMENT;
800
801       FT_TRACE5(( "    -> reference = %ld\n"
802                   "       overshoot = %ld\n",
803                   *blue_ref, *blue_shoot ));
804     }
805
806     FT_TRACE5(( "\n" ));
807
808     return;
809   }
810
811
812   /* Check whether all ASCII digits have the same advance width. */
813
814   FT_LOCAL_DEF( void )
815   af_latin_metrics_check_digits( AF_LatinMetrics  metrics,
816                                  FT_Face          face )
817   {
818     FT_UInt   i;
819     FT_Bool   started = 0, same_width = 1;
820     FT_Fixed  advance, old_advance = 0;
821
822
823     /* digit `0' is 0x30 in all supported charmaps */
824     for ( i = 0x30; i <= 0x39; i++ )
825     {
826       FT_ULong  glyph_index;
827       FT_Long   y_offset;
828
829
830       af_get_char_index( &metrics->root, i, &glyph_index, &y_offset );
831       if ( glyph_index == 0 )
832         continue;
833
834       if ( FT_Get_Advance( face, glyph_index,
835                            FT_LOAD_NO_SCALE         |
836                            FT_LOAD_NO_HINTING       |
837                            FT_LOAD_IGNORE_TRANSFORM,
838                            &advance ) )
839         continue;
840
841       if ( started )
842       {
843         if ( advance != old_advance )
844         {
845           same_width = 0;
846           break;
847         }
848       }
849       else
850       {
851         old_advance = advance;
852         started     = 1;
853       }
854     }
855
856     metrics->root.digits_have_same_width = same_width;
857   }
858
859
860   /* Initialize global metrics. */
861
862   FT_LOCAL_DEF( FT_Error )
863   af_latin_metrics_init( AF_LatinMetrics  metrics,
864                          FT_Face          face )
865   {
866     FT_CharMap  oldmap = face->charmap;
867
868
869     metrics->units_per_em = face->units_per_EM;
870
871     if ( !FT_Select_Charmap( face, FT_ENCODING_UNICODE ) )
872     {
873       af_latin_metrics_init_widths( metrics, face );
874       af_latin_metrics_init_blues( metrics, face );
875       af_latin_metrics_check_digits( metrics, face );
876     }
877
878     FT_Set_Charmap( face, oldmap );
879     return FT_Err_Ok;
880   }
881
882
883   /* Adjust scaling value, then scale and shift widths   */
884   /* and blue zones (if applicable) for given dimension. */
885
886   static void
887   af_latin_metrics_scale_dim( AF_LatinMetrics  metrics,
888                               AF_Scaler        scaler,
889                               AF_Dimension     dim )
890   {
891     FT_Fixed      scale;
892     FT_Pos        delta;
893     AF_LatinAxis  axis;
894     FT_UInt       nn;
895
896
897     if ( dim == AF_DIMENSION_HORZ )
898     {
899       scale = scaler->x_scale;
900       delta = scaler->x_delta;
901     }
902     else
903     {
904       scale = scaler->y_scale;
905       delta = scaler->y_delta;
906     }
907
908     axis = &metrics->axis[dim];
909
910     if ( axis->org_scale == scale && axis->org_delta == delta )
911       return;
912
913     axis->org_scale = scale;
914     axis->org_delta = delta;
915
916     /*
917      * correct X and Y scale to optimize the alignment of the top of small
918      * letters to the pixel grid
919      */
920     {
921       AF_LatinAxis  Axis = &metrics->axis[AF_DIMENSION_VERT];
922       AF_LatinBlue  blue = NULL;
923
924
925       for ( nn = 0; nn < Axis->blue_count; nn++ )
926       {
927         if ( Axis->blues[nn].flags & AF_LATIN_BLUE_ADJUSTMENT )
928         {
929           blue = &Axis->blues[nn];
930           break;
931         }
932       }
933
934       if ( blue )
935       {
936         FT_Pos   scaled;
937         FT_Pos   threshold;
938         FT_Pos   fitted;
939         FT_UInt  limit;
940         FT_UInt  ppem;
941
942
943         scaled    = FT_MulFix( blue->shoot.org, scaler->y_scale );
944         ppem      = metrics->root.scaler.face->size->metrics.x_ppem;
945         limit     = metrics->root.globals->increase_x_height;
946         threshold = 40;
947
948         /* if the `increase-x-height' property is active, */
949         /* we round up much more often                    */
950         if ( limit                                 &&
951              ppem <= limit                         &&
952              ppem >= AF_PROP_INCREASE_X_HEIGHT_MIN )
953           threshold = 52;
954
955         fitted = ( scaled + threshold ) & ~63;
956
957         if ( scaled != fitted )
958         {
959 #if 0
960           if ( dim == AF_DIMENSION_HORZ )
961           {
962             if ( fitted < scaled )
963               scale -= scale / 50;  /* scale *= 0.98 */
964           }
965           else
966 #endif
967           if ( dim == AF_DIMENSION_VERT )
968           {
969             scale = FT_MulDiv( scale, fitted, scaled );
970
971             FT_TRACE5((
972               "af_latin_metrics_scale_dim:"
973               " x height alignment (style `%s'):\n"
974               "                           "
975               " vertical scaling changed from %.4f to %.4f (by %d%%)\n"
976               "\n",
977               af_style_names[metrics->root.style_class->style],
978               axis->org_scale / 65536.0,
979               scale / 65536.0,
980               ( fitted - scaled ) * 100 / scaled ));
981           }
982         }
983       }
984     }
985
986     axis->scale = scale;
987     axis->delta = delta;
988
989     if ( dim == AF_DIMENSION_HORZ )
990     {
991       metrics->root.scaler.x_scale = scale;
992       metrics->root.scaler.x_delta = delta;
993     }
994     else
995     {
996       metrics->root.scaler.y_scale = scale;
997       metrics->root.scaler.y_delta = delta;
998     }
999
1000     FT_TRACE5(( "%s widths (style `%s')\n",
1001                 dim == AF_DIMENSION_HORZ ? "horizontal" : "vertical",
1002                 af_style_names[metrics->root.style_class->style] ));
1003
1004     /* scale the widths */
1005     for ( nn = 0; nn < axis->width_count; nn++ )
1006     {
1007       AF_Width  width = axis->widths + nn;
1008
1009
1010       width->cur = FT_MulFix( width->org, scale );
1011       width->fit = width->cur;
1012
1013       FT_TRACE5(( "  %d scaled to %.2f\n",
1014                   width->org,
1015                   width->cur / 64.0 ));
1016     }
1017
1018     FT_TRACE5(( "\n" ));
1019
1020     /* an extra-light axis corresponds to a standard width that is */
1021     /* smaller than 5/8 pixels                                     */
1022     axis->extra_light =
1023       (FT_Bool)( FT_MulFix( axis->standard_width, scale ) < 32 + 8 );
1024
1025 #ifdef FT_DEBUG_LEVEL_TRACE
1026     if ( axis->extra_light )
1027       FT_TRACE5(( "`%s' style is extra light (at current resolution)\n"
1028                   "\n",
1029                   af_style_names[metrics->root.style_class->style] ));
1030 #endif
1031
1032     if ( dim == AF_DIMENSION_VERT )
1033     {
1034       FT_TRACE5(( "blue zones (style `%s')\n",
1035                   af_style_names[metrics->root.style_class->style] ));
1036
1037       /* scale the blue zones */
1038       for ( nn = 0; nn < axis->blue_count; nn++ )
1039       {
1040         AF_LatinBlue  blue = &axis->blues[nn];
1041         FT_Pos        dist;
1042
1043
1044         blue->ref.cur   = FT_MulFix( blue->ref.org, scale ) + delta;
1045         blue->ref.fit   = blue->ref.cur;
1046         blue->shoot.cur = FT_MulFix( blue->shoot.org, scale ) + delta;
1047         blue->shoot.fit = blue->shoot.cur;
1048         blue->flags    &= ~AF_LATIN_BLUE_ACTIVE;
1049
1050         /* a blue zone is only active if it is less than 3/4 pixels tall */
1051         dist = FT_MulFix( blue->ref.org - blue->shoot.org, scale );
1052         if ( dist <= 48 && dist >= -48 )
1053         {
1054 #if 0
1055           FT_Pos  delta1;
1056 #endif
1057           FT_Pos  delta2;
1058
1059
1060           /* use discrete values for blue zone widths */
1061
1062 #if 0
1063
1064           /* generic, original code */
1065           delta1 = blue->shoot.org - blue->ref.org;
1066           delta2 = delta1;
1067           if ( delta1 < 0 )
1068             delta2 = -delta2;
1069
1070           delta2 = FT_MulFix( delta2, scale );
1071
1072           if ( delta2 < 32 )
1073             delta2 = 0;
1074           else if ( delta2 < 64 )
1075             delta2 = 32 + ( ( ( delta2 - 32 ) + 16 ) & ~31 );
1076           else
1077             delta2 = FT_PIX_ROUND( delta2 );
1078
1079           if ( delta1 < 0 )
1080             delta2 = -delta2;
1081
1082           blue->ref.fit   = FT_PIX_ROUND( blue->ref.cur );
1083           blue->shoot.fit = blue->ref.fit + delta2;
1084
1085 #else
1086
1087           /* simplified version due to abs(dist) <= 48 */
1088           delta2 = dist;
1089           if ( dist < 0 )
1090             delta2 = -delta2;
1091
1092           if ( delta2 < 32 )
1093             delta2 = 0;
1094           else if ( delta2 < 48 )
1095             delta2 = 32;
1096           else
1097             delta2 = 64;
1098
1099           if ( dist < 0 )
1100             delta2 = -delta2;
1101
1102           blue->ref.fit   = FT_PIX_ROUND( blue->ref.cur );
1103           blue->shoot.fit = blue->ref.fit - delta2;
1104
1105 #endif
1106
1107           blue->flags |= AF_LATIN_BLUE_ACTIVE;
1108
1109           FT_TRACE5(( "  reference %d: %d scaled to %.2f%s\n"
1110                       "  overshoot %d: %d scaled to %.2f%s\n",
1111                       nn,
1112                       blue->ref.org,
1113                       blue->ref.fit / 64.0,
1114                       blue->flags & AF_LATIN_BLUE_ACTIVE ? ""
1115                                                          : " (inactive)",
1116                       nn,
1117                       blue->shoot.org,
1118                       blue->shoot.fit / 64.0,
1119                       blue->flags & AF_LATIN_BLUE_ACTIVE ? ""
1120                                                          : " (inactive)" ));
1121         }
1122       }
1123     }
1124   }
1125
1126
1127   /* Scale global values in both directions. */
1128
1129   FT_LOCAL_DEF( void )
1130   af_latin_metrics_scale( AF_LatinMetrics  metrics,
1131                           AF_Scaler        scaler )
1132   {
1133     metrics->root.scaler.render_mode = scaler->render_mode;
1134     metrics->root.scaler.face        = scaler->face;
1135     metrics->root.scaler.flags       = scaler->flags;
1136
1137     af_latin_metrics_scale_dim( metrics, scaler, AF_DIMENSION_HORZ );
1138     af_latin_metrics_scale_dim( metrics, scaler, AF_DIMENSION_VERT );
1139   }
1140
1141
1142   /*************************************************************************/
1143   /*************************************************************************/
1144   /*****                                                               *****/
1145   /*****           L A T I N   G L Y P H   A N A L Y S I S             *****/
1146   /*****                                                               *****/
1147   /*************************************************************************/
1148   /*************************************************************************/
1149
1150
1151   /* Walk over all contours and compute its segments. */
1152
1153   FT_LOCAL_DEF( FT_Error )
1154   af_latin_hints_compute_segments( AF_GlyphHints  hints,
1155                                    AF_Dimension   dim )
1156   {
1157     AF_AxisHints   axis          = &hints->axis[dim];
1158     FT_Memory      memory        = hints->memory;
1159     FT_Error       error         = FT_Err_Ok;
1160     AF_Segment     segment       = NULL;
1161     AF_SegmentRec  seg0;
1162     AF_Point*      contour       = hints->contours;
1163     AF_Point*      contour_limit = contour + hints->num_contours;
1164     AF_Direction   major_dir, segment_dir;
1165
1166
1167     FT_ZERO( &seg0 );
1168     seg0.score = 32000;
1169     seg0.flags = AF_EDGE_NORMAL;
1170
1171     major_dir   = (AF_Direction)FT_ABS( axis->major_dir );
1172     segment_dir = major_dir;
1173
1174     axis->num_segments = 0;
1175
1176     /* set up (u,v) in each point */
1177     if ( dim == AF_DIMENSION_HORZ )
1178     {
1179       AF_Point  point = hints->points;
1180       AF_Point  limit = point + hints->num_points;
1181
1182
1183       for ( ; point < limit; point++ )
1184       {
1185         point->u = point->fx;
1186         point->v = point->fy;
1187       }
1188     }
1189     else
1190     {
1191       AF_Point  point = hints->points;
1192       AF_Point  limit = point + hints->num_points;
1193
1194
1195       for ( ; point < limit; point++ )
1196       {
1197         point->u = point->fy;
1198         point->v = point->fx;
1199       }
1200     }
1201
1202     /* do each contour separately */
1203     for ( ; contour < contour_limit; contour++ )
1204     {
1205       AF_Point  point   =  contour[0];
1206       AF_Point  last    =  point->prev;
1207       int       on_edge =  0;
1208       FT_Pos    min_pos =  32000;  /* minimum segment pos != min_coord */
1209       FT_Pos    max_pos = -32000;  /* maximum segment pos != max_coord */
1210       FT_Bool   passed;
1211
1212
1213       if ( point == last )  /* skip singletons -- just in case */
1214         continue;
1215
1216       if ( FT_ABS( last->out_dir )  == major_dir &&
1217            FT_ABS( point->out_dir ) == major_dir )
1218       {
1219         /* we are already on an edge, try to locate its start */
1220         last = point;
1221
1222         for (;;)
1223         {
1224           point = point->prev;
1225           if ( FT_ABS( point->out_dir ) != major_dir )
1226           {
1227             point = point->next;
1228             break;
1229           }
1230           if ( point == last )
1231             break;
1232         }
1233       }
1234
1235       last   = point;
1236       passed = 0;
1237
1238       for (;;)
1239       {
1240         FT_Pos  u, v;
1241
1242
1243         if ( on_edge )
1244         {
1245           u = point->u;
1246           if ( u < min_pos )
1247             min_pos = u;
1248           if ( u > max_pos )
1249             max_pos = u;
1250
1251           if ( point->out_dir != segment_dir || point == last )
1252           {
1253             /* we are just leaving an edge; record a new segment! */
1254             segment->last = point;
1255             segment->pos  = (FT_Short)( ( min_pos + max_pos ) >> 1 );
1256
1257             /* a segment is round if either its first or last point */
1258             /* is a control point                                   */
1259             if ( ( segment->first->flags | point->flags ) &
1260                  AF_FLAG_CONTROL                          )
1261               segment->flags |= AF_EDGE_ROUND;
1262
1263             /* compute segment size */
1264             min_pos = max_pos = point->v;
1265
1266             v = segment->first->v;
1267             if ( v < min_pos )
1268               min_pos = v;
1269             if ( v > max_pos )
1270               max_pos = v;
1271
1272             segment->min_coord = (FT_Short)min_pos;
1273             segment->max_coord = (FT_Short)max_pos;
1274             segment->height    = (FT_Short)( segment->max_coord -
1275                                              segment->min_coord );
1276
1277             on_edge = 0;
1278             segment = NULL;
1279             /* fall through */
1280           }
1281         }
1282
1283         /* now exit if we are at the start/end point */
1284         if ( point == last )
1285         {
1286           if ( passed )
1287             break;
1288           passed = 1;
1289         }
1290
1291         if ( !on_edge && FT_ABS( point->out_dir ) == major_dir )
1292         {
1293           /* this is the start of a new segment! */
1294           segment_dir = (AF_Direction)point->out_dir;
1295
1296           error = af_axis_hints_new_segment( axis, memory, &segment );
1297           if ( error )
1298             goto Exit;
1299
1300           /* clear all segment fields */
1301           segment[0] = seg0;
1302
1303           segment->dir      = (FT_Char)segment_dir;
1304           min_pos = max_pos = point->u;
1305           segment->first    = point;
1306           segment->last     = point;
1307
1308           on_edge = 1;
1309         }
1310
1311         point = point->next;
1312       }
1313
1314     } /* contours */
1315
1316
1317     /* now slightly increase the height of segments if this makes */
1318     /* sense -- this is used to better detect and ignore serifs   */
1319     {
1320       AF_Segment  segments     = axis->segments;
1321       AF_Segment  segments_end = segments + axis->num_segments;
1322
1323
1324       for ( segment = segments; segment < segments_end; segment++ )
1325       {
1326         AF_Point  first   = segment->first;
1327         AF_Point  last    = segment->last;
1328         FT_Pos    first_v = first->v;
1329         FT_Pos    last_v  = last->v;
1330
1331
1332         if ( first_v < last_v )
1333         {
1334           AF_Point  p;
1335
1336
1337           p = first->prev;
1338           if ( p->v < first_v )
1339             segment->height = (FT_Short)( segment->height +
1340                                           ( ( first_v - p->v ) >> 1 ) );
1341
1342           p = last->next;
1343           if ( p->v > last_v )
1344             segment->height = (FT_Short)( segment->height +
1345                                           ( ( p->v - last_v ) >> 1 ) );
1346         }
1347         else
1348         {
1349           AF_Point  p;
1350
1351
1352           p = first->prev;
1353           if ( p->v > first_v )
1354             segment->height = (FT_Short)( segment->height +
1355                                           ( ( p->v - first_v ) >> 1 ) );
1356
1357           p = last->next;
1358           if ( p->v < last_v )
1359             segment->height = (FT_Short)( segment->height +
1360                                           ( ( last_v - p->v ) >> 1 ) );
1361         }
1362       }
1363     }
1364
1365   Exit:
1366     return error;
1367   }
1368
1369
1370   /* Link segments to form stems and serifs.  If `width_count' and      */
1371   /* `widths' are non-zero, use them to fine-tune the scoring function. */
1372
1373   FT_LOCAL_DEF( void )
1374   af_latin_hints_link_segments( AF_GlyphHints  hints,
1375                                 FT_UInt        width_count,
1376                                 AF_WidthRec*   widths,
1377                                 AF_Dimension   dim )
1378   {
1379     AF_AxisHints  axis          = &hints->axis[dim];
1380     AF_Segment    segments      = axis->segments;
1381     AF_Segment    segment_limit = segments + axis->num_segments;
1382     FT_Pos        len_threshold, len_score, dist_score, max_width;
1383     AF_Segment    seg1, seg2;
1384
1385
1386     if ( width_count )
1387       max_width = widths[width_count - 1].org;
1388     else
1389       max_width = 0;
1390
1391     /* a heuristic value to set up a minimum value for overlapping */
1392     len_threshold = AF_LATIN_CONSTANT( hints->metrics, 8 );
1393     if ( len_threshold == 0 )
1394       len_threshold = 1;
1395
1396     /* a heuristic value to weight lengths */
1397     len_score = AF_LATIN_CONSTANT( hints->metrics, 6000 );
1398
1399     /* a heuristic value to weight distances (no call to    */
1400     /* AF_LATIN_CONSTANT needed, since we work on multiples */
1401     /* of the stem width)                                   */
1402     dist_score = 3000;
1403
1404     /* now compare each segment to the others */
1405     for ( seg1 = segments; seg1 < segment_limit; seg1++ )
1406     {
1407       if ( seg1->dir != axis->major_dir )
1408         continue;
1409
1410       /* search for stems having opposite directions, */
1411       /* with seg1 to the `left' of seg2              */
1412       for ( seg2 = segments; seg2 < segment_limit; seg2++ )
1413       {
1414         FT_Pos  pos1 = seg1->pos;
1415         FT_Pos  pos2 = seg2->pos;
1416
1417
1418         if ( seg1->dir + seg2->dir == 0 && pos2 > pos1 )
1419         {
1420           /* compute distance between the two segments */
1421           FT_Pos  min = seg1->min_coord;
1422           FT_Pos  max = seg1->max_coord;
1423           FT_Pos  len;
1424
1425
1426           if ( min < seg2->min_coord )
1427             min = seg2->min_coord;
1428
1429           if ( max > seg2->max_coord )
1430             max = seg2->max_coord;
1431
1432           /* compute maximum coordinate difference of the two segments */
1433           /* (this is, how much they overlap)                          */
1434           len = max - min;
1435           if ( len >= len_threshold )
1436           {
1437             /*
1438              *  The score is the sum of two demerits indicating the
1439              *  `badness' of a fit, measured along the segments' main axis
1440              *  and orthogonal to it, respectively.
1441              *
1442              *  o The less overlapping along the main axis, the worse it
1443              *    is, causing a larger demerit.
1444              *
1445              *  o The nearer the orthogonal distance to a stem width, the
1446              *    better it is, causing a smaller demerit.  For simplicity,
1447              *    however, we only increase the demerit for values that
1448              *    exceed the largest stem width.
1449              */
1450
1451             FT_Pos  dist = pos2 - pos1;
1452
1453             FT_Pos  dist_demerit, score;
1454
1455
1456             if ( max_width )
1457             {
1458               /* distance demerits are based on multiples of `max_width'; */
1459               /* we scale by 1024 for getting more precision              */
1460               FT_Pos  delta = ( dist << 10 ) / max_width - ( 1 << 10 );
1461
1462
1463               if ( delta > 10000 )
1464                 dist_demerit = 32000;
1465               else if ( delta > 0 )
1466                 dist_demerit = delta * delta / dist_score;
1467               else
1468                 dist_demerit = 0;
1469             }
1470             else
1471               dist_demerit = dist; /* default if no widths available */
1472
1473             score = dist_demerit + len_score / len;
1474
1475             /* and we search for the smallest score */
1476             if ( score < seg1->score )
1477             {
1478               seg1->score = score;
1479               seg1->link  = seg2;
1480             }
1481
1482             if ( score < seg2->score )
1483             {
1484               seg2->score = score;
1485               seg2->link  = seg1;
1486             }
1487           }
1488         }
1489       }
1490     }
1491
1492     /* now compute the `serif' segments, cf. explanations in `afhints.h' */
1493     for ( seg1 = segments; seg1 < segment_limit; seg1++ )
1494     {
1495       seg2 = seg1->link;
1496
1497       if ( seg2 )
1498       {
1499         if ( seg2->link != seg1 )
1500         {
1501           seg1->link  = 0;
1502           seg1->serif = seg2->link;
1503         }
1504       }
1505     }
1506   }
1507
1508
1509   /* Link segments to edges, using feature analysis for selection. */
1510
1511   FT_LOCAL_DEF( FT_Error )
1512   af_latin_hints_compute_edges( AF_GlyphHints  hints,
1513                                 AF_Dimension   dim )
1514   {
1515     AF_AxisHints  axis   = &hints->axis[dim];
1516     FT_Error      error  = FT_Err_Ok;
1517     FT_Memory     memory = hints->memory;
1518     AF_LatinAxis  laxis  = &((AF_LatinMetrics)hints->metrics)->axis[dim];
1519
1520     AF_Segment    segments      = axis->segments;
1521     AF_Segment    segment_limit = segments + axis->num_segments;
1522     AF_Segment    seg;
1523
1524 #if 0
1525     AF_Direction  up_dir;
1526 #endif
1527     FT_Fixed      scale;
1528     FT_Pos        edge_distance_threshold;
1529     FT_Pos        segment_length_threshold;
1530
1531
1532     axis->num_edges = 0;
1533
1534     scale = ( dim == AF_DIMENSION_HORZ ) ? hints->x_scale
1535                                          : hints->y_scale;
1536
1537 #if 0
1538     up_dir = ( dim == AF_DIMENSION_HORZ ) ? AF_DIR_UP
1539                                           : AF_DIR_RIGHT;
1540 #endif
1541
1542     /*
1543      *  We ignore all segments that are less than 1 pixel in length
1544      *  to avoid many problems with serif fonts.  We compute the
1545      *  corresponding threshold in font units.
1546      */
1547     if ( dim == AF_DIMENSION_HORZ )
1548         segment_length_threshold = FT_DivFix( 64, hints->y_scale );
1549     else
1550         segment_length_threshold = 0;
1551
1552     /*********************************************************************/
1553     /*                                                                   */
1554     /* We begin by generating a sorted table of edges for the current    */
1555     /* direction.  To do so, we simply scan each segment and try to find */
1556     /* an edge in our table that corresponds to its position.            */
1557     /*                                                                   */
1558     /* If no edge is found, we create and insert a new edge in the       */
1559     /* sorted table.  Otherwise, we simply add the segment to the edge's */
1560     /* list which gets processed in the second step to compute the       */
1561     /* edge's properties.                                                */
1562     /*                                                                   */
1563     /* Note that the table of edges is sorted along the segment/edge     */
1564     /* position.                                                         */
1565     /*                                                                   */
1566     /*********************************************************************/
1567
1568     /* assure that edge distance threshold is at most 0.25px */
1569     edge_distance_threshold = FT_MulFix( laxis->edge_distance_threshold,
1570                                          scale );
1571     if ( edge_distance_threshold > 64 / 4 )
1572       edge_distance_threshold = 64 / 4;
1573
1574     edge_distance_threshold = FT_DivFix( edge_distance_threshold,
1575                                          scale );
1576
1577     for ( seg = segments; seg < segment_limit; seg++ )
1578     {
1579       AF_Edge  found = NULL;
1580       FT_Int   ee;
1581
1582
1583       if ( seg->height < segment_length_threshold )
1584         continue;
1585
1586       /* A special case for serif edges: If they are smaller than */
1587       /* 1.5 pixels we ignore them.                               */
1588       if ( seg->serif                                     &&
1589            2 * seg->height < 3 * segment_length_threshold )
1590         continue;
1591
1592       /* look for an edge corresponding to the segment */
1593       for ( ee = 0; ee < axis->num_edges; ee++ )
1594       {
1595         AF_Edge  edge = axis->edges + ee;
1596         FT_Pos   dist;
1597
1598
1599         dist = seg->pos - edge->fpos;
1600         if ( dist < 0 )
1601           dist = -dist;
1602
1603         if ( dist < edge_distance_threshold && edge->dir == seg->dir )
1604         {
1605           found = edge;
1606           break;
1607         }
1608       }
1609
1610       if ( !found )
1611       {
1612         AF_Edge  edge;
1613
1614
1615         /* insert a new edge in the list and */
1616         /* sort according to the position    */
1617         error = af_axis_hints_new_edge( axis, seg->pos,
1618                                         (AF_Direction)seg->dir,
1619                                         memory, &edge );
1620         if ( error )
1621           goto Exit;
1622
1623         /* add the segment to the new edge's list */
1624         FT_ZERO( edge );
1625
1626         edge->first    = seg;
1627         edge->last     = seg;
1628         edge->dir      = seg->dir;
1629         edge->fpos     = seg->pos;
1630         edge->opos     = FT_MulFix( seg->pos, scale );
1631         edge->pos      = edge->opos;
1632         seg->edge_next = seg;
1633       }
1634       else
1635       {
1636         /* if an edge was found, simply add the segment to the edge's */
1637         /* list                                                       */
1638         seg->edge_next         = found->first;
1639         found->last->edge_next = seg;
1640         found->last            = seg;
1641       }
1642     }
1643
1644
1645     /******************************************************************/
1646     /*                                                                */
1647     /* Good, we now compute each edge's properties according to the   */
1648     /* segments found on its position.  Basically, these are          */
1649     /*                                                                */
1650     /*  - the edge's main direction                                   */
1651     /*  - stem edge, serif edge or both (which defaults to stem then) */
1652     /*  - rounded edge, straight or both (which defaults to straight) */
1653     /*  - link for edge                                               */
1654     /*                                                                */
1655     /******************************************************************/
1656
1657     /* first of all, set the `edge' field in each segment -- this is */
1658     /* required in order to compute edge links                       */
1659
1660     /*
1661      * Note that removing this loop and setting the `edge' field of each
1662      * segment directly in the code above slows down execution speed for
1663      * some reasons on platforms like the Sun.
1664      */
1665     {
1666       AF_Edge  edges      = axis->edges;
1667       AF_Edge  edge_limit = edges + axis->num_edges;
1668       AF_Edge  edge;
1669
1670
1671       for ( edge = edges; edge < edge_limit; edge++ )
1672       {
1673         seg = edge->first;
1674         if ( seg )
1675           do
1676           {
1677             seg->edge = edge;
1678             seg       = seg->edge_next;
1679
1680           } while ( seg != edge->first );
1681       }
1682
1683       /* now compute each edge properties */
1684       for ( edge = edges; edge < edge_limit; edge++ )
1685       {
1686         FT_Int  is_round    = 0;  /* does it contain round segments?    */
1687         FT_Int  is_straight = 0;  /* does it contain straight segments? */
1688 #if 0
1689         FT_Pos  ups         = 0;  /* number of upwards segments         */
1690         FT_Pos  downs       = 0;  /* number of downwards segments       */
1691 #endif
1692
1693
1694         seg = edge->first;
1695
1696         do
1697         {
1698           FT_Bool  is_serif;
1699
1700
1701           /* check for roundness of segment */
1702           if ( seg->flags & AF_EDGE_ROUND )
1703             is_round++;
1704           else
1705             is_straight++;
1706
1707 #if 0
1708           /* check for segment direction */
1709           if ( seg->dir == up_dir )
1710             ups   += seg->max_coord - seg->min_coord;
1711           else
1712             downs += seg->max_coord - seg->min_coord;
1713 #endif
1714
1715           /* check for links -- if seg->serif is set, then seg->link must */
1716           /* be ignored                                                   */
1717           is_serif = (FT_Bool)( seg->serif               &&
1718                                 seg->serif->edge         &&
1719                                 seg->serif->edge != edge );
1720
1721           if ( ( seg->link && seg->link->edge != NULL ) || is_serif )
1722           {
1723             AF_Edge     edge2;
1724             AF_Segment  seg2;
1725
1726
1727             edge2 = edge->link;
1728             seg2  = seg->link;
1729
1730             if ( is_serif )
1731             {
1732               seg2  = seg->serif;
1733               edge2 = edge->serif;
1734             }
1735
1736             if ( edge2 )
1737             {
1738               FT_Pos  edge_delta;
1739               FT_Pos  seg_delta;
1740
1741
1742               edge_delta = edge->fpos - edge2->fpos;
1743               if ( edge_delta < 0 )
1744                 edge_delta = -edge_delta;
1745
1746               seg_delta = seg->pos - seg2->pos;
1747               if ( seg_delta < 0 )
1748                 seg_delta = -seg_delta;
1749
1750               if ( seg_delta < edge_delta )
1751                 edge2 = seg2->edge;
1752             }
1753             else
1754               edge2 = seg2->edge;
1755
1756             if ( is_serif )
1757             {
1758               edge->serif   = edge2;
1759               edge2->flags |= AF_EDGE_SERIF;
1760             }
1761             else
1762               edge->link  = edge2;
1763           }
1764
1765           seg = seg->edge_next;
1766
1767         } while ( seg != edge->first );
1768
1769         /* set the round/straight flags */
1770         edge->flags = AF_EDGE_NORMAL;
1771
1772         if ( is_round > 0 && is_round >= is_straight )
1773           edge->flags |= AF_EDGE_ROUND;
1774
1775 #if 0
1776         /* set the edge's main direction */
1777         edge->dir = AF_DIR_NONE;
1778
1779         if ( ups > downs )
1780           edge->dir = (FT_Char)up_dir;
1781
1782         else if ( ups < downs )
1783           edge->dir = (FT_Char)-up_dir;
1784
1785         else if ( ups == downs )
1786           edge->dir = 0;  /* both up and down! */
1787 #endif
1788
1789         /* get rid of serifs if link is set                 */
1790         /* XXX: This gets rid of many unpleasant artefacts! */
1791         /*      Example: the `c' in cour.pfa at size 13     */
1792
1793         if ( edge->serif && edge->link )
1794           edge->serif = 0;
1795       }
1796     }
1797
1798   Exit:
1799     return error;
1800   }
1801
1802
1803   /* Detect segments and edges for given dimension. */
1804
1805   FT_LOCAL_DEF( FT_Error )
1806   af_latin_hints_detect_features( AF_GlyphHints  hints,
1807                                   FT_UInt        width_count,
1808                                   AF_WidthRec*   widths,
1809                                   AF_Dimension   dim )
1810   {
1811     FT_Error  error;
1812
1813
1814     error = af_latin_hints_compute_segments( hints, dim );
1815     if ( !error )
1816     {
1817       af_latin_hints_link_segments( hints, width_count, widths, dim );
1818
1819       error = af_latin_hints_compute_edges( hints, dim );
1820     }
1821
1822     return error;
1823   }
1824
1825
1826   /* Compute all edges which lie within blue zones. */
1827
1828   FT_LOCAL_DEF( void )
1829   af_latin_hints_compute_blue_edges( AF_GlyphHints    hints,
1830                                      AF_LatinMetrics  metrics )
1831   {
1832     AF_AxisHints  axis       = &hints->axis[AF_DIMENSION_VERT];
1833     AF_Edge       edge       = axis->edges;
1834     AF_Edge       edge_limit = edge + axis->num_edges;
1835     AF_LatinAxis  latin      = &metrics->axis[AF_DIMENSION_VERT];
1836     FT_Fixed      scale      = latin->scale;
1837
1838
1839     /* compute which blue zones are active, i.e. have their scaled */
1840     /* size < 3/4 pixels                                           */
1841
1842     /* for each horizontal edge search the blue zone which is closest */
1843     for ( ; edge < edge_limit; edge++ )
1844     {
1845       FT_UInt   bb;
1846       AF_Width  best_blue            = NULL;
1847       FT_Bool   best_blue_is_neutral = 0;
1848       FT_Pos    best_dist;                 /* initial threshold */
1849
1850
1851       /* compute the initial threshold as a fraction of the EM size */
1852       /* (the value 40 is heuristic)                                */
1853       best_dist = FT_MulFix( metrics->units_per_em / 40, scale );
1854
1855       /* assure a minimum distance of 0.5px */
1856       if ( best_dist > 64 / 2 )
1857         best_dist = 64 / 2;
1858
1859       for ( bb = 0; bb < latin->blue_count; bb++ )
1860       {
1861         AF_LatinBlue  blue = latin->blues + bb;
1862         FT_Bool       is_top_blue, is_neutral_blue, is_major_dir;
1863
1864
1865         /* skip inactive blue zones (i.e., those that are too large) */
1866         if ( !( blue->flags & AF_LATIN_BLUE_ACTIVE ) )
1867           continue;
1868
1869         /* if it is a top zone, check for right edges (against the major */
1870         /* direction); if it is a bottom zone, check for left edges (in  */
1871         /* the major direction) -- this assumes the TrueType convention  */
1872         /* for the orientation of contours                               */
1873         is_top_blue =
1874           (FT_Byte)( ( blue->flags & AF_LATIN_BLUE_TOP ) != 0 );
1875         is_neutral_blue =
1876           (FT_Byte)( ( blue->flags & AF_LATIN_BLUE_NEUTRAL ) != 0);
1877         is_major_dir =
1878           FT_BOOL( edge->dir == axis->major_dir );
1879
1880         /* neutral blue zones are handled for both directions */
1881         if ( is_top_blue ^ is_major_dir || is_neutral_blue )
1882         {
1883           FT_Pos  dist;
1884
1885
1886           /* first of all, compare it to the reference position */
1887           dist = edge->fpos - blue->ref.org;
1888           if ( dist < 0 )
1889             dist = -dist;
1890
1891           dist = FT_MulFix( dist, scale );
1892           if ( dist < best_dist )
1893           {
1894             best_dist            = dist;
1895             best_blue            = &blue->ref;
1896             best_blue_is_neutral = is_neutral_blue;
1897           }
1898
1899           /* now compare it to the overshoot position and check whether */
1900           /* the edge is rounded, and whether the edge is over the      */
1901           /* reference position of a top zone, or under the reference   */
1902           /* position of a bottom zone (provided we don't have a        */
1903           /* neutral blue zone)                                         */
1904           if ( edge->flags & AF_EDGE_ROUND &&
1905                dist != 0                   &&
1906                !is_neutral_blue            )
1907           {
1908             FT_Bool  is_under_ref = FT_BOOL( edge->fpos < blue->ref.org );
1909
1910
1911             if ( is_top_blue ^ is_under_ref )
1912             {
1913               dist = edge->fpos - blue->shoot.org;
1914               if ( dist < 0 )
1915                 dist = -dist;
1916
1917               dist = FT_MulFix( dist, scale );
1918               if ( dist < best_dist )
1919               {
1920                 best_dist            = dist;
1921                 best_blue            = &blue->shoot;
1922                 best_blue_is_neutral = is_neutral_blue;
1923               }
1924             }
1925           }
1926         }
1927       }
1928
1929       if ( best_blue )
1930       {
1931         edge->blue_edge = best_blue;
1932         if ( best_blue_is_neutral )
1933           edge->flags |= AF_EDGE_NEUTRAL;
1934       }
1935     }
1936   }
1937
1938
1939   /* Initalize hinting engine. */
1940
1941   static FT_Error
1942   af_latin_hints_init( AF_GlyphHints    hints,
1943                        AF_LatinMetrics  metrics )
1944   {
1945     FT_Render_Mode  mode;
1946     FT_UInt32       scaler_flags, other_flags;
1947     FT_Face         face = metrics->root.scaler.face;
1948
1949
1950     af_glyph_hints_rescale( hints, (AF_StyleMetrics)metrics );
1951
1952     /*
1953      *  correct x_scale and y_scale if needed, since they may have
1954      *  been modified by `af_latin_metrics_scale_dim' above
1955      */
1956     hints->x_scale = metrics->axis[AF_DIMENSION_HORZ].scale;
1957     hints->x_delta = metrics->axis[AF_DIMENSION_HORZ].delta;
1958     hints->y_scale = metrics->axis[AF_DIMENSION_VERT].scale;
1959     hints->y_delta = metrics->axis[AF_DIMENSION_VERT].delta;
1960
1961     /* compute flags depending on render mode, etc. */
1962     mode = metrics->root.scaler.render_mode;
1963
1964 #if 0 /* #ifdef AF_CONFIG_OPTION_USE_WARPER */
1965     if ( mode == FT_RENDER_MODE_LCD || mode == FT_RENDER_MODE_LCD_V )
1966       metrics->root.scaler.render_mode = mode = FT_RENDER_MODE_NORMAL;
1967 #endif
1968
1969     scaler_flags = hints->scaler_flags;
1970     other_flags  = 0;
1971
1972     /*
1973      *  We snap the width of vertical stems for the monochrome and
1974      *  horizontal LCD rendering targets only.
1975      */
1976     if ( mode == FT_RENDER_MODE_MONO || mode == FT_RENDER_MODE_LCD )
1977       other_flags |= AF_LATIN_HINTS_HORZ_SNAP;
1978
1979     /*
1980      *  We snap the width of horizontal stems for the monochrome and
1981      *  vertical LCD rendering targets only.
1982      */
1983     if ( mode == FT_RENDER_MODE_MONO || mode == FT_RENDER_MODE_LCD_V )
1984       other_flags |= AF_LATIN_HINTS_VERT_SNAP;
1985
1986     /*
1987      *  We adjust stems to full pixels only if we don't use the `light' mode.
1988      */
1989     if ( mode != FT_RENDER_MODE_LIGHT )
1990       other_flags |= AF_LATIN_HINTS_STEM_ADJUST;
1991
1992     if ( mode == FT_RENDER_MODE_MONO )
1993       other_flags |= AF_LATIN_HINTS_MONO;
1994
1995     /*
1996      *  In `light' hinting mode we disable horizontal hinting completely.
1997      *  We also do it if the face is italic.
1998      */
1999     if ( mode == FT_RENDER_MODE_LIGHT                      ||
2000          ( face->style_flags & FT_STYLE_FLAG_ITALIC ) != 0 )
2001       scaler_flags |= AF_SCALER_FLAG_NO_HORIZONTAL;
2002
2003     hints->scaler_flags = scaler_flags;
2004     hints->other_flags  = other_flags;
2005
2006     return FT_Err_Ok;
2007   }
2008
2009
2010   /*************************************************************************/
2011   /*************************************************************************/
2012   /*****                                                               *****/
2013   /*****        L A T I N   G L Y P H   G R I D - F I T T I N G        *****/
2014   /*****                                                               *****/
2015   /*************************************************************************/
2016   /*************************************************************************/
2017
2018   /* Snap a given width in scaled coordinates to one of the */
2019   /* current standard widths.                               */
2020
2021   static FT_Pos
2022   af_latin_snap_width( AF_Width  widths,
2023                        FT_Int    count,
2024                        FT_Pos    width )
2025   {
2026     int     n;
2027     FT_Pos  best      = 64 + 32 + 2;
2028     FT_Pos  reference = width;
2029     FT_Pos  scaled;
2030
2031
2032     for ( n = 0; n < count; n++ )
2033     {
2034       FT_Pos  w;
2035       FT_Pos  dist;
2036
2037
2038       w = widths[n].cur;
2039       dist = width - w;
2040       if ( dist < 0 )
2041         dist = -dist;
2042       if ( dist < best )
2043       {
2044         best      = dist;
2045         reference = w;
2046       }
2047     }
2048
2049     scaled = FT_PIX_ROUND( reference );
2050
2051     if ( width >= reference )
2052     {
2053       if ( width < scaled + 48 )
2054         width = reference;
2055     }
2056     else
2057     {
2058       if ( width > scaled - 48 )
2059         width = reference;
2060     }
2061
2062     return width;
2063   }
2064
2065
2066   /* Compute the snapped width of a given stem, ignoring very thin ones. */
2067   /* There is a lot of voodoo in this function; changing the hard-coded  */
2068   /* parameters influence the whole hinting process.                     */
2069
2070   static FT_Pos
2071   af_latin_compute_stem_width( AF_GlyphHints  hints,
2072                                AF_Dimension   dim,
2073                                FT_Pos         width,
2074                                AF_Edge_Flags  base_flags,
2075                                AF_Edge_Flags  stem_flags )
2076   {
2077     AF_LatinMetrics  metrics  = (AF_LatinMetrics)hints->metrics;
2078     AF_LatinAxis     axis     = &metrics->axis[dim];
2079     FT_Pos           dist     = width;
2080     FT_Int           sign     = 0;
2081     FT_Int           vertical = ( dim == AF_DIMENSION_VERT );
2082
2083
2084     if ( !AF_LATIN_HINTS_DO_STEM_ADJUST( hints ) ||
2085          axis->extra_light                       )
2086       return width;
2087
2088     if ( dist < 0 )
2089     {
2090       dist = -width;
2091       sign = 1;
2092     }
2093
2094     if ( (  vertical && !AF_LATIN_HINTS_DO_VERT_SNAP( hints ) ) ||
2095          ( !vertical && !AF_LATIN_HINTS_DO_HORZ_SNAP( hints ) ) )
2096     {
2097       /* smooth hinting process: very lightly quantize the stem width */
2098
2099       /* leave the widths of serifs alone */
2100       if ( ( stem_flags & AF_EDGE_SERIF ) &&
2101            vertical                       &&
2102            ( dist < 3 * 64 )              )
2103         goto Done_Width;
2104
2105       else if ( base_flags & AF_EDGE_ROUND )
2106       {
2107         if ( dist < 80 )
2108           dist = 64;
2109       }
2110       else if ( dist < 56 )
2111         dist = 56;
2112
2113       if ( axis->width_count > 0 )
2114       {
2115         FT_Pos  delta;
2116
2117
2118         /* compare to standard width */
2119         delta = dist - axis->widths[0].cur;
2120
2121         if ( delta < 0 )
2122           delta = -delta;
2123
2124         if ( delta < 40 )
2125         {
2126           dist = axis->widths[0].cur;
2127           if ( dist < 48 )
2128             dist = 48;
2129
2130           goto Done_Width;
2131         }
2132
2133         if ( dist < 3 * 64 )
2134         {
2135           delta  = dist & 63;
2136           dist  &= -64;
2137
2138           if ( delta < 10 )
2139             dist += delta;
2140
2141           else if ( delta < 32 )
2142             dist += 10;
2143
2144           else if ( delta < 54 )
2145             dist += 54;
2146
2147           else
2148             dist += delta;
2149         }
2150         else
2151           dist = ( dist + 32 ) & ~63;
2152       }
2153     }
2154     else
2155     {
2156       /* strong hinting process: snap the stem width to integer pixels */
2157
2158       FT_Pos  org_dist = dist;
2159
2160
2161       dist = af_latin_snap_width( axis->widths, axis->width_count, dist );
2162
2163       if ( vertical )
2164       {
2165         /* in the case of vertical hinting, always round */
2166         /* the stem heights to integer pixels            */
2167
2168         if ( dist >= 64 )
2169           dist = ( dist + 16 ) & ~63;
2170         else
2171           dist = 64;
2172       }
2173       else
2174       {
2175         if ( AF_LATIN_HINTS_DO_MONO( hints ) )
2176         {
2177           /* monochrome horizontal hinting: snap widths to integer pixels */
2178           /* with a different threshold                                   */
2179
2180           if ( dist < 64 )
2181             dist = 64;
2182           else
2183             dist = ( dist + 32 ) & ~63;
2184         }
2185         else
2186         {
2187           /* for horizontal anti-aliased hinting, we adopt a more subtle */
2188           /* approach: we strengthen small stems, round stems whose size */
2189           /* is between 1 and 2 pixels to an integer, otherwise nothing  */
2190
2191           if ( dist < 48 )
2192             dist = ( dist + 64 ) >> 1;
2193
2194           else if ( dist < 128 )
2195           {
2196             /* We only round to an integer width if the corresponding */
2197             /* distortion is less than 1/4 pixel.  Otherwise this     */
2198             /* makes everything worse since the diagonals, which are  */
2199             /* not hinted, appear a lot bolder or thinner than the    */
2200             /* vertical stems.                                        */
2201
2202             FT_Pos  delta;
2203
2204
2205             dist = ( dist + 22 ) & ~63;
2206             delta = dist - org_dist;
2207             if ( delta < 0 )
2208               delta = -delta;
2209
2210             if ( delta >= 16 )
2211             {
2212               dist = org_dist;
2213               if ( dist < 48 )
2214                 dist = ( dist + 64 ) >> 1;
2215             }
2216           }
2217           else
2218             /* round otherwise to prevent color fringes in LCD mode */
2219             dist = ( dist + 32 ) & ~63;
2220         }
2221       }
2222     }
2223
2224   Done_Width:
2225     if ( sign )
2226       dist = -dist;
2227
2228     return dist;
2229   }
2230
2231
2232   /* Align one stem edge relative to the previous stem edge. */
2233
2234   static void
2235   af_latin_align_linked_edge( AF_GlyphHints  hints,
2236                               AF_Dimension   dim,
2237                               AF_Edge        base_edge,
2238                               AF_Edge        stem_edge )
2239   {
2240     FT_Pos  dist = stem_edge->opos - base_edge->opos;
2241
2242     FT_Pos  fitted_width = af_latin_compute_stem_width(
2243                              hints, dim, dist,
2244                              (AF_Edge_Flags)base_edge->flags,
2245                              (AF_Edge_Flags)stem_edge->flags );
2246
2247
2248     stem_edge->pos = base_edge->pos + fitted_width;
2249
2250     FT_TRACE5(( "  LINK: edge %d (opos=%.2f) linked to %.2f,"
2251                 " dist was %.2f, now %.2f\n",
2252                 stem_edge - hints->axis[dim].edges, stem_edge->opos / 64.0,
2253                 stem_edge->pos / 64.0, dist / 64.0, fitted_width / 64.0 ));
2254   }
2255
2256
2257   /* Shift the coordinates of the `serif' edge by the same amount */
2258   /* as the corresponding `base' edge has been moved already.     */
2259
2260   static void
2261   af_latin_align_serif_edge( AF_GlyphHints  hints,
2262                              AF_Edge        base,
2263                              AF_Edge        serif )
2264   {
2265     FT_UNUSED( hints );
2266
2267     serif->pos = base->pos + ( serif->opos - base->opos );
2268   }
2269
2270
2271   /*************************************************************************/
2272   /*************************************************************************/
2273   /*************************************************************************/
2274   /****                                                                 ****/
2275   /****                    E D G E   H I N T I N G                      ****/
2276   /****                                                                 ****/
2277   /*************************************************************************/
2278   /*************************************************************************/
2279   /*************************************************************************/
2280
2281
2282   /* The main grid-fitting routine. */
2283
2284   FT_LOCAL_DEF( void )
2285   af_latin_hint_edges( AF_GlyphHints  hints,
2286                        AF_Dimension   dim )
2287   {
2288     AF_AxisHints  axis       = &hints->axis[dim];
2289     AF_Edge       edges      = axis->edges;
2290     AF_Edge       edge_limit = edges + axis->num_edges;
2291     FT_PtrDist    n_edges;
2292     AF_Edge       edge;
2293     AF_Edge       anchor     = NULL;
2294     FT_Int        has_serifs = 0;
2295
2296 #ifdef FT_DEBUG_LEVEL_TRACE
2297     FT_UInt       num_actions = 0;
2298 #endif
2299
2300
2301     FT_TRACE5(( "latin %s edge hinting (style `%s')\n",
2302                 dim == AF_DIMENSION_VERT ? "horizontal" : "vertical",
2303                 af_style_names[hints->metrics->style_class->style] ));
2304
2305     /* we begin by aligning all stems relative to the blue zone */
2306     /* if needed -- that's only for horizontal edges            */
2307
2308     if ( dim == AF_DIMENSION_VERT && AF_HINTS_DO_BLUES( hints ) )
2309     {
2310       for ( edge = edges; edge < edge_limit; edge++ )
2311       {
2312         AF_Width  blue;
2313         AF_Edge   edge1, edge2; /* these edges form the stem to check */
2314
2315
2316         if ( edge->flags & AF_EDGE_DONE )
2317           continue;
2318
2319         edge1 = NULL;
2320         edge2 = edge->link;
2321
2322         /*
2323          *  If a stem contains both a neutral and a non-neutral blue zone,
2324          *  skip the neutral one.  Otherwise, outlines with different
2325          *  directions might be incorrectly aligned at the same vertical
2326          *  position.
2327          *
2328          *  If we have two neutral blue zones, skip one of them.
2329          *
2330          */
2331         if ( edge->blue_edge && edge2 && edge2->blue_edge )
2332         {
2333           FT_Byte  neutral  = edge->flags  & AF_EDGE_NEUTRAL;
2334           FT_Byte  neutral2 = edge2->flags & AF_EDGE_NEUTRAL;
2335
2336
2337           if ( ( neutral && neutral2 ) || neutral2 )
2338           {
2339             edge2->blue_edge = NULL;
2340             edge2->flags    &= ~AF_EDGE_NEUTRAL;
2341           }
2342           else if ( neutral )
2343           {
2344             edge->blue_edge = NULL;
2345             edge->flags    &= ~AF_EDGE_NEUTRAL;
2346           }
2347         }
2348
2349         blue = edge->blue_edge;
2350         if ( blue )
2351           edge1 = edge;
2352
2353         /* flip edges if the other edge is aligned to a blue zone */
2354         else if ( edge2 && edge2->blue_edge )
2355         {
2356           blue  = edge2->blue_edge;
2357           edge1 = edge2;
2358           edge2 = edge;
2359         }
2360
2361         if ( !edge1 )
2362           continue;
2363
2364 #ifdef FT_DEBUG_LEVEL_TRACE
2365         if ( !anchor )
2366           FT_TRACE5(( "  BLUE_ANCHOR: edge %d (opos=%.2f) snapped to %.2f,"
2367                       " was %.2f (anchor=edge %d)\n",
2368                       edge1 - edges, edge1->opos / 64.0, blue->fit / 64.0,
2369                       edge1->pos / 64.0, edge - edges ));
2370         else
2371           FT_TRACE5(( "  BLUE: edge %d (opos=%.2f) snapped to %.2f,"
2372                       " was %.2f\n",
2373                       edge1 - edges, edge1->opos / 64.0, blue->fit / 64.0,
2374                       edge1->pos / 64.0 ));
2375
2376         num_actions++;
2377 #endif
2378
2379         edge1->pos    = blue->fit;
2380         edge1->flags |= AF_EDGE_DONE;
2381
2382         if ( edge2 && !edge2->blue_edge )
2383         {
2384           af_latin_align_linked_edge( hints, dim, edge1, edge2 );
2385           edge2->flags |= AF_EDGE_DONE;
2386
2387 #ifdef FT_DEBUG_LEVEL_TRACE
2388           num_actions++;
2389 #endif
2390         }
2391
2392         if ( !anchor )
2393           anchor = edge;
2394       }
2395     }
2396
2397     /* now we align all other stem edges, trying to maintain the */
2398     /* relative order of stems in the glyph                      */
2399     for ( edge = edges; edge < edge_limit; edge++ )
2400     {
2401       AF_Edge  edge2;
2402
2403
2404       if ( edge->flags & AF_EDGE_DONE )
2405         continue;
2406
2407       /* skip all non-stem edges */
2408       edge2 = edge->link;
2409       if ( !edge2 )
2410       {
2411         has_serifs++;
2412         continue;
2413       }
2414
2415       /* now align the stem */
2416
2417       /* this should not happen, but it's better to be safe */
2418       if ( edge2->blue_edge )
2419       {
2420         FT_TRACE5(( "  ASSERTION FAILED for edge %d\n", edge2 - edges ));
2421
2422         af_latin_align_linked_edge( hints, dim, edge2, edge );
2423         edge->flags |= AF_EDGE_DONE;
2424
2425 #ifdef FT_DEBUG_LEVEL_TRACE
2426         num_actions++;
2427 #endif
2428         continue;
2429       }
2430
2431       if ( !anchor )
2432       {
2433         /* if we reach this if clause, no stem has been aligned yet */
2434
2435         FT_Pos  org_len, org_center, cur_len;
2436         FT_Pos  cur_pos1, error1, error2, u_off, d_off;
2437
2438
2439         org_len = edge2->opos - edge->opos;
2440         cur_len = af_latin_compute_stem_width(
2441                     hints, dim, org_len,
2442                     (AF_Edge_Flags)edge->flags,
2443                     (AF_Edge_Flags)edge2->flags );
2444
2445         /* some voodoo to specially round edges for small stem widths; */
2446         /* the idea is to align the center of a stem, then shifting    */
2447         /* the stem edges to suitable positions                        */
2448         if ( cur_len <= 64 )
2449         {
2450           /* width <= 1px */
2451           u_off = 32;
2452           d_off = 32;
2453         }
2454         else
2455         {
2456           /* 1px < width < 1.5px */
2457           u_off = 38;
2458           d_off = 26;
2459         }
2460
2461         if ( cur_len < 96 )
2462         {
2463           org_center = edge->opos + ( org_len >> 1 );
2464           cur_pos1   = FT_PIX_ROUND( org_center );
2465
2466           error1 = org_center - ( cur_pos1 - u_off );
2467           if ( error1 < 0 )
2468             error1 = -error1;
2469
2470           error2 = org_center - ( cur_pos1 + d_off );
2471           if ( error2 < 0 )
2472             error2 = -error2;
2473
2474           if ( error1 < error2 )
2475             cur_pos1 -= u_off;
2476           else
2477             cur_pos1 += d_off;
2478
2479           edge->pos  = cur_pos1 - cur_len / 2;
2480           edge2->pos = edge->pos + cur_len;
2481         }
2482         else
2483           edge->pos = FT_PIX_ROUND( edge->opos );
2484
2485         anchor       = edge;
2486         edge->flags |= AF_EDGE_DONE;
2487
2488         FT_TRACE5(( "  ANCHOR: edge %d (opos=%.2f) and %d (opos=%.2f)"
2489                     " snapped to %.2f and %.2f\n",
2490                     edge - edges, edge->opos / 64.0,
2491                     edge2 - edges, edge2->opos / 64.0,
2492                     edge->pos / 64.0, edge2->pos / 64.0 ));
2493
2494         af_latin_align_linked_edge( hints, dim, edge, edge2 );
2495
2496 #ifdef FT_DEBUG_LEVEL_TRACE
2497         num_actions += 2;
2498 #endif
2499       }
2500       else
2501       {
2502         FT_Pos  org_pos, org_len, org_center, cur_len;
2503         FT_Pos  cur_pos1, cur_pos2, delta1, delta2;
2504
2505
2506         org_pos    = anchor->pos + ( edge->opos - anchor->opos );
2507         org_len    = edge2->opos - edge->opos;
2508         org_center = org_pos + ( org_len >> 1 );
2509
2510         cur_len = af_latin_compute_stem_width(
2511                     hints, dim, org_len,
2512                     (AF_Edge_Flags)edge->flags,
2513                     (AF_Edge_Flags)edge2->flags );
2514
2515         if ( edge2->flags & AF_EDGE_DONE )
2516         {
2517           FT_TRACE5(( "  ADJUST: edge %d (pos=%.2f) moved to %.2f\n",
2518                       edge - edges, edge->pos / 64.0,
2519                       ( edge2->pos - cur_len ) / 64.0 ));
2520
2521           edge->pos = edge2->pos - cur_len;
2522         }
2523
2524         else if ( cur_len < 96 )
2525         {
2526           FT_Pos  u_off, d_off;
2527
2528
2529           cur_pos1 = FT_PIX_ROUND( org_center );
2530
2531           if ( cur_len <= 64 )
2532           {
2533             u_off = 32;
2534             d_off = 32;
2535           }
2536           else
2537           {
2538             u_off = 38;
2539             d_off = 26;
2540           }
2541
2542           delta1 = org_center - ( cur_pos1 - u_off );
2543           if ( delta1 < 0 )
2544             delta1 = -delta1;
2545
2546           delta2 = org_center - ( cur_pos1 + d_off );
2547           if ( delta2 < 0 )
2548             delta2 = -delta2;
2549
2550           if ( delta1 < delta2 )
2551             cur_pos1 -= u_off;
2552           else
2553             cur_pos1 += d_off;
2554
2555           edge->pos  = cur_pos1 - cur_len / 2;
2556           edge2->pos = cur_pos1 + cur_len / 2;
2557
2558           FT_TRACE5(( "  STEM: edge %d (opos=%.2f) linked to %d (opos=%.2f)"
2559                       " snapped to %.2f and %.2f\n",
2560                       edge - edges, edge->opos / 64.0,
2561                       edge2 - edges, edge2->opos / 64.0,
2562                       edge->pos / 64.0, edge2->pos / 64.0 ));
2563         }
2564
2565         else
2566         {
2567           org_pos    = anchor->pos + ( edge->opos - anchor->opos );
2568           org_len    = edge2->opos - edge->opos;
2569           org_center = org_pos + ( org_len >> 1 );
2570
2571           cur_len    = af_latin_compute_stem_width(
2572                          hints, dim, org_len,
2573                          (AF_Edge_Flags)edge->flags,
2574                          (AF_Edge_Flags)edge2->flags );
2575
2576           cur_pos1 = FT_PIX_ROUND( org_pos );
2577           delta1   = cur_pos1 + ( cur_len >> 1 ) - org_center;
2578           if ( delta1 < 0 )
2579             delta1 = -delta1;
2580
2581           cur_pos2 = FT_PIX_ROUND( org_pos + org_len ) - cur_len;
2582           delta2   = cur_pos2 + ( cur_len >> 1 ) - org_center;
2583           if ( delta2 < 0 )
2584             delta2 = -delta2;
2585
2586           edge->pos  = ( delta1 < delta2 ) ? cur_pos1 : cur_pos2;
2587           edge2->pos = edge->pos + cur_len;
2588
2589           FT_TRACE5(( "  STEM: edge %d (opos=%.2f) linked to %d (opos=%.2f)"
2590                       " snapped to %.2f and %.2f\n",
2591                       edge - edges, edge->opos / 64.0,
2592                       edge2 - edges, edge2->opos / 64.0,
2593                       edge->pos / 64.0, edge2->pos / 64.0 ));
2594         }
2595
2596 #ifdef FT_DEBUG_LEVEL_TRACE
2597         num_actions++;
2598 #endif
2599
2600         edge->flags  |= AF_EDGE_DONE;
2601         edge2->flags |= AF_EDGE_DONE;
2602
2603         if ( edge > edges && edge->pos < edge[-1].pos )
2604         {
2605 #ifdef FT_DEBUG_LEVEL_TRACE
2606           FT_TRACE5(( "  BOUND: edge %d (pos=%.2f) moved to %.2f\n",
2607                       edge - edges, edge->pos / 64.0, edge[-1].pos / 64.0 ));
2608
2609           num_actions++;
2610 #endif
2611
2612           edge->pos = edge[-1].pos;
2613         }
2614       }
2615     }
2616
2617     /* make sure that lowercase m's maintain their symmetry */
2618
2619     /* In general, lowercase m's have six vertical edges if they are sans */
2620     /* serif, or twelve if they are with serifs.  This implementation is  */
2621     /* based on that assumption, and seems to work very well with most    */
2622     /* faces.  However, if for a certain face this assumption is not      */
2623     /* true, the m is just rendered like before.  In addition, any stem   */
2624     /* correction will only be applied to symmetrical glyphs (even if the */
2625     /* glyph is not an m), so the potential for unwanted distortion is    */
2626     /* relatively low.                                                    */
2627
2628     /* We don't handle horizontal edges since we can't easily assure that */
2629     /* the third (lowest) stem aligns with the base line; it might end up */
2630     /* one pixel higher or lower.                                         */
2631
2632     n_edges = edge_limit - edges;
2633     if ( dim == AF_DIMENSION_HORZ && ( n_edges == 6 || n_edges == 12 ) )
2634     {
2635       AF_Edge  edge1, edge2, edge3;
2636       FT_Pos   dist1, dist2, span, delta;
2637
2638
2639       if ( n_edges == 6 )
2640       {
2641         edge1 = edges;
2642         edge2 = edges + 2;
2643         edge3 = edges + 4;
2644       }
2645       else
2646       {
2647         edge1 = edges + 1;
2648         edge2 = edges + 5;
2649         edge3 = edges + 9;
2650       }
2651
2652       dist1 = edge2->opos - edge1->opos;
2653       dist2 = edge3->opos - edge2->opos;
2654
2655       span = dist1 - dist2;
2656       if ( span < 0 )
2657         span = -span;
2658
2659       if ( span < 8 )
2660       {
2661         delta = edge3->pos - ( 2 * edge2->pos - edge1->pos );
2662         edge3->pos -= delta;
2663         if ( edge3->link )
2664           edge3->link->pos -= delta;
2665
2666         /* move the serifs along with the stem */
2667         if ( n_edges == 12 )
2668         {
2669           ( edges + 8 )->pos -= delta;
2670           ( edges + 11 )->pos -= delta;
2671         }
2672
2673         edge3->flags |= AF_EDGE_DONE;
2674         if ( edge3->link )
2675           edge3->link->flags |= AF_EDGE_DONE;
2676       }
2677     }
2678
2679     if ( has_serifs || !anchor )
2680     {
2681       /*
2682        *  now hint the remaining edges (serifs and single) in order
2683        *  to complete our processing
2684        */
2685       for ( edge = edges; edge < edge_limit; edge++ )
2686       {
2687         FT_Pos  delta;
2688
2689
2690         if ( edge->flags & AF_EDGE_DONE )
2691           continue;
2692
2693         delta = 1000;
2694
2695         if ( edge->serif )
2696         {
2697           delta = edge->serif->opos - edge->opos;
2698           if ( delta < 0 )
2699             delta = -delta;
2700         }
2701
2702         if ( delta < 64 + 16 )
2703         {
2704           af_latin_align_serif_edge( hints, edge->serif, edge );
2705           FT_TRACE5(( "  SERIF: edge %d (opos=%.2f) serif to %d (opos=%.2f)"
2706                       " aligned to %.2f\n",
2707                       edge - edges, edge->opos / 64.0,
2708                       edge->serif - edges, edge->serif->opos / 64.0,
2709                       edge->pos / 64.0 ));
2710         }
2711         else if ( !anchor )
2712         {
2713           edge->pos = FT_PIX_ROUND( edge->opos );
2714           anchor    = edge;
2715           FT_TRACE5(( "  SERIF_ANCHOR: edge %d (opos=%.2f)"
2716                       " snapped to %.2f\n",
2717                       edge-edges, edge->opos / 64.0, edge->pos / 64.0 ));
2718         }
2719         else
2720         {
2721           AF_Edge  before, after;
2722
2723
2724           for ( before = edge - 1; before >= edges; before-- )
2725             if ( before->flags & AF_EDGE_DONE )
2726               break;
2727
2728           for ( after = edge + 1; after < edge_limit; after++ )
2729             if ( after->flags & AF_EDGE_DONE )
2730               break;
2731
2732           if ( before >= edges && before < edge   &&
2733                after < edge_limit && after > edge )
2734           {
2735             if ( after->opos == before->opos )
2736               edge->pos = before->pos;
2737             else
2738               edge->pos = before->pos +
2739                           FT_MulDiv( edge->opos - before->opos,
2740                                      after->pos - before->pos,
2741                                      after->opos - before->opos );
2742
2743             FT_TRACE5(( "  SERIF_LINK1: edge %d (opos=%.2f) snapped to %.2f"
2744                         " from %d (opos=%.2f)\n",
2745                         edge - edges, edge->opos / 64.0,
2746                         edge->pos / 64.0,
2747                         before - edges, before->opos / 64.0 ));
2748           }
2749           else
2750           {
2751             edge->pos = anchor->pos +
2752                         ( ( edge->opos - anchor->opos + 16 ) & ~31 );
2753             FT_TRACE5(( "  SERIF_LINK2: edge %d (opos=%.2f)"
2754                         " snapped to %.2f\n",
2755                         edge - edges, edge->opos / 64.0, edge->pos / 64.0 ));
2756           }
2757         }
2758
2759 #ifdef FT_DEBUG_LEVEL_TRACE
2760         num_actions++;
2761 #endif
2762         edge->flags |= AF_EDGE_DONE;
2763
2764         if ( edge > edges && edge->pos < edge[-1].pos )
2765         {
2766 #ifdef FT_DEBUG_LEVEL_TRACE
2767           FT_TRACE5(( "  BOUND: edge %d (pos=%.2f) moved to %.2f\n",
2768                       edge - edges, edge->pos / 64.0, edge[-1].pos / 64.0 ));
2769
2770           num_actions++;
2771 #endif
2772           edge->pos = edge[-1].pos;
2773         }
2774
2775         if ( edge + 1 < edge_limit        &&
2776              edge[1].flags & AF_EDGE_DONE &&
2777              edge->pos > edge[1].pos      )
2778         {
2779 #ifdef FT_DEBUG_LEVEL_TRACE
2780           FT_TRACE5(( "  BOUND: edge %d (pos=%.2f) moved to %.2f\n",
2781                       edge - edges, edge->pos / 64.0, edge[1].pos / 64.0 ));
2782
2783           num_actions++;
2784 #endif
2785
2786           edge->pos = edge[1].pos;
2787         }
2788       }
2789     }
2790
2791 #ifdef FT_DEBUG_LEVEL_TRACE
2792     if ( !num_actions )
2793       FT_TRACE5(( "  (none)\n" ));
2794     FT_TRACE5(( "\n" ));
2795 #endif
2796   }
2797
2798
2799   /* Apply the complete hinting algorithm to a latin glyph. */
2800
2801   static FT_Error
2802   af_latin_hints_apply( AF_GlyphHints    hints,
2803                         FT_Outline*      outline,
2804                         AF_LatinMetrics  metrics )
2805   {
2806     FT_Error  error;
2807     int       dim;
2808
2809     AF_LatinAxis  axis;
2810
2811
2812     error = af_glyph_hints_reload( hints, outline );
2813     if ( error )
2814       goto Exit;
2815
2816     /* analyze glyph outline */
2817 #ifdef AF_CONFIG_OPTION_USE_WARPER
2818     if ( metrics->root.scaler.render_mode == FT_RENDER_MODE_LIGHT ||
2819          AF_HINTS_DO_HORIZONTAL( hints )                          )
2820 #else
2821     if ( AF_HINTS_DO_HORIZONTAL( hints ) )
2822 #endif
2823     {
2824       axis  = &metrics->axis[AF_DIMENSION_HORZ];
2825       error = af_latin_hints_detect_features( hints,
2826                                               axis->width_count,
2827                                               axis->widths,
2828                                               AF_DIMENSION_HORZ );
2829       if ( error )
2830         goto Exit;
2831     }
2832
2833     if ( AF_HINTS_DO_VERTICAL( hints ) )
2834     {
2835       axis  = &metrics->axis[AF_DIMENSION_VERT];
2836       error = af_latin_hints_detect_features( hints,
2837                                               axis->width_count,
2838                                               axis->widths,
2839                                               AF_DIMENSION_VERT );
2840       if ( error )
2841         goto Exit;
2842
2843       af_latin_hints_compute_blue_edges( hints, metrics );
2844     }
2845
2846     /* grid-fit the outline */
2847     for ( dim = 0; dim < AF_DIMENSION_MAX; dim++ )
2848     {
2849 #ifdef AF_CONFIG_OPTION_USE_WARPER
2850       if ( dim == AF_DIMENSION_HORZ                                 &&
2851            metrics->root.scaler.render_mode == FT_RENDER_MODE_LIGHT )
2852       {
2853         AF_WarperRec  warper;
2854         FT_Fixed      scale;
2855         FT_Pos        delta;
2856
2857
2858         af_warper_compute( &warper, hints, (AF_Dimension)dim,
2859                            &scale, &delta );
2860         af_glyph_hints_scale_dim( hints, (AF_Dimension)dim,
2861                                   scale, delta );
2862         continue;
2863       }
2864 #endif
2865
2866       if ( ( dim == AF_DIMENSION_HORZ && AF_HINTS_DO_HORIZONTAL( hints ) ) ||
2867            ( dim == AF_DIMENSION_VERT && AF_HINTS_DO_VERTICAL( hints ) )   )
2868       {
2869         af_latin_hint_edges( hints, (AF_Dimension)dim );
2870         af_glyph_hints_align_edge_points( hints, (AF_Dimension)dim );
2871         af_glyph_hints_align_strong_points( hints, (AF_Dimension)dim );
2872         af_glyph_hints_align_weak_points( hints, (AF_Dimension)dim );
2873       }
2874     }
2875
2876     af_glyph_hints_save( hints, outline );
2877
2878   Exit:
2879     return error;
2880   }
2881
2882
2883   /*************************************************************************/
2884   /*************************************************************************/
2885   /*****                                                               *****/
2886   /*****              L A T I N   S C R I P T   C L A S S              *****/
2887   /*****                                                               *****/
2888   /*************************************************************************/
2889   /*************************************************************************/
2890
2891
2892   AF_DEFINE_WRITING_SYSTEM_CLASS(
2893     af_latin_writing_system_class,
2894
2895     AF_WRITING_SYSTEM_LATIN,
2896
2897     sizeof ( AF_LatinMetricsRec ),
2898
2899     (AF_WritingSystem_InitMetricsFunc) af_latin_metrics_init,
2900     (AF_WritingSystem_ScaleMetricsFunc)af_latin_metrics_scale,
2901     (AF_WritingSystem_DoneMetricsFunc) NULL,
2902
2903     (AF_WritingSystem_InitHintsFunc)   af_latin_hints_init,
2904     (AF_WritingSystem_ApplyHintsFunc)  af_latin_hints_apply
2905   )
2906
2907
2908 /* END */