Easy3D 3.0.0
Loading...
Searching...
No Matches
Tutorial_309_TextRendering

Rendering 2D strings (labels, HUDs, annotations) with Easy3D's text layout engine.

Overview

This tutorial draws text on top of a 3D scene: a multi-line instruction block plus a gallery line for every installed font, each in a different color. All layout and rasterization happen on the CPU in a TextLayoutEngine; the resulting textured quads are handed to the viewer as overlay draw commands. The TutorialTextRendering class below rebuilds the text whenever a layout parameter changes (font size, spacing, alignment, origin, kerning, window size, DPI).

The technique

Real-time text rendering is usually done with a glyph (font) atlas: each needed character is rasterized once from the TrueType outlines into a small region of a texture, and drawing a string then becomes drawing one textured quad per character, sampling its glyph from the atlas. Layout decides where each quad goes: advancing by each glyph's width, applying extra character/line spacing, aligning shorter lines within the longest one, and optionally kerning (tightening specific pairs like "AV" using the font's kerning table). Because glyph bitmaps are resolution-dependent, sizes are specified in framebuffer pixels: on high-DPI displays the framebuffer is larger than the window, so the tutorial scales all sizes by framebuffer_width()/width() to keep the text crisp and physically the same size. Layouts are immutable snapshots, so previously issued draw commands stay valid even after the cache is cleared and new glyphs are rasterized.

Easy3D API

Running it

'+'/'-' change the font size, '<'/'>' the character spacing, 'up'/'down' the line spacing, 'l'/'c'/'r' the alignment of the multi-line block, 'o' switches the origin between upper-left and bottom-left, and 'space' toggles kerning. The usual viewer navigation still works.

1
27#include "viewer.h"
28#include <easy3d/util/resource.h>
29#include <easy3d/util/initializer.h>
30
83using namespace easy3d;
84
85int main(int argc, char **argv) {
86 // initialize Easy3D.
87 initialize();
88
89 // A simple background model so the text overlays are seen on top of a real 3D scene.
90 const std::string file_name = resource::directory() + "/data/sphere.obj";
91
92 // The constructor loads every .ttf font found in the resource fonts directory.
93 TutorialTextRendering viewer(EXAMPLE_TITLE);
94
95 viewer.add_model(file_name);
96
97 // run the viewer
98 return viewer.run();
99}
Definition collider.cpp:182

The header file of the viewer class:

1
27#ifndef EASY3D_TUTORIAL_TEXT_RENDERING_H
28#define EASY3D_TUTORIAL_TEXT_RENDERING_H
29
30#include <easy3d/viewer/viewer.h>
31
32#include <easy3d/renderer/text_layout.h>
33
43class TutorialTextRendering : public easy3d::Viewer {
44public:
45 // Loads all TrueType fonts from the resource directory into the layout engine.
46 explicit TutorialTextRendering(const std::string &title);
47 ~TutorialTextRendering() override;
48
49protected:
50 // Edits the layout parameters (size, spacing, alignment, origin, kerning).
51 bool key_press_event(int key, int modifiers) override;
52 // Window size changed: the text must be laid out again for the new framebuffer.
53 void post_resize(int width, int height) override;
54 // Rebuilds the overlay draw commands when the layout is dirty (see viewer.cpp).
55 void pre_draw() override;
56
57private:
58 // The layout engine; 1024 is the glyph atlas texture size in pixels.
60 // Layout parameters in window units; dpi_ caches the last framebuffer/window scale.
61 float size_ = 28, spacing_ = 0, line_spacing_ = 0, dpi_ = 0;
62 easy3d::graphics::TextAlign align_ = easy3d::graphics::TextAlign::center;
63 // upper_left_: text origin convention; kerning_: pairwise glyph tightening;
64 // dirty_: a re-layout is needed before the next frame.
65 bool upper_left_ = true, kerning_ = false, dirty_ = true;
66};
67
68#endif // EASY3D_TUTORIAL_TEXT_RENDERING_H
The default viewer implementation for both OpenGL and Vulkan backends.
Definition viewer.h:143
Rasterize TrueType glyphs and produce backend-independent text commands.
Definition text_layout.h:85

The source file of the viewer class:

