The correct approach has already been explained
here. What you're trying to do is unnecessarily complex, the only thing you need is stbtt_GetCodepointHMetrics and the advance value.
I have updated the Truetype demo in the LWJGL repository with some example code,
here. It does the following:
- Iterates the string's codepoints correctly (i.e. combines surrogate pairs), so works across the entire UTF-16 range.
- Uses stbtt_GetCodepointHMetrics to sum the codepoint advance values. (super simple)
- Uses stbtt_GetCodepointKernAdvance to adjust the advance value, for fonts with kerning information. (improves quality significantly)
All of the above can be precomputed/cached for performance.
If you can run the demo, press K to toggle kerning on/off and B to render a bounding box around each line (it should be tight around the text). Note that the included demo/FiraSans.ttf does not have kerning information. Change it to e.g. C:\Windows\Fonts\Arial.ttf to see how kerning works.
Also note how the line bounding box is adjusted with the descent value returned from stbtt_GetFontVMetrics.