ThreadedRenderer.cs 13 KB

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