TextServerManager in Godot – Complete Guide

When diving into the world of game development, one quickly realizes that managing text isn’t as simple as it seems. Whether you’re displaying dialogue in an RPG, showing scores in a sports game, or just rendering menus, efficient and flexible text management is vital. That’s where Godot 4’s TextServerManager comes into play. This powerful singleton class provides a backend API for handling all things text, from loading and enumerating to switching TextServers, ensuring that your game can support a wide array of languages and fonts with ease.

What is TextServerManager?

The TextServerManager is a core class in Godot 4’s engine. It serves as a management system for TextServer implementations, which are responsible for handling the complex task of text layout and rendering. The system allows developers to register different TextServers, switch between them, and query various attributes about the current state of text interfaces.

What is it for?

In any game or application, rendering text properly is crucial. The TextServerManager ensures you have the right tools to handle multiple languages, writing systems, and fonts. With it, you can create rich and localized text experiences for your players, all while maintaining performance and efficiency in your game’s text rendering.

Why Should I Learn About TextServerManager?

Understanding the TextServerManager is essential for any aspiring game developer using Godot 4:

– **Localization**: Makes your game accessible to a global audience.
– **Flexibility**: Lets you switch between different text rendering systems with ease.
– **Performance**: Aids in managing text rendering in the most efficient way possible.

By mastering the TextServerManager, you’ll be equipped to bring your game’s text to life in a way that’s both beautiful and functional, no matter where your players are from or what language they speak.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Enumerating Available TextServers

When you start working with TextServerManager, the first thing to grasp is how to list the TextServers that are available to your game. This can be essential if you plan to support multiple languages or special text rendering features. Here’s how you can enumerate the TextServers in your system:

var servers = TextServerManager.get_registered_text_servers()
for server in servers:
    print("TextServer: %s" % [server])

This code snippet will print out the names of all registered TextServers. Being familiar with what is available can help you decide which one to use based on your game’s needs.

Getting and Setting the Current TextServer

It’s important to know which TextServer is currently in use and, if necessary, to set a different one as the default. Use the following examples to get and set the TextServer:

To get the current TextServer:

var current_text_server = TextServerManager.get_primary_interface()
print("Current TextServer: %s" % [current_text_server.get_name()])

To set a different TextServer:

var desired_text_server_name = "YourTextServerNameHere"
var servers = TextServerManager.get_registered_text_servers()
for server_name in servers:
    if server_name == desired_text_server_name:
        TextServerManager.set_primary_interface(server_name)
        break

Ensure you replace “YourTextServerNameHere” with the actual name of the TextServer you want to set as primary. Changing the TextServer may drastically affect how the text is rendered in your game, so it’s a powerful feature.

Loading and Managing Fonts

Fonts are a critical part of text rendering, and Godot’s TextServerManager allows for dynamic loading and management of fonts:

To load a font:

var font_resource = preload("res://path/to/your/font.ttf")
var font = TextServer.font_create()
TextServer.font_set_data(font, font_resource)

To change the font size:

TextServer.font_set_size(font, size_in_pixels)

Remember that changing the font size can impact the visual layout of your game, so it’s something you may want to test with different resolutions and aspect ratios.

Creating and Configuring TextStyles

For more fine-tuned control over your text appearance, you’ll work with TextStyles. These are configurations that determine how text should look regarding color, outline, and more:

To create a TextStyle:

var style = TextServer.text_style_create()
TextServer.text_style_set_color(style, Color(1, 1, 1))  # Sets the text color to white
TextServer.text_style_set_outline(style, 1, Color(0, 0, 0))  # Sets a black outline with a width of 1

To apply TextStyle to a Label:

var label = Label.new()
label.add_text_style(style)

TextStyles offer you an incredible amount of customization for your game’s text, providing a professional and polished look regardless of the in-game context. With these basics under your belt, you’ll be well-equipped to move on to more advanced text management scenarios in Godot 4.Working with the TextServerManager provides a granular level of control over text rendering, which is essential for creating a game that can adapt to various languages and special typography needs. Below are more code examples that further explore capabilities provided by the TextServerManager.

Shaping Text with TextServer

Text shaping is the process of converting a string of characters into positioned glyphs. This process accounts for specific language rules and font metrics. Here’s how you can shape a piece of text in Godot 4:

var font = TextServer.font_create()
var shaped_text = TextServer.shaped_text_create()
TextServer.shaped_text_set_font(shaped_text, font)
TextServer.shaped_text_add_string(shaped_text, "Hello, Zenva!", [], 0)

This code will display “Hello, Zenva!” on the screen, shaped according to the font metrics. Note that the empty array `[]` and the `0` are placeholders for potential additional styling options and could be replaced by actual values if needed.

Rendering Shaped Text

Once you’ve shaped text, you might want to render it on screen. This involves creating a CanvasItem (such as Node2D or Control) and drawing the text within the `_draw()` function:

func _draw():
    TextServer.canvas_item_add_shaped_text(get_canvas_item(), Vector2(10, 20), shaped_text, 0, 1)

The `Vector2` specifies the position on the canvas where the text will start, in this case 10 pixels from the left and 20 pixels from the top.

Working with Bidirectional Text

Bidirectional text refers to text that contains both left-to-right and right-to-left scripts, which is typical in languages such as Arabic and Hebrew. Here’s how you handle that in Godot 4:

var bidi_override = TextServer.BIDI_OVERRIDE_LTR
TextServer.shaped_text_set_bidi_override(shaped_text, bidi_override)

This snippet sets the bidirectional override of the shaped text to left-to-right which can be useful for aligning mixed-language text in a predictable way.

Querying Text Properties

Often, you’ll need to know the dimensions of a piece of text to properly lay out your game UI. Godot 4 makes it easy to get this data:

