BLF: avoid glyph cache use-after free
[blender.git] / source / blender / blenfont / intern / blf_glyph.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 Copyright (C) 2009 Blender Foundation.
19  * All rights reserved.
20  *
21  * 
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenfont/intern/blf_glyph.c
28  *  \ingroup blf
29  *
30  * Glyph rendering, texturing and caching. Wraps Freetype and OpenGL functions.
31  */
32
33
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <math.h>
38
39 #include <ft2build.h>
40
41 #include FT_FREETYPE_H
42 #include FT_GLYPH_H
43 #include FT_OUTLINE_H
44 #include FT_BITMAP_H
45
46 #include "MEM_guardedalloc.h"
47
48 #include "DNA_vec_types.h"
49 #include "DNA_userdef_types.h"
50
51 #include "BLI_listbase.h"
52 #include "BLI_rect.h"
53 #include "BLI_threads.h"
54
55 #include "BIF_gl.h"
56 #include "BLF_api.h"
57
58 #ifndef BLF_STANDALONE
59 #include "GPU_basic_shader.h"
60 #endif
61
62 #include "blf_internal_types.h"
63 #include "blf_internal.h"
64
65 #include "BLI_strict_flags.h"
66
67 GlyphCacheBLF *blf_glyph_cache_find(FontBLF *font, unsigned int size, unsigned int dpi)
68 {
69         GlyphCacheBLF *p;
70
71         p = (GlyphCacheBLF *)font->cache.first;
72         while (p) {
73                 if (p->size == size && p->dpi == dpi)
74                         return p;
75                 p = p->next;
76         }
77         return NULL;
78 }
79
80 /* Create a new glyph cache for the current size and dpi. */
81 GlyphCacheBLF *blf_glyph_cache_new(FontBLF *font)
82 {
83         GlyphCacheBLF *gc;
84
85         gc = (GlyphCacheBLF *)MEM_callocN(sizeof(GlyphCacheBLF), "blf_glyph_cache_new");
86         gc->next = NULL;
87         gc->prev = NULL;
88         gc->size = font->size;
89         gc->dpi = font->dpi;
90
91         memset(gc->glyph_ascii_table, 0, sizeof(gc->glyph_ascii_table));
92         memset(gc->bucket, 0, sizeof(gc->bucket));
93
94         gc->textures = (GLuint *)MEM_mallocN(sizeof(GLuint) * 256, __func__);
95         gc->ntex = 256;
96         gc->cur_tex = BLF_CURTEX_UNSET;
97         gc->x_offs = 0;
98         gc->y_offs = 0;
99         gc->pad = 3;
100
101         gc->num_glyphs = (int)font->face->num_glyphs;
102         gc->rem_glyphs = (int)font->face->num_glyphs;
103         gc->ascender = ((float)font->face->size->metrics.ascender) / 64.0f;
104         gc->descender = ((float)font->face->size->metrics.descender) / 64.0f;
105
106         if (FT_IS_SCALABLE(font->face)) {
107                 gc->max_glyph_width = (int)((float)(font->face->bbox.xMax - font->face->bbox.xMin) *
108                                             (((float)font->face->size->metrics.x_ppem) /
109                                              ((float)font->face->units_per_EM)));
110
111                 gc->max_glyph_height = (int)((float)(font->face->bbox.yMax - font->face->bbox.yMin) *
112                                              (((float)font->face->size->metrics.y_ppem) /
113                                               ((float)font->face->units_per_EM)));
114         }
115         else {
116                 gc->max_glyph_width = (int)(((float)font->face->size->metrics.max_advance) / 64.0f);
117                 gc->max_glyph_height = (int)(((float)font->face->size->metrics.height) / 64.0f);
118         }
119
120         /* can happen with size 1 fonts */
121         CLAMP_MIN(gc->max_glyph_width, 1);
122         CLAMP_MIN(gc->max_glyph_height, 1);
123
124         gc->p2_width = 0;
125         gc->p2_height = 0;
126
127         BLI_addhead(&font->cache, gc);
128         return gc;
129 }
130
131 void blf_glyph_cache_clear(FontBLF *font)
132 {
133         GlyphCacheBLF *gc;
134
135         while ((gc = BLI_pophead(&font->cache))) {
136                 blf_glyph_cache_free(gc);
137         }
138         font->glyph_cache = NULL;
139 }
140
141 void blf_glyph_cache_free(GlyphCacheBLF *gc)
142 {
143         GlyphBLF *g;
144         int i;
145
146         for (i = 0; i < 257; i++) {
147                 while ((g = BLI_pophead(&gc->bucket[i]))) {
148                         blf_glyph_free(g);
149                 }
150         }
151
152         if (gc->cur_tex != BLF_CURTEX_UNSET)
153                 glDeleteTextures((int)gc->cur_tex + 1, gc->textures);
154         MEM_freeN((void *)gc->textures);
155         MEM_freeN(gc);
156 }
157
158 static void blf_glyph_cache_texture(FontBLF *font, GlyphCacheBLF *gc)
159 {
160         int i;
161
162         /* move the index. */
163         gc->cur_tex++;
164
165         if (UNLIKELY(gc->cur_tex >= gc->ntex)) {
166                 gc->ntex *= 2;
167                 gc->textures = (GLuint *)MEM_reallocN((void *)gc->textures, sizeof(GLuint) * gc->ntex);
168         }
169
170         gc->p2_width = (int)blf_next_p2((unsigned int)((gc->rem_glyphs * gc->max_glyph_width) + (gc->pad * 2)));
171         if (gc->p2_width > font->max_tex_size)
172                 gc->p2_width = font->max_tex_size;
173
174         i = (int)((gc->p2_width - (gc->pad * 2)) / gc->max_glyph_width);
175         gc->p2_height = (int)blf_next_p2((unsigned int)(((gc->num_glyphs / i) + 1) * gc->max_glyph_height));
176
177         if (gc->p2_height > font->max_tex_size)
178                 gc->p2_height = font->max_tex_size;
179
180         glGenTextures(1, &gc->textures[gc->cur_tex]);
181         glBindTexture(GL_TEXTURE_2D, (font->tex_bind_state = gc->textures[gc->cur_tex]));
182         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
183         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
184         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
185         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
186
187 #ifndef BLF_STANDALONE
188         /* needed since basic shader doesn't support alpha-only textures,
189          * while we could add support this is only used in a few places
190          * (an alternative could be to have a simple shader for BLF). */
191         if (GLEW_ARB_texture_swizzle && GPU_basic_shader_use_glsl_get()) {
192                 GLint swizzle_mask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ALPHA};
193                 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzle_mask);
194         }
195 #endif
196
197         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, gc->p2_width, gc->p2_height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, NULL);
198 }
199
200 GlyphBLF *blf_glyph_search(GlyphCacheBLF *gc, unsigned int c)
201 {
202         GlyphBLF *p;
203         unsigned int key;
204
205         key = blf_hash(c);
206         p = gc->bucket[key].first;
207         while (p) {
208                 if (p->c == c)
209                         return p;
210                 p = p->next;
211         }
212         return NULL;
213 }
214
215 GlyphBLF *blf_glyph_add(FontBLF *font, unsigned int index, unsigned int c)
216 {
217         FT_GlyphSlot slot;
218         GlyphBLF *g;
219         FT_Error err;
220         FT_Bitmap bitmap, tempbitmap;
221         const bool is_sharp = (U.text_render & USER_TEXT_DISABLE_AA) != 0;
222         int flags = FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;
223         FT_BBox bbox;
224         unsigned int key;
225
226         g = blf_glyph_search(font->glyph_cache, c);
227         if (g)
228                 return g;
229
230         /* glyphs are dynamically created as needed by font rendering. this means that
231          * to make font rendering thread safe we have to do locking here. note that this
232          * must be a lock for the whole library and not just per font, because the font
233          * renderer uses a shared buffer internally */
234         BLI_spin_lock(font->ft_lib_mutex);
235
236         /* search again after locking */
237         g = blf_glyph_search(font->glyph_cache, c);
238         if (g) {
239                 BLI_spin_unlock(font->ft_lib_mutex);
240                 return g;
241         }
242
243         if (font->flags & BLF_HINTING)
244                 flags &= ~FT_LOAD_NO_HINTING;
245         
246         if (is_sharp)
247                 err = FT_Load_Glyph(font->face, (FT_UInt)index, FT_LOAD_TARGET_MONO);
248         else
249                 err = FT_Load_Glyph(font->face, (FT_UInt)index, flags);  
250
251         if (err) {
252                 BLI_spin_unlock(font->ft_lib_mutex);
253                 return NULL;
254         }
255
256         /* get the glyph. */
257         slot = font->face->glyph;
258
259         if (is_sharp) {
260                 err = FT_Render_Glyph(slot, FT_RENDER_MODE_MONO);
261
262                 /* Convert result from 1 bit per pixel to 8 bit per pixel */
263                 /* Accum errors for later, fine if not interested beyond "ok vs any error" */
264                 FT_Bitmap_New(&tempbitmap);
265                 err += FT_Bitmap_Convert(font->ft_lib, &slot->bitmap, &tempbitmap, 1); /* Does Blender use Pitch 1 always? It works so far */
266                 err += FT_Bitmap_Copy(font->ft_lib, &tempbitmap, &slot->bitmap);
267                 err += FT_Bitmap_Done(font->ft_lib, &tempbitmap);
268         }
269         else {
270                 err = FT_Render_Glyph(slot, FT_RENDER_MODE_NORMAL);
271         }
272
273         if (err || slot->format != FT_GLYPH_FORMAT_BITMAP) {
274                 BLI_spin_unlock(font->ft_lib_mutex);
275                 return NULL;
276         }
277
278         g = (GlyphBLF *)MEM_callocN(sizeof(GlyphBLF), "blf_glyph_add");
279         g->c = c;
280         g->idx = (FT_UInt)index;
281         g->xoff = -1;
282         g->yoff = -1;
283         bitmap = slot->bitmap;
284         g->width = (int)bitmap.width;
285         g->height = (int)bitmap.rows;
286
287         if (g->width && g->height) {
288                 if (is_sharp) {
289                         /* Font buffer uses only 0 or 1 values, Blender expects full 0..255 range */
290                         int i;
291                         for (i = 0; i < (g->width * g->height); i++) {
292                                 bitmap.buffer[i] = bitmap.buffer[i] ? 255 : 0;
293                         }
294                 }
295
296                 g->bitmap = (unsigned char *)MEM_mallocN((size_t)(g->width * g->height), "glyph bitmap");
297                 memcpy((void *)g->bitmap, (void *)bitmap.buffer, (size_t)(g->width * g->height));
298         }
299
300         g->advance = ((float)slot->advance.x) / 64.0f;
301         g->advance_i = (int)g->advance;
302         g->pos_x = (float)slot->bitmap_left;
303         g->pos_y = (float)slot->bitmap_top;
304         g->pitch = slot->bitmap.pitch;
305
306         FT_Outline_Get_CBox(&(slot->outline), &bbox);
307         g->box.xmin = ((float)bbox.xMin) / 64.0f;
308         g->box.xmax = ((float)bbox.xMax) / 64.0f;
309         g->box.ymin = ((float)bbox.yMin) / 64.0f;
310         g->box.ymax = ((float)bbox.yMax) / 64.0f;
311
312         key = blf_hash(g->c);
313         BLI_addhead(&(font->glyph_cache->bucket[key]), g);
314
315         BLI_spin_unlock(font->ft_lib_mutex);
316
317         return g;
318 }
319
320 void blf_glyph_free(GlyphBLF *g)
321 {
322         /* don't need free the texture, the GlyphCache already
323          * have a list of all the texture and free it.
324          */
325         if (g->bitmap)
326                 MEM_freeN(g->bitmap);
327         MEM_freeN(g);
328 }
329
330 static void blf_texture_draw(float uv[2][2], float dx, float y1, float dx1, float y2)
331 {
332         glBegin(GL_QUADS);
333         glTexCoord2f(uv[0][0], uv[0][1]);
334         glVertex2f(dx, y1);
335         
336         glTexCoord2f(uv[0][0], uv[1][1]);
337         glVertex2f(dx, y2);
338         
339         glTexCoord2f(uv[1][0], uv[1][1]);
340         glVertex2f(dx1, y2);
341         
342         glTexCoord2f(uv[1][0], uv[0][1]);
343         glVertex2f(dx1, y1);
344         glEnd();
345 }
346
347 static void blf_texture5_draw(const float shadow_col[4], float uv[2][2], float x1, float y1, float x2, float y2)
348 {
349         const float soft[25] = {1 / 60.0f, 1 / 60.0f, 2 / 60.0f, 1 / 60.0f, 1 / 60.0f,
350                                 1 / 60.0f, 3 / 60.0f, 5 / 60.0f, 3 / 60.0f, 1 / 60.0f,
351                                 2 / 60.0f, 5 / 60.0f, 8 / 60.0f, 5 / 60.0f, 2 / 60.0f,
352                                 1 / 60.0f, 3 / 60.0f, 5 / 60.0f, 3 / 60.0f, 1 / 60.0f,
353                                 1 / 60.0f, 1 / 60.0f, 2 / 60.0f, 1 / 60.0f, 1 / 60.0f};
354         
355         const float *fp = soft;
356         float color[4];
357         float dx, dy;
358
359         color[0] = shadow_col[0];
360         color[1] = shadow_col[1];
361         color[2] = shadow_col[2];
362         
363         for (dx = -2; dx < 3; dx++) {
364                 for (dy = -2; dy < 3; dy++, fp++) {
365                         color[3] = *(fp) * shadow_col[3];
366                         glColor4fv(color);
367                         blf_texture_draw(uv, x1 + dx, y1 + dy, x2 + dx, y2 + dy);
368                 }
369         }
370         
371         glColor4fv(color);
372 }
373
374 static void blf_texture3_draw(const float shadow_col[4], float uv[2][2], float x1, float y1, float x2, float y2)
375 {
376         const float soft[9] = {1 / 16.0f, 2 / 16.0f, 1 / 16.0f,
377                                2 / 16.0f, 4 / 16.0f, 2 / 16.0f,
378                                1 / 16.0f, 2 / 16.0f, 1 / 16.0f};
379
380         const float *fp = soft;
381         float color[4];
382         float dx, dy;
383
384         color[0] = shadow_col[0];
385         color[1] = shadow_col[1];
386         color[2] = shadow_col[2];
387
388         for (dx = -1; dx < 2; dx++) {
389                 for (dy = -1; dy < 2; dy++, fp++) {
390                         color[3] = *(fp) * shadow_col[3];
391                         glColor4fv(color);
392                         blf_texture_draw(uv, x1 + dx, y1 + dy, x2 + dx, y2 + dy);
393                 }
394         }
395         
396         glColor4fv(color);
397 }
398
399 static void blf_glyph_calc_rect(rctf *rect, GlyphBLF *g, float x, float y)
400 {
401         rect->xmin = floorf(x + g->pos_x);
402         rect->xmax = rect->xmin + (float)g->width;
403         rect->ymin = y + g->pos_y;
404         rect->ymax = y + g->pos_y - (float)g->height;
405 }
406
407 void blf_glyph_render(FontBLF *font, GlyphBLF *g, float x, float y)
408 {
409         rctf rect;
410
411         if ((!g->width) || (!g->height))
412                 return;
413
414         if (g->build_tex == 0) {
415                 GlyphCacheBLF *gc = font->glyph_cache;
416
417                 if (font->max_tex_size == -1)
418                         glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint *)&font->max_tex_size);
419
420                 if (gc->cur_tex == BLF_CURTEX_UNSET) {
421                         blf_glyph_cache_texture(font, gc);
422                         gc->x_offs = gc->pad;
423                         gc->y_offs = 0;
424                 }
425
426                 if (gc->x_offs > (gc->p2_width - gc->max_glyph_width)) {
427                         gc->x_offs = gc->pad;
428                         gc->y_offs += gc->max_glyph_height;
429
430                         if (gc->y_offs > (gc->p2_height - gc->max_glyph_height)) {
431                                 gc->y_offs = 0;
432                                 blf_glyph_cache_texture(font, gc);
433                         }
434                 }
435
436                 g->tex = gc->textures[gc->cur_tex];
437                 g->xoff = gc->x_offs;
438                 g->yoff = gc->y_offs;
439
440                 /* prevent glTexSubImage2D from failing if the character
441                  * asks for pixels out of bounds, this tends only to happen
442                  * with very small sizes (5px high or less) */
443                 if (UNLIKELY((g->xoff + g->width)  > gc->p2_width)) {
444                         g->width  -= (g->xoff + g->width)  - gc->p2_width;
445                         BLI_assert(g->width > 0);
446                 }
447                 if (UNLIKELY((g->yoff + g->height) > gc->p2_height)) {
448                         g->height -= (g->yoff + g->height) - gc->p2_height;
449                         BLI_assert(g->height > 0);
450                 }
451
452
453                 glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
454                 glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
455                 glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
456                 glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
457
458                 glBindTexture(GL_TEXTURE_2D, g->tex);
459                 glTexSubImage2D(GL_TEXTURE_2D, 0, g->xoff, g->yoff, g->width, g->height, GL_ALPHA, GL_UNSIGNED_BYTE, g->bitmap);
460                 glPopClientAttrib();
461
462                 g->uv[0][0] = ((float)g->xoff) / ((float)gc->p2_width);
463                 g->uv[0][1] = ((float)g->yoff) / ((float)gc->p2_height);
464                 g->uv[1][0] = ((float)(g->xoff + g->width)) / ((float)gc->p2_width);
465                 g->uv[1][1] = ((float)(g->yoff + g->height)) / ((float)gc->p2_height);
466
467                 /* update the x offset for the next glyph. */
468                 gc->x_offs += (int)BLI_rctf_size_x(&g->box) + gc->pad;
469
470                 gc->rem_glyphs--;
471                 g->build_tex = 1;
472         }
473
474         blf_glyph_calc_rect(&rect, g, x, y);
475
476         if (font->flags & BLF_CLIPPING) {
477                 /* intentionally check clipping without shadow offset */
478                 rctf rect_test = rect;
479                 BLI_rctf_translate(&rect_test, font->pos[0], font->pos[1]);
480
481                 if (!BLI_rctf_inside_rctf(&font->clip_rec, &rect_test)) {
482                         return;
483                 }
484         }
485
486         if (font->tex_bind_state != g->tex) {
487                 glBindTexture(GL_TEXTURE_2D, (font->tex_bind_state = g->tex));
488         }
489
490         if (font->flags & BLF_SHADOW) {
491                 rctf rect_ofs;
492                 blf_glyph_calc_rect(&rect_ofs, g,
493                                     x + (float)font->shadow_x,
494                                     y + (float)font->shadow_y);
495
496                 switch (font->shadow) {
497                         case 3:
498                                 blf_texture3_draw(font->shadow_col, g->uv, rect_ofs.xmin, rect_ofs.ymin, rect_ofs.xmax, rect_ofs.ymax);
499                                 break;
500                         case 5:
501                                 blf_texture5_draw(font->shadow_col, g->uv, rect_ofs.xmin, rect_ofs.ymin, rect_ofs.xmax, rect_ofs.ymax);
502                                 break;
503                         default:
504                                 glColor4fv(font->shadow_col);
505                                 blf_texture_draw(g->uv, rect_ofs.xmin, rect_ofs.ymin, rect_ofs.xmax, rect_ofs.ymax);
506                                 break;
507                 }
508
509                 glColor4fv(font->orig_col);
510         }
511
512         switch (font->blur) {
513                 case 3:
514                         blf_texture3_draw(font->orig_col, g->uv, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
515                         break;
516                 case 5:
517                         blf_texture5_draw(font->orig_col, g->uv, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
518                         break;
519                 default:
520                         blf_texture_draw(g->uv, rect.xmin, rect.ymin, rect.xmax, rect.ymax);
521                         break;
522         }
523
524         return;
525 }