Utility.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text.RegularExpressions;
  7. using UnityEngine;
  8. namespace MeidoPhotoStudio.Plugin;
  9. public static class Utility
  10. {
  11. internal static readonly byte[] PngHeader = { 137, 80, 78, 71, 13, 10, 26, 10 };
  12. internal static readonly byte[] PngEnd = System.Text.Encoding.ASCII.GetBytes("IEND");
  13. internal static readonly Regex GuidRegEx =
  14. new(@"^[a-f0-9]{8}(\-[a-f0-9]{4}){3}\-[a-f0-9]{12}$", RegexOptions.IgnoreCase);
  15. internal static readonly GameObject MousePositionGameObject;
  16. internal static readonly MousePosition MousePositionValue;
  17. private const BindingFlags ReflectionFlags =
  18. BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
  19. private static readonly BepInEx.Logging.ManualLogSource Logger =
  20. BepInEx.Logging.Logger.CreateLogSource(MeidoPhotoStudio.PluginName);
  21. static Utility()
  22. {
  23. MousePositionGameObject = new();
  24. MousePositionValue = MousePositionGameObject.AddComponent<MousePosition>();
  25. }
  26. public enum ModKey
  27. {
  28. Control,
  29. Shift,
  30. Alt,
  31. }
  32. public static string Timestamp =>
  33. $"{DateTime.Now:yyyyMMddHHmmss}";
  34. public static Vector3 MousePosition =>
  35. MousePositionValue.Position;
  36. public static void LogInfo(object data) =>
  37. Logger.LogInfo(data);
  38. public static void LogMessage(object data) =>
  39. Logger.LogMessage(data);
  40. public static void LogWarning(object data) =>
  41. Logger.LogWarning(data);
  42. public static void LogError(object data) =>
  43. Logger.LogError(data);
  44. public static void LogDebug(object data) =>
  45. Logger.LogDebug(data);
  46. public static int Wrap(int value, int min, int max)
  47. {
  48. max--;
  49. return value < min ? max : value > max ? min : value;
  50. }
  51. public static int GetPix(int num) =>
  52. (int)((1f + (Screen.width / 1280f - 1f) * 0.6f) * num);
  53. public static float Bound(float value, float left, float right) =>
  54. left > (double)right ? Mathf.Clamp(value, right, left) : Mathf.Clamp(value, left, right);
  55. public static int Bound(int value, int left, int right) =>
  56. left > right ? Mathf.Clamp(value, right, left) : Mathf.Clamp(value, left, right);
  57. public static Texture2D MakeTex(int width, int height, Color color)
  58. {
  59. var colors = new Color32[width * height];
  60. for (var i = 0; i < colors.Length; i++)
  61. colors[i] = color;
  62. var texture2D = new Texture2D(width, height);
  63. texture2D.SetPixels32(colors);
  64. texture2D.Apply();
  65. return texture2D;
  66. }
  67. public static FieldInfo GetFieldInfo<T>(string field) =>
  68. typeof(T).GetField(field, ReflectionFlags);
  69. public static TValue GetFieldValue<TType, TValue>(TType instance, string field)
  70. {
  71. var fieldInfo = GetFieldInfo<TType>(field);
  72. return fieldInfo is null || !fieldInfo.IsStatic && instance == null
  73. ? default
  74. : (TValue)fieldInfo.GetValue(instance);
  75. }
  76. public static void SetFieldValue<TType, TValue>(TType instance, string name, TValue value) =>
  77. GetFieldInfo<TType>(name).SetValue(instance, value);
  78. public static PropertyInfo GetPropertyInfo<T>(string field) =>
  79. typeof(T).GetProperty(field, ReflectionFlags);
  80. public static TValue GetPropertyValue<TType, TValue>(TType instance, string property)
  81. {
  82. var propertyInfo = GetPropertyInfo<TType>(property);
  83. return propertyInfo is null
  84. ? default
  85. : (TValue)propertyInfo.GetValue(instance, null);
  86. }
  87. public static void SetPropertyValue<TType, TValue>(TType instance, string name, TValue value) =>
  88. GetPropertyInfo<TType>(name).SetValue(instance, value, null);
  89. public static bool AnyMouseDown() =>
  90. Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2);
  91. public static string ScreenshotFilename()
  92. {
  93. var screenShotDir = Path.Combine(GameMain.Instance.SerializeStorageManager.StoreDirectoryPath, "ScreenShot");
  94. if (!Directory.Exists(screenShotDir))
  95. Directory.CreateDirectory(screenShotDir);
  96. return Path.Combine(screenShotDir, $"img{Timestamp}.png");
  97. }
  98. public static string TempScreenshotFilename() =>
  99. Path.Combine(Path.GetTempPath(), $"cm3d2_{Guid.NewGuid()}.png");
  100. public static void ShowMouseExposition(string text, float time = 2f)
  101. {
  102. var mouseExposition = MouseExposition.GetObject();
  103. mouseExposition.SetText(text, time);
  104. }
  105. public static bool IsGuidString(string guid) =>
  106. !string.IsNullOrEmpty(guid) && guid.Length is 36 && GuidRegEx.IsMatch(guid);
  107. public static string HandItemToOdogu(string menu)
  108. {
  109. menu = menu.Substring(menu.IndexOf('_') + 1);
  110. menu = menu.Substring(0, menu.IndexOf("_i_.menu", StringComparison.OrdinalIgnoreCase));
  111. menu = $"odogu_{menu}";
  112. return menu;
  113. }
  114. public static void FixGameObjectScale(GameObject go)
  115. {
  116. var scale = go.transform.localScale;
  117. var largest = Mathf.Max(scale.x, Mathf.Max(scale.y, scale.z));
  118. go.transform.localScale = Vector3.one * (float)Math.Round(largest, 3);
  119. }
  120. public static string SanitizePathPortion(string path)
  121. {
  122. var invalid = Path.GetInvalidFileNameChars();
  123. path = path.Trim();
  124. path = string.Join("_", path.Split(invalid)).Replace(".", string.Empty).Trim('_');
  125. return path;
  126. }
  127. public static string GP01FbFaceHash(TMorph face, string hash)
  128. {
  129. if (face.bodyskin.PartsVersion < 120 || hash is "eyeclose3" || !hash.StartsWith("eyeclose"))
  130. return hash;
  131. if (hash is "eyeclose")
  132. hash += '1';
  133. hash += TMorph.crcFaceTypesStr[(int)face.GetFaceTypeGP01FB()];
  134. return hash;
  135. }
  136. public static void ResizeToFit(Texture2D texture, int maxWidth, int maxHeight)
  137. {
  138. var width = texture.width;
  139. var height = texture.height;
  140. if (width == maxWidth && height == maxHeight)
  141. return;
  142. var scale = Mathf.Min(maxWidth / (float)width, maxHeight / (float)height);
  143. width = Mathf.RoundToInt(width * scale);
  144. height = Mathf.RoundToInt(height * scale);
  145. TextureScale.Bilinear(texture, width, height);
  146. }
  147. public static bool BytesEqual(byte[] buffer, byte[] other)
  148. {
  149. if (buffer.Length != other.Length)
  150. return false;
  151. for (var i = 0; i < buffer.Length; i++)
  152. if (buffer[i] != other[i])
  153. return false;
  154. return true;
  155. }
  156. public static bool IsPngFile(Stream stream)
  157. {
  158. var buffer = new byte[8];
  159. stream.Read(buffer, 0, 8);
  160. return BytesEqual(buffer, PngHeader);
  161. }
  162. public static bool SeekPngEnd(Stream stream)
  163. {
  164. var buffer = new byte[8];
  165. stream.Read(buffer, 0, 8);
  166. if (!BytesEqual(buffer, PngHeader))
  167. return false;
  168. buffer = new byte[4];
  169. do
  170. {
  171. stream.Read(buffer, 0, 4);
  172. if (BitConverter.IsLittleEndian)
  173. Array.Reverse(buffer);
  174. var length = BitConverter.ToUInt32(buffer, 0);
  175. stream.Read(buffer, 0, 4);
  176. stream.Seek(length + 4L, SeekOrigin.Current);
  177. }
  178. while (!BytesEqual(buffer, PngEnd));
  179. return true;
  180. }
  181. public static void WriteToFile(string name, IEnumerable<string> list)
  182. {
  183. if (Path.GetExtension(name) is not ".txt")
  184. name += ".txt";
  185. File.WriteAllLines(Path.Combine(Constants.ConfigPath, name), list.ToArray());
  186. }
  187. public static void WriteToFile(string name, byte[] data) =>
  188. File.WriteAllBytes(Path.Combine(Constants.ConfigPath, name), data);
  189. }