ShaderCache.cs 48 KB

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