ShaderCache.cs 50 KB

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