Utility.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. using System;
  2. using System.Text.RegularExpressions;
  3. using System.IO;
  4. using System.Reflection;
  5. using UnityEngine;
  6. using System.Linq;
  7. namespace COM3D2.MeidoPhotoStudio.Plugin
  8. {
  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 = new Regex(
  14. @"^[a-f0-9]{8}(\-[a-f0-9]{4}){3}\-[a-f0-9]{12}$", RegexOptions.IgnoreCase
  15. );
  16. internal static readonly GameObject mousePositionGo;
  17. internal static readonly MousePosition mousePosition;
  18. public static readonly BepInEx.Logging.ManualLogSource Logger
  19. = BepInEx.Logging.Logger.CreateLogSource(MeidoPhotoStudio.pluginName);
  20. public enum ModKey
  21. {
  22. Control, Shift, Alt
  23. }
  24. public static string Timestamp => $"{DateTime.Now:yyyyMMddHHmmss}";
  25. public static Vector3 MousePosition => mousePosition.Position;
  26. static Utility()
  27. {
  28. mousePositionGo = new GameObject();
  29. mousePosition = mousePositionGo.AddComponent<MousePosition>();
  30. }
  31. public static void LogInfo(object data) => Logger.LogInfo(data);
  32. public static void LogMessage(object data) => Logger.LogMessage(data);
  33. public static void LogWarning(object data) => Logger.LogWarning(data);
  34. public static void LogError(object data) => Logger.LogError(data);
  35. public static void LogDebug(object data) => Logger.LogDebug(data);
  36. public static int Wrap(int value, int min, int max)
  37. {
  38. max--;
  39. return value < min ? max : value > max ? min : value;
  40. }
  41. public static int GetPix(int num) => (int)((1f + (((Screen.width / 1280f) - 1f) * 0.6f)) * num);
  42. public static float Bound(float value, float left, float right)
  43. {
  44. return left > (double)right ? Mathf.Clamp(value, right, left) : Mathf.Clamp(value, left, right);
  45. }
  46. public static int Bound(int value, int left, int right)
  47. {
  48. return left > right ? Mathf.Clamp(value, right, left) : Mathf.Clamp(value, left, right);
  49. }
  50. public static Texture2D MakeTex(int width, int height, Color color)
  51. {
  52. Color[] colors = new Color[width * height];
  53. for (int i = 0; i < colors.Length; i++)
  54. {
  55. colors[i] = color;
  56. }
  57. Texture2D texture2D = new Texture2D(width, height);
  58. texture2D.SetPixels(colors);
  59. texture2D.Apply();
  60. return texture2D;
  61. }
  62. public static FieldInfo GetFieldInfo<T>(string field)
  63. {
  64. const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
  65. | BindingFlags.Static;
  66. return typeof(T).GetField(field, bindingFlags);
  67. }
  68. public static TValue GetFieldValue<TType, TValue>(TType instance, string field)
  69. {
  70. FieldInfo fieldInfo = GetFieldInfo<TType>(field);
  71. if (fieldInfo == null || (!fieldInfo.IsStatic && instance == null)) return default;
  72. return (TValue)fieldInfo.GetValue(instance);
  73. }
  74. public static void SetFieldValue<TType, TValue>(TType instance, string name, TValue value)
  75. {
  76. GetFieldInfo<TType>(name).SetValue(instance, value);
  77. }
  78. public static bool AnyMouseDown()
  79. {
  80. return Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2);
  81. }
  82. public static string ScreenshotFilename()
  83. {
  84. string screenShotDir = Path.Combine(
  85. GameMain.Instance.SerializeStorageManager.StoreDirectoryPath, "ScreenShot"
  86. );
  87. if (!Directory.Exists(screenShotDir)) Directory.CreateDirectory(screenShotDir);
  88. return Path.Combine(screenShotDir, $"img{Timestamp}.png");
  89. }
  90. public static string TempScreenshotFilename()
  91. {
  92. return Path.Combine(Path.GetTempPath(), $"cm3d2_{Guid.NewGuid()}.png");
  93. }
  94. public static void ShowMouseExposition(string text, float time = 2f)
  95. {
  96. MouseExposition mouseExposition = MouseExposition.GetObject();
  97. mouseExposition.SetText(text, time);
  98. }
  99. public static bool IsGuidString(string guid)
  100. {
  101. if (string.IsNullOrEmpty(guid) || guid.Length != 36) return false;
  102. return guidRegEx.IsMatch(guid);
  103. }
  104. public static string HandItemToOdogu(string menu)
  105. {
  106. menu = menu.Substring(menu.IndexOf('_') + 1);
  107. menu = menu.Substring(0, menu.IndexOf("_i_.menu"));
  108. menu = $"odogu_{menu}";
  109. return menu;
  110. }
  111. public static void FixGameObjectScale(GameObject go)
  112. {
  113. Vector3 scale = go.transform.localScale;
  114. float largest = Mathf.Max(scale.x, Mathf.Max(scale.y, scale.z));
  115. go.transform.localScale = Vector3.one * (float)Math.Round(largest, 3);
  116. }
  117. public static string SanitizePathPortion(string path)
  118. {
  119. char[] invalid = Path.GetInvalidFileNameChars();
  120. path = path.Trim();
  121. path = string.Join("_", path.Split(invalid)).Replace(".", "").Trim('_');
  122. return path;
  123. }
  124. public static string GP01FbFaceHash(TMorph face, string hash)
  125. {
  126. if ((face.bodyskin.PartsVersion >= 120) && (hash != "eyeclose3") && hash.StartsWith("eyeclose"))
  127. {
  128. if (hash == "eyeclose") hash += '1';
  129. hash += TMorph.crcFaceTypesStr[(int)face.GetFaceTypeGP01FB()];
  130. }
  131. return hash;
  132. }
  133. public static void ResizeToFit(Texture2D texture, int maxWidth, int maxHeight)
  134. {
  135. int width = texture.width;
  136. int height = texture.height;
  137. if (width != maxWidth || height != maxHeight)
  138. {
  139. float scale = Mathf.Min(maxWidth / (float)width, maxHeight / (float)height);
  140. width = Mathf.RoundToInt(width * scale);
  141. height = Mathf.RoundToInt(height * scale);
  142. TextureScale.Bilinear(texture, width, height);
  143. }
  144. }
  145. public static bool BytesEqual(byte[] buffer, byte[] other)
  146. {
  147. if (buffer.Length != other.Length) return false;
  148. for (int i = 0; i < buffer.Length; i++)
  149. {
  150. if (buffer[i] != other[i]) return false;
  151. }
  152. return true;
  153. }
  154. public static bool IsPngFile(Stream stream)
  155. {
  156. byte[] buffer = new byte[8];
  157. stream.Read(buffer, 0, 8);
  158. stream.Position = 0L;
  159. return BytesEqual(buffer, pngHeader);
  160. }
  161. public static bool SeekPngEnd(Stream stream)
  162. {
  163. byte[] buffer = new byte[8];
  164. stream.Read(buffer, 0, 8);
  165. if (!BytesEqual(buffer, pngHeader)) return false;
  166. buffer = new byte[4];
  167. do
  168. {
  169. stream.Read(buffer, 0, 4);
  170. if (BitConverter.IsLittleEndian) Array.Reverse(buffer);
  171. uint length = BitConverter.ToUInt32(buffer, 0);
  172. stream.Read(buffer, 0, 4);
  173. stream.Seek(length + 4L, SeekOrigin.Current);
  174. } while (!BytesEqual(buffer, pngEnd));
  175. return true;
  176. }
  177. public static void WriteToFile(string name, System.Collections.Generic.IEnumerable<string> list)
  178. {
  179. if (Path.GetExtension(name) != ".txt") name += ".txt";
  180. File.WriteAllLines(Path.Combine(Constants.configPath, name), list.ToArray());
  181. }
  182. }
  183. public class MousePosition : MonoBehaviour
  184. {
  185. private Vector3 mousePosition;
  186. public Vector3 Position => mousePosition;
  187. private void Awake()
  188. {
  189. DontDestroyOnLoad(this);
  190. mousePosition = Input.mousePosition;
  191. }
  192. private void Update()
  193. {
  194. if (Input.GetMouseButton(0))
  195. {
  196. mousePosition.x += Input.GetAxis("Mouse X") * 20;
  197. mousePosition.y += Input.GetAxis("Mouse Y") * 20;
  198. }
  199. else mousePosition = Input.mousePosition;
  200. }
  201. }
  202. public static class BinaryExtensions
  203. {
  204. public static string ReadNullableString(this BinaryReader binaryReader)
  205. {
  206. return binaryReader.ReadBoolean() ? binaryReader.ReadString() : null;
  207. }
  208. public static void WriteNullableString(this BinaryWriter binaryWriter, string str)
  209. {
  210. binaryWriter.Write(str != null);
  211. if (str != null) binaryWriter.Write(str);
  212. }
  213. public static void WriteVector3(this BinaryWriter binaryWriter, Vector3 vector3)
  214. {
  215. binaryWriter.Write(vector3.x);
  216. binaryWriter.Write(vector3.y);
  217. binaryWriter.Write(vector3.z);
  218. }
  219. public static Vector3 ReadVector3(this BinaryReader binaryReader)
  220. {
  221. return new Vector3(
  222. binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()
  223. );
  224. }
  225. public static void WriteQuaternion(this BinaryWriter binaryWriter, Quaternion quaternion)
  226. {
  227. binaryWriter.Write(quaternion.x);
  228. binaryWriter.Write(quaternion.y);
  229. binaryWriter.Write(quaternion.z);
  230. binaryWriter.Write(quaternion.w);
  231. }
  232. public static Quaternion ReadQuaternion(this BinaryReader binaryReader)
  233. {
  234. return new Quaternion
  235. (
  236. binaryReader.ReadSingle(), binaryReader.ReadSingle(),
  237. binaryReader.ReadSingle(), binaryReader.ReadSingle()
  238. );
  239. }
  240. public static void WriteColour(this BinaryWriter binaryWriter, Color colour)
  241. {
  242. binaryWriter.Write(colour.r);
  243. binaryWriter.Write(colour.g);
  244. binaryWriter.Write(colour.b);
  245. binaryWriter.Write(colour.a);
  246. }
  247. public static Color ReadColour(this BinaryReader binaryReader)
  248. {
  249. return new Color
  250. (
  251. binaryReader.ReadSingle(), binaryReader.ReadSingle(),
  252. binaryReader.ReadSingle(), binaryReader.ReadSingle()
  253. );
  254. }
  255. }
  256. }