Debian Codegraph @

src/rtext.c

raw symbols SCIP
1 /**********************************************************************************************
2 *
3 * rtext - Basic functions to load fonts and draw text
4 *
5 * CONFIGURATION:
6 * #define SUPPORT_MODULE_RTEXT 1
7 * rtext module is included in the build
8 *
9 * #define SUPPORT_FILEFORMAT_FNT 1
10 * #define SUPPORT_FILEFORMAT_TTF 1
11 * #define SUPPORT_FILEFORMAT_BDF 0
12 * Selected desired fileformats to be supported for loading. Some of those formats are
13 * supported by default, to remove support, #define as 0 in this module or your build system
14 *
15 * #define MAX_TEXT_BUFFER_LENGTH 1024
16 * Text functions using static buffer max size
17 *
18 * #define MAX_TEXTSPLIT_COUNT 128
19 * TextSplit() function static substrings pointers array (pointing to static buffer)
20 *
21 * #define FONT_ATLAS_CORNER_REC_SIZE 3
22 * On font atlas image generation [GenImageFontAtlas()], add a NxN pixels white rectangle
23 * at the bottom-right corner of the atlas. It can be useful to for shapes drawing, to allow
24 * drawing text and shapes with a single draw call [SetShapesTexture()]
25 *
26 * DEPENDENCIES:
27 * stb_truetype - Load TTF file and rasterize characters data
28 * stb_rect_pack - Rectangles packing algorithms, required for font atlas generation
29 *
30 *
31 * LICENSE: zlib/libpng
32 *
33 * Copyright (c) 2013-2026 Ramon Santamaria (@raysan5)
34 *
35 * This software is provided "as-is", without any express or implied warranty. In no event
36 * will the authors be held liable for any damages arising from the use of this software.
37 *
38 * Permission is granted to anyone to use this software for any purpose, including commercial
39 * applications, and to alter it and redistribute it freely, subject to the following restrictions:
40 *
41 * 1. The origin of this software must not be misrepresented; you must not claim that you
42 * wrote the original software. If you use this software in a product, an acknowledgment
43 * in the product documentation would be appreciated but is not required.
44 *
45 * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
46 * as being the original software.
47 *
48 * 3. This notice may not be removed or altered from any source distribution.
49 *
50 **********************************************************************************************/
51
52 #include "raylib.h" // Declares module functions
53
54 #include "config.h" // Defines module configuration flags
55
56 #if SUPPORT_MODULE_RTEXT
57
58 #include "rlgl.h" // OpenGL abstraction layer to OpenGL 1.1, 2.1, 3.3+ or ES2 -> Only DrawTextPro()
59
60 #include <stdlib.h> // Required for: malloc(), free()
61 #include <stdio.h> // Required for: vsprintf()
62 #include <string.h> // Required for: strcmp(), strstr(), strncpy() [Used in TextReplace()], sscanf() [Used in LoadBMFont()]
63 #include <stdarg.h> // Required for: va_list, va_start(), vsprintf(), va_end() [Used in TextFormat()]
64 #include <ctype.h> // Required for: toupper(), tolower() [Used in TextToUpper(), TextToLower()]
65
66 #if SUPPORT_FILEFORMAT_TTF || SUPPORT_FILEFORMAT_BDF
67 #if defined(__GNUC__) // GCC and Clang
68 #pragma GCC diagnostic push
69 #pragma GCC diagnostic ignored "-Wunused-function"
70 #endif
71
72 #define STB_RECT_PACK_IMPLEMENTATION
73 #include "external/stb_rect_pack.h" // Required for: ttf/bdf font rectangles packaging
74
75 #include <math.h> // Required for: ttf/bdf font rectangles packaging
76
77 #if defined(__GNUC__) // GCC and Clang
78 #pragma GCC diagnostic pop
79 #endif
80 #endif
81
82 #if SUPPORT_FILEFORMAT_TTF
83 #if defined(__GNUC__) // GCC and Clang
84 #pragma GCC diagnostic push
85 #pragma GCC diagnostic ignored "-Wunused-function"
86 #endif
87
88 #define STBTT_malloc(x,u) ((void)(u),RL_MALLOC(x))
89 #define STBTT_free(x,u) ((void)(u),RL_FREE(x))
90
91 #define STBTT_STATIC
92 #define STB_TRUETYPE_IMPLEMENTATION
93 #include "external/stb_truetype.h" // Required for: ttf font data reading
94
95 #if defined(__GNUC__) // GCC and Clang
96 #pragma GCC diagnostic pop
97 #endif
98 #endif
99
100 //----------------------------------------------------------------------------------
101 // Defines and Macros
102 //----------------------------------------------------------------------------------
103 #ifndef MAX_TEXT_BUFFER_LENGTH
104 #define MAX_TEXT_BUFFER_LENGTH 1024 // Size of internal static buffers used on some functions:
105 // TextFormat(), TextSubtext(), TextToUpper(), TextToLower(), TextToPascal(), TextSplit()
106 #endif
107 #ifndef MAX_TEXTSPLIT_COUNT
108 #define MAX_TEXTSPLIT_COUNT 128 // Maximum number of substrings to split: TextSplit()
109 #endif
110
111 #ifndef FONT_ATLAS_CORNER_REC_SIZE
112 // On font atlas image generation [GenImageFontAtlas()], add a 3x3 pixels white rectangle
113 // at the bottom-right corner of the atlas. It can be useful for shapes drawing, to allow
114 // drawing text and shapes with a single draw call [SetShapesTexture()]
115 #define FONT_ATLAS_CORNER_REC_SIZE 3 // Size of white rectangle drawn on font atlas on font loading
116 #endif
117
118 //----------------------------------------------------------------------------------
119 // Types and Structures Definition
120 //----------------------------------------------------------------------------------
121 //...
122
123 //----------------------------------------------------------------------------------
124 // Global variables
125 //----------------------------------------------------------------------------------
126 // Default font provided by raylib
127 // NOTE: Default font is loaded on InitWindow() and disposed on CloseWindow() [module: core]
128 static Font defaultFont = { 0 };
129
130 // Text vertical line spacing in pixels (between lines)
131 static int textLineSpacing = 2;
132
133 //----------------------------------------------------------------------------------
134 // Other Modules Functions Declaration (required by text)
135 //----------------------------------------------------------------------------------
136 //...
137
138 //----------------------------------------------------------------------------------
139 // Module Internal Functions Declaration
140 //----------------------------------------------------------------------------------
141 #if SUPPORT_FILEFORMAT_FNT
142 static Font LoadBMFont(const char *fileName); // Load a BMFont file (AngelCode font file)
143 #endif
144 #if SUPPORT_FILEFORMAT_BDF
145 static GlyphInfo *LoadFontDataBDF(const unsigned char *fileData, int dataSize, const int *codepoints, int codepointCount, int *outFontSize);
146 #endif
147
148 extern void LoadFontDefault(void);
149 extern void UnloadFontDefault(void);
150
151 //----------------------------------------------------------------------------------
152 // Module Functions Definition
153 //----------------------------------------------------------------------------------
154 // Load raylib default font
155 extern void LoadFontDefault(void)
156 {
157 #define BIT_CHECK(a,b) ((a) & (1u << (b)))
158
159 // Check to see if the font for an image has alreeady been allocated,
160 // and if no need to upload, then return
161 if (defaultFont.glyphs != NULL) return;
162
163 // NOTE: Using UTF-8 encoding table for Unicode U+0000..U+00FF Basic Latin + Latin-1 Supplement
164 // REF: http://www.utf8-chartable.de/unicode-utf8-table.pl
165
166 defaultFont.glyphCount = 224; // Number of glyphs included in our default font
167 defaultFont.glyphPadding = 0; // Characters padding
168
169 // Default font is directly defined here (data generated from a sprite font image)
170 // This way, reconstructing Font without creating large global variables
171 // This data is automatically allocated to Stack and automatically deallocated at the end of this function
172 unsigned int defaultFontData[512] = {
173 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00200020, 0x0001b000, 0x00000000, 0x00000000, 0x8ef92520, 0x00020a00, 0x7dbe8000, 0x1f7df45f,
174 0x4a2bf2a0, 0x0852091e, 0x41224000, 0x10041450, 0x2e292020, 0x08220812, 0x41222000, 0x10041450, 0x10f92020, 0x3efa084c, 0x7d22103c, 0x107df7de,
175 0xe8a12020, 0x08220832, 0x05220800, 0x10450410, 0xa4a3f000, 0x08520832, 0x05220400, 0x10450410, 0xe2f92020, 0x0002085e, 0x7d3e0281, 0x107df41f,
176 0x00200000, 0x8001b000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
177 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xc0000fbe, 0xfbf7e00f, 0x5fbf7e7d, 0x0050bee8, 0x440808a2, 0x0a142fe8, 0x50810285, 0x0050a048,
178 0x49e428a2, 0x0a142828, 0x40810284, 0x0048a048, 0x10020fbe, 0x09f7ebaf, 0xd89f3e84, 0x0047a04f, 0x09e48822, 0x0a142aa1, 0x50810284, 0x0048a048,
179 0x04082822, 0x0a142fa0, 0x50810285, 0x0050a248, 0x00008fbe, 0xfbf42021, 0x5f817e7d, 0x07d09ce8, 0x00008000, 0x00000fe0, 0x00000000, 0x00000000,
180 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x000c0180,
181 0xdfbf4282, 0x0bfbf7ef, 0x42850505, 0x004804bf, 0x50a142c6, 0x08401428, 0x42852505, 0x00a808a0, 0x50a146aa, 0x08401428, 0x42852505, 0x00081090,
182 0x5fa14a92, 0x0843f7e8, 0x7e792505, 0x00082088, 0x40a15282, 0x08420128, 0x40852489, 0x00084084, 0x40a16282, 0x0842022a, 0x40852451, 0x00088082,
183 0xc0bf4282, 0xf843f42f, 0x7e85fc21, 0x3e0900bf, 0x00000000, 0x00000004, 0x00000000, 0x000c0180, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
184 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x04000402, 0x41482000, 0x00000000, 0x00000800,
185 0x04000404, 0x4100203c, 0x00000000, 0x00000800, 0xf7df7df0, 0x514bef85, 0xbefbefbe, 0x04513bef, 0x14414500, 0x494a2885, 0xa28a28aa, 0x04510820,
186 0xf44145f0, 0x474a289d, 0xa28a28aa, 0x04510be0, 0x14414510, 0x494a2884, 0xa28a28aa, 0x02910a00, 0xf7df7df0, 0xd14a2f85, 0xbefbe8aa, 0x011f7be0,
187 0x00000000, 0x00400804, 0x20080000, 0x00000000, 0x00000000, 0x00600f84, 0x20080000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
188 0xac000000, 0x00000f01, 0x00000000, 0x00000000, 0x24000000, 0x00000f01, 0x00000000, 0x06000000, 0x24000000, 0x00000f01, 0x00000000, 0x09108000,
189 0x24fa28a2, 0x00000f01, 0x00000000, 0x013e0000, 0x2242252a, 0x00000f52, 0x00000000, 0x038a8000, 0x2422222a, 0x00000f29, 0x00000000, 0x010a8000,
190 0x2412252a, 0x00000f01, 0x00000000, 0x010a8000, 0x24fbe8be, 0x00000f01, 0x00000000, 0x0ebe8000, 0xac020000, 0x00000f01, 0x00000000, 0x00048000,
191 0x0003e000, 0x00000f00, 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000038, 0x8443b80e, 0x00203a03,
192 0x02bea080, 0xf0000020, 0xc452208a, 0x04202b02, 0xf8029122, 0x07f0003b, 0xe44b388e, 0x02203a02, 0x081e8a1c, 0x0411e92a, 0xf4420be0, 0x01248202,
193 0xe8140414, 0x05d104ba, 0xe7c3b880, 0x00893a0a, 0x283c0e1c, 0x04500902, 0xc4400080, 0x00448002, 0xe8208422, 0x04500002, 0x80400000, 0x05200002,
194 0x083e8e00, 0x04100002, 0x804003e0, 0x07000042, 0xf8008400, 0x07f00003, 0x80400000, 0x04000022, 0x00000000, 0x00000000, 0x80400000, 0x04000002,
195 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800702, 0x1848a0c2, 0x84010000, 0x02920921, 0x01042642, 0x00005121, 0x42023f7f, 0x00291002,
196 0xefc01422, 0x7efdfbf7, 0xefdfa109, 0x03bbbbf7, 0x28440f12, 0x42850a14, 0x20408109, 0x01111010, 0x28440408, 0x42850a14, 0x2040817f, 0x01111010,
197 0xefc78204, 0x7efdfbf7, 0xe7cf8109, 0x011111f3, 0x2850a932, 0x42850a14, 0x2040a109, 0x01111010, 0x2850b840, 0x42850a14, 0xefdfbf79, 0x03bbbbf7,
198 0x001fa020, 0x00000000, 0x00001000, 0x00000000, 0x00002070, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
199 0x08022800, 0x00012283, 0x02430802, 0x01010001, 0x8404147c, 0x20000144, 0x80048404, 0x00823f08, 0xdfbf4284, 0x7e03f7ef, 0x142850a1, 0x0000210a,
200 0x50a14684, 0x528a1428, 0x142850a1, 0x03efa17a, 0x50a14a9e, 0x52521428, 0x142850a1, 0x02081f4a, 0x50a15284, 0x4a221428, 0xf42850a1, 0x03efa14b,
201 0x50a16284, 0x4a521428, 0x042850a1, 0x0228a17a, 0xdfbf427c, 0x7e8bf7ef, 0xf7efdfbf, 0x03efbd0b, 0x00000000, 0x04000000, 0x00000000, 0x00000008,
202 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00200508, 0x00840400, 0x11458122, 0x00014210,
203 0x00514294, 0x51420800, 0x20a22a94, 0x0050a508, 0x00200000, 0x00000000, 0x00050000, 0x08000000, 0xfefbefbe, 0xfbefbefb, 0xfbeb9114, 0x00fbefbe,
204 0x20820820, 0x8a28a20a, 0x8a289114, 0x3e8a28a2, 0xfefbefbe, 0xfbefbe0b, 0x8a289114, 0x008a28a2, 0x228a28a2, 0x08208208, 0x8a289114, 0x088a28a2,
205 0xfefbefbe, 0xfbefbefb, 0xfa2f9114, 0x00fbefbe, 0x00000000, 0x00000040, 0x00000000, 0x00000000, 0x00000000, 0x00000020, 0x00000000, 0x00000000,
206 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00210100, 0x00000004, 0x00000000, 0x00000000, 0x14508200, 0x00001402, 0x00000000, 0x00000000,
207 0x00000010, 0x00000020, 0x00000000, 0x00000000, 0xa28a28be, 0x00002228, 0x00000000, 0x00000000, 0xa28a28aa, 0x000022e8, 0x00000000, 0x00000000,
208 0xa28a28aa, 0x000022a8, 0x00000000, 0x00000000, 0xa28a28aa, 0x000022e8, 0x00000000, 0x00000000, 0xbefbefbe, 0x00003e2f, 0x00000000, 0x00000000,
209 0x00000004, 0x00002028, 0x00000000, 0x00000000, 0x80000000, 0x00003e0f, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
210 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
211 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
212 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
213 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
214 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
215 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 };
216
217 int charsHeight = 10;
218 int charsDivisor = 1; // Every char is separated from the consecutive by a 1 pixel divisor, horizontally and vertically
219
220 int charsWidth[224] = { 3, 1, 4, 6, 5, 7, 6, 2, 3, 3, 5, 5, 2, 4, 1, 7, 5, 2, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 3, 4, 3, 6,
221 7, 6, 6, 6, 6, 6, 6, 6, 6, 3, 5, 6, 5, 7, 6, 6, 6, 6, 6, 6, 7, 6, 7, 7, 6, 6, 6, 2, 7, 2, 3, 5,
222 2, 5, 5, 5, 5, 5, 4, 5, 5, 1, 2, 5, 2, 5, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 3, 1, 3, 4, 4,
223 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
224 1, 1, 5, 5, 5, 7, 1, 5, 3, 7, 3, 5, 4, 1, 7, 4, 3, 5, 3, 3, 2, 5, 6, 1, 2, 2, 3, 5, 6, 6, 6, 6,
225 6, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 3, 3, 3, 3, 7, 6, 6, 6, 6, 6, 6, 5, 6, 6, 6, 6, 6, 6, 4, 6,
226 5, 5, 5, 5, 5, 5, 9, 5, 5, 5, 5, 5, 2, 2, 3, 3, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 5 };
227
228 // Re-construct image from defaultFontData and generate OpenGL texture
229 //----------------------------------------------------------------------
230 Image imFont = {
231 .data = RL_CALLOC(128*128, 2), // 2 bytes per pixel (gray + alpha)
232 .width = 128,
233 .height = 128,
234 .mipmaps = 1,
235 .format = PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA
236 };
237
238 // Fill image.data with defaultFontData (convert from bit to pixel!)
239 for (int i = 0, counter = 0; i < imFont.width*imFont.height; i += 32)
240 {
241 for (int j = 31; j >= 0; j--)
242 {
243 if (BIT_CHECK(defaultFontData[counter], j))
244 {
245 // NOTE: Unreferencing data as short, so,
246 // considering data as little-endian (alpha + gray)
247 ((unsigned short *)imFont.data)[i + j] = 0xffff;
248 }
249 else
250 {
251 ((unsigned char *)imFont.data)[(i + j)*sizeof(short)] = 0xff;
252 ((unsigned char *)imFont.data)[(i + j)*sizeof(short) + 1] = 0x00;
253 }
254 }
255
256 counter++;
257 }
258
259 defaultFont.texture = LoadTextureFromImage(imFont);
260
261 // Check again if font glyph data has been already loaded
262 // to avoid reallocating the glyphs and rects
263 if (defaultFont.glyphs != NULL)
264 {
265 UnloadImage(imFont);
266 return;
267 }
268
269 // Reconstruct charSet using charsWidth[], charsHeight, charsDivisor, glyphCount
270 //------------------------------------------------------------------------------
271 // Allocate space for our characters info data
272 // NOTE: This memory must be freed at end! --> Done by CloseWindow()
273 defaultFont.glyphs = (GlyphInfo *)RL_CALLOC(defaultFont.glyphCount, sizeof(GlyphInfo));
274 defaultFont.recs = (Rectangle *)RL_CALLOC(defaultFont.glyphCount, sizeof(Rectangle));
275
276 int currentLine = 0;
277 int currentPosX = charsDivisor;
278 int testPosX = charsDivisor;
279
280 for (int i = 0; i < defaultFont.glyphCount; i++)
281 {
282 defaultFont.glyphs[i].value = 32 + i; // First char is 32
283
284 defaultFont.recs[i].x = (float)currentPosX;
285 defaultFont.recs[i].y = (float)(charsDivisor + currentLine*(charsHeight + charsDivisor));
286 defaultFont.recs[i].width = (float)charsWidth[i];
287 defaultFont.recs[i].height = (float)charsHeight;
288
289 testPosX += (int)(defaultFont.recs[i].width + (float)charsDivisor);
290
291 if (testPosX >= imFont.width)
292 {
293 currentLine++;
294 currentPosX = 2*charsDivisor + charsWidth[i];
295 testPosX = currentPosX;
296
297 defaultFont.recs[i].x = (float)charsDivisor;
298 defaultFont.recs[i].y = (float)(charsDivisor + currentLine*(charsHeight + charsDivisor));
299 }
300 else currentPosX = testPosX;
301
302 // NOTE: On default font character offsets and xAdvance are not required
303 defaultFont.glyphs[i].offsetX = 0;
304 defaultFont.glyphs[i].offsetY = 0;
305 defaultFont.glyphs[i].advanceX = 0;
306
307 // Fill character image data from fontClear data
308 defaultFont.glyphs[i].image = ImageFromImage(imFont, defaultFont.recs[i]);
309 }
310
311 UnloadImage(imFont);
312
313 defaultFont.baseSize = (int)defaultFont.recs[0].height;
314
315 TRACELOG(LOG_INFO, "FONT: Default font loaded successfully (%i glyphs)", defaultFont.glyphCount);
316 }
317
318 // Unload raylib default font
319 extern void UnloadFontDefault(void)
320 {
321 for (int i = 0; i < defaultFont.glyphCount; i++) UnloadImage(defaultFont.glyphs[i].image);
322 UnloadTexture(defaultFont.texture);
323 RL_FREE(defaultFont.glyphs);
324 RL_FREE(defaultFont.recs);
325 defaultFont.glyphCount = 0;
326 defaultFont.glyphs = NULL;
327 defaultFont.recs = NULL;
328 }
329
330 // Get the default font, useful to be used with extended parameters
331 Font GetFontDefault()
332 {
333 return defaultFont;
334 }
335
336 // Load Font from file into GPU memory (VRAM)
337 Font LoadFont(const char *fileName)
338 {
339 // Default values for ttf font generation
340 #ifndef FONT_TTF_DEFAULT_SIZE
341 #define FONT_TTF_DEFAULT_SIZE 32 // TTF font generation default char size (char-height)
342 #endif
343 #ifndef FONT_TTF_DEFAULT_NUMCHARS
344 #define FONT_TTF_DEFAULT_NUMCHARS 95 // TTF font generation default charset: 95 glyphs (ASCII 32..126)
345 #endif
346 #ifndef FONT_TTF_DEFAULT_FIRST_CHAR
347 #define FONT_TTF_DEFAULT_FIRST_CHAR 32 // TTF font generation default first char for image sprite font (32-Space)
348 #endif
349 #ifndef FONT_TTF_DEFAULT_CHARS_PADDING
350 #define FONT_TTF_DEFAULT_CHARS_PADDING 4 // TTF font generation default glyphs padding
351 #endif
352
353 Font font = { 0 };
354
355 #if SUPPORT_FILEFORMAT_TTF
356 if (IsFileExtension(fileName, ".ttf") || IsFileExtension(fileName, ".otf")) font = LoadFontEx(fileName, FONT_TTF_DEFAULT_SIZE, NULL, FONT_TTF_DEFAULT_NUMCHARS);
357 else
358 #endif
359 #if SUPPORT_FILEFORMAT_FNT
360 if (IsFileExtension(fileName, ".fnt")) font = LoadBMFont(fileName);
361 else
362 #endif
363 #if SUPPORT_FILEFORMAT_BDF
364 if (IsFileExtension(fileName, ".bdf")) font = LoadFontEx(fileName, FONT_TTF_DEFAULT_SIZE, NULL, FONT_TTF_DEFAULT_NUMCHARS);
365 else
366 #endif
367 {
368 Image image = LoadImage(fileName);
369 if (image.data != NULL) font = LoadFontFromImage(image, MAGENTA, FONT_TTF_DEFAULT_FIRST_CHAR);
370 else font = GetFontDefault();
371 UnloadImage(image);
372 }
373
374 if (font.texture.id == 0) TRACELOG(LOG_WARNING, "FONT: [%s] Failed to load font texture -> Using default font", fileName);
375 else
376 {
377 SetTextureFilter(font.texture, TEXTURE_FILTER_POINT); // By default, set point filter (the best performance)
378 TRACELOG(LOG_INFO, "FONT: Data loaded successfully (%i pixel size | %i glyphs)", font.baseSize, font.glyphCount);
379 }
380
381 return font;
382 }
383
384 // Load Font from TTF or BDF font file with generation parameters
385 // NOTE: You can pass an array with desired characters, those characters should be available in the font
386 // if array is NULL, default char set is selected 32..126
387 Font LoadFontEx(const char *fileName, int fontSize, const int *codepoints, int codepointCount)
388 {
389 Font font = { 0 };
390
391 // Loading file to memory
392 int dataSize = 0;
393 unsigned char *fileData = LoadFileData(fileName, &dataSize);
394
395 if (fileData != NULL)
396 {
397 // Loading font from memory data
398 font = LoadFontFromMemory(GetFileExtension(fileName), fileData, dataSize, fontSize, codepoints, codepointCount);
399
400 UnloadFileData(fileData);
401 }
402
403 return font;
404 }
405
406 // Load an Image font file (XNA style)
407 Font LoadFontFromImage(Image image, Color key, int firstChar)
408 {
409 #ifndef MAX_GLYPHS_FROM_IMAGE
410 #define MAX_GLYPHS_FROM_IMAGE 256 // Maximum number of glyphs supported on image scan
411 #endif
412
413 #define COLOR_EQUAL(col1, col2) ((col1.r == col2.r) && (col1.g == col2.g) && (col1.b == col2.b) && (col1.a == col2.a))
414
415 Font font = GetFontDefault();
416
417 int charSpacing = 0;
418 int lineSpacing = 0;
419
420 int x = 0;
421 int y = 0;
422
423 // Allocate a temporal arrays for glyphs data measures,
424 // once the actual number of glyphs is obtained, copy data to a sized array
425 int tempCharValues[MAX_GLYPHS_FROM_IMAGE] = { 0 };
426 Rectangle tempCharRecs[MAX_GLYPHS_FROM_IMAGE] = { 0 };
427
428 Color *pixels = LoadImageColors(image);
429
430 // Parse image data to get charSpacing and lineSpacing
431 for (y = 0; y < image.height; y++)
432 {
433 for (x = 0; x < image.width; x++)
434 {
435 if (!COLOR_EQUAL(pixels[y*image.width + x], key)) break;
436 }
437
438 if (!COLOR_EQUAL(pixels[y*image.width + x], key)) break;
439 }
440
441 if ((x == 0) || (y == 0)) return font; // Security check
442
443 charSpacing = x;
444 lineSpacing = y;
445
446 int charHeight = 0;
447 int j = 0;
448
449 while (((lineSpacing + j) < image.height) &&
450 !COLOR_EQUAL(pixels[(lineSpacing + j)*image.width + charSpacing], key)) j++;
451
452 charHeight = j;
453
454 // Check array values to get characters: value, x, y, w, h
455 int index = 0;
456 int lineToRead = 0;
457 int xPosToRead = charSpacing;
458
459 // Parse image data to get rectangle sizes
460 while ((lineSpacing + lineToRead*(charHeight + lineSpacing)) < image.height)
461 {
462 while ((xPosToRead < image.width) &&
463 !COLOR_EQUAL((pixels[(lineSpacing + (charHeight+lineSpacing)*lineToRead)*image.width + xPosToRead]), key))
464 {
465 tempCharValues[index] = firstChar + index;
466
467 tempCharRecs[index].x = (float)xPosToRead;
468 tempCharRecs[index].y = (float)(lineSpacing + lineToRead*(charHeight + lineSpacing));
469 tempCharRecs[index].height = (float)charHeight;
470
471 int charWidth = 0;
472
473 while (((xPosToRead + charWidth) < image.width) &&
474 !COLOR_EQUAL(pixels[(lineSpacing + (charHeight + lineSpacing)*lineToRead)*image.width + xPosToRead + charWidth], key)) charWidth++;
475
476 tempCharRecs[index].width = (float)charWidth;
477
478 index++;
479
480 xPosToRead += (charWidth + charSpacing);
481 }
482
483 lineToRead++;
484 xPosToRead = charSpacing;
485 }
486
487 // NOTE: Key color borders need to be removed from image to avoid weird
488 // artifacts on texture scaling when using TEXTURE_FILTER_BILINEAR or TEXTURE_FILTER_TRILINEAR
489 for (int i = 0; i < image.height*image.width; i++) if (COLOR_EQUAL(pixels[i], key)) pixels[i] = BLANK;
490
491 // Create a new image with the processed color data (key color replaced by BLANK)
492 Image fontClear = {
493 .data = pixels,
494 .width = image.width,
495 .height = image.height,
496 .mipmaps = 1,
497 .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8
498 };
499
500 // Set font with all data parsed from image
501 font.texture = LoadTextureFromImage(fontClear); // Convert processed image to OpenGL texture
502 font.glyphCount = index;
503 font.glyphPadding = 0;
504
505 // Populate tempCharValues and tempCharsRecs with glyphs data
506 // Move temp data to sized charValues and charRecs arrays
507 font.glyphs = (GlyphInfo *)RL_MALLOC(font.glyphCount*sizeof(GlyphInfo));
508 font.recs = (Rectangle *)RL_MALLOC(font.glyphCount*sizeof(Rectangle));
509
510 for (int i = 0; i < font.glyphCount; i++)
511 {
512 font.glyphs[i].value = tempCharValues[i];
513
514 // Get character rectangle in the font atlas texture
515 font.recs[i] = tempCharRecs[i];
516
517 // NOTE: On image based fonts (XNA style), character offsets and xAdvance are not required (set to 0)
518 font.glyphs[i].offsetX = 0;
519 font.glyphs[i].offsetY = 0;
520 font.glyphs[i].advanceX = 0;
521
522 // Fill character image data from fontClear data
523 font.glyphs[i].image = ImageFromImage(fontClear, tempCharRecs[i]);
524 }
525
526 UnloadImage(fontClear); // Unload processed image once converted to texture
527
528 font.baseSize = (int)font.recs[0].height;
529
530 return font;
531 }
532
533 // Load font from memory buffer, fileType refers to extension: i.e. ".ttf"
534 Font LoadFontFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int fontSize, const int *codepoints, int codepointCount)
535 {
536 Font font = { 0 };
537
538 char fileExtLower[16] = { 0 };
539 strncpy(fileExtLower, TextToLower(fileType), 16 - 1);
540
541 font.baseSize = fontSize;
542 font.glyphPadding = 0;
543
544 #if SUPPORT_FILEFORMAT_TTF
545 if (TextIsEqual(fileExtLower, ".ttf") ||
546 TextIsEqual(fileExtLower, ".otf"))
547 {
548 font.glyphs = LoadFontData(fileData, dataSize, font.baseSize, codepoints, (codepointCount > 0)? codepointCount : 95, FONT_DEFAULT, &font.glyphCount);
549 }
550 else
551 #endif
552 #if SUPPORT_FILEFORMAT_BDF
553 if (TextIsEqual(fileExtLower, ".bdf"))
554 {
555 font.glyphs = LoadFontDataBDF(fileData, dataSize, codepoints, (codepointCount > 0)? codepointCount : 95, &font.baseSize);
556 font.glyphCount = (codepointCount > 0)? codepointCount : 95;
557 }
558 else
559 #endif
560 {
561 font.glyphs = NULL;
562 }
563
564 #if SUPPORT_FILEFORMAT_TTF || SUPPORT_FILEFORMAT_BDF
565 if (font.glyphs != NULL)
566 {
567 font.glyphPadding = FONT_TTF_DEFAULT_CHARS_PADDING;
568
569 Image atlas = GenImageFontAtlas(font.glyphs, &font.recs, font.glyphCount, font.baseSize, font.glyphPadding, 0);
570 font.texture = LoadTextureFromImage(atlas);
571
572 // Update glyphs[i].image to use alpha, required to be used on ImageDrawText()
573 for (int i = 0; i < font.glyphCount; i++)
574 {
575 UnloadImage(font.glyphs[i].image);
576 font.glyphs[i].image = ImageFromImage(atlas, font.recs[i]);
577 }
578
579 UnloadImage(atlas);
580
581 TRACELOG(LOG_INFO, "FONT: Data loaded successfully (%i pixel size | %i glyphs)", font.baseSize, font.glyphCount);
582 }
583 else font = GetFontDefault();
584 #else
585 font = GetFontDefault();
586 #endif
587
588 return font;
589 }
590
591 // Check if a font is valid (font data loaded)
592 // WARNING: GPU texture not checked
593 bool IsFontValid(Font font)
594 {
595 return ((font.baseSize > 0) && // Validate font size
596 (font.glyphCount > 0) && // Validate font contains some glyph
597 (font.recs != NULL) && // Validate font recs defining glyphs on texture atlas
598 (font.glyphs != NULL)); // Validate glyph data is loaded
599
600 // NOTE: Further validations could be done to verify if recs and glyphs contain valid data (glyphs values, metrics...)
601 }
602
603 // Load font data for further use
604 // NOTE: Requires TTF font memory data and can generate SDF data
605 GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSize, const int *codepoints, int codepointCount, int type, int *glyphCount)
606 {
607 // NOTE: Using some SDF generation default values,
608 // trades off precision with ability to handle *smaller* sizes
609 #ifndef FONT_SDF_CHAR_PADDING
610 #define FONT_SDF_CHAR_PADDING 4 // SDF font generation char padding
611 #endif
612 #ifndef FONT_SDF_ON_EDGE_VALUE
613 #define FONT_SDF_ON_EDGE_VALUE 128 // SDF font generation on edge value
614 #endif
615 #ifndef FONT_SDF_PIXEL_DIST_SCALE
616 #define FONT_SDF_PIXEL_DIST_SCALE 64.0f // SDF font generation pixel distance scale
617 #endif
618 #ifndef FONT_BITMAP_ALPHA_THRESHOLD
619 #define FONT_BITMAP_ALPHA_THRESHOLD 80 // Bitmap (B&W) font generation alpha threshold
620 #endif
621
622 GlyphInfo *glyphs = NULL;
623 int glyphCounter = 0;
624
625 #if SUPPORT_FILEFORMAT_TTF
626 // Load font data (including pixel data) from TTF memory file
627 // NOTE: Loaded information should be enough to generate font image atlas, using any packaging method
628 if (fileData != NULL)
629 {
630 bool genFontChars = false;
631 stbtt_fontinfo fontInfo = { 0 };
632 // TODO: Should a shallow copy be created to avoid "dealing" with a const user array?
633 int *requiredCodepoints = (int *)codepoints;
634
635 if (stbtt_InitFont(&fontInfo, (unsigned char *)fileData, 0)) // Initialize font for data reading
636 {
637 // Calculate font scale factor
638 float scaleFactor = stbtt_ScaleForPixelHeight(&fontInfo, (float)fontSize);
639
640 // Calculate font basic metrics
641 // NOTE: ascent is equivalent to font baseline
642 int ascent = 0;
643 int descent = 0;
644 int lineGap = 0;
645 stbtt_GetFontVMetrics(&fontInfo, &ascent, &descent, &lineGap);
646
647 // In case no chars count provided, default to 95
648 codepointCount = (codepointCount > 0)? codepointCount : 95;
649
650 // Fill fontChars in case not provided externally
651 // NOTE: By default filling glyphCount consecutively, starting at 32 (Space)
652 if (requiredCodepoints == NULL)
653 {
654 requiredCodepoints = (int *)RL_MALLOC(codepointCount*sizeof(int));
655 for (int i = 0; i < codepointCount; i++) requiredCodepoints[i] = i + 32;
656 genFontChars = true;
657 }
658
659 // Check available glyphs on provided font before loading them
660 for (int i = 0, index; i < codepointCount; i++)
661 {
662 index = stbtt_FindGlyphIndex(&fontInfo, requiredCodepoints[i]);
663 if (index > 0) glyphCounter++;
664 }
665
666 // WARNING: Allocating space for maximum number of codepoints
667 glyphs = (GlyphInfo *)RL_CALLOC(glyphCounter, sizeof(GlyphInfo));
668 glyphCounter = 0; // Reset to reuse
669
670 int k = 0;
671 for (int i = 0; i < codepointCount; i++)
672 {
673 int cpWidth = 0, cpHeight = 0; // Codepoint width and height (on generation)
674 int cp = requiredCodepoints[i]; // Codepoint value to get info for
675
676 // Render a unicode codepoint to a bitmap
677 // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
678 // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
679 // stbtt_MakeCodepointBitmap() -- renders into a provided bitmap
680
681 // Check if a glyph is available in the font
682 // WARNING: if (index == 0), glyph not found, it could fallback to default .notdef glyph (if defined in font)
683 int index = stbtt_FindGlyphIndex(&fontInfo, cp);
684
685 if (index > 0)
686 {
687 // NOTE: Only storing glyphs for codepoints found in the font
688 glyphs[k].value = cp;
689
690 switch (type)
691 {
692 case FONT_DEFAULT:
693 case FONT_BITMAP:
694 {
695 glyphs[k].image.data = stbtt_GetCodepointBitmap(&fontInfo, scaleFactor, scaleFactor, cp,
696 &cpWidth, &cpHeight, &glyphs[k].offsetX, &glyphs[k].offsetY);
697 } break;
698 case FONT_SDF:
699 {
700 if (cp != 32)
701 {
702 glyphs[k].image.data = stbtt_GetCodepointSDF(&fontInfo, scaleFactor, cp,
703 FONT_SDF_CHAR_PADDING, FONT_SDF_ON_EDGE_VALUE, FONT_SDF_PIXEL_DIST_SCALE,
704 &cpWidth, &cpHeight, &glyphs[k].offsetX, &glyphs[k].offsetY);
705 }
706 } break;
707 //case FONT_MSDF:
708 default: break;
709 }
710
711 if (glyphs[k].image.data != NULL) // Glyph data has been found in the font
712 {
713 stbtt_GetCodepointHMetrics(&fontInfo, cp, &glyphs[k].advanceX, NULL);
714 glyphs[k].advanceX = (int)((float)glyphs[k].advanceX*scaleFactor);
715
716 // WARNING: If requested SDF font, sdf-glyph height is definitely bigger than fontSize due to FONT_SDF_CHAR_PADDING
717 if ((type != FONT_SDF) && (cpHeight > fontSize)) TRACELOG(LOG_WARNING, "FONT: [0x%04x] Glyph height is bigger than requested font size: %i > %i", cp, cpHeight, (int)fontSize);
718
719 // Load glyph image
720 glyphs[k].image.width = cpWidth;
721 glyphs[k].image.height = cpHeight;
722 glyphs[k].image.mipmaps = 1;
723 glyphs[k].image.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE;
724
725 glyphs[k].offsetY += (int)((float)ascent*scaleFactor);
726 }
727 //else TRACELOG(LOG_WARNING, "FONT: Glyph [0x%08x] has no image data available", cp); // Only reported for 0x20 and 0x3000
728
729 // Create an empty image for Space character (0x20), useful for sprite font generation
730 // NOTE: Another space to consider: 0x3000 (CJK - Ideographic Space)
731 if ((cp == 0x20) || (cp == 0x3000))
732 {
733 stbtt_GetCodepointHMetrics(&fontInfo, cp, &glyphs[k].advanceX, NULL);
734 glyphs[k].advanceX = (int)((float)glyphs[k].advanceX*scaleFactor);
735
736 Image imSpace = {
737 .data = NULL,
738 .width = glyphs[k].advanceX,
739 .height = fontSize,
740 .mipmaps = 1,
741 .format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE
742 };
743
744 // Only allocate space image if required
745 if (glyphs[k].advanceX > 0) imSpace.data = RL_CALLOC(glyphs[k].advanceX*fontSize, 1);
746 else glyphs[k].advanceX = 0;
747
748 glyphs[k].image = imSpace;
749 }
750
751 if (type == FONT_BITMAP)
752 {
753 // Aliased bitmap (black & white) font generation, avoiding anti-aliasing
754 // NOTE: For optimum results, bitmap font should be generated at base pixel size
755 for (int p = 0; p < cpWidth*cpHeight; p++)
756 {
757 if (((unsigned char *)glyphs[k].image.data)[p] < FONT_BITMAP_ALPHA_THRESHOLD)
758 ((unsigned char *)glyphs[k].image.data)[p] = 0;
759 else ((unsigned char *)glyphs[k].image.data)[p] = 255;
760 }
761 }
762
763 k++;
764 glyphCounter++;
765 }
766 else
767 {
768 // WARNING: Glyph not found on font, optionally use a fallback glyph
769 }
770 }
771
772 if (glyphCounter < codepointCount) TRACELOG(LOG_WARNING, "FONT: Requested codepoints glyphs found: [%i/%i]", k, codepointCount);
773 }
774 else TRACELOG(LOG_WARNING, "FONT: Failed to process TTF font data");
775
776 if (genFontChars) RL_FREE(requiredCodepoints);
777 }
778 #endif
779
780 *glyphCount = glyphCounter;
781 return glyphs;
782 }
783
784 // Generate image font atlas using chars info
785 // NOTE: Packing method: 0-Default, 1-Skyline
786 #if SUPPORT_FILEFORMAT_TTF || SUPPORT_FILEFORMAT_BDF
787 Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyphCount, int fontSize, int padding, int packMethod)
788 {
789 Image atlas = { 0 };
790
791 if (glyphs == NULL)
792 {
793 TRACELOG(LOG_WARNING, "FONT: Provided glyphs info not valid, returning empty image atlas");
794 return atlas;
795 }
796
797 *glyphRecs = NULL;
798
799 // In case no chars count provided, suppose default of 95
800 glyphCount = (glyphCount > 0)? glyphCount : 95;
801
802 // NOTE: Rectangles memory is loaded here!
803 Rectangle *recs = (Rectangle *)RL_MALLOC(glyphCount*sizeof(Rectangle));
804
805 // Calculate image size based on total glyph width and glyph row count
806 int totalWidth = 0;
807 int maxGlyphWidth = 0;
808
809 for (int i = 0; i < glyphCount; i++)
810 {
811 if (glyphs[i].image.width > maxGlyphWidth) maxGlyphWidth = glyphs[i].image.width;
812 totalWidth += glyphs[i].image.width + 2*padding;
813 }
814
815 int paddedFontSize = fontSize + 2*padding;
816
817 // Estimate image atlas size from available data
818 // NOTE: Multiplying total expected area by 1.2f scale factor but in case
819 // some glyphs do not fit, the atlas height is scaled x2 to fit them
820 float totalArea = totalWidth*paddedFontSize*1.2f;
821 float imageMinSize = sqrtf(totalArea);
822 int imageSize = (int)powf(2, ceilf(logf(imageMinSize)/logf(2)));
823
824 if (totalArea < ((imageSize*imageSize)/2))
825 {
826 atlas.width = imageSize; // Atlas bitmap width
827 atlas.height = imageSize/2; // Atlas bitmap height
828 }
829 else
830 {
831 atlas.width = imageSize; // Atlas bitmap width
832 atlas.height = imageSize; // Atlas bitmap height
833 }
834
835 int atlasDataSize = atlas.width*atlas.height; // Save total size for bounds checking
836 atlas.data = (unsigned char *)RL_CALLOC(atlasDataSize, 1); // Create a bitmap to store characters (8 bpp)
837 atlas.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE;
838 atlas.mipmaps = 1;
839
840 // DEBUG: View padding in the generated image setting a gray background...
841 //for (int i = 0; i < atlas.width*atlas.height; i++) ((unsigned char *)atlas.data)[i] = 100;
842
843 if (packMethod == 0) // Use basic packing algorithm
844 {
845 int offsetX = padding;
846 int offsetY = padding;
847
848 // NOTE: Using simple packaging, one char after another
849 for (int i = 0; i < glyphCount; i++)
850 {
851 // Check remaining space for glyph
852 if (offsetX >= (atlas.width - glyphs[i].image.width - 2*padding))
853 {
854 offsetX = padding;
855
856 // NOTE: Be careful on offsetY for SDF fonts, by default SDF
857 // use an internal padding of 4 pixels, it means char rectangle
858 // height is bigger than fontSize, it could be up to (fontSize + 8)
859 offsetY += (fontSize + 2*padding);
860
861 if (offsetY > (atlas.height - fontSize - padding))
862 {
863 TRACELOG(LOG_WARNING, "FONT: Updating atlas size to fit all characters");
864
865 // Update atlas size to fit all characters
866 int updatedAtlasHeight = atlas.height*2;
867 int updatedAtlasDataSize = atlas.width*updatedAtlasHeight;
868 unsigned char *updatedAtlasData = (unsigned char *)RL_CALLOC(updatedAtlasDataSize, 1);
869
870 memcpy(updatedAtlasData, atlas.data, atlasDataSize);
871 RL_FREE(atlas.data);
872 atlas.data = updatedAtlasData;
873 atlas.height = updatedAtlasHeight;
874 atlasDataSize = updatedAtlasDataSize;
875 }
876 }
877
878 // Copy pixel data from glyph image to atlas
879 for (int y = 0; y < glyphs[i].image.height; y++)
880 {
881 for (int x = 0; x < glyphs[i].image.width; x++)
882 {
883 int destX = offsetX + x;
884 int destY = offsetY + y;
885
886 // Security: check both lower and upper bounds
887 if ((destX >= 0) && (destX < atlas.width) && (destY >= 0) && (destY < atlas.height))
888 {
889 ((unsigned char *)atlas.data)[destY*atlas.width + destX] =
890 ((unsigned char *)glyphs[i].image.data)[y*glyphs[i].image.width + x];
891 }
892 }
893 }
894
895 // Fill chars rectangles in atlas info
896 recs[i].x = (float)offsetX;
897 recs[i].y = (float)offsetY;
898 recs[i].width = (float)glyphs[i].image.width;
899 recs[i].height = (float)glyphs[i].image.height;
900
901 // Move atlas position X for next character drawing
902 offsetX += (glyphs[i].image.width + 2*padding);
903 }
904 }
905 else if (packMethod == 1) // Use Skyline rect packing algorithm (stb_pack_rect)
906 {
907 stbrp_context *context = (stbrp_context *)RL_MALLOC(sizeof(*context));
908 stbrp_node *nodes = (stbrp_node *)RL_MALLOC(glyphCount*sizeof(*nodes));
909
910 stbrp_init_target(context, atlas.width, atlas.height, nodes, glyphCount);
911 stbrp_rect *rects = (stbrp_rect *)RL_MALLOC(glyphCount*sizeof(stbrp_rect));
912
913 // Fill rectangles for packaging
914 for (int i = 0; i < glyphCount; i++)
915 {
916 rects[i].id = i;
917 rects[i].w = glyphs[i].image.width + 2*padding;
918 rects[i].h = glyphs[i].image.height + 2*padding;
919 }
920
921 // Package rectangles into atlas
922 stbrp_pack_rects(context, rects, glyphCount);
923
924 for (int i = 0; i < glyphCount; i++)
925 {
926 // It returns char rectangles in atlas
927 recs[i].x = rects[i].x + (float)padding;
928 recs[i].y = rects[i].y + (float)padding;
929 recs[i].width = (float)glyphs[i].image.width;
930 recs[i].height = (float)glyphs[i].image.height;
931
932 if (rects[i].was_packed)
933 {
934 // Copy pixel data from fc.data to atlas
935 for (int y = 0; y < glyphs[i].image.height; y++)
936 {
937 for (int x = 0; x < glyphs[i].image.width; x++)
938 {
939 int destX = rects[i].x + padding + x;
940 int destY = rects[i].y + padding + y;
941
942 // Security fix: check both lower and upper bounds
943 if (destX >= 0 && destX < atlas.width && destY >= 0 && destY < atlas.height)
944 {
945 ((unsigned char *)atlas.data)[destY * atlas.width + destX] =
946 ((unsigned char *)glyphs[i].image.data)[y * glyphs[i].image.width + x];
947 }
948 }
949 }
950 }
951 else TRACELOG(LOG_WARNING, "FONT: Failed to package glyph (0x%02x)", glyphs[i].value);
952 }
953
954 RL_FREE(rects);
955 RL_FREE(nodes);
956 RL_FREE(context);
957 }
958
959 // Add a 3x3 white rectangle at the bottom-right corner of the generated atlas,
960 // useful to use as the white texture to draw shapes with raylib
961 // Security: ensure the atlas is large enough to hold a 3x3 rectangle
962 if ((FONT_ATLAS_CORNER_REC_SIZE > 0) && (atlas.width >= 3) && (atlas.height >= 3))
963 {
964 for (int i = 0, k = atlas.width*atlas.height - 1; i < FONT_ATLAS_CORNER_REC_SIZE; i++)
965 {
966 ((unsigned char *)atlas.data)[k - 0] = 255;
967 ((unsigned char *)atlas.data)[k - 1] = 255;
968 ((unsigned char *)atlas.data)[k - 2] = 255;
969 k -= atlas.width;
970 }
971 }
972
973 // Convert image data from GRAYSCALE to GRAY_ALPHA
974 unsigned char *dataGrayAlpha = (unsigned char *)RL_MALLOC(atlas.width*atlas.height*sizeof(unsigned char)*2); // Two channels
975
976 for (int i = 0, k = 0; i < atlas.width*atlas.height; i++, k += 2)
977 {
978 dataGrayAlpha[k] = 255;
979 dataGrayAlpha[k + 1] = ((unsigned char *)atlas.data)[i];
980 }
981
982 RL_FREE(atlas.data);
983 atlas.data = dataGrayAlpha;
984 atlas.format = PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA;
985
986 *glyphRecs = recs;
987
988 return atlas;
989 }
990 #endif
991
992 // Unload font glyphs info data (RAM)
993 void UnloadFontData(GlyphInfo *glyphs, int glyphCount)
994 {
995 if (glyphs != NULL)
996 {
997 for (int i = 0; i < glyphCount; i++) UnloadImage(glyphs[i].image);
998
999 RL_FREE(glyphs);
1000 }
1001 }
1002
1003 // Unload Font from GPU memory (VRAM)
1004 void UnloadFont(Font font)
1005 {
1006 // NOTE: Make sure font is not default font (fallback)
1007 if (font.texture.id != GetFontDefault().texture.id)
1008 {
1009 UnloadFontData(font.glyphs, font.glyphCount);
1010 UnloadTexture(font.texture);
1011 RL_FREE(font.recs);
1012
1013 TRACELOG(LOG_DEBUG, "FONT: Unloaded font data from RAM and VRAM");
1014 }
1015 }
1016
1017 // Export font as code file, returns true on success
1018 bool ExportFontAsCode(Font font, const char *fileName)
1019 {
1020 bool result = false;
1021
1022 #ifndef TEXT_BYTES_PER_LINE
1023 #define TEXT_BYTES_PER_LINE 20
1024 #endif
1025
1026 // Get file name from path
1027 char fileNamePascal[256] = { 0 };
1028 strncpy(fileNamePascal, TextToPascal(GetFileNameWithoutExt(fileName)), 256 - 1);
1029
1030 // Get font atlas image and size, required to estimate code file size
1031 // NOTE: This mechanism is highly coupled to raylib
1032 Image image = LoadImageFromTexture(font.texture);
1033 if (image.format != PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) TRACELOG(LOG_WARNING, "Font export as code: Font image format is not GRAY+ALPHA!");
1034 int imageDataSize = GetPixelDataSize(image.width, image.height, image.format);
1035
1036 // Image data is usually GRAYSCALE + ALPHA and can be reduced to GRAYSCALE
1037 //ImageFormat(&image, PIXELFORMAT_UNCOMPRESSED_GRAYSCALE);
1038
1039 // Estimate text code size
1040 // - Image data is stored as "0x%02x", so it requires at least 4 char per byte, let's use 6
1041 // - font.recs[] data is stored as "{ %1.0f, %1.0f, %1.0f , %1.0f }", let's reserve 64 per rec
1042 // - font.glyphs[] data is stored as "{ %i, %i, %i, %i, { 0 }},\n", let's reserve 64 per glyph
1043 // - Comments and additional code, let's reserve 32KB
1044 int txtDataSize = imageDataSize*6 + font.glyphCount*64 + font.glyphCount*64 + 32768;
1045 char *txtData = (char *)RL_CALLOC(txtDataSize, sizeof(char));
1046
1047 int byteCount = 0;
1048 byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n");
1049 byteCount += sprintf(txtData + byteCount, "// //\n");
1050 byteCount += sprintf(txtData + byteCount, "// FontAsCode exporter v1.0 - Font data exported as an array of bytes //\n");
1051 byteCount += sprintf(txtData + byteCount, "// //\n");
1052 byteCount += sprintf(txtData + byteCount, "// more info and bugs-report: github.com/raysan5/raylib //\n");
1053 byteCount += sprintf(txtData + byteCount, "// feedback and support: ray[at]raylib.com //\n");
1054 byteCount += sprintf(txtData + byteCount, "// //\n");
1055 byteCount += sprintf(txtData + byteCount, "// Copyright (c) 2018-2026 Ramon Santamaria (@raysan5) //\n");
1056 byteCount += sprintf(txtData + byteCount, "// //\n");
1057 byteCount += sprintf(txtData + byteCount, "// ---------------------------------------------------------------------------------- //\n");
1058 byteCount += sprintf(txtData + byteCount, "// //\n");
1059 byteCount += sprintf(txtData + byteCount, "// TODO: Fill the information and license of the exported font here: //\n");
1060 byteCount += sprintf(txtData + byteCount, "// //\n");
1061 byteCount += sprintf(txtData + byteCount, "// Font name: .... //\n");
1062 byteCount += sprintf(txtData + byteCount, "// Font creator: .... //\n");
1063 byteCount += sprintf(txtData + byteCount, "// Font LICENSE: .... //\n");
1064 byteCount += sprintf(txtData + byteCount, "// //\n");
1065 byteCount += sprintf(txtData + byteCount, "////////////////////////////////////////////////////////////////////////////////////////\n\n");
1066
1067 #define SUPPORT_COMPRESSED_FONT_ATLAS
1068 #if defined(SUPPORT_COMPRESSED_FONT_ATLAS)
1069 // WARNING: Data is compressed using raylib CompressData() DEFLATE,
1070 // it requires to be decompressed with raylib DecompressData(), that requires
1071 // compiling raylib with SUPPORT_COMPRESSION_API config flag enabled
1072
1073 // Compress font image data
1074 int compDataSize = 0;
1075 unsigned char *compData = CompressData((const unsigned char *)image.data, imageDataSize, &compDataSize);
1076
1077 // Save font image data (compressed)
1078 byteCount += sprintf(txtData + byteCount, "#define COMPRESSED_DATA_SIZE_FONT_%s %i\n\n", TextToUpper(fileNamePascal), compDataSize);
1079 byteCount += sprintf(txtData + byteCount, "// Font image pixels data compressed (DEFLATE)\n");
1080 byteCount += sprintf(txtData + byteCount, "// NOTE: Original pixel data simplified to GRAYSCALE\n");
1081 byteCount += sprintf(txtData + byteCount, "static unsigned char fontData_%s[COMPRESSED_DATA_SIZE_FONT_%s] = { ", fileNamePascal, TextToUpper(fileNamePascal));
1082 for (int i = 0; i < compDataSize - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "0x%02x,\n " : "0x%02x, "), compData[i]);
1083 byteCount += sprintf(txtData + byteCount, "0x%02x };\n\n", compData[compDataSize - 1]);
1084 RL_FREE(compData);
1085 #else
1086 // Save font image data (uncompressed)
1087 byteCount += sprintf(txtData + byteCount, "// Font image pixels data\n");
1088 byteCount += sprintf(txtData + byteCount, "// NOTE: 2 bytes per pixel, GRAY + ALPHA channels\n");
1089 byteCount += sprintf(txtData + byteCount, "static unsigned char fontImageData_%s[%i] = { ", fileNamePascal, imageDataSize);
1090 for (int i = 0; i < imageDataSize - 1; i++) byteCount += sprintf(txtData + byteCount, ((i%TEXT_BYTES_PER_LINE == 0)? "0x%02x,\n " : "0x%02x, "), ((unsigned char *)imFont.data)[i]);
1091 byteCount += sprintf(txtData + byteCount, "0x%02x };\n\n", ((unsigned char *)imFont.data)[imageDataSize - 1]);
1092 #endif
1093
1094 // Save font recs data
1095 byteCount += sprintf(txtData + byteCount, "// Font characters rectangles data\n");
1096 byteCount += sprintf(txtData + byteCount, "static Rectangle fontRecs_%s[%i] = {\n", fileNamePascal, font.glyphCount);
1097 for (int i = 0; i < font.glyphCount; i++)
1098 {
1099 byteCount += sprintf(txtData + byteCount, " { %1.0f, %1.0f, %1.0f , %1.0f },\n", font.recs[i].x, font.recs[i].y, font.recs[i].width, font.recs[i].height);
1100 }
1101 byteCount += sprintf(txtData + byteCount, "};\n\n");
1102
1103 // Save font glyphs data
1104 // NOTE: Glyphs image data not saved (grayscale pixels), it could be generated from image and recs
1105 byteCount += sprintf(txtData + byteCount, "// Font glyphs info data\n");
1106 byteCount += sprintf(txtData + byteCount, "// NOTE: No glyphs.image data provided\n");
1107 byteCount += sprintf(txtData + byteCount, "static GlyphInfo fontGlyphs_%s[%i] = {\n", fileNamePascal, font.glyphCount);
1108 for (int i = 0; i < font.glyphCount; i++)
1109 {
1110 byteCount += sprintf(txtData + byteCount, " { %i, %i, %i, %i, { 0 }},\n", font.glyphs[i].value, font.glyphs[i].offsetX, font.glyphs[i].offsetY, font.glyphs[i].advanceX);
1111 }
1112 byteCount += sprintf(txtData + byteCount, "};\n\n");
1113
1114 // Custom font loading function
1115 byteCount += sprintf(txtData + byteCount, "// Font loading function: %s\n", fileNamePascal);
1116 byteCount += sprintf(txtData + byteCount, "static Font LoadFont_%s(void)\n{\n", fileNamePascal);
1117 byteCount += sprintf(txtData + byteCount, " Font font = { 0 };\n\n");
1118 byteCount += sprintf(txtData + byteCount, " font.baseSize = %i;\n", font.baseSize);
1119 byteCount += sprintf(txtData + byteCount, " font.glyphCount = %i;\n", font.glyphCount);
1120 byteCount += sprintf(txtData + byteCount, " font.glyphPadding = %i;\n\n", font.glyphPadding);
1121 byteCount += sprintf(txtData + byteCount, " // Custom font loading\n");
1122 #if defined(SUPPORT_COMPRESSED_FONT_ATLAS)
1123 byteCount += sprintf(txtData + byteCount, " // NOTE: Compressed font image data (DEFLATE), it requires DecompressData() function\n");
1124 byteCount += sprintf(txtData + byteCount, " int fontDataSize_%s = 0;\n", fileNamePascal);
1125 byteCount += sprintf(txtData + byteCount, " unsigned char *data = DecompressData(fontData_%s, COMPRESSED_DATA_SIZE_FONT_%s, &fontDataSize_%s);\n", fileNamePascal, TextToUpper(fileNamePascal), fileNamePascal);
1126 byteCount += sprintf(txtData + byteCount, " Image imFont = { data, %i, %i, 1, %i };\n\n", image.width, image.height, image.format);
1127 #else
1128 byteCount += sprintf(txtData + byteCount, " Image imFont = { fontImageData_%s, %i, %i, 1, %i };\n\n", styleName, image.width, image.height, image.format);
1129 #endif
1130 byteCount += sprintf(txtData + byteCount, " // Load texture from image\n");
1131 byteCount += sprintf(txtData + byteCount, " font.texture = LoadTextureFromImage(imFont);\n");
1132 #if defined(SUPPORT_COMPRESSED_FONT_ATLAS)
1133 byteCount += sprintf(txtData + byteCount, " UnloadImage(imFont); // Uncompressed data can be unloaded from memory\n\n");
1134 #endif
1135 // There are two possible mechanisms to assign font.recs and font.glyphs data,
1136 // that data is already available as global arrays, two options to assign that data:
1137 // - 1. Data copy. This option consumes more memory and Font MUST be unloaded by user, requiring additional code
1138 // - 2. Data assignment. This option consumes less memory and Font MUST NOT be unloaded by user because data is on protected DATA segment
1139 //#define SUPPORT_FONT_DATA_COPY
1140 #if defined(SUPPORT_FONT_DATA_COPY)
1141 byteCount += sprintf(txtData + byteCount, " // Copy glyph recs data from global fontRecs\n");
1142 byteCount += sprintf(txtData + byteCount, " // NOTE: Required to avoid issues if trying to free font\n");
1143 byteCount += sprintf(txtData + byteCount, " font.recs = (Rectangle *)malloc(font.glyphCount*sizeof(Rectangle));\n");
1144 byteCount += sprintf(txtData + byteCount, " memcpy(font.recs, fontRecs_%s, font.glyphCount*sizeof(Rectangle));\n\n", fileNamePascal);
1145
1146 byteCount += sprintf(txtData + byteCount, " // Copy font glyph info data from global fontChars\n");
1147 byteCount += sprintf(txtData + byteCount, " // NOTE: Required to avoid issues if trying to free font\n");
1148 byteCount += sprintf(txtData + byteCount, " font.glyphs = (GlyphInfo *)malloc(font.glyphCount*sizeof(GlyphInfo));\n");
1149 byteCount += sprintf(txtData + byteCount, " memcpy(font.glyphs, fontGlyphs_%s, font.glyphCount*sizeof(GlyphInfo));\n\n", fileNamePascal);
1150 #else
1151 byteCount += sprintf(txtData + byteCount, " // Assign glyph recs and info data directly\n");
1152 byteCount += sprintf(txtData + byteCount, " // WARNING: This font data must not be unloaded\n");
1153 byteCount += sprintf(txtData + byteCount, " font.recs = fontRecs_%s;\n", fileNamePascal);
1154 byteCount += sprintf(txtData + byteCount, " font.glyphs = fontGlyphs_%s;\n\n", fileNamePascal);
1155 #endif
1156 byteCount += sprintf(txtData + byteCount, " return font;\n");
1157 byteCount += sprintf(txtData + byteCount, "}\n");
1158
1159 UnloadImage(image);
1160
1161 // NOTE: Text data size exported is determined by '\0' (NULL) character
1162 result = SaveFileText(fileName, txtData);
1163
1164 RL_FREE(txtData);
1165
1166 if (result != 0) TRACELOG(LOG_INFO, "FILEIO: [%s] Font as code exported successfully", fileName);
1167 else TRACELOG(LOG_WARNING, "FILEIO: [%s] Failed to export font as code", fileName);
1168
1169 return result;
1170 }
1171
1172 // Draw current FPS
1173 // NOTE: Uses default font
1174 void DrawFPS(int posX, int posY)
1175 {
1176 Color color = LIME; // Good FPS
1177 int fps = GetFPS();
1178
1179 if ((fps < 30) && (fps >= 15)) color = ORANGE; // Warning FPS
1180 else if (fps < 15) color = RED; // Low FPS
1181
1182 DrawText(TextFormat("%2i FPS", fps), posX, posY, 20, color);
1183 }
1184
1185 // Draw text (using default font)
1186 // NOTE: fontSize work like in any drawing program but if fontSize is lower than font-base-size, then font-base-size is used
1187 // NOTE: chars spacing is proportional to fontSize
1188 void DrawText(const char *text, int posX, int posY, int fontSize, Color color)
1189 {
1190 // Check if default font has been loaded
1191 if (GetFontDefault().texture.id != 0)
1192 {
1193 Vector2 position = { (float)posX, (float)posY };
1194
1195 int defaultFontSize = 10; // Default Font chars height in pixel
1196 if (fontSize < defaultFontSize) fontSize = defaultFontSize;
1197 int spacing = fontSize/defaultFontSize;
1198
1199 DrawTextEx(GetFontDefault(), text, position, (float)fontSize, (float)spacing, color);
1200 }
1201 }
1202
1203 // Draw text using Font
1204 // NOTE: chars spacing is NOT proportional to fontSize
1205 void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint)
1206 {
1207 if (font.texture.id == 0) font = GetFontDefault(); // Security check in case of not valid font
1208
1209 int size = TextLength(text); // Total size in bytes of the text, scanned by codepoints in loop
1210
1211 float textOffsetY = 0; // Offset between lines (on linebreak '\n')
1212 float textOffsetX = 0.0f; // Offset X to next character to draw
1213
1214 float scaleFactor = fontSize/font.baseSize; // Character quad scaling factor
1215
1216 for (int i = 0; i < size;)
1217 {
1218 // Get next codepoint from byte string and glyph index in font
1219 int codepointByteCount = 0;
1220 int codepoint = GetCodepointNext(&text[i], &codepointByteCount);
1221 int index = GetGlyphIndex(font, codepoint);
1222
1223 if (codepoint == '\n')
1224 {
1225 // NOTE: Line spacing is a global variable, use SetTextLineSpacing() to setup
1226 textOffsetY += (fontSize + textLineSpacing);
1227 textOffsetX = 0.0f;
1228 }
1229 else
1230 {
1231 if ((codepoint != ' ') && (codepoint != '\t'))
1232 {
1233 DrawTextCodepoint(font, codepoint, (Vector2){ position.x + textOffsetX, position.y + textOffsetY }, fontSize, tint);
1234 }
1235
1236 if (font.glyphs[index].advanceX == 0) textOffsetX += ((float)font.recs[index].width*scaleFactor + spacing);
1237 else textOffsetX += ((float)font.glyphs[index].advanceX*scaleFactor + spacing);
1238 }
1239
1240 i += codepointByteCount; // Move text bytes counter to next codepoint
1241 }
1242 }
1243
1244 // Draw text using Font and pro parameters (rotation)
1245 void DrawTextPro(Font font, const char *text, Vector2 position, Vector2 origin, float rotation, float fontSize, float spacing, Color tint)
1246 {
1247 rlPushMatrix();
1248
1249 rlTranslatef(position.x, position.y, 0.0f);
1250 rlRotatef(rotation, 0.0f, 0.0f, 1.0f);
1251 rlTranslatef(-origin.x, -origin.y, 0.0f);
1252
1253 DrawTextEx(font, text, (Vector2){ 0.0f, 0.0f }, fontSize, spacing, tint);
1254
1255 rlPopMatrix();
1256 }
1257
1258 // Draw one character (codepoint)
1259 void DrawTextCodepoint(Font font, int codepoint, Vector2 position, float fontSize, Color tint)
1260 {
1261 // Character index position in sprite font
1262 // NOTE: In case a codepoint is not available in the font, index returned points to '?'
1263 int index = GetGlyphIndex(font, codepoint);
1264 float scaleFactor = fontSize/font.baseSize; // Character quad scaling factor
1265
1266 // Character destination rectangle on screen
1267 // NOTE: Considering glyph padding on drawing
1268 Rectangle dstRec = { position.x + font.glyphs[index].offsetX*scaleFactor - (float)font.glyphPadding*scaleFactor,
1269 position.y + font.glyphs[index].offsetY*scaleFactor - (float)font.glyphPadding*scaleFactor,
1270 (font.recs[index].width + 2.0f*font.glyphPadding)*scaleFactor,
1271 (font.recs[index].height + 2.0f*font.glyphPadding)*scaleFactor };
1272
1273 // Character source rectangle from font texture atlas
1274 // NOTE: Considering glyphs padding when drawing, it could be required for outline/glow shader effects
1275 Rectangle srcRec = { font.recs[index].x - (float)font.glyphPadding, font.recs[index].y - (float)font.glyphPadding,
1276 font.recs[index].width + 2.0f*font.glyphPadding, font.recs[index].height + 2.0f*font.glyphPadding };
1277
1278 // Draw the character texture on the screen
1279 DrawTexturePro(font.texture, srcRec, dstRec, (Vector2){ 0, 0 }, 0.0f, tint);
1280 }
1281
1282 // Draw multiple character (codepoints)
1283 void DrawTextCodepoints(Font font, const int *codepoints, int codepointCount, Vector2 position, float fontSize, float spacing, Color tint)
1284 {
1285 float textOffsetY = 0; // Offset between lines (on linebreak '\n')
1286 float textOffsetX = 0.0f; // Offset X to next character to draw
1287
1288 float scaleFactor = fontSize/font.baseSize; // Character quad scaling factor
1289
1290 for (int i = 0; i < codepointCount; i++)
1291 {
1292 int index = GetGlyphIndex(font, codepoints[i]);
1293
1294 if (codepoints[i] == '\n')
1295 {
1296 // NOTE: Line spacing is a global variable, use SetTextLineSpacing() to setup
1297 textOffsetY += (fontSize + textLineSpacing);
1298 textOffsetX = 0.0f;
1299 }
1300 else
1301 {
1302 if ((codepoints[i] != ' ') && (codepoints[i] != '\t'))
1303 {
1304 DrawTextCodepoint(font, codepoints[i], (Vector2){ position.x + textOffsetX, position.y + textOffsetY }, fontSize, tint);
1305 }
1306
1307 if (font.glyphs[index].advanceX == 0) textOffsetX += ((float)font.recs[index].width*scaleFactor + spacing);
1308 else textOffsetX += ((float)font.glyphs[index].advanceX*scaleFactor + spacing);
1309 }
1310 }
1311 }
1312
1313 // Set vertical line spacing when drawing with line-breaks
1314 void SetTextLineSpacing(int spacing)
1315 {
1316 textLineSpacing = spacing;
1317 }
1318
1319 // Measure string width for default font
1320 int MeasureText(const char *text, int fontSize)
1321 {
1322 Vector2 textSize = { 0.0f, 0.0f };
1323
1324 // Check if default font has been loaded
1325 if (GetFontDefault().texture.id != 0)
1326 {
1327 int defaultFontSize = 10; // Default Font glyphs height in pixel
1328 if (fontSize < defaultFontSize) fontSize = defaultFontSize;
1329 int spacing = fontSize/defaultFontSize;
1330
1331 textSize = MeasureTextEx(GetFontDefault(), text, (float)fontSize, (float)spacing);
1332 }
1333
1334 return (int)textSize.x;
1335 }
1336
1337 // Measure string size for Font
1338 Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing)
1339 {
1340 Vector2 textSize = { 0 };
1341
1342 if ((font.texture.id == 0) || (text == NULL) || (text[0] == '\0')) return textSize; // Security check
1343
1344 int size = TextLength(text); // Get size in bytes of text
1345 int tempByteCounter = 0; // Used to count longer text line num chars
1346 int byteCounter = 0;
1347
1348 float textWidth = 0.0f;
1349 float tempTextWidth = 0.0f; // Used to count longer text line width
1350
1351 float textHeight = fontSize;
1352 float scaleFactor = fontSize/(float)font.baseSize;
1353
1354 int letter = 0; // Current character
1355 int index = 0; // Index position in sprite font
1356
1357 for (int i = 0; i < size;)
1358 {
1359 byteCounter++;
1360
1361 int codepointByteCount = 0;
1362 letter = GetCodepointNext(&text[i], &codepointByteCount);
1363 index = GetGlyphIndex(font, letter);
1364
1365 i += codepointByteCount;
1366
1367 if (letter != '\n')
1368 {
1369 if (font.glyphs[index].advanceX > 0) textWidth += font.glyphs[index].advanceX;
1370 else textWidth += (font.recs[index].width + font.glyphs[index].offsetX);
1371 }
1372 else
1373 {
1374 if (tempTextWidth < textWidth) tempTextWidth = textWidth;
1375 byteCounter = 0;
1376 textWidth = 0;
1377
1378 // NOTE: Line spacing is a global variable, use SetTextLineSpacing() to setup
1379 textHeight += (fontSize + textLineSpacing);
1380 }
1381
1382 if (tempByteCounter < byteCounter) tempByteCounter = byteCounter;
1383 }
1384
1385 if (tempTextWidth < textWidth) tempTextWidth = textWidth;
1386
1387 textSize.x = tempTextWidth*scaleFactor + (float)((tempByteCounter - 1)*spacing);
1388 textSize.y = textHeight;
1389
1390 return textSize;
1391 }
1392
1393 // Measure string size for an existing array of codepoints for Font
1394 Vector2 MeasureTextCodepoints(Font font, const int *codepoints, int length, float fontSize, float spacing)
1395 {
1396 Vector2 textSize = { 0 };
1397
1398 if ((font.texture.id == 0) || (codepoints == NULL) || (length == 0)) return textSize; // Security check
1399
1400 float textWidth = 0.0f;
1401 // Used to count longer text line width
1402 float tempTextWidth = 0.0f;
1403
1404 // Used to count longer text line num chars
1405 int tempGlyphCounter = 0;
1406 int glyphCounter = 0;
1407
1408 float textHeight = fontSize;
1409 float scaleFactor = fontSize/(float)font.baseSize;
1410
1411 // Current character
1412 int letter = 0;
1413 // Index position in sprite font
1414 int index = 0;
1415
1416 for (int i = 0; i < length; i++)
1417 {
1418 letter = codepoints[i];
1419 index = GetGlyphIndex(font, letter);
1420
1421 if (letter != '\n')
1422 {
1423 glyphCounter++;
1424
1425 if (font.glyphs[index].advanceX > 0) textWidth += font.glyphs[index].advanceX;
1426 else textWidth += (font.recs[index].width + font.glyphs[index].offsetX);
1427 }
1428 else
1429 {
1430 if (tempTextWidth < textWidth) tempTextWidth = textWidth;
1431
1432 textWidth = 0;
1433 glyphCounter = 0;
1434
1435 // NOTE: Line spacing is a global variable, use SetTextLineSpacing() to setup
1436 textHeight += (fontSize + textLineSpacing);
1437 }
1438
1439 if (tempGlyphCounter < glyphCounter) tempGlyphCounter = glyphCounter;
1440 }
1441
1442 if (tempTextWidth < textWidth) tempTextWidth = textWidth;
1443
1444 textSize.x = tempTextWidth*scaleFactor + (float)((tempGlyphCounter - 1)*spacing);
1445 textSize.y = textHeight;
1446
1447 return textSize;
1448 }
1449
1450 // Get index position for a unicode character on font
1451 // NOTE: If codepoint is not found in the font it fallbacks to '?'
1452 int GetGlyphIndex(Font font, int codepoint)
1453 {
1454 int index = 0;
1455 if (!IsFontValid(font)) return index;
1456
1457 #define SUPPORT_UNORDERED_CHARSET
1458 #if defined(SUPPORT_UNORDERED_CHARSET)
1459 int fallbackIndex = 0; // Get index of fallback glyph '?'
1460
1461 // Look for character index in the unordered charset
1462 for (int i = 0; i < font.glyphCount; i++)
1463 {
1464 if (font.glyphs[i].value == 63) fallbackIndex = i;
1465
1466 if (font.glyphs[i].value == codepoint)
1467 {
1468 index = i;
1469 break;
1470 }
1471 }
1472
1473 if ((index == 0) && (font.glyphs[0].value != codepoint)) index = fallbackIndex;
1474 #else
1475 index = codepoint - 32;
1476 #endif
1477
1478 return index;
1479 }
1480
1481 // Get glyph font info data for a codepoint (unicode character)
1482 // NOTE: If codepoint is not found in the font it fallbacks to '?'
1483 GlyphInfo GetGlyphInfo(Font font, int codepoint)
1484 {
1485 GlyphInfo info = { 0 };
1486
1487 info = font.glyphs[GetGlyphIndex(font, codepoint)];
1488
1489 return info;
1490 }
1491
1492 // Get glyph rectangle in font atlas for a codepoint (unicode character)
1493 // NOTE: If codepoint is not found in the font it fallbacks to '?'
1494 Rectangle GetGlyphAtlasRec(Font font, int codepoint)
1495 {
1496 Rectangle rec = { 0 };
1497
1498 rec = font.recs[GetGlyphIndex(font, codepoint)];
1499
1500 return rec;
1501 }
1502
1503 //----------------------------------------------------------------------------------
1504 // Text strings management functions
1505 //----------------------------------------------------------------------------------
1506 // Load text as separate lines ('\n')
1507 // NOTE: Returned lines end with null terminator '\0'
1508 char **LoadTextLines(const char *text, int *count)
1509 {
1510 char **lines = NULL;
1511 int lineCount = 0;
1512
1513 if (text != NULL)
1514 {
1515 int textLength = TextLength(text);
1516 lineCount = 1;
1517
1518 // First text scan pass to get required line count
1519 for (int i = 0; i < textLength; i++)
1520 {
1521 if (text[i] == '\n') lineCount++;
1522 }
1523
1524 lines = (char **)RL_CALLOC(lineCount, sizeof(char *));
1525 for (int i = 0, l = 0, lineLen = 0; i <= textLength; i++)
1526 {
1527 if ((text[i] == '\n') || (text[i] == '\0'))
1528 {
1529 lines[l] = (char *)RL_CALLOC(lineLen + 1, 1);
1530 strncpy(lines[l], &text[i - lineLen], lineLen);
1531 lineLen = 0;
1532 l++;
1533 }
1534 else lineLen++;
1535 }
1536 }
1537
1538 *count = lineCount;
1539 return lines;
1540 }
1541
1542 // Unload text lines
1543 void UnloadTextLines(char **lines, int lineCount)
1544 {
1545 for (int i = 0; i < lineCount; i++) RL_FREE(lines[i]);
1546 RL_FREE(lines);
1547 }
1548
1549 // Get text length in bytes, check for \0 character
1550 // NOTE: Alternative: use strlen(text)
1551 unsigned int TextLength(const char *text)
1552 {
1553 unsigned int length = 0;
1554
1555 if (text != NULL)
1556 {
1557 while (text[length] != '\0') length++;
1558 }
1559
1560 return length;
1561 }
1562
1563 // Formatting of text with variables to 'embed'
1564 // WARNING: String returned will expire after this function is called MAX_TEXTFORMAT_BUFFERS times
1565 const char *TextFormat(const char *text, ...)
1566 {
1567 #ifndef MAX_TEXTFORMAT_BUFFERS
1568 #define MAX_TEXTFORMAT_BUFFERS 4 // Maximum number of static buffers for text formatting
1569 #endif
1570
1571 // Create an array of buffers so strings don't expire until MAX_TEXTFORMAT_BUFFERS invocations
1572 static char buffers[MAX_TEXTFORMAT_BUFFERS][MAX_TEXT_BUFFER_LENGTH] = { 0 };
1573 static int index = 0;
1574
1575 char *currentBuffer = buffers[index];
1576 memset(currentBuffer, 0, MAX_TEXT_BUFFER_LENGTH); // Clear buffer before using
1577
1578 if (text != NULL)
1579 {
1580 va_list args;
1581 va_start(args, text);
1582 int requiredByteCount = vsnprintf(currentBuffer, MAX_TEXT_BUFFER_LENGTH, text, args);
1583 va_end(args);
1584
1585 // If requiredByteCount is larger than the MAX_TEXT_BUFFER_LENGTH, then overflow occurred
1586 if (requiredByteCount >= MAX_TEXT_BUFFER_LENGTH)
1587 {
1588 // Inserting "..." at the end of the string to mark as truncated
1589 char *truncBuffer = buffers[index] + MAX_TEXT_BUFFER_LENGTH - 4; // Adding 4 bytes = "...\0"
1590 snprintf(truncBuffer, 4, "...");
1591 }
1592
1593 index += 1; // Move to next buffer for next function call
1594 if (index >= MAX_TEXTFORMAT_BUFFERS) index = 0;
1595 }
1596
1597 return currentBuffer;
1598 }
1599
1600 // Get integer value from text
1601 // NOTE: This function replaces atoi() [stdlib.h]
1602 int TextToInteger(const char *text)
1603 {
1604 int value = 0;
1605 int sign = 1;
1606
1607 if (text != NULL)
1608 {
1609 if ((text[0] == '+') || (text[0] == '-'))
1610 {
1611 if (text[0] == '-') sign = -1;
1612 text++;
1613 }
1614
1615 for (int i = 0; ((text[i] >= '0') && (text[i] <= '9')); i++) value = value*10 + (int)(text[i] - '0');
1616 }
1617
1618 return value*sign;
1619 }
1620
1621 // Get float value from text
1622 // NOTE: This function replaces atof() [stdlib.h]
1623 // WARNING: Only '.' character is understood as decimal point
1624 float TextToFloat(const char *text)
1625 {
1626 float value = 0.0f;
1627 float sign = 1.0f;
1628
1629 if (text != NULL)
1630 {
1631 if ((text[0] == '+') || (text[0] == '-'))
1632 {
1633 if (text[0] == '-') sign = -1.0f;
1634 text++;
1635 }
1636
1637 int i = 0;
1638 for (; ((text[i] >= '0') && (text[i] <= '9')); i++) value = value*10.0f + (float)(text[i] - '0');
1639
1640 if (text[i++] == '.')
1641 {
1642 float divisor = 10.0f;
1643 for (; ((text[i] >= '0') && (text[i] <= '9')); i++)
1644 {
1645 value += ((float)(text[i] - '0'))/divisor;
1646 divisor = divisor*10.0f;
1647 }
1648 }
1649 }
1650
1651 return value*sign;
1652 }
1653
1654 // Copy one string to another, returns bytes copied
1655 // NOTE: Alternative implementation to strcpy(dst, src) from C standard library
1656 int TextCopy(char *dst, const char *src)
1657 {
1658 int bytes = 0;
1659
1660 if ((src != NULL) && (dst != NULL))
1661 {
1662 while (*src != '\0')
1663 {
1664 *dst = *src;
1665 dst++;
1666 src++;
1667
1668 bytes++;
1669 }
1670
1671 *dst = '\0';
1672 }
1673
1674 return bytes;
1675 }
1676
1677 // Check if two text string are equal
1678 // REQUIRES: strcmp()
1679 bool TextIsEqual(const char *text1, const char *text2)
1680 {
1681 bool result = false;
1682
1683 if ((text1 != NULL) && (text2 != NULL))
1684 {
1685 if (strcmp(text1, text2) == 0) result = true;
1686 }
1687
1688 return result;
1689 }
1690
1691 // Get a piece of a text string
1692 const char *TextSubtext(const char *text, int position, int length)
1693 {
1694 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
1695 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
1696
1697 if (text != NULL)
1698 {
1699 int textLength = TextLength(text);
1700
1701 if (position < textLength)
1702 {
1703 int maxLength = textLength - position;
1704 if (length > maxLength) length = maxLength;
1705 if (length >= MAX_TEXT_BUFFER_LENGTH) length = MAX_TEXT_BUFFER_LENGTH - 1;
1706
1707 // NOTE: Alternative: memcpy(buffer, text + position, length)
1708
1709 for (int c = 0; c < length; c++) buffer[c] = text[position + c];
1710
1711 buffer[length] = '\0';
1712 }
1713 }
1714
1715 return buffer;
1716 }
1717
1718 // Remove text spaces, concat words
1719 const char *TextRemoveSpaces(const char *text)
1720 {
1721 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
1722 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
1723
1724 if (text != NULL)
1725 {
1726 // Avoid copying the ' ' characters
1727 for (int i = 0, j = 0; (i < MAX_TEXT_BUFFER_LENGTH - 1) && (text[j] != '\0'); i++)
1728 {
1729 if (text[i] != ' ') { buffer[j] = text[i]; j++; }
1730 }
1731 }
1732
1733 return buffer;
1734 }
1735
1736 // Get text between two strings
1737 char *GetTextBetween(const char *text, const char *begin, const char *end)
1738 {
1739 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
1740 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
1741
1742 int beginIndex = TextFindIndex(text, begin);
1743
1744 if (beginIndex > -1)
1745 {
1746 int beginLen = TextLength(begin);
1747 int endIndex = TextFindIndex(text + beginIndex + beginLen, end);
1748
1749 if (endIndex > -1)
1750 {
1751 endIndex += (beginIndex + beginLen);
1752 int len = (endIndex - beginIndex - beginLen);
1753 if (len < (MAX_TEXT_BUFFER_LENGTH - 1)) strncpy(buffer, text + beginIndex + beginLen, len);
1754 else strncpy(buffer, text + beginIndex + beginLen, MAX_TEXT_BUFFER_LENGTH - 1);
1755 }
1756 }
1757
1758 return buffer;
1759 }
1760
1761 // Replace text string
1762 // REQUIRES: strstr(), strncpy()
1763 // NOTE: Limited text replace functionality, using static string
1764 char *TextReplace(const char *text, const char *search, const char *replacement)
1765 {
1766 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
1767 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
1768
1769 if ((text != NULL) && (search != NULL) && (search[0] != '\0'))
1770 {
1771 if (replacement == NULL) replacement = "";
1772
1773 char *insertPoint = NULL; // Next insert point
1774 char *tempPtr = NULL; // Temp pointer
1775 int textLen = 0; // Text string length
1776 int searchLen = 0; // Search string length of (the string to remove)
1777 int replaceLen = 0; // Replacement length (the string to replace by)
1778 int lastReplacePos = 0; // Distance between next search and end of last replace
1779 int count = 0; // Number of replacements
1780
1781 textLen = TextLength(text);
1782 searchLen = TextLength(search);
1783 replaceLen = TextLength(replacement);
1784
1785 // Count the number of replacements needed
1786 insertPoint = (char *)text;
1787 for (count = 0; (tempPtr = strstr(insertPoint, search)); count++) insertPoint = tempPtr + searchLen;
1788
1789 if ((textLen + count*(replaceLen - searchLen)) < (MAX_TEXT_BUFFER_LENGTH - 1))
1790 {
1791 // TODO: Allow copying data replaced up to maximum buffer size and stop
1792
1793 tempPtr = buffer; // Point to result start
1794
1795 // First time through the loop, all the variable are set correctly from here on,
1796 // - 'temp' points to the end of the result string
1797 // - 'insertPoint' points to the next occurrence of replace in text
1798 // - 'text' points to the remainder of text after "end of replace"
1799 while (count > 0)
1800 {
1801 insertPoint = (char *)strstr(text, search);
1802 lastReplacePos = (int)(insertPoint - text);
1803
1804 memcpy(tempPtr, text, lastReplacePos);
1805 tempPtr += lastReplacePos;
1806
1807 if (replaceLen > 0)
1808 {
1809 memcpy(tempPtr, replacement, replaceLen);
1810 tempPtr += replaceLen;
1811 }
1812
1813 text += (lastReplacePos + searchLen); // Move to next "end of replace"
1814 count--;
1815 }
1816
1817 // Copy remaind text part after replacement to result (pointed by moving temp)
1818 // NOTE: Text pointer internal copy has been updated along the process
1819 strncpy(tempPtr, text, TextLength(text));
1820 }
1821 else TRACELOG(LOG_WARNING, "Text with replacement is longer than internal buffer, use TextReplaceAlloc()");
1822 }
1823
1824 return buffer;
1825 }
1826
1827 // Replace text string
1828 // REQUIRES: strstr(), strncpy()
1829 // WARNING: Allocated memory must be manually freed
1830 char *TextReplaceAlloc(const char *text, const char *search, const char *replacement)
1831 {
1832 char *result = NULL;
1833
1834 if ((text != NULL) && (search != NULL) && (search[0] != '\0'))
1835 {
1836 if (replacement == NULL) replacement = "";
1837
1838 char *insertPoint = NULL; // Next insert point
1839 char *temp = NULL; // Temp pointer
1840 int textLen = 0; // Text string length
1841 int searchLen = 0; // Search string length of (the string to remove)
1842 int replaceLen = 0; // Replacement length (the string to replace by)
1843 int lastReplacePos = 0; // Distance between next search and end of last replace
1844 int count = 0; // Number of replacements
1845
1846 textLen = TextLength(text);
1847 searchLen = TextLength(search);
1848 replaceLen = TextLength(replacement);
1849
1850 // Count the number of replacements needed
1851 insertPoint = (char *)text;
1852 for (count = 0; (temp = strstr(insertPoint, search)); count++) insertPoint = temp + searchLen;
1853
1854 // Allocate returning string and point temp to it
1855 int tempLen = textLen + (replaceLen - searchLen)*count + 1;
1856 temp = result = (char *)RL_CALLOC(tempLen, sizeof(char));
1857
1858 if (result != NULL) // Memory was allocated
1859 {
1860 // First time through the loop, all the variable are set correctly from here on,
1861 // - 'temp' points to the end of the result string
1862 // - 'insertPoint' points to the next occurrence of replace in text
1863 // - 'text' points to the remainder of text after "end of replace"
1864 while (count > 0)
1865 {
1866 insertPoint = (char *)strstr(text, search);
1867 lastReplacePos = (int)(insertPoint - text);
1868
1869 memcpy(temp, text, lastReplacePos);
1870 temp += lastReplacePos;
1871
1872 if (replaceLen > 0)
1873 {
1874 memcpy(temp, replacement, replaceLen);
1875 temp += replaceLen;
1876 }
1877
1878 text += (lastReplacePos + searchLen); // Move to next "end of replace"
1879
1880 count--;
1881 }
1882
1883 // Copy remaind text part after replacement to result (pointed by moving temp)
1884 // NOTE: Text pointer internal copy has been updated along the process
1885 strncpy(temp, text, TextLength(text));
1886 }
1887 }
1888
1889 return result;
1890 }
1891
1892 // Replace text between two specific strings
1893 // REQUIRES: strncpy()
1894 // NOTE: If (replacement == NULL) removes "begin"[ ]"end" text
1895 char *TextReplaceBetween(const char *text, const char *begin, const char *end, const char *replacement)
1896 {
1897 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
1898 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
1899
1900 if ((text != NULL) && (begin != NULL) && (end != NULL))
1901 {
1902 int beginIndex = TextFindIndex(text, begin);
1903
1904 if (beginIndex > -1)
1905 {
1906 int beginLen = TextLength(begin);
1907 int endIndex = TextFindIndex(text + beginIndex + beginLen, end);
1908
1909 if (endIndex > -1)
1910 {
1911 endIndex += (beginIndex + beginLen);
1912
1913 int textLen = TextLength(text);
1914 int replaceLen = (replacement == NULL)? 0 : TextLength(replacement);
1915 //int toreplaceLen = endIndex - beginIndex - beginLen;
1916
1917 strncpy(buffer, text, beginIndex + beginLen); // Copy first text part
1918 if (replacement != NULL) strncpy(buffer + beginIndex + beginLen, replacement, replaceLen); // Copy replacement (if provided)
1919 strncpy(buffer + beginIndex + beginLen + replaceLen, text + endIndex, textLen - endIndex); // Copy end text part
1920 }
1921 }
1922 }
1923
1924 return buffer;
1925 }
1926
1927 // Replace text between two specific strings
1928 // REQUIRES: strncpy()
1929 // NOTE: If (replacement == NULL) remove "begin"[ ]"end" text
1930 // WARNING: Returned string must be freed by user
1931 char *TextReplaceBetweenAlloc(const char *text, const char *begin, const char *end, const char *replacement)
1932 {
1933 char *result = NULL;
1934
1935 if ((text != NULL) && (begin != NULL) && (end != NULL))
1936 {
1937 int beginIndex = TextFindIndex(text, begin);
1938
1939 if (beginIndex > -1)
1940 {
1941 int beginLen = TextLength(begin);
1942 int endIndex = TextFindIndex(text + beginIndex + beginLen, end);
1943
1944 if (endIndex > -1)
1945 {
1946 endIndex += (beginIndex + beginLen);
1947
1948 int textLen = TextLength(text);
1949 int replaceLen = (replacement == NULL)? 0 : TextLength(replacement);
1950 int toreplaceLen = endIndex - beginIndex - beginLen;
1951 result = (char *)RL_CALLOC(textLen + replaceLen - toreplaceLen + 1, sizeof(char));
1952
1953 strncpy(result, text, beginIndex + beginLen); // Copy first text part
1954 if (replacement != NULL) strncpy(result + beginIndex + beginLen, replacement, replaceLen); // Copy replacement (if provided)
1955 strncpy(result + beginIndex + beginLen + replaceLen, text + endIndex, textLen - endIndex); // Copy end text part
1956 }
1957 }
1958 }
1959
1960 return result;
1961 }
1962
1963 // Insert text in a specific position, moves all text forward
1964 // WARNING: Allocated memory must be manually freed
1965 char *TextInsert(const char *text, const char *insert, int position)
1966 {
1967 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
1968 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
1969
1970 if ((text != NULL) && (insert != NULL))
1971 {
1972 int textLen = TextLength(text);
1973 int insertLen = TextLength(insert);
1974
1975 if ((textLen + insertLen) < (MAX_TEXT_BUFFER_LENGTH - 1))
1976 {
1977 // TODO: Allow copying data inserted up to maximum buffer size and stop
1978
1979 for (int i = 0; i < position; i++) buffer[i] = text[i];
1980 for (int i = position; i < insertLen + position; i++) buffer[i] = insert[i - position];
1981 for (int i = (insertLen + position); i < (textLen + insertLen); i++) buffer[i] = text[i];
1982
1983 buffer[textLen + insertLen] = '\0'; // Add EOL
1984 }
1985 else TRACELOG(LOG_WARNING, "Text with inserted string is longer than internal buffer, use TextInserExt()");
1986 }
1987
1988 return buffer;
1989 }
1990
1991 // Insert text in a specific position, moves all text forward
1992 // WARNING: Allocated memory must be manually freed
1993 char *TextInsertAlloc(const char *text, const char *insert, int position)
1994 {
1995 char *result = NULL;
1996
1997 if ((text != NULL) && (insert != NULL))
1998 {
1999 int textLen = TextLength(text);
2000 int insertLen = TextLength(insert);
2001
2002 result = (char *)RL_MALLOC(textLen + insertLen + 1);
2003
2004 for (int i = 0; i < position; i++) result[i] = text[i];
2005 for (int i = position; i < insertLen + position; i++) result[i] = insert[i - position];
2006 for (int i = (insertLen + position); i < (textLen + insertLen); i++) result[i] = text[i];
2007
2008 result[textLen + insertLen] = '\0'; // Add EOL
2009 }
2010
2011 return result;
2012 }
2013
2014 // Join text strings with delimiter
2015 // REQUIRES: memset(), memcpy()
2016 char *TextJoin(char **textList, int count, const char *delimiter)
2017 {
2018 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
2019 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
2020 char *textPtr = buffer;
2021
2022 int totalLength = 0;
2023 int delimiterLen = TextLength(delimiter);
2024
2025 for (int i = 0; i < count; i++)
2026 {
2027 int textLength = TextLength(textList[i]);
2028
2029 // Make sure joined text could fit inside MAX_TEXT_BUFFER_LENGTH
2030 if ((totalLength + textLength) < MAX_TEXT_BUFFER_LENGTH)
2031 {
2032 memcpy(textPtr, textList[i], textLength);
2033 totalLength += textLength;
2034 textPtr += textLength;
2035
2036 if ((delimiterLen > 0) && (i < (count - 1)))
2037 {
2038 memcpy(textPtr, delimiter, delimiterLen);
2039 totalLength += delimiterLen;
2040 textPtr += delimiterLen;
2041 }
2042 }
2043 }
2044
2045 return buffer;
2046 }
2047
2048 // Split string into multiple strings
2049 // REQUIRES: memset()
2050 char **TextSplit(const char *text, char delimiter, int *count)
2051 {
2052 // NOTE: Current implementation returns a copy of the provided string with '\0' (string end delimiter)
2053 // inserted between strings defined by "delimiter" parameter. No memory is dynamically allocated,
2054 // all used memory is static... it has some limitations:
2055 // 1. Maximum number of possible split strings is set by MAX_TEXTSPLIT_COUNT
2056 // 2. Maximum size of text to split is MAX_TEXT_BUFFER_LENGTH
2057
2058 static char *buffers[MAX_TEXTSPLIT_COUNT] = { NULL }; // Pointers to buffer[] text data
2059 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 }; // Text data with '\0' separators
2060 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
2061
2062 buffers[0] = buffer;
2063 int counter = 0;
2064
2065 if (text != NULL)
2066 {
2067 counter = 1;
2068
2069 // Count how many substrings ar found on text and set pointers to every one
2070 for (int i = 0; i < MAX_TEXT_BUFFER_LENGTH; i++)
2071 {
2072 buffer[i] = text[i];
2073 if (buffer[i] == '\0') break;
2074 else if (buffer[i] == delimiter)
2075 {
2076 buffer[i] = '\0'; // Set an end of string at this point
2077 buffers[counter] = buffer + i + 1;
2078 counter++;
2079
2080 if (counter == MAX_TEXTSPLIT_COUNT) break;
2081 }
2082 }
2083 }
2084
2085 *count = counter;
2086 return buffers;
2087 }
2088
2089 // Append text at specific position and move cursor
2090 // WARNING: It's up to the user to make sure appended text does not overflow the buffer!
2091 void TextAppend(char *text, const char *append, int *position)
2092 {
2093 if ((text != NULL) && (append != NULL))
2094 {
2095 TextCopy(text + *position, append);
2096 *position += TextLength(append);
2097 }
2098 }
2099
2100 // Find first text occurrence within a string
2101 // REQUIRES: strstr()
2102 int TextFindIndex(const char *text, const char *search)
2103 {
2104 int position = -1;
2105
2106 if (text != NULL)
2107 {
2108 char *ptr = (char *)strstr(text, search);
2109
2110 if (ptr != NULL) position = (int)(ptr - text);
2111 }
2112
2113 return position;
2114 }
2115
2116 // Get upper case version of provided string
2117 // WARNING: Limited functionality, only basic characters set
2118 // TODO: Support UTF-8 diacritics to upper-case, check codepoints
2119 char *TextToUpper(const char *text)
2120 {
2121 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
2122 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
2123
2124 if (text != NULL)
2125 {
2126 for (int i = 0; (i < MAX_TEXT_BUFFER_LENGTH - 1) && (text[i] != '\0'); i++)
2127 {
2128 if ((text[i] >= 'a') && (text[i] <= 'z')) buffer[i] = text[i] - 32;
2129 else buffer[i] = text[i];
2130 }
2131 }
2132
2133 return buffer;
2134 }
2135
2136 // Get lower case version of provided string
2137 // WARNING: Limited functionality, only basic characters set
2138 char *TextToLower(const char *text)
2139 {
2140 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
2141 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
2142
2143 if (text != NULL)
2144 {
2145 for (int i = 0; (i < MAX_TEXT_BUFFER_LENGTH - 1) && (text[i] != '\0'); i++)
2146 {
2147 if ((text[i] >= 'A') && (text[i] <= 'Z')) buffer[i] = text[i] + 32;
2148 else buffer[i] = text[i];
2149 }
2150 }
2151
2152 return buffer;
2153 }
2154
2155 // Get Pascal case notation version of provided string
2156 // WARNING: Limited functionality, only basic characters set
2157 char *TextToPascal(const char *text)
2158 {
2159 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
2160 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
2161
2162 if (text != NULL)
2163 {
2164 // Upper case first character
2165 if ((text[0] >= 'a') && (text[0] <= 'z')) buffer[0] = text[0] - 32;
2166 else buffer[0] = text[0];
2167
2168 // Check for next separator to upper case another character
2169 for (int i = 1, j = 1; (i < MAX_TEXT_BUFFER_LENGTH - 1) && (text[j] != '\0'); i++, j++)
2170 {
2171 if (text[j] != '_') buffer[i] = text[j];
2172 else
2173 {
2174 j++;
2175 if ((text[j] >= 'a') && (text[j] <= 'z')) buffer[i] = text[j] - 32;
2176 else if ((text[j] >= '0') && (text[j] <= '9')) buffer[i] = text[j];
2177 }
2178 }
2179 }
2180
2181 return buffer;
2182 }
2183
2184 // Get snake case notation version of provided string
2185 // WARNING: Limited functionality, only basic characters set
2186 char *TextToSnake(const char *text)
2187 {
2188 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
2189 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
2190
2191 if (text != NULL)
2192 {
2193 // Check for next separator to upper case another character
2194 for (int i = 0, j = 0; (i < MAX_TEXT_BUFFER_LENGTH - 1) && (text[j] != '\0'); i++, j++)
2195 {
2196 if ((text[j] >= 'A') && (text[j] <= 'Z'))
2197 {
2198 if (i >= 1)
2199 {
2200 buffer[i] = '_';
2201 i++;
2202 }
2203 buffer[i] = text[j] + 32;
2204 }
2205 else buffer[i] = text[j];
2206 }
2207 }
2208
2209 return buffer;
2210 }
2211
2212 // Get Camel case notation version of provided string
2213 // WARNING: Limited functionality, only basic characters set
2214 char *TextToCamel(const char *text)
2215 {
2216 static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
2217 memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
2218
2219 if (text != NULL)
2220 {
2221 // Lower case first character
2222 if ((text[0] >= 'A') && (text[0] <= 'Z')) buffer[0] = text[0] + 32;
2223 else buffer[0] = text[0];
2224
2225 // Check for next separator to upper case another character
2226 for (int i = 1, j = 1; (i < MAX_TEXT_BUFFER_LENGTH - 1) && (text[j] != '\0'); i++, j++)
2227 {
2228 if (text[j] != '_') buffer[i] = text[j];
2229 else
2230 {
2231 j++;
2232 if ((text[j] >= 'a') && (text[j] <= 'z')) buffer[i] = text[j] - 32;
2233 }
2234 }
2235 }
2236
2237 return buffer;
2238 }
2239
2240 // Encode text codepoint into UTF-8 text
2241 // REQUIRES: memcpy()
2242 // WARNING: Allocated memory must be manually freed
2243 char *LoadUTF8(const int *codepoints, int length)
2244 {
2245 char *text = NULL;
2246
2247 if ((codepoints != NULL) && (length > 0))
2248 {
2249 // Allocate enough memory to fit all possible codepoints
2250 // NOTE: 5 bytes for every codepoint should be enough
2251 text = (char *)RL_CALLOC(length*5, 1);
2252 const char *utf8 = NULL;
2253 int size = 0;
2254
2255 for (int i = 0, bytes = 0; i < length; i++)
2256 {
2257 utf8 = CodepointToUTF8(codepoints[i], &bytes);
2258 memcpy(text + size, utf8, bytes);
2259 size += bytes;
2260 }
2261
2262 // Create second buffer and copy data manually to it
2263 char *temp = (char *)RL_CALLOC(size + 1, 1);
2264 memcpy(temp, text, size);
2265 RL_FREE(text);
2266 text = temp;
2267 }
2268
2269 return text;
2270 }
2271
2272 // Unload UTF-8 text encoded from codepoints array
2273 void UnloadUTF8(char *text)
2274 {
2275 RL_FREE(text);
2276 }
2277
2278 // Load all codepoints from a UTF-8 text string, codepoints count returned by parameter
2279 int *LoadCodepoints(const char *text, int *count)
2280 {
2281 int *codepoints = NULL;
2282 int codepointCount = 0;
2283
2284 if (text != NULL)
2285 {
2286 int textLength = TextLength(text);
2287
2288 // Allocate a big enough buffer to store as many codepoints as text bytes
2289 codepoints = (int *)RL_CALLOC(textLength, sizeof(int));
2290
2291 int codepointSize = 0;
2292 for (int i = 0; i < textLength; codepointCount++)
2293 {
2294 codepoints[codepointCount] = GetCodepointNext(text + i, &codepointSize);
2295 i += codepointSize;
2296 }
2297
2298 // Create second buffer and copy data manually to it
2299 int *temp = (int *)RL_CALLOC(codepointCount, sizeof(int));
2300 for (int i = 0; i < codepointCount; i++) temp[i] = codepoints[i];
2301 RL_FREE(codepoints);
2302 codepoints = temp;
2303 }
2304
2305 *count = codepointCount;
2306 return codepoints;
2307 }
2308
2309 // Unload codepoints data from memory
2310 void UnloadCodepoints(int *codepoints)
2311 {
2312 RL_FREE(codepoints);
2313 }
2314
2315 // Get total number of characters(codepoints) in a UTF-8 encoded text, until '\0' is found
2316 // NOTE: If an invalid UTF-8 sequence is encountered a '?'(0x3f) codepoint is counted instead
2317 int GetCodepointCount(const char *text)
2318 {
2319 unsigned int length = 0;
2320 const char *ptr = text;
2321
2322 if (ptr != NULL)
2323 {
2324 while (*ptr != '\0')
2325 {
2326 int next = 0;
2327 GetCodepointNext(ptr, &next);
2328 ptr += next;
2329 length++;
2330 }
2331 }
2332
2333 return length;
2334 }
2335
2336 // Encode codepoint into utf8 text (char array length returned as parameter)
2337 // NOTE: It uses a static array to store UTF-8 bytes
2338 const char *CodepointToUTF8(int codepoint, int *utf8Size)
2339 {
2340 static char utf8[6] = { 0 };
2341 memset(utf8, 0, 6); // Clear static array
2342 int size = 0; // Byte size of codepoint
2343
2344 if (codepoint <= 0x7f)
2345 {
2346 utf8[0] = (char)codepoint;
2347 size = 1;
2348 }
2349 else if (codepoint <= 0x7ff)
2350 {
2351 utf8[0] = (char)(((codepoint >> 6) & 0x1f) | 0xc0);
2352 utf8[1] = (char)((codepoint & 0x3f) | 0x80);
2353 size = 2;
2354 }
2355 else if (codepoint <= 0xffff)
2356 {
2357 utf8[0] = (char)(((codepoint >> 12) & 0x0f) | 0xe0);
2358 utf8[1] = (char)(((codepoint >> 6) & 0x3f) | 0x80);
2359 utf8[2] = (char)((codepoint & 0x3f) | 0x80);
2360 size = 3;
2361 }
2362 else if (codepoint <= 0x10ffff)
2363 {
2364 utf8[0] = (char)(((codepoint >> 18) & 0x07) | 0xf0);
2365 utf8[1] = (char)(((codepoint >> 12) & 0x3f) | 0x80);
2366 utf8[2] = (char)(((codepoint >> 6) & 0x3f) | 0x80);
2367 utf8[3] = (char)((codepoint & 0x3f) | 0x80);
2368 size = 4;
2369 }
2370
2371 *utf8Size = size;
2372
2373 return utf8;
2374 }
2375
2376 // Get next codepoint in a UTF-8 encoded text, scanning until '\0' is found
2377 // When an invalid UTF-8 byte is encountered, exit as soon as possible and a '?'(0x3f) codepoint is returned
2378 // Total number of bytes processed are returned as a parameter
2379 // NOTE: The standard says U+FFFD should be returned in case of errors
2380 // but that character is not supported by the default font in raylib
2381 int GetCodepoint(const char *text, int *codepointSize)
2382 {
2383 /*
2384 UTF-8 specs from https://www.ietf.org/rfc/rfc3629.txt
2385
2386 Char. number range | UTF-8 octet sequence
2387 (hexadecimal) | (binary)
2388 --------------------+---------------------------------------------
2389 0000 0000-0000 007F | 0xxxxxxx
2390 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
2391 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
2392 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
2393 */
2394
2395 int codepoint = 0x3f; // Codepoint (defaults to '?')
2396 *codepointSize = 1;
2397 if (text == NULL) return codepoint;
2398
2399 // NOTE: On decoding errors, return as soon as possible
2400 int octet = (unsigned char)(text[0]); // The first UTF8 octet
2401
2402 if (octet <= 0x7f)
2403 {
2404 // Only one octet (ASCII range x00-7F)
2405 codepoint = text[0];
2406 }
2407 else if ((octet & 0xe0) == 0xc0)
2408 {
2409 // Two octets
2410
2411 // [0]xC2-DF [1]UTF8-tail(x80-BF)
2412 unsigned char octet1 = text[1];
2413
2414 if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *codepointSize = 2; return codepoint; } // Unexpected sequence
2415
2416 if ((octet >= 0xc2) && (octet <= 0xdf))
2417 {
2418 codepoint = ((octet & 0x1f) << 6) | (octet1 & 0x3f);
2419 *codepointSize = 2;
2420 }
2421 }
2422 else if ((octet & 0xf0) == 0xe0)
2423 {
2424 // Three octets
2425 unsigned char octet1 = text[1];
2426 unsigned char octet2 = '\0';
2427
2428 if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *codepointSize = 2; return codepoint; } // Unexpected sequence
2429
2430 octet2 = text[2];
2431
2432 if ((octet2 == '\0') || ((octet2 >> 6) != 2)) { *codepointSize = 3; return codepoint; } // Unexpected sequence
2433
2434 // [0]xE0 [1]xA0-BF [2]UTF8-tail(x80-BF)
2435 // [0]xE1-EC [1]UTF8-tail [2]UTF8-tail(x80-BF)
2436 // [0]xED [1]x80-9F [2]UTF8-tail(x80-BF)
2437 // [0]xEE-EF [1]UTF8-tail [2]UTF8-tail(x80-BF)
2438
2439 if (((octet == 0xe0) && !((octet1 >= 0xa0) && (octet1 <= 0xbf))) ||
2440 ((octet == 0xed) && !((octet1 >= 0x80) && (octet1 <= 0x9f)))) { *codepointSize = 2; return codepoint; }
2441
2442 if ((octet >= 0xe0) && (octet <= 0xef))
2443 {
2444 codepoint = ((octet & 0xf) << 12) | ((octet1 & 0x3f) << 6) | (octet2 & 0x3f);
2445 *codepointSize = 3;
2446 }
2447 }
2448 else if ((octet & 0xf8) == 0xf0)
2449 {
2450 // Four octets
2451 if (octet > 0xf4) return codepoint;
2452
2453 unsigned char octet1 = text[1];
2454 unsigned char octet2 = '\0';
2455 unsigned char octet3 = '\0';
2456
2457 if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *codepointSize = 2; return codepoint; } // Unexpected sequence
2458
2459 octet2 = text[2];
2460
2461 if ((octet2 == '\0') || ((octet2 >> 6) != 2)) { *codepointSize = 3; return codepoint; } // Unexpected sequence
2462
2463 octet3 = text[3];
2464
2465 if ((octet3 == '\0') || ((octet3 >> 6) != 2)) { *codepointSize = 4; return codepoint; } // Unexpected sequence
2466
2467 // [0]xF0 [1]x90-BF [2]UTF8-tail [3]UTF8-tail
2468 // [0]xF1-F3 [1]UTF8-tail [2]UTF8-tail [3]UTF8-tail
2469 // [0]xF4 [1]x80-8F [2]UTF8-tail [3]UTF8-tail
2470
2471 if (((octet == 0xf0) && !((octet1 >= 0x90) && (octet1 <= 0xbf))) ||
2472 ((octet == 0xf4) && !((octet1 >= 0x80) && (octet1 <= 0x8f)))) { *codepointSize = 2; return codepoint; } // Unexpected sequence
2473
2474 if (octet >= 0xf0)
2475 {
2476 codepoint = ((octet & 0x7) << 18) | ((octet1 & 0x3f) << 12) | ((octet2 & 0x3f) << 6) | (octet3 & 0x3f);
2477 *codepointSize = 4;
2478 }
2479 }
2480
2481 if (codepoint > 0x10ffff) codepoint = 0x3f; // Codepoints after U+10ffff are invalid
2482
2483 return codepoint;
2484 }
2485
2486 // Get next codepoint in a byte sequence and bytes processed
2487 int GetCodepointNext(const char *text, int *codepointSize)
2488 {
2489 const char *ptr = text;
2490 int codepoint = 0x3f; // Codepoint (defaults to '?')
2491 *codepointSize = 1;
2492 if (text == NULL) return codepoint;
2493
2494 // Get current codepoint and bytes processed
2495 if (0xf0 == (0xf8 & ptr[0]))
2496 {
2497 // 4 byte UTF-8 codepoint
2498 if (((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80) || ((ptr[3] & 0xC0) ^ 0x80)) { return codepoint; } // 10xxxxxx checks
2499 codepoint = ((0x07 & ptr[0]) << 18) | ((0x3f & ptr[1]) << 12) | ((0x3f & ptr[2]) << 6) | (0x3f & ptr[3]);
2500 *codepointSize = 4;
2501 }
2502 else if (0xe0 == (0xf0 & ptr[0]))
2503 {
2504 // 3 byte UTF-8 codepoint */
2505 if (((ptr[1] & 0xC0) ^ 0x80) || ((ptr[2] & 0xC0) ^ 0x80)) { return codepoint; } // 10xxxxxx checks
2506 codepoint = ((0x0f & ptr[0]) << 12) | ((0x3f & ptr[1]) << 6) | (0x3f & ptr[2]);
2507 *codepointSize = 3;
2508 }
2509 else if (0xc0 == (0xe0 & ptr[0]))
2510 {
2511 // 2 byte UTF-8 codepoint
2512 if ((ptr[1] & 0xC0) ^ 0x80) { return codepoint; } // 10xxxxxx checks
2513 codepoint = ((0x1f & ptr[0]) << 6) | (0x3f & ptr[1]);
2514 *codepointSize = 2;
2515 }
2516 else if (0x00 == (0x80 & ptr[0]))
2517 {
2518 // 1 byte UTF-8 codepoint
2519 codepoint = ptr[0];
2520 *codepointSize = 1;
2521 }
2522
2523 return codepoint;
2524 }
2525
2526 // Get previous codepoint in a byte sequence and bytes processed
2527 int GetCodepointPrevious(const char *text, int *codepointSize)
2528 {
2529 const char *ptr = text;
2530 int codepoint = 0x3f; // Codepoint (defaults to '?')
2531 *codepointSize = 1;
2532 if (text == NULL) return codepoint;
2533
2534 // Move to previous codepoint
2535 do ptr--;
2536 while (((0x80 & ptr[0]) != 0) && ((0xc0 & ptr[0]) == 0x80));
2537
2538 int cpSize = 0;
2539 codepoint = GetCodepointNext(ptr, &cpSize);
2540 if (codepoint != 0) *codepointSize = cpSize;
2541
2542 return codepoint;
2543 }
2544
2545 //----------------------------------------------------------------------------------
2546 // Module Internal Functions Definition
2547 //----------------------------------------------------------------------------------
2548 #if SUPPORT_FILEFORMAT_FNT || SUPPORT_FILEFORMAT_BDF
2549 // Read a line from memory
2550 // REQUIRES: memcpy()
2551 // NOTE: Returns the number of bytes read
2552 static int GetLine(const char *origin, char *buffer, int maxLength)
2553 {
2554 int count = 0;
2555 for (; count < maxLength - 1; count++) if (origin[count] == '\n') break;
2556 memcpy(buffer, origin, count);
2557 buffer[count] = '\0';
2558 return count;
2559 }
2560 #endif
2561
2562 #if SUPPORT_FILEFORMAT_FNT
2563 // Load a BMFont file (AngelCode font file)
2564 // REQUIRES: strstr(), sscanf(), strrchr(), memcpy()
2565 static Font LoadBMFont(const char *fileName)
2566 {
2567 #define MAX_BUFFER_SIZE 256
2568 #define MAX_FONT_IMAGE_PAGES 8
2569
2570 Font font = { 0 };
2571
2572 char buffer[MAX_BUFFER_SIZE] = { 0 };
2573 char *searchPoint = NULL;
2574
2575 int fontSize = 0;
2576 int glyphCount = 0;
2577
2578 int imWidth = 0;
2579 int imHeight = 0;
2580 int pageCount = 1;
2581 char imFileName[MAX_FONT_IMAGE_PAGES][129] = { 0 };
2582
2583 int base = 0; // Useless data
2584 int readBytes = 0; // Data bytes read
2585 int readVars = 0; // Variables filled by sscanf()
2586
2587 char *fileText = LoadFileText(fileName);
2588
2589 if (fileText == NULL) return font;
2590
2591 char *fileTextPtr = fileText;
2592
2593 // NOTE: Skip first line, it contains no useful information
2594 readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE);
2595 fileTextPtr += (readBytes + 1);
2596
2597 // Read line data
2598 readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE);
2599 searchPoint = strstr(buffer, "lineHeight");
2600 readVars = sscanf(searchPoint, "lineHeight=%i base=%i scaleW=%i scaleH=%i pages=%i", &fontSize, &base, &imWidth, &imHeight, &pageCount);
2601 fileTextPtr += (readBytes + 1);
2602
2603 if (readVars < 4) { UnloadFileText(fileText); return font; } // Some data not available, file malformed
2604
2605 if (pageCount > MAX_FONT_IMAGE_PAGES)
2606 {
2607 TRACELOG(LOG_WARNING, "FONT: [%s] Font defines more pages than supported: %i/%i", fileName, pageCount, MAX_FONT_IMAGE_PAGES);
2608 pageCount = MAX_FONT_IMAGE_PAGES;
2609 }
2610
2611 for (int i = 0; i < pageCount; i++)
2612 {
2613 readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE);
2614 searchPoint = strstr(buffer, "file");
2615 readVars = sscanf(searchPoint, "file=\"%128[^\"]\"", imFileName[i]);
2616 fileTextPtr += (readBytes + 1);
2617
2618 if (readVars < 1) { UnloadFileText(fileText); return font; } // No fileName read
2619 }
2620
2621 readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE);
2622 searchPoint = strstr(buffer, "count");
2623 readVars = sscanf(searchPoint, "count=%i", &glyphCount);
2624 fileTextPtr += (readBytes + 1);
2625
2626 if (readVars < 1) { UnloadFileText(fileText); return font; } // No glyphCount read
2627
2628 // Load all required images for further compose
2629 Image *imFonts = (Image *)RL_CALLOC(pageCount, sizeof(Image)); // Font atlases, multiple images
2630
2631 for (int i = 0; i < pageCount; i++)
2632 {
2633 imFonts[i] = LoadImage(TextFormat("%s/%s", GetDirectoryPath(fileName), imFileName[i]));
2634
2635 if (imFonts[i].format == PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)
2636 {
2637 // Convert image to GRAYSCALE + ALPHA, using the mask as the alpha channel
2638 Image imFontAlpha = {
2639 .data = RL_CALLOC(imFonts[i].width*imFonts[i].height, 2),
2640 .width = imFonts[i].width,
2641 .height = imFonts[i].height,
2642 .mipmaps = 1,
2643 .format = PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA
2644 };
2645
2646 for (int p = 0, pi = 0; p < (imFonts[i].width*imFonts[i].height*2); p += 2, pi++)
2647 {
2648 ((unsigned char *)(imFontAlpha.data))[p] = 0xff;
2649 ((unsigned char *)(imFontAlpha.data))[p + 1] = ((unsigned char *)imFonts[i].data)[pi];
2650 }
2651
2652 UnloadImage(imFonts[i]);
2653 imFonts[i] = imFontAlpha;
2654 }
2655 }
2656
2657 Image fullFont = imFonts[0];
2658 for (int i = 1; i < pageCount; i++) UnloadImage(imFonts[i]);
2659
2660 // If multiple atlas, then merge atlas
2661 // NOTE: WARNING: This process could be really slow!
2662 if (pageCount > 1)
2663 {
2664 // Resize font atlas to draw additional images
2665 ImageResizeCanvas(&fullFont, imWidth, imHeight*pageCount, 0, 0, BLACK);
2666
2667 for (int i = 1; i < pageCount; i++)
2668 {
2669 Rectangle srcRec = { 0.0f, 0.0f, (float)imWidth, (float)imHeight };
2670 Rectangle destRec = { 0.0f, (float)imHeight*(float)i, (float)imWidth, (float)imHeight };
2671 ImageDraw(&fullFont, imFonts[i], srcRec, destRec, WHITE);
2672 }
2673 }
2674
2675 RL_FREE(imFonts);
2676
2677 font.texture = LoadTextureFromImage(fullFont);
2678
2679 // Fill font characters info data
2680 font.baseSize = fontSize;
2681 font.glyphCount = glyphCount;
2682 font.glyphPadding = 0;
2683 font.glyphs = (GlyphInfo *)RL_MALLOC(glyphCount*sizeof(GlyphInfo));
2684 font.recs = (Rectangle *)RL_MALLOC(glyphCount*sizeof(Rectangle));
2685
2686 int charId = 0;
2687 int charX = 0;
2688 int charY = 0;
2689 int charWidth = 0;
2690 int charHeight = 0;
2691 int charOffsetX = 0;
2692 int charOffsetY = 0;
2693 int charAdvanceX = 0;
2694 int pageID = 0;
2695
2696 for (int i = 0; i < glyphCount; i++)
2697 {
2698 readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE);
2699 readVars = sscanf(buffer, "char id=%i x=%i y=%i width=%i height=%i xoffset=%i yoffset=%i xadvance=%i page=%i",
2700 &charId, &charX, &charY, &charWidth, &charHeight, &charOffsetX, &charOffsetY, &charAdvanceX, &pageID);
2701 fileTextPtr += (readBytes + 1);
2702
2703 if (readVars == 9) // Make sure all char data has been properly read
2704 {
2705 // Get character rectangle in the font atlas texture
2706 font.recs[i] = (Rectangle){ (float)charX, (float)charY + (float)imHeight*pageID, (float)charWidth, (float)charHeight };
2707
2708 // Save data properly in sprite font
2709 font.glyphs[i].value = charId;
2710 font.glyphs[i].offsetX = charOffsetX;
2711 font.glyphs[i].offsetY = charOffsetY;
2712 font.glyphs[i].advanceX = charAdvanceX;
2713
2714 // Fill character image data from full font data
2715 font.glyphs[i].image = ImageFromImage(fullFont, font.recs[i]);
2716 }
2717 else
2718 {
2719 font.glyphs[i].image = GenImageColor((int)font.recs[i].width, (int)font.recs[i].height, BLACK);
2720 TRACELOG(LOG_WARNING, "FONT: [%s] Some characters data not correctly provided", fileName);
2721 }
2722 }
2723
2724 UnloadImage(fullFont);
2725 UnloadFileText(fileText);
2726
2727 if (font.texture.id == 0)
2728 {
2729 UnloadFont(font);
2730 font = GetFontDefault();
2731 TRACELOG(LOG_WARNING, "FONT: [%s] Failed to load texture, reverted to default font", fileName);
2732 }
2733 else TRACELOG(LOG_INFO, "FONT: [%s] Font loaded successfully (%i glyphs)", fileName, font.glyphCount);
2734
2735 return font;
2736 }
2737 #endif
2738
2739 #if SUPPORT_FILEFORMAT_BDF
2740 // Convert hexadecimal to decimal (single digit)
2741 static unsigned char HexToInt(char hex)
2742 {
2743 if ((hex >= '0') && (hex <= '9')) return hex - '0';
2744 else if ((hex >= 'a') && (hex <= 'f')) return hex - 'a' + 10;
2745 else if ((hex >= 'A') && (hex <= 'F')) return hex - 'A' + 10;
2746 else return 0;
2747 }
2748
2749 // Load font data for further use
2750 // NOTE: Requires BDF font memory data
2751 static GlyphInfo *LoadFontDataBDF(const unsigned char *fileData, int dataSize, const int *codepoints, int codepointCount, int *outFontSize)
2752 {
2753 #define MAX_BUFFER_SIZE 256
2754
2755 char buffer[MAX_BUFFER_SIZE] = { 0 };
2756
2757 GlyphInfo *glyphs = NULL;
2758 bool internalCodepoints = false;
2759
2760 int totalReadBytes = 0; // Data bytes read (total)
2761 int readBytes = 0; // Data bytes read (line)
2762 int readVars = 0; // Variables filled by sscanf()
2763
2764 const char *fileText = (const char *)fileData;
2765 const char *fileTextPtr = fileText;
2766
2767 bool fontMalformed = false; // Is the font malformed
2768 bool fontStarted = false; // Has font started (STARTFONT)
2769 int fontBBw = 0; // Font base character bounding box width
2770 int fontBBh = 0; // Font base character bounding box height
2771 int fontBBxoff0 = 0; // Font base character bounding box X0 offset
2772 int fontBByoff0 = 0; // Font base character bounding box Y0 offset
2773 int fontAscent = 0; // Font ascent
2774
2775 bool charStarted = false; // Has character started (STARTCHAR)
2776 bool charBitmapStarted = false; // Has bitmap data started (BITMAP)
2777 int charBitmapNextRow = 0; // Y position for the next row of bitmap data
2778 int charEncoding = -1; // The unicode value of the character (-1 if not set)
2779 int charBBw = 0; // Character bounding box width
2780 int charBBh = 0; // Character bounding box height
2781 int charBBxoff0 = 0; // Character bounding box X0 offset
2782 int charBByoff0 = 0; // Character bounding box Y0 offset
2783 int charDWidthX = 0; // Character advance X
2784 int charDWidthY = 0; // Character advance Y (unused)
2785
2786 int *requiredCodepoints = (int *)RL_MALLOC(codepointCount*sizeof(int));
2787
2788 if (fileData == NULL) return glyphs;
2789
2790 // In case no chars count provided, default to 95
2791 codepointCount = (codepointCount > 0)? codepointCount : 95;
2792
2793 if (codepoints == NULL)
2794 {
2795 // Fill internal codepoints array in case not provided externally
2796 // NOTE: By default, filling glyph count consecutively, starting at 32 (Space)
2797 for (int i = 0; i < codepointCount; i++) requiredCodepoints[i] = i + 32;
2798 internalCodepoints = true;
2799 }
2800 else
2801 {
2802 for (int i = 0; i < codepointCount; i++) requiredCodepoints[i] = codepoints[i];
2803 }
2804
2805 glyphs = (GlyphInfo *)RL_CALLOC(codepointCount, sizeof(GlyphInfo));
2806
2807 while (totalReadBytes <= dataSize)
2808 {
2809 readBytes = GetLine(fileTextPtr, buffer, MAX_BUFFER_SIZE);
2810 totalReadBytes += (readBytes + 1);
2811 fileTextPtr += (readBytes + 1);
2812
2813 // Line: COMMENT
2814 if (strstr(buffer, "COMMENT") != NULL) continue; // Ignore line
2815
2816 if (charStarted)
2817 {
2818 // Line: ENDCHAR
2819 if (strstr(buffer, "ENDCHAR") != NULL)
2820 {
2821 charStarted = false;
2822 continue;
2823 }
2824
2825 if (charBitmapStarted)
2826 {
2827 if (glyphs != NULL)
2828 {
2829 int pixelY = charBitmapNextRow++;
2830
2831 if (pixelY >= glyphs->image.height) break;
2832
2833 for (int x = 0; x < readBytes; x++)
2834 {
2835 unsigned char byte = HexToInt(buffer[x]);
2836
2837 for (int bitX = 0; bitX < 4; bitX++)
2838 {
2839 int pixelX = ((x*4) + bitX);
2840
2841 if (pixelX >= glyphs->image.width) break;
2842
2843 if ((byte & (8 >> bitX)) > 0) ((unsigned char *)glyphs->image.data)[(pixelY*glyphs->image.width) + pixelX] = 255;
2844 }
2845 }
2846 }
2847 continue;
2848 }
2849
2850 // Line: ENCODING
2851 if (strstr(buffer, "ENCODING") != NULL)
2852 {
2853 readVars = sscanf(buffer, "ENCODING %i", &charEncoding);
2854 continue;
2855 }
2856
2857 // Line: BBX
2858 if (strstr(buffer, "BBX") != NULL)
2859 {
2860 readVars = sscanf(buffer, "BBX %i %i %i %i", &charBBw, &charBBh, &charBBxoff0, &charBByoff0);
2861 continue;
2862 }
2863
2864 // Line: DWIDTH
2865 if (strstr(buffer, "DWIDTH") != NULL)
2866 {
2867 readVars = sscanf(buffer, "DWIDTH %i %i", &charDWidthX, &charDWidthY);
2868 continue;
2869 }
2870
2871 // Line: BITMAP
2872 if (strstr(buffer, "BITMAP") != NULL)
2873 {
2874 // Search for glyph index in codepoints
2875 glyphs = NULL;
2876
2877 for (int index = 0; index < codepointCount; index++)
2878 {
2879 if (requiredCodepoints[index] == charEncoding)
2880 {
2881 glyphs = &glyphs[index];
2882 break;
2883 }
2884 }
2885
2886 // Init glyph info
2887 if (glyphs != NULL)
2888 {
2889 glyphs->value = charEncoding;
2890 glyphs->offsetX = charBBxoff0 + fontBByoff0;
2891 glyphs->offsetY = fontBBh - (charBBh + charBByoff0 + fontBByoff0 + fontAscent);
2892 glyphs->advanceX = charDWidthX;
2893
2894 glyphs->image.data = RL_CALLOC(charBBw*charBBh, 1);
2895 glyphs->image.width = charBBw;
2896 glyphs->image.height = charBBh;
2897 glyphs->image.mipmaps = 1;
2898 glyphs->image.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE;
2899 }
2900
2901 charBitmapStarted = true;
2902 charBitmapNextRow = 0;
2903
2904 continue;
2905 }
2906 }
2907 else if (fontStarted)
2908 {
2909 // Line: ENDFONT
2910 if (strstr(buffer, "ENDFONT") != NULL)
2911 {
2912 fontStarted = false;
2913 break;
2914 }
2915
2916 // Line: SIZE
2917 if (strstr(buffer, "SIZE") != NULL)
2918 {
2919 if (outFontSize != NULL) readVars = sscanf(buffer, "SIZE %i", outFontSize);
2920 continue;
2921 }
2922
2923 // PIXEL_SIZE
2924 if (strstr(buffer, "PIXEL_SIZE") != NULL)
2925 {
2926 if (outFontSize != NULL) readVars = sscanf(buffer, "PIXEL_SIZE %i", outFontSize);
2927 continue;
2928 }
2929
2930 // FONTBOUNDINGBOX
2931 if (strstr(buffer, "FONTBOUNDINGBOX") != NULL)
2932 {
2933 readVars = sscanf(buffer, "FONTBOUNDINGBOX %i %i %i %i", &fontBBw, &fontBBh, &fontBBxoff0, &fontBByoff0);
2934 continue;
2935 }
2936
2937 // FONT_ASCENT
2938 if (strstr(buffer, "FONT_ASCENT") != NULL)
2939 {
2940 readVars = sscanf(buffer, "FONT_ASCENT %i", &fontAscent);
2941 continue;
2942 }
2943
2944 // STARTCHAR
2945 if (strstr(buffer, "STARTCHAR") != NULL)
2946 {
2947 charStarted = true;
2948 charEncoding = -1;
2949 glyphs = NULL;
2950 charBBw = 0;
2951 charBBh = 0;
2952 charBBxoff0 = 0;
2953 charBByoff0 = 0;
2954 charDWidthX = 0;
2955 charDWidthY = 0;
2956 glyphs = NULL;
2957 charBitmapStarted = false;
2958 charBitmapNextRow = 0;
2959 continue;
2960 }
2961 }
2962 else
2963 {
2964 // STARTFONT
2965 if (strstr(buffer, "STARTFONT") != NULL)
2966 {
2967 if (fontStarted)
2968 {
2969 fontMalformed = true;
2970 break;
2971 }
2972 else
2973 {
2974 fontStarted = true;
2975 continue;
2976 }
2977 }
2978 }
2979 }
2980
2981 RL_FREE(requiredCodepoints);
2982
2983 if (fontMalformed)
2984 {
2985 RL_FREE(glyphs);
2986 glyphs = NULL;
2987 }
2988
2989 return glyphs;
2990 }
2991 #endif // SUPPORT_FILEFORMAT_BDF
2992
2993 #endif // SUPPORT_MODULE_RTEXT