1
27#include "viewer.h"
28
29
30#include <easy3d/renderer/text_layout.h>
31#include <easy3d/util/file_system.h>
32#include <easy3d/util/resource.h>
33#include <algorithm>
34#include <cmath>
35#include <cctype>
36#include <stdexcept>
37
38#include "easy3d/core/random.h"
39
40using namespace easy3d;
41
42// \cond
43TutorialTextRendering::TutorialTextRendering(const std::string &title) : Viewer(title) {
44 // manual_ is the help text shown by the viewer's built-in help overlay.
45 manual_ =
46 "----------------------- Text Rendering usage ------------------------ \n"
47 "Press '+'/'-' to increase/decrease font size \n"
48 "Press '<'/'>' to increase/decrease character spacing \n"
49 "Press 'up'/'down' to increase/decrease line spacing \n"
50 "Press 'l'/'c'/'r' to left/center/right align the multi-line text \n"
51 "Press 'o' to switch the origin between 'upper left' and 'bottom left' \n"
52 "Press 'space' to enable/disable kerning \n"
53 "--------------------------------------------------------------------- \n";
54
55 // Discover every font shipped with the resources and register it with the engine.
56 // Each font gets an index (its position in font_names()), used later as TextOptions::font.
57 std::vector<std::string> files;
58 easy3d::file_system::get_directory_entries(easy3d::resource::directory() + "/fonts/", files, false);
59 std::sort(files.begin(), files.end());
60 for (const auto &file : files) {
61 auto extension = easy3d::file_system::extension(file);
62 std::transform(extension.begin(), extension.end(), extension.begin(),
63 [](unsigned char c) { return char(std::tolower(c)); });
64 if (extension == "ttf")
65 text_.add_font(easy3d::resource::directory() + "/fonts/" + file);
66 }
67 // Without fonts there is nothing to render, so fail loudly instead of showing a blank HUD.
68 if (text_.font_names().empty())
69 throw std::runtime_error("Tutorial 309 requires the resource fonts");
70}
71
72TutorialTextRendering::~TutorialTextRendering() = default;
73
74// Each recognized key edits one layout parameter (clamped to a sensible range), then marks
75// the layout dirty and requests a redraw. Unrecognized keys go to the base Viewer.
76bool TutorialTextRendering::key_press_event(int key, int modifiers) {
77 using easy3d::graphics::TextAlign;
78 switch (key) {
79 case KEY_MINUS:
80 size_ = std::max(8.0f, size_ - 1);
81 break;
82 case KEY_EQUAL:
83 // '+' is shift+'=' on most keyboard layouts, hence KEY_EQUAL.
84 size_ = std::min(278.0f, size_ + 1);
85 break;
86 case KEY_COMMA:
87 // '<' is shift+',' — decrease character spacing.
88 spacing_ = std::max(0.0f, spacing_ - 0.5f);
89 break;
90 case KEY_PERIOD:
91 // '>' is shift+'.' — increase character spacing.
92 spacing_ = std::min(50.0f, spacing_ + 0.5f);
93 break;
94 case KEY_DOWN:
95 line_spacing_ = std::max(-1.0f, line_spacing_ - 0.1f);
96 break;
97 case KEY_UP:
98 line_spacing_ = std::min(2.0f, line_spacing_ + 0.1f);
99 break;
100 case KEY_L:
101 align_ = TextAlign::left;
102 break;
103 case KEY_C:
104 align_ = TextAlign::center;
105 break;
106 case KEY_R:
107 align_ = TextAlign::right;
108 break;
109 case KEY_O:
110 upper_left_ = !upper_left_;
111 break;
112 case KEY_SPACE:
113 kerning_ = !kerning_;
114 break;
115 default:
116 return Viewer::key_press_event(key, modifiers);
117 }
118 // Parameter changed: re-layout on the next frame (not once per key event).
119 dirty_ = true;
120 update();
121 return true;
122}
123
124// A resize changes the framebuffer the text is laid out for, so invalidate the layout.
125void TutorialTextRendering::post_resize(int, int) {
126 dirty_ = true;
127}
128
129// Called before each frame: rebuild the overlay text only when something changed.
130void TutorialTextRendering::pre_draw() {
131 Viewer::pre_draw();
132 // On high-DPI screens the framebuffer has more pixels than the window reports.
133 // Text sizes are in framebuffer pixels, so scale by this ratio to keep the text
134 // crisp and the same physical size on any display.
135 int w = width();
136 int fw = 0, fh = 0;
137 framebuffer_size(fw, fh);
138 const float dpi = w > 0 ? float(fw) / w : 1;
139 if (dpi != dpi_) {
140 dirty_ = true;
141 dpi_ = dpi;
142 }
143 if (!dirty_)
144 return;
145 // Discard obsolete font sizes on edits; existing draw commands retain their snapshots.
146 text_.clear_cache();
147 // Translate the user-facing parameters into engine options (all in framebuffer pixels).
149 o.size = size_ * dpi;
150 o.x = 50 * dpi;
151 o.y = 50 * dpi;
152 o.align = align_;
153 o.character_spacing = spacing_ * dpi;
154 o.line_spacing = line_spacing_;
155 o.upper_left = upper_left_;
156 o.kerning = kerning_;
157 // Lay out the multi-line instruction block; layout() rasterizes the needed glyphs
158 // into the atlas and returns one textured-quad draw command per character.
159 auto intro = text_.layout(
160 "This example shows how to render strings with Easy3D\n" "'+'/'-': increase/decrease font size\n" "'<'/'>': increase/decrease character spacing\n" "'up'/'down': increase/decrease line spacing\n" "'l'/'c'/'r': left/center/right align the multi-line text\n" "'o': switch the origin between 'upper left' and 'bottom left'\n" "'space': enable/disable kerning",
161 fw, fh, o);
162 auto commands = std::move(intro.commands);
163 // Move below the instruction block (7 lines plus a gap) for the font gallery.
164 o.y += 7 * intro.line_height + size_ * dpi * 0.5f;
165 o.align = easy3d::graphics::TextAlign::left;
166 // One sample line per loaded font, two per row, each in a pseudo-random color.
167 const auto &names = text_.font_names();
168 float next_x = o.x;
169 for (std::size_t i = 0; i < names.size(); ++i) {
170 o.font = i; // select the i-th registered font
171 // Even indices start a new row at the left margin; odd indices continue the row.
172 o.x = (i % 2) ? next_x : 50 * dpi;
173 o.color = vec4(color_from_index(i), 1.0f);
174 const auto label = std::to_string(i) + (i % 2 ? " - I Love Easy3D!" : " - Easy3D makes 3D easy! ");
175 auto line = text_.layout(label, fw, fh, o);
176 // advance = how far the line extended; the next sample on this row starts there.
177 next_x = o.x + line.advance;
178 commands.insert(commands.end(), line.commands.begin(), line.commands.end());
179 if (i % 2)
180 o.y += size_ * dpi * 1.5f; // row finished: step down to the next one
181 }
182 // Install the commands as 2D overlays; the viewer draws them on top of the 3D scene.
183 set_overlays(std::move(commands));
184 dirty_ = false;
185}
186// \endcond
std::string extension(const std::string &file_name, bool lowercase)
Query the file extension without dot (e.g., /a/b/c.Ext => Ext).
Definition file_system.cpp:315
std::string directory()
Get the selected resource directory.
vec3 color_from_index(std::size_t index)
Generate a color by an index. Colors from different indices have visual distinction.
Definition random.h:146
Font and placement options for a laid-out UTF-8 string.
Definition text_layout.h:40
bool upper_left
Definition text_layout.h:59
vec4 color
Text color in RGBA.
Definition text_layout.h:48
float character_spacing
Additional horizontal spacing between characters, in framebuffer pixels.
Definition text_layout.h:52
float line_spacing
Additional line spacing as a fraction of font line height; must be at least -1.
Definition text_layout.h:54
TextAlign align
Alignment of shorter lines relative to the longest line.
Definition text_layout.h:50
float y
Definition text_layout.h:46
float size
Font size in framebuffer pixels, independent of platform DPI.
Definition text_layout.h:44
float x
Horizontal framebuffer-pixel origin.
Definition text_layout.h:45
std::size_t font
Index returned by TextLayoutEngine::add_font().
Definition text_layout.h:42
bool kerning
Apply the font's horizontal kerning pairs when positioning glyphs.
Definition text_layout.h:56
See also
graphics::TextLayoutEngine, graphics::TextOptions, Viewer