/
font.kt
1465 lines (1277 loc) · 63.8 KB
/
font.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package imgui
import glm_.*
import kool.bufferBig
import kool.free
import glm_.vec2.Vec2
import glm_.vec2.Vec2i
import glm_.vec2.operators.div
import glm_.vec4.Vec4
import imgui.ImGui.io
import imgui.ImGui.style
import imgui.internal.fileLoadToCharArray
import imgui.internal.isBlankA
import imgui.internal.isBlankW
import imgui.internal.upperPowerOfTwo
import imgui.stb.*
import org.lwjgl.stb.*
import org.lwjgl.stb.STBRectPack.stbrp_pack_rects
import org.lwjgl.stb.STBTruetype.*
import org.lwjgl.system.MemoryUtil
import uno.convert.decode85
import uno.kotlin.buffers.isNotEmpty
import uno.stb.stb
import unsigned.toULong
import java.nio.ByteBuffer
import kotlin.math.floor
class FontConfig {
/** TTF/OTF data */
var fontData = charArrayOf()
/** TTF/OTF data size */
var fontDataSize = 0
lateinit var fontDataBuffer: ByteBuffer
/** TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself). */
var fontDataOwnedByAtlas = true
/** Index of font within TTF/OTF file */
var fontNo = 0
/** Size in pixels for rasterizer (more or less maps to the resulting font height). */
var sizePixels = 0f
/** Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. */
var oversample = Vec2i(3, 1)
/** Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default
* font. If enabled, you can set OversampleH/V to 1. */
var pixelSnapH = false
/** Extra spacing (in pixels) between glyphs. Only X axis is supported for now. */
var glyphExtraSpacing = Vec2()
/** Offset all glyphs from this font input. */
var glyphOffset = Vec2()
/** Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated
* list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. */
var glyphRanges = intArrayOf()
/** Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font */
var glyphMinAdvanceX = 0f
/** Maximum AdvanceX for glyphs */
var glyphMaxAdvanceX = Float.MAX_VALUE
/** Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons +
* Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights. */
var mergeMode = false
/** Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one. */
var rasterizerFlags = 0x00
/** Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them
* more readable. */
var rasterizerMultiply = 1f
// [Internal]
/** Name (strictly to ease debugging) */
var name = ""
var dstFont: Font? = null
}
class FontGlyph {
/** 0x0000..0xFFFF */
var codepoint = NUL
/** Distance to next character (= data from font + FontConfig.glyphExtraSpacing.x baked in) */
var advanceX = 0f
// Glyph corners
var x0 = 0f
var y0 = 0f
var x1 = 0f
var y1 = 0f
// Texture coordinates
var u0 = 0f
var v0 = 0f
var u1 = 0f
var v1 = 0f
infix fun put(other: FontGlyph) {
codepoint = other.codepoint
advanceX = other.advanceX
x0 = other.x0
y0 = other.y0
x1 = other.x1
y1 = other.y1
u0 = other.u0
v0 = other.v0
u1 = other.u1
v1 = other.v1
}
}
/** Load and rasterize multiple TTF/OTF fonts into a same texture.
* Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering.
* We also add custom graphic data into the texture that serves for ImGui.
* 1. (Optional) Call AddFont*** functions. If you don't call any, the default font will be loaded for you.
* 2. Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.
* 3. Upload the pixels data into a texture within your graphics system.
* 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you
* during rendering to identify the texture.
* IMPORTANT: If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist
* up until the ImFont is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data.
* We only copy the pointer, not the data. */
class FontAtlas {
fun addFont(fontCfg: FontConfig): Font {
assert(!locked) { "Cannot modify a locked FontAtlas between NewFrame() and EndFrame/Render()!" }
assert(fontCfg.fontData.isNotEmpty())
assert(fontCfg.sizePixels > 0f)
// Create new font
if (!fontCfg.mergeMode)
fonts += Font()
else
assert(fonts.isNotEmpty()) { " When using MergeMode make sure that a font has already been added before. You can use io.fonts.addFontDefault to add the default imgui font. " }
configData.add(fontCfg)
if (fontCfg.dstFont == null)
fontCfg.dstFont = fonts.last()
if (!fontCfg.fontDataOwnedByAtlas)
fontCfg.fontDataOwnedByAtlas = true
// memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize) TODO check, same object?
// Invalidate texture
clearTexData()
return fontCfg.dstFont!!
}
/** Load embedded ProggyClean.ttf at size 13, disable oversampling */
fun addFontDefault(): Font {
val fontCfg = FontConfig()
fontCfg.oversample put 1
fontCfg.pixelSnapH = true
return addFontDefault(fontCfg)
}
fun addFontDefault(fontCfg: FontConfig): Font {
if (fontCfg.name.isEmpty()) fontCfg.name = "ProggyClean.ttf, 13px"
if (fontCfg.sizePixels <= 0f) fontCfg.sizePixels = 13f
val ttfCompressedBase85 = proggyCleanTtfCompressedDataBase85
val glyphRanges = fontCfg.glyphRanges.takeIf { it.isNotEmpty() } ?: glyphRanges.default
return addFontFromMemoryCompressedBase85TTF(ttfCompressedBase85, fontCfg.sizePixels, fontCfg, glyphRanges)
.apply { displayOffset.y = 1f }
}
fun addFontFromFileTTF(filename: String, sizePixels: Float, fontCfg: FontConfig = FontConfig(),
glyphRanges: IntArray = intArrayOf()): Font? {
assert(!locked) { "Cannot modify a locked FontAtlas between NewFrame() and EndFrame/Render()!" }
val chars = fileLoadToCharArray(filename) ?: return null
if (fontCfg.name.isEmpty())
// Store a short copy of filename into into the font name for convenience
fontCfg.name = "${filename.substringAfterLast('/')}, %.0fpx".format(style.locale, sizePixels)
return addFontFromMemoryTTF(chars, sizePixels, fontCfg, glyphRanges)
}
/** Note: Transfer ownership of 'ttfData' to FontAtlas! Will be deleted after build(). Set fontCfg.fontDataOwnedByAtlas
* to false to keep ownership. */
fun addFontFromMemoryTTF(fontData: CharArray, sizePixels: Float, fontCfg: FontConfig = FontConfig(),
glyphRanges: IntArray = intArrayOf()): Font {
assert(!locked) { "Cannot modify a locked FontAtlas between NewFrame() and EndFrame/Render()!" }
assert(fontCfg.fontData.isEmpty())
fontCfg.fontData = fontData
fontCfg.fontDataBuffer = bufferBig(fontData.size).apply { fontData.forEachIndexed { i, c -> this[i] = c.b } }
fontCfg.sizePixels = sizePixels
if (glyphRanges.isNotEmpty())
fontCfg.glyphRanges = glyphRanges
return addFont(fontCfg)
}
/** @param compressedFontData still owned by caller. Compress with binary_to_compressed_c.cpp. */
fun addFontFromMemoryCompressedTTF(compressedFontData: CharArray, sizePixels: Float, fontCfg: FontConfig = FontConfig(),
glyphRanges: IntArray = intArrayOf()): Font {
val bufDecompressedData = stb.decompress(compressedFontData)
assert(fontCfg.fontData.isEmpty())
fontCfg.fontDataOwnedByAtlas = true
return addFontFromMemoryTTF(bufDecompressedData, sizePixels, fontCfg, glyphRanges)
}
/** @param compressedFontDataBase85 still owned by caller. Compress with binary_to_compressed_c.cpp with -base85
* paramaeter */
fun addFontFromMemoryCompressedBase85TTF(compressedFontDataBase85: String, sizePixels: Float, fontCfg: FontConfig = FontConfig(),
glyphRanges: IntArray = intArrayOf()): Font {
val compressedTtf = decode85(compressedFontDataBase85)
return addFontFromMemoryCompressedTTF(compressedTtf, sizePixels, fontCfg, glyphRanges)
}
/** Clear input data (all FontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used
* to build the texture and fonts. */
fun clearInputData() {
assert(!locked) { "Cannot modify a locked FontAtlas between NewFrame() and EndFrame/Render()!" }
configData.filter { it.fontData.isNotEmpty() && it.fontDataOwnedByAtlas }.forEach {
it.fontData = charArrayOf()
}
// When clearing this we lose access to the font name and other information used to build the font.
fonts.filter { configData.contains(it.configData[0]) }.forEach {
it.configData.clear()
it.configDataCount = 0
}
configData.clear()
customRects.clear()
customRectIds.fill(-1)
}
/** Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory. */
fun clearTexData() {
assert(!locked) { "Cannot modify a locked FontAtlas between NewFrame() and EndFrame/Render()!" }
texPixelsAlpha8?.free()
texPixelsAlpha8 = null
texPixelsRGBA32?.free()
texPixelsRGBA32 = null
}
/** Clear output font data (glyphs storage, UV coordinates). */
fun clearFonts() {
assert(!locked) { "Cannot modify a locked FontAtlas between NewFrame() and EndFrame/Render()!" }
for (font in fonts) font.clearOutputData()
fonts.clear()
}
/** Clear all input and output. ~ destroy */
fun clear() {
assert(!locked) { "Cannot modify a locked FontAtlas between NewFrame() and EndFrame/Render()!" }
clearInputData()
clearTexData()
clearFonts()
stbClear()
}
/* Build atlas, retrieve pixel data.
User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine).
Then store your texture handle with setTexID().ClearInputData
RGBA32 format is provided for convenience and compatibility, but note that unless you use CustomRect to draw
color data, the RGB pixels emitted from Fonts will all be white (~75% of waste).
Pitch = Width * BytesPerPixels */
/** Build pixels data. This is automatically for you by the GetTexData*** functions. */
private fun build() {
assert(!locked) { "Cannot modify a locked FontAtlas between NewFrame() and EndFrame/Render()!" }
buildWithStbTrueType()
}
val isBuilt: Boolean
get() = fonts.size > 0 && (texPixelsAlpha8 != null || texPixelsRGBA32 != null)
/** 1 byte per-pixel */
fun getTexDataAsAlpha8(): Triple<ByteBuffer, Vec2i, Int> {
// Build atlas on demand
if (texPixelsAlpha8 == null) {
if (configData.isEmpty())
addFontDefault()
build()
}
return Triple(texPixelsAlpha8!!, texSize, 1)
}
/** 4 bytes-per-pixel */
fun getTexDataAsRGBA32(): Triple<ByteBuffer, Vec2i, Int> {
/* Convert to RGBA32 format on demand
Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp */
if (texPixelsRGBA32 == null) {
val (pixels, _, _) = getTexDataAsAlpha8()
if (pixels.isNotEmpty()) {
texPixelsRGBA32 = bufferBig(texSize.x * texSize.y * 4)
val dst = texPixelsRGBA32!!
for (n in 0 until pixels.size) {
dst[n * 4] = 255.b
dst[n * 4 + 1] = 255.b
dst[n * 4 + 2] = 255.b
dst[n * 4 + 3] = pixels[n]
}
}
}
return Triple(texPixelsRGBA32!!, texSize, 4)
}
// Helpers to build glyph ranges from text data. Feed your application strings/characters to it then call BuildRanges().
// struct GlyphRangesBuilder
// {
// ImVector<unsigned char> UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used)
// GlyphRangesBuilder() { UsedChars.resize(0x10000 / 8); memset(UsedChars.Data, 0, 0x10000 / 8); }
// bool GetBit(int n) { return (UsedChars[n >> 3] & (1 << (n & 7))) != 0; }
// void SetBit(int n) { UsedChars[n >> 3] |= 1 << (n & 7); } // Set bit 'c' in the array
// void AddChar(ImWchar c) { SetBit(c); } // Add character
// IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added)
// IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext
// IMGUI_API void BuildRanges(ImVector<ImWchar>* out_ranges); // Output new ranges
// };
// //-----------------------------------------------------------------------------
// +// ImFontAtlas::GlyphRangesBuilder
// +//-----------------------------------------------------------------------------
// +
// +void ImFontAtlas::GlyphRangesBuilder::AddText(const char* text, const char* text_end)
// +{
// while (text_end ? (text < text_end) : *text)
// {
// unsigned int c = 0;
// int c_len = ImTextCharFromUtf8(&c, text, text_end);
// text += c_len;
// if (c_len == 0)
// break;
// if (c < 0x10000)
// AddChar((ImWchar)c);
// }
// +}
// +
// +void ImFontAtlas::GlyphRangesBuilder::AddRanges(const ImWchar* ranges)
// +{
// for (; ranges[0]; ranges += 2)
// for (ImWchar c = ranges[0]; c <= ranges[1]; c++)
// AddChar(c);
// +}
// +
// +void ImFontAtlas::GlyphRangesBuilder::BuildRanges(ImVector<ImWchar>* out_ranges)
// +{
// for (int n = 0; n < 0x10000; n++)
// if (GetBit(n))
// {
// out_ranges->push_back((ImWchar)n);
// while (n < 0x10000 && GetBit(n + 1))
// n++;
// out_ranges->push_back((ImWchar)n);
// }
// out_ranges->push_back(0);
// +}
//-------------------------------------------
// Custom Rectangles/Glyphs API
//-------------------------------------------
/** You can request arbitrary rectangles to be packed into the atlas, for your own purposes. After calling build(),
* you can query the rectangle position and render your pixels.
* You can also request your rectangles to be mapped as font glyph (given a font + Unicode point),
* so you can render e.g. custom colorful icons and use them as regular glyphs. */
class CustomRect {
/** Input, User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data. */
var id = 0xFFFFFFFF.i
/** Input, Desired rectangle width */
var width = 0
/** Input, Desired rectangle height */
var height = 0
/** Output, Packed width position in Atlas */
var x = 0xFFFF
/** Output, Packed height position in Atlas */
var y = 0xFFFF
/** Input, For custom font glyphs only (ID<0x10000): glyph xadvance */
var glyphAdvanceX = 0f
/** Input, For custom font glyphs only (ID<0x10000): glyph display offset */
var glyphOffset = Vec2()
/** Input, For custom font glyphs only (ID<0x10000): target font */
var font: Font? = null
val isPacked get() = x != 0xFFFF
}
/** Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and DrawList */
fun addCustomRectRegular(id: Int, width: Int, height: Int): Int {
assert(id.toULong() >= 0x10000 && width in 0..0xFFFF && height in 0..0xFFFF)
val r = CustomRect()
r.id = id
r.width = width
r.height = height
customRects.add(r)
return customRects.lastIndex
}
/** Id needs to be < 0x10000 to register a rectangle to map into a specific font. */
fun addCustomRectFontGlyph(font: Font, id: Int, width: Int, height: Int, advanceX: Float, offset: Vec2 = Vec2()): Int {
assert(width in 1..0xFFFF && height in 1..0xFFFF)
val r = CustomRect()
r.id = id
r.width = width
r.height = height
r.glyphAdvanceX = advanceX
r.glyphOffset = offset
r.font = font
customRects.add(r)
return customRects.lastIndex // Return index
}
fun getCustomRectByIndex(index: Int) = customRects.getOrNull(index)
// Internals
fun calcCustomRectUV(rect: CustomRect, outUvMin: Vec2, outUvMax: Vec2) {
assert(texSize allGreaterThan 0) { "Font atlas needs to be built before we can calculate UV coordinates" }
assert(rect.isPacked) { "Make sure the rectangle has been packed" }
outUvMin.put(rect.x.f * texUvScale.x, rect.y.f * texUvScale.y)
outUvMax.put((rect.x + rect.width).f * texUvScale.x, (rect.y + rect.height).f * texUvScale.y)
}
fun getMouseCursorTexData(cursor: MouseCursor, outOffset: Vec2, outSize: Vec2, outUv: Array<Vec2>): Boolean {
if (cursor == MouseCursor.None) return false
if (flags has FontAtlasFlag.NoMouseCursors) return false
assert(customRectIds[0] != -1)
val r = customRects[customRectIds[0]]
assert(r.id == DefaultTexData.id)
val pos = DefaultTexData.cursorDatas[cursor.i][0] + Vec2(r.x, r.y)
val size = DefaultTexData.cursorDatas[cursor.i][1]
outSize put size
outOffset put DefaultTexData.cursorDatas[cursor.i][2]
// JVM border
outUv[0] = pos * texUvScale
outUv[1] = (pos + size) * texUvScale
pos.x += DefaultTexData.wHalf + 1
// JVM fill
outUv[2] = pos * texUvScale
outUv[3] = (pos + size) * texUvScale
return true
}
//-------------------------------------------
// Members
//-------------------------------------------
enum class FontAtlasFlag {
/** Don't round the height to next power of two */
NoPowerOfTwoHeight,
/** Don't build software mouse cursors into the atlas */
NoMouseCursors;
val i = 1 shl ordinal
}
infix fun Int.has(flag: FontAtlasFlag) = and(flag.i) != 0
infix fun Int.hasnt(flag: FontAtlasFlag) = and(flag.i) == 0
/** Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert. */
var locked = false
/** Build flags (see ImFontAtlasFlags_) */
var flags: FontAtlasFlags = 0
/** User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you
during rendering via the DrawCmd structure. */
var texId: TextureID = 0
/** 1 component per pixel, each component is unsigned 8-bit. Total size = texSize.x * texSize.y */
var texPixelsAlpha8: ByteBuffer? = null
/** 4 component per pixel, each component is unsigned 8-bit. Total size = texSize.x * texSize.y * 4 */
var texPixelsRGBA32: ByteBuffer? = null
/** Texture size calculated during Build(). */
var texSize = Vec2i()
/** Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have
* texture size restrictions you may want to increase texture width to decrease height. */
var texDesiredWidth = 0
/** Padding between glyphs within texture in pixels. Defaults to 1. */
var texGlyphPadding = 1
/** = (1.0f/TexWidth, 1.0f/TexHeight) */
var texUvScale = Vec2()
/** Texture coordinates to a white pixel */
var texUvWhitePixel = Vec2()
/** Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use
* ImGui::PushFont()/PopFont() to change the current font. */
val fonts = ArrayList<Font>()
/** Rectangles for packing custom texture data into the atlas. */
private val customRects = ArrayList<CustomRect>()
/** Internal data */
private val configData = ArrayList<FontConfig>()
/** Identifiers of custom texture rectangle used by FontAtlas/DrawList */
private val customRectIds = intArrayOf(-1)
private fun customRectCalcUV(rect: CustomRect, outUvMin: Vec2, outUvMax: Vec2) {
assert(texSize.x > 0 && texSize.y > 0) { "Font atlas needs to be built before we can calculate UV coordinates" }
assert(rect.isPacked) { "Make sure the rectangle has been packed " }
outUvMin.put(rect.x / texSize.x, rect.y / texSize.y)
outUvMax.put((rect.x + rect.width) / texSize.x, (rect.y + rect.height) / texSize.y)
}
// ImFontAtlas internals
fun buildWithStbTrueType(): Boolean {
assert(configData.isNotEmpty())
buildRegisterDefaultCustomRects()
texId = 0
texSize put 0
texUvScale put 0f
texUvWhitePixel put 0f
clearTexData()
val inRange = IntArray(2)
// Count glyphs/ranges
var totalGlyphsCount = 0
var totalRangesCount = 0
for (cfg in configData) {
if (cfg.glyphRanges.isEmpty()) cfg.glyphRanges = glyphRanges.default
var i = 0
inRange[0] = cfg.glyphRanges[i++]
inRange[1] = cfg.glyphRanges[i++]
while (inRange[0] != 0 && inRange[1] != 0) {
totalGlyphsCount += (inRange[1] - inRange[0]) + 1
inRange[0] = cfg.glyphRanges.getOrElse(i++, { 0 })
inRange[1] = cfg.glyphRanges.getOrElse(i++, { 0 })
totalRangesCount++
}
}
/* We need a width for the skyline algorithm. Using a dumb heuristic here to decide of width. User can override
texDesiredWidth and texGlyphPadding if they wish. Width doesn't really matter much, but some API/GPU have
texture size limitations and increasing width can decrease height. */
texSize.x = when {
texDesiredWidth > 0 -> texDesiredWidth
totalGlyphsCount > 4000 -> 4096
totalGlyphsCount > 2000 -> 2048
totalGlyphsCount > 1000 -> 1024
else -> 512
}
texSize.y = 0
// Start packing
val maxTexHeight = 1024 * 32
val spc = STBTTPackContext.create()
if (!stbtt_PackBegin(spc, null, texSize.x, maxTexHeight, 0, texGlyphPadding, MemoryUtil.NULL))
return false
/* Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have
small values). */
buildPackCustomRects(spc.packInfo)
// Initialize font information (so we can error without any cleanup)
class FontTempBuildData {
var fontInfo = STBTTFontinfo.create()
lateinit var rects: STBRPRect.Buffer
var rectsCount = 0
lateinit var ranges: STBTTPackRange.Buffer
var rangesCount = 0
}
val tmpArray = Array(configData.size, { FontTempBuildData() })
configData.forEachIndexed { input, cfg ->
val tmp = tmpArray[input]
assert(with(cfg.dstFont!!) { !isLoaded || containerAtlas == this@FontAtlas })
val fontOffset = stbtt_GetFontOffsetForIndex(cfg.fontDataBuffer, cfg.fontNo)
assert(fontOffset >= 0) { "FontData is incorrect, or FontNo cannot be found." }
if (!stbtt_InitFont(tmp.fontInfo, cfg.fontDataBuffer, fontOffset)) {
texSize put 0 // Reset output on failure
return false
}
}
// Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
var (bufPackedcharsN, bufRectsN, bufRangesN) = Triple(0, 0, 0)
val bufPackedchars = STBTTPackedchar.calloc(totalGlyphsCount)
val bufRects = STBRPRect.calloc(totalGlyphsCount)
val bufRanges = STBTTPackRange.calloc(totalRangesCount)
/* First font pass: pack all glyphs (no rendering at this point, we are working with rectangles in an
infinitely tall texture at this point) */
configData.forEachIndexed { input, cfg ->
val tmp = tmpArray[input]
// Setup ranges
var fontGlyphsCount = 0
var fontRangesCount = 0
var i = 0
inRange[0] = cfg.glyphRanges[i++]
inRange[1] = cfg.glyphRanges[i++]
while (inRange[0] != 0 && inRange[1] != 0) {
fontGlyphsCount += (inRange[1] - inRange[0]) + 1
inRange[0] = cfg.glyphRanges.getOrElse(i++, { 0 })
inRange[1] = cfg.glyphRanges.getOrElse(i++, { 0 })
fontRangesCount++
}
var address = bufRanges.address() + bufRangesN * STBTTPackRange.SIZEOF
tmp.ranges = STBTTPackRange.create(address, fontRangesCount)
tmp.rangesCount = fontRangesCount
bufRangesN += fontRangesCount
i = 0
while (i < fontRangesCount) {
inRange[0] = cfg.glyphRanges[i * 2]
inRange[1] = cfg.glyphRanges[i * 2 + 1]
val range = tmp.ranges[i++]
range.fontSize = cfg.sizePixels
range.firstUnicodeCodepointInRange = inRange[0]
range.numChars = (inRange[1] - inRange[0]) + 1
address = bufPackedchars.address() + bufPackedcharsN * STBTTPackedchar.SIZEOF
range.chardataForRange = STBTTPackedchar.create(address, range.numChars)
bufPackedcharsN += range.numChars
}
// Gather the sizes of all rectangle we need
tmp.rects = STBRPRect.create(bufRects.address() + bufRectsN * STBRPRect.SIZEOF, fontGlyphsCount)
tmp.rectsCount = fontGlyphsCount
bufRectsN += fontGlyphsCount
stbtt_PackSetOversampling(spc, cfg.oversample)
val n = stbtt_PackFontRangesGatherRects(spc, tmp.fontInfo, tmp.ranges, tmp.rects)
assert(n == fontGlyphsCount)
/* Detect missing glyphs and replace them with a zero-sized box instead of relying on the default glyphs
This allows us merging overlapping icon fonts more easily.
JVM, this provokes a jvm crash, probably it will work with the custom stb */
// var rectI = 0
// for (rangeI in 0 until tmp.rangesCount)
// for (charI in 0 until tmp.ranges[rangeI].numChars) {
// if (stbtt_FindGlyphIndex(tmp.fontInfo, tmp.ranges[rangeI].firstUnicodeCodepointInRange + charI) == 0)
// tmp.rects[rectI].apply {
//// w = 0
//// h = 0
// }
// rectI++
// }
// Pack
stbrp_pack_rects(spc.packInfo, tmp.rects) // fuck, Omar modified his stb_rect_pack.h, we shall also have our own?
/* Extend texture height
Also mark missing glyphs as non-packed so we don't attempt to render into them */
for (r in tmp.rects) {
if (tmp.rects[i].w == 0 && tmp.rects[i].h == 0)
tmp.rects[i].wasPacked = false
if (r.wasPacked)
texSize.y = glm.max(texSize.y, r.y + r.h)
}
}
assert(bufRectsN == totalGlyphsCount)
assert(bufPackedcharsN == totalGlyphsCount)
assert(bufRangesN == totalRangesCount)
// Create texture
texSize.y = if (flags has FontAtlasFlag.NoPowerOfTwoHeight) texSize.y + 1 else texSize.y.upperPowerOfTwo
texUvScale = 1f / Vec2(texSize)
texPixelsAlpha8 = bufferBig(texSize.x * texSize.y)
spc.pixels = texPixelsAlpha8!!
spc.height = texSize.y
// Second pass: render characters
for (input in 0 until configData.size) {
val cfg = configData[input]
val tmp = tmpArray[input]
stbtt_PackSetOversampling(spc, cfg.oversample)
stbtt_PackFontRangesRenderIntoRects(spc, tmp.fontInfo, tmp.ranges, tmp.rects)
if (cfg.rasterizerMultiply != 1f) {
val multiplyTable = buildMultiplyCalcLookupTable(cfg.rasterizerMultiply)
for (r in tmp.rects)
if (r.wasPacked)
buildMultiplyRectAlpha8(multiplyTable, spc.pixels, r, spc.strideInBytes)
}
// tmp.rects.free()
}
// End packing
stbtt_PackEnd(spc)
// bufRects.free() TODO check why crashes, container is null
// Third pass: setup ImFont and glyphs for runtime
for (input in 0 until configData.size) {
val cfg = configData[input]
val tmp = tmpArray[input]
// We can have multiple input fonts writing into a same destination font (when using MergeMode=true)
val dstFont = cfg.dstFont!!
if (cfg.mergeMode)
dstFont.buildLookupTable()
val fontScale = stbtt_ScaleForPixelHeight(tmp.fontInfo, cfg.sizePixels)
val (unscaledAscent, unscaledDescent, unscaledLineGap) = stbtt_GetFontVMetrics(tmp.fontInfo)
val ascent = floor(unscaledAscent * fontScale + if (unscaledAscent > 0f) +1 else -1)
val descent = floor(unscaledDescent * fontScale + if (unscaledDescent > 0f) +1 else -1)
buildSetupFont(dstFont, cfg, ascent, descent)
val fontOffX = cfg.glyphOffset.x
val fontOffY = cfg.glyphOffset.y + (dstFont.ascent + 0.5f).i.f
tmp.ranges.forEach { range ->
for (charIdx in 0 until range.numChars) {
val pc = range.chardataForRange[charIdx]
if (pc.x0 == 0 && pc.x1 == 0 && pc.y0 == 0 && pc.y1 == 0) continue
val codepoint = range.firstUnicodeCodepointInRange + charIdx
if (cfg.mergeMode && dstFont.findGlyphNoFallback(codepoint) != null) continue
val charAdvanceXOrg = pc.xAdvance
val charAdvanceXMod = glm.clamp(charAdvanceXOrg, cfg.glyphMinAdvanceX, cfg.glyphMaxAdvanceX)
var charOffX = fontOffX
if (charAdvanceXOrg != charAdvanceXMod) {
val t = (charAdvanceXMod - charAdvanceXOrg) * 0.5f
charOffX += if (cfg.pixelSnapH) t.i.f else t
}
val q = STBTTAlignedQuad.create()
stbtt_GetPackedQuad(range.chardataForRange, texSize, charIdx, Vec2(), q, false)
dstFont.addGlyph(codepoint, q.x0 + charOffX, q.y0 + fontOffY,
q.x1 + charOffX, q.y1 + fontOffY, q.s0, q.t0, q.s1, q.t1, charAdvanceXMod)
}
}
}
// Cleanup temporaries
bufPackedchars.free()
bufRanges.free()
buildFinish()
return true
}
fun buildRegisterDefaultCustomRects() {
if (customRectIds[0] >= 0) return
customRectIds[0] = when {
flags hasnt FontAtlasFlag.NoMouseCursors -> addCustomRectRegular(DefaultTexData.id, DefaultTexData.wHalf * 2 + 1, DefaultTexData.h)
else -> addCustomRectRegular(DefaultTexData.id, 2, 2)
}
}
fun buildSetupFont(font: Font, fontConfig: FontConfig, ascent: Float, descent: Float) {
if (!fontConfig.mergeMode) with(font) {
containerAtlas = this@FontAtlas
configData.add(fontConfig) // TODO replace [0] if not empty?
configDataCount = 0
fontSize = fontConfig.sizePixels
this.ascent = ascent
this.descent = descent
glyphs.clear()
metricsTotalSurface = 0
}
font.configDataCount++
}
fun buildPackCustomRects(packContext: STBRPContext) {
val userRects = customRects
// We expect at least the default custom rects to be registered, else something went wrong.
assert(userRects.isNotEmpty())
val packRects = STBRPRect.calloc(userRects.size) // calloc -> all 0
for (i in userRects.indices) {
packRects[i].w = userRects[i].width
packRects[i].h = userRects[i].height
}
stbrp_pack_rects(packContext, packRects)
for (i in userRects.indices)
if (packRects[i].wasPacked) {
userRects[i].x = packRects[i].x
userRects[i].y = packRects[i].y
assert(packRects[i].w == userRects[i].width && packRects[i].h == userRects[i].height)
texSize.y = glm.max(texSize.y, packRects[i].y + packRects[i].h)
}
}
fun buildFinish() {
// Render into our custom data block
buildRenderDefaultTexData()
// Register custom rectangle glyphs
for (r in customRects) {
val font = r.font
if (font == null || r.id > 0x10000) continue
assert(font.containerAtlas === this)
val uv0 = Vec2()
val uv1 = Vec2()
calcCustomRectUV(r, uv0, uv1)
font.addGlyph(r.id, r.glyphOffset.x, r.glyphOffset.y, r.glyphOffset.x + r.width, r.glyphOffset.y + r.height,
uv0.x, uv0.y, uv1.x, uv1.y, r.glyphAdvanceX)
}
// Build all fonts lookup tables
fonts.filter { it.dirtyLookupTables }.forEach { it.buildLookupTable() }
}
fun buildRenderDefaultTexData() {
assert(customRectIds[0] >= 0 && texPixelsAlpha8 != null)
val r = customRects[customRectIds[0]]
assert(r.id == DefaultTexData.id && r.isPacked)
val w = texSize.x
if (flags hasnt FontAtlasFlag.NoMouseCursors) {
// Render/copy pixels
assert(r.width == DefaultTexData.wHalf * 2 + 1 && r.height == DefaultTexData.h)
var n = 0
for (y in 0 until DefaultTexData.h)
for (x in 0 until DefaultTexData.wHalf) {
val offset0 = r.x + x + (r.y + y) * w
val offset1 = offset0 + DefaultTexData.wHalf + 1
texPixelsAlpha8!![offset0] = if (DefaultTexData.pixels[n] == '.') 0xFF.b else 0x00.b
texPixelsAlpha8!![offset1] = if (DefaultTexData.pixels[n] == 'X') 0xFF.b else 0x00.b
n++
}
} else {
assert(r.width == 2 && r.height == 2)
val offset = r.x.i + r.y.i * w
with(texPixelsAlpha8!!) {
put(offset + w + 1, 0xFF.b)
put(offset + w, 0xFF.b)
put(offset + 1, 0xFF.b)
put(offset, 0xFF.b)
}
}
texUvWhitePixel = (Vec2(r.x, r.y) + 0.5f) * texUvScale
}
fun buildMultiplyCalcLookupTable(inBrightenFactor: Float) = CharArray(256) {
val value = (it * inBrightenFactor).i
(if (value > 255) 255 else (value and 0xFF)).c
}
fun buildMultiplyRectAlpha8(table: CharArray, pixels: ByteBuffer, rect: STBRPRect, stride: Int) {
var ptr = rect.x + rect.y * stride
var j = rect.h
while (j > 0) {
for (i in 0 until rect.w)
pixels[ptr + i] = table[pixels[ptr + i].i].b
j--
ptr += stride
}
}
/* A work of art lies ahead! (. = white layer, X = black layer, others are blank)
The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes. */
object DefaultTexData {
val wHalf = 108
val h = 27
val id = 0x80000000.i
val pixels = run {
val s = StringBuilder()
s += "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX "
s += "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X "
s += "--- -XXX.XXX- X...X - X...X -X....X - X....X- X..X "
s += "X - X.X - X.....X - X.....X -X...X - X...X- X..X "
s += "XX - X.X -X.......X- X.......X -X..X.X - X.X..X- X..X "
s += "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X- X..XXX "
s += "X..X - X.X - X.X - X.X -XX X.X - X.X XX- X..X..XXX "
s += "X...X - X.X - X.X - XX X.X XX - X.X - X.X - X..X..X..XX "
s += "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X - X..X..X..X.X "
s += "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X -XXX X..X..X..X..X"
s += "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X -X..XX........X..X"
s += "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X -X...X...........X"
s += "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X - X..............X"
s += "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X - X.............X"
s += "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X - X.............X"
s += "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X - X............X"
s += "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX - X...........X "
s += "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------- X..........X "
s += "X.X X..X - -X.......X- X.......X - XX XX - - X..........X "
s += "XX X..X - - X.....X - X.....X - X.X X.X - - X........X "
s += " X..X - X...X - X...X - X..X X..X - - X........X "
s += " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - - XXXXXXXXXX "
s += "------------ - X - X -X.....................X- ------------------"
s += " ----------------------------------- X...XXXXXXXXXXXXX...X - "
s += " - X..X X..X - "
s += " - X.X X.X - "
s += " - XX XX - "
s.toString().toCharArray()
}
val cursorDatas = arrayOf(
// Pos ........ Size ......... Offset ......
arrayOf(Vec2(0, 3), Vec2(12, 19), Vec2(0)), // MouseCursor.Arrow
arrayOf(Vec2(13, 0), Vec2(7, 16), Vec2(1, 8)), // MouseCursor.TextInput
arrayOf(Vec2(31, 0), Vec2(23), Vec2(11)), // MouseCursor.Move
arrayOf(Vec2(21, 0), Vec2(9, 23), Vec2(4, 11)), // MouseCursor.ResizeNS
arrayOf(Vec2(55, 18), Vec2(23, 9), Vec2(11, 4)), // MouseCursor.ResizeEW
arrayOf(Vec2(73, 0), Vec2(17), Vec2(8)), // MouseCursor.ResizeNESW
arrayOf(Vec2(55, 0), Vec2(17), Vec2(8)), // MouseCursor.ResizeNWSE
arrayOf(Vec2(91, 0), Vec2(17, 22), Vec2(5, 0))) // ImGuiMouseCursor_Hand
}
}
/** Font runtime data and rendering
* ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or
* GetTexDataAsRGBA32(). */
class Font {
// Members: Hot ~62/78 bytes
/** <user set>, Height of characters, set during loading (don't change after loading) */
var fontSize = 0f
/** Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() */
var scale = 1f
/** Offset font rendering by xx pixels */
var displayOffset = Vec2(0f, 0f)
/** All glyphs. */
val glyphs = ArrayList<FontGlyph>()
/** Sparse. Glyphs.xAdvance in a directly indexable way (more cache-friendly, for CalcTextSize functions which are
often bottleneck in large UI). */
val indexAdvanceX = ArrayList<Float>()
/** Sparse. Index glyphs by Unicode code-point. */
val indexLookup = ArrayList<Int>()
/** == FindGlyph(FontFallbackChar) */
var fallbackGlyph: FontGlyph? = null
/** == FallbackGlyph.xAdvance */
var fallbackAdvanceX = 0f
/** Replacement glyph if one isn't found. Only set via SetFallbackChar() */
var fallbackChar = '?'
// Members: Cold ~18/26 bytes
/** Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. */
var configDataCount = 0
/** Pointer within ContainerAtlas->ConfigData */
var configData = ArrayList<FontConfig>()
var configDataIdx = 0
/** What we has been loaded into */
lateinit var containerAtlas: FontAtlas
/** Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] */
var ascent = 0f
var descent = 0f
var dirtyLookupTables = true
/** Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding
between glyphs) */
var metricsTotalSurface = 0
//
// // Methods
// IMGUI_API ImFont();
// IMGUI_API ~ImFont();
fun clearOutputData() {
fontSize = 0f
displayOffset = Vec2(0.0f, 1.0f)
glyphs.clear()
indexAdvanceX.clear()
indexLookup.clear()
fallbackGlyph = null
fallbackAdvanceX = 0f
configDataCount = 0
configData.clear()
// containerAtlas = NULL TODO check
ascent = 0f
descent = 0f
dirtyLookupTables = true
metricsTotalSurface = 0
}
fun buildLookupTable() {
val maxCodepoint = glyphs.map { it.codepoint.i }.max()!!
assert(glyphs.size < 0xFFFF) { "-1 is reserved" }
indexAdvanceX.clear()
indexLookup.clear()
dirtyLookupTables = false
growIndex(maxCodepoint + 1)
glyphs.forEachIndexed { i, g ->
indexAdvanceX[g.codepoint.i] = g.advanceX
indexLookup[g.codepoint.i] = i
}
// Create a glyph to handle TAB
// FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?)
if (findGlyph(' ') != null) {
if (glyphs.last().codepoint != '\t') // So we can call this function multiple times
glyphs += FontGlyph()
val tabGlyph = glyphs.last()
tabGlyph put findGlyph(' ')!!
tabGlyph.codepoint = '\t'
tabGlyph.advanceX *= 4
indexAdvanceX[tabGlyph.codepoint.i] = tabGlyph.advanceX
indexLookup[tabGlyph.codepoint.i] = glyphs.size - 1
}
fallbackGlyph = findGlyphNoFallback(fallbackChar)
fallbackAdvanceX = fallbackGlyph?.advanceX ?: 0f
for (i in 0 until maxCodepoint + 1)
if (indexAdvanceX[i] < 0f)
indexAdvanceX[i] = fallbackAdvanceX
}
fun findGlyph(c: Char) = findGlyph(c.i)
fun findGlyph(c: Int) = indexLookup.getOrNull(c)?.let { glyphs.getOrNull(it) } ?: fallbackGlyph
fun findGlyphNoFallback(c: Char) = findGlyphNoFallback(c.i)
fun findGlyphNoFallback(c: Int) = indexLookup.getOrNull(c)?.let { glyphs.getOrNull(it) }
// IMGUI_API void SetFallbackChar(ImWchar c);
fun getCharAdvance(c: Char): Float = if (c < indexAdvanceX.size) indexAdvanceX[c.i] else fallbackAdvanceX
val isLoaded get() = ::containerAtlas.isInitialized