Merge branch 'blender2.7'
[blender.git] / source / blender / blenfont / intern / blf_glyph.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2009 Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file blender/blenfont/intern/blf_glyph.c
21  *  \ingroup blf
22  *
23  * Glyph rendering, texturing and caching. Wraps Freetype and OpenGL functions.
24  */
25
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <math.h>
31
32 #include <ft2build.h>
33
34 #include FT_FREETYPE_H
35 #include FT_GLYPH_H
36 #include FT_OUTLINE_H
37 #include FT_BITMAP_H
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_vec_types.h"
42 #include "DNA_userdef_types.h"
43
44 #include "BLI_listbase.h"
45 #include "BLI_rect.h"
46 #include "BLI_threads.h"
47
48 #include "BLF_api.h"
49
50 #ifndef BLF_STANDALONE
51 #  include "GPU_immediate.h"
52 #  include "GPU_extensions.h"
53 #endif
54
55 #include "blf_internal_types.h"
56 #include "blf_internal.h"
57
58 #include "BLI_strict_flags.h"
59 #include "BLI_math_vector.h"
60
61 KerningCacheBLF *blf_kerning_cache_find(FontBLF *font)
62 {
63         KerningCacheBLF *p;
64
65         p = (KerningCacheBLF *)font->kerning_caches.first;
66         while (p) {
67                 if (p->mode == font->kerning_mode)
68                         return p;
69                 p = p->next;
70         }
71         return NULL;
72 }
73
74 /* Create a new glyph cache for the current kerning mode. */
75 KerningCacheBLF *blf_kerning_cache_new(FontBLF *font)
76 {
77         KerningCacheBLF *kc;
78
79         kc = (KerningCacheBLF *)MEM_callocN(sizeof(KerningCacheBLF), "blf_kerning_cache_new");
80         kc->next = NULL;
81         kc->prev = NULL;
82         kc->mode = font->kerning_mode;
83
84         unsigned int i, j;
85         for (i = 0; i < 0x80; i++) {
86                 for (j = 0; j < 0x80; j++) {
87                         GlyphBLF *g = blf_glyph_search(font->glyph_cache, i);
88                         if (!g) {
89                                 FT_UInt glyph_index = FT_Get_Char_Index(font->face, i);
90                                 g = blf_glyph_add(font, glyph_index, i);
91                         }
92                         /* Cannot fail since it has been added just before. */
93                         GlyphBLF *g_prev = blf_glyph_search(font->glyph_cache, j);
94
95                         FT_Vector delta = { .x = 0, .y = 0, };
96                         if (FT_Get_Kerning(font->face, g_prev->idx, g->idx, kc->mode, &delta) == 0) {
97                                 kc->table[i][j] = (int)delta.x >> 6;
98                         }
99                         else {
100                                 kc->table[i][j] = 0;
101                         }
102                 }
103         }
104
105         BLI_addhead(&font->kerning_caches, kc);
106         return kc;
107 }
108
109 void blf_kerning_cache_clear(FontBLF *font)
110 {
111         font->kerning_cache = NULL;
112         BLI_freelistN(&font->kerning_caches);
113 }
114
115 GlyphCacheBLF *blf_glyph_cache_find(FontBLF *font, unsigned int size, unsigned int dpi)
116 {
117         GlyphCacheBLF *p;
118
119         p = (GlyphCacheBLF *)font->cache.first;
120         while (p) {
121                 if (p->size == size && p->dpi == dpi)
122                         return p;
123                 p = p->next;
124         }
125         return NULL;
126 }
127
128 /* Create a new glyph cache for the current size and dpi. */
129 GlyphCacheBLF *blf_glyph_cache_new(FontBLF *font)
130 {
131         GlyphCacheBLF *gc;
132
133         gc = (GlyphCacheBLF *)MEM_callocN(sizeof(GlyphCacheBLF), "blf_glyph_cache_new");
134         gc->next = NULL;
135         gc->prev = NULL;
136         gc->size = font->size;
137         gc->dpi = font->dpi;
138
139         memset(gc->glyph_ascii_table, 0, sizeof(gc->glyph_ascii_table));
140         memset(gc->bucket, 0, sizeof(gc->bucket));
141
142         gc->textures = (GPUTexture **)MEM_callocN(sizeof(GPUTexture *) * 256, __func__);
143         gc->textures_len = 256;
144         gc->texture_current = BLF_TEXTURE_UNSET;
145         gc->offset_x = 3; /* enough padding for blur */
146         gc->offset_y = 3; /* enough padding for blur */
147         gc->pad = 6;
148
149         gc->glyphs_len_max = (int)font->face->num_glyphs;
150         gc->glyphs_len_free = (int)font->face->num_glyphs;
151         gc->ascender = ((float)font->face->size->metrics.ascender) / 64.0f;
152         gc->descender = ((float)font->face->size->metrics.descender) / 64.0f;
153
154         if (FT_IS_SCALABLE(font->face)) {
155                 gc->glyph_width_max = (int)((float)(font->face->bbox.xMax - font->face->bbox.xMin) *
156                                             (((float)font->face->size->metrics.x_ppem) /
157                                              ((float)font->face->units_per_EM)));
158
159                 gc->glyph_height_max = (int)((float)(font->face->bbox.yMax - font->face->bbox.yMin) *
160                                              (((float)font->face->size->metrics.y_ppem) /
161                                               ((float)font->face->units_per_EM)));
162         }
163         else {
164                 gc->glyph_width_max = (int)(((float)font->face->size->metrics.max_advance) / 64.0f);
165                 gc->glyph_height_max = (int)(((float)font->face->size->metrics.height) / 64.0f);
166         }
167
168         /* can happen with size 1 fonts */
169         CLAMP_MIN(gc->glyph_width_max, 1);
170         CLAMP_MIN(gc->glyph_height_max, 1);
171
172         gc->p2_width = 0;
173         gc->p2_height = 0;
174
175         BLI_addhead(&font->cache, gc);
176         return gc;
177 }
178
179 void blf_glyph_cache_clear(FontBLF *font)
180 {
181         GlyphCacheBLF *gc;
182
183         while ((gc = BLI_pophead(&font->cache))) {
184                 blf_glyph_cache_free(gc);
185         }
186         font->glyph_cache = NULL;
187 }
188
189 void blf_glyph_cache_free(GlyphCacheBLF *gc)
190 {
191         GlyphBLF *g;
192         unsigned int i;
193
194         for (i = 0; i < 257; i++) {
195                 while ((g = BLI_pophead(&gc->bucket[i]))) {
196                         blf_glyph_free(g);
197                 }
198         }
199         for (i = 0; i < gc->textures_len; i++) {
200                 if (gc->textures[i]) {
201                         GPU_texture_free(gc->textures[i]);
202                 }
203         }
204         MEM_freeN(gc->textures);
205         MEM_freeN(gc);
206 }
207
208 static void blf_glyph_cache_texture(FontBLF *font, GlyphCacheBLF *gc)
209 {
210         int i;
211         char error[256];
212
213         /* move the index. */
214         gc->texture_current++;
215
216         if (UNLIKELY(gc->texture_current >= gc->textures_len)) {
217                 gc->textures_len *= 2;
218                 gc->textures = MEM_recallocN((void *)gc->textures, sizeof(GPUTexture *) * gc->textures_len);
219         }
220
221         gc->p2_width = (int)blf_next_p2((unsigned int)((gc->glyphs_len_free * gc->glyph_width_max) + (gc->pad * 2)));
222         if (gc->p2_width > font->tex_size_max) {
223                 gc->p2_width = font->tex_size_max;
224         }
225
226         i = (int)((gc->p2_width - (gc->pad * 2)) / gc->glyph_width_max);
227         gc->p2_height = (int)blf_next_p2((unsigned int)(((gc->glyphs_len_max / i) + 1) * gc->glyph_height_max + (gc->pad * 2)));
228
229         if (gc->p2_height > font->tex_size_max) {
230                 gc->p2_height = font->tex_size_max;
231         }
232
233         unsigned char *pixels = MEM_callocN((size_t)gc->p2_width * (size_t)gc->p2_height, "BLF texture init");
234         GPUTexture *tex = GPU_texture_create_nD(gc->p2_width, gc->p2_height, 0, 2, pixels, GPU_R8, GPU_DATA_UNSIGNED_BYTE, 0, false, error);
235         MEM_freeN(pixels);
236         gc->textures[gc->texture_current] = tex;
237         GPU_texture_bind(tex, 0);
238         GPU_texture_wrap_mode(tex, false);
239         GPU_texture_filters(tex, GPU_NEAREST, GPU_LINEAR);
240         GPU_texture_unbind(tex);
241 }
242
243 GlyphBLF *blf_glyph_search(GlyphCacheBLF *gc, unsigned int c)
244 {
245         GlyphBLF *p;
246         unsigned int key;
247
248         key = blf_hash(c);
249         p = gc->bucket[key].first;
250         while (p) {
251                 if (p->c == c)
252                         return p;
253                 p = p->next;
254         }
255         return NULL;
256 }
257
258 GlyphBLF *blf_glyph_add(FontBLF *font, unsigned int index, unsigned int c)
259 {
260         FT_GlyphSlot slot;
261         GlyphBLF *g;
262         FT_Error err;
263         FT_Bitmap bitmap, tempbitmap;
264         FT_BBox bbox;
265         unsigned int key;
266
267         g = blf_glyph_search(font->glyph_cache, c);
268         if (g)
269                 return g;
270
271         /* glyphs are dynamically created as needed by font rendering. this means that
272          * to make font rendering thread safe we have to do locking here. note that this
273          * must be a lock for the whole library and not just per font, because the font
274          * renderer uses a shared buffer internally */
275         BLI_spin_lock(font->ft_lib_mutex);
276
277         /* search again after locking */
278         g = blf_glyph_search(font->glyph_cache, c);
279         if (g) {
280                 BLI_spin_unlock(font->ft_lib_mutex);
281                 return g;
282         }
283
284         if (font->flags & BLF_MONOCHROME) {
285                 err = FT_Load_Glyph(font->face, (FT_UInt)index, FT_LOAD_TARGET_MONO);
286         }
287         else {
288                 int flags = FT_LOAD_NO_BITMAP;
289
290                 if (font->flags & BLF_HINTING_NONE) {
291                         flags |= FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING;
292                 }
293                 else if (font->flags & BLF_HINTING_SLIGHT) {
294                         flags |= FT_LOAD_TARGET_LIGHT;
295                 }
296                 else if (font->flags & BLF_HINTING_FULL) {
297                         flags |= FT_LOAD_TARGET_NORMAL;
298                 }
299                 else {
300                         /* Default, hinting disabled until FreeType has been upgraded
301                          * to give good results on all platforms. */
302                         flags |= FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING;
303                 }
304
305                 err = FT_Load_Glyph(font->face, (FT_UInt)index, flags);
306         }
307
308         if (err) {
309                 BLI_spin_unlock(font->ft_lib_mutex);
310                 return NULL;
311         }
312
313         /* get the glyph. */
314         slot = font->face->glyph;
315
316         if (font->flags & BLF_MONOCHROME) {
317                 err = FT_Render_Glyph(slot, FT_RENDER_MODE_MONO);
318
319                 /* Convert result from 1 bit per pixel to 8 bit per pixel */
320                 /* Accum errors for later, fine if not interested beyond "ok vs any error" */
321                 FT_Bitmap_New(&tempbitmap);
322                 err += FT_Bitmap_Convert(font->ft_lib, &slot->bitmap, &tempbitmap, 1); /* Does Blender use Pitch 1 always? It works so far */
323                 err += FT_Bitmap_Copy(font->ft_lib, &tempbitmap, &slot->bitmap);
324                 err += FT_Bitmap_Done(font->ft_lib, &tempbitmap);
325         }
326         else {
327                 err = FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
328         }
329
330         if (err || slot->format != FT_GLYPH_FORMAT_BITMAP) {
331                 BLI_spin_unlock(font->ft_lib_mutex);
332                 return NULL;
333         }
334
335         g = (GlyphBLF *)MEM_callocN(sizeof(GlyphBLF), "blf_glyph_add");
336         g->c = c;
337         g->idx = (FT_UInt)index;
338         g->offset_x = -1;
339         g->offset_y = -1;
340         bitmap = slot->bitmap;
341         g->width = (int)bitmap.width;
342         g->height = (int)bitmap.rows;
343
344         if (g->width && g->height) {
345                 if (font->flags & BLF_MONOCHROME) {
346                         /* Font buffer uses only 0 or 1 values, Blender expects full 0..255 range */
347                         int i;
348                         for (i = 0; i < (g->width * g->height); i++) {
349                                 bitmap.buffer[i] = bitmap.buffer[i] ? 255 : 0;
350                         }
351                 }
352
353                 g->bitmap = (unsigned char *)MEM_mallocN((size_t)g->width * (size_t)g->height, "glyph bitmap");
354                 memcpy((void *)g->bitmap, (void *)bitmap.buffer, (size_t)g->width * (size_t)g->height);
355         }
356
357         g->advance = ((float)slot->advance.x) / 64.0f;
358         g->advance_i = (int)g->advance;
359         g->pos_x = (float)slot->bitmap_left;
360         g->pos_y = (float)slot->bitmap_top;
361         g->pitch = slot->bitmap.pitch;
362
363         FT_Outline_Get_CBox(&(slot->outline), &bbox);
364         g->box.xmin = ((float)bbox.xMin) / 64.0f;
365         g->box.xmax = ((float)bbox.xMax) / 64.0f;
366         g->box.ymin = ((float)bbox.yMin) / 64.0f;
367         g->box.ymax = ((float)bbox.yMax) / 64.0f;
368
369         key = blf_hash(g->c);
370         BLI_addhead(&(font->glyph_cache->bucket[key]), g);
371
372         BLI_spin_unlock(font->ft_lib_mutex);
373
374         return g;
375 }
376
377 void blf_glyph_free(GlyphBLF *g)
378 {
379         /* don't need free the texture, the GlyphCache already
380          * have a list of all the texture and free it.
381          */
382         if (g->bitmap)
383                 MEM_freeN(g->bitmap);
384         MEM_freeN(g);
385 }
386
387 static void blf_texture_draw(const unsigned char color[4], const float uv[2][2], float x1, float y1, float x2, float y2)
388 {
389         /* Only one vertex per glyph, geometry shader expand it into a quad. */
390         /* TODO Get rid of Geom Shader because it's not optimal AT ALL for the GPU */
391         copy_v4_fl4(GPU_vertbuf_raw_step(&g_batch.pos_step), x1 + g_batch.ofs[0], y1 + g_batch.ofs[1],
392                                                              x2 + g_batch.ofs[0], y2 + g_batch.ofs[1]);
393         copy_v4_v4(GPU_vertbuf_raw_step(&g_batch.tex_step), (float *)uv);
394         copy_v4_v4_uchar(GPU_vertbuf_raw_step(&g_batch.col_step), color);
395         g_batch.glyph_len++;
396         /* Flush cache if it's full. */
397         if (g_batch.glyph_len == BLF_BATCH_DRAW_LEN_MAX) {
398                 blf_batch_draw();
399         }
400 }
401
402 static void blf_texture5_draw(const unsigned char color_in[4], int tex_w, int tex_h, const float uv[2][2],
403                               float x1, float y1, float x2, float y2)
404 {
405         float ofs[2] = { 2 / (float)tex_w, 2 / (float)tex_h };
406         float uv_flag[2][2];
407         copy_v4_v4((float *)uv_flag, (float *)uv);
408         /* flag the x and y component signs for 5x5 blurring */
409         uv_flag[0][0] = -(uv_flag[0][0] - ofs[0]);
410         uv_flag[0][1] = -(uv_flag[0][1] - ofs[1]);
411         uv_flag[1][0] = -(uv_flag[1][0] + ofs[0]);
412         uv_flag[1][1] = -(uv_flag[1][1] + ofs[1]);
413
414         blf_texture_draw(color_in, uv_flag, x1 - 2, y1 + 2, x2 + 2, y2 - 2);
415 }
416
417 static void blf_texture3_draw(const unsigned char color_in[4], int tex_w, int tex_h, const float uv[2][2],
418                               float x1, float y1, float x2, float y2)
419 {
420         float ofs[2] = { 1 / (float)tex_w, 1 / (float)tex_h };
421         float uv_flag[2][2];
422         copy_v4_v4((float *)uv_flag, (float *)uv);
423         /* flag the x component sign for 3x3 blurring */
424         uv_flag[0][0] = -(uv_flag[0][0] - ofs[0]);
425         uv_flag[0][1] =  (uv_flag[0][1] - ofs[1]);
426         uv_flag[1][0] = -(uv_flag[1][0] + ofs[0]);
427         uv_flag[1][1] =  (uv_flag[1][1] + ofs[1]);
428
429         blf_texture_draw(color_in, uv_flag, x1 - 1, y1 + 1, x2 + 1, y2 - 1);
430 }
431
432 static void blf_glyph_calc_rect(rctf *rect, GlyphBLF *g, float x, float y)
433 {
434         rect->xmin = floorf(x + g->pos_x);
435         rect->xmax = rect->xmin + (float)g->width;
436         rect->ymin = floorf(y + g->pos_y);
437         rect->ymax = rect->ymin - (float)g->height;
438 }
439
440 void blf_glyph_render(FontBLF *font, GlyphBLF *g, float x, float y)
441 {
442         rctf rect;
443
444         if ((!g->width) || (!g->height))
445                 return;
446
447         if (g->build_tex == 0) {
448                 GlyphCacheBLF *gc = font->glyph_cache;
449
450                 if (font->tex_size_max == -1)
451                         font->tex_size_max = GPU_max_texture_size();
452
453                 if (gc->texture_current == BLF_TEXTURE_UNSET) {
454                         blf_glyph_cache_texture(font, gc);
455                         gc->offset_x = gc->pad;
456                         gc->offset_y = 3; /* enough padding for blur */
457                 }
458
459                 if (gc->offset_x > (gc->p2_width - gc->glyph_width_max)) {
460                         gc->offset_x = gc->pad;
461                         gc->offset_y += gc->glyph_height_max;
462
463                         if (gc->offset_y > (gc->p2_height - gc->glyph_height_max)) {
464                                 gc->offset_y = 3; /* enough padding for blur */
465                                 blf_glyph_cache_texture(font, gc);
466                         }
467                 }
468
469                 g->tex = gc->textures[gc->texture_current];
470                 g->offset_x = gc->offset_x;
471                 g->offset_y = gc->offset_y;
472
473                 /* prevent glTexSubImage2D from failing if the character
474                  * asks for pixels out of bounds, this tends only to happen
475                  * with very small sizes (5px high or less) */
476                 if (UNLIKELY((g->offset_x + g->width)  > gc->p2_width)) {
477                         g->width  -= (g->offset_x + g->width)  - gc->p2_width;
478                         BLI_assert(g->width > 0);
479                 }
480                 if (UNLIKELY((g->offset_y + g->height) > gc->p2_height)) {
481                         g->height -= (g->offset_y + g->height) - gc->p2_height;
482                         BLI_assert(g->height > 0);
483                 }
484
485                 GPU_texture_update_sub(g->tex, GPU_DATA_UNSIGNED_BYTE, g->bitmap, g->offset_x, g->offset_y, 0, g->width, g->height, 0);
486
487                 g->uv[0][0] = ((float)g->offset_x) / ((float)gc->p2_width);
488                 g->uv[0][1] = ((float)g->offset_y) / ((float)gc->p2_height);
489                 g->uv[1][0] = ((float)(g->offset_x + g->width)) / ((float)gc->p2_width);
490                 g->uv[1][1] = ((float)(g->offset_y + g->height)) / ((float)gc->p2_height);
491
492                 /* update the x offset for the next glyph. */
493                 gc->offset_x += (int)BLI_rctf_size_x(&g->box) + gc->pad;
494
495                 gc->glyphs_len_free--;
496                 g->build_tex = 1;
497         }
498
499         blf_glyph_calc_rect(&rect, g, x, y);
500
501         if (font->flags & BLF_CLIPPING) {
502                 /* intentionally check clipping without shadow offset */
503                 rctf rect_test = rect;
504                 BLI_rctf_translate(&rect_test, font->pos[0], font->pos[1]);
505
506                 if (!BLI_rctf_inside_rctf(&font->clip_rec, &rect_test)) {
507                         return;
508                 }
509         }
510
511         if (font->tex_bind_state != g->tex) {
512                 blf_batch_draw();
513                 font->tex_bind_state = g->tex;
514                 GPU_texture_bind(font->tex_bind_state, 0);
515         }
516
517         g_batch.tex_bind_state = g->tex;
518
519         if (font->flags & BLF_SHADOW) {
520                 rctf rect_ofs;
521                 blf_glyph_calc_rect(&rect_ofs, g,
522                                     x + (float)font->shadow_x,
523                                     y + (float)font->shadow_y);
524
525                 if (font->shadow == 0) {
526                         blf_texture_draw(font->shadow_color, g->uv, rect_ofs.xmin, rect_ofs.ymin, rect_ofs.xmax, rect_ofs.ymax);
527                 }
528                 else if (font->shadow <= 4) {
529                         blf_texture3_draw(font->shadow_color, font->glyph_cache->p2_width, font->glyph_cache->p2_height, g->uv,
530                                           rect_ofs.xmin, rect_ofs.ymin, rect_ofs.xmax, rect_ofs.ymax);
531                 }
532                 else {
533                         blf_texture5_draw(font->shadow_color, font->glyph_cache->p2_width, font->glyph_cache->p2_height, g->uv,
534                                           rect_ofs.xmin, rect_ofs.ymin, rect_ofs.xmax, rect_ofs.ymax);
535                 }
536         }
537
538 #if BLF_BLUR_ENABLE
539         switch (font->blur) {
540                 case 3:
541                         blf_texture3_draw(font->color, font->glyph_cache->p2_width, font->glyph_cache->p2_height, g->uv,
542                                           rect.xmin, rect.ymin, rect.xmax, rect.ymax);
543                         break;
544                 case 5:
545                         blf_texture5_draw(font->color, font->glyph_cache->p2_width, font->glyph_cache->p2_height, g->uv,
546                                           rect.xmin, rect.ymin, rect.xmax, rect.ymax);
547                         break;
548                 default:
549                         blf_texture_draw(font->color, g->uv, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
550         }
551 #else
552         blf_texture_draw(font->color, g->uv, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
553 #endif
554 }