ShaderCache.cs 42 KB

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