ShaderCache.cs 21 KB

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