-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
PPGeDraw.cpp
1488 lines (1293 loc) · 43.3 KB
/
PPGeDraw.cpp
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
// Copyright (c) 2012- PPSSPP Project.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 2.0 or later versions.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License 2.0 for more details.
// A copy of the GPL 2.0 should have been included with the program.
// If not, see http://www.gnu.org/licenses/
// Official git repository and contact information can be found at
// https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/.
#include <algorithm>
#include "ext/xxhash.h"
#include "Common/System/System.h"
#include "Common/Data/Color/RGBAUtil.h"
#include "Common/File/VFS/VFS.h"
#include "Common/Data/Format/ZIMLoad.h"
#include "Common/Data/Format/PNGLoad.h"
#include "Common/Data/Encoding/Utf8.h"
#include "Common/Render/TextureAtlas.h"
#include "Common/Render/Text/draw_text.h"
#include "Common/Serialize/Serializer.h"
#include "Common/Serialize/SerializeFuncs.h"
#include "Common/StringUtils.h"
#include "Core/Config.h"
#include "Common/BitScan.h"
#include "Core/HDRemaster.h"
#include "GPU/ge_constants.h"
#include "GPU/GPUState.h"
#include "GPU/GPUInterface.h"
#include "Core/FileSystems/MetaFileSystem.h"
#include "Core/Util/PPGeDraw.h"
#include "Core/HLE/sceKernel.h"
#include "Core/HLE/sceKernelMemory.h"
#include "Core/HLE/sceGe.h"
#include "Core/MemMapHelpers.h"
#include "Core/System.h"
static Atlas g_ppge_atlas;
static Draw::DrawContext *g_draw = nullptr;
static u32 atlasPtr;
static int atlasWidth;
static int atlasHeight;
static uint64_t atlasHash;
static bool atlasRequiresReset;
struct PPGeVertex {
u16_le u, v;
u32_le color;
float_le x, y, z;
};
struct PPGeRemasterVertex {
float_le u, v;
u32_le color;
float_le x, y, z;
};
static PSPPointer<PspGeListArgs> listArgs;
static u32 listArgsSize = sizeof(PspGeListArgs);
static u32 savedContextPtr;
static u32 savedContextSize = 512 * 4;
// Display list writer
static u32 dlPtr;
static u32 dlWritePtr;
static u32 dlSize = 0x10000; // should be enough for a frame of gui...
static u32 dataPtr;
static u32 dataWritePtr;
static u32 dataSize = 0x10000; // should be enough for a frame of gui...
static PSPPointer<u16_le> palette;
static u32 paletteSize = sizeof(u16) * 16;
// Vertex collector
static u32 vertexStart;
static u32 vertexCount;
// Used for formatting text
struct AtlasCharVertex
{
float x;
float y;
const AtlasChar *c;
};
struct AtlasTextMetrics
{
float x;
float y;
float maxWidth;
float lineHeight;
float scale;
int numLines;
};
typedef std::vector<AtlasCharVertex> AtlasCharLine;
typedef std::vector<AtlasCharLine> AtlasLineArray;
static AtlasCharLine char_one_line;
static AtlasLineArray char_lines;
static AtlasTextMetrics char_lines_metrics;
static bool textDrawerInited = false;
static TextDrawer *textDrawer = nullptr;
struct PPGeTextDrawerCacheKey {
bool operator < (const PPGeTextDrawerCacheKey &other) const {
if (align != other.align)
return align < other.align;
if (wrapWidth != other.wrapWidth)
return wrapWidth < other.wrapWidth;
return text < other.text;
}
std::string text;
int align;
float wrapWidth;
};
struct PPGeTextDrawerImage {
PPGeTextDrawerImage() : entry(0) {}
TextStringEntry entry;
u32 ptr;
};
static std::map<PPGeTextDrawerCacheKey, PPGeTextDrawerImage> textDrawerImages;
void PPGeSetDrawContext(Draw::DrawContext *draw) {
g_draw = draw;
}
// Overwrite the current text lines buffer so it can be drawn later.
void PPGePrepareText(std::string_view text, float x, float y, PPGeAlign align, float scale, float lineHeightScale,
int WrapType = PPGE_LINE_NONE, int wrapWidth = 0);
// These functions must be called between PPGeBegin and PPGeEnd.
// Draw currently buffered text using the state from PPGeGetTextBoundingBox() call.
// Clears the buffer and state when done.
void PPGeDrawCurrentText(u32 color = 0xFFFFFFFF);
static void PPGeDecimateTextImages(int age = 97);
void PPGeSetTexture(u32 dataAddr, int width, int height);
//only 0xFFFFFF of data is used
static void WriteCmd(u8 cmd, u32 data) {
Memory::Write_U32((cmd << 24) | (data & 0xFFFFFF), dlWritePtr);
dlWritePtr += 4;
_dbg_assert_(dlWritePtr <= dlPtr + dlSize);
}
static void WriteCmdAddrWithBase(u8 cmd, u32 addr) {
WriteCmd(GE_CMD_BASE, (addr >> 8) & 0xFF0000);
WriteCmd(cmd, addr & 0xFFFFFF);
}
/*
static void WriteCmdFloat(u8 cmd, float f) {
union {
float fl;
u32 u;
} conv;
conv.fl = f;
WriteCmd(cmd, conv.u >> 8);
}*/
static void BeginVertexData() {
vertexCount = 0;
vertexStart = dataWritePtr;
}
static void Vertex(float x, float y, float u, float v, int tw, int th, u32 color = 0xFFFFFFFF) {
if (g_RemasterMode) {
auto vtx = PSPPointer<PPGeRemasterVertex>::Create(dataWritePtr);
vtx->x = x; vtx->y = y; vtx->z = 0;
vtx->u = u * tw; vtx->v = v * th;
vtx->color = color;
dataWritePtr += (u32)vtx.ElementSize();
} else {
auto vtx = PSPPointer<PPGeVertex>::Create(dataWritePtr);
vtx->x = x; vtx->y = y; vtx->z = 0;
vtx->u = u * tw; vtx->v = v * th;
vtx->color = color;
dataWritePtr += (u32)vtx.ElementSize();
}
_dbg_assert_(dataWritePtr <= dataPtr + dataSize);
vertexCount++;
}
static void EndVertexDataAndDraw(int prim) {
_assert_msg_(vertexStart != 0, "Missing matching call to BeginVertexData()");
if (vertexCount != 0) {
NotifyMemInfo(MemBlockFlags::WRITE, vertexStart, dataWritePtr - vertexStart, "PPGe Vertex");
WriteCmdAddrWithBase(GE_CMD_VADDR, vertexStart);
WriteCmd(GE_CMD_PRIM, (prim << 16) | vertexCount);
}
vertexStart = 0;
}
bool PPGeIsFontTextureAddress(u32 addr) {
return addr == atlasPtr;
}
static u32 __PPGeDoAlloc(u32 &size, bool fromTop, const char *name) {
u32 ptr = kernelMemory.Alloc(size, fromTop, name);
// Didn't get it, try again after decimating images.
if (ptr == (u32)-1) {
PPGeDecimateTextImages(4);
PPGeImage::Decimate(4);
ptr = kernelMemory.Alloc(size, fromTop, name);
if (ptr == (u32)-1) {
return 0;
}
}
return ptr;
}
void __PPGeSetupListArgs()
{
if (listArgs.IsValid())
return;
listArgs = __PPGeDoAlloc(listArgsSize, false, "PPGe List Args");
if (listArgs.IsValid()) {
listArgs->size = 8;
if (savedContextPtr == 0)
savedContextPtr = __PPGeDoAlloc(savedContextSize, false, "PPGe Saved Context");
listArgs->context = savedContextPtr;
}
}
void __PPGeInit() {
// PPGe isn't really important for headless, and LoadZIM takes a long time.
bool skipZIM = System_GetPropertyBool(SYSPROP_SKIP_UI);
u8 *imageData[12]{};
int width[12]{};
int height[12]{};
int flags = 0;
bool loadedZIM = !skipZIM && LoadZIM("ppge_atlas.zim", width, height, &flags, imageData);
if (!skipZIM && !loadedZIM) {
ERROR_LOG(Log::sceGe, "Failed to load ppge_atlas.zim.\n\nPlace it in the directory \"assets\" under your PPSSPP directory.\n\nPPGe stuff will not be drawn.");
}
if (loadedZIM) {
size_t atlas_data_size;
if (!g_ppge_atlas.IsMetadataLoaded()) {
uint8_t *atlas_data = g_VFS.ReadFile("ppge_atlas.meta", &atlas_data_size);
if (atlas_data)
g_ppge_atlas.Load(atlas_data, atlas_data_size);
delete[] atlas_data;
}
}
u32 atlasSize = height[0] * width[0] / 2; // it's a 4-bit paletted texture in ram
atlasWidth = width[0];
atlasHeight = height[0];
dlPtr = __PPGeDoAlloc(dlSize, false, "PPGe Display List");
dataPtr = __PPGeDoAlloc(dataSize, false, "PPGe Vertex Data");
__PPGeSetupListArgs();
atlasPtr = atlasSize == 0 ? 0 : __PPGeDoAlloc(atlasSize, false, "PPGe Atlas Texture");
palette = __PPGeDoAlloc(paletteSize, false, "PPGe Texture Palette");
// Generate 16-greyscale palette. All PPGe graphics are greyscale so we can use a tiny paletted texture.
for (int i = 0; i < 16; i++) {
int val = i;
palette[i] = (val << 12) | 0xFFF;
}
NotifyMemInfo(MemBlockFlags::WRITE, palette.ptr, 16 * sizeof(u16_le), "PPGe Palette");
const u32_le *imagePtr = (u32_le *)imageData[0];
u8 *ramPtr = atlasPtr == 0 ? nullptr : (u8 *)Memory::GetPointerRange(atlasPtr, atlasSize);
// Palettize to 4-bit, the easy way.
for (int i = 0; i < width[0] * height[0] / 2; i++) {
// Each pixel is 16 bits, so this loads two pixels.
u32 c = imagePtr[i];
// It's white anyway, so we only look at one channel of each pixel.
int a1 = (c & 0x0000000F) >> 0;
int a2 = (c & 0x000F0000) >> 16;
u8 cval = (a2 << 4) | a1;
ramPtr[i] = cval;
}
if (atlasPtr != 0) {
atlasHash = XXH3_64bits(ramPtr, atlasSize);
NotifyMemInfo(MemBlockFlags::WRITE, atlasPtr, atlasSize, "PPGe Atlas");
}
free(imageData[0]);
// We can't create it here, because Android needs it on the right thread.
// Avoid creating ever on headless just to be safe.
textDrawerInited = PSP_CoreParameter().headLess;
textDrawer = nullptr;
textDrawerImages.clear();
atlasRequiresReset = false;
INFO_LOG(Log::sceGe, "PPGe drawing library initialized. DL: %08x Data: %08x Atlas: %08x (%i) Args: %08x",
dlPtr, dataPtr, atlasPtr, atlasSize, listArgs.ptr);
}
void __PPGeDoState(PointerWrap &p)
{
auto s = p.Section("PPGeDraw", 1, 4);
if (!s)
return;
Do(p, atlasPtr);
Do(p, atlasWidth);
Do(p, atlasHeight);
Do(p, palette);
// If the atlas the save state was created with differs from the current one, reload.
uint64_t savedHash = atlasHash;
if (s >= 4) {
Do(p, savedHash);
} else {
// Memory was already updated by this point, so check directly.
if (atlasPtr != 0) {
savedHash = XXH3_64bits(Memory::GetPointerRange(atlasPtr, atlasWidth * atlasHeight / 2), atlasWidth * atlasHeight / 2);
} else {
savedHash ^= 1;
}
}
atlasRequiresReset = savedHash != atlasHash;
Do(p, savedContextPtr);
Do(p, savedContextSize);
if (s == 1) {
listArgs = 0;
} else {
Do(p, listArgs);
}
if (s >= 3) {
uint32_t sz = (uint32_t)textDrawerImages.size();
Do(p, sz);
switch (p.mode) {
case PointerWrap::MODE_READ:
textDrawerImages.clear();
for (uint32_t i = 0; i < sz; ++i) {
// We only care about the pointers, so we can free them. We'll decimate right away.
PPGeTextDrawerCacheKey key{ StringFromFormat("__savestate__%d", i), -1, -1 };
textDrawerImages[key] = PPGeTextDrawerImage{};
Do(p, textDrawerImages[key].ptr);
}
break;
default:
for (const auto &im : textDrawerImages) {
Do(p, im.second.ptr);
}
break;
}
} else {
textDrawerImages.clear();
}
Do(p, dlPtr);
Do(p, dlWritePtr);
Do(p, dlSize);
Do(p, dataPtr);
Do(p, dataWritePtr);
Do(p, dataSize);
Do(p, vertexStart);
Do(p, vertexCount);
Do(p, char_lines);
Do(p, char_lines_metrics);
}
void __PPGeShutdown()
{
if (atlasPtr)
kernelMemory.Free(atlasPtr);
if (dataPtr)
kernelMemory.Free(dataPtr);
if (dlPtr)
kernelMemory.Free(dlPtr);
if (listArgs.IsValid())
kernelMemory.Free(listArgs.ptr);
if (savedContextPtr)
kernelMemory.Free(savedContextPtr);
if (palette)
kernelMemory.Free(palette.ptr);
atlasPtr = 0;
dataPtr = 0;
dlPtr = 0;
savedContextPtr = 0;
listArgs = 0;
delete textDrawer;
textDrawer = nullptr;
for (auto im : textDrawerImages)
kernelMemory.Free(im.second.ptr);
textDrawerImages.clear();
}
void PPGeBegin()
{
if (!dlPtr)
return;
// Reset write pointers to start of command and data buffers.
dlWritePtr = dlPtr;
dataWritePtr = dataPtr;
// Set up the correct states for UI drawing
WriteCmd(GE_CMD_OFFSETADDR, 0);
WriteCmd(GE_CMD_ALPHABLENDENABLE, 1);
WriteCmd(GE_CMD_BLENDMODE, 2 | (3 << 4));
WriteCmd(GE_CMD_ALPHATESTENABLE, 0);
WriteCmd(GE_CMD_COLORTESTENABLE, 0);
WriteCmd(GE_CMD_ZTESTENABLE, 0);
WriteCmd(GE_CMD_LIGHTINGENABLE, 0);
WriteCmd(GE_CMD_FOGENABLE, 0);
WriteCmd(GE_CMD_STENCILTESTENABLE, 0);
WriteCmd(GE_CMD_CULLFACEENABLE, 0);
WriteCmd(GE_CMD_CLEARMODE, 0); // Normal mode
WriteCmd(GE_CMD_MASKRGB, 0);
WriteCmd(GE_CMD_MASKALPHA, 0);
WriteCmd(GE_CMD_DITHERENABLE, 0);
PPGeSetDefaultTexture();
PPGeScissor(0, 0, 480, 272);
WriteCmd(GE_CMD_MINZ, 0);
WriteCmd(GE_CMD_MAXZ, 0xFFFF);
// Through mode, so we don't have to bother with matrices
if (g_RemasterMode) {
WriteCmd(GE_CMD_VERTEXTYPE, GE_VTYPE_TC_FLOAT | GE_VTYPE_COL_8888 | GE_VTYPE_POS_FLOAT | GE_VTYPE_THROUGH);
} else {
WriteCmd(GE_CMD_VERTEXTYPE, GE_VTYPE_TC_16BIT | GE_VTYPE_COL_8888 | GE_VTYPE_POS_FLOAT | GE_VTYPE_THROUGH);
}
}
void PPGeEnd()
{
if (!dlPtr)
return;
WriteCmd(GE_CMD_FINISH, 0);
WriteCmd(GE_CMD_END, 0);
// Might've come from an old savestate.
__PPGeSetupListArgs();
if (dataWritePtr > dataPtr) {
// We actually drew something
gpu->EnableInterrupts(false);
NotifyMemInfo(MemBlockFlags::WRITE, dlPtr, dlWritePtr - dlPtr, "PPGe ListCmds");
u32 list = sceGeListEnQueue(dlPtr, dlWritePtr, -1, listArgs.ptr);
DEBUG_LOG(Log::sceGe, "PPGe enqueued display list %i", list);
gpu->EnableInterrupts(true);
}
}
void PPGeScissor(int x1, int y1, int x2, int y2) {
_dbg_assert_(x1 >= 0 && x1 <= 480 && x2 >= 0 && x2 <= 480);
_dbg_assert_(y1 >= 0 && y1 <= 272 && y2 >= 0 && y2 <= 272);
WriteCmd(GE_CMD_SCISSOR1, (y1 << 10) | x1);
WriteCmd(GE_CMD_SCISSOR2, ((y2 - 1) << 10) | (x2 - 1));
}
void PPGeScissorReset() {
PPGeScissor(0, 0, 480, 272);
}
static const AtlasChar *PPGeGetChar(const AtlasFont &atlasfont, unsigned int cval)
{
const AtlasChar *c = atlasfont.getChar(cval);
if (c == NULL) {
// Try to use a replacement character, these come from the below table.
// http://unicode.org/cldr/charts/supplemental/character_fallback_substitutions.html
switch (cval) {
case 0x00A0: // NO-BREAK SPACE
case 0x2000: // EN QUAD
case 0x2001: // EM QUAD
case 0x2002: // EN SPACE
case 0x2003: // EM SPACE
case 0x2004: // THREE-PER-EM SPACE
case 0x2005: // FOUR-PER-EM SPACE
case 0x2006: // SIX-PER-EM SPACE
case 0x2007: // FIGURE SPACE
case 0x2008: // PUNCTUATION SPACE
case 0x2009: // THIN SPACE
case 0x200A: // HAIR SPACE
case 0x202F: // NARROW NO-BREAK SPACE
case 0x205F: // MEDIUM MATHEMATICAL
case 0x3000: // IDEOGRAPHIC SPACE
c = atlasfont.getChar(0x0020);
break;
default:
c = atlasfont.getChar(0xFFFD);
break;
}
if (c == NULL)
c = atlasfont.getChar('?');
}
return c;
}
// Break a single text string into mutiple lines.
static AtlasTextMetrics BreakLines(std::string_view text, const AtlasFont &atlasfont, float x, float y,
PPGeAlign align, float scale, float lineHeightScale, int wrapType, float wrapWidth, bool dryRun)
{
y += atlasfont.ascend * scale;
float sx = x, sy = y;
// TODO: Can we wrap it smartly on the screen edge?
if (wrapWidth <= 0) {
wrapWidth = 480.f;
}
// used for replacing with ellipses
float wrapCutoff = 8.0f;
const AtlasChar *dot = PPGeGetChar(atlasfont, '.');
if (dot) {
wrapCutoff = dot->wx * scale * 3.0f;
}
float threshold = sx + wrapWidth - wrapCutoff;
//const float wrapGreyZone = 2.0f; // Grey zone for punctuations at line ends
int numLines = 1;
float maxw = 0;
float lineHeight = atlasfont.height * lineHeightScale;
for (UTF8 utf(text); !utf.end(); )
{
float lineWidth = 0;
bool skipRest = false;
while (!utf.end())
{
UTF8 utfWord(utf);
float nextWidth = 0;
float spaceWidth = 0;
int numChars = 0;
bool finished = false;
while (!utfWord.end() && !finished)
{
UTF8 utfPrev = utfWord;
u32 cval = utfWord.next();
const AtlasChar *ch = PPGeGetChar(atlasfont, cval);
if (!ch) {
continue;
}
switch (cval) {
// TODO: This list of punctuation is very incomplete.
case ',':
case '.':
case ':':
case '!':
case ')':
case '?':
case 0x3001: // IDEOGRAPHIC COMMA
case 0x3002: // IDEOGRAPHIC FULL STOP
case 0x06D4: // ARABIC FULL STOP
case 0xFF01: // FULLWIDTH EXCLAMATION MARK
case 0xFF09: // FULLWIDTH RIGHT PARENTHESIS
case 0xFF1F: // FULLWIDTH QUESTION MARK
// Count this character (punctuation is so clingy), but then we're done.
++numChars;
nextWidth += ch->wx * scale;
finished = true;
break;
case ' ':
case 0x3000: // IDEOGRAPHIC SPACE
spaceWidth += ch->wx * scale;
finished = true;
break;
case '\t':
case '\r':
case '\n':
// Ignore this character and we're done.
finished = true;
break;
default:
{
// CJK characters can be wrapped more freely.
bool isCJK = (cval >= 0x1100 && cval <= 0x11FF); // Hangul Jamo.
isCJK = isCJK || (cval >= 0x2E80 && cval <= 0x2FFF); // Kangxi Radicals etc.
#if 0
isCJK = isCJK || (cval >= 0x3040 && cval <= 0x31FF); // Hiragana, Katakana, Hangul Compatibility Jamo etc.
isCJK = isCJK || (cval >= 0x3200 && cval <= 0x32FF); // CJK Enclosed
isCJK = isCJK || (cval >= 0x3300 && cval <= 0x33FF); // CJK Compatibility
isCJK = isCJK || (cval >= 0x3400 && cval <= 0x4DB5); // CJK Unified Ideographs Extension A
#else
isCJK = isCJK || (cval >= 0x3040 && cval <= 0x4DB5); // Above collapsed
#endif
isCJK = isCJK || (cval >= 0x4E00 && cval <= 0x9FBB); // CJK Unified Ideographs
isCJK = isCJK || (cval >= 0xAC00 && cval <= 0xD7AF); // Hangul Syllables
isCJK = isCJK || (cval >= 0xF900 && cval <= 0xFAD9); // CJK Compatibility Ideographs
isCJK = isCJK || (cval >= 0x20000 && cval <= 0x2A6D6); // CJK Unified Ideographs Extension B
isCJK = isCJK || (cval >= 0x2F800 && cval <= 0x2FA1D); // CJK Compatibility Supplement
if (isCJK) {
if (numChars > 0) {
utfWord = utfPrev;
finished = true;
break;
}
}
}
++numChars;
nextWidth += ch->wx * scale;
break;
}
}
bool useEllipsis = false;
if (wrapType > 0)
{
if (lineWidth + nextWidth > wrapWidth || skipRest)
{
if (wrapType & PPGE_LINE_WRAP_WORD) {
// TODO: Should check if we have had at least one other word instead.
if (lineWidth > 0) {
++numLines;
break;
}
}
if (wrapType & PPGE_LINE_USE_ELLIPSIS) {
useEllipsis = true;
if (skipRest) {
numChars = 0;
} else if (nextWidth < wrapCutoff) {
// The word is too short, so just backspace!
x = threshold;
}
nextWidth = 0;
spaceWidth = 0;
lineWidth = wrapWidth;
}
}
}
for (int i = 0; i < numChars; ++i)
{
u32 cval = utf.next();
const AtlasChar *c = PPGeGetChar(atlasfont, cval);
if (c)
{
if (useEllipsis && x >= threshold && dot)
{
if (!dryRun)
{
AtlasCharVertex cv;
// Replace the following part with an ellipsis.
cv.x = x + dot->ox * scale;
cv.y = y + dot->oy * scale;
cv.c = dot;
char_one_line.push_back(cv);
cv.x += dot->wx * scale;
char_one_line.push_back(cv);
cv.x += dot->wx * scale;
char_one_line.push_back(cv);
}
skipRest = true;
break;
}
if (!dryRun)
{
AtlasCharVertex cv;
cv.x = x + c->ox * scale;
cv.y = y + c->oy * scale;
cv.c = c;
char_one_line.push_back(cv);
}
x += c->wx * scale;
}
}
lineWidth += nextWidth;
u32 cval = utf.end() ? 0 : utf.next();
if (spaceWidth > 0)
{
if (!dryRun)
{
// No need to check c.
const AtlasChar *c = PPGeGetChar(atlasfont, cval);
AtlasCharVertex cv;
cv.x = x + c->ox * scale;
cv.y = y + c->oy * scale;
cv.c = c;
char_one_line.push_back(cv);
}
x += spaceWidth;
lineWidth += spaceWidth;
if (wrapType > 0 && lineWidth > wrapWidth) {
lineWidth = wrapWidth;
}
}
else if (cval == '\n') {
++numLines;
break;
}
utf = utfWord;
}
y += lineHeight;
x = sx;
if (lineWidth > maxw) {
maxw = lineWidth;
}
if (!dryRun)
{
char_lines.push_back(char_one_line);
char_one_line.clear();
}
}
const float w = maxw;
const float h = (float)numLines * lineHeight;
if (align & PPGeAlign::ANY) {
if (!dryRun) {
for (auto i = char_lines.begin(); i != char_lines.end(); ++i) {
for (auto j = i->begin(); j != i->end(); ++j) {
if (align & PPGeAlign::BOX_HCENTER) j->x -= w / 2.0f;
else if (align & PPGeAlign::BOX_RIGHT) j->x -= w;
if (align & PPGeAlign::BOX_VCENTER) j->y -= h / 2.0f;
else if (align & PPGeAlign::BOX_BOTTOM) j->y -= h;
}
}
}
if (align & PPGeAlign::BOX_HCENTER) sx -= w / 2.0f;
else if (align & PPGeAlign::BOX_RIGHT) sx -= w;
if (align & PPGeAlign::BOX_VCENTER) sy -= h / 2.0f;
else if (align & PPGeAlign::BOX_BOTTOM) sy -= h;
}
AtlasTextMetrics metrics = { sx, sy, w, lineHeight, scale, numLines };
return metrics;
}
static bool HasTextDrawer() {
// We create this on first use so it's on the correct thread.
if (textDrawerInited) {
return textDrawer != nullptr;
}
// Should we pass a draw_? Yes! UWP requires it.
textDrawer = TextDrawer::Create(g_draw);
if (textDrawer) {
textDrawer->SetFontScale(1.0f, 1.0f);
textDrawer->SetForcedDPIScale(1.0f);
textDrawer->SetFont(g_Config.sFont.c_str(), 18, 0);
}
textDrawerInited = true;
return textDrawer != nullptr;
}
static std::string PPGeSanitizeText(std::string_view text) {
return SanitizeUTF8(text);
}
void PPGeMeasureText(float *w, float *h, std::string_view text, float scale, int WrapType, int wrapWidth) {
std::string s = PPGeSanitizeText(text);
if (HasTextDrawer()) {
float mw, mh;
textDrawer->SetFontScale(scale, scale);
int dtalign = (WrapType & PPGE_LINE_WRAP_WORD) ? FLAG_WRAP_TEXT : 0;
if (WrapType & PPGE_LINE_USE_ELLIPSIS)
dtalign |= FLAG_ELLIPSIZE_TEXT;
Bounds b(0, 0, wrapWidth <= 0 ? 480.0f : wrapWidth, 272.0f);
textDrawer->MeasureStringRect(s, b, &mw, &mh, dtalign);
if (w)
*w = mw;
if (h)
*h = mh;
return;
}
if (!g_ppge_atlas.IsMetadataLoaded() || g_ppge_atlas.num_fonts < 1) {
if (w)
*w = 0;
if (h)
*h = 0;
return;
}
const AtlasFont &atlasfont = g_ppge_atlas.fonts[0];
AtlasTextMetrics metrics = BreakLines(s.c_str(), atlasfont, 0, 0, PPGeAlign::BOX_TOP, scale, scale, WrapType, wrapWidth, true);
if (w) *w = metrics.maxWidth;
if (h) *h = metrics.lineHeight * metrics.numLines;
}
void PPGePrepareText(std::string_view text, float x, float y, PPGeAlign align, float scale, float lineHeightScale, int WrapType, int wrapWidth)
{
const AtlasFont &atlasfont = g_ppge_atlas.fonts[0];
if (!g_ppge_atlas.IsMetadataLoaded() || g_ppge_atlas.num_fonts < 1) {
return;
}
char_lines_metrics = BreakLines(text, atlasfont, x, y, align, scale, lineHeightScale, WrapType, wrapWidth, false);
}
static void PPGeResetCurrentText() {
char_one_line.clear();
char_lines.clear();
AtlasTextMetrics zeroBox = { 0 };
char_lines_metrics = zeroBox;
}
// Draws some text using the one font we have in the atlas.
void PPGeDrawCurrentText(u32 color) {
// If the atlas is larger than 512x512, need to use windows into it.
bool useTextureWindow = g_Config.bSoftwareRendering && (atlasWidth > 512 || atlasHeight > 512);
uint32_t texturePosX = 0;
uint32_t texturePosY = 0;
// Use half the available size just in case a character straddles a boundary.
const float textureMaxPosX = !useTextureWindow ? 1.0f : atlasWidth / 256.0f;
const float textureMaxPosY = !useTextureWindow ? 1.0f : atlasHeight / 256.0f;
// These are the actual scale used.
const float textureWindowW = !useTextureWindow ? atlasWidth : 512.0f;
const float textureWindowH = !useTextureWindow ? atlasHeight : 512.0f;
const float textureScaleX = !useTextureWindow ? 1.0f : atlasWidth / 512.0f;
const float textureScaleY = !useTextureWindow ? 1.0f : atlasWidth / 512.0f;
if (dlPtr) {
float scale = char_lines_metrics.scale;
if (useTextureWindow) {
WriteCmd(GE_CMD_TEXWRAP, 0);
WriteCmd(GE_CMD_TEXSIZE0, 9 | (9 << 8));
}
BeginVertexData();
for (auto i = char_lines.begin(); i != char_lines.end(); ++i) {
for (auto j = i->begin(); j != i->end(); ++j) {
const AtlasChar &c = *j->c;
int wantedPosX = (int)floorf(c.sx * textureMaxPosX);
int wantedPosY = (int)floorf(c.sy * textureMaxPosY);
if (useTextureWindow && (wantedPosX != texturePosX || wantedPosY != texturePosY)) {
EndVertexDataAndDraw(GE_PRIM_RECTANGLES);
uint32_t offset = atlasWidth * wantedPosY * 256 + wantedPosX * 256;
WriteCmd(GE_CMD_TEXADDR0, (atlasPtr & 0xFFFFF0) + offset / 2);
texturePosX = wantedPosX;
texturePosY = wantedPosY;
BeginVertexData();
}
float sx = (c.sx - texturePosX / textureMaxPosX) * textureScaleX;
float sy = (c.sy - texturePosY / textureMaxPosY) * textureScaleY;
float ex = (c.ex - texturePosX / textureMaxPosX) * textureScaleX;
float ey = (c.ey - texturePosY / textureMaxPosY) * textureScaleY;
float cx1 = j->x;
float cy1 = j->y;
float cx2 = cx1 + c.pw * scale;
float cy2 = cy1 + c.ph * scale;
Vertex(cx1, cy1, sx, sy, textureWindowW, textureWindowH, color);
Vertex(cx2, cy2, ex, ey, textureWindowW, textureWindowH, color);
}
}
EndVertexDataAndDraw(GE_PRIM_RECTANGLES);
}
PPGeResetCurrentText();
if (useTextureWindow) {
PPGeSetDefaultTexture();
}
}
// Return a value such that (1 << value) >= x
inline int GetPow2(int x) {
int ret = 31 - clz32_nonzero(x | 1);
if ((1 << ret) < x)
ret++;
return ret;
}
static PPGeTextDrawerImage PPGeGetTextImage(std::string_view text, const PPGeStyle &style, float maxWidth, bool wrap) {
int tdalign = 0;
tdalign |= FLAG_ELLIPSIZE_TEXT;
if (wrap) {
tdalign |= FLAG_WRAP_TEXT;
}
PPGeTextDrawerCacheKey key{ std::string(text), tdalign, maxWidth / style.scale };
PPGeTextDrawerImage im{};
auto cacheItem = textDrawerImages.find(key);
if (cacheItem != textDrawerImages.end()) {
im = cacheItem->second;
cacheItem->second.entry.lastUsedFrame = gpuStats.numFlips;
} else {
std::vector<uint8_t> bitmapData;
textDrawer->SetFontScale(style.scale, style.scale);
Bounds b(0, 0, maxWidth, 272.0f);
std::string cleaned = ReplaceAll(text, "\r", "");
textDrawer->DrawStringBitmapRect(bitmapData, im.entry, Draw::DataFormat::R8_UNORM, cleaned.c_str(), b, tdalign, false);
int bufwBytes = ((im.entry.bmWidth + 31) / 32) * 16;
u32 sz = bufwBytes * (im.entry.bmHeight + 1);
u32 origSz = sz;
im.ptr = __PPGeDoAlloc(sz, true, "PPGeText");
if (bitmapData.size() & 1)
bitmapData.resize(bitmapData.size() + 1);
if (im.ptr) {
int wBytes = (im.entry.bmWidth + 1) / 2;
u8 *ramPtr = Memory::GetPointerWriteRange(im.ptr, sz);
for (int y = 0; y < im.entry.bmHeight; ++y) {
for (int x = 0; x < wBytes; ++x) {
uint8_t c1 = bitmapData[y * im.entry.bmWidth + x * 2];
uint8_t c2 = bitmapData[y * im.entry.bmWidth + x * 2 + 1];
// Convert this to 4-bit palette values.
ramPtr[y * bufwBytes + x] = (c2 & 0xF0) | (c1 >> 4);
}
if (bufwBytes != wBytes) {
memset(ramPtr + y * bufwBytes + wBytes, 0, bufwBytes - wBytes);
}
}
memset(ramPtr + im.entry.bmHeight * bufwBytes, 0, bufwBytes + sz - origSz);
}
im.entry.lastUsedFrame = gpuStats.numFlips;
textDrawerImages[key] = im;
}
return im;
}
static void PPGeDrawTextImage(const PPGeTextDrawerImage &im, float x, float y, const PPGeStyle &style) {
if (!im.ptr) {
return;
}
// Sometimes our texture can be larger than 512 wide, which means we need to tile it.
int bufw = ((im.entry.bmWidth + 31) / 32) * 32;
int tile1bmWidth = std::min(512, im.entry.bmWidth);
int tile2bmWidth = tile1bmWidth == 512 ? im.entry.bmWidth - 512 : 0;
bool hasTile2 = tile2bmWidth != 0;
// Now figure the tile shift value.
int tile1wp2 = GetPow2(tile1bmWidth);
int tile2wp2 = hasTile2 ? GetPow2(tile2bmWidth) : 0;
int hp2 = GetPow2(im.entry.bmHeight);
WriteCmd(GE_CMD_TEXADDR0, im.ptr & 0xFFFFF0);
WriteCmd(GE_CMD_TEXBUFWIDTH0, bufw | ((im.ptr & 0xFF000000) >> 8));
WriteCmd(GE_CMD_TEXSIZE0, tile1wp2 | (hp2 << 8));
WriteCmd(GE_CMD_TEXFLUSH, 0);
float w = im.entry.width * style.scale;
float h = im.entry.height * style.scale;
if (style.align & PPGeAlign::BOX_HCENTER)
x -= w / 2.0f;
else if (style.align & PPGeAlign::BOX_RIGHT)
x -= w;
if (style.align & PPGeAlign::BOX_VCENTER)
y -= h / 2.0f;
else if (style.align & PPGeAlign::BOX_BOTTOM)
y -= h;
BeginVertexData();
float tile2x = 512 * style.scale;
float tile1w = hasTile2 ? 512.0f * style.scale : w;
float tile2w = hasTile2 ? w - tile1w : 0.0f;
float tile1u1 = hasTile2 ? 1.0f : (float)im.entry.width / (1 << tile1wp2);
float tile2u1 = hasTile2 ? (float)(im.entry.width - 512) / (1 << tile2wp2) : 0.0f;
float v1 = (float)im.entry.height / (1 << hp2);
if (style.hasShadow) {
// Draw more shadows for a blurrier shadow.
u32 shadowColor = alphaMul(style.shadowColor, 0.35f);
for (float dy = 0.0f; dy <= 2.0f; dy += 1.0f) {
for (float dx = 0.0f; dx <= 1.0f; dx += 0.5f) {
if (dx == 0.0f && dy == 0.0f)
continue;
Vertex(x + dx, y + dy, 0, 0, 1 << tile1wp2, 1 << hp2, shadowColor);