ThreadedRenderer.cs 13 KB

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