ShaderCache.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.State;
  3. using Ryujinx.Graphics.Shader;
  4. using Ryujinx.Graphics.Shader.Translation;
  5. using System;
  6. using System.Collections.Generic;
  7. namespace Ryujinx.Graphics.Gpu.Shader
  8. {
  9. /// <summary>
  10. /// Memory cache of shader code.
  11. /// </summary>
  12. class ShaderCache : IDisposable
  13. {
  14. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  15. private readonly GpuContext _context;
  16. private readonly ShaderDumper _dumper;
  17. private readonly Dictionary<ulong, List<ShaderBundle>> _cpPrograms;
  18. private readonly Dictionary<ShaderAddresses, List<ShaderBundle>> _gpPrograms;
  19. /// <summary>
  20. /// Creates a new instance of the shader cache.
  21. /// </summary>
  22. /// <param name="context">GPU context that the shader cache belongs to</param>
  23. public ShaderCache(GpuContext context)
  24. {
  25. _context = context;
  26. _dumper = new ShaderDumper();
  27. _cpPrograms = new Dictionary<ulong, List<ShaderBundle>>();
  28. _gpPrograms = new Dictionary<ShaderAddresses, List<ShaderBundle>>();
  29. }
  30. /// <summary>
  31. /// Gets a compute shader from the cache.
  32. /// </summary>
  33. /// <remarks>
  34. /// This automatically translates, compiles and adds the code to the cache if not present.
  35. /// </remarks>
  36. /// <param name="state">Current GPU state</param>
  37. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  38. /// <param name="localSizeX">Local group size X of the computer shader</param>
  39. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  40. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  41. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  42. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  43. /// <returns>Compiled compute shader code</returns>
  44. public ShaderBundle GetComputeShader(
  45. GpuState state,
  46. ulong gpuVa,
  47. int localSizeX,
  48. int localSizeY,
  49. int localSizeZ,
  50. int localMemorySize,
  51. int sharedMemorySize)
  52. {
  53. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ShaderBundle> list);
  54. if (isCached)
  55. {
  56. foreach (ShaderBundle cachedCpShader in list)
  57. {
  58. if (IsShaderEqual(cachedCpShader, gpuVa))
  59. {
  60. return cachedCpShader;
  61. }
  62. }
  63. }
  64. ShaderCodeHolder shader = TranslateComputeShader(
  65. state,
  66. gpuVa,
  67. localSizeX,
  68. localSizeY,
  69. localSizeZ,
  70. localMemorySize,
  71. sharedMemorySize);
  72. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  73. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  74. ShaderBundle cpShader = new ShaderBundle(hostProgram, shader);
  75. if (!isCached)
  76. {
  77. list = new List<ShaderBundle>();
  78. _cpPrograms.Add(gpuVa, list);
  79. }
  80. list.Add(cpShader);
  81. return cpShader;
  82. }
  83. /// <summary>
  84. /// Gets a graphics shader program from the shader cache.
  85. /// This includes all the specified shader stages.
  86. /// </summary>
  87. /// <remarks>
  88. /// This automatically translates, compiles and adds the code to the cache if not present.
  89. /// </remarks>
  90. /// <param name="state">Current GPU state</param>
  91. /// <param name="addresses">Addresses of the shaders for each stage</param>
  92. /// <returns>Compiled graphics shader code</returns>
  93. public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  94. {
  95. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  96. if (isCached)
  97. {
  98. foreach (ShaderBundle cachedGpShaders in list)
  99. {
  100. if (IsShaderEqual(cachedGpShaders, addresses))
  101. {
  102. return cachedGpShaders;
  103. }
  104. }
  105. }
  106. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  107. var tfd = GetTransformFeedbackDescriptors(state);
  108. TranslationFlags flags = DefaultFlags;
  109. if (tfd != null)
  110. {
  111. flags |= TranslationFlags.Feedback;
  112. }
  113. TranslationCounts counts = new TranslationCounts();
  114. if (addresses.VertexA != 0)
  115. {
  116. shaders[0] = TranslateGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
  117. }
  118. else
  119. {
  120. shaders[0] = TranslateGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
  121. }
  122. shaders[1] = TranslateGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
  123. shaders[2] = TranslateGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  124. shaders[3] = TranslateGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
  125. shaders[4] = TranslateGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);
  126. List<IShader> hostShaders = new List<IShader>();
  127. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  128. {
  129. ShaderProgram program = shaders[stage]?.Program;
  130. if (program == null)
  131. {
  132. continue;
  133. }
  134. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  135. shaders[stage].HostShader = hostShader;
  136. hostShaders.Add(hostShader);
  137. }
  138. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  139. ShaderBundle gpShaders = new ShaderBundle(hostProgram, shaders);
  140. if (!isCached)
  141. {
  142. list = new List<ShaderBundle>();
  143. _gpPrograms.Add(addresses, list);
  144. }
  145. list.Add(gpShaders);
  146. return gpShaders;
  147. }
  148. /// <summary>
  149. /// Gets transform feedback state from the current GPU state.
  150. /// </summary>
  151. /// <param name="state">Current GPU state</param>
  152. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  153. private TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  154. {
  155. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  156. if (!tfEnable)
  157. {
  158. return null;
  159. }
  160. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  161. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  162. {
  163. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  164. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  165. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  166. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  167. }
  168. return descs;
  169. }
  170. /// <summary>
  171. /// Checks if compute shader code in memory is equal to the cached shader.
  172. /// </summary>
  173. /// <param name="cpShader">Cached compute shader</param>
  174. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  175. /// <returns>True if the code is different, false otherwise</returns>
  176. private bool IsShaderEqual(ShaderBundle cpShader, ulong gpuVa)
  177. {
  178. return IsShaderEqual(cpShader.Shaders[0], gpuVa);
  179. }
  180. /// <summary>
  181. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  182. /// </summary>
  183. /// <param name="gpShaders">Cached graphics shaders</param>
  184. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  185. /// <returns>True if the code is different, false otherwise</returns>
  186. private bool IsShaderEqual(ShaderBundle gpShaders, ShaderAddresses addresses)
  187. {
  188. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  189. {
  190. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  191. ulong gpuVa = 0;
  192. switch (stage)
  193. {
  194. case 0: gpuVa = addresses.Vertex; break;
  195. case 1: gpuVa = addresses.TessControl; break;
  196. case 2: gpuVa = addresses.TessEvaluation; break;
  197. case 3: gpuVa = addresses.Geometry; break;
  198. case 4: gpuVa = addresses.Fragment; break;
  199. }
  200. if (!IsShaderEqual(shader, gpuVa, addresses.VertexA))
  201. {
  202. return false;
  203. }
  204. }
  205. return true;
  206. }
  207. /// <summary>
  208. /// Checks if the code of the specified cached shader is different from the code in memory.
  209. /// </summary>
  210. /// <param name="shader">Cached shader to compare with</param>
  211. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  212. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  213. /// <returns>True if the code is different, false otherwise</returns>
  214. private bool IsShaderEqual(ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  215. {
  216. if (shader == null)
  217. {
  218. return true;
  219. }
  220. ReadOnlySpan<byte> memoryCode = _context.MemoryManager.GetSpan(gpuVa, shader.Code.Length);
  221. bool equals = memoryCode.SequenceEqual(shader.Code);
  222. if (equals && shader.Code2 != null)
  223. {
  224. memoryCode = _context.MemoryManager.GetSpan(gpuVaA, shader.Code2.Length);
  225. equals = memoryCode.SequenceEqual(shader.Code2);
  226. }
  227. return equals;
  228. }
  229. /// <summary>
  230. /// Translates the binary Maxwell shader code to something that the host API accepts.
  231. /// </summary>
  232. /// <param name="state">Current GPU state</param>
  233. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  234. /// <param name="localSizeX">Local group size X of the computer shader</param>
  235. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  236. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  237. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  238. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  239. /// <returns>Compiled compute shader code</returns>
  240. private ShaderCodeHolder TranslateComputeShader(
  241. GpuState state,
  242. ulong gpuVa,
  243. int localSizeX,
  244. int localSizeY,
  245. int localSizeZ,
  246. int localMemorySize,
  247. int sharedMemorySize)
  248. {
  249. if (gpuVa == 0)
  250. {
  251. return null;
  252. }
  253. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  254. ShaderProgram program;
  255. program = Translator.Translate(gpuVa, gpuAccessor, DefaultFlags | TranslationFlags.Compute);
  256. byte[] code = _context.MemoryManager.GetSpan(gpuVa, program.Size).ToArray();
  257. _dumper.Dump(code, compute: true, out string fullPath, out string codePath);
  258. if (fullPath != null && codePath != null)
  259. {
  260. program.Prepend("// " + codePath);
  261. program.Prepend("// " + fullPath);
  262. }
  263. return new ShaderCodeHolder(program, code);
  264. }
  265. /// <summary>
  266. /// Translates the binary Maxwell shader code to something that the host API accepts.
  267. /// </summary>
  268. /// <remarks>
  269. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  270. /// </remarks>
  271. /// <param name="state">Current GPU state</param>
  272. /// <param name="counts">Cumulative shader resource counts</param>
  273. /// <param name="flags">Flags that controls shader translation</param>
  274. /// <param name="stage">Shader stage</param>
  275. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  276. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" shader code</param>
  277. /// <returns>Compiled graphics shader code</returns>
  278. private ShaderCodeHolder TranslateGraphicsShader(
  279. GpuState state,
  280. TranslationCounts counts,
  281. TranslationFlags flags,
  282. ShaderStage stage,
  283. ulong gpuVa,
  284. ulong gpuVaA = 0)
  285. {
  286. if (gpuVa == 0)
  287. {
  288. return null;
  289. }
  290. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  291. if (gpuVaA != 0)
  292. {
  293. ShaderProgram program = Translator.Translate(gpuVaA, gpuVa, gpuAccessor, flags, counts);
  294. byte[] codeA = _context.MemoryManager.GetSpan(gpuVaA, program.SizeA).ToArray();
  295. byte[] codeB = _context.MemoryManager.GetSpan(gpuVa, program.Size).ToArray();
  296. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  297. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  298. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  299. {
  300. program.Prepend("// " + codePathB);
  301. program.Prepend("// " + fullPathB);
  302. program.Prepend("// " + codePathA);
  303. program.Prepend("// " + fullPathA);
  304. }
  305. return new ShaderCodeHolder(program, codeB, codeA);
  306. }
  307. else
  308. {
  309. ShaderProgram program = Translator.Translate(gpuVa, gpuAccessor, flags, counts);
  310. byte[] code = _context.MemoryManager.GetSpan(gpuVa, program.Size).ToArray();
  311. _dumper.Dump(code, compute: false, out string fullPath, out string codePath);
  312. if (fullPath != null && codePath != null)
  313. {
  314. program.Prepend("// " + codePath);
  315. program.Prepend("// " + fullPath);
  316. }
  317. return new ShaderCodeHolder(program, code);
  318. }
  319. }
  320. /// <summary>
  321. /// Disposes the shader cache, deleting all the cached shaders.
  322. /// It's an error to use the shader cache after disposal.
  323. /// </summary>
  324. public void Dispose()
  325. {
  326. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  327. {
  328. foreach (ShaderBundle bundle in list)
  329. {
  330. bundle.Dispose();
  331. }
  332. }
  333. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  334. {
  335. foreach (ShaderBundle bundle in list)
  336. {
  337. bundle.Dispose();
  338. }
  339. }
  340. }
  341. }
  342. }