ShaderBinarySerializer.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Memory;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Shader;
  5. using Ryujinx.Graphics.Shader.Translation;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. namespace Ryujinx.Graphics.Gpu.Shader.DiskCache
  10. {
  11. static class ShaderBinarySerializer
  12. {
  13. public static byte[] Pack(ShaderSource[] sources)
  14. {
  15. using MemoryStream output = MemoryStreamManager.Shared.GetStream();
  16. output.Write(sources.Length);
  17. foreach (ShaderSource source in sources)
  18. {
  19. output.Write((int)source.Stage);
  20. output.Write(source.BinaryCode.Length);
  21. output.Write(source.BinaryCode);
  22. }
  23. return output.ToArray();
  24. }
  25. public static ShaderSource[] Unpack(CachedShaderStage[] stages, byte[] code)
  26. {
  27. using MemoryStream input = new MemoryStream(code);
  28. using BinaryReader reader = new BinaryReader(input);
  29. List<ShaderSource> output = new List<ShaderSource>();
  30. int count = reader.ReadInt32();
  31. for (int i = 0; i < count; i++)
  32. {
  33. ShaderStage stage = (ShaderStage)reader.ReadInt32();
  34. int binaryCodeLength = reader.ReadInt32();
  35. byte[] binaryCode = reader.ReadBytes(binaryCodeLength);
  36. output.Add(new ShaderSource(binaryCode, GetBindings(stages, stage), stage, TargetLanguage.Spirv));
  37. }
  38. return output.ToArray();
  39. }
  40. private static ShaderBindings GetBindings(CachedShaderStage[] stages, ShaderStage stage)
  41. {
  42. for (int i = 0; i < stages.Length; i++)
  43. {
  44. CachedShaderStage currentStage = stages[i];
  45. if (currentStage?.Info != null && currentStage.Info.Stage == stage)
  46. {
  47. return ShaderCache.GetBindings(currentStage.Info);
  48. }
  49. }
  50. return new ShaderBindings(Array.Empty<int>(), Array.Empty<int>(), Array.Empty<int>(), Array.Empty<int>());
  51. }
  52. }
  53. }