rougier / freetype-gl

OpenGL text using one vertex buffer, one texture and FreeType
Other
1.65k stars 266 forks source link

How to compute the pen origin for text_buffer_t when extents of text unknown #152

Open silverness2 opened 7 years ago

silverness2 commented 7 years ago

In my OpenGL program, I first display a sphere, and then, on the fly, I read in an arbitrary amount of text from a file and then display it on top of the sphere. I never know in advance the (width, height) of the text extents, the text's fonts and font sizes, etc.

I'm using the text_buffer_printf() function to write lines of markup_t text into a text_buffer_t, similar to the markup.c demo program. In that demo program, I see that the window size is initialized to (500, 220), and the pen offset is initialized to (20, 200), so all the markup text fits nicely in the window. It appears that the pen origin is the top left corner of the window.

The problem I'm running into is that because I don't know the metrics (font size, number of lines of text, etc) of the text beforehand, I can't set an appropriate window size to contain the text and I can't set an appropriate pen origin needed by text_buffer_printf().

If I'm restricted to setting a pen origin at the top left corner, what I'm trying to accomplish is this: 1 - get the extents of the text (width, height) 2 - initialize the pen offset to (0, height) so that the text origin begins at the top of the window 3 - load text using text_buffer_printf() with the pen offset from (2)

rougier commented 7 years ago

I agree this is a problem. One "quick and dirty solution": if you render the text anywhere for the first frame, can't you used the computed extents to move the text at the right place ?

Howewer, if your problem is to have the window at the right size from the beginning, it might be harder since we need an OpenGL to display text and compute extents. It means we probably need to have a dedicated offscreen method to compute text extents.

silverness2 commented 7 years ago

Thanks for your response.

What ended up working for me as a quick n' dirty solution was: 1 - set pen origin to (0,0) 2 - set up multi-line text using text_buffer_printf() 3 - use text_buffer_get_bounds() to get the height of the multi-line text 4 - clear the text buffer using text_buffer_clear() 5 - set pen origin to (0, height) 6 - set up multi-line text again using text_buffer_printf() 7 - set window size to (width, height) (I'm rendering the text into an OpenGL framebuffer object)

This works okay in my first scenario where the text does not change per new image frame. I'll have to evaluate performance for text that changes per frame of a movie playing in the background, for example.

rougier commented 7 years ago

Yes, the best would be to have a dedicated API. I remember a (very) long time ago being very frustrating not being able to do that with a text library and I don't want to be the cause of such frustration for others :)