ShaderCache.cs 44 KB

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