• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /****************************************************************************
2  *
3  * ttinterp.h
4  *
5  *   TrueType bytecode interpreter (specification).
6  *
7  * Copyright (C) 1996-2023 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 #ifndef TTINTERP_H_
20 #define TTINTERP_H_
21 
22 #include "ttobjs.h"
23 
24 
25 FT_BEGIN_HEADER
26 
27 
28   /**************************************************************************
29    *
30    * Rounding mode constants.
31    */
32 #define TT_Round_Off             5
33 #define TT_Round_To_Half_Grid    0
34 #define TT_Round_To_Grid         1
35 #define TT_Round_To_Double_Grid  2
36 #define TT_Round_Up_To_Grid      4
37 #define TT_Round_Down_To_Grid    3
38 #define TT_Round_Super           6
39 #define TT_Round_Super_45        7
40 
41 
42   /**************************************************************************
43    *
44    * Function types used by the interpreter, depending on various modes
45    * (e.g. the rounding mode, whether to render a vertical or horizontal
46    * line etc).
47    *
48    */
49 
50   /* Rounding function */
51   typedef FT_F26Dot6
52   (*TT_Round_Func)( TT_ExecContext  exc,
53                     FT_F26Dot6      distance,
54                     FT_Int          color );
55 
56   /* Point displacement along the freedom vector routine */
57   typedef void
58   (*TT_Move_Func)( TT_ExecContext  exc,
59                    TT_GlyphZone    zone,
60                    FT_UShort       point,
61                    FT_F26Dot6      distance );
62 
63   /* Distance projection along one of the projection vectors */
64   typedef FT_F26Dot6
65   (*TT_Project_Func)( TT_ExecContext  exc,
66                       FT_Pos          dx,
67                       FT_Pos          dy );
68 
69   /* getting current ppem.  Take care of non-square pixels if necessary */
70   typedef FT_Long
71   (*TT_Cur_Ppem_Func)( TT_ExecContext  exc );
72 
73   /* reading a cvt value.  Take care of non-square pixels if necessary */
74   typedef FT_F26Dot6
75   (*TT_Get_CVT_Func)( TT_ExecContext  exc,
76                       FT_ULong        idx );
77 
78   /* setting or moving a cvt value.  Take care of non-square pixels  */
79   /* if necessary                                                    */
80   typedef void
81   (*TT_Set_CVT_Func)( TT_ExecContext  exc,
82                       FT_ULong        idx,
83                       FT_F26Dot6      value );
84 
85 
86   /**************************************************************************
87    *
88    * This structure defines a call record, used to manage function calls.
89    */
90   typedef struct  TT_CallRec_
91   {
92     FT_Int   Caller_Range;
93     FT_Long  Caller_IP;
94     FT_Long  Cur_Count;
95 
96     TT_DefRecord  *Def; /* either FDEF or IDEF */
97 
98   } TT_CallRec, *TT_CallStack;
99 
100 
101 #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY
102 
103   /**************************************************************************
104    *
105    * These structures define rules used to tweak subpixel hinting for
106    * various fonts.  "", 0, "", NULL value indicates to match any value.
107    */
108 
109 #define SPH_MAX_NAME_SIZE      32
110 #define SPH_MAX_CLASS_MEMBERS  100
111 
112   typedef struct  SPH_TweakRule_
113   {
114     const char      family[SPH_MAX_NAME_SIZE];
115     const FT_UInt   ppem;
116     const char      style[SPH_MAX_NAME_SIZE];
117     const FT_ULong  glyph;
118 
119   } SPH_TweakRule;
120 
121 
122   typedef struct  SPH_ScaleRule_
123   {
124     const char      family[SPH_MAX_NAME_SIZE];
125     const FT_UInt   ppem;
126     const char      style[SPH_MAX_NAME_SIZE];
127     const FT_ULong  glyph;
128     const FT_ULong  scale;
129 
130   } SPH_ScaleRule;
131 
132 
133   typedef struct  SPH_Font_Class_
134   {
135     const char  name[SPH_MAX_NAME_SIZE];
136     const char  member[SPH_MAX_CLASS_MEMBERS][SPH_MAX_NAME_SIZE];
137 
138   } SPH_Font_Class;
139 
140 #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */
141 
142 
143   /**************************************************************************
144    *
145    * The main structure for the interpreter which collects all necessary
146    * variables and states.
147    *
148    * Members that are initialized by `TT_Load_Context` are marked with '!'.
149    * Members that are initialized by `TT_Run_Context` are marked with '@'.
150    */
151   typedef struct  TT_ExecContextRec_
152   {
153     TT_Face            face;       /* ! */
154     TT_Size            size;       /* ! */
155     FT_Memory          memory;
156 
157     /* instructions state */
158 
159     FT_Error           error;      /* last execution error */
160 
161     FT_Long            top;        /* @ top of exec. stack */
162 
163     FT_Long            stackSize;  /* ! size of exec. stack */
164     FT_Long*           stack;      /* ! current exec. stack */
165 
166     FT_Long            args;
167     FT_Long            new_top;    /* new top after exec. */
168 
169     TT_GlyphZoneRec    zp0,        /* @! zone records */
170                        zp1,        /* @!              */
171                        zp2,        /* @!              */
172                        pts,        /*  !              */
173                        twilight;   /*  !              */
174 
175     FT_Long            pointSize;  /* ! in 26.6 format */
176     FT_Size_Metrics    metrics;    /* !                */
177     TT_Size_Metrics    tt_metrics; /* ! size metrics   */
178 
179     TT_GraphicsState   GS;         /* !@ current graphics state */
180 
181     FT_Int             iniRange;  /* initial code range number   */
182     FT_Int             curRange;  /* current code range number   */
183     FT_Byte*           code;      /* current code range          */
184     FT_Long            IP;        /* current instruction pointer */
185     FT_Long            codeSize;  /* size of current range       */
186 
187     FT_Byte            opcode;    /* current opcode              */
188     FT_Int             length;    /* length of current opcode    */
189 
190     FT_Bool            step_ins;  /* true if the interpreter must */
191                                   /* increment IP after ins. exec */
192     FT_ULong           cvtSize;   /* ! */
193     FT_Long*           cvt;       /* ! */
194     FT_ULong           glyfCvtSize;
195     FT_Long*           glyfCvt;   /* cvt working copy for glyph */
196 
197     FT_UInt            glyphSize; /* ! glyph instructions buffer size */
198     FT_Byte*           glyphIns;  /* ! glyph instructions buffer      */
199 
200     FT_UInt            numFDefs;  /* ! number of function defs         */
201     FT_UInt            maxFDefs;  /* ! maximum number of function defs */
202     TT_DefArray        FDefs;     /*   table of FDefs entries          */
203 
204     FT_UInt            numIDefs;  /* ! number of instruction defs */
205     FT_UInt            maxIDefs;  /* ! maximum number of ins defs */
206     TT_DefArray        IDefs;     /*   table of IDefs entries     */
207 
208     FT_UInt            maxFunc;   /* ! maximum function index    */
209     FT_UInt            maxIns;    /* ! maximum instruction index */
210 
211     FT_Int             callTop,    /* @ top of call stack during execution */
212                        callSize;   /*   size of call stack                 */
213     TT_CallStack       callStack;  /*   call stack                         */
214 
215     FT_UShort          maxPoints;    /* capacity of this context's `pts' */
216     FT_Short           maxContours;  /* record, expressed in points and  */
217                                      /* contours.                        */
218 
219     TT_CodeRangeTable  codeRangeTable;  /* ! table of valid code ranges */
220                                         /*   useful for the debugger    */
221 
222     FT_UShort          storeSize;    /* ! size of current storage */
223     FT_Long*           storage;      /* ! storage area            */
224     FT_UShort          glyfStoreSize;
225     FT_Long*           glyfStorage;  /* storage working copy for glyph */
226 
227     FT_F26Dot6         period;     /* values used for the */
228     FT_F26Dot6         phase;      /* `SuperRounding'     */
229     FT_F26Dot6         threshold;
230 
231     FT_Bool            instruction_trap; /* ! If `True', the interpreter   */
232                                          /*   exits after each instruction */
233 
234     TT_GraphicsState   default_GS;       /* graphics state resulting from   */
235                                          /* the prep program                */
236     FT_Bool            is_composite;     /* true if the glyph is composite  */
237     FT_Bool            pedantic_hinting; /* true if pedantic interpretation */
238 
239     /* latest interpreter additions */
240 
241     FT_Long            F_dot_P;    /* dot product of freedom and projection */
242                                    /* vectors                               */
243     TT_Round_Func      func_round; /* current rounding function             */
244 
245     TT_Project_Func    func_project,   /* current projection function */
246                        func_dualproj,  /* current dual proj. function */
247                        func_freeProj;  /* current freedom proj. func  */
248 
249     TT_Move_Func       func_move;      /* current point move function     */
250     TT_Move_Func       func_move_orig; /* move original position function */
251 
252     TT_Cur_Ppem_Func   func_cur_ppem;  /* get current proj. ppem value  */
253 
254     TT_Get_CVT_Func    func_read_cvt;  /* read a cvt entry              */
255     TT_Set_CVT_Func    func_write_cvt; /* write a cvt entry (in pixels) */
256     TT_Set_CVT_Func    func_move_cvt;  /* incr a cvt entry (in pixels)  */
257 
258     FT_Bool            grayscale;      /* bi-level hinting and */
259                                        /* grayscale rendering  */
260 
261 #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL
262     /*
263      * FreeType supports ClearType-like hinting of TrueType fonts through
264      * the version 40 interpreter.  This is achieved through several hacks
265      * in the base (v35) interpreter, as detailed below.
266      *
267      * ClearType is an umbrella term for several rendering techniques
268      * employed by Microsoft's various GUI and rendering toolkit
269      * implementations, most importantly: subpixel rendering for using the
270      * RGB subpixels of LCDs to approximately triple the perceived
271      * resolution on the x-axis and subpixel hinting for positioning stems
272      * on subpixel borders.  TrueType programming is explicit, i.e., fonts
273      * must be programmed to take advantage of ClearType's possibilities.
274      *
275      * When ClearType was introduced, it seemed unlikely that all fonts
276      * would be reprogrammed, so Microsoft decided to implement a backward
277      * compatibility mode.  It employs several simple to complicated
278      * assumptions and tricks, many of them font-dependent, that modify the
279      * interpretation of the bytecode contained in these fonts to retrofit
280      * them into a ClearType-y look.  The quality of the results varies.
281      * Most (web)fonts that were released since then have come to rely on
282      * these hacks to render correctly, even some of Microsoft's flagship
283      * fonts (e.g., Calibri, Cambria, Segoe UI).
284      *
285      * FreeType's minimal subpixel hinting code (interpreter version 40)
286      * employs a small list of font-agnostic hacks loosely based on the
287      * public information available on Microsoft's compatibility mode[2].
288      * The focus is on modern (web)fonts rather than legacy fonts that were
289      * made for monochrome rendering.  It will not match ClearType rendering
290      * exactly.  Unlike the `Infinality' code (interpreter version 38) that
291      * came before, it will not try to toggle hacks for specific fonts for
292      * performance and complexity reasons.  It will fall back to version 35
293      * behavior for tricky fonts[1] or when monochrome rendering is
294      * requested.
295      *
296      * Major hacks
297      *
298      * - Any point movement on the x axis is ignored (cf. `Direct_Move' and
299      *   `Direct_Move_X').  This has the smallest code footprint and single
300      *   biggest effect.  The ClearType way to increase resolution is
301      *   supersampling the x axis, the FreeType way is ignoring instructions
302      *   on the x axis, which gives the same result in the majority of
303      *   cases.
304      *
305      * - Points are not moved post-IUP (neither on the x nor on the y axis),
306      *   except the x component of diagonal moves post-IUP (cf.
307      *   `Direct_Move', `Direct_Move_Y', `Move_Zp2_Point').  Post-IUP
308      *   changes are commonly used to `fix' pixel patterns which has little
309      *   use outside monochrome rendering.
310      *
311      * - SHPIX and DELTAP don't execute unless moving a composite on the
312      *   y axis or moving a previously y touched point.  SHPIX additionally
313      *   denies movement on the x axis (cf. `Ins_SHPIX' and `Ins_DELTAP').
314      *   Both instructions are commonly used to `fix' pixel patterns for
315      *   monochrome or Windows's GDI rendering but make little sense for
316      *   FreeType rendering.  Both can distort the outline.  See [2] for
317      *   details.
318      *
319      * - The hdmx table and modifications to phantom points are ignored.
320      *   Bearings and advance widths remain unchanged (except rounding them
321      *   outside the interpreter!), cf. `compute_glyph_metrics' and
322      *   `TT_Hint_Glyph'.  Letting non-native-ClearType fonts modify spacing
323      *   might mess up spacing.
324      *
325      * Minor hacks
326      *
327      * - FLIPRGON, FLIPRGOFF, and FLIPPT don't execute post-IUP.  This
328      *   prevents dents in e.g. Arial-Regular's `D' and `G' glyphs at
329      *   various sizes.
330      *
331      * (Post-IUP is the state after both IUP[x] and IUP[y] have been
332      * executed.)
333      *
334      * The best results are achieved for fonts that were from the outset
335      * designed with ClearType in mind, meaning they leave the x axis mostly
336      * alone and don't mess with the `final' outline to produce more
337      * pleasing pixel patterns.  The harder the designer tried to produce
338      * very specific patterns (`superhinting') for pre-ClearType-displays,
339      * the worse the results.
340      *
341      * Microsoft defines a way to turn off backward compatibility and
342      * interpret instructions as before (called `native ClearType')[2][3].
343      * The font designer then regains full control and is responsible for
344      * making the font work correctly with ClearType without any
345      * hand-holding by the interpreter or rasterizer[4].  The v40
346      * interpreter assumes backward compatibility by default, which can be
347      * turned off the same way by executing the following in the control
348      * program (cf. `Ins_INSTCTRL').
349      *
350      *   #PUSH 4,3
351      *   INSTCTRL[]
352      *
353      * [1] Tricky fonts as FreeType defines them rely on the bytecode
354      *     interpreter to display correctly.  Hacks can interfere with them,
355      *     so they get treated like native ClearType fonts (v40 with
356      *     backward compatibility turned off).  Cf. `TT_RunIns'.
357      *
358      * [2] Proposed by Microsoft's Greg Hitchcock in
359      *     https://www.microsoft.com/typography/cleartype/truetypecleartype.aspx
360      *
361      * [3] Beat Stamm describes it in more detail:
362      *     http://rastertragedy.com/RTRCh4.htm#Sec12.
363      *
364      * [4] The list of `native ClearType' fonts is small at the time of this
365      *     writing; I found the following on a Windows 10 Update 1511
366      *     installation: Constantia, Corbel, Sitka, Malgun Gothic, Microsoft
367      *     JhengHei (Bold and UI Bold), Microsoft YaHei (Bold and UI Bold),
368      *     SimSun, NSimSun, and Yu Gothic.
369      *
370      */
371 
372     /* Using v40 implies subpixel hinting, unless FT_RENDER_MODE_MONO has been
373      * requested.  Used to detect interpreter */
374     /* version switches.  `_lean' to differentiate from the Infinality */
375     /* `subpixel_hinting', which is managed differently.               */
376     FT_Bool            subpixel_hinting_lean;
377 
378     /* Long side of a LCD subpixel is vertical (e.g., screen is rotated). */
379     /* `_lean' to differentiate from the Infinality `vertical_lcd', which */
380     /* is managed differently.                                            */
381     FT_Bool            vertical_lcd_lean;
382 
383     /* Default to backward compatibility mode in v40 interpreter.  If   */
384     /* this is false, it implies the interpreter is in v35 or in native */
385     /* ClearType mode.                                                  */
386     FT_Bool            backward_compatibility;
387 
388     /* Useful for detecting and denying post-IUP trickery that is usually */
389     /* used to fix pixel patterns (`superhinting').                       */
390     FT_Bool            iupx_called;
391     FT_Bool            iupy_called;
392 
393     /* ClearType hinting and grayscale rendering, as used by Universal */
394     /* Windows Platform apps (Windows 8 and above).  Like the standard */
395     /* colorful ClearType mode, it utilizes a vastly increased virtual */
396     /* resolution on the x axis.  Different from bi-level hinting and  */
397     /* grayscale rendering, the old mode from Win9x days that roughly  */
398     /* adheres to the physical pixel grid on both axes.                */
399     FT_Bool            grayscale_cleartype;
400 #endif /* TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL */
401 
402 #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY
403     TT_Round_Func      func_round_sphn;   /* subpixel rounding function */
404 
405     FT_Bool            subpixel_hinting;  /* Using subpixel hinting?       */
406     FT_Bool            ignore_x_mode;     /* Standard rendering mode for   */
407                                           /* subpixel hinting.  On if gray */
408                                           /* or subpixel hinting is on.    */
409 
410     /* The following 6 aren't fully implemented but here for MS rasterizer */
411     /* compatibility.                                                      */
412     FT_Bool            compatible_widths;     /* compatible widths?        */
413     FT_Bool            symmetrical_smoothing; /* symmetrical_smoothing?    */
414     FT_Bool            bgr;                   /* bgr instead of rgb?       */
415     FT_Bool            vertical_lcd;          /* long side of LCD subpixel */
416                                               /* rectangles is horizontal  */
417     FT_Bool            subpixel_positioned;   /* subpixel positioned       */
418                                               /* (DirectWrite ClearType)?  */
419     FT_Bool            gray_cleartype;        /* ClearType hinting but     */
420                                               /* grayscale rendering       */
421 
422     FT_Int             rasterizer_version;    /* MS rasterizer version     */
423 
424     FT_Bool            iup_called;            /* IUP called for glyph?     */
425 
426     FT_ULong           sph_tweak_flags;       /* flags to control          */
427                                               /* hint tweaks               */
428 
429     FT_ULong           sph_in_func_flags;     /* flags to indicate if in   */
430                                               /* special functions         */
431 
432 #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */
433 
434     /* We maintain two counters (in addition to the instruction counter) */
435     /* that act as loop detectors for LOOPCALL and jump opcodes with     */
436     /* negative arguments.                                               */
437     FT_ULong           loopcall_counter;
438     FT_ULong           loopcall_counter_max;
439     FT_ULong           neg_jump_counter;
440     FT_ULong           neg_jump_counter_max;
441 
442   } TT_ExecContextRec;
443 
444 
445   extern const TT_GraphicsState  tt_default_graphics_state;
446 
447 
448 #ifdef TT_USE_BYTECODE_INTERPRETER
449   FT_LOCAL( void )
450   TT_Goto_CodeRange( TT_ExecContext  exec,
451                      FT_Int          range,
452                      FT_Long         IP );
453 
454   FT_LOCAL( void )
455   TT_Set_CodeRange( TT_ExecContext  exec,
456                     FT_Int          range,
457                     void*           base,
458                     FT_Long         length );
459 
460   FT_LOCAL( void )
461   TT_Clear_CodeRange( TT_ExecContext  exec,
462                       FT_Int          range );
463 
464 
465   FT_LOCAL( FT_Error )
466   Update_Max( FT_Memory  memory,
467               FT_ULong*  size,
468               FT_ULong   multiplier,
469               void*      _pbuff,
470               FT_ULong   new_max );
471 #endif /* TT_USE_BYTECODE_INTERPRETER */
472 
473 
474   /**************************************************************************
475    *
476    * @Function:
477    *   TT_New_Context
478    *
479    * @Description:
480    *   Create a `TT_ExecContext`.  Note that there is now an execution
481    *   context per `TT_Size` that is not shared among faces.
482    *
483    * @Input:
484    *   driver ::
485    *     A handle to the driver, used for memory allocation.
486    *
487    * @Return:
488    *   A handle to a new empty execution context.
489    *
490    * @Note:
491    *   Only the glyph loader and debugger should call this function.
492    *   (And right now only the glyph loader uses it.)
493    */
494   FT_EXPORT( TT_ExecContext )
495   TT_New_Context( TT_Driver  driver );
496 
497 
498 #ifdef TT_USE_BYTECODE_INTERPRETER
499   FT_LOCAL( void )
500   TT_Done_Context( TT_ExecContext  exec );
501 
502   FT_LOCAL( FT_Error )
503   TT_Load_Context( TT_ExecContext  exec,
504                    TT_Face         face,
505                    TT_Size         size );
506 
507   FT_LOCAL( void )
508   TT_Save_Context( TT_ExecContext  exec,
509                    TT_Size         ins );
510 
511   FT_LOCAL( FT_Error )
512   TT_Run_Context( TT_ExecContext  exec );
513 #endif /* TT_USE_BYTECODE_INTERPRETER */
514 
515 
516   /**************************************************************************
517    *
518    * @Function:
519    *   TT_RunIns
520    *
521    * @Description:
522    *   Executes one or more instruction in the execution context.  This
523    *   is the main function of the TrueType opcode interpreter.
524    *
525    * @Input:
526    *   exec ::
527    *     A handle to the target execution context.
528    *
529    * @Return:
530    *   FreeType error code.  0 means success.
531    *
532    * @Note:
533    *   Only the object manager and debugger should call this function.
534    *
535    *   This function is publicly exported because it is directly
536    *   invoked by the TrueType debugger.
537    */
538   FT_EXPORT( FT_Error )
539   TT_RunIns( TT_ExecContext  exec );
540 
541 
542 FT_END_HEADER
543 
544 #endif /* TTINTERP_H_ */
545 
546 
547 /* END */
548