/
NativeApp.cpp
1153 lines (979 loc) · 34 KB
/
NativeApp.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/.
// NativeApp implementation for platforms that will use that framework, like:
// Android, Linux, MacOSX.
//
// Native is a cross platform framework. It's not very mature and mostly
// just built according to the needs of my own apps.
//
// Windows has its own code that bypasses the framework entirely.
#include "ppsspp_config.h"
// Background worker threads should be spawned in NativeInit and joined
// in NativeShutdown.
#include <locale.h>
// Linux doesn't like using std::find with std::vector<int> without this :/
#if !defined(MOBILE_DEVICE)
#include <algorithm>
#endif
#include <memory>
#include <thread>
#include <mutex>
#if defined(_WIN32)
#include "Windows/DSoundStream.h"
#include "Windows/MainWindow.h"
#endif
#include "base/display.h"
#include "base/timeutil.h"
#include "base/logging.h"
#include "base/NativeApp.h"
#include "file/vfs.h"
#include "file/zip_read.h"
#include "net/http_client.h"
#include "net/resolve.h"
#include "gfx_es2/draw_text.h"
#include "gfx_es2/gpu_features.h"
#include "i18n/i18n.h"
#include "input/input_state.h"
#include "math/fast/fast_math.h"
#include "math/math_util.h"
#include "math/lin/matrix4x4.h"
#include "profiler/profiler.h"
#include "thin3d/thin3d.h"
#include "ui/ui.h"
#include "ui/screen.h"
#include "ui/ui_context.h"
#include "ui/view.h"
#include "util/text/utf8.h"
#include "Common/CPUDetect.h"
#include "Common/FileUtil.h"
#include "Common/LogManager.h"
#include "Common/MemArena.h"
#include "Common/GraphicsContext.h"
#include "Core/Config.h"
#include "Core/Core.h"
#include "Core/FileLoaders/DiskCachingFileLoader.h"
#include "Core/Host.h"
#include "Core/Reporting.h"
#include "Core/SaveState.h"
#include "Core/Screenshot.h"
#include "Core/System.h"
#include "Core/HLE/__sceAudio.h"
#include "Core/HLE/sceCtrl.h"
#include "Core/HLE/sceUsbCam.h"
#include "Core/HLE/sceUsbGps.h"
#include "Core/Util/GameManager.h"
#include "Core/Util/AudioFormat.h"
#include "GPU/GPUInterface.h"
#include "ui_atlas.h"
#include "UI/EmuScreen.h"
#include "UI/GameInfoCache.h"
#include "UI/HostTypes.h"
#include "UI/OnScreenDisplay.h"
#include "UI/MiscScreens.h"
#include "UI/RemoteISOScreen.h"
#include "UI/TiltEventProcessor.h"
#include "UI/BackgroundAudio.h"
#include "UI/TextureUtil.h"
#if !defined(MOBILE_DEVICE)
#include "Common/KeyMap.h"
#endif
// The new UI framework, for initialization
static UI::Theme ui_theme;
#if defined(ARM) && defined(__ANDROID__)
#include "../../android/jni/ArmEmitterTest.h"
#elif defined(ARM64) && defined(__ANDROID__)
#include "../../android/jni/Arm64EmitterTest.h"
#endif
#ifdef IOS
#include "ios/iOSCoreAudio.h"
#elif defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
// https://github.com/richq/android-ndk-profiler
#ifdef ANDROID_NDK_PROFILER
#include <stdlib.h>
#include "android/android-ndk-profiler/prof.h"
#endif
std::unique_ptr<ManagedTexture> uiTexture;
ScreenManager *screenManager;
std::string config_filename;
bool g_graphicsInited;
// Really need to clean this mess of globals up... but instead I add more :P
bool g_TakeScreenshot;
static bool isOuya;
static bool resized = false;
static bool restarting = false;
struct PendingMessage {
std::string msg;
std::string value;
};
static std::mutex pendingMutex;
static std::vector<PendingMessage> pendingMessages;
static Draw::DrawContext *g_draw;
static Draw::Pipeline *colorPipeline;
static Draw::Pipeline *texColorPipeline;
static UIContext *uiContext;
static std::vector<std::string> inputboxValue;
#ifdef _WIN32
WindowsAudioBackend *winAudioBackend;
#endif
std::thread *graphicsLoadThread;
class AndroidLogger : public LogListener {
public:
void Log(const LogMessage &message) override {
// Log with simplified headers as Android already provides timestamp etc.
switch (message.level) {
case LogTypes::LVERBOSE:
case LogTypes::LDEBUG:
case LogTypes::LINFO:
ILOG("[%s] %s", message.log, message.msg.c_str());
break;
case LogTypes::LERROR:
ELOG("[%s] %s", message.log, message.msg.c_str());
break;
case LogTypes::LWARNING:
WLOG("[%s] %s", message.log, message.msg.c_str());
break;
case LogTypes::LNOTICE:
default:
ILOG("[%s] !!! %s", message.log, message.msg.c_str());
break;
}
}
};
#ifdef _WIN32
int Win32Mix(short *buffer, int numSamples, int bits, int rate, int channels) {
return NativeMix(buffer, numSamples);
}
#endif
// globals
static AndroidLogger *logger = nullptr;
std::string boot_filename = "";
void NativeHost::InitSound() {
#ifdef IOS
iOSCoreAudioInit();
#endif
}
void NativeHost::ShutdownSound() {
#ifdef IOS
iOSCoreAudioShutdown();
#endif
}
#if !defined(MOBILE_DEVICE) && defined(USING_QT_UI)
void QtHost::InitSound() { }
void QtHost::ShutdownSound() { }
#endif
std::string NativeQueryConfig(std::string query) {
char temp[128];
if (query == "screenRotation") {
ILOG("g_Config.screenRotation = %d", g_Config.iScreenRotation);
snprintf(temp, sizeof(temp), "%d", g_Config.iScreenRotation);
return std::string(temp);
} else if (query == "immersiveMode") {
return std::string(g_Config.bImmersiveMode ? "1" : "0");
} else if (query == "hwScale") {
int scale = g_Config.iAndroidHwScale;
if (scale == 1) {
// If g_Config.iInternalResolution is also set to Auto (1), we fall back to "Device resolution" (0). It works out.
scale = g_Config.iInternalResolution;
} else if (scale >= 2) {
scale -= 1;
}
int max_res = std::max(System_GetPropertyInt(SYSPROP_DISPLAY_XRES), System_GetPropertyInt(SYSPROP_DISPLAY_YRES)) / 480 + 1;
snprintf(temp, sizeof(temp), "%d", std::min(scale, max_res));
return std::string(temp);
} else if (query == "force44khz") {
return std::string("0");
} else if (query == "androidJavaGL") {
// If we're using Vulkan, we say no... need C++ to use Vulkan.
if (GetGPUBackend() == GPUBackend::VULKAN) {
return "false";
}
// Otherwise, some devices prefer the Java init so play it safe.
return "true";
} else if (query == "sustainedPerformanceMode") {
return std::string(g_Config.bSustainedPerformanceMode ? "1" : "0");
} else {
return "";
}
}
int NativeMix(short *audio, int num_samples) {
if (GetUIState() != UISTATE_INGAME) {
PlayBackgroundAudio();
}
int sample_rate = System_GetPropertyInt(SYSPROP_AUDIO_SAMPLE_RATE);
num_samples = __AudioMix(audio, num_samples, sample_rate > 0 ? sample_rate : 44100);
#ifdef _WIN32
winAudioBackend->Update();
#endif
return num_samples;
}
// This is called before NativeInit so we do a little bit of initialization here.
void NativeGetAppInfo(std::string *app_dir_name, std::string *app_nice_name, bool *landscape, std::string *version) {
*app_nice_name = "PPSSPP";
*app_dir_name = "ppsspp";
*landscape = true;
*version = PPSSPP_GIT_VERSION;
#if defined(ARM) && defined(__ANDROID__)
ArmEmitterTest();
#elif defined(ARM64) && defined(__ANDROID__)
Arm64EmitterTest();
#endif
}
#if defined(_WIN32) && !PPSSPP_PLATFORM(UWP)
bool CheckFontIsUsable(const wchar_t *fontFace) {
wchar_t actualFontFace[1024] = { 0 };
HFONT f = CreateFont(0, 0, 0, 0, FW_LIGHT, 0, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, PROOF_QUALITY, VARIABLE_PITCH, fontFace);
if (f != nullptr) {
HDC hdc = CreateCompatibleDC(nullptr);
if (hdc != nullptr) {
SelectObject(hdc, f);
GetTextFace(hdc, 1024, actualFontFace);
DeleteDC(hdc);
}
DeleteObject(f);
}
// If we were able to get the font name, did it load?
if (actualFontFace[0] != 0) {
return wcsncmp(actualFontFace, fontFace, ARRAY_SIZE(actualFontFace)) == 0;
}
return false;
}
#endif
void NativeInit(int argc, const char *argv[], const char *savegame_dir, const char *external_dir, const char *cache_dir, bool fs) {
net::Init(); // This needs to happen before we load the config. So on Windows we also run it in Main. It's fine to call multiple times.
InitFastMath(cpu_info.bNEON);
SetupAudioFormats();
// Make sure UI state is MENU.
ResetUIState();
bool skipLogo = false;
setlocale( LC_ALL, "C" );
std::string user_data_path = savegame_dir;
pendingMessages.clear();
#ifdef IOS
user_data_path += "/";
#endif
// We want this to be FIRST.
#ifdef USING_QT_UI
VFSRegister("", new AssetsAssetReader());
#elif defined(IOS)
// Packed assets are included in app
VFSRegister("", new DirectoryAssetReader(external_dir));
#endif
#if !defined(MOBILE_DEVICE) && !defined(_WIN32)
VFSRegister("", new DirectoryAssetReader((File::GetExeDirectory() + "assets/").c_str()));
VFSRegister("", new DirectoryAssetReader((File::GetExeDirectory()).c_str()));
VFSRegister("", new DirectoryAssetReader("/usr/share/ppsspp/assets/"));
#endif
VFSRegister("", new DirectoryAssetReader("assets/"));
VFSRegister("", new DirectoryAssetReader(savegame_dir));
#if (defined(MOBILE_DEVICE) || !defined(USING_QT_UI)) && !PPSSPP_PLATFORM(UWP)
if (host == nullptr) {
host = new NativeHost();
}
#endif
#if defined(__ANDROID__)
g_Config.internalDataDirectory = savegame_dir;
// Maybe there should be an option to use internal memory instead, but I think
// that for most people, using external memory (SDCard/USB Storage) makes the
// most sense.
g_Config.memStickDirectory = std::string(external_dir) + "/";
g_Config.flash0Directory = std::string(external_dir) + "/flash0/";
#elif defined(IOS)
g_Config.memStickDirectory = user_data_path;
g_Config.flash0Directory = std::string(external_dir) + "/flash0/";
#elif !defined(_WIN32)
std::string config;
if (getenv("XDG_CONFIG_HOME") != NULL)
config = getenv("XDG_CONFIG_HOME");
else if (getenv("HOME") != NULL)
config = getenv("HOME") + std::string("/.config");
else // Just in case
config = "./config";
g_Config.memStickDirectory = config + "/ppsspp/";
g_Config.flash0Directory = File::GetExeDirectory() + "/assets/flash0/";
#endif
if (cache_dir && strlen(cache_dir)) {
DiskCachingFileLoaderCache::SetCacheDir(cache_dir);
g_Config.appCacheDirectory = cache_dir;
}
if (!LogManager::GetInstance())
LogManager::Init();
#ifndef _WIN32
g_Config.AddSearchPath(user_data_path);
g_Config.AddSearchPath(g_Config.memStickDirectory + "PSP/SYSTEM/");
g_Config.SetDefaultPath(g_Config.memStickDirectory + "PSP/SYSTEM/");
g_Config.Load();
g_Config.externalDirectory = external_dir;
#endif
LogManager *logman = LogManager::GetInstance();
#ifdef __ANDROID__
// TODO: This is also done elsewhere. Remove?
// On Android, create a PSP directory tree in the external_dir,
// to hopefully reduce confusion a bit.
ILOG("Creating %s", (g_Config.memStickDirectory + "PSP").c_str());
File::CreateDir((g_Config.memStickDirectory + "PSP").c_str());
File::CreateDir((g_Config.memStickDirectory + "PSP/SAVEDATA").c_str());
File::CreateDir((g_Config.memStickDirectory + "PSP/GAME").c_str());
#endif
const char *fileToLog = 0;
const char *stateToLoad = 0;
bool gotBootFilename = false;
// Parse command line
LogTypes::LOG_LEVELS logLevel = LogTypes::LINFO;
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
switch (argv[i][1]) {
case 'd':
// Enable debug logging
// Note that you must also change the max log level in Log.h.
logLevel = LogTypes::LDEBUG;
break;
case 'v':
// Enable verbose logging
// Note that you must also change the max log level in Log.h.
logLevel = LogTypes::LVERBOSE;
break;
case 'j':
g_Config.iCpuCore = (int)CPUCore::JIT;
g_Config.bSaveSettings = false;
break;
case 'i':
g_Config.iCpuCore = (int)CPUCore::INTERPRETER;
g_Config.bSaveSettings = false;
break;
case 'r':
g_Config.iCpuCore = (int)CPUCore::IR_JIT;
g_Config.bSaveSettings = false;
break;
case '-':
if (!strncmp(argv[i], "--log=", strlen("--log=")) && strlen(argv[i]) > strlen("--log="))
fileToLog = argv[i] + strlen("--log=");
if (!strncmp(argv[i], "--state=", strlen("--state=")) && strlen(argv[i]) > strlen("--state="))
stateToLoad = argv[i] + strlen("--state=");
if (!strncmp(argv[1], "--PS3", strlen("--PS3")))
g_Config.bPS3Controller = true;
#if !defined(MOBILE_DEVICE)
if (!strncmp(argv[i], "--escape-exit", strlen("--escape-exit")))
g_Config.bPauseExitsEmulator = true;
#endif
break;
}
} else {
// This parameter should be a boot filename. Only accept it if we
// don't already have one.
if (!gotBootFilename) {
gotBootFilename = true;
ILOG("Boot filename found in args: '%s'", argv[i]);
bool okToLoad = true;
if (System_GetPropertyBool(SYSPROP_SUPPORTS_PERMISSIONS)) {
PermissionStatus status = System_GetPermissionStatus(SYSTEM_PERMISSION_STORAGE);
if (status != PERMISSION_STATUS_GRANTED) {
ELOG("Storage permission not granted. Launching without argument.");
okToLoad = false;
} else {
ILOG("Storage permission granted.");
}
}
if (okToLoad) {
boot_filename = argv[i];
#ifdef _WIN32
boot_filename = ReplaceAll(boot_filename, "\\", "/");
#endif
skipLogo = true;
std::unique_ptr<FileLoader> fileLoader(ConstructFileLoader(boot_filename));
if (!fileLoader->Exists()) {
fprintf(stderr, "File not found: %s\n", boot_filename.c_str());
exit(1);
}
}
} else {
fprintf(stderr, "Can only boot one file");
exit(1);
}
}
}
if (fileToLog)
LogManager::GetInstance()->ChangeFileLog(fileToLog);
#ifndef _WIN32
if (g_Config.currentDirectory == "") {
#if defined(__ANDROID__)
g_Config.currentDirectory = external_dir;
#elif defined(IOS) || defined(_WIN32)
g_Config.currentDirectory = savegame_dir;
#else
if (getenv("HOME") != NULL)
g_Config.currentDirectory = getenv("HOME");
else
g_Config.currentDirectory = "./";
#endif
}
#endif
// Hard reset the logs. TODO: Get rid of this and read from config.
#ifndef _WIN32
for (int i = 0; i < LogTypes::NUMBER_OF_LOGS; i++) {
LogTypes::LOG_TYPE type = (LogTypes::LOG_TYPE)i;
logman->SetEnabled(type, true);
logman->SetLogLevel(type, logLevel);
}
#endif
#if defined(__ANDROID__) || (defined(MOBILE_DEVICE) && !defined(_DEBUG))
// Enable basic logging for any kind of mobile device, since LogManager doesn't.
// The MOBILE_DEVICE/_DEBUG condition matches LogManager.cpp.
logger = new AndroidLogger();
logman->AddListener(logger);
#endif
// Allow the lang directory to be overridden for testing purposes (e.g. Android, where it's hard to
// test new languages without recompiling the entire app, which is a hassle).
const std::string langOverridePath = g_Config.memStickDirectory + "PSP/SYSTEM/lang/";
// If we run into the unlikely case that "lang" is actually a file, just use the built-in translations.
if (!File::Exists(langOverridePath) || !File::IsDirectory(langOverridePath))
i18nrepo.LoadIni(g_Config.sLanguageIni);
else
i18nrepo.LoadIni(g_Config.sLanguageIni, langOverridePath);
I18NCategory *des = GetI18NCategory("DesktopUI");
// Note to translators: do not translate this/add this to PPSSPP-lang's files.
// It's intended to be custom for every user.
// Only add it to your own personal copies of PPSSPP.
#if defined(_WIN32) && !PPSSPP_PLATFORM(UWP)
// TODO: Could allow a setting to specify a font file to load?
// TODO: Make this a constant if we can sanely load the font on other systems?
AddFontResourceEx(L"assets/Roboto-Condensed.ttf", FR_PRIVATE, NULL);
// The font goes by two names, let's allow either one.
if (CheckFontIsUsable(L"Roboto Condensed")) {
g_Config.sFont = des->T("Font", "Roboto Condensed");
} else {
g_Config.sFont = des->T("Font", "Roboto");
}
#endif
if (!boot_filename.empty() && stateToLoad != NULL) {
SaveState::Load(stateToLoad, [](bool status, const std::string &message, void *) {
if (!message.empty()) {
osm.Show(message, 2.0);
}
});
}
screenManager = new ScreenManager();
if (skipLogo) {
screenManager->switchScreen(new EmuScreen(boot_filename));
} else {
screenManager->switchScreen(new LogoScreen());
}
if (g_Config.bRemoteShareOnStartup) {
StartRemoteISOSharing();
}
std::string sysName = System_GetProperty(SYSPROP_NAME);
isOuya = KeyMap::IsOuya(sysName);
#if !defined(MOBILE_DEVICE) && defined(USING_QT_UI)
MainWindow* mainWindow = new MainWindow(0,fs);
mainWindow->show();
if (host == nullptr) {
host = new QtHost(mainWindow);
}
#endif
// We do this here, instead of in NativeInitGraphics, because the display may be reset.
// When it's reset we don't want to forget all our managed things.
SetGPUBackend((GPUBackend) g_Config.iGPUBackend);
// Must be done restarting by now.
restarting = false;
}
static UI::Style MakeStyle(uint32_t fg, uint32_t bg) {
UI::Style s;
s.background = UI::Drawable(bg);
s.fgColor = fg;
return s;
}
static void UIThemeInit() {
#if defined(_WIN32) && !PPSSPP_PLATFORM(UWP)
ui_theme.uiFont = UI::FontStyle(UBUNTU24, g_Config.sFont.c_str(), 22);
ui_theme.uiFontSmall = UI::FontStyle(UBUNTU24, g_Config.sFont.c_str(), 15);
ui_theme.uiFontSmaller = UI::FontStyle(UBUNTU24, g_Config.sFont.c_str(), 12);
#else
ui_theme.uiFont = UI::FontStyle(UBUNTU24, "", 20);
ui_theme.uiFontSmall = UI::FontStyle(UBUNTU24, "", 14);
ui_theme.uiFontSmaller = UI::FontStyle(UBUNTU24, "", 11);
#endif
ui_theme.checkOn = I_CHECKEDBOX;
ui_theme.checkOff = I_SQUARE;
ui_theme.whiteImage = I_SOLIDWHITE;
ui_theme.sliderKnob = I_CIRCLE;
ui_theme.dropShadow4Grid = I_DROP_SHADOW;
ui_theme.itemStyle = MakeStyle(g_Config.uItemStyleFg, g_Config.uItemStyleBg);
ui_theme.itemFocusedStyle = MakeStyle(g_Config.uItemFocusedStyleFg, g_Config.uItemFocusedStyleBg);
ui_theme.itemDownStyle = MakeStyle(g_Config.uItemDownStyleFg, g_Config.uItemDownStyleBg);
ui_theme.itemDisabledStyle = MakeStyle(g_Config.uItemDisabledStyleFg, g_Config.uItemDisabledStyleBg);
ui_theme.itemHighlightedStyle = MakeStyle(g_Config.uItemHighlightedStyleFg, g_Config.uItemHighlightedStyleBg);
ui_theme.buttonStyle = MakeStyle(g_Config.uButtonStyleFg, g_Config.uButtonStyleBg);
ui_theme.buttonFocusedStyle = MakeStyle(g_Config.uButtonFocusedStyleFg, g_Config.uButtonFocusedStyleBg);
ui_theme.buttonDownStyle = MakeStyle(g_Config.uButtonDownStyleFg, g_Config.uButtonDownStyleBg);
ui_theme.buttonDisabledStyle = MakeStyle(g_Config.uButtonDisabledStyleFg, g_Config.uButtonDisabledStyleBg);
ui_theme.buttonHighlightedStyle = MakeStyle(g_Config.uButtonHighlightedStyleFg, g_Config.uButtonHighlightedStyleBg);
ui_theme.headerStyle.fgColor = g_Config.uHeaderStyleFg;
ui_theme.infoStyle = MakeStyle(g_Config.uInfoStyleFg, g_Config.uInfoStyleBg);
ui_theme.popupTitle.fgColor = g_Config.uPopupTitleStyleFg;
ui_theme.popupStyle = MakeStyle(g_Config.uPopupStyleFg, g_Config.uPopupStyleBg);
}
void RenderOverlays(UIContext *dc, void *userdata);
bool NativeInitGraphics(GraphicsContext *graphicsContext) {
ILOG("NativeInitGraphics");
_assert_msg_(G3D, graphicsContext, "No graphics context!");
using namespace Draw;
Core_SetGraphicsContext(graphicsContext);
g_draw = graphicsContext->GetDrawContext();
_assert_msg_(G3D, g_draw, "No draw context available!");
ui_draw2d.SetAtlas(&ui_atlas);
ui_draw2d_front.SetAtlas(&ui_atlas);
UIThemeInit();
uiTexture = CreateTextureFromFile(g_draw, "ui_atlas.zim", ImageFileType::ZIM);
if (!uiTexture) {
PanicAlert("Failed to load ui_atlas.zim.\n\nPlace it in the directory \"assets\" under your PPSSPP directory.");
ELOG("Failed to load ui_atlas.zim");
#if defined(_WIN32) && !PPSSPP_PLATFORM(UWP)
UINT ExitCode = 0;
ExitProcess(ExitCode);
#endif
}
uiContext = new UIContext();
uiContext->theme = &ui_theme;
Draw::InputLayout *inputLayout = ui_draw2d.CreateInputLayout(g_draw);
Draw::BlendState *blendNormal = g_draw->CreateBlendState({ true, 0xF, BlendFactor::SRC_ALPHA, BlendFactor::ONE_MINUS_SRC_ALPHA });
Draw::DepthStencilState *depth = g_draw->CreateDepthStencilState({ false, false, Comparison::LESS });
Draw::RasterState *rasterNoCull = g_draw->CreateRasterState({});
PipelineDesc colorDesc{
Primitive::TRIANGLE_LIST,
{ g_draw->GetVshaderPreset(VS_COLOR_2D), g_draw->GetFshaderPreset(FS_COLOR_2D) },
inputLayout, depth, blendNormal, rasterNoCull, &vsColBufDesc,
};
PipelineDesc texColorDesc{
Primitive::TRIANGLE_LIST,
{ g_draw->GetVshaderPreset(VS_TEXTURE_COLOR_2D), g_draw->GetFshaderPreset(FS_TEXTURE_COLOR_2D) },
inputLayout, depth, blendNormal, rasterNoCull, &vsTexColBufDesc,
};
colorPipeline = g_draw->CreateGraphicsPipeline(colorDesc);
texColorPipeline = g_draw->CreateGraphicsPipeline(texColorDesc);
// Release these now, reference counting should ensure that they get completely released
// once we delete both pipelines.
inputLayout->Release();
rasterNoCull->Release();
blendNormal->Release();
depth->Release();
ui_draw2d.Init(g_draw, texColorPipeline);
ui_draw2d_front.Init(g_draw, texColorPipeline);
uiContext->Init(g_draw, texColorPipeline, colorPipeline, &ui_draw2d, &ui_draw2d_front);
RasterStateDesc desc;
desc.cull = CullMode::NONE;
desc.frontFace = Facing::CCW;
if (uiContext->Text())
uiContext->Text()->SetFont("Tahoma", 20, 0);
screenManager->setUIContext(uiContext);
screenManager->setDrawContext(g_draw);
screenManager->setPostRenderCallback(&RenderOverlays, nullptr);
UIBackgroundInit(*uiContext);
#ifdef _WIN32
winAudioBackend = CreateAudioBackend((AudioBackendType)g_Config.iAudioBackend);
#if PPSSPP_PLATFORM(UWP)
winAudioBackend->Init(0, &Win32Mix, 44100);
#else
winAudioBackend->Init(MainWindow::GetHWND(), &Win32Mix, 44100);
#endif
#endif
g_gameInfoCache = new GameInfoCache();
if (gpu)
gpu->DeviceRestore();
g_graphicsInited = true;
ILOG("NativeInitGraphics completed");
return true;
}
void NativeShutdownGraphics() {
if (gpu)
gpu->DeviceLost();
g_graphicsInited = false;
ILOG("NativeShutdownGraphics");
#ifdef _WIN32
delete winAudioBackend;
winAudioBackend = nullptr;
#endif
delete g_gameInfoCache;
g_gameInfoCache = nullptr;
UIBackgroundShutdown();
uiTexture.reset(nullptr);
delete uiContext;
uiContext = nullptr;
ui_draw2d.Shutdown();
ui_draw2d_front.Shutdown();
colorPipeline->Release();
texColorPipeline->Release();
ILOG("NativeShutdownGraphics done");
}
void TakeScreenshot() {
g_TakeScreenshot = false;
#if defined(_WIN32) || (defined(USING_QT_UI) && !defined(MOBILE_DEVICE))
std::string path = GetSysDirectory(DIRECTORY_SCREENSHOT);
while (path.length() > 0 && path.back() == '/') {
path.resize(path.size() - 1);
}
if (!File::Exists(path)) {
File::CreateDir(path);
}
// First, find a free filename.
int i = 0;
std::string gameId = g_paramSFO.GetDiscID();
char filename[2048];
while (i < 10000){
if (g_Config.bScreenshotsAsPNG)
snprintf(filename, sizeof(filename), "%s/%s_%05d.png", path.c_str(), gameId.c_str(), i);
else
snprintf(filename, sizeof(filename), "%s/%s_%05d.jpg", path.c_str(), gameId.c_str(), i);
FileInfo info;
if (!getFileInfo(filename, &info))
break;
i++;
}
bool success = TakeGameScreenshot(filename, g_Config.bScreenshotsAsPNG ? ScreenshotFormat::PNG : ScreenshotFormat::JPG, SCREENSHOT_OUTPUT);
if (success) {
osm.Show(filename);
} else {
I18NCategory *err = GetI18NCategory("Error");
osm.Show(err->T("Could not save screenshot file"));
}
#endif
}
void RenderOverlays(UIContext *dc, void *userdata) {
// Thin bar at the top of the screen like Chrome.
std::vector<float> progress = g_DownloadManager.GetCurrentProgress();
if (!progress.empty()) {
static const uint32_t colors[4] = {
0xFFFFFFFF,
0xFFCCCCCC,
0xFFAAAAAA,
0xFF777777,
};
dc->Begin();
int h = 5;
for (size_t i = 0; i < progress.size(); i++) {
float barWidth = 10 + (dc->GetBounds().w - 10) * progress[i];
Bounds bounds(0, h * i, barWidth, h);
UI::Drawable solid(colors[i & 3]);
dc->FillRect(solid, bounds);
}
dc->End();
dc->Flush();
}
if (g_TakeScreenshot) {
TakeScreenshot();
}
}
void NativeRender(GraphicsContext *graphicsContext) {
g_GameManager.Update();
// If uitexture gets reloaded, make sure we use the latest one.
// Not sure this happens anymore now that we tear down all graphics on app switches...
uiContext->FrameSetup(uiTexture->GetTexture());
float xres = dp_xres;
float yres = dp_yres;
// Apply the UIContext bounds as a 2D transformation matrix.
// TODO: This should be moved into the draw context...
Matrix4x4 ortho;
switch (GetGPUBackend()) {
case GPUBackend::VULKAN:
ortho.setOrthoD3D(0.0f, xres, 0, yres, -1.0f, 1.0f);
break;
case GPUBackend::DIRECT3D9:
ortho.setOrthoD3D(0.0f, xres, yres, 0.0f, -1.0f, 1.0f);
Matrix4x4 translation;
// Account for the small window adjustment.
translation.setTranslation(Vec3(-0.5f * g_dpi_scale_x / g_dpi_scale_real_x, -0.5f * g_dpi_scale_y / g_dpi_scale_real_y, 0.0f));
ortho = translation * ortho;
break;
case GPUBackend::DIRECT3D11:
ortho.setOrthoD3D(0.0f, xres, yres, 0.0f, -1.0f, 1.0f);
break;
case GPUBackend::OPENGL:
ortho.setOrtho(0.0f, xres, yres, 0.0f, -1.0f, 1.0f);
break;
}
if (g_display_rotation != DisplayRotation::ROTATE_0) {
ortho = ortho * g_display_rot_matrix;
}
ui_draw2d.PushDrawMatrix(ortho);
ui_draw2d_front.PushDrawMatrix(ortho);
// All actual rendering happen in here.
screenManager->render();
if (screenManager->getUIContext()->Text()) {
screenManager->getUIContext()->Text()->OncePerFrame();
}
if (resized) {
resized = false;
if (uiContext) {
// Modifying the bounds here can be used to "inset" the whole image to gain borders for TV overscan etc.
// The UI now supports any offset but not the EmuScreen yet.
uiContext->SetBounds(Bounds(0, 0, dp_xres, dp_yres));
// uiContext->SetBounds(Bounds(dp_xres/2, 0, dp_xres / 2, dp_yres / 2));
// OSX 10.6 and SDL 1.2 bug.
#if defined(__APPLE__) && !defined(USING_QT_UI)
static int dp_xres_old = dp_xres;
if (dp_xres != dp_xres_old) {
// uiTexture->Load("ui_atlas.zim");
dp_xres_old = dp_xres;
}
#endif
}
// Test lost/restore on PC
#if 0
if (gpu) {
gpu->DeviceLost();
gpu->DeviceRestore();
}
#endif
graphicsContext->Resize();
screenManager->resized();
// TODO: Move this to new GraphicsContext objects for each backend.
#ifndef _WIN32
if (GetGPUBackend() == GPUBackend::OPENGL) {
PSP_CoreParameter().pixelWidth = pixel_xres;
PSP_CoreParameter().pixelHeight = pixel_yres;
NativeMessageReceived("gpu_resized", "");
}
#endif
}
ui_draw2d.PopDrawMatrix();
ui_draw2d_front.PopDrawMatrix();
}
void HandleGlobalMessage(const std::string &msg, const std::string &value) {
if (msg == "inputDeviceConnected") {
KeyMap::NotifyPadConnected(value);
}
if (msg == "inputbox_completed") {
SplitString(value, ':', inputboxValue);
std::string setString = inputboxValue.size() > 1 ? inputboxValue[1] : "";
if (inputboxValue[0] == "IP")
g_Config.proAdhocServer = setString;
else if (inputboxValue[0] == "nickname")
g_Config.sNickName = setString;
else if (inputboxValue[0] == "remoteiso_subdir")
g_Config.sRemoteISOSubdir = setString;
else if (inputboxValue[0] == "remoteiso_server")
g_Config.sLastRemoteISOServer = setString;
inputboxValue.clear();
}
if (msg == "bgImage_updated") {
if (!value.empty()) {
std::string dest = GetSysDirectory(DIRECTORY_SYSTEM) + (endsWithNoCase(value, ".jpg") ? "background.jpg" : "background.png");
File::Copy(value, dest);
}
UIBackgroundShutdown();
UIBackgroundInit(*uiContext);
}
if (msg == "savestate_displayslot") {
I18NCategory *sy = GetI18NCategory("System");
std::string msg = StringFromFormat("%s: %d", sy->T("Savestate Slot"), SaveState::GetCurrentSlot() + 1);
// Show for the same duration as the preview.
osm.Show(msg, 2.0f, 0xFFFFFF, -1, true, "savestate_slot");
}
if (msg == "gpu_resized" || msg == "gpu_clearCache") {
if (gpu) {
gpu->ClearCacheNextFrame();
gpu->Resized();
}
Reporting::UpdateConfig();
}
if (msg == "core_powerSaving") {
if (value != "false") {
I18NCategory *sy = GetI18NCategory("System");
#ifdef __ANDROID__
osm.Show(sy->T("WARNING: Android battery save mode is on"), 2.0f, 0xFFFFFF, -1, true, "core_powerSaving");
#else
osm.Show(sy->T("WARNING: Battery save mode is on"), 2.0f, 0xFFFFFF, -1, true, "core_powerSaving");
#endif
}
Core_SetPowerSaving(value != "false");
}
}
void NativeUpdate() {
PROFILE_END_FRAME();
std::vector<PendingMessage> toProcess;
{
std::lock_guard<std::mutex> lock(pendingMutex);
toProcess = std::move(pendingMessages);
pendingMessages.clear();
}
for (size_t i = 0; i < toProcess.size(); i++) {
HandleGlobalMessage(toProcess[i].msg, toProcess[i].value);
screenManager->sendMessage(toProcess[i].msg.c_str(), toProcess[i].value.c_str());
}
g_DownloadManager.Update();
screenManager->update();
}
bool NativeIsAtTopLevel() {
Screen *currentScreen = screenManager->topScreen();
if (currentScreen) {
bool top = currentScreen->isTopLevel();
ILOG("Screen toplevel: %i", (int)top);
return currentScreen->isTopLevel();
} else {
ELOG("No current screen");
return false;
}
}
bool NativeTouch(const TouchInput &touch) {
if (screenManager) {
// Brute force prevent NaNs from getting into the UI system
if (my_isnan(touch.x) || my_isnan(touch.y)) {
return false;
}
screenManager->touch(touch);
return true;
} else {
return false;
}
}
bool NativeKey(const KeyInput &key) {
// ILOG("Key code: %i flags: %i", key.keyCode, key.flags);
#if !defined(MOBILE_DEVICE)
if (g_Config.bPauseExitsEmulator) {
static std::vector<int> pspKeys;
pspKeys.clear();
if (KeyMap::KeyToPspButton(key.deviceId, key.keyCode, &pspKeys)) {
if (std::find(pspKeys.begin(), pspKeys.end(), VIRTKEY_PAUSE) != pspKeys.end()) {
System_SendMessage("finish", "");
return true;
}
}
}
#endif
bool retval = false;
if (screenManager)
retval = screenManager->key(key);