ShaderCache.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. class ShaderCache
  12. {
  13. private const int MaxProgramSize = 0x100000;
  14. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  15. private GpuContext _context;
  16. private ShaderDumper _dumper;
  17. private Dictionary<ulong, List<ComputeShader>> _cpPrograms;
  18. private Dictionary<ShaderAddresses, List<GraphicsShader>> _gpPrograms;
  19. public ShaderCache(GpuContext context)
  20. {
  21. _context = context;
  22. _dumper = new ShaderDumper(context);
  23. _cpPrograms = new Dictionary<ulong, List<ComputeShader>>();
  24. _gpPrograms = new Dictionary<ShaderAddresses, List<GraphicsShader>>();
  25. }
  26. public ComputeShader GetComputeShader(ulong gpuVa, int sharedMemorySize, int localSizeX, int localSizeY, int localSizeZ)
  27. {
  28. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ComputeShader> list);
  29. if (isCached)
  30. {
  31. foreach (ComputeShader cachedCpShader in list)
  32. {
  33. if (!IsShaderDifferent(cachedCpShader, gpuVa))
  34. {
  35. return cachedCpShader;
  36. }
  37. }
  38. }
  39. CachedShader shader = TranslateComputeShader(gpuVa, sharedMemorySize, localSizeX, localSizeY, localSizeZ);
  40. IShader hostShader = _context.Renderer.CompileShader(shader.Program);
  41. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { hostShader });
  42. ulong address = _context.MemoryManager.Translate(gpuVa);
  43. ComputeShader cpShader = new ComputeShader(hostProgram, shader);
  44. if (!isCached)
  45. {
  46. list = new List<ComputeShader>();
  47. _cpPrograms.Add(gpuVa, list);
  48. }
  49. list.Add(cpShader);
  50. return cpShader;
  51. }
  52. public GraphicsShader GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  53. {
  54. bool isCached = _gpPrograms.TryGetValue(addresses, out List<GraphicsShader> list);
  55. if (isCached)
  56. {
  57. foreach (GraphicsShader cachedGpShaders in list)
  58. {
  59. if (!IsShaderDifferent(cachedGpShaders, addresses))
  60. {
  61. return cachedGpShaders;
  62. }
  63. }
  64. }
  65. GraphicsShader gpShaders = new GraphicsShader();
  66. if (addresses.VertexA != 0)
  67. {
  68. gpShaders.Shader[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex, addresses.VertexA);
  69. }
  70. else
  71. {
  72. gpShaders.Shader[0] = TranslateGraphicsShader(state, ShaderStage.Vertex, addresses.Vertex);
  73. }
  74. gpShaders.Shader[1] = TranslateGraphicsShader(state, ShaderStage.TessellationControl, addresses.TessControl);
  75. gpShaders.Shader[2] = TranslateGraphicsShader(state, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  76. gpShaders.Shader[3] = TranslateGraphicsShader(state, ShaderStage.Geometry, addresses.Geometry);
  77. gpShaders.Shader[4] = TranslateGraphicsShader(state, ShaderStage.Fragment, addresses.Fragment);
  78. BackpropQualifiers(gpShaders);
  79. List<IShader> hostShaders = new List<IShader>();
  80. for (int stage = 0; stage < gpShaders.Shader.Length; stage++)
  81. {
  82. ShaderProgram program = gpShaders.Shader[stage].Program;
  83. if (program == null)
  84. {
  85. continue;
  86. }
  87. IShader hostShader = _context.Renderer.CompileShader(program);
  88. gpShaders.Shader[stage].Shader = hostShader;
  89. hostShaders.Add(hostShader);
  90. }
  91. gpShaders.HostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray());
  92. if (!isCached)
  93. {
  94. list = new List<GraphicsShader>();
  95. _gpPrograms.Add(addresses, list);
  96. }
  97. list.Add(gpShaders);
  98. return gpShaders;
  99. }
  100. private bool IsShaderDifferent(ComputeShader cpShader, ulong gpuVa)
  101. {
  102. return IsShaderDifferent(cpShader.Shader, gpuVa);
  103. }
  104. private bool IsShaderDifferent(GraphicsShader gpShaders, ShaderAddresses addresses)
  105. {
  106. for (int stage = 0; stage < gpShaders.Shader.Length; stage++)
  107. {
  108. CachedShader shader = gpShaders.Shader[stage];
  109. if (shader.Code == null)
  110. {
  111. continue;
  112. }
  113. ulong gpuVa = 0;
  114. switch (stage)
  115. {
  116. case 0: gpuVa = addresses.Vertex; break;
  117. case 1: gpuVa = addresses.TessControl; break;
  118. case 2: gpuVa = addresses.TessEvaluation; break;
  119. case 3: gpuVa = addresses.Geometry; break;
  120. case 4: gpuVa = addresses.Fragment; break;
  121. }
  122. if (IsShaderDifferent(shader, gpuVa))
  123. {
  124. return true;
  125. }
  126. }
  127. return false;
  128. }
  129. private bool IsShaderDifferent(CachedShader shader, ulong gpuVa)
  130. {
  131. for (int index = 0; index < shader.Code.Length; index++)
  132. {
  133. if (_context.MemoryAccessor.ReadInt32(gpuVa + (ulong)index * 4) != shader.Code[index])
  134. {
  135. return true;
  136. }
  137. }
  138. return false;
  139. }
  140. private CachedShader TranslateComputeShader(ulong gpuVa, int sharedMemorySize, int localSizeX, int localSizeY, int localSizeZ)
  141. {
  142. if (gpuVa == 0)
  143. {
  144. return null;
  145. }
  146. QueryInfoCallback queryInfo = (QueryInfoName info, int index) =>
  147. {
  148. switch (info)
  149. {
  150. case QueryInfoName.ComputeLocalSizeX:
  151. return localSizeX;
  152. case QueryInfoName.ComputeLocalSizeY:
  153. return localSizeY;
  154. case QueryInfoName.ComputeLocalSizeZ:
  155. return localSizeZ;
  156. case QueryInfoName.ComputeSharedMemorySize:
  157. return sharedMemorySize;
  158. }
  159. return QueryInfoCommon(info);
  160. };
  161. ShaderProgram program;
  162. Span<byte> code = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
  163. program = Translator.Translate(code, queryInfo, DefaultFlags | TranslationFlags.Compute);
  164. int[] codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  165. _dumper.Dump(code, compute: true, out string fullPath, out string codePath);
  166. if (fullPath != null && codePath != null)
  167. {
  168. program.Prepend("// " + codePath);
  169. program.Prepend("// " + fullPath);
  170. }
  171. return new CachedShader(program, codeCached);
  172. }
  173. private CachedShader TranslateGraphicsShader(GpuState state, ShaderStage stage, ulong gpuVa, ulong gpuVaA = 0)
  174. {
  175. if (gpuVa == 0)
  176. {
  177. return new CachedShader(null, null);
  178. }
  179. QueryInfoCallback queryInfo = (QueryInfoName info, int index) =>
  180. {
  181. switch (info)
  182. {
  183. case QueryInfoName.IsTextureBuffer:
  184. return Convert.ToInt32(QueryIsTextureBuffer(state, (int)stage - 1, index));
  185. case QueryInfoName.IsTextureRectangle:
  186. return Convert.ToInt32(QueryIsTextureRectangle(state, (int)stage - 1, index));
  187. case QueryInfoName.PrimitiveTopology:
  188. return (int)GetPrimitiveTopology();
  189. case QueryInfoName.ViewportTransformEnable:
  190. return Convert.ToInt32(_context.Methods.GetViewportTransformEnable(state));
  191. }
  192. return QueryInfoCommon(info);
  193. };
  194. ShaderProgram program;
  195. int[] codeCached = null;
  196. if (gpuVaA != 0)
  197. {
  198. Span<byte> codeA = _context.MemoryAccessor.Read(gpuVaA, MaxProgramSize);
  199. Span<byte> codeB = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
  200. program = Translator.Translate(codeA, codeB, queryInfo, DefaultFlags);
  201. // TODO: We should also take "codeA" into account.
  202. codeCached = MemoryMarshal.Cast<byte, int>(codeB.Slice(0, program.Size)).ToArray();
  203. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  204. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  205. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  206. {
  207. program.Prepend("// " + codePathB);
  208. program.Prepend("// " + fullPathB);
  209. program.Prepend("// " + codePathA);
  210. program.Prepend("// " + fullPathA);
  211. }
  212. }
  213. else
  214. {
  215. Span<byte> code = _context.MemoryAccessor.Read(gpuVa, MaxProgramSize);
  216. program = Translator.Translate(code, queryInfo, DefaultFlags);
  217. codeCached = MemoryMarshal.Cast<byte, int>(code.Slice(0, program.Size)).ToArray();
  218. _dumper.Dump(code, compute: false, out string fullPath, out string codePath);
  219. if (fullPath != null && codePath != null)
  220. {
  221. program.Prepend("// " + codePath);
  222. program.Prepend("// " + fullPath);
  223. }
  224. }
  225. ulong address = _context.MemoryManager.Translate(gpuVa);
  226. return new CachedShader(program, codeCached);
  227. }
  228. private void BackpropQualifiers(GraphicsShader program)
  229. {
  230. ShaderProgram fragmentShader = program.Shader[4].Program;
  231. bool isFirst = true;
  232. for (int stage = 3; stage >= 0; stage--)
  233. {
  234. if (program.Shader[stage].Program == null)
  235. {
  236. continue;
  237. }
  238. // We need to iterate backwards, since we do name replacement,
  239. // and it would otherwise replace a subset of the longer names.
  240. for (int attr = 31; attr >= 0; attr--)
  241. {
  242. string iq = fragmentShader?.Info.InterpolationQualifiers[attr].ToGlslQualifier() ?? string.Empty;
  243. if (isFirst && iq != string.Empty)
  244. {
  245. program.Shader[stage].Program.Replace($"{DefineNames.OutQualifierPrefixName}{attr}", iq);
  246. }
  247. else
  248. {
  249. program.Shader[stage].Program.Replace($"{DefineNames.OutQualifierPrefixName}{attr} ", string.Empty);
  250. }
  251. }
  252. isFirst = false;
  253. }
  254. }
  255. private InputTopology GetPrimitiveTopology()
  256. {
  257. switch (_context.Methods.PrimitiveType)
  258. {
  259. case PrimitiveType.Points:
  260. return InputTopology.Points;
  261. case PrimitiveType.Lines:
  262. case PrimitiveType.LineLoop:
  263. case PrimitiveType.LineStrip:
  264. return InputTopology.Lines;
  265. case PrimitiveType.LinesAdjacency:
  266. case PrimitiveType.LineStripAdjacency:
  267. return InputTopology.LinesAdjacency;
  268. case PrimitiveType.Triangles:
  269. case PrimitiveType.TriangleStrip:
  270. case PrimitiveType.TriangleFan:
  271. return InputTopology.Triangles;
  272. case PrimitiveType.TrianglesAdjacency:
  273. case PrimitiveType.TriangleStripAdjacency:
  274. return InputTopology.TrianglesAdjacency;
  275. }
  276. return InputTopology.Points;
  277. }
  278. private bool QueryIsTextureBuffer(GpuState state, int stageIndex, int index)
  279. {
  280. return GetTextureDescriptor(state, stageIndex, index).UnpackTextureTarget() == TextureTarget.TextureBuffer;
  281. }
  282. private bool QueryIsTextureRectangle(GpuState state, int stageIndex, int index)
  283. {
  284. var descriptor = GetTextureDescriptor(state, stageIndex, index);
  285. TextureTarget target = descriptor.UnpackTextureTarget();
  286. bool is2DTexture = target == TextureTarget.Texture2D ||
  287. target == TextureTarget.Texture2DRect;
  288. return !descriptor.UnpackTextureCoordNormalized() && is2DTexture;
  289. }
  290. private Image.TextureDescriptor GetTextureDescriptor(GpuState state, int stageIndex, int index)
  291. {
  292. return _context.Methods.TextureManager.GetGraphicsTextureDescriptor(state, stageIndex, index);
  293. }
  294. private int QueryInfoCommon(QueryInfoName info)
  295. {
  296. switch (info)
  297. {
  298. case QueryInfoName.MaximumViewportDimensions:
  299. return _context.Capabilities.MaximumViewportDimensions;
  300. case QueryInfoName.StorageBufferOffsetAlignment:
  301. return _context.Capabilities.StorageBufferOffsetAlignment;
  302. case QueryInfoName.SupportsNonConstantTextureOffset:
  303. return Convert.ToInt32(_context.Capabilities.SupportsNonConstantTextureOffset);
  304. }
  305. return 0;
  306. }
  307. }
  308. }