Utility.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text.RegularExpressions;
  4. using System.IO;
  5. using System.Reflection;
  6. using UnityEngine;
  7. using System.Linq;
  8. using Ionic.Zlib;
  9. namespace COM3D2.MeidoPhotoStudio.Plugin
  10. {
  11. public static class Utility
  12. {
  13. private const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
  14. | BindingFlags.Static;
  15. internal static readonly byte[] pngHeader = { 137, 80, 78, 71, 13, 10, 26, 10 };
  16. internal static readonly byte[] pngEnd = System.Text.Encoding.ASCII.GetBytes("IEND");
  17. internal static readonly Regex guidRegEx = new Regex(
  18. @"^[a-f0-9]{8}(\-[a-f0-9]{4}){3}\-[a-f0-9]{12}$", RegexOptions.IgnoreCase
  19. );
  20. internal static readonly GameObject mousePositionGo;
  21. internal static readonly MousePosition mousePosition;
  22. public static readonly BepInEx.Logging.ManualLogSource Logger
  23. = BepInEx.Logging.Logger.CreateLogSource(MeidoPhotoStudio.pluginName);
  24. public enum ModKey
  25. {
  26. Control, Shift, Alt
  27. }
  28. public static string Timestamp => $"{DateTime.Now:yyyyMMddHHmmss}";
  29. public static Vector3 MousePosition => mousePosition.Position;
  30. static Utility()
  31. {
  32. mousePositionGo = new GameObject();
  33. mousePosition = mousePositionGo.AddComponent<MousePosition>();
  34. }
  35. public static void LogInfo(object data) => Logger.LogInfo(data);
  36. public static void LogMessage(object data) => Logger.LogMessage(data);
  37. public static void LogWarning(object data) => Logger.LogWarning(data);
  38. public static void LogError(object data) => Logger.LogError(data);
  39. public static void LogDebug(object data) => Logger.LogDebug(data);
  40. public static int Wrap(int value, int min, int max)
  41. {
  42. max--;
  43. return value < min ? max : value > max ? min : value;
  44. }
  45. public static int GetPix(int num) => (int)((1f + (((Screen.width / 1280f) - 1f) * 0.6f)) * num);
  46. public static float Bound(float value, float left, float right)
  47. {
  48. return left > (double)right ? Mathf.Clamp(value, right, left) : Mathf.Clamp(value, left, right);
  49. }
  50. public static int Bound(int value, int left, int right)
  51. {
  52. return left > right ? Mathf.Clamp(value, right, left) : Mathf.Clamp(value, left, right);
  53. }
  54. public static Texture2D MakeTex(int width, int height, Color color)
  55. {
  56. Color[] colors = new Color[width * height];
  57. for (int i = 0; i < colors.Length; i++)
  58. {
  59. colors[i] = color;
  60. }
  61. Texture2D texture2D = new Texture2D(width, height);
  62. texture2D.SetPixels(colors);
  63. texture2D.Apply();
  64. return texture2D;
  65. }
  66. public static FieldInfo GetFieldInfo<T>(string field) => typeof(T).GetField(field, bindingFlags);
  67. public static TValue GetFieldValue<TType, TValue>(TType instance, string field)
  68. {
  69. FieldInfo fieldInfo = GetFieldInfo<TType>(field);
  70. if (fieldInfo == null || (!fieldInfo.IsStatic && instance == null)) return default;
  71. return (TValue)fieldInfo.GetValue(instance);
  72. }
  73. public static void SetFieldValue<TType, TValue>(TType instance, string name, TValue value)
  74. {
  75. GetFieldInfo<TType>(name).SetValue(instance, value);
  76. }
  77. public static PropertyInfo GetPropertyInfo<T>(string field) => typeof(T).GetProperty(field, bindingFlags);
  78. public static TValue GetPropertyValue<TType, TValue>(TType instance, string property)
  79. {
  80. var propertyInfo = GetPropertyInfo<TType>(property);
  81. return propertyInfo == null ? default : (TValue) propertyInfo.GetValue(instance, null);
  82. }
  83. public static void SetPropertyValue<TType, TValue>(TType instance, string name, TValue value)
  84. => GetPropertyInfo<TType>(name).SetValue(instance, value, null);
  85. public static bool AnyMouseDown()
  86. {
  87. return Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1) || Input.GetMouseButtonDown(2);
  88. }
  89. public static string ScreenshotFilename()
  90. {
  91. string screenShotDir = Path.Combine(
  92. GameMain.Instance.SerializeStorageManager.StoreDirectoryPath, "ScreenShot"
  93. );
  94. if (!Directory.Exists(screenShotDir)) Directory.CreateDirectory(screenShotDir);
  95. return Path.Combine(screenShotDir, $"img{Timestamp}.png");
  96. }
  97. public static string TempScreenshotFilename()
  98. {
  99. return Path.Combine(Path.GetTempPath(), $"cm3d2_{Guid.NewGuid()}.png");
  100. }
  101. public static void ShowMouseExposition(string text, float time = 2f)
  102. {
  103. MouseExposition mouseExposition = MouseExposition.GetObject();
  104. mouseExposition.SetText(text, time);
  105. }
  106. public static bool IsGuidString(string guid)
  107. {
  108. if (string.IsNullOrEmpty(guid) || guid.Length != 36) return false;
  109. return guidRegEx.IsMatch(guid);
  110. }
  111. public static string HandItemToOdogu(string menu)
  112. {
  113. menu = menu.Substring(menu.IndexOf('_') + 1);
  114. menu = menu.Substring(0, menu.IndexOf("_i_.menu"));
  115. menu = $"odogu_{menu}";
  116. return menu;
  117. }
  118. public static void FixGameObjectScale(GameObject go)
  119. {
  120. Vector3 scale = go.transform.localScale;
  121. float largest = Mathf.Max(scale.x, Mathf.Max(scale.y, scale.z));
  122. go.transform.localScale = Vector3.one * (float)Math.Round(largest, 3);
  123. }
  124. public static string SanitizePathPortion(string path)
  125. {
  126. char[] invalid = Path.GetInvalidFileNameChars();
  127. path = path.Trim();
  128. path = string.Join("_", path.Split(invalid)).Replace(".", "").Trim('_');
  129. return path;
  130. }
  131. public static string GP01FbFaceHash(TMorph face, string hash)
  132. {
  133. if ((face.bodyskin.PartsVersion >= 120) && (hash != "eyeclose3") && hash.StartsWith("eyeclose"))
  134. {
  135. if (hash == "eyeclose") hash += '1';
  136. hash += TMorph.crcFaceTypesStr[(int)face.GetFaceTypeGP01FB()];
  137. }
  138. return hash;
  139. }
  140. public static void ResizeToFit(Texture2D texture, int maxWidth, int maxHeight)
  141. {
  142. int width = texture.width;
  143. int height = texture.height;
  144. if (width != maxWidth || height != maxHeight)
  145. {
  146. float scale = Mathf.Min(maxWidth / (float)width, maxHeight / (float)height);
  147. width = Mathf.RoundToInt(width * scale);
  148. height = Mathf.RoundToInt(height * scale);
  149. TextureScale.Bilinear(texture, width, height);
  150. }
  151. }
  152. public static bool BytesEqual(byte[] buffer, byte[] other)
  153. {
  154. if (buffer.Length != other.Length) return false;
  155. for (int i = 0; i < buffer.Length; i++)
  156. {
  157. if (buffer[i] != other[i]) return false;
  158. }
  159. return true;
  160. }
  161. public static bool IsPngFile(Stream stream)
  162. {
  163. byte[] buffer = new byte[8];
  164. stream.Read(buffer, 0, 8);
  165. return BytesEqual(buffer, pngHeader);
  166. }
  167. public static bool SeekPngEnd(Stream stream)
  168. {
  169. byte[] buffer = new byte[8];
  170. stream.Read(buffer, 0, 8);
  171. if (!BytesEqual(buffer, pngHeader)) return false;
  172. buffer = new byte[4];
  173. do
  174. {
  175. stream.Read(buffer, 0, 4);
  176. if (BitConverter.IsLittleEndian) Array.Reverse(buffer);
  177. uint length = BitConverter.ToUInt32(buffer, 0);
  178. stream.Read(buffer, 0, 4);
  179. stream.Seek(length + 4L, SeekOrigin.Current);
  180. } while (!BytesEqual(buffer, pngEnd));
  181. return true;
  182. }
  183. public static void WriteToFile(string name, System.Collections.Generic.IEnumerable<string> list)
  184. {
  185. if (Path.GetExtension(name) != ".txt") name += ".txt";
  186. File.WriteAllLines(Path.Combine(Constants.configPath, name), list.ToArray());
  187. }
  188. public static void WriteToFile(string name, byte[] data)
  189. {
  190. File.WriteAllBytes(Path.Combine(Constants.configPath, name), data);
  191. }
  192. }
  193. public class MousePosition : MonoBehaviour
  194. {
  195. private Vector3 mousePosition;
  196. public Vector3 Position => mousePosition;
  197. private void Awake()
  198. {
  199. DontDestroyOnLoad(this);
  200. mousePosition = Input.mousePosition;
  201. }
  202. private void Update()
  203. {
  204. if (Input.GetMouseButton(0))
  205. {
  206. mousePosition.x += Input.GetAxis("Mouse X") * 20;
  207. mousePosition.y += Input.GetAxis("Mouse Y") * 20;
  208. }
  209. else mousePosition = Input.mousePosition;
  210. }
  211. }
  212. public static class KeyValuePairExtensions
  213. {
  214. public static void Deconstruct<TKey, TValue>(
  215. this KeyValuePair<TKey, TValue> kvp, out TKey key, out TValue value
  216. )
  217. {
  218. key = kvp.Key;
  219. value = kvp.Value;
  220. }
  221. }
  222. public static class StreamExtensions
  223. {
  224. public static void CopyTo(this Stream stream, Stream outStream)
  225. {
  226. var buf = new byte[1024 * 32];
  227. int length;
  228. while ((length = stream.Read(buf, 0, buf.Length)) > 0)
  229. outStream.Write(buf, 0, length);
  230. }
  231. public static MemoryStream Decompress(this MemoryStream stream)
  232. {
  233. var dataMemoryStream = new MemoryStream();
  234. using var compressionStream = new DeflateStream(stream, CompressionMode.Decompress, true);
  235. compressionStream.CopyTo(dataMemoryStream);
  236. compressionStream.Flush();
  237. dataMemoryStream.Position = 0L;
  238. return dataMemoryStream;
  239. }
  240. public static DeflateStream GetCompressionStream(this MemoryStream stream)
  241. => new(stream, CompressionMode.Compress);
  242. }
  243. public static class CameraUtility
  244. {
  245. public static CameraMain MainCamera => GameMain.Instance.MainCamera;
  246. public static UltimateOrbitCamera UOCamera { get; } =
  247. GameMain.Instance.MainCamera.GetComponent<UltimateOrbitCamera>();
  248. public static void StopSpin()
  249. {
  250. Utility.SetFieldValue(UOCamera, "xVelocity", 0f);
  251. Utility.SetFieldValue(UOCamera, "yVelocity", 0f);
  252. }
  253. public static void StopMovement() => MainCamera.SetTargetPos(MainCamera.GetTargetPos());
  254. public static void StopAll()
  255. {
  256. StopSpin();
  257. StopMovement();
  258. }
  259. public static void ForceCalcNearClip(this CameraMain camera)
  260. {
  261. camera.StopAllCoroutines();
  262. camera.m_bCalcNearClip = false;
  263. camera.camera.nearClipPlane = 0.01f;
  264. }
  265. public static void ResetCalcNearClip(this CameraMain camera)
  266. {
  267. if (camera.m_bCalcNearClip) return;
  268. camera.StopAllCoroutines();
  269. camera.m_bCalcNearClip = true;
  270. camera.Start();
  271. }
  272. }
  273. public static class BinaryExtensions
  274. {
  275. public static string ReadNullableString(this BinaryReader binaryReader)
  276. {
  277. return binaryReader.ReadBoolean() ? binaryReader.ReadString() : null;
  278. }
  279. public static void WriteNullableString(this BinaryWriter binaryWriter, string str)
  280. {
  281. binaryWriter.Write(str != null);
  282. if (str != null) binaryWriter.Write(str);
  283. }
  284. public static void Write(this BinaryWriter binaryWriter, Vector3 vector3)
  285. {
  286. binaryWriter.Write(vector3.x);
  287. binaryWriter.Write(vector3.y);
  288. binaryWriter.Write(vector3.z);
  289. }
  290. public static void WriteVector3(this BinaryWriter binaryWriter, Vector3 vector3)
  291. {
  292. binaryWriter.Write(vector3.x);
  293. binaryWriter.Write(vector3.y);
  294. binaryWriter.Write(vector3.z);
  295. }
  296. public static Vector2 ReadVector2(this BinaryReader binaryReader)
  297. {
  298. return new Vector2(binaryReader.ReadSingle(), binaryReader.ReadSingle());
  299. }
  300. public static Vector3 ReadVector3(this BinaryReader binaryReader)
  301. {
  302. return new Vector3(
  303. binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()
  304. );
  305. }
  306. public static Vector4 ReadVector4(this BinaryReader binaryReader)
  307. {
  308. return new Vector4(
  309. binaryReader.ReadSingle(), binaryReader.ReadSingle(),
  310. binaryReader.ReadSingle(), binaryReader.ReadSingle()
  311. );
  312. }
  313. public static void Write(this BinaryWriter binaryWriter, Quaternion quaternion)
  314. {
  315. binaryWriter.Write(quaternion.x);
  316. binaryWriter.Write(quaternion.y);
  317. binaryWriter.Write(quaternion.z);
  318. binaryWriter.Write(quaternion.w);
  319. }
  320. public static void WriteQuaternion(this BinaryWriter binaryWriter, Quaternion quaternion)
  321. {
  322. binaryWriter.Write(quaternion.x);
  323. binaryWriter.Write(quaternion.y);
  324. binaryWriter.Write(quaternion.z);
  325. binaryWriter.Write(quaternion.w);
  326. }
  327. public static Quaternion ReadQuaternion(this BinaryReader binaryReader)
  328. {
  329. return new Quaternion
  330. (
  331. binaryReader.ReadSingle(), binaryReader.ReadSingle(),
  332. binaryReader.ReadSingle(), binaryReader.ReadSingle()
  333. );
  334. }
  335. public static void Write(this BinaryWriter binaryWriter, Color colour)
  336. {
  337. binaryWriter.Write(colour.r);
  338. binaryWriter.Write(colour.g);
  339. binaryWriter.Write(colour.b);
  340. binaryWriter.Write(colour.a);
  341. }
  342. public static void WriteColour(this BinaryWriter binaryWriter, Color colour)
  343. {
  344. binaryWriter.Write(colour.r);
  345. binaryWriter.Write(colour.g);
  346. binaryWriter.Write(colour.b);
  347. binaryWriter.Write(colour.a);
  348. }
  349. public static Color ReadColour(this BinaryReader binaryReader)
  350. {
  351. return new Color
  352. (
  353. binaryReader.ReadSingle(), binaryReader.ReadSingle(),
  354. binaryReader.ReadSingle(), binaryReader.ReadSingle()
  355. );
  356. }
  357. public static Matrix4x4 ReadMatrix4x4(this BinaryReader binaryReader)
  358. {
  359. Matrix4x4 matrix = default;
  360. for (var i = 0; i < 16; i++) matrix[i] = binaryReader.ReadSingle();
  361. return matrix;
  362. }
  363. }
  364. }