ShaderCache.cs 48 KB

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