ShaderCache.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Gpu.Image;
  4. using Ryujinx.Graphics.Gpu.State;
  5. using Ryujinx.Graphics.Shader;
  6. using Ryujinx.Graphics.Shader.Translation;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Runtime.InteropServices;
  10. namespace Ryujinx.Graphics.Gpu.Shader
  11. {
  12. using TextureDescriptor = Image.TextureDescriptor;
  13. /// <summary>
  14. /// Memory cache of shader code.
  15. /// </summary>
  16. class ShaderCache : IDisposable
  17. {
  18. private const int MaxProgramSize = 0x100000;
  19. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  20. private GpuContext _context;
  21. private ShaderDumper _dumper;
  22. private Dictionary<ulong, List<ComputeShader>> _cpPrograms;
  23. private Dictionary<ShaderAddresses, List<GraphicsShader>> _gpPrograms;
  24. /// <summary>
  25. /// Creates a new instance of the shader cache.
  26. /// </summary>
  27. /// <param name="context">GPU context that the shader cache belongs to</param>
  28. public ShaderCache(GpuContext context)
  29. {
  30. _context = context;
  31. _dumper = new ShaderDumper();
  32. _cpPrograms = new Dictionary<ulong, List<ComputeShader>>();
  33. _gpPrograms = new Dictionary<ShaderAddresses, List<GraphicsShader>>();
  34. }
  35. /// <summary>
  36. /// Gets a compute shader from the cache.
  37. /// </summary>
  38. /// <remarks>
  39. /// This automatically translates, compiles and adds the code to the cache if not present.
  40. /// </remarks>
  41. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  42. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  43. /// <param name="localSizeX">Local group size X of the computer shader</param>
  44. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  45. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  46. /// <returns>Compiled compute shader code</returns>
  47. public ComputeShader GetComputeShader(ulong gpuVa, int sharedMemorySize, int localSizeX, int localSizeY, int localSizeZ)
  48. {
  49. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ComputeShader> list);
  50. if (isCached)
  51. {
  52. foreach (ComputeShader cachedCpShader in list)
  53. {
  54. if (!IsShaderDifferent(cachedCpShader, gpuVa))
  55. {
  56. return cachedCpShader;
  57. }
  58. }
  59. }
  60. CachedShader shader = TranslateComputeShader(gpuVa, sharedMemorySize, localSizeX, localSizeY, localSizeZ);
  61. shader.HostShader = _context.Renderer.CompileShader(shader.Program);
  62. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader });
  63. ComputeShader cpShader = new ComputeShader(hostProgram, shader);
  64. if (!isCached)
  65. {
  66. list = new List<ComputeShader>();
  67. _cpPrograms.Add(gpuVa, list);
  68. }
  69. list.Add(cpShader);
  70. return cpShader;
  71. }
  72. /// <summary>
  73. /// Gets a graphics shader program from the shader cache.
  74. /// This includes all the specified shader stages.
  75. /// </summary>
  76. /// <remarks>
  77. /// This automatically translates, compiles and adds the code to the cache if not present.
  78. /// </remarks>
  79. /// <param name="state">Current GPU state</param>
  80. /// <param name="addresses">Addresses of the shaders for each stage</param>
  81. /// <returns>Compiled graphics shader code</returns>
  82. public GraphicsShader GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  83. {
  84. bool isCached = _gpPrograms.TryGetValue(addresses, out List<GraphicsShader> list);
  85. if (isCached)
  86. {
  87. foreach (GraphicsShader cachedGpShaders in list)
  88. {
  89. if (!IsShaderDifferent(cachedGpShaders, addresses))
  90. {
  91. return cachedGpShaders;
  92. }
  93. }
  94. }
  95. GraphicsShader gpShaders = new GraphicsShader();
  96. if (addresses.VertexA != 0)
  97. {
  98. gpShaders.Shaders[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
  99. }
  100. else
  101. {
  102. gpShaders.Shaders[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex);
  103. }
  104. gpShaders.Shaders[1] = TranslateGraphicsShader(state, ShaderStage.TessellationControl, addresses.TessControl);
  105. gpShaders.Shaders[2] = TranslateGraphicsShader(state, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  106. gpShaders.Shaders[3] = TranslateGraphicsShader(state, ShaderStage.Geometry, addresses.Geometry);
  107. gpShaders.Shaders[4] = TranslateGraphicsShader(state, ShaderStage.Fragment, addresses.Fragment);
  108. BackpropQualifiers(gpShaders);
  109. List<IShader> hostShaders = new List<IShader>();
  110. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  111. {
  112. ShaderProgram program = gpShaders.Shaders[stage]?.Program;
  113. if (program == null)
  114. {
  115. continue;
  116. }
  117. IShader hostShader = _context.Renderer.CompileShader(program);
  118. gpShaders.Shaders[stage].HostShader = hostShader;
  119. hostShaders.Add(hostShader);
  120. }
  121. gpShaders.HostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray());
  122. if (!isCached)
  123. {
  124. list = new List<GraphicsShader>();
  125. _gpPrograms.Add(addresses, list);
  126. }
  127. list.Add(gpShaders);
  128. return gpShaders;
  129. }
  130. /// <summary>
  131. /// Checks if compute shader code in memory is different from the cached shader.
  132. /// </summary>
  133. /// <param name="cpShader">Cached compute shader</param>
  134. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  135. /// <returns>True if the code is different, false otherwise</returns>
  136. private bool IsShaderDifferent(ComputeShader cpShader, ulong gpuVa)
  137. {
  138. return IsShaderDifferent(cpShader.Shader, gpuVa);
  139. }
  140. /// <summary>
  141. /// Checks if graphics shader code from all stages in memory is different from the cached shaders.
  142. /// </summary>
  143. /// <param name="gpShaders">Cached graphics shaders</param>
  144. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  145. /// <returns>True if the code is different, false otherwise</returns>
  146. private bool IsShaderDifferent(GraphicsShader gpShaders, ShaderAddresses addresses)
  147. {
  148. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  149. {
  150. CachedShader shader = gpShaders.Shaders[stage];
  151. ulong gpuVa = 0;
  152. switch (stage)
  153. {
  154. case 0: gpuVa = addresses.Vertex; break;
  155. case 1: gpuVa = addresses.TessControl; break;
  156. case 2: gpuVa = addresses.TessEvaluation; break;
  157. case 3: gpuVa = addresses.Geometry; break;
  158. case 4: gpuVa = addresses.Fragment; break;
  159. }
  160. if (IsShaderDifferent(shader, gpuVa))
  161. {
  162. return true;
  163. }
  164. }
  165. return false;
  166. }
  167. /// <summary>
  168. /// Checks if the code of the specified cached shader is different from the code in memory.
  169. /// </summary>
  170. /// <param name="shader">Cached shader to compare with</param>
  171. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  172. /// <returns>True if the code is different, false otherwise</returns>
  173. private bool IsShaderDifferent(CachedShader shader, ulong gpuVa)
  174. {
  175. if (shader == null)
  176. {
  177. return false;
  178. }
  179. for (int index = 0; index < shader.Code.Length; index++)
  180. {
  181. if (_context.MemoryAccessor.ReadInt32(gpuVa + (ulong)index * 4) != shader.Code[index])
  182. {
  183. return true;
  184. }
  185. }
  186. return false;
  187. }
  188. /// <summary>
  189. /// Translates the binary Maxwell shader code to something that the host API accepts.
  190. /// </summary>
  191. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  192. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  193. /// <param name="localSizeX">Local group size X of the computer shader</param>
  194. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  195. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  196. /// <returns>Compiled compute shader code</returns>
  197. private CachedShader TranslateComputeShader(ulong gpuVa, int sharedMemorySize, int localSizeX, int localSizeY, int localSizeZ)
  198. {
  199. if (gpuVa == 0)
  200. {
  201. return null;
  202. }
  203. int QueryInfo(QueryInfoName info, int index)
  204. {
  205. return info switch
  206. {
  207. QueryInfoName.ComputeLocalSizeX => localSizeX,
  208. QueryInfoName.ComputeLocalSizeY => localSizeY,
  209. QueryInfoName.ComputeLocalSizeZ => localSizeZ,
  210. QueryInfoName.ComputeSharedMemorySize => sharedMemorySize,
  211. _ => QueryInfoCommon(info)
  212. };
  213. }
  214. TranslatorCallbacks callbacks = new TranslatorCallbacks(QueryInfo, PrintLog);
  215. ShaderProgram program;
  216. ReadOnlySpan<byte> code = _context.MemoryAccessor.GetSpan(gpuVa, MaxProgramSize);
  217. program = Translator.Translate(code, callbacks, DefaultFlags | TranslationFlags.Compute);
  218. int[] codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  219. _dumper.Dump(code, compute: true, out string fullPath, out string codePath);
  220. if (fullPath != null && codePath != null)
  221. {
  222. program.Prepend("// " + codePath);
  223. program.Prepend("// " + fullPath);
  224. }
  225. return new CachedShader(program, codeCached);
  226. }
  227. /// <summary>
  228. /// Translates the binary Maxwell shader code to something that the host API accepts.
  229. /// </summary>
  230. /// <remarks>
  231. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  232. /// </remarks>
  233. /// <param name="state">Current GPU state</param>
  234. /// <param name="stage">Shader stage</param>
  235. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  236. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" shader code</param>
  237. /// <returns>Compiled graphics shader code</returns>
  238. private CachedShader TranslateGraphicsShader(GpuState state, ShaderStage stage, ulong gpuVa, ulong gpuVaA = 0)
  239. {
  240. if (gpuVa == 0)
  241. {
  242. return null;
  243. }
  244. int QueryInfo(QueryInfoName info, int index)
  245. {
  246. return info switch
  247. {
  248. QueryInfoName.IsTextureBuffer => Convert.ToInt32(QueryIsTextureBuffer(state, (int)stage - 1, index)),
  249. QueryInfoName.IsTextureRectangle => Convert.ToInt32(QueryIsTextureRectangle(state, (int)stage - 1, index)),
  250. QueryInfoName.PrimitiveTopology => (int)GetPrimitiveTopology(),
  251. _ => QueryInfoCommon(info)
  252. };
  253. }
  254. TranslatorCallbacks callbacks = new TranslatorCallbacks(QueryInfo, PrintLog);
  255. ShaderProgram program;
  256. int[] codeCached = null;
  257. if (gpuVaA != 0)
  258. {
  259. ReadOnlySpan<byte> codeA = _context.MemoryAccessor.GetSpan(gpuVaA, MaxProgramSize);
  260. ReadOnlySpan<byte> codeB = _context.MemoryAccessor.GetSpan(gpuVa, MaxProgramSize);
  261. program = Translator.Translate(codeA, codeB, callbacks, DefaultFlags);
  262. // TODO: We should also take "codeA" into account.
  263. codeCached = MemoryMarshal.Cast<byte, int>(codeB.Slice(0, program.Size)).ToArray();
  264. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  265. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  266. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  267. {
  268. program.Prepend("// " + codePathB);
  269. program.Prepend("// " + fullPathB);
  270. program.Prepend("// " + codePathA);
  271. program.Prepend("// " + fullPathA);
  272. }
  273. }
  274. else
  275. {
  276. ReadOnlySpan<byte> code = _context.MemoryAccessor.GetSpan(gpuVa, MaxProgramSize);
  277. program = Translator.Translate(code, callbacks, DefaultFlags);
  278. codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  279. _dumper.Dump(code, compute: false, out string fullPath, out string codePath);
  280. if (fullPath != null && codePath != null)
  281. {
  282. program.Prepend("// " + codePath);
  283. program.Prepend("// " + fullPath);
  284. }
  285. }
  286. ulong address = _context.MemoryManager.Translate(gpuVa);
  287. return new CachedShader(program, codeCached);
  288. }
  289. /// <summary>
  290. /// Performs backwards propagation of interpolation qualifiers or later shader stages input,
  291. /// to ealier shader stages output.
  292. /// This is required by older versions of OpenGL (pre-4.3).
  293. /// </summary>
  294. /// <param name="program">Graphics shader cached code</param>
  295. private void BackpropQualifiers(GraphicsShader program)
  296. {
  297. ShaderProgram fragmentShader = program.Shaders[4]?.Program;
  298. bool isFirst = true;
  299. for (int stage = 3; stage >= 0; stage--)
  300. {
  301. if (program.Shaders[stage] == null)
  302. {
  303. continue;
  304. }
  305. // We need to iterate backwards, since we do name replacement,
  306. // and it would otherwise replace a subset of the longer names.
  307. for (int attr = 31; attr >= 0; attr--)
  308. {
  309. string iq = fragmentShader?.Info.InterpolationQualifiers[attr].ToGlslQualifier() ?? string.Empty;
  310. if (isFirst && !string.IsNullOrEmpty(iq))
  311. {
  312. program.Shaders[stage].Program.Replace($"{DefineNames.OutQualifierPrefixName}{attr}", iq);
  313. }
  314. else
  315. {
  316. program.Shaders[stage].Program.Replace($"{DefineNames.OutQualifierPrefixName}{attr} ", string.Empty);
  317. }
  318. }
  319. isFirst = false;
  320. }
  321. }
  322. /// <summary>
  323. /// Gets the primitive topology for the current draw.
  324. /// This is required by geometry shaders.
  325. /// </summary>
  326. /// <returns>Primitive topology</returns>
  327. private InputTopology GetPrimitiveTopology()
  328. {
  329. switch (_context.Methods.PrimitiveType)
  330. {
  331. case PrimitiveType.Points:
  332. return InputTopology.Points;
  333. case PrimitiveType.Lines:
  334. case PrimitiveType.LineLoop:
  335. case PrimitiveType.LineStrip:
  336. return InputTopology.Lines;
  337. case PrimitiveType.LinesAdjacency:
  338. case PrimitiveType.LineStripAdjacency:
  339. return InputTopology.LinesAdjacency;
  340. case PrimitiveType.Triangles:
  341. case PrimitiveType.TriangleStrip:
  342. case PrimitiveType.TriangleFan:
  343. return InputTopology.Triangles;
  344. case PrimitiveType.TrianglesAdjacency:
  345. case PrimitiveType.TriangleStripAdjacency:
  346. return InputTopology.TrianglesAdjacency;
  347. }
  348. return InputTopology.Points;
  349. }
  350. /// <summary>
  351. /// Check if the target of a given texture is texture buffer.
  352. /// This is required as 1D textures and buffer textures shares the same sampler type on binary shader code,
  353. /// but not on GLSL.
  354. /// </summary>
  355. /// <param name="state">Current GPU state</param>
  356. /// <param name="stageIndex">Index of the shader stage</param>
  357. /// <param name="index">Index of the texture (this is the shader "fake" handle)</param>
  358. /// <returns>True if the texture is a buffer texture, false otherwise</returns>
  359. private bool QueryIsTextureBuffer(GpuState state, int stageIndex, int index)
  360. {
  361. return GetTextureDescriptor(state, stageIndex, index).UnpackTextureTarget() == TextureTarget.TextureBuffer;
  362. }
  363. /// <summary>
  364. /// Check if the target of a given texture is texture rectangle.
  365. /// This is required as 2D textures and rectangle textures shares the same sampler type on binary shader code,
  366. /// but not on GLSL.
  367. /// </summary>
  368. /// <param name="state">Current GPU state</param>
  369. /// <param name="stageIndex">Index of the shader stage</param>
  370. /// <param name="index">Index of the texture (this is the shader "fake" handle)</param>
  371. /// <returns>True if the texture is a rectangle texture, false otherwise</returns>
  372. private bool QueryIsTextureRectangle(GpuState state, int stageIndex, int index)
  373. {
  374. var descriptor = GetTextureDescriptor(state, stageIndex, index);
  375. TextureTarget target = descriptor.UnpackTextureTarget();
  376. bool is2DTexture = target == TextureTarget.Texture2D ||
  377. target == TextureTarget.Texture2DRect;
  378. return !descriptor.UnpackTextureCoordNormalized() && is2DTexture;
  379. }
  380. /// <summary>
  381. /// Gets the texture descriptor for a given texture on the pool.
  382. /// </summary>
  383. /// <param name="state">Current GPU state</param>
  384. /// <param name="stageIndex">Index of the shader stage</param>
  385. /// <param name="index">Index of the texture (this is the shader "fake" handle)</param>
  386. /// <returns>Texture descriptor</returns>
  387. private TextureDescriptor GetTextureDescriptor(GpuState state, int stageIndex, int index)
  388. {
  389. return _context.Methods.TextureManager.GetGraphicsTextureDescriptor(state, stageIndex, index);
  390. }
  391. /// <summary>
  392. /// Returns information required by both compute and graphics shader compilation.
  393. /// </summary>
  394. /// <param name="info">Information queried</param>
  395. /// <returns>Requested information</returns>
  396. private int QueryInfoCommon(QueryInfoName info)
  397. {
  398. return info switch
  399. {
  400. QueryInfoName.StorageBufferOffsetAlignment => _context.Capabilities.StorageBufferOffsetAlignment,
  401. QueryInfoName.SupportsNonConstantTextureOffset => Convert.ToInt32(_context.Capabilities.SupportsNonConstantTextureOffset),
  402. _ => 0
  403. };
  404. }
  405. /// <summary>
  406. /// Prints a warning from the shader code translator.
  407. /// </summary>
  408. /// <param name="message">Warning message</param>
  409. private static void PrintLog(string message)
  410. {
  411. Logger.PrintWarning(LogClass.Gpu, $"Shader translator: {message}");
  412. }
  413. /// <summary>
  414. /// Disposes the shader cache, deleting all the cached shaders.
  415. /// It's an error to use the shader cache after disposal.
  416. /// </summary>
  417. public void Dispose()
  418. {
  419. foreach (List<ComputeShader> list in _cpPrograms.Values)
  420. {
  421. foreach (ComputeShader shader in list)
  422. {
  423. shader.HostProgram.Dispose();
  424. shader.Shader?.HostShader.Dispose();
  425. }
  426. }
  427. foreach (List<GraphicsShader> list in _gpPrograms.Values)
  428. {
  429. foreach (GraphicsShader shader in list)
  430. {
  431. shader.HostProgram.Dispose();
  432. foreach (CachedShader cachedShader in shader.Shaders)
  433. {
  434. cachedShader?.HostShader.Dispose();
  435. }
  436. }
  437. }
  438. }
  439. }
  440. }