var text_width = TextServer.shaped_text_get_width(shaped_text)
var text_height = TextServer.shaped_text_get_ascent(shaped_text) + TextServer.shaped_text_get_descent(shaped_text)

These lines of code calculate the width and height of the shaped text that you might use for UI placement and scaling.

Handling Font Fallbacks

Not every font supports every character. To handle this, Godot allows you to set font fallbacks:

var primary_font = TextServer.font_create()
var fallback_font = TextServer.font_create()
TextServer.font_add_fallback(primary_font, fallback_font)

If the primary font doesn’t support a given character, the engine will automatically attempt to use the fallback font. This system is crucial for supporting multiple languages and writing systems.

Adjusting Font Features

Advanced typography might require the use of special font features. This could include stylistic sets, ligatures, and other OpenType features. Here’s a simple way to enable an OpenType feature in Godot 4:

var features = {"ss01": 1} # Enable stylistic set 01
TextServer.font_set_features(primary_font, features)

By setting these features on your font, you can control the typography at a very detailed level, giving you the ability to fine-tune the text’s aesthetics in your game.

With this knowledge, you have a solid foundation for managing and rendering text in Godot 4 using the TextServerManager. Each of these examples is a building block towards creating a professional-looking and internationally adaptable game. Remember to experiment with these features to truly understand their power and how they can enhance the player’s experience in your game.Let’s delve deeper into the capabilities of the TextServerManager by exploring more complex text-handling scenarios such as accessing and manipulating glyph information, handling different directions of writing, adjusting line spacing, and preparing for printing or exporting.

Manipulating individual glyph information is sometimes necessary, for example, when you need to apply specific effects to certain characters or analyze the text’s structure. Godot provides methods to access glyphs within shaped text:

var glyph_count = TextServer.shaped_text_get_glyph_count(shaped_text)
for i in range(glyph_count):
    var glyph = TextServer.shaped_text_get_glyph(shaped_text, i)
    print("Glyph %d: %s" % [i, glyph.character])

By iterating over the glyphs in the `shaped_text`, you can retrieve detailed information about each glyph, such as its character code, its position, or whether it is visible.

When you come across scripts that are written from right to left, such as Hebrew or Arabic, handling text direction becomes essential:

var rtl_text = "مثال على نص بالعربية"  # An example in Arabic
var rtl_shaped_text = TextServer.shaped_text_create()
TextServer.shaped_text_add_string(rtl_shaped_text, rtl_text, [], 0)
TextServer.shaped_text_set_bidi_override(rtl_shaped_text, TextServer.BIDI_OVERRIDE_RTL)

By setting the bidirectional override to right-to-left for `rtl_shaped_text`, Godot ensures that the Arabic text is displayed in the correct direction.

To adjust line spacing, which affects the vertical distance between lines of text, use the `line_spacing` property. This is particularly useful when laying out paragraphs or adjusting the aesthetics of a multi-line text box:

var line_spacing = 1.5  # Multiplier of the default line height
TextServer.font_set_line_spacing(primary_font, line_spacing)

Line spacing can contribute significantly to the readability and visual appeal of your in-game text.

Lastly, preparing text for printing or exporting might require rendering it into an image or a series of images. This is a twofold process: shaping and then drawing the text onto an image surface:

var text_image = Image.new()
var text_texture = ImageTexture.new()
text_image.create_from_data(text_width, text_height, false, Image.FORMAT_RGBA8, TextServer.shaped_text_get_data(shaped_text))
text_texture.create_from_image(text_image)

Creating a texture from the image allows you to render this text as part of a UI element or use it in other parts of your game, including exporting it as an asset.

Continuously experimenting with TextServerManager methods is the key to learning and understanding the sophisticated text handling available in Godot 4. Every feature—from glyph manipulation to rendering shaped text—offers unique possibilities to elevate your game’s presentation. By integrating the functionalities covered and addressing the challenges along the way, you will enhance your proficiency and innovate the way gamers experience text within your projects.

Where to Go Next in Your Game Development Journey

Embarking on the journey of game development can be simultaneously thrilling and challenging. As you’ve taken the first steps in mastering text management with the Godot 4 TextServerManager, you may be wondering, “What’s next?” Your path to becoming a seasoned game developer doesn’t end here. In fact, the road ahead is teeming with opportunities to expand your skills and creativity.

We at Zenva know the importance of continuous learning and staying updated with the latest trends and technologies in game development. That’s why we encourage you to explore our Godot Game Development Mini-Degree, a carefully curated collection of courses that will guide you through building cross-platform games with Godot 4. This program is tailored to nurture beginners into proficient developers capable of crafting engaging and polished games.

Furthermore, our wide-ranging selection of Godot courses will aid you in enhancing your knowledge at any level. Whether you are starting out or looking to deepen your expertise, Zenva offers the tools and resources to support your growth as a developer. With project-based learning and hands-on examples, you can build a robust portfolio to showcase your talent to the world.

Your journey in game development is unique, and with dedication and the right learning resources, you are well on your way to creating games that captivate players. Stay curious, keep learning, and let Zenva be your guide to the vast and exciting realm of game creation.

Conclusion

As you’ve navigated through the intricacies of the TextServerManager in Godot 4, you’ve equipped yourself with essential tools to elevate the text in your games to professional standards. The power to create accessible, visually stunning, and performance-friendly text not only enriches your player’s experience but also sets your games apart in a crowded market. Remember that learning is a continuous process, and every new feature you master is a step closer to building the games of your dreams.

Don’t stop here; continue your journey by exploring our Godot Game Development Mini-Degree and other valuable courses at Zenva. We’re excited to see where your creativity and newly honed skills will take you next in the world of game development. Dive deep into Godot, and keep building wonderful worlds for gamers around the globe!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.