ShaderCache.cs 35 KB

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