TextureExtensions.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using Harmony;
  7. using UnityEngine;
  8. using XUnity.AutoTranslator.Plugin.Core.Constants;
  9. namespace XUnity.AutoTranslator.Plugin.Core.Extensions
  10. {
  11. public static class TextureExtensions
  12. {
  13. private static readonly MethodInfo LoadImage = AccessTools.Method( ClrTypes.ImageConversion, "LoadImage", new[] { typeof( Texture2D ), typeof( byte[] ), typeof( bool ) } );
  14. private static readonly MethodInfo EncodeToPNG = AccessTools.Method( ClrTypes.ImageConversion, "EncodeToPNG", new[] { typeof( Texture2D ) } );
  15. public static bool IsNonReadable( this Texture2D texture )
  16. {
  17. return texture.GetRawTextureData().Length == 0;
  18. }
  19. public static void LoadImageEx( this Texture2D texture, byte[] data, bool markNonReadable )
  20. {
  21. if( LoadImage != null )
  22. {
  23. LoadImage.Invoke( null, new object[] { texture, data, markNonReadable } );
  24. }
  25. else
  26. {
  27. texture.LoadImageSafe( data, markNonReadable );
  28. }
  29. }
  30. private static void LoadImageSafe( this Texture2D texture, byte[] data, bool markNonReadable )
  31. {
  32. texture.LoadImage( data, markNonReadable );
  33. }
  34. public static byte[] EncodeToPNGEx( this Texture2D texture )
  35. {
  36. if( EncodeToPNG != null )
  37. {
  38. return (byte[])EncodeToPNG.Invoke( null, new object[] { texture } );
  39. }
  40. else
  41. {
  42. return texture.EncodeToPNGSafe();
  43. }
  44. }
  45. private static byte[] EncodeToPNGSafe( this Texture2D texture )
  46. {
  47. return texture.EncodeToPNG();
  48. }
  49. }
  50. }