-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathNativeApp.cpp
More file actions
1668 lines (1407 loc) · 54.2 KB
/
Copy pathNativeApp.cpp
File metadata and controls
1668 lines (1407 loc) · 54.2 KB
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 <errno.h>
#include <clocale>
#include <algorithm>
#include <cstdlib>
#include <memory>
#include <mutex>
#include <thread>
#if defined(_WIN32)
#include "Windows/WindowsAudio.h"
#include "Windows/MainWindow.h"
#endif
#if defined(_WIN32) && !PPSSPP_PLATFORM(UWP)
#include "Windows/CaptureDevice.h"
#endif
#include "Common/Net/HTTPClient.h"
#include "Common/Net/Resolve.h"
#include "Common/Net/URL.h"
#include "Common/Render/TextureAtlas.h"
#include "Common/Render/Text/draw_text.h"
#include "Common/GPU/OpenGL/GLFeatures.h"
#include "Common/GPU/thin3d.h"
#include "Common/UI/UI.h"
#include "Common/UI/Screen.h"
#include "Common/UI/Context.h"
#include "Common/UI/View.h"
#include "Common/UI/IconCache.h"
#include "android/jni/app-android.h"
#include "Common/System/Display.h"
#include "Common/System/Request.h"
#include "Common/System/System.h"
#include "Common/System/OSD.h"
#include "Common/System/NativeApp.h"
#include "Common/Data/Text/I18n.h"
#include "Common/Input/InputState.h"
#include "Common/Math/math_util.h"
#include "Common/Math/lin/matrix4x4.h"
#include "Common/Profiler/Profiler.h"
#include "Common/Data/Encoding/Utf8.h"
#include "Common/File/VFS/VFS.h"
#include "Common/File/VFS/ZipFileReader.h"
#include "Common/File/VFS/DirectoryReader.h"
#include "Common/CPUDetect.h"
#include "Common/File/FileUtil.h"
#include "Common/TimeUtil.h"
#include "Common/StringUtils.h"
#include "Common/Log/LogManager.h"
#include "Common/MemArena.h"
#include "Common/GraphicsContext.h"
#include "Common/OSVersion.h"
#include "Common/GPU/ShaderTranslation.h"
#include "Common/VR/PPSSPPVR.h"
#include "Common/Thread/ThreadManager.h"
#include "Common/Audio/AudioBackend.h"
#include "Common/UI/PopupScreens.h"
#include "Core/ControlMapper.h"
#include "Core/Config.h"
#include "Core/ConfigValues.h"
#include "Core/Core.h"
#include "Core/Debugger/Breakpoints.h"
#include "Core/FileLoaders/DiskCachingFileLoader.h"
#include "Core/FrameTiming.h"
#include "Core/KeyMap.h"
#include "Core/Reporting.h"
#include "Core/RetroAchievements.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/HLE/proAdhoc.h"
#include "Core/HW/MemoryStick.h"
#include "Core/Util/GameManager.h"
#include "Core/Util/PortManager.h"
#include "Core/Util/AudioFormat.h"
#include "Core/Util/RecentFiles.h"
#include "Core/Util/PathUtil.h"
#include "Core/WebServer.h"
#include "Core/TiltEventProcessor.h"
#include "GPU/GPUCommon.h"
#include "GPU/Common/PresentationCommon.h"
#include "UI/AudioCommon.h"
#include "UI/Background.h"
#include "UI/BackgroundAudio.h"
#include "UI/ControlMappingScreen.h"
#include "UI/DevScreens.h"
#include "UI/DiscordIntegration.h"
#include "UI/EmuScreen.h"
#include "UI/GameInfoCache.h"
#include "UI/GameSettingsScreen.h"
#include "UI/DeveloperToolsScreen.h"
#include "UI/GPUDriverTestScreen.h"
#include "UI/MiscScreens.h"
#include "UI/MemStickScreen.h"
#include "UI/OnScreenDisplay.h"
#include "UI/RemoteISOScreen.h"
#include "UI/Theme.h"
#include "UI/UIAtlas.h"
#if PPSSPP_PLATFORM(UWP)
#include <dwrite_3.h>
#include "UWP/UWPHelpers/InputHelpers.h"
#endif
#if PPSSPP_PLATFORM(ANDROID)
#include "android/jni/app-android.h"
#endif
#if PPSSPP_ARCH(ARM) && defined(__ANDROID__)
#include "../../android/jni/ArmEmitterTest.h"
#elif PPSSPP_ARCH(ARM64) && defined(__ANDROID__)
#include "../../android/jni/Arm64EmitterTest.h"
#endif
#if PPSSPP_PLATFORM(IOS)
#include "ios/iOSCoreAudio.h"
#elif defined(__APPLE__)
#include <mach-o/dyld.h>
#endif
#if PPSSPP_PLATFORM(IOS) || PPSSPP_PLATFORM(MAC)
#include "UI/DarwinFileSystemServices.h"
#endif
#if !defined(__LIBRETRO__)
#include "Core/Util/GameDB.h"
#endif
#include <Core/HLE/Plugins.h>
bool HandleGlobalMessage(UIMessage message, const std::string &value);
static void ProcessWheelRelease(InputKeyCode keyCode, double now, bool keyPress);
void SaveFrameDump();
ScreenManager *g_screenManager;
std::string config_filename;
// Really need to clean this mess of globals up... but instead I add more :P
bool g_TakeScreenshot;
static bool resized = false;
static bool restarting = false;
static int renderCounter = 0;
struct PendingMessage {
UIMessage message;
std::string value;
};
static std::mutex g_pendingMutex;
static std::vector<PendingMessage> pendingMessages;
static Draw::DrawContext *g_draw;
static Draw::Pipeline *colorPipeline;
static Draw::Pipeline *texColorPipeline;
static UIContext *uiContext;
static int g_restartGraphics;
static bool g_windowHidden = false;
std::vector<std::function<void()>> g_pendingClosures;
AudioBackend *g_audioBackend = nullptr;
std::thread *graphicsLoadThread;
// globals
Path boot_filename;
// 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 PPSSPP_ARCH(ARM) && defined(__ANDROID__)
ArmEmitterTest();
#elif PPSSPP_ARCH(ARM64) && defined(__ANDROID__)
Arm64EmitterTest();
#endif
}
#if defined(USING_WIN_UI) && !PPSSPP_PLATFORM(UWP)
static 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 PostLoadConfig() {
if (g_Config.currentDirectory.empty()) {
g_Config.currentDirectory = g_Config.defaultCurrentDirectory;
}
// 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 Path langOverridePath = GetSysDirectory(DIRECTORY_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))
g_i18nrepo.LoadIni(g_Config.sLanguageIni);
else
g_i18nrepo.LoadIni(g_Config.sLanguageIni, langOverridePath);
#if !PPSSPP_PLATFORM(WINDOWS) || PPSSPP_PLATFORM(UWP)
CreateSysDirectories();
#endif
}
static void CheckFailedGPUBackends() {
#ifdef _DEBUG
// If you're in debug mode, you probably don't want a fallback. If you're in release mode, use IGNORE below.
NOTICE_LOG(Log::Loader, "Not checking for failed graphics backends in debug mode");
return;
#endif
#if PPSSPP_PLATFORM(ANDROID)
if (System_GetPropertyInt(SYSPROP_SYSTEMVERSION) >= 30) {
// In Android 11 or later, Vulkan is as stable as OpenGL, so let's not even bother.
// Have also seen unexplained issues with random fallbacks to OpenGL for no good reason,
// especially when debugging.
return;
}
#endif
// We only want to do this once per process run and backend, to detect process crashes.
// If NativeShutdown is called before we finish, we might call this multiple times.
static int lastBackend = -1;
if (lastBackend == g_Config.iGPUBackend) {
return;
}
lastBackend = g_Config.iGPUBackend;
const Path failedBackendsDir = GetFailedBackendsDir();
const Path failedBackendsFile = failedBackendsDir / "FailedGraphicsBackends.txt";
std::string data;
if (File::ReadTextFileToString(failedBackendsFile, &data)) {
g_Config.sFailedGPUBackends = data;
}
// Use this if you want to debug a graphics crash...
if (g_Config.sFailedGPUBackends == "IGNORE")
return;
else if (!g_Config.sFailedGPUBackends.empty()) {
ERROR_LOG(Log::Loader, "Failed graphics backends: %s", g_Config.sFailedGPUBackends.c_str());
}
// Okay, let's not try a backend in the failed list.
g_Config.iGPUBackend = g_Config.NextValidBackend();
if (lastBackend != g_Config.iGPUBackend) {
// This is the expected path.
std::string param = GPUBackendToString((GPUBackend)lastBackend) + " -> " + GPUBackendToString((GPUBackend)g_Config.iGPUBackend);
System_GraphicsBackendFailedAlert(param);
INFO_LOG(Log::Loader, "Failed graphics backend switched from %s (%d to %d)", param.c_str(), lastBackend, g_Config.iGPUBackend);
} else {
WARN_LOG(Log::Loader, "Did not switch failed backend! %d", g_Config.iGPUBackend);
}
// And then let's - for now - add the current to the failed list, in case it fails - we'll clear it again once it succeeds.
const std::string curBackend = GPUBackendToString((GPUBackend)g_Config.iGPUBackend);
if (g_Config.sFailedGPUBackends.empty()) {
g_Config.sFailedGPUBackends = curBackend;
} else if (g_Config.sFailedGPUBackends.find(curBackend) != std::string::npos) {
// Backend already listed!
ERROR_LOG(Log::Loader, "Unexpected: Backend already in failed backends. Should not have been attempted");
} else if (g_Config.sFailedGPUBackends.find("ALL") == std::string::npos) {
g_Config.sFailedGPUBackends += "," + GPUBackendToString((GPUBackend)g_Config.iGPUBackend);
}
// Let's try to create, in case it doesn't exist.
File::CreateFullPath(failedBackendsDir);
File::WriteStringToFile(true, g_Config.sFailedGPUBackends, failedBackendsFile);
}
static void ClearFailedGPUBackends() {
if (g_Config.sFailedGPUBackends == "IGNORE")
return;
const Path failedBackendsDir = GetFailedBackendsDir();
const Path failedBackendsFile = failedBackendsDir / "FailedGraphicsBackends.txt";
// We've successfully started graphics without crashing, hurray.
// In case they update drivers and have totally different problems much later, clear the failed list.
g_Config.sFailedGPUBackends.clear();
File::Delete(failedBackendsFile);
}
void NativeInit(int argc, const char *argv[], const char *savegame_dir, const char *external_dir, const char *cache_dir) {
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.
g_Config.Init();
IncrementDebugCounter(DebugCounter::APP_BOOT);
// Probably an excessive timeout. it only causes delays on shutdown, though.
__UPnPInit(2000);
ShaderTranslationInit();
g_threadManager.Init(cpu_info.num_cores, cpu_info.logical_cpu_count);
g_recentFiles.EnsureThread();
// Make sure UI state is MENU.
ResetUIState();
bool skipLogo = false;
setlocale( LC_ALL, "C" );
std::string user_data_path = savegame_dir;
pendingMessages.clear();
g_pendingClosures.clear();
g_requestManager.Clear();
// external_dir has all kinds of meanings depending on platform.
// on iOS it's even the path to bundled app assets. It's a mess.
// We want this to be FIRST.
#if PPSSPP_PLATFORM(IOS) || PPSSPP_PLATFORM(MAC)
// Packed assets are included in app
g_VFS.Register("", new DirectoryReader(Path(external_dir)));
#endif
#if defined(ASSETS_DIR)
g_VFS.Register("", new DirectoryReader(Path(ASSETS_DIR)));
#endif
#if !defined(MOBILE_DEVICE) && !defined(_WIN32) && !PPSSPP_PLATFORM(SWITCH)
g_VFS.Register("", new DirectoryReader(File::GetExeDirectory() / "assets"));
g_VFS.Register("", new DirectoryReader(File::GetExeDirectory()));
g_VFS.Register("", new DirectoryReader(Path("/usr/local/share/ppsspp/assets")));
g_VFS.Register("", new DirectoryReader(Path("/usr/local/share/games/ppsspp/assets")));
g_VFS.Register("", new DirectoryReader(Path("/usr/share/ppsspp/assets")));
g_VFS.Register("", new DirectoryReader(Path("/usr/share/games/ppsspp/assets")));
#endif
#if PPSSPP_PLATFORM(SWITCH)
Path assetPath = Path(user_data_path) / "assets";
g_VFS.Register("", new DirectoryReader(assetPath));
#else
g_VFS.Register("", new DirectoryReader(Path("assets")));
#endif
g_VFS.Register("", new DirectoryReader(Path(savegame_dir)));
#if PPSSPP_PLATFORM(WINDOWS) || PPSSPP_PLATFORM(MAC)
g_Config.defaultCurrentDirectory = Path(System_GetProperty(SYSPROP_USER_DOCUMENTS_DIR));
#else
g_Config.defaultCurrentDirectory = Path("/");
#endif
#if !PPSSPP_PLATFORM(UWP)
g_Config.internalDataDirectory = Path(savegame_dir);
#endif
#if PPSSPP_PLATFORM(ANDROID)
// In Android 12 with scoped storage, due to the above, the external directory
// is no longer the plain root of external storage, but it's an app specific directory
// on external storage (g_extFilesDir).
if (System_GetPropertyBool(SYSPROP_ANDROID_SCOPED_STORAGE)) {
// There's no sensible default directory. Let the user browse for files.
g_Config.defaultCurrentDirectory.clear();
} else {
g_Config.memStickDirectory = Path(external_dir);
g_Config.defaultCurrentDirectory = Path(external_dir);
}
// Might also add an option to move it to internal / non-visible storage, but there's
// little point, really.
g_Config.flash0Directory = Path(external_dir) / "flash0";
Path memstickDirFile = g_Config.internalDataDirectory / "memstick_dir.txt";
if (File::Exists(memstickDirFile)) {
INFO_LOG(Log::System, "Reading '%s' to find memstick dir.", memstickDirFile.c_str());
std::string memstickDir;
if (File::ReadTextFileToString(memstickDirFile, &memstickDir)) {
Path memstickPath(memstickDir);
if (!memstickPath.empty() && File::Exists(memstickPath)) {
g_Config.memStickDirectory = memstickPath;
INFO_LOG(Log::System, "Memstick Directory from memstick_dir.txt: '%s'", g_Config.memStickDirectory.c_str());
} else {
ERROR_LOG(Log::System, "Couldn't read directory '%s' specified by memstick_dir.txt.", memstickDir.c_str());
if (System_GetPropertyBool(SYSPROP_ANDROID_SCOPED_STORAGE)) {
// Ask the user to configure a memstick directory.
INFO_LOG(Log::System, "Asking the user.");
g_Config.memStickDirectory.clear();
}
}
}
} else {
INFO_LOG(Log::System, "No memstick directory file found (tried to open '%s')", memstickDirFile.c_str());
}
// Attempt to create directories after reading the path.
if (!System_GetPropertyBool(SYSPROP_ANDROID_SCOPED_STORAGE)) {
CreateSysDirectories();
}
#elif PPSSPP_PLATFORM(UWP) && !defined(__LIBRETRO__)
Path memstickDirFile = g_Config.internalDataDirectory / "memstick_dir.txt";
if (File::Exists(memstickDirFile)) {
INFO_LOG(Log::System, "Reading '%s' to find memstick dir.", memstickDirFile.c_str());
std::string memstickDir;
if (File::ReadTextFileToString(memstickDirFile, &memstickDir)) {
Path memstickPath(memstickDir);
if (!memstickPath.empty() && File::Exists(memstickPath)) {
g_Config.memStickDirectory = memstickPath;
g_Config.SetSearchPath(GetSysDirectory(DIRECTORY_SYSTEM));
g_Config.Reload();
INFO_LOG(Log::System, "Memstick Directory from memstick_dir.txt: '%s'", g_Config.memStickDirectory.c_str());
} else {
ERROR_LOG(Log::System, "Couldn't read directory '%s' specified by memstick_dir.txt.", memstickDir.c_str());
g_Config.memStickDirectory.clear();
}
}
}
else {
INFO_LOG(Log::System, "No memstick directory file found (tried to open '%s')", memstickDirFile.c_str());
}
#elif PPSSPP_PLATFORM(IOS)
g_Config.defaultCurrentDirectory = g_Config.internalDataDirectory;
g_Config.memStickDirectory = DarwinFileSystemServices::appropriateMemoryStickDirectoryToUse();
g_Config.flash0Directory = Path(external_dir) / "flash0";
#elif PPSSPP_PLATFORM(MAC)
g_Config.memStickDirectory = DarwinFileSystemServices::appropriateMemoryStickDirectoryToUse();
g_Config.flash0Directory = Path(external_dir) / "flash0";
#elif PPSSPP_PLATFORM(SWITCH)
g_Config.memStickDirectory = g_Config.internalDataDirectory / "config/ppsspp";
g_Config.flash0Directory = g_Config.internalDataDirectory / "assets/flash0";
#elif !PPSSPP_PLATFORM(WINDOWS)
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 = Path(config) / "ppsspp";
g_Config.flash0Directory = File::GetExeDirectory() / "assets/flash0";
if (getenv("HOME") != nullptr) {
g_Config.defaultCurrentDirectory = Path(getenv("HOME"));
} else {
// Hm, should probably actually explicitly set the current directory..
// Though it's not many platforms that'll land us here.
g_Config.currentDirectory = Path(".");
}
#endif
if (g_Config.currentDirectory.empty()) {
g_Config.currentDirectory = g_Config.defaultCurrentDirectory;
}
if (cache_dir && strlen(cache_dir)) {
g_Config.appCacheDirectory = Path(cache_dir);
DiskCachingFileLoaderCache::SetCacheDir(g_Config.appCacheDirectory);
}
g_logManager.Init(&g_Config.bEnableLogging);
#if !PPSSPP_PLATFORM(WINDOWS)
g_Config.SetSearchPath(GetSysDirectory(DIRECTORY_SYSTEM));
// Note that if we don't have storage permission here, loading the config will
// fail and it will be set to the default. Later, we load again when we get permission.
g_Config.Load();
#endif
const char *fileToLog = nullptr;
Path stateToLoad;
bool gotBootFilename = false;
bool gotoGameSettings = false;
bool gotoTouchScreenTest = false;
bool gotoDeveloperTools = false;
boot_filename.clear();
// Parse command line
LogLevel logLevel = LogLevel::LINFO;
bool forceLogLevel = false;
const auto setLogLevel = [&logLevel, &forceLogLevel](LogLevel level) {
logLevel = level;
forceLogLevel = true;
};
// TODO: Need a much better command line argument parser.
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
#if defined(__APPLE__)
// On Apple system debugged executable may get -NSDocumentRevisionsDebugMode YES in argv.
if (!strcmp(argv[i], "-NSDocumentRevisionsDebugMode") && argc - 1 > i) {
i++;
continue;
}
#endif
switch (argv[i][1]) {
case 'd':
// Enable debug logging
// Note that you must also change the max log level in Log.h.
setLogLevel(LogLevel::LDEBUG);
break;
case 'v':
// Enable verbose logging
// Note that you must also change the max log level in Log.h.
setLogLevel(LogLevel::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_INTERPRETER;
g_Config.bSaveSettings = false;
break;
case 'J':
g_Config.iCpuCore = (int)CPUCore::JIT_IR;
g_Config.bSaveSettings = false;
break;
case '-':
if (!strncmp(argv[i], "--loglevel=", strlen("--loglevel=")) && strlen(argv[i]) > strlen("--loglevel="))
setLogLevel(static_cast<LogLevel>(std::atoi(argv[i] + strlen("--loglevel="))));
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 = Path(argv[i] + strlen("--state="));
if (!strncmp(argv[i], "--escape-exit", strlen("--escape-exit")))
g_Config.bPauseExitsEmulator = true;
if (!strncmp(argv[i], "--pause-menu-exit", strlen("--pause-menu-exit")))
g_Config.bPauseMenuExitsEmulator = true;
if (!strcmp(argv[i], "--fullscreen")) {
g_Config.iForceFullScreen = 1;
System_ToggleFullscreenState("1");
}
if (!strncmp(argv[i], "--root=", strlen("--root=")) && strlen(argv[i]) > strlen("--root=")) {
g_Config.mountRoot = Path(argv[i] + strlen("--root="));
}
if (!strcmp(argv[i], "--windowed")) {
g_Config.iForceFullScreen = 0;
System_ToggleFullscreenState("0");
}
if (!strcmp(argv[i], "--touchscreentest"))
gotoTouchScreenTest = true;
if (!strcmp(argv[i], "--gamesettings"))
gotoGameSettings = true;
if (!strcmp(argv[i], "--developertools"))
gotoDeveloperTools = true;
if (!strncmp(argv[i], "--appendconfig=", strlen("--appendconfig=")) && strlen(argv[i]) > strlen("--appendconfig=")) {
g_Config.SetAppendedConfigIni(Path(argv[i] + strlen("--appendconfig=")));
g_Config.LoadAppendedConfig();
}
break;
}
} else {
// This parameter should be a boot filename. Only accept it if we
// don't already have one.
if (!gotBootFilename) {
gotBootFilename = true;
INFO_LOG(Log::System, "Boot filename found in args: '%s'", argv[i]);
bool okToLoad = true;
bool okToCheck = true;
if (System_GetPropertyBool(SYSPROP_SUPPORTS_PERMISSIONS)) {
PermissionStatus status = System_GetPermissionStatus(SYSTEM_PERMISSION_STORAGE);
if (status == PERMISSION_STATUS_DENIED) {
ERROR_LOG(Log::IO, "Storage permission denied. Launching without argument.");
okToLoad = false;
okToCheck = false;
} else if (status != PERMISSION_STATUS_GRANTED) {
ERROR_LOG(Log::IO, "Storage permission not granted. Launching without argument check.");
okToCheck = false;
} else {
INFO_LOG(Log::IO, "Storage permission granted.");
}
}
if (okToLoad) {
std::string str = std::string(argv[i]);
// Handle file:/// URIs, since you get those when creating shortcuts on some Android systems.
if (startsWith(str, "file:///")) {
str = UriDecode(str.substr(7));
INFO_LOG(Log::IO, "Decoding '%s' to '%s'", argv[i], str.c_str());
}
boot_filename = Path(str);
skipLogo = true;
}
if (okToLoad && okToCheck) {
std::unique_ptr<FileLoader> fileLoader(ConstructFileLoader(boot_filename));
if (!fileLoader->Exists()) {
fprintf(stderr, "File not found: %s\n", boot_filename.c_str());
#if defined(_WIN32) || defined(__ANDROID__)
// Ignore and proceed.
boot_filename.clear();
#else
// Bail.
exit(1);
#endif
}
}
} else {
fprintf(stderr, "Syntax error: Can only boot one file.\nNote: Many command line args need a =, like --appendconfig=FILENAME.ini.\n");
#if defined(_WIN32) || defined(__ANDROID__)
// Ignore and proceed.
#else
// Bail.
exit(1);
#endif
}
}
}
if (fileToLog) {
g_logManager.EnableOutput(LogOutput::File);
g_logManager.SetFileLogPath(Path(fileToLog));
} else {
// Set a default file logging path, in case the user enables it with the checkbox later.
g_logManager.SetFileLogPath(GetSysDirectory(DIRECTORY_DUMP) / "log.txt");
}
if (forceLogLevel) {
NOTICE_LOG(Log::System, "Setting log level to %d due to command line override", (int)logLevel);
g_logManager.SetAllLogLevels(logLevel);
}
PostLoadConfig();
#if PPSSPP_PLATFORM(ANDROID)
// Stdio is used for Android logging too.
g_logManager.EnableOutput(LogOutput::Stdio);
#elif (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.
// TODO: Why not use stdio?
g_logManager.EnableOutput(LogOutput::Printf);
#endif
if (System_GetPropertyBool(SYSPROP_SUPPORTS_PERMISSIONS)) {
if (System_GetPermissionStatus(SYSTEM_PERMISSION_STORAGE) != PERMISSION_STATUS_GRANTED) {
System_AskForPermission(SYSTEM_PERMISSION_STORAGE);
}
}
g_BackgroundAudio.SFX().Init();
if (!boot_filename.empty() && stateToLoad.Valid()) {
SaveState::Load(stateToLoad, -1, [](SaveState::Status status, std::string_view message) {
if (!message.empty() && (!g_Config.bDumpFrames || !g_Config.bDumpVideoOutput)) {
g_OSD.Show(status == SaveState::Status::SUCCESS ? OSDType::MESSAGE_SUCCESS : OSDType::MESSAGE_ERROR,
message, status == SaveState::Status::SUCCESS ? 2.0 : 5.0);
}
});
}
if (g_Config.bAchievementsEnable) {
FILE *iconCacheFile = File::OpenCFile(GetSysDirectory(DIRECTORY_CACHE) / "icon.cache", "rb");
if (iconCacheFile) {
g_iconCache.LoadFromFile(iconCacheFile);
fclose(iconCacheFile);
}
}
g_DownloadManager.SetCacheDir(GetSysDirectory(DIRECTORY_APP_CACHE));
DEBUG_LOG(Log::System, "ScreenManager!");
g_screenManager = new ScreenManager();
if (g_Config.memStickDirectory.empty()) {
INFO_LOG(Log::System, "No memstick directory! Asking for one to be configured.");
g_screenManager->switchScreen(new LogoScreen(AfterLogoScreen::MEMSTICK_SCREEN_INITIAL_SETUP));
} else if (gotoGameSettings) {
g_screenManager->switchScreen(new LogoScreen(AfterLogoScreen::TO_GAME_SETTINGS));
} else if (gotoTouchScreenTest) {
g_screenManager->switchScreen(new MainScreen());
g_screenManager->push(new TouchTestScreen(Path()));
} else if (gotoDeveloperTools) {
g_screenManager->switchScreen(new MainScreen());
g_screenManager->push(new DeveloperToolsScreen(Path()));
} else if (skipLogo && !boot_filename.empty()) {
INFO_LOG(Log::System, "Launching EmuScreen with boot filename '%s'", boot_filename.c_str());
g_screenManager->switchScreen(new EmuScreen(boot_filename));
} else {
g_screenManager->switchScreen(new LogoScreen(AfterLogoScreen::DEFAULT));
}
g_screenManager->SetBackgroundOverlayScreens(new BackgroundScreen(), new OSDOverlayScreen());
// Easy testing
// screenManager->push(new GPUDriverTestScreen());
WebServerFlags flags = (WebServerFlags)0;
if (g_Config.bRemoteShareOnStartup) {
flags |= WebServerFlags::DISCS;
}
if (g_Config.bRemoteDebuggerOnStartup) {
flags |= WebServerFlags::DEBUGGER;
}
if (flags != WebServerFlags::NONE) {
StartWebServer(WebServerFlags::ALL);
}
std::string sysName = System_GetProperty(SYSPROP_NAME);
// 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.
CheckFailedGPUBackends();
SetGPUBackend((GPUBackend)g_Config.iGPUBackend);
renderCounter = 0;
// Initialize retro achievements runtime.
Achievements::Initialize();
// Must be done restarting by now.
restarting = false;
}
void CallbackPostRender(UIContext *dc, void *userdata);
bool CreateGlobalPipelines();
// TODO: Add faster special case for channels == 2.
static void NativeMixWrapper(float *dest, int framesToWrite, int sampleRateHz, void *userdata) {
static int16_t *buffer;
static int bufSize;
if (bufSize < framesToWrite * 2) {
buffer = new int16_t[framesToWrite * 2];
bufSize = framesToWrite * 2;
}
NativeMix(buffer, framesToWrite, sampleRateHz, userdata);
for (int i = 0; i < framesToWrite * 2; i++) {
dest[i] = (float)buffer[i] * (float)(1.0f / 32767.0f);
}
}
bool NativeInitGraphics(GraphicsContext *graphicsContext) {
INFO_LOG(Log::System, "NativeInitGraphics");
_assert_msg_(g_screenManager, "No screenmanager, bad init order. Backend = %d", g_Config.iGPUBackend);
// We set this now so any resize during init is processed later.
resized = false;
Core_SetGraphicsContext(graphicsContext);
g_draw = graphicsContext->GetDrawContext();
_assert_(g_draw);
if (!CreateGlobalPipelines()) {
ERROR_LOG(Log::G3D, "Failed to create global pipelines");
return false;
}
ui_draw2d.SetAtlas(GetUIAtlas());
ui_draw2d.SetFontAtlas(GetFontAtlas());
uiContext = new UIContext();
uiContext->SetTheme(GetTheme());
uiContext->SetAtlasProvider(&AtlasProvider);
UpdateTheme();
ui_draw2d.Init(g_draw, texColorPipeline);
uiContext->Init(g_draw, texColorPipeline, colorPipeline, &ui_draw2d);
if (uiContext->Text()) {
// This seems unnecessary.
// uiContext->Text()->SetOrCreateFont(FontStyle(FontID::invalid(), FontFamily::SansSerif, 20, FontStyleFlags::Default));
}
g_screenManager->setUIContext(uiContext);
g_screenManager->setPostRenderCallback(&CallbackPostRender, nullptr);
g_screenManager->deviceRestored(g_draw);
g_audioBackend = System_CreateAudioBackend();
if (g_audioBackend) {
g_audioBackend->SetRenderCallback(&NativeMixWrapper, nullptr);
bool reverted = false;
g_audioBackend->InitOutputDevice(g_Config.sAudioDevice, LatencyMode::Aggressive, &reverted);
if (reverted) {
g_Config.sAudioDevice.clear();
}
}
#if defined(_WIN32) && !PPSSPP_PLATFORM(UWP)
if (IsWin7OrHigher()) {
winCamera = new WindowsCaptureDevice(CAPTUREDEVIDE_TYPE::VIDEO);
winCamera->sendMessage({ CAPTUREDEVIDE_COMMAND::INITIALIZE, nullptr });
winMic = new WindowsCaptureDevice(CAPTUREDEVIDE_TYPE::Audio);
winMic->sendMessage({ CAPTUREDEVIDE_COMMAND::INITIALIZE, nullptr });
}
#endif
// Warn about low refresh rates on desktop. Might add other platforms later.
#if PPSSPP_PLATFORM(WINDOWS) || PPSSPP_PLATFORM(MAC)
const double displayHz = System_GetPropertyFloat(SYSPROP_DISPLAY_REFRESH_RATE);
if (displayHz < 55.0f) {
// This is a warning, not an error.
auto g = GetI18NCategory(I18NCat::GRAPHICS);
g_OSD.Show(OSDType::MESSAGE_WARNING, ApplySafeSubstitutions(g->T("Your display is set to a low refresh rate: %1 Hz. 60 Hz or higher is recommended."), (int)displayHz), 8.0f, "low_refresh");
g_OSD.SetClickCallback("low_refresh", [](bool clicked, void *) {
if (clicked) {
// Open the display settings.
System_OpenDisplaySettings();
}
}, nullptr);
}
#endif
g_gameInfoCache = new GameInfoCache();
if (gpu) {
PSP_CoreParameter().pixelWidth = g_display.pixel_xres;
PSP_CoreParameter().pixelHeight = g_display.pixel_yres;
gpu->DeviceRestore(g_draw);
}
INFO_LOG(Log::System, "NativeInitGraphics completed");
return true;
}
bool CreateGlobalPipelines() {
using namespace Draw;
ShaderModule *vs_color_2d = g_draw->GetVshaderPreset(VS_COLOR_2D);
ShaderModule *fs_color_2d = g_draw->GetFshaderPreset(FS_COLOR_2D);
ShaderModule *vs_texture_color_2d = g_draw->GetVshaderPreset(VS_TEXTURE_COLOR_2D);
ShaderModule *fs_texture_color_2d = g_draw->GetFshaderPreset(FS_TEXTURE_COLOR_2D);
if (!vs_color_2d || !fs_color_2d || !vs_texture_color_2d || !fs_texture_color_2d) {
ERROR_LOG(Log::G3D, "Failed to get shader preset");
return false;
}
InputLayout *inputLayout = ui_draw2d.CreateInputLayout(g_draw);
BlendState *blendNormal = g_draw->CreateBlendState({ true, 0xF, BlendFactor::ONE, BlendFactor::ONE_MINUS_SRC_ALPHA });
DepthStencilState *depth = g_draw->CreateDepthStencilState({ false, false, Comparison::LESS });
RasterState *rasterNoCull = g_draw->CreateRasterState({});
PipelineDesc colorDesc{
Primitive::TRIANGLE_LIST,
{ vs_color_2d, fs_color_2d },
inputLayout, depth, blendNormal, rasterNoCull, &vsColBufDesc,
};
PipelineDesc texColorDesc{
Primitive::TRIANGLE_LIST,
{ vs_texture_color_2d, fs_texture_color_2d },
inputLayout, depth, blendNormal, rasterNoCull, &vsTexColBufDesc,
};
colorPipeline = g_draw->CreateGraphicsPipeline(colorDesc, "global_color");
if (!colorPipeline) {
// Something really critical is wrong, don't care much about correct releasing of the states.
return false;
}
texColorPipeline = g_draw->CreateGraphicsPipeline(texColorDesc, "global_texcolor");
if (!texColorPipeline) {
// Something really critical is wrong, don't care much about correct releasing of the states.
return false;
}
// 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();
return true;
}
void NativeShutdownGraphics() {
INFO_LOG(Log::System, "NativeShutdownGraphics begin");
if (g_screenManager) {
g_screenManager->deviceLost();
}
g_iconCache.ClearTextures();
// TODO: This is not really necessary with Vulkan on Android - could keep shaders etc in memory
if (gpu)
gpu->DeviceLost();
#if PPSSPP_PLATFORM(WINDOWS) && !PPSSPP_PLATFORM(UWP)
if (winCamera) {
winCamera->waitShutDown();
delete winCamera;
winCamera = nullptr;
}
if (winMic) {
winMic->waitShutDown();
delete winMic;
winMic = nullptr;
}
#endif
if (g_audioBackend) {
delete g_audioBackend;
g_audioBackend = nullptr;
}
UIBackgroundShutdown();
delete g_gameInfoCache;
g_gameInfoCache = nullptr;
delete uiContext;
uiContext = nullptr;
ui_draw2d.Shutdown();
if (colorPipeline) {
colorPipeline->Release();
colorPipeline = nullptr;
}
if (texColorPipeline) {
texColorPipeline->Release();
texColorPipeline = nullptr;
}
INFO_LOG(Log::System, "NativeShutdownGraphics end");
}
static void TakeScreenshot(Draw::DrawContext *draw) {
Path path = GetSysDirectory(DIRECTORY_SCREENSHOT);
if (!File::Exists(path)) {
File::CreateDir(path);
}
// First, find a free filename.
//
// NOTE: On Android, the old approach of checking filenames one by one doesn't scale.
// So let's just grab the full file listing, and then find a name that's not in it.
//
// TODO: Also, we could do this on a thread too. Not sure if worth it.
const std::string gameId = g_paramSFO.GetDiscID();
// TODO: Make something like IterateFileInDir instead.
std::vector<File::FileInfo> files;
const std::string prefix = gameId + "_";
File::GetFilesInDir(path, &files, nullptr, 0, prefix);
std::set<std::string> existingNames;
for (auto &file : files) {
existingNames.insert(file.name);
}
Path filename;
int i = 0;
for (int i = 0; i < 20000; i++) {
const std::string pngName = prefix + StringFromFormat("%05d.png", i);