Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hrydgard
GitHub Repository: hrydgard/ppsspp
Path: blob/master/Windows/EmuThread.cpp
5654 views
1
#include <mutex>
2
#include <atomic>
3
#include <thread>
4
5
#include "Common/System/NativeApp.h"
6
#include "Common/System/System.h"
7
#include "Common/System/Request.h"
8
#include "Common/Data/Text/I18n.h"
9
#include "Common/Input/InputState.h"
10
#include "Common/Data/Encoding/Utf8.h"
11
#include "Common/Log.h"
12
#include "Common/StringUtils.h"
13
#include "Common/GraphicsContext.h"
14
#include "Common/TimeUtil.h"
15
#include "Common/Thread/ThreadUtil.h"
16
17
#include "Windows/EmuThread.h"
18
#include "Windows/W32Util/Misc.h"
19
#include "Windows/MainWindow.h"
20
#include "Windows/resource.h"
21
#include "Core/Reporting.h"
22
#include "Core/MemMap.h"
23
#include "Core/Core.h"
24
#include "Core/System.h"
25
#include "Core/Config.h"
26
#include "Core/ConfigValues.h"
27
28
#if PPSSPP_API(ANY_GL)
29
#include "Windows/GPU/WindowsGLContext.h"
30
#endif
31
#include "Windows/GPU/WindowsVulkanContext.h"
32
#include "Windows/GPU/D3D11Context.h"
33
34
enum class EmuThreadState {
35
DISABLED,
36
START_REQUESTED,
37
RUNNING,
38
QUIT_REQUESTED,
39
STOPPED,
40
};
41
42
static std::thread emuThread;
43
static std::atomic<EmuThreadState> g_emuThreadState(EmuThreadState::DISABLED);
44
45
static std::thread mainThread;
46
static bool useEmuThread;
47
static std::string g_error_message;
48
static bool g_inLoop;
49
50
extern std::vector<std::wstring> GetWideCmdLine();
51
52
class GraphicsContext;
53
static GraphicsContext *g_graphicsContext;
54
55
void MainThreadFunc();
56
57
// On most other platforms, we let the "main" thread become the render thread and
58
// start a separate emu thread from that, if needed. Should probably switch to that
59
// to make it the same on all platforms.
60
void MainThread_Start(bool separateEmuThread) {
61
useEmuThread = separateEmuThread;
62
mainThread = std::thread(&MainThreadFunc);
63
}
64
65
void MainThread_Stop() {
66
// Already stopped?
67
UpdateUIState(UISTATE_EXIT);
68
_dbg_assert_(mainThread.joinable());
69
mainThread.join();
70
}
71
72
bool MainThread_Ready() {
73
return g_inLoop;
74
}
75
76
static void EmuThreadFunc(GraphicsContext *graphicsContext) {
77
SetCurrentThreadName("EmuThread");
78
79
// There's no real requirement that NativeInit happen on this thread.
80
// We just call the update/render loop here.
81
g_emuThreadState = EmuThreadState::RUNNING;
82
83
NativeInitGraphics(graphicsContext);
84
85
while (g_emuThreadState != EmuThreadState::QUIT_REQUESTED) {
86
// We're here again, so the game quit. Restart Run() which controls the UI.
87
// This way they can load a new game.
88
if (!Core_IsActive()) {
89
UpdateUIState(UISTATE_MENU);
90
}
91
92
Core_StateProcessed();
93
NativeFrame(graphicsContext);
94
95
if (GetUIState() == UISTATE_EXIT) {
96
g_emuThreadState = EmuThreadState::QUIT_REQUESTED;
97
}
98
}
99
100
g_emuThreadState = EmuThreadState::STOPPED;
101
102
NativeShutdownGraphics();
103
}
104
105
static void EmuThreadStart(GraphicsContext *graphicsContext) {
106
g_emuThreadState = EmuThreadState::START_REQUESTED;
107
emuThread = std::thread(&EmuThreadFunc, graphicsContext);
108
}
109
110
static void EmuThreadStop() {
111
const EmuThreadState state = g_emuThreadState;
112
if (state != EmuThreadState::QUIT_REQUESTED &&
113
state != EmuThreadState::STOPPED) {
114
g_emuThreadState = EmuThreadState::QUIT_REQUESTED;
115
}
116
}
117
118
static void EmuThreadJoin() {
119
emuThread.join();
120
INFO_LOG(Log::System, "EmuThreadJoin - joined");
121
}
122
123
bool CreateGraphicsBackend(std::string *error_message, GraphicsContext **ctx) {
124
WindowsGraphicsContext *graphicsContext = nullptr;
125
switch (g_Config.iGPUBackend) {
126
#if PPSSPP_API(ANY_GL)
127
case (int)GPUBackend::OPENGL:
128
graphicsContext = new WindowsGLContext();
129
break;
130
#endif
131
case (int)GPUBackend::DIRECT3D11:
132
graphicsContext = new D3D11Context();
133
break;
134
case (int)GPUBackend::VULKAN:
135
graphicsContext = new WindowsVulkanContext();
136
break;
137
default:
138
return false;
139
}
140
141
if (graphicsContext->Init(MainWindow::GetHInstance(), MainWindow::GetHWND(), error_message)) {
142
*ctx = graphicsContext;
143
return true;
144
} else {
145
delete graphicsContext;
146
*ctx = nullptr;
147
return false;
148
}
149
}
150
151
void MainThreadFunc() {
152
// We'll start up a separate thread we'll call Emu
153
SetCurrentThreadName(useEmuThread ? "RenderThread" : "EmuThread");
154
155
const HWND console = GetConsoleWindow();
156
if (console && g_Config.iConsoleWindowX != -1 && g_Config.iConsoleWindowY != -1) {
157
SetWindowPos(console, NULL, g_Config.iConsoleWindowX, g_Config.iConsoleWindowY, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
158
}
159
160
System_SetWindowTitle("");
161
162
// We convert command line arguments to UTF-8 immediately.
163
std::vector<std::wstring> wideArgs = GetWideCmdLine();
164
std::vector<std::string> argsUTF8;
165
for (auto& string : wideArgs) {
166
argsUTF8.push_back(ConvertWStringToUTF8(string));
167
}
168
std::vector<const char *> args;
169
for (auto& string : argsUTF8) {
170
args.push_back(string.c_str());
171
}
172
bool performingRestart = NativeIsRestarting();
173
NativeInit(static_cast<int>(args.size()), &args[0], "", "", nullptr);
174
175
if (g_Config.iGPUBackend == (int)GPUBackend::OPENGL) {
176
if (!useEmuThread) {
177
// Okay, we must've switched to OpenGL. Let's flip the emu thread on.
178
useEmuThread = true;
179
SetCurrentThreadName("Render");
180
}
181
} else if (useEmuThread) {
182
// We must've failed over from OpenGL, flip the emu thread off.
183
useEmuThread = false;
184
SetCurrentThreadName("EmuThread");
185
}
186
187
if (g_Config.sFailedGPUBackends.find("ALL") != std::string::npos) {
188
Reporting::ReportMessage("Graphics init error: %s", "ALL");
189
190
auto err = GetI18NCategory(I18NCat::ERRORS);
191
const char *defaultErrorAll = "PPSSPP failed to startup with any graphics backend. Try upgrading your graphics and other drivers.";
192
std::string_view genericError = err->T("GenericAllStartupError", defaultErrorAll);
193
std::wstring title = ConvertUTF8ToWString(err->T("GenericGraphicsError", "Graphics Error"));
194
MessageBox(0, ConvertUTF8ToWString(genericError).c_str(), title.c_str(), MB_OK);
195
196
// Let's continue (and probably crash) just so they have a way to keep trying.
197
}
198
199
System_Notify(SystemNotification::UI);
200
201
std::string error_string;
202
bool success = CreateGraphicsBackend(&error_string, &g_graphicsContext);
203
204
if (success) {
205
// Main thread is the render thread.
206
success = g_graphicsContext->InitFromRenderThread(&error_string);
207
}
208
209
if (!success) {
210
// Before anything: are we restarting right now?
211
if (performingRestart) {
212
// Okay, switching graphics didn't work out. Probably a driver bug - fallback to restart.
213
// This happens on NVIDIA when switching OpenGL -> Vulkan.
214
g_Config.Save("switch_graphics_failed");
215
W32Util::ExitAndRestart();
216
}
217
218
auto err = GetI18NCategory(I18NCat::ERRORS);
219
Reporting::ReportMessage("Graphics init error: %s", error_string.c_str());
220
221
const char *defaultErrorVulkan = "Failed initializing graphics. Try upgrading your graphics drivers.\n\nWould you like to try switching to OpenGL?\n\nError message:";
222
const char *defaultErrorOpenGL = "Failed initializing graphics. Try upgrading your graphics drivers.\n\nWould you like to try switching to DirectX 9?\n\nError message:";
223
const char *defaultErrorDirect3D9 = "Failed initializing graphics. Try upgrading your graphics drivers and directx 9 runtime.\n\nWould you like to try switching to OpenGL?\n\nError message:";
224
std::string_view genericError;
225
GPUBackend nextBackend = GPUBackend::VULKAN;
226
switch (g_Config.iGPUBackend) {
227
case (int)GPUBackend::VULKAN:
228
nextBackend = GPUBackend::OPENGL;
229
genericError = err->T("GenericVulkanError", defaultErrorVulkan);
230
break;
231
case (int)GPUBackend::OPENGL:
232
default:
233
nextBackend = GPUBackend::DIRECT3D11;
234
genericError = err->T("GenericOpenGLError", defaultErrorOpenGL);
235
break;
236
}
237
std::string full_error = StringFromFormat("%.*s\n\n%s", (int)genericError.size(), genericError.data(), error_string.c_str());
238
std::wstring title = ConvertUTF8ToWString(err->T("GenericGraphicsError", "Graphics Error"));
239
bool yes = IDYES == MessageBox(0, ConvertUTF8ToWString(full_error).c_str(), title.c_str(), MB_ICONERROR | MB_YESNO);
240
ERROR_LOG(Log::Boot, "%s", full_error.c_str());
241
242
if (yes) {
243
// Change the config to the alternative and restart.
244
g_Config.iGPUBackend = (int)nextBackend;
245
// Clear this to ensure we try their selection.
246
g_Config.sFailedGPUBackends.clear();
247
g_Config.Save("save_graphics_fallback");
248
249
W32Util::ExitAndRestart();
250
}
251
252
// No safe way out without graphics.
253
ExitProcess(1);
254
}
255
256
GraphicsContext *graphicsContext = g_graphicsContext;
257
258
if (!useEmuThread) {
259
NativeInitGraphics(graphicsContext);
260
NativeResized();
261
}
262
263
DEBUG_LOG(Log::Boot, "Done.");
264
265
g_inLoop = true;
266
267
if (useEmuThread) {
268
EmuThreadStart(graphicsContext);
269
}
270
graphicsContext->ThreadStart();
271
272
if (useEmuThread) {
273
while (true) {
274
if (equals_any(g_emuThreadState, EmuThreadState::QUIT_REQUESTED, EmuThreadState::STOPPED)) {
275
break;
276
}
277
graphicsContext->ThreadFrame(true);
278
if (GetUIState() == UISTATE_EXIT) {
279
break;
280
}
281
}
282
} else {
283
while (GetUIState() != UISTATE_EXIT) { // && GetUIState() != UISTATE_EXCEPTION
284
// We're here again, so the game quit. Restart Run() which controls the UI.
285
// This way they can load a new game.
286
if (!(Core_IsActive() || Core_IsStepping()))
287
UpdateUIState(UISTATE_MENU);
288
Core_StateProcessed();
289
NativeFrame(graphicsContext);
290
}
291
}
292
Core_Stop();
293
if (!useEmuThread) {
294
// Process the shutdown. Without this, non-GL delays 800ms on shutdown.
295
Core_StateProcessed();
296
NativeFrame(graphicsContext);
297
}
298
299
g_inLoop = false;
300
301
if (useEmuThread) {
302
EmuThreadStop();
303
graphicsContext->ThreadFrameUntilCondition([] {
304
// Need to keep eating frames to allow the EmuThread to exit correctly.
305
return g_emuThreadState == EmuThreadState::STOPPED;
306
});
307
EmuThreadJoin();
308
}
309
310
if (!useEmuThread) {
311
NativeShutdownGraphics();
312
}
313
314
g_graphicsContext->ThreadEnd();
315
g_graphicsContext->ShutdownFromRenderThread();
316
317
g_graphicsContext->Shutdown();
318
319
delete g_graphicsContext;
320
g_graphicsContext = nullptr;
321
322
RECT rc;
323
if (console && GetWindowRect(console, &rc) && !IsIconic(console)) {
324
g_Config.iConsoleWindowX = rc.left;
325
g_Config.iConsoleWindowY = rc.top;
326
}
327
328
NativeShutdown();
329
330
PostMessage(MainWindow::GetHWND(), MainWindow::WM_USER_UPDATE_UI, 0, 0);
331
}
332
333