text.c 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786
  1. /**********************************************************************************************
  2. *
  3. * raylib.text - Basic functions to load Fonts and draw Text
  4. *
  5. * CONFIGURATION:
  6. *
  7. * #define SUPPORT_FILEFORMAT_FNT
  8. * #define SUPPORT_FILEFORMAT_TTF
  9. * Selected desired fileformats to be supported for loading. Some of those formats are
  10. * supported by default, to remove support, just comment unrequired #define in this module
  11. *
  12. * #define SUPPORT_DEFAULT_FONT
  13. * Load default raylib font on initialization to be used by DrawText() and MeasureText().
  14. * If no default font loaded, DrawTextEx() and MeasureTextEx() are required.
  15. *
  16. * #define TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH
  17. * TextSplit() function static buffer max size
  18. *
  19. * #define TEXTSPLIT_MAX_SUBSTRINGS_COUNT
  20. * TextSplit() function static substrings pointers array (pointing to static buffer)
  21. *
  22. *
  23. * DEPENDENCIES:
  24. * stb_truetype - Load TTF file and rasterize characters data
  25. * stb_rect_pack - Rectangles packing algorythms, required for font atlas generation
  26. *
  27. *
  28. * LICENSE: zlib/libpng
  29. *
  30. * Copyright (c) 2013-2020 Ramon Santamaria (@raysan5)
  31. *
  32. * This software is provided "as-is", without any express or implied warranty. In no event
  33. * will the authors be held liable for any damages arising from the use of this software.
  34. *
  35. * Permission is granted to anyone to use this software for any purpose, including commercial
  36. * applications, and to alter it and redistribute it freely, subject to the following restrictions:
  37. *
  38. * 1. The origin of this software must not be misrepresented; you must not claim that you
  39. * wrote the original software. If you use this software in a product, an acknowledgment
  40. * in the product documentation would be appreciated but is not required.
  41. *
  42. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented
  43. * as being the original software.
  44. *
  45. * 3. This notice may not be removed or altered from any source distribution.
  46. *
  47. **********************************************************************************************/
  48. #include "raylib.h" // Declares module functions
  49. // Check if config flags have been externally provided on compilation line
  50. #if !defined(EXTERNAL_CONFIG_FLAGS)
  51. #include "config.h" // Defines module configuration flags
  52. #endif
  53. #include <stdlib.h> // Required for: malloc(), free()
  54. #include <string.h> // Required for: strlen()
  55. #include <stdarg.h> // Required for: va_list, va_start(), vsprintf(), va_end()
  56. #include <stdio.h> // Required for: FILE, fopen(), fclose(), fscanf(), feof(), rewind(), fgets()
  57. #include <ctype.h> // Required for: toupper(), tolower()
  58. #include "utils.h" // Required for: fopen() Android mapping
  59. #if defined(SUPPORT_FILEFORMAT_TTF)
  60. #define STB_RECT_PACK_IMPLEMENTATION
  61. #include "external/stb_rect_pack.h" // Required for: ttf font rectangles packaging
  62. #define STBTT_STATIC
  63. #define STB_TRUETYPE_IMPLEMENTATION
  64. #include "external/stb_truetype.h" // Required for: ttf font data reading
  65. #endif
  66. //----------------------------------------------------------------------------------
  67. // Defines and Macros
  68. //----------------------------------------------------------------------------------
  69. #define MAX_TEXT_BUFFER_LENGTH 1024 // Size of internal static buffers used on some functions:
  70. // TextFormat(), TextSubtext(), TextToUpper(), TextToLower(), TextToPascal()
  71. #define MAX_TEXT_UNICODE_CHARS 512 // Maximum number of unicode codepoints
  72. #if !defined(TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH)
  73. #define TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH 1024 // Size of static buffer: TextSplit()
  74. #endif
  75. #if !defined(TEXTSPLIT_MAX_SUBSTRINGS_COUNT)
  76. #define TEXTSPLIT_MAX_SUBSTRINGS_COUNT 128 // Size of static pointers array: TextSplit()
  77. #endif
  78. //----------------------------------------------------------------------------------
  79. // Types and Structures Definition
  80. //----------------------------------------------------------------------------------
  81. // ...
  82. //----------------------------------------------------------------------------------
  83. // Global variables
  84. //----------------------------------------------------------------------------------
  85. #if defined(SUPPORT_DEFAULT_FONT)
  86. static Font defaultFont = { 0 }; // Default font provided by raylib
  87. // NOTE: defaultFont is loaded on InitWindow and disposed on CloseWindow [module: core]
  88. #endif
  89. //----------------------------------------------------------------------------------
  90. // Other Modules Functions Declaration (required by text)
  91. //----------------------------------------------------------------------------------
  92. //...
  93. //----------------------------------------------------------------------------------
  94. // Module specific Functions Declaration
  95. //----------------------------------------------------------------------------------
  96. #if defined(SUPPORT_FILEFORMAT_FNT)
  97. static Font LoadBMFont(const char *fileName); // Load a BMFont file (AngelCode font file)
  98. #endif
  99. #if defined(SUPPORT_DEFAULT_FONT)
  100. extern void LoadFontDefault(void);
  101. extern void UnloadFontDefault(void);
  102. #endif
  103. //----------------------------------------------------------------------------------
  104. // Module Functions Definition
  105. //----------------------------------------------------------------------------------
  106. #if defined(SUPPORT_DEFAULT_FONT)
  107. // Load raylib default font
  108. extern void LoadFontDefault(void)
  109. {
  110. #define BIT_CHECK(a,b) ((a) & (1u << (b)))
  111. // NOTE: Using UTF8 encoding table for Unicode U+0000..U+00FF Basic Latin + Latin-1 Supplement
  112. // Ref: http://www.utf8-chartable.de/unicode-utf8-table.pl
  113. defaultFont.charsCount = 224; // Number of chars included in our default font
  114. // Default font is directly defined here (data generated from a sprite font image)
  115. // This way, we reconstruct Font without creating large global variables
  116. // This data is automatically allocated to Stack and automatically deallocated at the end of this function
  117. unsigned int defaultFontData[512] = {
  118. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00200020, 0x0001b000, 0x00000000, 0x00000000, 0x8ef92520, 0x00020a00, 0x7dbe8000, 0x1f7df45f,
  119. 0x4a2bf2a0, 0x0852091e, 0x41224000, 0x10041450, 0x2e292020, 0x08220812, 0x41222000, 0x10041450, 0x10f92020, 0x3efa084c, 0x7d22103c, 0x107df7de,
  120. 0xe8a12020, 0x08220832, 0x05220800, 0x10450410, 0xa4a3f000, 0x08520832, 0x05220400, 0x10450410, 0xe2f92020, 0x0002085e, 0x7d3e0281, 0x107df41f,
  121. 0x00200000, 0x8001b000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  122. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xc0000fbe, 0xfbf7e00f, 0x5fbf7e7d, 0x0050bee8, 0x440808a2, 0x0a142fe8, 0x50810285, 0x0050a048,
  123. 0x49e428a2, 0x0a142828, 0x40810284, 0x0048a048, 0x10020fbe, 0x09f7ebaf, 0xd89f3e84, 0x0047a04f, 0x09e48822, 0x0a142aa1, 0x50810284, 0x0048a048,
  124. 0x04082822, 0x0a142fa0, 0x50810285, 0x0050a248, 0x00008fbe, 0xfbf42021, 0x5f817e7d, 0x07d09ce8, 0x00008000, 0x00000fe0, 0x00000000, 0x00000000,
  125. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x000c0180,
  126. 0xdfbf4282, 0x0bfbf7ef, 0x42850505, 0x004804bf, 0x50a142c6, 0x08401428, 0x42852505, 0x00a808a0, 0x50a146aa, 0x08401428, 0x42852505, 0x00081090,
  127. 0x5fa14a92, 0x0843f7e8, 0x7e792505, 0x00082088, 0x40a15282, 0x08420128, 0x40852489, 0x00084084, 0x40a16282, 0x0842022a, 0x40852451, 0x00088082,
  128. 0xc0bf4282, 0xf843f42f, 0x7e85fc21, 0x3e0900bf, 0x00000000, 0x00000004, 0x00000000, 0x000c0180, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  129. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x04000402, 0x41482000, 0x00000000, 0x00000800,
  130. 0x04000404, 0x4100203c, 0x00000000, 0x00000800, 0xf7df7df0, 0x514bef85, 0xbefbefbe, 0x04513bef, 0x14414500, 0x494a2885, 0xa28a28aa, 0x04510820,
  131. 0xf44145f0, 0x474a289d, 0xa28a28aa, 0x04510be0, 0x14414510, 0x494a2884, 0xa28a28aa, 0x02910a00, 0xf7df7df0, 0xd14a2f85, 0xbefbe8aa, 0x011f7be0,
  132. 0x00000000, 0x00400804, 0x20080000, 0x00000000, 0x00000000, 0x00600f84, 0x20080000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  133. 0xac000000, 0x00000f01, 0x00000000, 0x00000000, 0x24000000, 0x00000f01, 0x00000000, 0x06000000, 0x24000000, 0x00000f01, 0x00000000, 0x09108000,
  134. 0x24fa28a2, 0x00000f01, 0x00000000, 0x013e0000, 0x2242252a, 0x00000f52, 0x00000000, 0x038a8000, 0x2422222a, 0x00000f29, 0x00000000, 0x010a8000,
  135. 0x2412252a, 0x00000f01, 0x00000000, 0x010a8000, 0x24fbe8be, 0x00000f01, 0x00000000, 0x0ebe8000, 0xac020000, 0x00000f01, 0x00000000, 0x00048000,
  136. 0x0003e000, 0x00000f00, 0x00000000, 0x00008000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000038, 0x8443b80e, 0x00203a03,
  137. 0x02bea080, 0xf0000020, 0xc452208a, 0x04202b02, 0xf8029122, 0x07f0003b, 0xe44b388e, 0x02203a02, 0x081e8a1c, 0x0411e92a, 0xf4420be0, 0x01248202,
  138. 0xe8140414, 0x05d104ba, 0xe7c3b880, 0x00893a0a, 0x283c0e1c, 0x04500902, 0xc4400080, 0x00448002, 0xe8208422, 0x04500002, 0x80400000, 0x05200002,
  139. 0x083e8e00, 0x04100002, 0x804003e0, 0x07000042, 0xf8008400, 0x07f00003, 0x80400000, 0x04000022, 0x00000000, 0x00000000, 0x80400000, 0x04000002,
  140. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00800702, 0x1848a0c2, 0x84010000, 0x02920921, 0x01042642, 0x00005121, 0x42023f7f, 0x00291002,
  141. 0xefc01422, 0x7efdfbf7, 0xefdfa109, 0x03bbbbf7, 0x28440f12, 0x42850a14, 0x20408109, 0x01111010, 0x28440408, 0x42850a14, 0x2040817f, 0x01111010,
  142. 0xefc78204, 0x7efdfbf7, 0xe7cf8109, 0x011111f3, 0x2850a932, 0x42850a14, 0x2040a109, 0x01111010, 0x2850b840, 0x42850a14, 0xefdfbf79, 0x03bbbbf7,
  143. 0x001fa020, 0x00000000, 0x00001000, 0x00000000, 0x00002070, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  144. 0x08022800, 0x00012283, 0x02430802, 0x01010001, 0x8404147c, 0x20000144, 0x80048404, 0x00823f08, 0xdfbf4284, 0x7e03f7ef, 0x142850a1, 0x0000210a,
  145. 0x50a14684, 0x528a1428, 0x142850a1, 0x03efa17a, 0x50a14a9e, 0x52521428, 0x142850a1, 0x02081f4a, 0x50a15284, 0x4a221428, 0xf42850a1, 0x03efa14b,
  146. 0x50a16284, 0x4a521428, 0x042850a1, 0x0228a17a, 0xdfbf427c, 0x7e8bf7ef, 0xf7efdfbf, 0x03efbd0b, 0x00000000, 0x04000000, 0x00000000, 0x00000008,
  147. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00200508, 0x00840400, 0x11458122, 0x00014210,
  148. 0x00514294, 0x51420800, 0x20a22a94, 0x0050a508, 0x00200000, 0x00000000, 0x00050000, 0x08000000, 0xfefbefbe, 0xfbefbefb, 0xfbeb9114, 0x00fbefbe,
  149. 0x20820820, 0x8a28a20a, 0x8a289114, 0x3e8a28a2, 0xfefbefbe, 0xfbefbe0b, 0x8a289114, 0x008a28a2, 0x228a28a2, 0x08208208, 0x8a289114, 0x088a28a2,
  150. 0xfefbefbe, 0xfbefbefb, 0xfa2f9114, 0x00fbefbe, 0x00000000, 0x00000040, 0x00000000, 0x00000000, 0x00000000, 0x00000020, 0x00000000, 0x00000000,
  151. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00210100, 0x00000004, 0x00000000, 0x00000000, 0x14508200, 0x00001402, 0x00000000, 0x00000000,
  152. 0x00000010, 0x00000020, 0x00000000, 0x00000000, 0xa28a28be, 0x00002228, 0x00000000, 0x00000000, 0xa28a28aa, 0x000022e8, 0x00000000, 0x00000000,
  153. 0xa28a28aa, 0x000022a8, 0x00000000, 0x00000000, 0xa28a28aa, 0x000022e8, 0x00000000, 0x00000000, 0xbefbefbe, 0x00003e2f, 0x00000000, 0x00000000,
  154. 0x00000004, 0x00002028, 0x00000000, 0x00000000, 0x80000000, 0x00003e0f, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  155. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  156. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  157. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  158. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  159. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  160. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000 };
  161. int charsHeight = 10;
  162. int charsDivisor = 1; // Every char is separated from the consecutive by a 1 pixel divisor, horizontally and vertically
  163. 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,
  164. 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,
  165. 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,
  166. 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,
  167. 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,
  168. 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,
  169. 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 };
  170. // Re-construct image from defaultFontData and generate OpenGL texture
  171. //----------------------------------------------------------------------
  172. int imWidth = 128;
  173. int imHeight = 128;
  174. Color *imagePixels = (Color *)RL_MALLOC(imWidth*imHeight*sizeof(Color));
  175. for (int i = 0; i < imWidth*imHeight; i++) imagePixels[i] = BLANK; // Initialize array
  176. int counter = 0; // Font data elements counter
  177. // Fill imgData with defaultFontData (convert from bit to pixel!)
  178. for (int i = 0; i < imWidth*imHeight; i += 32)
  179. {
  180. for (int j = 31; j >= 0; j--)
  181. {
  182. if (BIT_CHECK(defaultFontData[counter], j)) imagePixels[i+j] = WHITE;
  183. }
  184. counter++;
  185. if (counter > 512) counter = 0; // Security check...
  186. }
  187. Image imFont = LoadImageEx(imagePixels, imWidth, imHeight);
  188. ImageFormat(&imFont, UNCOMPRESSED_GRAY_ALPHA);
  189. RL_FREE(imagePixels);
  190. defaultFont.texture = LoadTextureFromImage(imFont);
  191. // Reconstruct charSet using charsWidth[], charsHeight, charsDivisor, charsCount
  192. //------------------------------------------------------------------------------
  193. // Allocate space for our characters info data
  194. // NOTE: This memory should be freed at end! --> CloseWindow()
  195. defaultFont.chars = (CharInfo *)RL_MALLOC(defaultFont.charsCount*sizeof(CharInfo));
  196. defaultFont.recs = (Rectangle *)RL_MALLOC(defaultFont.charsCount*sizeof(Rectangle));
  197. int currentLine = 0;
  198. int currentPosX = charsDivisor;
  199. int testPosX = charsDivisor;
  200. for (int i = 0; i < defaultFont.charsCount; i++)
  201. {
  202. defaultFont.chars[i].value = 32 + i; // First char is 32
  203. defaultFont.recs[i].x = (float)currentPosX;
  204. defaultFont.recs[i].y = (float)(charsDivisor + currentLine*(charsHeight + charsDivisor));
  205. defaultFont.recs[i].width = (float)charsWidth[i];
  206. defaultFont.recs[i].height = (float)charsHeight;
  207. testPosX += (int)(defaultFont.recs[i].width + (float)charsDivisor);
  208. if (testPosX >= defaultFont.texture.width)
  209. {
  210. currentLine++;
  211. currentPosX = 2*charsDivisor + charsWidth[i];
  212. testPosX = currentPosX;
  213. defaultFont.recs[i].x = (float)charsDivisor;
  214. defaultFont.recs[i].y = (float)(charsDivisor + currentLine*(charsHeight + charsDivisor));
  215. }
  216. else currentPosX = testPosX;
  217. // NOTE: On default font character offsets and xAdvance are not required
  218. defaultFont.chars[i].offsetX = 0;
  219. defaultFont.chars[i].offsetY = 0;
  220. defaultFont.chars[i].advanceX = 0;
  221. // Fill character image data from fontClear data
  222. defaultFont.chars[i].image = ImageFromImage(imFont, defaultFont.recs[i]);
  223. }
  224. UnloadImage(imFont);
  225. defaultFont.baseSize = (int)defaultFont.recs[0].height;
  226. TraceLog(LOG_INFO, "[TEX ID %i] Default font loaded successfully", defaultFont.texture.id);
  227. }
  228. // Unload raylib default font
  229. extern void UnloadFontDefault(void)
  230. {
  231. for (int i = 0; i < defaultFont.charsCount; i++) UnloadImage(defaultFont.chars[i].image);
  232. UnloadTexture(defaultFont.texture);
  233. RL_FREE(defaultFont.chars);
  234. RL_FREE(defaultFont.recs);
  235. }
  236. #endif // SUPPORT_DEFAULT_FONT
  237. // Get the default font, useful to be used with extended parameters
  238. Font GetFontDefault()
  239. {
  240. #if defined(SUPPORT_DEFAULT_FONT)
  241. return defaultFont;
  242. #else
  243. Font font = { 0 };
  244. return font;
  245. #endif
  246. }
  247. // Load Font from file into GPU memory (VRAM)
  248. Font LoadFont(const char *fileName)
  249. {
  250. // Default hardcoded values for ttf file loading
  251. #define DEFAULT_TTF_FONTSIZE 32 // Font first character (32 - space)
  252. #define DEFAULT_TTF_NUMCHARS 95 // ASCII 32..126 is 95 glyphs
  253. #define DEFAULT_FIRST_CHAR 32 // Expected first char for image sprite font
  254. Font font = { 0 };
  255. #if defined(SUPPORT_FILEFORMAT_TTF)
  256. if (IsFileExtension(fileName, ".ttf;.otf")) font = LoadFontEx(fileName, DEFAULT_TTF_FONTSIZE, NULL, DEFAULT_TTF_NUMCHARS);
  257. else
  258. #endif
  259. #if defined(SUPPORT_FILEFORMAT_FNT)
  260. if (IsFileExtension(fileName, ".fnt")) font = LoadBMFont(fileName);
  261. else
  262. #endif
  263. {
  264. Image image = LoadImage(fileName);
  265. if (image.data != NULL) font = LoadFontFromImage(image, MAGENTA, DEFAULT_FIRST_CHAR);
  266. UnloadImage(image);
  267. }
  268. if (font.texture.id == 0)
  269. {
  270. TraceLog(LOG_WARNING, "[%s] Font could not be loaded, using default font", fileName);
  271. font = GetFontDefault();
  272. }
  273. else SetTextureFilter(font.texture, FILTER_POINT); // By default we set point filter (best performance)
  274. return font;
  275. }
  276. // Load Font from TTF font file with generation parameters
  277. // NOTE: You can pass an array with desired characters, those characters should be available in the font
  278. // if array is NULL, default char set is selected 32..126
  279. Font LoadFontEx(const char *fileName, int fontSize, int *fontChars, int charsCount)
  280. {
  281. Font font = { 0 };
  282. font.baseSize = fontSize;
  283. font.charsCount = (charsCount > 0)? charsCount : 95;
  284. font.chars = LoadFontData(fileName, font.baseSize, fontChars, font.charsCount, FONT_DEFAULT);
  285. #if defined(SUPPORT_FILEFORMAT_TTF)
  286. if (font.chars != NULL)
  287. {
  288. Image atlas = GenImageFontAtlas(font.chars, &font.recs, font.charsCount, font.baseSize, 2, 0);
  289. font.texture = LoadTextureFromImage(atlas);
  290. // Update chars[i].image to use alpha, required to be used on ImageDrawText()
  291. for (int i = 0; i < font.charsCount; i++)
  292. {
  293. UnloadImage(font.chars[i].image);
  294. font.chars[i].image = ImageFromImage(atlas, font.recs[i]);
  295. }
  296. UnloadImage(atlas);
  297. }
  298. else font = GetFontDefault();
  299. #else
  300. UnloadFont(font);
  301. font = GetFontDefault();
  302. #endif
  303. return font;
  304. }
  305. // Load an Image font file (XNA style)
  306. Font LoadFontFromImage(Image image, Color key, int firstChar)
  307. {
  308. #define COLOR_EQUAL(col1, col2) ((col1.r == col2.r)&&(col1.g == col2.g)&&(col1.b == col2.b)&&(col1.a == col2.a))
  309. int charSpacing = 0;
  310. int lineSpacing = 0;
  311. int x = 0;
  312. int y = 0;
  313. // Default number of characters supported
  314. #define MAX_FONTCHARS 256
  315. // We allocate a temporal arrays for chars data measures,
  316. // once we get the actual number of chars, we copy data to a sized arrays
  317. int tempCharValues[MAX_FONTCHARS];
  318. Rectangle tempCharRecs[MAX_FONTCHARS];
  319. Color *pixels = GetImageData(image);
  320. // Parse image data to get charSpacing and lineSpacing
  321. for (y = 0; y < image.height; y++)
  322. {
  323. for (x = 0; x < image.width; x++)
  324. {
  325. if (!COLOR_EQUAL(pixels[y*image.width + x], key)) break;
  326. }
  327. if (!COLOR_EQUAL(pixels[y*image.width + x], key)) break;
  328. }
  329. charSpacing = x;
  330. lineSpacing = y;
  331. int charHeight = 0;
  332. int j = 0;
  333. while (!COLOR_EQUAL(pixels[(lineSpacing + j)*image.width + charSpacing], key)) j++;
  334. charHeight = j;
  335. // Check array values to get characters: value, x, y, w, h
  336. int index = 0;
  337. int lineToRead = 0;
  338. int xPosToRead = charSpacing;
  339. // Parse image data to get rectangle sizes
  340. while ((lineSpacing + lineToRead*(charHeight + lineSpacing)) < image.height)
  341. {
  342. while ((xPosToRead < image.width) &&
  343. !COLOR_EQUAL((pixels[(lineSpacing + (charHeight+lineSpacing)*lineToRead)*image.width + xPosToRead]), key))
  344. {
  345. tempCharValues[index] = firstChar + index;
  346. tempCharRecs[index].x = (float)xPosToRead;
  347. tempCharRecs[index].y = (float)(lineSpacing + lineToRead*(charHeight + lineSpacing));
  348. tempCharRecs[index].height = (float)charHeight;
  349. int charWidth = 0;
  350. while (!COLOR_EQUAL(pixels[(lineSpacing + (charHeight+lineSpacing)*lineToRead)*image.width + xPosToRead + charWidth], key)) charWidth++;
  351. tempCharRecs[index].width = (float)charWidth;
  352. index++;
  353. xPosToRead += (charWidth + charSpacing);
  354. }
  355. lineToRead++;
  356. xPosToRead = charSpacing;
  357. }
  358. TraceLog(LOG_DEBUG, "Font data parsed correctly from image");
  359. // NOTE: We need to remove key color borders from image to avoid weird
  360. // artifacts on texture scaling when using FILTER_BILINEAR or FILTER_TRILINEAR
  361. for (int i = 0; i < image.height*image.width; i++) if (COLOR_EQUAL(pixels[i], key)) pixels[i] = BLANK;
  362. // Create a new image with the processed color data (key color replaced by BLANK)
  363. Image fontClear = LoadImageEx(pixels, image.width, image.height);
  364. RL_FREE(pixels); // Free pixels array memory
  365. // Create spritefont with all data parsed from image
  366. Font font = { 0 };
  367. font.texture = LoadTextureFromImage(fontClear); // Convert processed image to OpenGL texture
  368. font.charsCount = index;
  369. // We got tempCharValues and tempCharsRecs populated with chars data
  370. // Now we move temp data to sized charValues and charRecs arrays
  371. font.chars = (CharInfo *)RL_MALLOC(font.charsCount*sizeof(CharInfo));
  372. font.recs = (Rectangle *)RL_MALLOC(font.charsCount*sizeof(Rectangle));
  373. for (int i = 0; i < font.charsCount; i++)
  374. {
  375. font.chars[i].value = tempCharValues[i];
  376. // Get character rectangle in the font atlas texture
  377. font.recs[i] = tempCharRecs[i];
  378. // NOTE: On image based fonts (XNA style), character offsets and xAdvance are not required (set to 0)
  379. font.chars[i].offsetX = 0;
  380. font.chars[i].offsetY = 0;
  381. font.chars[i].advanceX = 0;
  382. // Fill character image data from fontClear data
  383. font.chars[i].image = ImageFromImage(fontClear, tempCharRecs[i]);
  384. }
  385. UnloadImage(fontClear); // Unload processed image once converted to texture
  386. font.baseSize = (int)font.recs[0].height;
  387. TraceLog(LOG_INFO, "Image file loaded correctly as Font");
  388. return font;
  389. }
  390. // Load font data for further use
  391. // NOTE: Requires TTF font and can generate SDF data
  392. CharInfo *LoadFontData(const char *fileName, int fontSize, int *fontChars, int charsCount, int type)
  393. {
  394. // NOTE: Using some SDF generation default values,
  395. // trades off precision with ability to handle *smaller* sizes
  396. #define SDF_CHAR_PADDING 4
  397. #define SDF_ON_EDGE_VALUE 128
  398. #define SDF_PIXEL_DIST_SCALE 64.0f
  399. #define BITMAP_ALPHA_THRESHOLD 80
  400. CharInfo *chars = NULL;
  401. #if defined(SUPPORT_FILEFORMAT_TTF)
  402. // Load font data (including pixel data) from TTF file
  403. // NOTE: Loaded information should be enough to generate font image atlas,
  404. // using any packaging method
  405. FILE *fontFile = fopen(fileName, "rb"); // Load font file
  406. if (fontFile != NULL)
  407. {
  408. fseek(fontFile, 0, SEEK_END);
  409. long size = ftell(fontFile); // Get file size
  410. fseek(fontFile, 0, SEEK_SET); // Reset file pointer
  411. unsigned char *fontBuffer = (unsigned char *)RL_MALLOC(size);
  412. fread(fontBuffer, size, 1, fontFile);
  413. fclose(fontFile);
  414. // Init font for data reading
  415. stbtt_fontinfo fontInfo;
  416. if (!stbtt_InitFont(&fontInfo, fontBuffer, 0)) TraceLog(LOG_WARNING, "Failed to init font!");
  417. // Calculate font scale factor
  418. float scaleFactor = stbtt_ScaleForPixelHeight(&fontInfo, (float)fontSize);
  419. // Calculate font basic metrics
  420. // NOTE: ascent is equivalent to font baseline
  421. int ascent, descent, lineGap;
  422. stbtt_GetFontVMetrics(&fontInfo, &ascent, &descent, &lineGap);
  423. // In case no chars count provided, default to 95
  424. charsCount = (charsCount > 0)? charsCount : 95;
  425. // Fill fontChars in case not provided externally
  426. // NOTE: By default we fill charsCount consecutevely, starting at 32 (Space)
  427. int genFontChars = false;
  428. if (fontChars == NULL)
  429. {
  430. fontChars = (int *)RL_MALLOC(charsCount*sizeof(int));
  431. for (int i = 0; i < charsCount; i++) fontChars[i] = i + 32;
  432. genFontChars = true;
  433. }
  434. chars = (CharInfo *)RL_MALLOC(charsCount*sizeof(CharInfo));
  435. // NOTE: Using simple packaging, one char after another
  436. for (int i = 0; i < charsCount; i++)
  437. {
  438. int chw = 0, chh = 0; // Character width and height (on generation)
  439. int ch = fontChars[i]; // Character value to get info for
  440. chars[i].value = ch;
  441. // Render a unicode codepoint to a bitmap
  442. // stbtt_GetCodepointBitmap() -- allocates and returns a bitmap
  443. // stbtt_GetCodepointBitmapBox() -- how big the bitmap must be
  444. // stbtt_MakeCodepointBitmap() -- renders into bitmap you provide
  445. if (type != FONT_SDF) chars[i].image.data = stbtt_GetCodepointBitmap(&fontInfo, scaleFactor, scaleFactor, ch, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY);
  446. else if (ch != 32) chars[i].image.data = stbtt_GetCodepointSDF(&fontInfo, scaleFactor, ch, SDF_CHAR_PADDING, SDF_ON_EDGE_VALUE, SDF_PIXEL_DIST_SCALE, &chw, &chh, &chars[i].offsetX, &chars[i].offsetY);
  447. else chars[i].image.data = NULL;
  448. stbtt_GetCodepointHMetrics(&fontInfo, ch, &chars[i].advanceX, NULL);
  449. chars[i].advanceX = (int)((float)chars[i].advanceX*scaleFactor);
  450. // Load characters images
  451. chars[i].image.width = chw;
  452. chars[i].image.height = chh;
  453. chars[i].image.mipmaps = 1;
  454. chars[i].image.format = UNCOMPRESSED_GRAYSCALE;
  455. chars[i].offsetY += (int)((float)ascent*scaleFactor);
  456. // NOTE: We create an empty image for space character, it could be further required for atlas packing
  457. if (ch == 32)
  458. {
  459. chars[i].image = GenImageColor(chars[i].advanceX, fontSize, BLANK);
  460. ImageFormat(&chars[i].image, UNCOMPRESSED_GRAYSCALE);
  461. }
  462. if (type == FONT_BITMAP)
  463. {
  464. // Aliased bitmap (black & white) font generation, avoiding anti-aliasing
  465. // NOTE: For optimum results, bitmap font should be generated at base pixel size
  466. for (int p = 0; p < chw*chh; p++)
  467. {
  468. if (((unsigned char *)chars[i].image.data)[p] < BITMAP_ALPHA_THRESHOLD) ((unsigned char *)chars[i].image.data)[p] = 0;
  469. else ((unsigned char *)chars[i].image.data)[p] = 255;
  470. }
  471. }
  472. // Get bounding box for character (may be offset to account for chars that dip above or below the line)
  473. /*
  474. int chX1, chY1, chX2, chY2;
  475. stbtt_GetCodepointBitmapBox(&fontInfo, ch, scaleFactor, scaleFactor, &chX1, &chY1, &chX2, &chY2);
  476. TraceLog(LOG_DEBUG, "Character box measures: %i, %i, %i, %i", chX1, chY1, chX2 - chX1, chY2 - chY1);
  477. TraceLog(LOG_DEBUG, "Character offsetY: %i", (int)((float)ascent*scaleFactor) + chY1);
  478. */
  479. }
  480. RL_FREE(fontBuffer);
  481. if (genFontChars) RL_FREE(fontChars);
  482. }
  483. else TraceLog(LOG_WARNING, "[%s] TTF file could not be opened", fileName);
  484. #else
  485. TraceLog(LOG_WARNING, "[%s] TTF support is disabled", fileName);
  486. #endif
  487. return chars;
  488. }
  489. // Generate image font atlas using chars info
  490. // NOTE: Packing method: 0-Default, 1-Skyline
  491. #if defined(SUPPORT_FILEFORMAT_TTF)
  492. Image GenImageFontAtlas(const CharInfo *chars, Rectangle **charRecs, int charsCount, int fontSize, int padding, int packMethod)
  493. {
  494. Image atlas = { 0 };
  495. *charRecs = NULL;
  496. // In case no chars count provided we suppose default of 95
  497. charsCount = (charsCount > 0)? charsCount : 95;
  498. // NOTE: Rectangles memory is loaded here!
  499. Rectangle *recs = (Rectangle *)RL_MALLOC(charsCount*sizeof(Rectangle));
  500. // Calculate image size based on required pixel area
  501. // NOTE 1: Image is forced to be squared and POT... very conservative!
  502. // NOTE 2: SDF font characters already contain an internal padding,
  503. // so image size would result bigger than default font type
  504. float requiredArea = 0;
  505. for (int i = 0; i < charsCount; i++) requiredArea += ((chars[i].image.width + 2*padding)*(chars[i].image.height + 2*padding));
  506. float guessSize = sqrtf(requiredArea)*1.3f;
  507. int imageSize = (int)powf(2, ceilf(logf((float)guessSize)/logf(2))); // Calculate next POT
  508. atlas.width = imageSize; // Atlas bitmap width
  509. atlas.height = imageSize; // Atlas bitmap height
  510. atlas.data = (unsigned char *)RL_CALLOC(1, atlas.width*atlas.height); // Create a bitmap to store characters (8 bpp)
  511. atlas.format = UNCOMPRESSED_GRAYSCALE;
  512. atlas.mipmaps = 1;
  513. // DEBUG: We can see padding in the generated image setting a gray background...
  514. //for (int i = 0; i < atlas.width*atlas.height; i++) ((unsigned char *)atlas.data)[i] = 100;
  515. if (packMethod == 0) // Use basic packing algorythm
  516. {
  517. int offsetX = padding;
  518. int offsetY = padding;
  519. // NOTE: Using simple packaging, one char after another
  520. for (int i = 0; i < charsCount; i++)
  521. {
  522. // Copy pixel data from fc.data to atlas
  523. for (int y = 0; y < chars[i].image.height; y++)
  524. {
  525. for (int x = 0; x < chars[i].image.width; x++)
  526. {
  527. ((unsigned char *)atlas.data)[(offsetY + y)*atlas.width + (offsetX + x)] = ((unsigned char *)chars[i].image.data)[y*chars[i].image.width + x];
  528. }
  529. }
  530. // Fill chars rectangles in atlas info
  531. recs[i].x = (float)offsetX;
  532. recs[i].y = (float)offsetY;
  533. recs[i].width = (float)chars[i].image.width;
  534. recs[i].height = (float)chars[i].image.height;
  535. // Move atlas position X for next character drawing
  536. offsetX += (chars[i].image.width + 2*padding);
  537. if (offsetX >= (atlas.width - chars[i].image.width - padding))
  538. {
  539. offsetX = padding;
  540. // NOTE: Be careful on offsetY for SDF fonts, by default SDF
  541. // use an internal padding of 4 pixels, it means char rectangle
  542. // height is bigger than fontSize, it could be up to (fontSize + 8)
  543. offsetY += (fontSize + 2*padding);
  544. if (offsetY > (atlas.height - fontSize - padding)) break;
  545. }
  546. }
  547. }
  548. else if (packMethod == 1) // Use Skyline rect packing algorythm (stb_pack_rect)
  549. {
  550. TraceLog(LOG_DEBUG, "Using Skyline packing algorythm!");
  551. stbrp_context *context = (stbrp_context *)RL_MALLOC(sizeof(*context));
  552. stbrp_node *nodes = (stbrp_node *)RL_MALLOC(charsCount*sizeof(*nodes));
  553. stbrp_init_target(context, atlas.width, atlas.height, nodes, charsCount);
  554. stbrp_rect *rects = (stbrp_rect *)RL_MALLOC(charsCount*sizeof(stbrp_rect));
  555. // Fill rectangles for packaging
  556. for (int i = 0; i < charsCount; i++)
  557. {
  558. rects[i].id = i;
  559. rects[i].w = chars[i].image.width + 2*padding;
  560. rects[i].h = chars[i].image.height + 2*padding;
  561. }
  562. // Package rectangles into atlas
  563. stbrp_pack_rects(context, rects, charsCount);
  564. for (int i = 0; i < charsCount; i++)
  565. {
  566. // It return char rectangles in atlas
  567. recs[i].x = rects[i].x + (float)padding;
  568. recs[i].y = rects[i].y + (float)padding;
  569. recs[i].width = (float)chars[i].image.width;
  570. recs[i].height = (float)chars[i].image.height;
  571. if (rects[i].was_packed)
  572. {
  573. // Copy pixel data from fc.data to atlas
  574. for (int y = 0; y < chars[i].image.height; y++)
  575. {
  576. for (int x = 0; x < chars[i].image.width; x++)
  577. {
  578. ((unsigned char *)atlas.data)[(rects[i].y + padding + y)*atlas.width + (rects[i].x + padding + x)] = ((unsigned char *)chars[i].image.data)[y*chars[i].image.width + x];
  579. }
  580. }
  581. }
  582. else TraceLog(LOG_WARNING, "Character could not be packed: %i", i);
  583. }
  584. RL_FREE(rects);
  585. RL_FREE(nodes);
  586. RL_FREE(context);
  587. }
  588. // TODO: Crop image if required for smaller size
  589. // Convert image data from GRAYSCALE to GRAY_ALPHA
  590. // WARNING: ImageAlphaMask(&atlas, atlas) does not work in this case, requires manual operation
  591. unsigned char *dataGrayAlpha = (unsigned char *)RL_MALLOC(atlas.width*atlas.height*sizeof(unsigned char)*2); // Two channels
  592. for (int i = 0, k = 0; i < atlas.width*atlas.height; i++, k += 2)
  593. {
  594. dataGrayAlpha[k] = 255;
  595. dataGrayAlpha[k + 1] = ((unsigned char *)atlas.data)[i];
  596. }
  597. RL_FREE(atlas.data);
  598. atlas.data = dataGrayAlpha;
  599. atlas.format = UNCOMPRESSED_GRAY_ALPHA;
  600. *charRecs = recs;
  601. return atlas;
  602. }
  603. #endif
  604. // Unload Font from GPU memory (VRAM)
  605. void UnloadFont(Font font)
  606. {
  607. // NOTE: Make sure font is not default font (fallback)
  608. if (font.texture.id != GetFontDefault().texture.id)
  609. {
  610. for (int i = 0; i < font.charsCount; i++) UnloadImage(font.chars[i].image);
  611. UnloadTexture(font.texture);
  612. RL_FREE(font.chars);
  613. RL_FREE(font.recs);
  614. TraceLog(LOG_DEBUG, "Unloaded sprite font data");
  615. }
  616. }
  617. // Shows current FPS on top-left corner
  618. // NOTE: Uses default font
  619. void DrawFPS(int posX, int posY)
  620. {
  621. // NOTE: We are rendering fps every certain time for better viewing on high framerates
  622. static int fps = 0;
  623. static int counter = 0;
  624. static int refreshRate = 20;
  625. if (counter < refreshRate) counter++;
  626. else
  627. {
  628. fps = GetFPS();
  629. refreshRate = fps;
  630. counter = 0;
  631. }
  632. // TODO: Find a better way to calculate FPS, maybe calculate the mean of multiple measures?
  633. // NOTE: We have rounding errors every frame, so it oscillates a lot
  634. DrawText(TextFormat("%2i FPS", fps), posX, posY, 20, LIME);
  635. }
  636. // Draw text (using default font)
  637. // NOTE: fontSize work like in any drawing program but if fontSize is lower than font-base-size, then font-base-size is used
  638. // NOTE: chars spacing is proportional to fontSize
  639. void DrawText(const char *text, int posX, int posY, int fontSize, Color color)
  640. {
  641. // Check if default font has been loaded
  642. if (GetFontDefault().texture.id != 0)
  643. {
  644. Vector2 position = { (float)posX, (float)posY };
  645. int defaultFontSize = 10; // Default Font chars height in pixel
  646. if (fontSize < defaultFontSize) fontSize = defaultFontSize;
  647. int spacing = fontSize/defaultFontSize;
  648. DrawTextEx(GetFontDefault(), text, position, (float)fontSize, (float)spacing, color);
  649. }
  650. }
  651. // Draw one character (codepoint)
  652. void DrawTextCodepoint(Font font, int codepoint, Vector2 position, float scale, Color tint)
  653. {
  654. // Character index position in sprite font
  655. // NOTE: In case a codepoint is not available in the font, index returned points to '?'
  656. int index = GetGlyphIndex(font, codepoint);
  657. // Character rectangle on screen
  658. // NOTE: Quad is scaled proportionally to base character width-height
  659. Rectangle rec = { position.x, position.y, font.recs[index].width*scale, font.recs[index].height*scale };
  660. DrawTexturePro(font.texture, font.recs[index], rec, (Vector2){ 0, 0 }, 0.0f, tint);
  661. }
  662. // Draw text using Font
  663. // NOTE: chars spacing is NOT proportional to fontSize
  664. void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint)
  665. {
  666. int length = strlen(text); // Total length in bytes of the text, scanned by codepoints in loop
  667. int textOffsetY = 0; // Offset between lines (on line break '\n')
  668. float textOffsetX = 0.0f; // Offset X to next character to draw
  669. float scaleFactor = fontSize/font.baseSize; // Character quad scaling factor
  670. for (int i = 0; i < length; i++)
  671. {
  672. // Get next codepoint from byte string and glyph index in font
  673. int codepointByteCount = 0;
  674. int codepoint = GetNextCodepoint(&text[i], &codepointByteCount);
  675. int index = GetGlyphIndex(font, codepoint);
  676. // NOTE: Normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
  677. // but we need to draw all of the bad bytes using the '?' symbol moving one byte
  678. if (codepoint == 0x3f) codepointByteCount = 1;
  679. if (codepoint == '\n')
  680. {
  681. // NOTE: Fixed line spacing of 1.5 line-height
  682. // TODO: Support custom line spacing defined by user
  683. textOffsetY += (int)((font.baseSize + font.baseSize/2)*scaleFactor);
  684. textOffsetX = 0.0f;
  685. }
  686. else
  687. {
  688. if ((codepoint != ' ') && (codepoint != '\t'))
  689. {
  690. Rectangle rec = { position.x + textOffsetX + font.chars[index].offsetX*scaleFactor,
  691. position.y + textOffsetY + font.chars[index].offsetY*scaleFactor,
  692. font.recs[index].width*scaleFactor,
  693. font.recs[index].height*scaleFactor };
  694. DrawTexturePro(font.texture, font.recs[index], rec, (Vector2){ 0, 0 }, 0.0f, tint);
  695. }
  696. if (font.chars[index].advanceX == 0) textOffsetX += ((float)font.recs[index].width*scaleFactor + spacing);
  697. else textOffsetX += ((float)font.chars[index].advanceX*scaleFactor + spacing);
  698. }
  699. i += (codepointByteCount - 1); // Move text bytes counter to next codepoint
  700. }
  701. }
  702. // Draw text using font inside rectangle limits
  703. void DrawTextRec(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint)
  704. {
  705. DrawTextRecEx(font, text, rec, fontSize, spacing, wordWrap, tint, 0, 0, WHITE, WHITE);
  706. }
  707. // Draw text using font inside rectangle limits with support for text selection
  708. void DrawTextRecEx(Font font, const char *text, Rectangle rec, float fontSize, float spacing, bool wordWrap, Color tint, int selectStart, int selectLength, Color selectTint, Color selectBackTint)
  709. {
  710. int length = strlen(text); // Total length in bytes of the text, scanned by codepoints in loop
  711. int textOffsetY = 0; // Offset between lines (on line break '\n')
  712. float textOffsetX = 0.0f; // Offset X to next character to draw
  713. float scaleFactor = fontSize/font.baseSize; // Character quad scaling factor
  714. // Word/character wrapping mechanism variables
  715. enum { MEASURE_STATE = 0, DRAW_STATE = 1 };
  716. int state = wordWrap? MEASURE_STATE : DRAW_STATE;
  717. int startLine = -1; // Index where to begin drawing (where a line begins)
  718. int endLine = -1; // Index where to stop drawing (where a line ends)
  719. int lastk = -1; // Holds last value of the character position
  720. for (int i = 0, k = 0; i < length; i++, k++)
  721. {
  722. // Get next codepoint from byte string and glyph index in font
  723. int codepointByteCount = 0;
  724. int codepoint = GetNextCodepoint(&text[i], &codepointByteCount);
  725. int index = GetGlyphIndex(font, codepoint);
  726. // NOTE: Normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
  727. // but we need to draw all of the bad bytes using the '?' symbol moving one byte
  728. if (codepoint == 0x3f) codepointByteCount = 1;
  729. i += (codepointByteCount - 1);
  730. int glyphWidth = 0;
  731. if (codepoint != '\n')
  732. {
  733. glyphWidth = (font.chars[index].advanceX == 0)?
  734. (int)(font.recs[index].width*scaleFactor + spacing):
  735. (int)(font.chars[index].advanceX*scaleFactor + spacing);
  736. }
  737. // NOTE: When wordWrap is ON we first measure how much of the text we can draw before going outside of the rec container
  738. // We store this info in startLine and endLine, then we change states, draw the text between those two variables
  739. // and change states again and again recursively until the end of the text (or until we get outside of the container).
  740. // When wordWrap is OFF we don't need the measure state so we go to the drawing state immediately
  741. // and begin drawing on the next line before we can get outside the container.
  742. if (state == MEASURE_STATE)
  743. {
  744. // TODO: There are multiple types of spaces in UNICODE, maybe it's a good idea to add support for more
  745. // Ref: http://jkorpela.fi/chars/spaces.html
  746. if ((codepoint == ' ') || (codepoint == '\t') || (codepoint == '\n')) endLine = i;
  747. if ((textOffsetX + glyphWidth + 1) >= rec.width)
  748. {
  749. endLine = (endLine < 1)? i : endLine;
  750. if (i == endLine) endLine -= codepointByteCount;
  751. if ((startLine + codepointByteCount) == endLine) endLine = (i - codepointByteCount);
  752. state = !state;
  753. }
  754. else if ((i + 1) == length)
  755. {
  756. endLine = i;
  757. state = !state;
  758. }
  759. else if (codepoint == '\n') state = !state;
  760. if (state == DRAW_STATE)
  761. {
  762. textOffsetX = 0;
  763. i = startLine;
  764. glyphWidth = 0;
  765. // Save character position when we switch states
  766. int tmp = lastk;
  767. lastk = k - 1;
  768. k = tmp;
  769. }
  770. }
  771. else
  772. {
  773. if (codepoint == '\n')
  774. {
  775. if (!wordWrap)
  776. {
  777. textOffsetY += (int)((font.baseSize + font.baseSize/2)*scaleFactor);
  778. textOffsetX = 0;
  779. }
  780. }
  781. else
  782. {
  783. if (!wordWrap && ((textOffsetX + glyphWidth + 1) >= rec.width))
  784. {
  785. textOffsetY += (int)((font.baseSize + font.baseSize/2)*scaleFactor);
  786. textOffsetX = 0;
  787. }
  788. // When text overflows rectangle height limit, just stop drawing
  789. if ((textOffsetY + (int)(font.baseSize*scaleFactor)) > rec.height) break;
  790. // Draw selection background
  791. bool isGlyphSelected = false;
  792. if ((selectStart >= 0) && (k >= selectStart) && (k < (selectStart + selectLength)))
  793. {
  794. DrawRectangleRec((Rectangle){ rec.x + textOffsetX - 1, rec.y + textOffsetY, glyphWidth, (int)((float)font.baseSize*scaleFactor) }, selectBackTint);
  795. isGlyphSelected = true;
  796. }
  797. // Draw current chracter glyph
  798. if ((codepoint != ' ') && (codepoint != '\t'))
  799. {
  800. DrawTexturePro(font.texture, font.recs[index],
  801. (Rectangle){ rec.x + textOffsetX + font.chars[index].offsetX*scaleFactor,
  802. rec.y + textOffsetY + font.chars[index].offsetY*scaleFactor,
  803. font.recs[index].width*scaleFactor, font.recs[index].height*scaleFactor },
  804. (Vector2){ 0, 0 }, 0.0f, (!isGlyphSelected)? tint : selectTint);
  805. }
  806. }
  807. if (wordWrap && (i == endLine))
  808. {
  809. textOffsetY += (int)((font.baseSize + font.baseSize/2)*scaleFactor);
  810. textOffsetX = 0;
  811. startLine = endLine;
  812. endLine = -1;
  813. glyphWidth = 0;
  814. k = lastk;
  815. state = !state;
  816. }
  817. }
  818. textOffsetX += glyphWidth;
  819. }
  820. }
  821. // Measure string width for default font
  822. int MeasureText(const char *text, int fontSize)
  823. {
  824. Vector2 vec = { 0.0f, 0.0f };
  825. // Check if default font has been loaded
  826. if (GetFontDefault().texture.id != 0)
  827. {
  828. int defaultFontSize = 10; // Default Font chars height in pixel
  829. if (fontSize < defaultFontSize) fontSize = defaultFontSize;
  830. int spacing = fontSize/defaultFontSize;
  831. vec = MeasureTextEx(GetFontDefault(), text, (float)fontSize, (float)spacing);
  832. }
  833. return (int)vec.x;
  834. }
  835. // Measure string size for Font
  836. Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing)
  837. {
  838. int len = strlen(text);
  839. int tempLen = 0; // Used to count longer text line num chars
  840. int lenCounter = 0;
  841. float textWidth = 0.0f;
  842. float tempTextWidth = 0.0f; // Used to count longer text line width
  843. float textHeight = (float)font.baseSize;
  844. float scaleFactor = fontSize/(float)font.baseSize;
  845. int letter = 0; // Current character
  846. int index = 0; // Index position in sprite font
  847. for (int i = 0; i < len; i++)
  848. {
  849. lenCounter++;
  850. int next = 0;
  851. letter = GetNextCodepoint(&text[i], &next);
  852. index = GetGlyphIndex(font, letter);
  853. // NOTE: normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
  854. // but we need to draw all of the bad bytes using the '?' symbol so to not skip any we set next = 1
  855. if (letter == 0x3f) next = 1;
  856. i += next - 1;
  857. if (letter != '\n')
  858. {
  859. if (font.chars[index].advanceX != 0) textWidth += font.chars[index].advanceX;
  860. else textWidth += (font.recs[index].width + font.chars[index].offsetX);
  861. }
  862. else
  863. {
  864. if (tempTextWidth < textWidth) tempTextWidth = textWidth;
  865. lenCounter = 0;
  866. textWidth = 0;
  867. textHeight += ((float)font.baseSize*1.5f); // NOTE: Fixed line spacing of 1.5 lines
  868. }
  869. if (tempLen < lenCounter) tempLen = lenCounter;
  870. }
  871. if (tempTextWidth < textWidth) tempTextWidth = textWidth;
  872. Vector2 vec = { 0 };
  873. vec.x = tempTextWidth*scaleFactor + (float)((tempLen - 1)*spacing); // Adds chars spacing to measure
  874. vec.y = textHeight*scaleFactor;
  875. return vec;
  876. }
  877. // Returns index position for a unicode character on spritefont
  878. int GetGlyphIndex(Font font, int codepoint)
  879. {
  880. #define TEXT_CHARACTER_NOTFOUND 63 // Character: '?'
  881. #define UNORDERED_CHARSET
  882. #if defined(UNORDERED_CHARSET)
  883. int index = TEXT_CHARACTER_NOTFOUND;
  884. for (int i = 0; i < font.charsCount; i++)
  885. {
  886. if (font.chars[i].value == codepoint)
  887. {
  888. index = i;
  889. break;
  890. }
  891. }
  892. return index;
  893. #else
  894. return (codepoint - 32);
  895. #endif
  896. }
  897. //----------------------------------------------------------------------------------
  898. // Text strings management functions
  899. //----------------------------------------------------------------------------------
  900. // Copy one string to another, returns bytes copied
  901. int TextCopy(char *dst, const char *src)
  902. {
  903. int bytes = 0;
  904. if (dst != NULL)
  905. {
  906. while (*src != '\0')
  907. {
  908. *dst = *src;
  909. dst++;
  910. src++;
  911. bytes++;
  912. }
  913. *dst = '\0';
  914. }
  915. return bytes;
  916. }
  917. // Check if two text string are equal
  918. // REQUIRES: strcmp()
  919. bool TextIsEqual(const char *text1, const char *text2)
  920. {
  921. bool result = false;
  922. if (strcmp(text1, text2) == 0) result = true;
  923. return result;
  924. }
  925. // Get text length in bytes, check for \0 character
  926. unsigned int TextLength(const char *text)
  927. {
  928. unsigned int length = 0;
  929. while (*text++) length++;
  930. return length;
  931. }
  932. // Formatting of text with variables to 'embed'
  933. // WARNING: String returned will expire after this function is called MAX_TEXTFORMAT_BUFFERS times
  934. const char *TextFormat(const char *text, ...)
  935. {
  936. #define MAX_TEXTFORMAT_BUFFERS 4
  937. // We create an array of buffers so strings don't expire until MAX_TEXTFORMAT_BUFFERS invocations
  938. static char buffers[MAX_TEXTFORMAT_BUFFERS][MAX_TEXT_BUFFER_LENGTH] = { 0 };
  939. static int index = 0;
  940. char *currentBuffer = buffers[index];
  941. va_list args;
  942. va_start(args, text);
  943. vsprintf(currentBuffer, text, args);
  944. va_end(args);
  945. index += 1; // Move to next buffer for next function call
  946. if (index >= MAX_TEXTFORMAT_BUFFERS) index = 0;
  947. return currentBuffer;
  948. }
  949. // Get a piece of a text string
  950. // REQUIRES: strlen()
  951. const char *TextSubtext(const char *text, int position, int length)
  952. {
  953. static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
  954. int textLength = strlen(text);
  955. if (position >= textLength)
  956. {
  957. position = textLength - 1;
  958. length = 0;
  959. }
  960. if (length >= textLength) length = textLength;
  961. for (int c = 0 ; c < length ; c++)
  962. {
  963. *(buffer + c) = *(text + position);
  964. text++;
  965. }
  966. *(buffer + length) = '\0';
  967. return buffer;
  968. }
  969. // Replace text string
  970. // REQUIRES: strlen(), strstr(), strncpy(), strcpy()
  971. // WARNING: Internally allocated memory must be freed by the user (if return != NULL)
  972. char *TextReplace(char *text, const char *replace, const char *by)
  973. {
  974. char *result;
  975. char *insertPoint; // Next insert point
  976. char *temp; // Temp pointer
  977. int replaceLen; // Replace string length of (the string to remove)
  978. int byLen; // Replacement length (the string to replace replace by)
  979. int lastReplacePos; // Distance between replace and end of last replace
  980. int count; // Number of replacements
  981. // Sanity checks and initialization
  982. if (!text || !replace) return NULL;
  983. replaceLen = strlen(replace);
  984. if (replaceLen == 0) return NULL; // Empty replace causes infinite loop during count
  985. if (!by) by = ""; // Replace by nothing if not provided
  986. byLen = strlen(by);
  987. // Count the number of replacements needed
  988. insertPoint = text;
  989. for (count = 0; (temp = strstr(insertPoint, replace)); count++) insertPoint = temp + replaceLen;
  990. // Allocate returning string and point temp to it
  991. temp = result = RL_MALLOC(strlen(text) + (byLen - replaceLen)*count + 1);
  992. if (!result) return NULL; // Memory could not be allocated
  993. // First time through the loop, all the variable are set correctly from here on,
  994. // temp points to the end of the result string
  995. // insertPoint points to the next occurrence of replace in text
  996. // text points to the remainder of text after "end of replace"
  997. while (count--)
  998. {
  999. insertPoint = strstr(text, replace);
  1000. lastReplacePos = insertPoint - text;
  1001. temp = strncpy(temp, text, lastReplacePos) + lastReplacePos;
  1002. temp = strcpy(temp, by) + byLen;
  1003. text += lastReplacePos + replaceLen; // Move to next "end of replace"
  1004. }
  1005. // Copy remaind text part after replacement to result (pointed by moving temp)
  1006. strcpy(temp, text);
  1007. return result;
  1008. }
  1009. // Insert text in a specific position, moves all text forward
  1010. // REQUIRES: strlen(), strcpy(), strtok()
  1011. // WARNING: Allocated memory should be manually freed
  1012. char *TextInsert(const char *text, const char *insert, int position)
  1013. {
  1014. int textLen = strlen(text);
  1015. int insertLen = strlen(insert);
  1016. char *result = (char *)RL_MALLOC(textLen + insertLen + 1);
  1017. for (int i = 0; i < position; i++) result[i] = text[i];
  1018. for (int i = position; i < insertLen + position; i++) result[i] = insert[i];
  1019. for (int i = (insertLen + position); i < (textLen + insertLen); i++) result[i] = text[i];
  1020. result[textLen + insertLen] = '\0'; // Make sure text string is valid!
  1021. return result;
  1022. }
  1023. // Join text strings with delimiter
  1024. // REQUIRES: strcat()
  1025. const char *TextJoin(const char **textList, int count, const char *delimiter)
  1026. {
  1027. static char text[MAX_TEXT_BUFFER_LENGTH] = { 0 };
  1028. memset(text, 0, MAX_TEXT_BUFFER_LENGTH);
  1029. int totalLength = 0;
  1030. int delimiterLen = strlen(delimiter);
  1031. for (int i = 0; i < count; i++)
  1032. {
  1033. int textListLength = strlen(textList[i]);
  1034. // Make sure joined text could fit inside MAX_TEXT_BUFFER_LENGTH
  1035. if ((totalLength + textListLength) < MAX_TEXT_BUFFER_LENGTH)
  1036. {
  1037. strcat(text, textList[i]);
  1038. totalLength += textListLength;
  1039. if ((delimiterLen > 0) && (i < (count - 1)))
  1040. {
  1041. strcat(text, delimiter);
  1042. totalLength += delimiterLen;
  1043. }
  1044. }
  1045. }
  1046. return text;
  1047. }
  1048. // Split string into multiple strings
  1049. const char **TextSplit(const char *text, char delimiter, int *count)
  1050. {
  1051. // NOTE: Current implementation returns a copy of the provided string with '\0' (string end delimiter)
  1052. // inserted between strings defined by "delimiter" parameter. No memory is dynamically allocated,
  1053. // all used memory is static... it has some limitations:
  1054. // 1. Maximum number of possible split strings is set by TEXTSPLIT_MAX_SUBSTRINGS_COUNT
  1055. // 2. Maximum size of text to split is TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH
  1056. static const char *result[TEXTSPLIT_MAX_SUBSTRINGS_COUNT] = { NULL };
  1057. static char buffer[TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH] = { 0 };
  1058. memset(buffer, 0, TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH);
  1059. result[0] = buffer;
  1060. int counter = 0;
  1061. if (text != NULL)
  1062. {
  1063. counter = 1;
  1064. // Count how many substrings we have on text and point to every one
  1065. for (int i = 0; i < TEXTSPLIT_MAX_TEXT_BUFFER_LENGTH; i++)
  1066. {
  1067. buffer[i] = text[i];
  1068. if (buffer[i] == '\0') break;
  1069. else if (buffer[i] == delimiter)
  1070. {
  1071. buffer[i] = '\0'; // Set an end of string at this point
  1072. result[counter] = buffer + i + 1;
  1073. counter++;
  1074. if (counter == TEXTSPLIT_MAX_SUBSTRINGS_COUNT) break;
  1075. }
  1076. }
  1077. }
  1078. *count = counter;
  1079. return result;
  1080. }
  1081. // Append text at specific position and move cursor!
  1082. // REQUIRES: strcpy()
  1083. void TextAppend(char *text, const char *append, int *position)
  1084. {
  1085. strcpy(text + *position, append);
  1086. *position += strlen(append);
  1087. }
  1088. // Find first text occurrence within a string
  1089. // REQUIRES: strstr()
  1090. int TextFindIndex(const char *text, const char *find)
  1091. {
  1092. int position = -1;
  1093. char *ptr = strstr(text, find);
  1094. if (ptr != NULL) position = ptr - text;
  1095. return position;
  1096. }
  1097. // Get upper case version of provided string
  1098. // REQUIRES: toupper()
  1099. const char *TextToUpper(const char *text)
  1100. {
  1101. static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
  1102. for (int i = 0; i < MAX_TEXT_BUFFER_LENGTH; i++)
  1103. {
  1104. if (text[i] != '\0') buffer[i] = (char)toupper(text[i]);
  1105. else { buffer[i] = '\0'; break; }
  1106. }
  1107. return buffer;
  1108. }
  1109. // Get lower case version of provided string
  1110. // REQUIRES: tolower()
  1111. const char *TextToLower(const char *text)
  1112. {
  1113. static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
  1114. for (int i = 0; i < MAX_TEXT_BUFFER_LENGTH; i++)
  1115. {
  1116. if (text[i] != '\0') buffer[i] = (char)tolower(text[i]);
  1117. else { buffer[i] = '\0'; break; }
  1118. }
  1119. return buffer;
  1120. }
  1121. // Get Pascal case notation version of provided string
  1122. // REQUIRES: toupper()
  1123. const char *TextToPascal(const char *text)
  1124. {
  1125. static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
  1126. buffer[0] = (char)toupper(text[0]);
  1127. for (int i = 1, j = 1; i < MAX_TEXT_BUFFER_LENGTH; i++, j++)
  1128. {
  1129. if (text[j] != '\0')
  1130. {
  1131. if (text[j] != '_') buffer[i] = text[j];
  1132. else
  1133. {
  1134. j++;
  1135. buffer[i] = (char)toupper(text[j]);
  1136. }
  1137. }
  1138. else { buffer[i] = '\0'; break; }
  1139. }
  1140. return buffer;
  1141. }
  1142. // Get integer value from text
  1143. // NOTE: This function replaces atoi() [stdlib.h]
  1144. int TextToInteger(const char *text)
  1145. {
  1146. int value = 0;
  1147. int sign = 1;
  1148. if ((text[0] == '+') || (text[0] == '-'))
  1149. {
  1150. if (text[0] == '-') sign = -1;
  1151. text++;
  1152. }
  1153. for (int i = 0; ((text[i] >= '0') && (text[i] <= '9')); ++i) value = value*10 + (int)(text[i] - '0');
  1154. return value*sign;
  1155. }
  1156. // Encode text codepoint into utf8 text (memory must be freed!)
  1157. char *TextToUtf8(int *codepoints, int length)
  1158. {
  1159. // We allocate enough memory fo fit all possible codepoints
  1160. // NOTE: 5 bytes for every codepoint should be enough
  1161. char *text = (char *)calloc(length*5, 1);
  1162. const char *utf8 = NULL;
  1163. int size = 0;
  1164. for (int i = 0, bytes = 0; i < length; i++)
  1165. {
  1166. utf8 = CodepointToUtf8(codepoints[i], &bytes);
  1167. strncpy(text + size, utf8, bytes);
  1168. size += bytes;
  1169. }
  1170. // Resize memory to text length + string NULL terminator
  1171. text = RL_REALLOC(text, size + 1);
  1172. return text;
  1173. }
  1174. // Get all codepoints in a string, codepoints count returned by parameters
  1175. int *GetCodepoints(const char *text, int *count)
  1176. {
  1177. static int codepoints[MAX_TEXT_UNICODE_CHARS] = { 0 };
  1178. memset(codepoints, 0, MAX_TEXT_UNICODE_CHARS*sizeof(int));
  1179. int bytesProcessed = 0;
  1180. int textLength = strlen(text);
  1181. int codepointsCount = 0;
  1182. for (int i = 0; i < textLength; codepointsCount++)
  1183. {
  1184. codepoints[codepointsCount] = GetNextCodepoint(text + i, &bytesProcessed);
  1185. i += bytesProcessed;
  1186. }
  1187. *count = codepointsCount;
  1188. return codepoints;
  1189. }
  1190. // Returns total number of characters(codepoints) in a UTF8 encoded text, until '\0' is found
  1191. // NOTE: If an invalid UTF8 sequence is encountered a '?'(0x3f) codepoint is counted instead
  1192. int GetCodepointsCount(const char *text)
  1193. {
  1194. unsigned int len = 0;
  1195. char *ptr = (char *)&text[0];
  1196. while (*ptr != '\0')
  1197. {
  1198. int next = 0;
  1199. int letter = GetNextCodepoint(ptr, &next);
  1200. if (letter == 0x3f) ptr += 1;
  1201. else ptr += next;
  1202. len++;
  1203. }
  1204. return len;
  1205. }
  1206. // Returns next codepoint in a UTF8 encoded text, scanning until '\0' is found
  1207. // When a invalid UTF8 byte is encountered we exit as soon as possible and a '?'(0x3f) codepoint is returned
  1208. // Total number of bytes processed are returned as a parameter
  1209. // NOTE: the standard says U+FFFD should be returned in case of errors
  1210. // but that character is not supported by the default font in raylib
  1211. // TODO: optimize this code for speed!!
  1212. int GetNextCodepoint(const char *text, int *bytesProcessed)
  1213. {
  1214. /*
  1215. UTF8 specs from https://www.ietf.org/rfc/rfc3629.txt
  1216. Char. number range | UTF-8 octet sequence
  1217. (hexadecimal) | (binary)
  1218. --------------------+---------------------------------------------
  1219. 0000 0000-0000 007F | 0xxxxxxx
  1220. 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
  1221. 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
  1222. 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1223. */
  1224. // NOTE: on decode errors we return as soon as possible
  1225. int code = 0x3f; // Codepoint (defaults to '?')
  1226. int octet = (unsigned char)(text[0]); // The first UTF8 octet
  1227. *bytesProcessed = 1;
  1228. if (octet <= 0x7f)
  1229. {
  1230. // Only one octet (ASCII range x00-7F)
  1231. code = text[0];
  1232. }
  1233. else if ((octet & 0xe0) == 0xc0)
  1234. {
  1235. // Two octets
  1236. // [0]xC2-DF [1]UTF8-tail(x80-BF)
  1237. unsigned char octet1 = text[1];
  1238. if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *bytesProcessed = 2; return code; } // Unexpected sequence
  1239. if ((octet >= 0xc2) && (octet <= 0xdf))
  1240. {
  1241. code = ((octet & 0x1f) << 6) | (octet1 & 0x3f);
  1242. *bytesProcessed = 2;
  1243. }
  1244. }
  1245. else if ((octet & 0xf0) == 0xe0)
  1246. {
  1247. // Three octets
  1248. unsigned char octet1 = text[1];
  1249. unsigned char octet2 = '\0';
  1250. if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *bytesProcessed = 2; return code; } // Unexpected sequence
  1251. octet2 = text[2];
  1252. if ((octet2 == '\0') || ((octet2 >> 6) != 2)) { *bytesProcessed = 3; return code; } // Unexpected sequence
  1253. /*
  1254. [0]xE0 [1]xA0-BF [2]UTF8-tail(x80-BF)
  1255. [0]xE1-EC [1]UTF8-tail [2]UTF8-tail(x80-BF)
  1256. [0]xED [1]x80-9F [2]UTF8-tail(x80-BF)
  1257. [0]xEE-EF [1]UTF8-tail [2]UTF8-tail(x80-BF)
  1258. */
  1259. if (((octet == 0xe0) && !((octet1 >= 0xa0) && (octet1 <= 0xbf))) ||
  1260. ((octet == 0xed) && !((octet1 >= 0x80) && (octet1 <= 0x9f)))) { *bytesProcessed = 2; return code; }
  1261. if ((octet >= 0xe0) && (0 <= 0xef))
  1262. {
  1263. code = ((octet & 0xf) << 12) | ((octet1 & 0x3f) << 6) | (octet2 & 0x3f);
  1264. *bytesProcessed = 3;
  1265. }
  1266. }
  1267. else if ((octet & 0xf8) == 0xf0)
  1268. {
  1269. // Four octets
  1270. if (octet > 0xf4) return code;
  1271. unsigned char octet1 = text[1];
  1272. unsigned char octet2 = '\0';
  1273. unsigned char octet3 = '\0';
  1274. if ((octet1 == '\0') || ((octet1 >> 6) != 2)) { *bytesProcessed = 2; return code; } // Unexpected sequence
  1275. octet2 = text[2];
  1276. if ((octet2 == '\0') || ((octet2 >> 6) != 2)) { *bytesProcessed = 3; return code; } // Unexpected sequence
  1277. octet3 = text[3];
  1278. if ((octet3 == '\0') || ((octet3 >> 6) != 2)) { *bytesProcessed = 4; return code; } // Unexpected sequence
  1279. /*
  1280. [0]xF0 [1]x90-BF [2]UTF8-tail [3]UTF8-tail
  1281. [0]xF1-F3 [1]UTF8-tail [2]UTF8-tail [3]UTF8-tail
  1282. [0]xF4 [1]x80-8F [2]UTF8-tail [3]UTF8-tail
  1283. */
  1284. if (((octet == 0xf0) && !((octet1 >= 0x90) && (octet1 <= 0xbf))) ||
  1285. ((octet == 0xf4) && !((octet1 >= 0x80) && (octet1 <= 0x8f)))) { *bytesProcessed = 2; return code; } // Unexpected sequence
  1286. if (octet >= 0xf0)
  1287. {
  1288. code = ((octet & 0x7) << 18) | ((octet1 & 0x3f) << 12) | ((octet2 & 0x3f) << 6) | (octet3 & 0x3f);
  1289. *bytesProcessed = 4;
  1290. }
  1291. }
  1292. if (code > 0x10ffff) code = 0x3f; // Codepoints after U+10ffff are invalid
  1293. return code;
  1294. }
  1295. // Encode codepoint into utf8 text (char array length returned as parameter)
  1296. RLAPI const char *CodepointToUtf8(int codepoint, int *byteLength)
  1297. {
  1298. static char utf8[6] = { 0 };
  1299. int length = 0;
  1300. if (codepoint <= 0x7f)
  1301. {
  1302. utf8[0] = (char)codepoint;
  1303. length = 1;
  1304. }
  1305. else if (codepoint <= 0x7ff)
  1306. {
  1307. utf8[0] = (char)(((codepoint >> 6) & 0x1f) | 0xc0);
  1308. utf8[1] = (char)((codepoint & 0x3f) | 0x80);
  1309. length = 2;
  1310. }
  1311. else if (codepoint <= 0xffff)
  1312. {
  1313. utf8[0] = (char)(((codepoint >> 12) & 0x0f) | 0xe0);
  1314. utf8[1] = (char)(((codepoint >> 6) & 0x3f) | 0x80);
  1315. utf8[2] = (char)((codepoint & 0x3f) | 0x80);
  1316. length = 3;
  1317. }
  1318. else if (codepoint <= 0x10ffff)
  1319. {
  1320. utf8[0] = (char)(((codepoint >> 18) & 0x07) | 0xf0);
  1321. utf8[1] = (char)(((codepoint >> 12) & 0x3f) | 0x80);
  1322. utf8[2] = (char)(((codepoint >> 6) & 0x3f) | 0x80);
  1323. utf8[3] = (char)((codepoint & 0x3f) | 0x80);
  1324. length = 4;
  1325. }
  1326. *byteLength = length;
  1327. return utf8;
  1328. }
  1329. //----------------------------------------------------------------------------------
  1330. //----------------------------------------------------------------------------------
  1331. // Module specific Functions Definition
  1332. //----------------------------------------------------------------------------------
  1333. #if defined(SUPPORT_FILEFORMAT_FNT)
  1334. // Load a BMFont file (AngelCode font file)
  1335. static Font LoadBMFont(const char *fileName)
  1336. {
  1337. #define MAX_BUFFER_SIZE 256
  1338. Font font = { 0 };
  1339. font.texture.id = 0;
  1340. char buffer[MAX_BUFFER_SIZE] = { 0 };
  1341. char *searchPoint = NULL;
  1342. int fontSize = 0;
  1343. int texWidth = 0;
  1344. int texHeight = 0;
  1345. char texFileName[129];
  1346. int charsCount = 0;
  1347. int base = 0; // Useless data
  1348. FILE *fntFile = NULL;
  1349. fntFile = fopen(fileName, "rt");
  1350. if (fntFile == NULL)
  1351. {
  1352. TraceLog(LOG_WARNING, "[%s] FNT file could not be opened", fileName);
  1353. return font;
  1354. }
  1355. // NOTE: We skip first line, it contains no useful information
  1356. fgets(buffer, MAX_BUFFER_SIZE, fntFile);
  1357. //searchPoint = strstr(buffer, "size");
  1358. //sscanf(searchPoint, "size=%i", &fontSize);
  1359. fgets(buffer, MAX_BUFFER_SIZE, fntFile);
  1360. searchPoint = strstr(buffer, "lineHeight");
  1361. sscanf(searchPoint, "lineHeight=%i base=%i scaleW=%i scaleH=%i", &fontSize, &base, &texWidth, &texHeight);
  1362. TraceLog(LOG_DEBUG, "[%s] Font size: %i", fileName, fontSize);
  1363. TraceLog(LOG_DEBUG, "[%s] Font texture scale: %ix%i", fileName, texWidth, texHeight);
  1364. fgets(buffer, MAX_BUFFER_SIZE, fntFile);
  1365. searchPoint = strstr(buffer, "file");
  1366. sscanf(searchPoint, "file=\"%128[^\"]\"", texFileName);
  1367. TraceLog(LOG_DEBUG, "[%s] Font texture filename: %s", fileName, texFileName);
  1368. fgets(buffer, MAX_BUFFER_SIZE, fntFile);
  1369. searchPoint = strstr(buffer, "count");
  1370. sscanf(searchPoint, "count=%i", &charsCount);
  1371. TraceLog(LOG_DEBUG, "[%s] Font num chars: %i", fileName, charsCount);
  1372. // Compose correct path using route of .fnt file (fileName) and texFileName
  1373. char *texPath = NULL;
  1374. char *lastSlash = NULL;
  1375. lastSlash = strrchr(fileName, '/');
  1376. if (lastSlash == NULL)
  1377. {
  1378. lastSlash = strrchr(fileName, '\\');
  1379. }
  1380. // NOTE: We need some extra space to avoid memory corruption on next allocations!
  1381. texPath = RL_MALLOC(strlen(fileName) - strlen(lastSlash) + strlen(texFileName) + 4);
  1382. // NOTE: strcat() and strncat() required a '\0' terminated string to work!
  1383. *texPath = '\0';
  1384. strncat(texPath, fileName, strlen(fileName) - strlen(lastSlash) + 1);
  1385. strncat(texPath, texFileName, strlen(texFileName));
  1386. TraceLog(LOG_DEBUG, "[%s] Font texture loading path: %s", fileName, texPath);
  1387. Image imFont = LoadImage(texPath);
  1388. if (imFont.format == UNCOMPRESSED_GRAYSCALE)
  1389. {
  1390. // Convert image to GRAYSCALE + ALPHA, using the mask as the alpha channel
  1391. ImageAlphaMask(&imFont, imFont);
  1392. for (int p = 0; p < (imFont.width*imFont.height*2); p += 2) ((unsigned char *)(imFont.data))[p] = 0xff;
  1393. }
  1394. font.texture = LoadTextureFromImage(imFont);
  1395. RL_FREE(texPath);
  1396. // Fill font characters info data
  1397. font.baseSize = fontSize;
  1398. font.charsCount = charsCount;
  1399. font.chars = (CharInfo *)RL_MALLOC(charsCount*sizeof(CharInfo));
  1400. font.recs = (Rectangle *)RL_MALLOC(charsCount*sizeof(Rectangle));
  1401. int charId, charX, charY, charWidth, charHeight, charOffsetX, charOffsetY, charAdvanceX;
  1402. for (int i = 0; i < charsCount; i++)
  1403. {
  1404. fgets(buffer, MAX_BUFFER_SIZE, fntFile);
  1405. sscanf(buffer, "char id=%i x=%i y=%i width=%i height=%i xoffset=%i yoffset=%i xadvance=%i",
  1406. &charId, &charX, &charY, &charWidth, &charHeight, &charOffsetX, &charOffsetY, &charAdvanceX);
  1407. // Get character rectangle in the font atlas texture
  1408. font.recs[i] = (Rectangle){ (float)charX, (float)charY, (float)charWidth, (float)charHeight };
  1409. // Save data properly in sprite font
  1410. font.chars[i].value = charId;
  1411. font.chars[i].offsetX = charOffsetX;
  1412. font.chars[i].offsetY = charOffsetY;
  1413. font.chars[i].advanceX = charAdvanceX;
  1414. // Fill character image data from imFont data
  1415. font.chars[i].image = ImageFromImage(imFont, font.recs[i]);
  1416. }
  1417. UnloadImage(imFont);
  1418. fclose(fntFile);
  1419. if (font.texture.id == 0)
  1420. {
  1421. UnloadFont(font);
  1422. font = GetFontDefault();
  1423. }
  1424. else TraceLog(LOG_INFO, "[%s] Font loaded successfully", fileName);
  1425. return font;
  1426. }
  1427. #endif