ShaderCache.cs 44 KB

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