ShaderCache.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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. bool isDiskShaderCacheIncompatible = shaderContexts[0].UsedFeatures.HasFlag(FeatureFlags.Bindless);
  336. shader.HostShader = _context.Renderer.CompileShader(ShaderStage.Compute, shader.Program.Code);
  337. IProgram hostProgram = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);
  338. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });
  339. cpShader = new ShaderBundle(hostProgram, shader);
  340. if (isShaderCacheEnabled && !isDiskShaderCacheIncompatible)
  341. {
  342. _cpProgramsDiskCache.Add(programCodeHash, cpShader);
  343. if (!isShaderCacheReadOnly)
  344. {
  345. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries), hostProgramBinary);
  346. }
  347. }
  348. }
  349. if (!isCached)
  350. {
  351. list = new List<ShaderBundle>();
  352. _cpPrograms.Add(gpuVa, list);
  353. }
  354. list.Add(cpShader);
  355. return cpShader;
  356. }
  357. /// <summary>
  358. /// Gets a graphics shader program from the shader cache.
  359. /// This includes all the specified shader stages.
  360. /// </summary>
  361. /// <remarks>
  362. /// This automatically translates, compiles and adds the code to the cache if not present.
  363. /// </remarks>
  364. /// <param name="state">Current GPU state</param>
  365. /// <param name="addresses">Addresses of the shaders for each stage</param>
  366. /// <returns>Compiled graphics shader code</returns>
  367. public ShaderBundle GetGraphicsShader(GpuState state, ShaderAddresses addresses)
  368. {
  369. bool isCached = _gpPrograms.TryGetValue(addresses, out List<ShaderBundle> list);
  370. if (isCached)
  371. {
  372. foreach (ShaderBundle cachedGpShaders in list)
  373. {
  374. if (IsShaderEqual(cachedGpShaders, addresses))
  375. {
  376. return cachedGpShaders;
  377. }
  378. }
  379. }
  380. TranslatorContext[] shaderContexts = new TranslatorContext[Constants.ShaderStages + 1];
  381. TransformFeedbackDescriptor[] tfd = GetTransformFeedbackDescriptors(state);
  382. TranslationFlags flags = DefaultFlags;
  383. if (tfd != null)
  384. {
  385. flags |= TranslationFlags.Feedback;
  386. }
  387. TranslationCounts counts = new TranslationCounts();
  388. if (addresses.VertexA != 0)
  389. {
  390. shaderContexts[0] = DecodeGraphicsShader(state, counts, flags | TranslationFlags.VertexA, ShaderStage.Vertex, addresses.VertexA);
  391. }
  392. shaderContexts[1] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Vertex, addresses.Vertex);
  393. shaderContexts[2] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationControl, addresses.TessControl);
  394. shaderContexts[3] = DecodeGraphicsShader(state, counts, flags, ShaderStage.TessellationEvaluation, addresses.TessEvaluation);
  395. shaderContexts[4] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Geometry, addresses.Geometry);
  396. shaderContexts[5] = DecodeGraphicsShader(state, counts, flags, ShaderStage.Fragment, addresses.Fragment);
  397. bool isShaderCacheEnabled = _cacheManager != null;
  398. bool isShaderCacheReadOnly = false;
  399. Hash128 programCodeHash = default;
  400. GuestShaderCacheEntry[] shaderCacheEntries = null;
  401. if (isShaderCacheEnabled)
  402. {
  403. isShaderCacheReadOnly = _cacheManager.IsReadOnly;
  404. // Compute hash and prepare data for shader disk cache comparison.
  405. shaderCacheEntries = CacheHelper.CreateShaderCacheEntries(_context.MemoryManager, shaderContexts);
  406. programCodeHash = CacheHelper.ComputeGuestHashFromCache(shaderCacheEntries, tfd);
  407. }
  408. ShaderBundle gpShaders;
  409. // Search for the program hash in loaded shaders.
  410. if (!isShaderCacheEnabled || !_gpProgramsDiskCache.TryGetValue(programCodeHash, out gpShaders))
  411. {
  412. if (isShaderCacheEnabled)
  413. {
  414. Logger.Debug?.Print(LogClass.Gpu, $"Shader {programCodeHash} not in cache, compiling!");
  415. }
  416. // The shader isn't currently cached, translate it and compile it.
  417. ShaderCodeHolder[] shaders = new ShaderCodeHolder[Constants.ShaderStages];
  418. shaders[0] = TranslateShader(shaderContexts[1], shaderContexts[0]);
  419. shaders[1] = TranslateShader(shaderContexts[2]);
  420. shaders[2] = TranslateShader(shaderContexts[3]);
  421. shaders[3] = TranslateShader(shaderContexts[4]);
  422. shaders[4] = TranslateShader(shaderContexts[5]);
  423. bool isDiskShaderCacheIncompatible = false;
  424. for (int i = 0; i < shaderContexts.Length; i++)
  425. {
  426. if (shaderContexts[i] != null && shaderContexts[i].UsedFeatures.HasFlag(FeatureFlags.Bindless))
  427. {
  428. isDiskShaderCacheIncompatible = true;
  429. break;
  430. }
  431. }
  432. List<IShader> hostShaders = new List<IShader>();
  433. for (int stage = 0; stage < Constants.ShaderStages; stage++)
  434. {
  435. ShaderProgram program = shaders[stage]?.Program;
  436. if (program == null)
  437. {
  438. continue;
  439. }
  440. IShader hostShader = _context.Renderer.CompileShader(program.Stage, program.Code);
  441. shaders[stage].HostShader = hostShader;
  442. hostShaders.Add(hostShader);
  443. }
  444. IProgram hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);
  445. byte[] hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);
  446. gpShaders = new ShaderBundle(hostProgram, shaders);
  447. if (isShaderCacheEnabled && !isDiskShaderCacheIncompatible)
  448. {
  449. _gpProgramsDiskCache.Add(programCodeHash, gpShaders);
  450. if (!isShaderCacheReadOnly)
  451. {
  452. _cacheManager.SaveProgram(ref programCodeHash, CacheHelper.CreateGuestProgramDump(shaderCacheEntries, tfd), hostProgramBinary);
  453. }
  454. }
  455. }
  456. if (!isCached)
  457. {
  458. list = new List<ShaderBundle>();
  459. _gpPrograms.Add(addresses, list);
  460. }
  461. list.Add(gpShaders);
  462. return gpShaders;
  463. }
  464. /// <summary>
  465. /// Gets transform feedback state from the current GPU state.
  466. /// </summary>
  467. /// <param name="state">Current GPU state</param>
  468. /// <returns>Four transform feedback descriptors for the enabled TFBs, or null if TFB is disabled</returns>
  469. private TransformFeedbackDescriptor[] GetTransformFeedbackDescriptors(GpuState state)
  470. {
  471. bool tfEnable = state.Get<Boolean32>(MethodOffset.TfEnable);
  472. if (!tfEnable)
  473. {
  474. return null;
  475. }
  476. TransformFeedbackDescriptor[] descs = new TransformFeedbackDescriptor[Constants.TotalTransformFeedbackBuffers];
  477. for (int i = 0; i < Constants.TotalTransformFeedbackBuffers; i++)
  478. {
  479. var tf = state.Get<TfState>(MethodOffset.TfState, i);
  480. int length = (int)Math.Min((uint)tf.VaryingsCount, 0x80);
  481. var varyingLocations = state.GetSpan(MethodOffset.TfVaryingLocations + i * 0x80, length).ToArray();
  482. descs[i] = new TransformFeedbackDescriptor(tf.BufferIndex, tf.Stride, varyingLocations);
  483. }
  484. return descs;
  485. }
  486. /// <summary>
  487. /// Checks if compute shader code in memory is equal to the cached shader.
  488. /// </summary>
  489. /// <param name="cpShader">Cached compute shader</param>
  490. /// <param name="gpuVa">GPU virtual address of the shader code in memory</param>
  491. /// <returns>True if the code is different, false otherwise</returns>
  492. private bool IsShaderEqual(ShaderBundle cpShader, ulong gpuVa)
  493. {
  494. return IsShaderEqual(cpShader.Shaders[0], gpuVa);
  495. }
  496. /// <summary>
  497. /// Checks if graphics shader code from all stages in memory are equal to the cached shaders.
  498. /// </summary>
  499. /// <param name="gpShaders">Cached graphics shaders</param>
  500. /// <param name="addresses">GPU virtual addresses of all enabled shader stages</param>
  501. /// <returns>True if the code is different, false otherwise</returns>
  502. private bool IsShaderEqual(ShaderBundle gpShaders, ShaderAddresses addresses)
  503. {
  504. for (int stage = 0; stage < gpShaders.Shaders.Length; stage++)
  505. {
  506. ShaderCodeHolder shader = gpShaders.Shaders[stage];
  507. ulong gpuVa = 0;
  508. switch (stage)
  509. {
  510. case 0: gpuVa = addresses.Vertex; break;
  511. case 1: gpuVa = addresses.TessControl; break;
  512. case 2: gpuVa = addresses.TessEvaluation; break;
  513. case 3: gpuVa = addresses.Geometry; break;
  514. case 4: gpuVa = addresses.Fragment; break;
  515. }
  516. if (!IsShaderEqual(shader, gpuVa, addresses.VertexA))
  517. {
  518. return false;
  519. }
  520. }
  521. return true;
  522. }
  523. /// <summary>
  524. /// Checks if the code of the specified cached shader is different from the code in memory.
  525. /// </summary>
  526. /// <param name="shader">Cached shader to compare with</param>
  527. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  528. /// <param name="gpuVaA">Optional GPU virtual address of the "Vertex A" binary shader code</param>
  529. /// <returns>True if the code is different, false otherwise</returns>
  530. private bool IsShaderEqual(ShaderCodeHolder shader, ulong gpuVa, ulong gpuVaA = 0)
  531. {
  532. if (shader == null)
  533. {
  534. return true;
  535. }
  536. ReadOnlySpan<byte> memoryCode = _context.MemoryManager.GetSpan(gpuVa, shader.Code.Length);
  537. bool equals = memoryCode.SequenceEqual(shader.Code);
  538. if (equals && shader.Code2 != null)
  539. {
  540. memoryCode = _context.MemoryManager.GetSpan(gpuVaA, shader.Code2.Length);
  541. equals = memoryCode.SequenceEqual(shader.Code2);
  542. }
  543. return equals;
  544. }
  545. /// <summary>
  546. /// Decode the binary Maxwell shader code to a translator context.
  547. /// </summary>
  548. /// <param name="state">Current GPU state</param>
  549. /// <param name="gpuVa">GPU virtual address of the binary shader code</param>
  550. /// <param name="localSizeX">Local group size X of the computer shader</param>
  551. /// <param name="localSizeY">Local group size Y of the computer shader</param>
  552. /// <param name="localSizeZ">Local group size Z of the computer shader</param>
  553. /// <param name="localMemorySize">Local memory size of the compute shader</param>
  554. /// <param name="sharedMemorySize">Shared memory size of the compute shader</param>
  555. /// <returns>The generated translator context</returns>
  556. private TranslatorContext DecodeComputeShader(
  557. GpuState state,
  558. ulong gpuVa,
  559. int localSizeX,
  560. int localSizeY,
  561. int localSizeZ,
  562. int localMemorySize,
  563. int sharedMemorySize)
  564. {
  565. if (gpuVa == 0)
  566. {
  567. return null;
  568. }
  569. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, localSizeX, localSizeY, localSizeZ, localMemorySize, sharedMemorySize);
  570. return Translator.CreateContext(gpuVa, gpuAccessor, DefaultFlags | TranslationFlags.Compute);
  571. }
  572. /// <summary>
  573. /// Decode the binary Maxwell shader code to a translator context.
  574. /// </summary>
  575. /// <remarks>
  576. /// This will combine the "Vertex A" and "Vertex B" shader stages, if specified, into one shader.
  577. /// </remarks>
  578. /// <param name="state">Current GPU state</param>
  579. /// <param name="counts">Cumulative shader resource counts</param>
  580. /// <param name="flags">Flags that controls shader translation</param>
  581. /// <param name="stage">Shader stage</param>
  582. /// <param name="gpuVa">GPU virtual address of the shader code</param>
  583. /// <returns>The generated translator context</returns>
  584. private TranslatorContext DecodeGraphicsShader(
  585. GpuState state,
  586. TranslationCounts counts,
  587. TranslationFlags flags,
  588. ShaderStage stage,
  589. ulong gpuVa)
  590. {
  591. if (gpuVa == 0)
  592. {
  593. return null;
  594. }
  595. GpuAccessor gpuAccessor = new GpuAccessor(_context, state, (int)stage - 1);
  596. return Translator.CreateContext(gpuVa, gpuAccessor, flags, counts);
  597. }
  598. /// <summary>
  599. /// Translates a previously generated translator context to something that the host API accepts.
  600. /// </summary>
  601. /// <param name="translatorContext">Current translator context to translate</param>
  602. /// <param name="translatorContext2">Optional translator context of the shader that should be combined</param>
  603. /// <returns>Compiled graphics shader code</returns>
  604. private ShaderCodeHolder TranslateShader(TranslatorContext translatorContext, TranslatorContext translatorContext2 = null)
  605. {
  606. if (translatorContext == null)
  607. {
  608. return null;
  609. }
  610. if (translatorContext2 != null)
  611. {
  612. byte[] codeA = _context.MemoryManager.GetSpan(translatorContext2.Address, translatorContext2.Size).ToArray();
  613. byte[] codeB = _context.MemoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  614. _dumper.Dump(codeA, compute: false, out string fullPathA, out string codePathA);
  615. _dumper.Dump(codeB, compute: false, out string fullPathB, out string codePathB);
  616. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo, translatorContext2);
  617. if (fullPathA != null && fullPathB != null && codePathA != null && codePathB != null)
  618. {
  619. program.Prepend("// " + codePathB);
  620. program.Prepend("// " + fullPathB);
  621. program.Prepend("// " + codePathA);
  622. program.Prepend("// " + fullPathA);
  623. }
  624. return new ShaderCodeHolder(program, shaderProgramInfo, codeB, codeA);
  625. }
  626. else
  627. {
  628. byte[] code = _context.MemoryManager.GetSpan(translatorContext.Address, translatorContext.Size).ToArray();
  629. _dumper.Dump(code, translatorContext.Stage == ShaderStage.Compute, out string fullPath, out string codePath);
  630. ShaderProgram program = translatorContext.Translate(out ShaderProgramInfo shaderProgramInfo);
  631. if (fullPath != null && codePath != null)
  632. {
  633. program.Prepend("// " + codePath);
  634. program.Prepend("// " + fullPath);
  635. }
  636. return new ShaderCodeHolder(program, shaderProgramInfo, code);
  637. }
  638. }
  639. /// <summary>
  640. /// Disposes the shader cache, deleting all the cached shaders.
  641. /// It's an error to use the shader cache after disposal.
  642. /// </summary>
  643. public void Dispose()
  644. {
  645. foreach (List<ShaderBundle> list in _cpPrograms.Values)
  646. {
  647. foreach (ShaderBundle bundle in list)
  648. {
  649. bundle.Dispose();
  650. }
  651. }
  652. foreach (List<ShaderBundle> list in _gpPrograms.Values)
  653. {
  654. foreach (ShaderBundle bundle in list)
  655. {
  656. bundle.Dispose();
  657. }
  658. }
  659. _progressReportEvent?.Dispose();
  660. _cacheManager?.Dispose();
  661. }
  662. }
  663. }