353b73a6403452da1d5410d1b919bead718adc94
[blender.git] / source / blender / blenlib / intern / freetypefont.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is written by Rob Haarsma (phase)
19  * All rights reserved.
20  *
21  * Contributor(s): none yet.
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  *
25  * This code parses the Freetype font outline data to chains of Blender's beziertriples.
26  * Additional information can be found at the bottom of this file.
27  *
28  * Code that uses exotic character maps is present but commented out.
29  */
30
31 /** \file blender/blenlib/intern/freetypefont.c
32  *  \ingroup bli
33  */
34
35
36 #ifdef _MSC_VER
37 #  pragma warning (disable:4244)
38 #endif
39
40 #include <ft2build.h>
41 #include FT_FREETYPE_H
42 /* not needed yet */
43 // #include FT_GLYPH_H
44 // #include FT_BBOX_H
45 // #include FT_SIZES_H
46 // #include <freetype/ttnameid.h>
47
48 #include "MEM_guardedalloc.h"
49
50 #include "BLI_vfontdata.h"
51 #include "BLI_blenlib.h"
52 #include "BLI_math.h"
53 #include "BLI_utildefines.h"
54
55 #include "DNA_vfont_types.h"
56 #include "DNA_packedFile_types.h"
57 #include "DNA_curve_types.h"
58
59 /* local variables */
60 static FT_Library library;
61 static FT_Error err;
62
63
64 static void freetypechar_to_vchar(FT_Face face, FT_ULong charcode, VFontData *vfd)
65 {
66         /* Blender */
67         struct Nurb *nu;
68         struct VChar *che;
69         struct BezTriple *bezt;
70
71         /* Freetype2 */
72         FT_GlyphSlot glyph;
73         FT_UInt glyph_index;
74         FT_Outline ftoutline;
75         float scale, height;
76         float dx, dy;
77         int j, k, l, m = 0;
78
79         /* adjust font size */
80         height = ((double) face->bbox.yMax - (double) face->bbox.yMin);
81         if (height != 0.0f)
82                 scale = 1.0f / height;
83         else
84                 scale = 1.0f / 1000.0f;
85
86         /*
87          * Generate the character 3D data
88          *
89          * Get the FT Glyph index and load the Glyph */
90         glyph_index = FT_Get_Char_Index(face, charcode);
91         err = FT_Load_Glyph(face, glyph_index, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP);
92
93         /* If loading succeeded, convert the FT glyph to the internal format */
94         if (!err) {
95                 int *npoints;
96                 int *onpoints;
97
98                 /* First we create entry for the new character to the character list */
99                 che = (VChar *) MEM_callocN(sizeof(struct VChar), "objfnt_char");
100                 BLI_addtail(&vfd->characters, che);
101
102                 /* Take some data for modifying purposes */
103                 glyph = face->glyph;
104                 ftoutline = glyph->outline;
105
106                 /* Set the width and character code */
107                 che->index = charcode;
108                 che->width = glyph->advance.x * scale;
109
110                 /* Start converting the FT data */
111                 npoints = (int *)MEM_callocN((ftoutline.n_contours) * sizeof(int), "endpoints");
112                 onpoints = (int *)MEM_callocN((ftoutline.n_contours) * sizeof(int), "onpoints");
113
114                 /* calculate total points of each contour */
115                 for (j = 0; j < ftoutline.n_contours; j++) {
116                         if (j == 0)
117                                 npoints[j] = ftoutline.contours[j] + 1;
118                         else
119                                 npoints[j] = ftoutline.contours[j] - ftoutline.contours[j - 1];
120                 }
121
122                 /* get number of on-curve points for beziertriples (including conic virtual on-points) */
123                 for (j = 0; j < ftoutline.n_contours; j++) {
124                         for (k = 0; k < npoints[j]; k++) {
125                                 l = (j > 0) ? (k + ftoutline.contours[j - 1] + 1) : k;
126
127                                 if (ftoutline.tags[l] == FT_Curve_Tag_On)
128                                         onpoints[j]++;
129
130                                 if (k < npoints[j] - 1) {
131                                         if (ftoutline.tags[l] == FT_Curve_Tag_Conic &&
132                                             ftoutline.tags[l + 1] == FT_Curve_Tag_Conic)
133                                         {
134                                                 onpoints[j]++;
135                                         }
136                                 }
137                         }
138                 }
139
140                 /* contour loop, bezier & conic styles merged */
141                 for (j = 0; j < ftoutline.n_contours; j++) {
142                         /* add new curve */
143                         nu  =  (Nurb *)MEM_callocN(sizeof(struct Nurb), "objfnt_nurb");
144                         bezt = (BezTriple *)MEM_callocN((onpoints[j]) * sizeof(BezTriple), "objfnt_bezt");
145                         BLI_addtail(&che->nurbsbase, nu);
146
147                         nu->type = CU_BEZIER;
148                         nu->pntsu = onpoints[j];
149                         nu->resolu = 8;
150                         nu->flag = CU_2D;
151                         nu->flagu = CU_NURB_CYCLIC;
152                         nu->bezt = bezt;
153
154                         /* individual curve loop, start-end */
155                         for (k = 0; k < npoints[j]; k++) {
156                                 if (j > 0) l = k + ftoutline.contours[j - 1] + 1; else l = k;
157                                 if (k == 0) m = l;
158
159                                 /* virtual conic on-curve points */
160                                 if (k < npoints[j] - 1) {
161                                         if (ftoutline.tags[l] == FT_Curve_Tag_Conic && ftoutline.tags[l + 1] == FT_Curve_Tag_Conic) {
162                                                 dx = (ftoutline.points[l].x + ftoutline.points[l + 1].x) * scale / 2.0f;
163                                                 dy = (ftoutline.points[l].y + ftoutline.points[l + 1].y) * scale / 2.0f;
164
165                                                 /* left handle */
166                                                 bezt->vec[0][0] = (dx + (2 * ftoutline.points[l].x) * scale) / 3.0f;
167                                                 bezt->vec[0][1] = (dy + (2 * ftoutline.points[l].y) * scale) / 3.0f;
168
169                                                 /* midpoint (virtual on-curve point) */
170                                                 bezt->vec[1][0] = dx;
171                                                 bezt->vec[1][1] = dy;
172
173                                                 /* right handle */
174                                                 bezt->vec[2][0] = (dx + (2 * ftoutline.points[l + 1].x) * scale) / 3.0f;
175                                                 bezt->vec[2][1] = (dy + (2 * ftoutline.points[l + 1].y) * scale) / 3.0f;
176
177                                                 bezt->h1 = bezt->h2 = HD_ALIGN;
178                                                 bezt->radius = 1.0f;
179                                                 bezt++;
180                                         }
181                                 }
182
183                                 /* on-curve points */
184                                 if (ftoutline.tags[l] == FT_Curve_Tag_On) {
185                                         /* left handle */
186                                         if (k > 0) {
187                                                 if (ftoutline.tags[l - 1] == FT_Curve_Tag_Cubic) {
188                                                         bezt->vec[0][0] = ftoutline.points[l - 1].x * scale;
189                                                         bezt->vec[0][1] = ftoutline.points[l - 1].y * scale;
190                                                         bezt->h1 = HD_FREE;
191                                                 }
192                                                 else if (ftoutline.tags[l - 1] == FT_Curve_Tag_Conic) {
193                                                         bezt->vec[0][0] = (ftoutline.points[l].x + (2 * ftoutline.points[l - 1].x)) * scale / 3.0f;
194                                                         bezt->vec[0][1] = (ftoutline.points[l].y + (2 * ftoutline.points[l - 1].y)) * scale / 3.0f;
195                                                         bezt->h1 = HD_FREE;
196                                                 }
197                                                 else {
198                                                         bezt->vec[0][0] = ftoutline.points[l].x * scale - (ftoutline.points[l].x - ftoutline.points[l - 1].x) * scale / 3.0f;
199                                                         bezt->vec[0][1] = ftoutline.points[l].y * scale - (ftoutline.points[l].y - ftoutline.points[l - 1].y) * scale / 3.0f;
200                                                         bezt->h1 = HD_VECT;
201                                                 }
202                                         }
203                                         else { /* first point on curve */
204                                                 if (ftoutline.tags[ftoutline.contours[j]] == FT_Curve_Tag_Cubic) {
205                                                         bezt->vec[0][0] = ftoutline.points[ftoutline.contours[j]].x * scale;
206                                                         bezt->vec[0][1] = ftoutline.points[ftoutline.contours[j]].y * scale;
207                                                         bezt->h1 = HD_FREE;
208                                                 }
209                                                 else if (ftoutline.tags[ftoutline.contours[j]] == FT_Curve_Tag_Conic) {
210                                                         bezt->vec[0][0] = (ftoutline.points[l].x + (2 * ftoutline.points[ftoutline.contours[j]].x)) * scale / 3.0f;
211                                                         bezt->vec[0][1] = (ftoutline.points[l].y + (2 * ftoutline.points[ftoutline.contours[j]].y)) * scale / 3.0f;
212                                                         bezt->h1 = HD_FREE;
213                                                 }
214                                                 else {
215                                                         bezt->vec[0][0] = ftoutline.points[l].x * scale - (ftoutline.points[l].x - ftoutline.points[ftoutline.contours[j]].x) * scale / 3.0f;
216                                                         bezt->vec[0][1] = ftoutline.points[l].y * scale - (ftoutline.points[l].y - ftoutline.points[ftoutline.contours[j]].y) * scale / 3.0f;
217                                                         bezt->h1 = HD_VECT;
218                                                 }
219                                         }
220
221                                         /* midpoint (on-curve point) */
222                                         bezt->vec[1][0] = ftoutline.points[l].x * scale;
223                                         bezt->vec[1][1] = ftoutline.points[l].y * scale;
224
225                                         /* right handle */
226                                         if (k < (npoints[j] - 1)) {
227                                                 if (ftoutline.tags[l + 1] == FT_Curve_Tag_Cubic) {
228                                                         bezt->vec[2][0] = ftoutline.points[l + 1].x * scale;
229                                                         bezt->vec[2][1] = ftoutline.points[l + 1].y * scale;
230                                                         bezt->h2 = HD_FREE;
231                                                 }
232                                                 else if (ftoutline.tags[l + 1] == FT_Curve_Tag_Conic) {
233                                                         bezt->vec[2][0] = (ftoutline.points[l].x + (2 * ftoutline.points[l + 1].x)) * scale / 3.0f;
234                                                         bezt->vec[2][1] = (ftoutline.points[l].y + (2 * ftoutline.points[l + 1].y)) * scale / 3.0f;
235                                                         bezt->h2 = HD_FREE;
236                                                 }
237                                                 else {
238                                                         bezt->vec[2][0] = ftoutline.points[l].x * scale - (ftoutline.points[l].x - ftoutline.points[l + 1].x) * scale / 3.0f;
239                                                         bezt->vec[2][1] = ftoutline.points[l].y * scale - (ftoutline.points[l].y - ftoutline.points[l + 1].y) * scale / 3.0f;
240                                                         bezt->h2 = HD_VECT;
241                                                 }
242                                         }
243                                         else { /* last point on curve */
244                                                 if (ftoutline.tags[m] == FT_Curve_Tag_Cubic) {
245                                                         bezt->vec[2][0] = ftoutline.points[m].x * scale;
246                                                         bezt->vec[2][1] = ftoutline.points[m].y * scale;
247                                                         bezt->h2 = HD_FREE;
248                                                 }
249                                                 else if (ftoutline.tags[m] == FT_Curve_Tag_Conic) {
250                                                         bezt->vec[2][0] = (ftoutline.points[l].x + (2 * ftoutline.points[m].x)) * scale / 3.0f;
251                                                         bezt->vec[2][1] = (ftoutline.points[l].y + (2 * ftoutline.points[m].y)) * scale / 3.0f;
252                                                         bezt->h2 = HD_FREE;
253                                                 }
254                                                 else {
255                                                         bezt->vec[2][0] = ftoutline.points[l].x * scale - (ftoutline.points[l].x - ftoutline.points[m].x) * scale / 3.0f;
256                                                         bezt->vec[2][1] = ftoutline.points[l].y * scale - (ftoutline.points[l].y - ftoutline.points[m].y) * scale / 3.0f;
257                                                         bezt->h2 = HD_VECT;
258                                                 }
259                                         }
260
261                                         /* get the handles that are aligned, tricky...
262                                          * dist_to_line_v2, check if the three beztriple points are on one line
263                                          * len_squared_v2v2, see if there's a distance between the three points
264                                          * len_squared_v2v2 again, to check the angle between the handles
265                                          * finally, check if one of them is a vector handle */
266                                         if ((bezt->h1 != HD_VECT && bezt->h2 != HD_VECT) &&
267                                             (dist_to_line_v2(bezt->vec[0], bezt->vec[1], bezt->vec[2]) < 0.001f) &&
268                                             (len_squared_v2v2(bezt->vec[0], bezt->vec[1]) > 0.0001f * 0.0001f) &&
269                                             (len_squared_v2v2(bezt->vec[1], bezt->vec[2]) > 0.0001f * 0.0001f) &&
270                                             (len_squared_v2v2(bezt->vec[0], bezt->vec[2]) > 0.0002f * 0.0001f) &&
271                                             (len_squared_v2v2(bezt->vec[0], bezt->vec[2]) >
272                                              max_ff(len_squared_v2v2(bezt->vec[0], bezt->vec[1]),
273                                                   len_squared_v2v2(bezt->vec[1], bezt->vec[2]))))
274                                         {
275                                                 bezt->h1 = bezt->h2 = HD_ALIGN;
276                                         }
277                                         bezt->radius = 1.0f;
278                                         bezt++;
279                                 }
280                         }
281                 }
282                 if (npoints) MEM_freeN(npoints);
283                 if (onpoints) MEM_freeN(onpoints);
284         }
285 }
286
287 static int objchr_to_ftvfontdata(VFont *vfont, FT_ULong charcode)
288 {
289         /* Freetype2 */
290         FT_Face face;
291
292         /* Load the font to memory */
293         if (vfont->temp_pf) {
294                 err = FT_New_Memory_Face(library,
295                                          vfont->temp_pf->data,
296                                          vfont->temp_pf->size,
297                                          0,
298                                          &face);
299                 if (err) return FALSE;
300         }
301         else {
302                 err = TRUE;
303                 return FALSE;
304         }
305                 
306         /* Read the char */
307         freetypechar_to_vchar(face, charcode, vfont->data);
308         
309         /* And everything went ok */
310         return TRUE;
311 }
312
313
314 static VFontData *objfnt_to_ftvfontdata(PackedFile *pf)
315 {
316         /* Variables */
317         FT_Face face;
318         FT_ULong charcode = 0, lcode;
319         FT_UInt glyph_index;
320         const char *fontname;
321         VFontData *vfd;
322
323 #if 0
324         FT_CharMap found = 0;
325         FT_CharMap charmap;
326         FT_UShort my_platform_id = TT_PLATFORM_MICROSOFT;
327         FT_UShort my_encoding_id = TT_MS_ID_UNICODE_CS;
328         int n;
329 #endif
330
331         /* load the freetype font */
332         err = FT_New_Memory_Face(library,
333                                  pf->data,
334                                  pf->size,
335                                  0,
336                                  &face);
337
338         if (err) return NULL;
339
340 #if 0
341         for (n = 0; n < face->num_charmaps; n++)
342         {
343                 charmap = face->charmaps[n];
344                 if (charmap->platform_id == my_platform_id &&
345                     charmap->encoding_id == my_encoding_id)
346                 {
347                         found = charmap;
348                         break;
349                 }
350         }
351
352         if (!found) { return NULL; }
353
354         /* now, select the charmap for the face object */
355         err = FT_Set_Charmap(face, found);
356         if (err) { return NULL; }
357 #endif
358
359         /* allocate blender font */
360         vfd = MEM_callocN(sizeof(*vfd), "FTVFontData");
361
362         /* get the name */
363         fontname = FT_Get_Postscript_Name(face);
364         BLI_strncpy(vfd->name, (fontname == NULL) ? "" : fontname, sizeof(vfd->name));
365
366         /* Extract the first 256 character from TTF */
367         lcode = charcode = FT_Get_First_Char(face, &glyph_index);
368
369         /* No charmap found from the ttf so we need to figure it out */
370         if (glyph_index == 0) {
371                 FT_CharMap found = NULL;
372                 FT_CharMap charmap;
373                 int n;
374
375                 for (n = 0; n < face->num_charmaps; n++) {
376                         charmap = face->charmaps[n];
377                         if (charmap->encoding == FT_ENCODING_APPLE_ROMAN) {
378                                 found = charmap;
379                                 break;
380                         }
381                 }
382
383                 err = FT_Set_Charmap(face, found);
384
385                 if (err)
386                         return NULL;
387
388                 lcode = charcode = FT_Get_First_Char(face, &glyph_index);
389         }
390
391         /* Load characters */
392         while (charcode < 256) {
393                 /* Generate the font data */
394                 freetypechar_to_vchar(face, charcode, vfd);
395
396                 /* Next glyph */
397                 charcode = FT_Get_Next_Char(face, charcode, &glyph_index);
398
399                 /* Check that we won't start infinite loop */
400                 if (charcode <= lcode)
401                         break;
402                 lcode = charcode;
403         }
404
405         return vfd;
406 }
407
408
409 static int check_freetypefont(PackedFile *pf)
410 {
411         FT_Face face;
412         FT_GlyphSlot glyph;
413         FT_UInt glyph_index;
414 #if 0
415         FT_CharMap charmap;
416         FT_CharMap found;
417         FT_UShort my_platform_id = TT_PLATFORM_MICROSOFT;
418         FT_UShort my_encoding_id = TT_MS_ID_UNICODE_CS;
419         int n;
420 #endif
421         int success = 0;
422
423         err = FT_New_Memory_Face(library,
424                                  pf->data,
425                                  pf->size,
426                                  0,
427                                  &face);
428         if (err) {
429                 success = 0;
430                 //XXX error("This is not a valid font");
431         }
432         else {
433
434 #if 0
435                 for (n = 0; n < face->num_charmaps; n++) {
436                         charmap = face->charmaps[n];
437                         if (charmap->platform_id == my_platform_id && charmap->encoding_id == my_encoding_id) {
438                                 found = charmap;
439                                 break;
440                         }
441                 }
442
443                 if (!found) { return 0; }
444
445                 /* now, select the charmap for the face object */
446                 err = FT_Set_Charmap(face, found);
447                 if (err) { return 0; }
448 #endif
449
450                 glyph_index = FT_Get_Char_Index(face, 'A');
451                 err = FT_Load_Glyph(face, glyph_index, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP);
452                 if (err) success = 0;
453                 else {
454                         glyph = face->glyph;
455                         if (glyph->format == ft_glyph_format_outline) {
456                                 success = 1;
457                         }
458                         else {
459                                 //XXX error("Selected Font has no outline data");
460                                 success = 0;
461                         }
462                 }
463         }
464         
465         return success;
466 }
467
468
469 VFontData *BLI_vfontdata_from_freetypefont(PackedFile *pf)
470 {
471         VFontData *vfd = NULL;
472         int success = 0;
473
474         /* init Freetype */
475         err = FT_Init_FreeType(&library);
476         if (err) {
477                 /* XXX error("Failed to load the Freetype font library"); */
478                 return NULL;
479         }
480
481         success = check_freetypefont(pf);
482         
483         if (success) {
484                 vfd = objfnt_to_ftvfontdata(pf);
485         }
486
487         /* free Freetype */
488         FT_Done_FreeType(library);
489         
490         return vfd;
491 }
492
493 int BLI_vfontchar_from_freetypefont(VFont *vfont, unsigned long character)
494 {
495         int success = FALSE;
496
497         if (!vfont) return FALSE;
498
499         /* Init Freetype */
500         err = FT_Init_FreeType(&library);
501         if (err) {
502                 /* XXX error("Failed to load the Freetype font library"); */
503                 return 0;
504         }
505
506         /* Load the character */
507         success = objchr_to_ftvfontdata(vfont, character);
508         if (success == FALSE) return FALSE;
509
510         /* Free Freetype */
511         FT_Done_FreeType(library);
512
513         /* Ahh everything ok */
514         return TRUE;
515 }
516
517 #if 0
518
519 /* Freetype2 Outline struct */
520
521 typedef struct  FT_Outline_
522 {
523         short       n_contours;      /* number of contours in glyph        */
524         short       n_points;        /* number of points in the glyph      */
525
526         FT_Vector  *points;          /* the outline's points               */
527         char       *tags;            /* the points flags                   */
528         short      *contours;        /* the contour end points             */
529
530         int         flags;           /* outline masks                      */
531 } FT_Outline;
532
533 #endif
534
535 /*
536  * from: http://www.freetype.org/freetype2/docs/glyphs/glyphs-6.html#section-1
537  *
538  * Vectorial representation of Freetype glyphs
539  *
540  * The source format of outlines is a collection of closed paths called "contours". Each contour is
541  * made of a series of line segments and bezier arcs. Depending on the file format, these can be
542  * second-order or third-order polynomials. The former are also called quadratic or conic arcs, and
543  * they come from the TrueType format. The latter are called cubic arcs and mostly come from the
544  * Type1 format.
545  *
546  * Each arc is described through a series of start, end and control points. Each point of the outline
547  * has a specific tag which indicates whether it is used to describe a line segment or an arc.
548  *
549  *
550  * The following rules are applied to decompose the contour's points into segments and arcs :
551  *
552  * # two successive "on" points indicate a line segment joining them.
553  *
554  * # one conic "off" point amidst two "on" points indicates a conic bezier arc, the "off" point being
555  *   the control point, and the "on" ones the start and end points.
556  *
557  * # Two successive cubic "off" points amidst two "on" points indicate a cubic bezier arc. There must
558  *   be exactly two cubic control points and two on points for each cubic arc (using a single cubic
559  *   "off" point between two "on" points is forbidden, for example).
560  *
561  * # finally, two successive conic "off" points forces the rasterizer to create (during the scan-line
562  *   conversion process exclusively) a virtual "on" point amidst them, at their exact middle. This
563  *   greatly facilitates the definition of successive conic bezier arcs. Moreover, it's the way
564  *   outlines are described in the TrueType specification.
565  *
566  * Note that it is possible to mix conic and cubic arcs in a single contour, even though no current
567  * font driver produces such outlines.
568  *
569  *                                   *            # on
570  *                                                * off
571  *                                __---__
572  *   #-__                      _--       -_
573  *       --__                _-            -
574  *           --__           #               \
575  *               --__                        #
576  *                   -#
577  *                            Two "on" points
578  *    Two "on" points       and one "conic" point
579  *                             between them
580  *
581  *
582  *
583  *                 *
584  *   #            __      Two "on" points with two "conic"
585  *    \          -  -     points between them. The point
586  *     \        /    \    marked '0' is the middle of the
587  *      -      0      \   "off" points, and is a 'virtual'
588  *       -_  _-       #   "on" point where the curve passes.
589  *         --             It does not appear in the point
590  *                        list.
591  *         *
592  *
593  *
594  *
595  *
596  *         *                # on
597  *                    *     * off
598  *          __---__
599  *       _--       -_
600  *     _-            -
601  *    #               \
602  *                     #
603  *
604  *      Two "on" points
605  *    and two "cubic" point
606  *       between them
607  *
608  *
609  * Each glyph's original outline points are located on a grid of indivisible units. The points are stored
610  * in the font file as 16-bit integer grid coordinates, with the grid origin's being at (0, 0); they thus
611  * range from -16384 to 16383.
612  *
613  * Convert conic to bezier arcs:
614  * Conic P0 P1 P2
615  * Bezier B0 B1 B2 B3
616  * B0=P0
617  * B1=(P0+2*P1)/3
618  * B2=(P2+2*P1)/3
619  * B3=P2
620  *
621  */