I have just finished porting fractious’s Rendering Text in OpenGL on Android to OpenGL ES 2.0 (this is the mobile version of OpenGL 3.0 and the main difference with the older versions OpenGL is having acces to the shaders, which allow us to run code on the GPU).
I had to do this because my project TheHunt uses, you guessed it, the newer version. Reason is that it would allow me to do some nifty shader tricks… some day :-)
Some implementation details:
- I firstly started by simply converting the OpenGL ES 1 commands to the newer version. The Model, View and Projection matrices were passed using a uniform variable to the shaders, i.e. all the letters used the same matrices. This was good enough to produce horizontal text
- In TheHunt I use text to label events (fishbone flops, net snatches), and I need this text to be tilted (it would be somewhat boring otherwise). For this I needed to be able to assign individual model matrices to each word. A bit tricky, but using Sprite Batching in OpenGL ES 2.0 | Anton Holmquist as inspiration I managed to do it. In short, instead of an uniform Model-View-Projection matrix, the vertex shader has an uniform array of matrices. I fill this array with an individual matrix for each letter and also pass a matrix index attribute for each vertex (the exact same method suggested by Anton Holmquist.) The result is that each GLText::draw call can tilt the string drawn with a certain angle (it can now receive an angle argument, in degrees).
- The last catch was drawing color text – at first, all text was coming out black for me. The reason turns out to be that the texture is defined as grayscale, so in the fragment shader we need to multiply the color we want for the text (passed as uniform u_Color) with the grayscale value (called W in OpenGL) of the texture (not with the whole texture color, because it is something like [0, 0, 0, grayscale] which was resulting in the all black text):
gl_FragColor = texture2D(u_Texture, v_TexCoordinate).w * u_Color
— from BatchTextProgram.java
That’s all I can think of, and the result is efficient text drawing in OpenGL ES 2.0, and more importantly in TheHunt, where you can expect a nice GUI to appear soon!