Search code examples
c++openglunicodesdl

Unicode Input Handling in Games


I have a game that requires me to allow players to chat with each other via network. All is well, except the part where players can type in Unicode input.

So, the question can be split into two parts:

  • When players type, how do I capture input? I have done this before via the game input handling (polling), however, it is not as responsive as something like Windows Forms.

  • After I capture input into a string, how do I output it using TrueType Fonts? The reason I ask this is because usually, I would build bitmap fonts at the start of the game from the all the text used in the game. But with unicode input, there are nearly 10k characters that are needed, which is quite impossible to build at the start of the game.

P.S. My target input languages are more specific to Chinese, Korean and Japanese.


Solution

  • For Input

    1. Use SDL_EnableUNICODE to enable unicode input handling
    2. Receive the SDL_KeyboardEvent as usual
    3. Use the unicode member of SDL_keysym to get the unicode

    For Rendering

    If the needed font size is reasonably small, say 16px, you actually could just render it all to a single texture, you can fit a minimum of 4096 glyphs on 1024x1024 texture at that size, a bit more when you pack them tightly (see fontgen for example code). That should be enough for common chat, but not enough to fit all the glyphs of a TTF file.

    If you don't want to use a larger texture size you have to generate the fonts on demand, to do that just create the Texture's as usual and then use glTexSubImage2D to upload new glyphs to the texture.

    Another alternative is to not use textures for glyphs, but for the text itself. That way you bypass all the trouble that glyph generation produces. But its probably not such a good idea for non-static editable text.