ShaderCache.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Gpu.Shader.Cache;
  5. using Ryujinx.Graphics.Gpu.Shader.Cache.Definition;
  6. using Ryujinx.Graphics.Gpu.State;
  7. using Ryujinx.Graphics.Shader;
  8. using Ryujinx.Graphics.Shader.Translation;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. namespace Ryujinx.Graphics.Gpu.Shader
  13. {
  14. /// <summary>
  15. /// Memory cache of shader code.
  16. /// </summary>
  17. class ShaderCache : IDisposable
  18. {
  19. private const TranslationFlags DefaultFlags = TranslationFlags.DebugMode;
  20. private readonly GpuContext _context;
  21. private readonly ShaderDumper _dumper;
  22. private readonly Dictionary<ulong, List<ShaderBundle>> _cpPrograms;
  23. private readonly Dictionary<ShaderAddresses, List<ShaderBundle>> _gpPrograms;
  24. private CacheManager _cacheManager;
  25. private Dictionary<Hash128, ShaderBundle> _gpProgramsDiskCache;
  26. private Dictionary<Hash128, ShaderBundle> _cpProgramsDiskCache;
  27. /// <summary>
  28. /// Version of the codegen (to be changed when codegen or guest format change).
  29. /// </summary>
  30. private const ulong ShaderCodeGenVersion = 1961;
  31. /// <summary>
  32. /// Creates a new instance of the shader cache.
  33. /// </summary>
  34. /// <param name="context">GPU context that the shader cache belongs to</param>
  35. public ShaderCache(GpuContext context)
  36. {
  37. _context = context;
  38. _dumper = new ShaderDumper();
  39. _cpPrograms = new Dictionary<ulong, List<ShaderBundle>>();
  40. _gpPrograms = new Dictionary<ShaderAddresses, List<ShaderBundle>>();
  41. _gpProgramsDiskCache = new Dictionary<Hash128, ShaderBundle>();
  42. _cpProgramsDiskCache = new Dictionary<Hash128, ShaderBundle>();
  43. }
  44. /// <summary>
  45. /// Initialize the cache.
  46. /// </summary>
  47. internal void Initialize()
  48. {
  49. if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
  50. {
  51. _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);
  52. bool isReadOnly = _cacheManager.IsReadOnly;
  53. HashSet<Hash128> invalidEntries = null;
  54. if (isReadOnly)
  55. {
  56. Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
  57. }
  58. else
  59. {
  60. invalidEntries = new HashSet<Hash128>();
  61. }
  62. ReadOnlySpan<Hash128> guestProgramList = _cacheManager.GetGuestProgramList();
  63. for (int programIndex = 0; programIndex < guestProgramList.Length; programIndex++)
  64. {
  65. Hash128 key = guestProgramList[programIndex];
  66. Logger.Info?.Print(LogClass.Gpu, $"Compiling shader {key} ({programIndex + 1} / {guestProgramList.Length})");
  67. byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
  68. bool hasHostCache = hostProgramBinary != null;
  69. IProgram hostProgram = null;
  70. // If the program sources aren't in the cache, compile from saved guest program.
  71. byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);
  72. if (guestProgram == null)
  73. {
  74. Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");
  75. // Should not happen, but if someone messed with the cache it's better to catch it.
  76. invalidEntries?.Add(key);
  77. continue;
  78. }
  79. ReadOnlySpan<byte> guestProgramReadOnlySpan = guestProgram;
  80. ReadOnlySpan<GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);
  81. if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
  82. {
  83. Debug.Assert(cachedShaderEntries.Length == 1);
  84. GuestShaderCacheEntry entry = cachedShaderEntries[0];
  85. HostShaderCacheEntry[] hostShaderEntries = null;
  86. // Try loading host shader binary.
  87. if (hasHostCache)
  88. {
  89. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  90. hostProgramBinary = hostProgramBinarySpan.ToArray();
  91. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  92. }
  93. bool isHostProgramValid = hostProgram != null;
  94. ShaderProgram program;
  95. ShaderProgramInfo shaderProgramInfo;
  96. // Reconstruct code holder.
  97. if (isHostProgramValid)
  98. {
  99. program = new ShaderProgram(entry.Header.Stage, "");
  100. shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();
  101. }
  102. else
  103. {
  104. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  105. program = Translator.CreateContext(0, gpuAccessor, DefaultFlags | TranslationFlags.Compute).Translate(out shaderProgramInfo);
  106. }
  107. ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  108. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  109. if (hostProgram == null)
  110. {
  111. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  112. // Compile shader and create program as the shader program binary got invalidated.
  113. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  114. hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  115. // As the host program was invalidated, save the new entry in the cache.
  116. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  117. if (!isReadOnly)
  118. {
  119. if (hasHostCache)
  120. {
  121. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  122. }
  123. else
  124. {
  125. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  126. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  127. }
  128. }
  129. }
  130. _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));
  131. }
  132. else
  133. {
  134. Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);
  135. ShaderCodeHolder[] shaders = new ShaderCodeHolder[cachedShaderEntries.Length];
  136. List<ShaderProgram> shaderPrograms = new List<ShaderProgram>();
  137. TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);
  138. TranslationFlags flags = DefaultFlags;
  139. if (tfd != null)
  140. {
  141. flags = TranslationFlags.Feedback;
  142. }
  143. TranslationCounts counts = new TranslationCounts();
  144. HostShaderCacheEntry[] hostShaderEntries = null;
  145. // Try loading host shader binary.
  146. if (hasHostCache)
  147. {
  148. hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan<byte> hostProgramBinarySpan);
  149. hostProgramBinary = hostProgramBinarySpan.ToArray();
  150. hostProgram = _context.Renderer.LoadProgramBinary(hostProgramBinary);
  151. }
  152. bool isHostProgramValid = hostProgram != null;
  153. // Reconstruct code holder.
  154. for (int i = 0; i < cachedShaderEntries.Length; i++)
  155. {
  156. GuestShaderCacheEntry entry = cachedShaderEntries[i];
  157. if (entry == null)
  158. {
  159. continue;
  160. }
  161. ShaderProgram program;
  162. if (entry.Header.SizeA != 0)
  163. {
  164. ShaderProgramInfo shaderProgramInfo;
  165. if (isHostProgramValid)
  166. {
  167. program = new ShaderProgram(entry.Header.Stage, "");
  168. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  169. }
  170. else
  171. {
  172. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  173. TranslatorContext translatorContext = Translator.CreateContext(0, gpuAccessor, flags, counts);
  174. TranslatorContext translatorContext2 = Translator.CreateContext((ulong)entry.Header.Size, gpuAccessor, flags | TranslationFlags.VertexA, counts);
  175. program = translatorContext.Translate(out shaderProgramInfo, translatorContext2);
  176. }
  177. // NOTE: Vertex B comes first in the shader cache.
  178. byte[] code = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
  179. byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();
  180. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
  181. }
  182. else
  183. {
  184. ShaderProgramInfo shaderProgramInfo;
  185. if (isHostProgramValid)
  186. {
  187. program = new ShaderProgram(entry.Header.Stage, "");
  188. shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
  189. }
  190. else
  191. {
  192. IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);
  193. program = Translator.CreateContext(0, gpuAccessor, flags, counts).Translate(out shaderProgramInfo);
  194. }
  195. shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
  196. }
  197. shaderPrograms.Add(program);
  198. }
  199. // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
  200. if (!isHostProgramValid)
  201. {
  202. Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");
  203. List<IShader> hostShaders = new List<IShader>();
  204. // Compile shaders and create program as the shader program binary got invalidated.
  205. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  206. {
  207. ShaderProgram program = shaders[stage]?.Program;
  208. if (program == null)
  209. {
  210. continue;
  211. }
  212. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  213. shaders[stage].HostShader = hostShader;
  214. hostShaders.Add(hostShader);
  215. }
  216. hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  217. // As the host program was invalidated, save the new entry in the cache.
  218. hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  219. if (!isReadOnly)
  220. {
  221. if (hasHostCache)
  222. {
  223. _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
  224. }
  225. else
  226. {
  227. Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");
  228. _cacheManager.AddHostProgram(ref key, hostProgramBinary);
  229. }
  230. }
  231. }
  232. _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));
  233. }
  234. }
  235. if (!isReadOnly)
  236. {
  237. // Remove entries that are broken in the cache
  238. _cacheManager.RemoveManifestEntries(invalidEntries);
  239. _cacheManager.FlushToArchive();
  240. _cacheManager.Synchronize();
  241. }
  242. Logger.Info?.Print(LogClass.Gpu, "Shader cache loaded.");
  243. }
  244. }
  245. /// <summary>
  246. /// Gets a compute shader from the cache.
  247. /// </summary>
  248. /// <remarks>
  249. /// This automatically translates, compiles and adds the code to the cache if not present.
  250. /// </remarks>
  251. /// <param name="state">Current GPU state</param>
  252. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  253. /// <param name="localSizeX">Local group size X of the computer shader</param>
  254. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  255. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  256. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  257. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  258. /// <returns>Compiled compute shader code</returns>
  259. public ShaderBundle GetComputeShader(
  260. GpuState state,
  261. ulong gpuVa,
  262. int localSizeX,
  263. int localSizeY,
  264. int localSizeZ,
  265. int localMemorySize,
  266. int sharedMemorySize)
  267. {
  268. bool isCached = _cpPrograms.TryGetValue(gpuVa, out List<ShaderBundle> list);
  269. if (isCached)
  270. {
  271. foreach (ShaderBundle cachedCpShader in list)
  272. {
  273. if (IsShaderEqual(cachedCpShader, gpuVa))
  274. {
  275. return cachedCpShader;
  276. }
  277. }
  278. }
  279. TranslatorContext[] shaderContexts = new TranslatorContext[1];
  280. shaderContexts[0] = DecodeComputeShader(
  281. state,
  282. gpuVa,
  283. localSizeX,
  284. localSizeY,
  285. localSizeZ,
  286. localMemorySize,
  287. sharedMemorySize);
  288. bool isShaderCacheEnabled = _cacheManager != null;
  289. bool isShaderCacheReadOnly = false;
  290. Hash128 programCodeHash = default;
  291. GuestShaderCacheEntry[] shaderCacheEntries = null;
  292. if (isShaderCacheEnabled)
  293. {
  294. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  295. // Compute hash and prepare data for shader disk cache comparison.
  296. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
  297. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries);
  298. }
  299. ShaderBundle cpShader;
  300. // Search for the program hash in loaded shaders.
  301. if (!isShaderCacheEnabled || !_cpProgramsDiskCache.TryGetValue(programCodeHash, out cpShader))
  302. {
  303. if (isShaderCacheEnabled)
  304. {
  305. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  306. }
  307. // The shader isn't currently cached, translate it and compile it.
  308. ShaderCodeHolder shader = TranslateShader(shaderContexts[0]);
  309. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  310. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  311. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  312. cpShader = new ShaderBundle(hostProgram, shader);
  313. if (isShaderCacheEnabled)
  314. {
  315. _cpProgramsDiskCache.Add(programCodeHash, cpShader);
  316. if (!isShaderCacheReadOnly)
  317. {
  318. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries), hostProgramBinary);
  319. }
  320. }
  321. }
  322. if (!isCached)
  323. {
  324. list = new List<ShaderBundle>();
  325. _cpPrograms.Add(gpuVa, list);
  326. }
  327. list.Add(cpShader);
  328. return cpShader;
  329. }
  330. /// <summary>
  331. /// Gets a graphics shader program from the shader cache.
  332. /// This includes all the specified shader stages.
  333. /// </summary>
  334. /// <remarks>
  335. /// This automatically translates, compiles and adds the code to the cache if not present.
  336. /// </remarks>
  337. /// <param name="state">Current GPU state</param>
  338. /// <param name="addresses">Addresses of the shaders for each stage</param>
  339. /// <returns>Compiled graphics shader code</returns>
  340. public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  341. {
  342. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  343. if (isCached)
  344. {
  345. foreach (ShaderBundle cachedGpShaders in list)
  346. {
  347. if (IsShaderEqual(cachedGpShaders, addresses))
  348. {
  349. return cachedGpShaders;
  350. }
  351. }
  352. }
  353. TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages + 1];
  354. TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(state);
  355. TranslationFlags flags = DefaultFlags;
  356. if (tfd != null)
  357. {
  358. flags |= TranslationFlags.Feedback;
  359. }
  360. TranslationCounts counts = new TranslationCounts();
  361. if (addresses.VertexA != 0)
  362. {
  363. shaderContexts[0] = DecodeGraphicsShader(state, counts, flags | TranslationFlags.VertexA, ShaderStage.Vertex, addresses.VertexA);
  364. }
  365. shaderContexts[1] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
  366. shaderContexts[2] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
  367. shaderContexts[3] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  368. shaderContexts[4] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
  369. shaderContexts[5] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);
  370. bool isShaderCacheEnabled = _cacheManager != null;
  371. bool isShaderCacheReadOnly = false;
  372. Hash128 programCodeHash = default;
  373. GuestShaderCacheEntry[] shaderCacheEntries = null;
  374. if (isShaderCacheEnabled)
  375. {
  376. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  377. // Compute hash and prepare data for shader disk cache comparison.
  378. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
  379. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
  380. }
  381. ShaderBundle gpShaders;
  382. // Search for the program hash in loaded shaders.
  383. if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
  384. {
  385. if (isShaderCacheEnabled)
  386. {
  387. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  388. }
  389. // The shader isn't currently cached, translate it and compile it.
  390. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  391. shaders[0] = TranslateShader(shaderContexts[1], shaderContexts[0]);
  392. shaders[1] = TranslateShader(shaderContexts[2]);
  393. shaders[2] = TranslateShader(shaderContexts[3]);
  394. shaders[3] = TranslateShader(shaderContexts[4]);
  395. shaders[4] = TranslateShader(shaderContexts[5]);
  396. List<IShader> hostShaders = new List<IShader>();
  397. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  398. {
  399. ShaderProgram program = shaders[stage]?.Program;
  400. if (program == null)
  401. {
  402. continue;
  403. }
  404. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  405. shaders[stage].HostShader = hostShader;
  406. hostShaders.Add(hostShader);
  407. }
  408. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  409. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  410. gpShaders = new ShaderBundle(hostProgram, shaders);
  411. if (isShaderCacheEnabled)
  412. {
  413. _gpProgramsDiskCache.Add(programCodeHash, gpShaders);
  414. if (!isShaderCacheReadOnly)
  415. {
  416. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
  417. }
  418. }
  419. }
  420. if (!isCached)
  421. {
  422. list = new List<ShaderBundle>();
  423. _gpPrograms.Add(addresses, list);
  424. }
  425. list.Add(gpShaders);
  426. return gpShaders;
  427. }
  428. /// <summary>
  429. /// Gets transform feedback state from the current GPU state.
  430. /// </summary>
  431. /// <param name="state">Current GPU state</param>
  432. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  433. private TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  434. {
  435. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  436. if (!tfEnable)
  437. {
  438. return null;
  439. }
  440. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  441. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  442. {
  443. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  444. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  445. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  446. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  447. }
  448. return descs;
  449. }
  450. /// <summary>
  451. /// Checks if compute shader code in memory is equal to the cached shader.
  452. /// </summary>
  453. /// <param name="cpShader">Cached compute shader</param>
  454. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  455. /// <returns>True if the code is different, false otherwise</returns>
  456. private bool IsShaderEqual(ShaderBundle cpShader, ulong gpuVa)
  457. {
  458. return IsShaderEqual(cpShader.Shaders[0], gpuVa);
  459. }
  460. /// <summary>
  461. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  462. /// </summary>
  463. /// <param name="gpShaders">Cached graphics shaders</param>
  464. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  465. /// <returns>True if the code is different, false otherwise</returns>
  466. private bool IsShaderEqual(ShaderBundle gpShaders, ShaderAddresses addresses)
  467. {
  468. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  469. {
  470. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  471. ulong gpuVa = 0;
  472. switch (stage)
  473. {
  474. case 0: gpuVa = addresses.Vertex; break;
  475. case 1: gpuVa = addresses.TessControl; break;
  476. case 2: gpuVa = addresses.TessEvaluation; break;
  477. case 3: gpuVa = addresses.Geometry; break;
  478. case 4: gpuVa = addresses.Fragment; break;
  479. }
  480. if (!IsShaderEqual(shader, gpuVa, addresses.VertexA))
  481. {
  482. return false;
  483. }
  484. }
  485. return true;
  486. }
  487. /// <summary>
  488. /// Checks if the code of the specified cached shader is different from the code in memory.
  489. /// </summary>
  490. /// <param name="shader">Cached shader to compare with</param>
  491. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  492. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  493. /// <returns>True if the code is different, false otherwise</returns>
  494. private bool IsShaderEqual(ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  495. {
  496. if (shader == null)
  497. {
  498. return true;
  499. }
  500. ReadOnlySpan<byte> memoryCode = _context.MemoryManager.GetSpan(gpuVa, shader.Code.Length);
  501. bool equals = memoryCode.SequenceEqual(shader.Code);
  502. if (equals && shader.Code2 != null)
  503. {
  504. memoryCode = _context.MemoryManager.GetSpan(gpuVaA, shader.Code2.Length);
  505. equals = memoryCode.SequenceEqual(shader.Code2);
  506. }
  507. return equals;
  508. }
  509. /// <summary>
  510. /// Decode the binary Maxwell shader code to a translator context.
  511. /// </summary>
  512. /// <param name="state">Current GPU state</param>
  513. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  514. /// <param name="localSizeX">Local group size X of the computer shader</param>
  515. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  516. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  517. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  518. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  519. /// <returns>The generated translator context</returns>
  520. private TranslatorContext DecodeComputeShader(
  521. GpuState state,
  522. ulong gpuVa,
  523. int localSizeX,
  524. int localSizeY,
  525. int localSizeZ,
  526. int localMemorySize,
  527. int sharedMemorySize)
  528. {
  529. if (gpuVa == 0)
  530. {
  531. return null;
  532. }
  533. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  534. return Translator.CreateContext(gpuVa, gpuAccessor, DefaultFlags | TranslationFlags.Compute);
  535. }
  536. /// <summary>
  537. /// Decode the binary Maxwell shader code to a translator context.
  538. /// </summary>
  539. /// <remarks>
  540. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  541. /// </remarks>
  542. /// <param name="state">Current GPU state</param>
  543. /// <param name="counts">Cumulative shader resource counts</param>
  544. /// <param name="flags">Flags that controls shader translation</param>
  545. /// <param name="stage">Shader stage</param>
  546. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  547. /// <returns>The generated translator context</returns>
  548. private TranslatorContext DecodeGraphicsShader(
  549. GpuState state,
  550. TranslationCounts counts,
  551. TranslationFlags flags,
  552. ShaderStage stage,
  553. ulong gpuVa)
  554. {
  555. if (gpuVa == 0)
  556. {
  557. return null;
  558. }
  559. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  560. return Translator.CreateContext(gpuVa, gpuAccessor, flags, counts);
  561. }
  562. /// <summary>
  563. /// Translates a previously generated translator context to something that the host API accepts.
  564. /// </summary>
  565. /// <param name="translatorContext">Current translator context to translate</param>
  566. /// <param name="translatorContext2">Optional translator context of the shader that should be combined</param>
  567. /// <returns>Compiled graphics shader code</returns>
  568. private ShaderCodeHolder TranslateShader(TranslatorContext translatorContext, TranslatorContext translatorContext2 = null)
  569. {
  570. if (translatorContext == null)
  571. {
  572. return null;
  573. }
  574. if (translatorContext2 != null)
  575. {
  576. byte[] codeA = _context.MemoryManager.GetSpan(translatorContext2.Address, translatorContext2.Size).ToArray();
  577. byte[] codeB = _context.MemoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  578. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  579. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  580. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo, translatorContext2);
  581. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  582. {
  583. program.Prepend("// " + codePathB);
  584. program.Prepend("// " + fullPathB);
  585. program.Prepend("// " + codePathA);
  586. program.Prepend("// " + fullPathA);
  587. }
  588. return new ShaderCodeHolder(program, shaderProgramInfo, codeB, codeA);
  589. }
  590. else
  591. {
  592. byte[] code = _context.MemoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  593. _dumper.Dump(code, translatorContext.Stage == ShaderStage.Compute, out string fullPath, out string codePath);
  594. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo);
  595. if (fullPath != null && codePath != null)
  596. {
  597. program.Prepend("// " + codePath);
  598. program.Prepend("// " + fullPath);
  599. }
  600. return new ShaderCodeHolder(program, shaderProgramInfo, code);
  601. }
  602. }
  603. /// <summary>
  604. /// Disposes the shader cache, deleting all the cached shaders.
  605. /// It's an error to use the shader cache after disposal.
  606. /// </summary>
  607. public void Dispose()
  608. {
  609. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  610. {
  611. foreach (ShaderBundle bundle in list)
  612. {
  613. bundle.Dispose();
  614. }
  615. }
  616. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  617. {
  618. foreach (ShaderBundle bundle in list)
  619. {
  620. bundle.Dispose();
  621. }
  622. }
  623. _cacheManager?.Dispose();
  624. }
  625. }
  626. }