Blender V5.3
string_image.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include <cstdint>
6#include <limits>
7#include <string>
8
9#include "BLI_assert.hh"
10#include "BLI_hash.hh"
11#include "BLI_memory_utils.hh"
12#include "BLI_path_utils.hh"
13#include "BLI_rect.hh"
14#include "BLI_string.hh"
15
17#include "DNA_vfont_types.h"
18
19#include "BKE_lib_id.hh"
20#include "BKE_main.hh"
21#include "BKE_vfont.hh"
22
23#include "BLF_api.hh"
24
25#include "COM_context.hh"
26#include "COM_result.hh"
27#include "COM_string_image.hh"
28#include "COM_utilities.hh"
29
30namespace blender::compositor {
31
32/* --------------------------------------------------------------------
33 * String Image Key.
34 */
35
50
57
58/* --------------------------------------------------------------------
59 * String Image.
60 */
61
62/* Loads a BLF font from the given font ID and return its identifier. Unloading the font is the
63 * responsibility of the caller. */
64static int load_font(const VFont *font)
65{
66 if (!font || BKE_vfont_is_builtin(font)) {
67 return BLF_load_default(true);
68 }
69
70 if (font->packedfile != nullptr) {
71 char name[MAX_ID_FULL_NAME];
72 BKE_id_full_name_get(name, &font->id, 0);
74 name, static_cast<const uchar *>(font->packedfile->data), font->packedfile->size);
75 }
76
77 char file_path[FILE_MAX];
78 STRNCPY(file_path, font->filepath);
79 BLI_path_abs(file_path, ID_BLEND_PATH_FROM_GLOBAL(&font->id));
80 return BLF_load_unique(file_path);
81}
82
83/* Computes the horizontal position in pixels from which the line with the given width should be
84 * drawn. The BLF module draws from the left most edge of the line. The start offset is an offset
85 * that is intrinsic to the used font and thus should be canceled here to draw right from the edge
86 * of the image. The total width is the total width of the image and is the maximum width of all
87 * lines. */
88static float compute_draw_horizontal_position(const int start_offset,
89 const int line_width,
90 const int total_width,
91 const HorizontalAlignment alignment)
92{
93 switch (alignment) {
95 return float(-start_offset);
97 return -start_offset + (total_width - line_width) / 2.0f;
99 return float(-start_offset + total_width - line_width);
100 }
101
103 return float(-start_offset);
104}
105
106/* Computes the vertical position in pixels from which the line with the given index should be
107 * drawn. Assuming there are the given number of lines with each having the given height and
108 * descender. The BLF module draws from the baseline of the line starting from the lower left
109 * origin of the image, therefore, we need to subtract the negative descender such that the line is
110 * fully drawn in the image. */
111static float compute_draw_vertical_position(const int lines_count,
112 const int line_index,
113 const int line_height,
114 const int descender)
115{
116 return (lines_count - 1 - line_index) * line_height - float(descender);
117}
118
119/* Computes the horizontal offset in pixels depending on the alignment. We also restore the start
120 * offset that was canceled during drawing, see compute_draw_horizontal_position. */
121static float compute_horizontal_offset(const int start_offset,
122 const int total_width,
123 const HorizontalAlignment alignment)
124{
125 switch (alignment) {
127 return start_offset + total_width / 2.0f;
129 return float(start_offset);
131 return start_offset - total_width / 2.0f;
132 }
133
135 return float(start_offset);
136}
137
138/* Computes the vertical offset in pixels depending on the alignment. Assuming the image has the
139 * given total height, the lines have the given height and negative descender. */
140static float compute_vertical_offset(const int total_height,
141 const int line_height,
142 const int descender,
143 const VerticalAlignment alignment)
144{
145 switch (alignment) {
147 return -total_height / 2.0f;
149 return -total_height / 2.0f + line_height + descender;
151 return 0.0f;
153 return total_height / 2.0f + descender;
155 return total_height / 2.0f;
156 }
157
159 return float(descender);
160}
161
163 const std::string string,
164 const VFont *font,
165 const float size,
166 const HorizontalAlignment horizontal_alignment,
167 const VerticalAlignment vertical_alignment,
168 const std::optional<int> wrap_width)
169 : result(context.create_result(ResultType::Float))
170{
171 if (string.empty() || !font || size <= 0.0f) {
172 return;
173 }
174
175 const int font_identifier = load_font(font);
176 if (font_identifier == -1) {
177 return;
178 }
179 BLI_SCOPED_DEFER([&]() { BLF_unload_id(font_identifier); });
180
181 BLF_size(font_identifier, size);
182 /* Only fallback to default fonts for unknown characters if this is the built-in font, otherwise,
183 * the image might change across setups and versions if fonts we fallback to change. */
184 if (!BLF_is_builtin(font_identifier)) {
185 BLF_enable(font_identifier, BLF_NO_FALLBACK);
186 }
187
189 font_identifier, string, wrap_width.value_or(-1), BLFWrapMode::Typographical);
190
191 /* Compute the width of all lines as well as their starting offset. The starting offset will be
192 * zero in most fonts, but some special fonts might start before or after the zero point. */
193 int total_width = 0;
194 Array<int> line_widths(lines.size());
195 int start_offset = std::numeric_limits<int>::max();
196 for (const int64_t i : lines.index_range()) {
197 rcti line_bounding_box;
198 BLF_boundbox(font_identifier, lines[i].data(), lines[i].size(), &line_bounding_box);
199 line_widths[i] = BLI_rcti_size_x(&line_bounding_box);
200 total_width = math::max(total_width, line_widths[i]);
201 start_offset = math::min(start_offset, line_bounding_box.xmin);
202 }
203
204 const int line_height = BLF_height_max(font_identifier);
205 const int total_height = line_height * lines.size();
206
207 /* Fill the background with alpha since the draws function does not initialize the background. */
208 Result result_cpu = context.create_result(ResultType::Float);
209 result_cpu.allocate_texture(int2(total_width, total_height), false, ResultStorageType::CPUImage);
210 parallel_for(result_cpu.domain().data_size,
211 [&](const int2 texel) { result_cpu.store_pixel(texel, 0.0f); });
212
213 BLF_buffer_col(font_identifier, Color(1.0f, 1.0f, 1.0f, 1.0f));
214 BLF_buffer(font_identifier,
215 static_cast<float *>(result_cpu.cpu_data_for_write().data()),
216 nullptr,
217 total_width,
218 total_height,
219 1,
220 nullptr);
221
222 /* Draw each of lines in the appropriate position. */
223 const int descender = BLF_descender(font_identifier);
224 for (const int64_t i : lines.index_range()) {
225 const float vertical_position = compute_draw_vertical_position(
226 lines.size(), i, line_height, descender);
227 const float horizontal_position = compute_draw_horizontal_position(
228 start_offset, line_widths[i], total_width, horizontal_alignment);
229 BLF_position(font_identifier, horizontal_position, vertical_position, 0.0f);
230 BLF_draw_buffer(font_identifier, lines[i].data(), lines[i].size());
231 }
232
233 BLF_buffer(font_identifier, nullptr, nullptr, 0, 0, 1, nullptr);
234
235 /* Move the image to account for the requested alignment. */
236 const float horizontal_offset = compute_horizontal_offset(
237 start_offset, total_width, horizontal_alignment);
238 const float vertical_offset = compute_vertical_offset(
239 total_height, line_height, descender, vertical_alignment);
240 result_cpu.domain().transformation.location() = float2(horizontal_offset, vertical_offset);
241
242 if (context.use_gpu()) {
243 Result result_gpu = result_cpu.upload_to_gpu(false);
244 this->result.share_data(result_gpu);
245 result_gpu.release();
246 }
247 else {
248 this->result.share_data(result_cpu);
249 }
250
251 result_cpu.release();
252}
253
255{
256 this->result.release();
257}
258
259/* --------------------------------------------------------------------
260 * String Image Container.
261 */
262
264{
265 /* First, delete all resources that are no longer needed. */
266 map_.remove_if([](auto item) { return !item.value->needed; });
267
268 /* Second, reset the needed status of the remaining resources to false to ready them to track
269 * their needed status for the next evaluation. */
270 for (auto &value : map_.values()) {
271 value->needed = false;
272 }
273}
274
276 const std::string string,
277 const VFont *font,
278 const float size,
279 const HorizontalAlignment horizontal_alignment,
280 const VerticalAlignment vertical_alignment,
281 const std::optional<int> wrap_width)
282{
283 const StringImageKey key(
284 string, font, size, horizontal_alignment, vertical_alignment, wrap_width);
285
286 auto &string_image = *map_.lookup_or_add_cb(key, [&]() {
287 return std::make_unique<StringImage>(
288 context, string, font, size, horizontal_alignment, vertical_alignment, wrap_width);
289 });
290
291 string_image.needed = true;
292 return string_image.result;
293}
294
295} // namespace blender::compositor
#define MAX_ID_FULL_NAME
#define BLI_SCOPED_DEFER(function_to_defer)
#define FILE_MAX
#define ID_BLEND_PATH_FROM_GLOBAL(_id)
Definition DNA_ID.h:691
#define BLI_assert_unreachable()
void share_data(const Result &source)
Definition result.cc:996
Result upload_to_gpu(const bool from_pool) const
Definition result.cc:671
void allocate_texture(const Domain domain, const bool from_pool=true, const std::optional< ResultStorageType > storage_type=std::nullopt)
Definition result.cc:554
GMutableSpan cpu_data_for_write()
Result & get(Context &context, const std::string string, const VFont *font, const float size, const HorizontalAlignment horizontal_alignment, const VerticalAlignment vertical_alignment, const std::optional< int > wrap_width)
StringImageKey(const std::string string, const VFont *font, const float size, const HorizontalAlignment horizontal_alignment, const VerticalAlignment vertical_alignment, const std::optional< int > wrap_width)
const VerticalAlignment vertical_alignment
const HorizontalAlignment horizontal_alignment
const std::optional< int > wrap_width
StringImage(Context &context, const std::string string, const VFont *font, const float size, const HorizontalAlignment horizontal_alignment, const VerticalAlignment vertical_alignment, const std::optional< int > wrap_width)
static float compute_vertical_offset(const int total_height, const int line_height, const int descender, const VerticalAlignment alignment)
ColorSceneLinear4f< eAlpha::Premultiplied > Color
Definition COM_result.hh:96
static float compute_draw_vertical_position(const int lines_count, const int line_index, const int line_height, const int descender)
static float compute_horizontal_offset(const int start_offset, const int total_width, const HorizontalAlignment alignment)
void parallel_for(const int2 range, const Function &function)
static int load_font(const VFont *font)
static float compute_draw_horizontal_position(const int start_offset, const int line_width, const int total_width, const HorizontalAlignment alignment)
T min(const T &a, const T &b)
T max(const T &a, const T &b)
void BLF_boundbox(int fontid, const char *str, size_t str_len, rcti *r_box, ResultBLF *r_info=nullptr) ATTR_NONNULL(2)
Definition blf.cc:805
unsigned __int64 uint64_t
Definition BKE_text.h:91
__int64 int64_t
Definition BKE_text.h:90
char * STRNCPY(char(&dst)[N], const char *src)
int BLF_load_default(bool unique)
void BLF_position(int fontid, float x, float y, float z)
Definition blf.cc:390
bool BLI_path_abs(char path[FILE_MAX], const char *basepath) ATTR_NONNULL(1
bool BKE_vfont_is_builtin(const VFont *vfont)
Definition vfont.cc:278
void BLF_buffer(int fontid, float *fbuf, unsigned char *cbuf, int w, int h, int channel_count, const ColorSpace *colorspace)
Definition blf.cc:989
void BLF_size(int fontid, float size)
Definition blf.cc:445
unsigned char uchar
Definition BKE_text.h:58
BMesh const char void * data
Vector< StringRef > BLF_string_wrap(int fontid, StringRef str, const int max_pixel_width, BLFWrapMode mode=BLFWrapMode::Minimal)
Definition blf.cc:1103
BLI_INLINE int BLI_rcti_size_x(const struct rcti *rct)
Definition BLI_rect.hh:203
int BLF_load_mem_unique(const char *name, const unsigned char *mem, int mem_size) ATTR_NONNULL(1
Definition blf.cc:236
void BLF_buffer_col(int fontid, const float srgb_color[4]) ATTR_NONNULL(2)
Definition blf.cc:1057
int BLF_height_max(int fontid) ATTR_WARN_UNUSED_RESULT
Definition blf.cc:883
int BLF_descender(int fontid) ATTR_WARN_UNUSED_RESULT
Definition blf.cc:905
int BLF_load_unique(const char *filepath) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition blf.cc:190
void BLF_draw_buffer(int fontid, const char *str, size_t str_len, ResultBLF *r_info=nullptr) ATTR_NONNULL(2)
Definition blf.cc:1087
void BKE_id_full_name_get(char name[MAX_ID_FULL_NAME], const ID *id, char separator_char)
Definition lib_id.cc:2691
bool BLF_is_builtin(int fontid)
Definition blf.cc:340
constexpr uint64_t get_default_hash(const T &v, const Args &...args)
Definition BLI_hash.hh:252
void BLF_enable(int fontid, FontFlags flag)
Definition blf.cc:322
@ BLF_NO_FALLBACK
Definition BLF_enums.hh:66
bool BLF_unload_id(int fontid)
Definition blf.cc:282
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
struct PackedFile * packedfile
char filepath[1024]