1#include <base/dbg.h>
2#include <base/log.h>
3#include <base/math.h>
4#include <base/sphore.h>
5#include <base/str.h>
6#include <base/thread.h>
7
8#include <engine/client/backend_sdl.h>
9#include <engine/client/graphics_threaded.h>
10#include <engine/graphics.h>
11#include <engine/shared/config.h>
12
13#if defined(CONF_VIDEORECORDER) && !defined(BACKEND_NO_SDL)
14#include <engine/shared/video.h>
15#endif
16
17#if defined(CONF_PLATFORM_MACOS)
18#include <CoreFoundation/CFRunLoop.h>
19
20#include <chrono>
21#include <cstdlib>
22#endif
23
24class IStorage;
25
26// ------------ CGraphicsBackend_Threaded
27
28// Run everything single threaded when compiling for Emscripten, as context binding does not work outside of the main thread with SDL2.
29// TODO SDL3: Check if SDL3 supports threaded graphics and PROXY_TO_PTHREAD, OFFSCREENCANVAS_SUPPORT and OFFSCREEN_FRAMEBUFFER correctly.
30#if !defined(CONF_PLATFORM_EMSCRIPTEN)
31void CGraphicsBackend_Threaded::ThreadFunc(void *pUser)
32{
33 auto *pSelf = (CGraphicsBackend_Threaded *)pUser;
34 std::unique_lock<std::mutex> Lock(pSelf->m_BufferSwapMutex);
35 // notify, that the thread started
36 pSelf->m_Started = true;
37 pSelf->m_BufferSwapCond.notify_all();
38 while(!pSelf->m_Shutdown)
39 {
40 pSelf->m_BufferSwapCond.wait(lock&: Lock, p: [&pSelf] { return pSelf->m_pBuffer != nullptr || pSelf->m_Shutdown; });
41 if(pSelf->m_pBuffer)
42 {
43#if defined(CONF_PLATFORM_MACOS) || defined(CONF_PLATFORM_IOS)
44 CAutoreleasePool AutoreleasePool;
45#endif
46 Lock.unlock();
47 pSelf->m_pProcessor->RunBuffer(pBuffer: pSelf->m_pBuffer);
48 Lock.lock();
49
50 pSelf->m_pBuffer = nullptr;
51 pSelf->m_BufferInProcess.store(i: false, m: std::memory_order_relaxed);
52 pSelf->m_BufferSwapCond.notify_all();
53
54#if defined(CONF_VIDEORECORDER) && !defined(BACKEND_NO_SDL)
55 if(IVideo::Current())
56 IVideo::Current()->NextVideoFrameThread();
57#endif
58 }
59 }
60}
61#endif
62
63CGraphicsBackend_Threaded::CGraphicsBackend_Threaded(TTranslateFunc &&TranslateFunc) :
64 m_TranslateFunc(std::move(TranslateFunc))
65{
66 m_pProcessor = nullptr;
67 m_Shutdown = true;
68#if !defined(CONF_PLATFORM_EMSCRIPTEN)
69 m_pBuffer = nullptr;
70 m_BufferInProcess.store(i: false, m: std::memory_order_relaxed);
71#endif
72}
73
74void CGraphicsBackend_Threaded::StartProcessor(ICommandProcessor *pProcessor)
75{
76 dbg_assert(m_Shutdown, "Processor was already not shut down.");
77 m_Shutdown = false;
78 m_pProcessor = pProcessor;
79#if !defined(CONF_PLATFORM_EMSCRIPTEN)
80 std::unique_lock<std::mutex> Lock(m_BufferSwapMutex);
81 m_pThread = thread_init(threadfunc: ThreadFunc, user: this, name: "Graphics thread");
82 // wait for the thread to start
83 m_BufferSwapCond.wait(lock&: Lock, p: [this]() -> bool { return m_Started; });
84#endif
85}
86
87void CGraphicsBackend_Threaded::StopProcessor()
88{
89 dbg_assert(!m_Shutdown, "Processor was already shut down.");
90 m_Shutdown = true;
91#if defined(CONF_PLATFORM_EMSCRIPTEN)
92 m_Warning = m_pProcessor->GetWarning();
93#else
94 {
95 std::unique_lock<std::mutex> Lock(m_BufferSwapMutex);
96 m_Warning = m_pProcessor->GetWarning();
97 m_BufferSwapCond.notify_all();
98 }
99 thread_wait(thread: m_pThread);
100#endif
101}
102
103void CGraphicsBackend_Threaded::RunBuffer(CCommandBuffer *pBuffer)
104{
105 SGfxErrorContainer Error;
106#if defined(CONF_PLATFORM_EMSCRIPTEN)
107 Error = m_pProcessor->GetError();
108 if(Error.m_ErrorType == GFX_ERROR_TYPE_NONE)
109 {
110 RunBufferSingleThreadedUnsafe(pBuffer);
111#if defined(CONF_VIDEORECORDER) && !defined(BACKEND_NO_SDL)
112 if(IVideo::Current())
113 IVideo::Current()->NextVideoFrameThread();
114#endif
115 }
116#else
117 WaitForIdle();
118 {
119 std::unique_lock<std::mutex> Lock(m_BufferSwapMutex);
120 Error = m_pProcessor->GetError();
121 if(Error.m_ErrorType == GFX_ERROR_TYPE_NONE)
122 {
123 m_pBuffer = pBuffer;
124 m_BufferInProcess.store(i: true, m: std::memory_order_relaxed);
125 m_BufferSwapCond.notify_all();
126 }
127 }
128#endif
129
130 // Process error after lock is released to prevent deadlock
131 if(Error.m_ErrorType != GFX_ERROR_TYPE_NONE)
132 {
133 ProcessError(Error);
134 }
135}
136
137void CGraphicsBackend_Threaded::RunBufferSingleThreadedUnsafe(CCommandBuffer *pBuffer)
138{
139 m_pProcessor->RunBuffer(pBuffer);
140}
141
142bool CGraphicsBackend_Threaded::IsIdle() const
143{
144#if defined(CONF_PLATFORM_EMSCRIPTEN)
145 return true;
146#else
147 return !m_BufferInProcess.load(m: std::memory_order_relaxed);
148#endif
149}
150
151void CGraphicsBackend_Threaded::WaitForIdle()
152{
153#if !defined(CONF_PLATFORM_EMSCRIPTEN)
154 std::unique_lock<std::mutex> Lock(m_BufferSwapMutex);
155#if defined(CONF_PLATFORM_MACOS)
156 while(!m_BufferSwapCond.wait_for(Lock, std::chrono::milliseconds(1), [this]() { return m_pBuffer == nullptr; }))
157 {
158 Lock.unlock();
159 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true);
160 Lock.lock();
161 }
162#else
163 m_BufferSwapCond.wait(lock&: Lock, p: [this]() { return m_pBuffer == nullptr; });
164#endif
165#endif
166}
167
168void CGraphicsBackend_Threaded::ProcessError(const SGfxErrorContainer &Error)
169{
170 m_FatalError = "";
171 for(const auto &ErrStr : Error.m_vErrors)
172 {
173 if(!m_FatalError.empty())
174 {
175 m_FatalError.append(s: "\n");
176 }
177 if(ErrStr.m_RequiresTranslation)
178 m_FatalError.append(s: m_TranslateFunc(ErrStr.m_Err.c_str(), "Graphics error"));
179 else
180 m_FatalError.append(str: ErrStr.m_Err);
181 }
182 std::string LogMessage = "Graphics Error:\n" + m_FatalError;
183 dbg_assert_failed("%s", LogMessage.c_str());
184}
185
186const char *CGraphicsBackend_Threaded::GetFatalError() const
187{
188 return m_FatalError.c_str();
189}
190
191bool CGraphicsBackend_Threaded::GetWarning(std::vector<std::string> &WarningStrings)
192{
193 if(m_Warning.m_WarningType != GFX_WARNING_TYPE_NONE)
194 {
195 m_Warning.m_WarningType = GFX_WARNING_TYPE_NONE;
196 WarningStrings = m_Warning.m_vWarnings;
197 return true;
198 }
199 return false;
200}
201
202// ------------ CCommandProcessorFragment_General
203
204void CCommandProcessorFragment_General::Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand)
205{
206 pCommand->m_pSemaphore->Signal();
207}
208
209bool CCommandProcessorFragment_General::RunCommand(const CCommandBuffer::SCommand *pBaseCommand)
210{
211 switch(pBaseCommand->m_Cmd)
212 {
213 case CCommandBuffer::CMD_SIGNAL: Cmd_Signal(pCommand: static_cast<const CCommandBuffer::SCommand_Signal *>(pBaseCommand)); break;
214 default: return false;
215 }
216
217 return true;
218}
219