ThreadedRenderer.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Configuration;
  3. using Ryujinx.Graphics.GAL.Multithreading.Commands;
  4. using Ryujinx.Graphics.GAL.Multithreading.Commands.Buffer;
  5. using Ryujinx.Graphics.GAL.Multithreading.Commands.Renderer;
  6. using Ryujinx.Graphics.GAL.Multithreading.Model;
  7. using Ryujinx.Graphics.GAL.Multithreading.Resources;
  8. using Ryujinx.Graphics.GAL.Multithreading.Resources.Programs;
  9. using System;
  10. using System.Diagnostics;
  11. using System.Runtime.CompilerServices;
  12. using System.Runtime.InteropServices;
  13. using System.Threading;
  14. namespace Ryujinx.Graphics.GAL.Multithreading
  15. {
  16. /// <summary>
  17. /// The ThreadedRenderer is a layer that can be put in front of any Renderer backend to make
  18. /// its processing happen on a separate thread, rather than intertwined with the GPU emulation.
  19. /// A new thread is created to handle the GPU command processing, separate from the renderer thread.
  20. /// Calls to the renderer, pipeline and resources are queued to happen on the renderer thread.
  21. /// </summary>
  22. public class ThreadedRenderer : IRenderer
  23. {
  24. private const int SpanPoolBytes = 4 * 1024 * 1024;
  25. private const int MaxRefsPerCommand = 2;
  26. private const int QueueCount = 10000;
  27. private int _elementSize;
  28. private IRenderer _baseRenderer;
  29. private Thread _gpuThread;
  30. private Thread _backendThread;
  31. private bool _disposed;
  32. private bool _running;
  33. private AutoResetEvent _frameComplete = new AutoResetEvent(true);
  34. private ManualResetEventSlim _galWorkAvailable;
  35. private CircularSpanPool _spanPool;
  36. private ManualResetEventSlim _invokeRun;
  37. private AutoResetEvent _interruptRun;
  38. private bool _lastSampleCounterClear = true;
  39. private byte[] _commandQueue;
  40. private object[] _refQueue;
  41. private int _consumerPtr;
  42. private int _commandCount;
  43. private int _producerPtr;
  44. private int _lastProducedPtr;
  45. private int _invokePtr;
  46. private int _refProducerPtr;
  47. private int _refConsumerPtr;
  48. private Action _interruptAction;
  49. public event EventHandler<ScreenCaptureImageInfo> ScreenCaptured;
  50. internal BufferMap Buffers { get; }
  51. internal SyncMap Sync { get; }
  52. internal CircularSpanPool SpanPool { get; }
  53. internal ProgramQueue Programs { get; }
  54. public IPipeline Pipeline { get; }
  55. public IWindow Window { get; }
  56. public IRenderer BaseRenderer => _baseRenderer;
  57. public bool PreferThreading => _baseRenderer.PreferThreading;
  58. public ThreadedRenderer(IRenderer renderer)
  59. {
  60. _baseRenderer = renderer;
  61. renderer.ScreenCaptured += (sender, info) => ScreenCaptured?.Invoke(this, info);
  62. renderer.SetInterruptAction(Interrupt);
  63. Pipeline = new ThreadedPipeline(this, renderer.Pipeline);
  64. Window = new ThreadedWindow(this, renderer);
  65. Buffers = new BufferMap();
  66. Sync = new SyncMap();
  67. Programs = new ProgramQueue(renderer);
  68. _galWorkAvailable = new ManualResetEventSlim(false);
  69. _invokeRun = new ManualResetEventSlim();
  70. _interruptRun = new AutoResetEvent(false);
  71. _spanPool = new CircularSpanPool(this, SpanPoolBytes);
  72. SpanPool = _spanPool;
  73. _elementSize = BitUtils.AlignUp(CommandHelper.GetMaxCommandSize(), 4);
  74. _commandQueue = new byte[_elementSize * QueueCount];
  75. _refQueue = new object[MaxRefsPerCommand * QueueCount];
  76. }
  77. public void RunLoop(Action gpuLoop)
  78. {
  79. _running = true;
  80. _backendThread = Thread.CurrentThread;
  81. _gpuThread = new Thread(() => {
  82. gpuLoop();
  83. _running = false;
  84. _galWorkAvailable.Set();
  85. });
  86. _gpuThread.Name = "GPU.MainThread";
  87. _gpuThread.Start();
  88. RenderLoop();
  89. }
  90. public void RenderLoop()
  91. {
  92. // Power through the render queue until the Gpu thread work is done.
  93. while (_running && !_disposed)
  94. {
  95. _galWorkAvailable.Wait();
  96. _galWorkAvailable.Reset();
  97. if (Volatile.Read(ref _interruptAction) != null)
  98. {
  99. _interruptAction();
  100. _interruptRun.Set();
  101. Interlocked.Exchange(ref _interruptAction, null);
  102. }
  103. // The other thread can only increase the command count.
  104. // We can assume that if it is above 0, it will stay there or get higher.
  105. while (_commandCount > 0 && Volatile.Read(ref _interruptAction) == null)
  106. {
  107. int commandPtr = _consumerPtr;
  108. Span<byte> command = new Span<byte>(_commandQueue, commandPtr * _elementSize, _elementSize);
  109. // Run the command.
  110. CommandHelper.RunCommand(command, this, _baseRenderer);
  111. if (Interlocked.CompareExchange(ref _invokePtr, -1, commandPtr) == commandPtr)
  112. {
  113. _invokeRun.Set();
  114. }
  115. _consumerPtr = (_consumerPtr + 1) % QueueCount;
  116. Interlocked.Decrement(ref _commandCount);
  117. }
  118. }
  119. }
  120. internal SpanRef<T> CopySpan<T>(ReadOnlySpan<T> data) where T : unmanaged
  121. {
  122. return _spanPool.Insert(data);
  123. }
  124. private TableRef<T> Ref<T>(T reference)
  125. {
  126. return new TableRef<T>(this, reference);
  127. }
  128. internal ref T New<T>() where T : struct
  129. {
  130. while (_producerPtr == (_consumerPtr + QueueCount - 1) % QueueCount)
  131. {
  132. // If incrementing the producer pointer would overflow, we need to wait.
  133. // _consumerPtr can only move forward, so there's no race to worry about here.
  134. Thread.Sleep(1);
  135. }
  136. int taken = _producerPtr;
  137. _lastProducedPtr = taken;
  138. _producerPtr = (_producerPtr + 1) % QueueCount;
  139. Span<byte> memory = new Span<byte>(_commandQueue, taken * _elementSize, _elementSize);
  140. ref T result = ref Unsafe.As<byte, T>(ref MemoryMarshal.GetReference(memory));
  141. memory[memory.Length - 1] = (byte)((IGALCommand)result).CommandType;
  142. return ref result;
  143. }
  144. internal int AddTableRef(object obj)
  145. {
  146. // The reference table is sized so that it will never overflow, so long as the references are taken after the command is allocated.
  147. int index = _refProducerPtr;
  148. _refQueue[index] = obj;
  149. _refProducerPtr = (_refProducerPtr + 1) % _refQueue.Length;
  150. return index;
  151. }
  152. internal object RemoveTableRef(int index)
  153. {
  154. Debug.Assert(index == _refConsumerPtr);
  155. object result = _refQueue[_refConsumerPtr];
  156. _refQueue[_refConsumerPtr] = null;
  157. _refConsumerPtr = (_refConsumerPtr + 1) % _refQueue.Length;
  158. return result;
  159. }
  160. internal void QueueCommand()
  161. {
  162. int result = Interlocked.Increment(ref _commandCount);
  163. if (result == 1)
  164. {
  165. _galWorkAvailable.Set();
  166. }
  167. }
  168. internal void InvokeCommand()
  169. {
  170. _invokeRun.Reset();
  171. _invokePtr = _lastProducedPtr;
  172. QueueCommand();
  173. // Wait for the command to complete.
  174. _invokeRun.Wait();
  175. }
  176. internal void WaitForFrame()
  177. {
  178. _frameComplete.WaitOne();
  179. }
  180. internal void SignalFrame()
  181. {
  182. _frameComplete.Set();
  183. }
  184. internal bool IsGpuThread()
  185. {
  186. return Thread.CurrentThread == _gpuThread;
  187. }
  188. public void BackgroundContextAction(Action action, bool alwaysBackground = false)
  189. {
  190. if (IsGpuThread() && !alwaysBackground)
  191. {
  192. // The action must be performed on the render thread.
  193. New<ActionCommand>().Set(Ref(action));
  194. InvokeCommand();
  195. }
  196. else
  197. {
  198. _baseRenderer.BackgroundContextAction(action, true);
  199. }
  200. }
  201. public BufferHandle CreateBuffer(int size)
  202. {
  203. BufferHandle handle = Buffers.CreateBufferHandle();
  204. New<CreateBufferCommand>().Set(handle, size);
  205. QueueCommand();
  206. return handle;
  207. }
  208. public IProgram CreateProgram(ShaderSource[] shaders, ShaderInfo info)
  209. {
  210. var program = new ThreadedProgram(this);
  211. SourceProgramRequest request = new SourceProgramRequest(program, shaders, info);
  212. Programs.Add(request);
  213. New<CreateProgramCommand>().Set(Ref((IProgramRequest)request));
  214. QueueCommand();
  215. return program;
  216. }
  217. public ISampler CreateSampler(SamplerCreateInfo info)
  218. {
  219. var sampler = new ThreadedSampler(this);
  220. New<CreateSamplerCommand>().Set(Ref(sampler), info);
  221. QueueCommand();
  222. return sampler;
  223. }
  224. public void CreateSync(ulong id, bool strict)
  225. {
  226. Sync.CreateSyncHandle(id);
  227. New<CreateSyncCommand>().Set(id, strict);
  228. QueueCommand();
  229. }
  230. public ITexture CreateTexture(TextureCreateInfo info, float scale)
  231. {
  232. if (IsGpuThread())
  233. {
  234. var texture = new ThreadedTexture(this, info, scale);
  235. New<CreateTextureCommand>().Set(Ref(texture), info, scale);
  236. QueueCommand();
  237. return texture;
  238. }
  239. else
  240. {
  241. var texture = new ThreadedTexture(this, info, scale);
  242. texture.Base = _baseRenderer.CreateTexture(info, scale);
  243. return texture;
  244. }
  245. }
  246. public void DeleteBuffer(BufferHandle buffer)
  247. {
  248. New<BufferDisposeCommand>().Set(buffer);
  249. QueueCommand();
  250. }
  251. public ReadOnlySpan<byte> GetBufferData(BufferHandle buffer, int offset, int size)
  252. {
  253. if (IsGpuThread())
  254. {
  255. ResultBox<PinnedSpan<byte>> box = new ResultBox<PinnedSpan<byte>>();
  256. New<BufferGetDataCommand>().Set(buffer, offset, size, Ref(box));
  257. InvokeCommand();
  258. return box.Result.Get();
  259. }
  260. else
  261. {
  262. return _baseRenderer.GetBufferData(Buffers.MapBufferBlocking(buffer), offset, size);
  263. }
  264. }
  265. public Capabilities GetCapabilities()
  266. {
  267. ResultBox<Capabilities> box = new ResultBox<Capabilities>();
  268. New<GetCapabilitiesCommand>().Set(Ref(box));
  269. InvokeCommand();
  270. return box.Result;
  271. }
  272. public ulong GetCurrentSync()
  273. {
  274. return _baseRenderer.GetCurrentSync();
  275. }
  276. public HardwareInfo GetHardwareInfo()
  277. {
  278. return _baseRenderer.GetHardwareInfo();
  279. }
  280. /// <summary>
  281. /// Initialize the base renderer. Must be called on the render thread.
  282. /// </summary>
  283. /// <param name="logLevel">Log level to use</param>
  284. public void Initialize(GraphicsDebugLevel logLevel)
  285. {
  286. _baseRenderer.Initialize(logLevel);
  287. }
  288. public IProgram LoadProgramBinary(byte[] programBinary, bool hasFragmentShader, ShaderInfo info)
  289. {
  290. var program = new ThreadedProgram(this);
  291. BinaryProgramRequest request = new BinaryProgramRequest(program, programBinary, hasFragmentShader, info);
  292. Programs.Add(request);
  293. New<CreateProgramCommand>().Set(Ref((IProgramRequest)request));
  294. QueueCommand();
  295. return program;
  296. }
  297. public void PreFrame()
  298. {
  299. New<PreFrameCommand>();
  300. QueueCommand();
  301. }
  302. public ICounterEvent ReportCounter(CounterType type, EventHandler<ulong> resultHandler, bool hostReserved)
  303. {
  304. ThreadedCounterEvent evt = new ThreadedCounterEvent(this, type, _lastSampleCounterClear);
  305. New<ReportCounterCommand>().Set(Ref(evt), type, Ref(resultHandler), hostReserved);
  306. QueueCommand();
  307. if (type == CounterType.SamplesPassed)
  308. {
  309. _lastSampleCounterClear = false;
  310. }
  311. return evt;
  312. }
  313. public void ResetCounter(CounterType type)
  314. {
  315. New<ResetCounterCommand>().Set(type);
  316. QueueCommand();
  317. _lastSampleCounterClear = true;
  318. }
  319. public void Screenshot()
  320. {
  321. _baseRenderer.Screenshot();
  322. }
  323. public void SetBufferData(BufferHandle buffer, int offset, ReadOnlySpan<byte> data)
  324. {
  325. New<BufferSetDataCommand>().Set(buffer, offset, CopySpan(data));
  326. QueueCommand();
  327. }
  328. public void UpdateCounters()
  329. {
  330. New<UpdateCountersCommand>();
  331. QueueCommand();
  332. }
  333. public void WaitSync(ulong id)
  334. {
  335. Sync.WaitSyncAvailability(id);
  336. _baseRenderer.WaitSync(id);
  337. }
  338. private void Interrupt(Action action)
  339. {
  340. // Interrupt the backend thread from any external thread and invoke the given action.
  341. if (Thread.CurrentThread == _backendThread)
  342. {
  343. // If this is called from the backend thread, the action can run immediately.
  344. action();
  345. }
  346. else
  347. {
  348. while (Interlocked.CompareExchange(ref _interruptAction, action, null) != null) { }
  349. _galWorkAvailable.Set();
  350. _interruptRun.WaitOne();
  351. }
  352. }
  353. public void SetInterruptAction(Action<Action> interruptAction)
  354. {
  355. // Threaded renderer ignores given interrupt action, as it provides its own to the child renderer.
  356. }
  357. public void Dispose()
  358. {
  359. // Dispose must happen from the render thread, after all commands have completed.
  360. // Stop the GPU thread.
  361. _disposed = true;
  362. if (_gpuThread != null && _gpuThread.IsAlive)
  363. {
  364. _gpuThread.Join();
  365. }
  366. // Dispose the renderer.
  367. _baseRenderer.Dispose();
  368. // Dispose events.
  369. _frameComplete.Dispose();
  370. _galWorkAvailable.Dispose();
  371. _invokeRun.Dispose();
  372. _interruptRun.Dispose();
  373. Sync.Dispose();
  374. }
  375. }
  376. }