ShaderCache.cs 21 KB

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