r/GraphicsProgramming • • Apr 20 '15

Draw 2D Text in fixed position on the display in a 3D world - OpenGL

I am creating a very simple OpenGL game in C++, with a 3D model moving in a 3D world. I have to put on the screen some 2D text: the camera is constantly following the model and I would like the text to appear in a fixed position with respect to the window.

0 Upvotes

9 comments sorted by

5

u/JamiesWhiteShirt Apr 20 '15

When drawing the world, you are using a world projection. It seems you want to draw UI, which should be drawn with a different projection. An orthographic projection with pixel coordinates is fit for this task.

As for rendering text, it's a very difficult procedure. Have a look for a library to do it for you.

2

u/[deleted] Apr 24 '15

Rendering isn't that hard, but indeed actually interpreting font data is. Freetype is decent for this.

1

u/[deleted] Apr 21 '15

Absolutely the way to go. An orthographic matrix can also make it easier to place something in screen-space. This is because you can define the bounds of the orthographic projection to the width and height of the screen. Doing this, one OpenGL unit in space will correlate exactly to one pixel.

1

u/Madsy9 Apr 24 '15

World projection? Do you perhaps mean a perspective projection?

1

u/JamiesWhiteShirt Apr 25 '15

It is indeed a perspective projection, but it's also positioned and rotated to according to the camera.

2

u/drmugg123 Apr 20 '15

render your text to a framebuffer on top of the screen

1

u/fb39ca4 Apr 20 '15

Just use a different transformation matrix which only needs to scale and translate on the x and y axes, and not do a perspective projection.

1

u/smallstepforman Apr 22 '15

You need two cameras (perspective/projection/transformation matrices), an perspective (3D) camera for the world and an orthographic (2D) camera for the GUI.

-1

u/[deleted] Apr 24 '15 edited Apr 24 '15

Find a font reading library; Freetype is decent, as long as you don't mind a pure C API which IIRC is GPL.

There are articles on teh webz for how to read the bitmap data.

Rendering it is simple: with alpha blending enabled, you specify texture coordinates for a quad which is the size of the image and then map the texture to the quad.

Use a vertex shader which processes the input data in screen space, as others have said.

Then, in your fragment shader, just call GLSL's texture function and assign its first 3 coordinates to a vec4, like so:

Fragment = vec4(texture(sampler, uv).rgb, 0);

The zero, with alpha blending enabled, will ensure that the font faces don't have a background.

I'm almost positive this method is naive, but it's good if you just want to get something up and running in the meantime.

I might be missing a few things as well. Last time I did this I remember soecifying the internal texture format as GL_R8, and then swizzling with .rrr instead of .rgb. However, I don't think that's necessary.