ShaderCache.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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(shader.Program);
  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. if (addresses.VertexA != 0)
  108. {
  109. shaders[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
  110. }
  111. else
  112. {
  113. shaders[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex);
  114. }
  115. shaders[1] = TranslateGraphicsShader(state, ShaderStage.TessellationControl, addresses.TessControl);
  116. shaders[2] = TranslateGraphicsShader(state, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  117. shaders[3] = TranslateGraphicsShader(state, ShaderStage.Geometry, addresses.Geometry);
  118. shaders[4] = TranslateGraphicsShader(state, ShaderStage.Fragment, addresses.Fragment);
  119. List<IShader> hostShaders = new List<IShader>();
  120. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  121. {
  122. ShaderProgram program = shaders[stage]?.Program;
  123. if (program == null)
  124. {
  125. continue;
  126. }
  127. var tfd = GetTransformFeedbackDescriptors(state);
  128. IShader hostShader = _context.Renderer.CompileShader(program);
  129. shaders[stage].HostShader = hostShader;
  130. hostShaders.Add(hostShader);
  131. }
  132. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), GetTransformFeedbackDescriptors(state));
  133. ShaderBundle gpShaders = new ShaderBundle(hostProgram, shaders);
  134. if (!isCached)
  135. {
  136. list = new List<ShaderBundle>();
  137. _gpPrograms.Add(addresses, list);
  138. }
  139. list.Add(gpShaders);
  140. return gpShaders;
  141. }
  142. /// <summary>
  143. /// Gets transform feedback state from the current GPU state.
  144. /// </summary>
  145. /// <param name="state">Current GPU state</param>
  146. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  147. private TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  148. {
  149. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  150. if (!tfEnable)
  151. {
  152. return null;
  153. }
  154. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  155. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  156. {
  157. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  158. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  159. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  160. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  161. }
  162. return descs;
  163. }
  164. /// <summary>
  165. /// Checks if compute shader code in memory is equal to the cached shader.
  166. /// </summary>
  167. /// <param name="cpShader">Cached compute shader</param>
  168. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  169. /// <returns>True if the code is different, false otherwise</returns>
  170. private bool IsShaderEqual(ShaderBundle cpShader, ulong gpuVa)
  171. {
  172. return IsShaderEqual(cpShader.Shaders[0], gpuVa);
  173. }
  174. /// <summary>
  175. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  176. /// </summary>
  177. /// <param name="gpShaders">Cached graphics shaders</param>
  178. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  179. /// <returns>True if the code is different, false otherwise</returns>
  180. private bool IsShaderEqual(ShaderBundle gpShaders, ShaderAddresses addresses)
  181. {
  182. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  183. {
  184. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  185. ulong gpuVa = 0;
  186. switch (stage)
  187. {
  188. case 0: gpuVa = addresses.Vertex; break;
  189. case 1: gpuVa = addresses.TessControl; break;
  190. case 2: gpuVa = addresses.TessEvaluation; break;
  191. case 3: gpuVa = addresses.Geometry; break;
  192. case 4: gpuVa = addresses.Fragment; break;
  193. }
  194. if (!IsShaderEqual(shader, gpuVa, addresses.VertexA))
  195. {
  196. return false;
  197. }
  198. }
  199. return true;
  200. }
  201. /// <summary>
  202. /// Checks if the code of the specified cached shader is different from the code in memory.
  203. /// </summary>
  204. /// <param name="shader">Cached shader to compare with</param>
  205. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  206. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  207. /// <returns>True if the code is different, false otherwise</returns>
  208. private bool IsShaderEqual(ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  209. {
  210. if (shader == null)
  211. {
  212. return true;
  213. }
  214. ReadOnlySpan<byte> memoryCode = _context.MemoryAccessor.GetSpan(gpuVa, shader.Code.Length);
  215. bool equals = memoryCode.SequenceEqual(shader.Code);
  216. if (equals && shader.Code2 != null)
  217. {
  218. memoryCode = _context.MemoryAccessor.GetSpan(gpuVaA, shader.Code2.Length);
  219. equals = memoryCode.SequenceEqual(shader.Code2);
  220. }
  221. return equals;
  222. }
  223. /// <summary>
  224. /// Translates the binary Maxwell shader code to something that the host API accepts.
  225. /// </summary>
  226. /// <param name="state">Current GPU state</param>
  227. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  228. /// <param name="localSizeX">Local group size X of the computer shader</param>
  229. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  230. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  231. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  232. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  233. /// <returns>Compiled compute shader code</returns>
  234. private ShaderCodeHolder TranslateComputeShader(
  235. GpuState state,
  236. ulong gpuVa,
  237. int localSizeX,
  238. int localSizeY,
  239. int localSizeZ,
  240. int localMemorySize,
  241. int sharedMemorySize)
  242. {
  243. if (gpuVa == 0)
  244. {
  245. return null;
  246. }
  247. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  248. ShaderProgram program;
  249. program = Translator.Translate(gpuVa, gpuAccessor, DefaultFlags | TranslationFlags.Compute);
  250. byte[] code = _context.MemoryAccessor.ReadBytes(gpuVa, program.Size);
  251. _dumper.Dump(code, compute: true, out string fullPath, out string codePath);
  252. if (fullPath != null && codePath != null)
  253. {
  254. program.Prepend("// " + codePath);
  255. program.Prepend("// " + fullPath);
  256. }
  257. return new ShaderCodeHolder(program, code);
  258. }
  259. /// <summary>
  260. /// Translates the binary Maxwell shader code to something that the host API accepts.
  261. /// </summary>
  262. /// <remarks>
  263. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  264. /// </remarks>
  265. /// <param name="state">Current GPU state</param>
  266. /// <param name="stage">Shader stage</param>
  267. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  268. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" shader code</param>
  269. /// <returns>Compiled graphics shader code</returns>
  270. private ShaderCodeHolder TranslateGraphicsShader(GpuState state, ShaderStage stage, ulong gpuVa, ulong gpuVaA = 0)
  271. {
  272. if (gpuVa == 0)
  273. {
  274. return null;
  275. }
  276. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  277. if (gpuVaA != 0)
  278. {
  279. ShaderProgram program = Translator.Translate(gpuVaA, gpuVa, gpuAccessor, DefaultFlags);
  280. byte[] codeA = _context.MemoryAccessor.ReadBytes(gpuVaA, program.SizeA);
  281. byte[] codeB = _context.MemoryAccessor.ReadBytes(gpuVa, program.Size);
  282. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  283. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  284. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  285. {
  286. program.Prepend("// " + codePathB);
  287. program.Prepend("// " + fullPathB);
  288. program.Prepend("// " + codePathA);
  289. program.Prepend("// " + fullPathA);
  290. }
  291. return new ShaderCodeHolder(program, codeB, codeA);
  292. }
  293. else
  294. {
  295. ShaderProgram program = Translator.Translate(gpuVa, gpuAccessor, DefaultFlags);
  296. byte[] code = _context.MemoryAccessor.ReadBytes(gpuVa, program.Size);
  297. _dumper.Dump(code, compute: false, out string fullPath, out string codePath);
  298. if (fullPath != null && codePath != null)
  299. {
  300. program.Prepend("// " + codePath);
  301. program.Prepend("// " + fullPath);
  302. }
  303. return new ShaderCodeHolder(program, code);
  304. }
  305. }
  306. /// <summary>
  307. /// Disposes the shader cache, deleting all the cached shaders.
  308. /// It's an error to use the shader cache after disposal.
  309. /// </summary>
  310. public void Dispose()
  311. {
  312. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  313. {
  314. foreach (ShaderBundle bundle in list)
  315. {
  316. bundle.Dispose();
  317. }
  318. }
  319. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  320. {
  321. foreach (ShaderBundle bundle in list)
  322. {
  323. bundle.Dispose();
  324. }
  325. }
  326. }
  327. }
  328. }