ThreadedRenderer.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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 IShader CompileShader(ShaderStage stage, string code)
  191. {
  192. var shader = new ThreadedShader(this, stage, code);
  193. New<CompileShaderCommand>().Set(Ref(shader));
  194. QueueCommand();
  195. return shader;
  196. }
  197. public BufferHandle CreateBuffer(int size)
  198. {
  199. BufferHandle handle = Buffers.CreateBufferHandle();
  200. New<CreateBufferCommand>().Set(handle, size);
  201. QueueCommand();
  202. return handle;
  203. }
  204. public IProgram CreateProgram(IShader[] shaders)
  205. {
  206. var program = new ThreadedProgram(this);
  207. SourceProgramRequest request = new SourceProgramRequest(program, shaders);
  208. Programs.Add(request);
  209. New<CreateProgramCommand>().Set(Ref((IProgramRequest)request));
  210. QueueCommand();
  211. return program;
  212. }
  213. public ISampler CreateSampler(SamplerCreateInfo info)
  214. {
  215. var sampler = new ThreadedSampler(this);
  216. New<CreateSamplerCommand>().Set(Ref(sampler), info);
  217. QueueCommand();
  218. return sampler;
  219. }
  220. public void CreateSync(ulong id)
  221. {
  222. Sync.CreateSyncHandle(id);
  223. New<CreateSyncCommand>().Set(id);
  224. QueueCommand();
  225. }
  226. public ITexture CreateTexture(TextureCreateInfo info, float scale)
  227. {
  228. if (IsGpuThread())
  229. {
  230. var texture = new ThreadedTexture(this, info, scale);
  231. New<CreateTextureCommand>().Set(Ref(texture), info, scale);
  232. QueueCommand();
  233. return texture;
  234. }
  235. else
  236. {
  237. var texture = new ThreadedTexture(this, info, scale);
  238. texture.Base = _baseRenderer.CreateTexture(info, scale);
  239. return texture;
  240. }
  241. }
  242. public void DeleteBuffer(BufferHandle buffer)
  243. {
  244. New<BufferDisposeCommand>().Set(buffer);
  245. QueueCommand();
  246. }
  247. public ReadOnlySpan<byte> GetBufferData(BufferHandle buffer, int offset, int size)
  248. {
  249. if (IsGpuThread())
  250. {
  251. ResultBox<PinnedSpan<byte>> box = new ResultBox<PinnedSpan<byte>>();
  252. New<BufferGetDataCommand>().Set(buffer, offset, size, Ref(box));
  253. InvokeCommand();
  254. return box.Result.Get();
  255. }
  256. else
  257. {
  258. return _baseRenderer.GetBufferData(Buffers.MapBufferBlocking(buffer), offset, size);
  259. }
  260. }
  261. public Capabilities GetCapabilities()
  262. {
  263. ResultBox<Capabilities> box = new ResultBox<Capabilities>();
  264. New<GetCapabilitiesCommand>().Set(Ref(box));
  265. InvokeCommand();
  266. return box.Result;
  267. }
  268. /// <summary>
  269. /// Initialize the base renderer. Must be called on the render thread.
  270. /// </summary>
  271. /// <param name="logLevel">Log level to use</param>
  272. public void Initialize(GraphicsDebugLevel logLevel)
  273. {
  274. _baseRenderer.Initialize(logLevel);
  275. }
  276. public IProgram LoadProgramBinary(byte[] programBinary)
  277. {
  278. var program = new ThreadedProgram(this);
  279. BinaryProgramRequest request = new BinaryProgramRequest(program, programBinary);
  280. Programs.Add(request);
  281. New<CreateProgramCommand>().Set(Ref((IProgramRequest)request));
  282. QueueCommand();
  283. return program;
  284. }
  285. public void PreFrame()
  286. {
  287. New<PreFrameCommand>();
  288. QueueCommand();
  289. }
  290. public ICounterEvent ReportCounter(CounterType type, EventHandler<ulong> resultHandler, bool hostReserved)
  291. {
  292. ThreadedCounterEvent evt = new ThreadedCounterEvent(this, type, _lastSampleCounterClear);
  293. New<ReportCounterCommand>().Set(Ref(evt), type, Ref(resultHandler), hostReserved);
  294. QueueCommand();
  295. if (type == CounterType.SamplesPassed)
  296. {
  297. _lastSampleCounterClear = false;
  298. }
  299. return evt;
  300. }
  301. public void ResetCounter(CounterType type)
  302. {
  303. New<ResetCounterCommand>().Set(type);
  304. QueueCommand();
  305. _lastSampleCounterClear = true;
  306. }
  307. public void Screenshot()
  308. {
  309. _baseRenderer.Screenshot();
  310. }
  311. public void SetBufferData(BufferHandle buffer, int offset, ReadOnlySpan<byte> data)
  312. {
  313. New<BufferSetDataCommand>().Set(buffer, offset, CopySpan(data));
  314. QueueCommand();
  315. }
  316. public void UpdateCounters()
  317. {
  318. New<UpdateCountersCommand>();
  319. QueueCommand();
  320. }
  321. public void WaitSync(ulong id)
  322. {
  323. Sync.WaitSyncAvailability(id);
  324. _baseRenderer.WaitSync(id);
  325. }
  326. public void Dispose()
  327. {
  328. // Dispose must happen from the render thread, after all commands have completed.
  329. // Stop the GPU thread.
  330. _disposed = true;
  331. _gpuThread.Join();
  332. // Dispose the renderer.
  333. _baseRenderer.Dispose();
  334. // Dispose events.
  335. _frameComplete.Dispose();
  336. _galWorkAvailable.Dispose();
  337. _invokeRun.Dispose();
  338. Sync.Dispose();
  339. }
  340. }
  341. }