diff --git a/.gitignore b/.gitignore index 951558a..05b90d5 100644 --- a/.gitignore +++ b/.gitignore @@ -29,4 +29,3 @@ UserSettings/Layouts/*.dwlt Assets/StreamingAssets.meta **/.DS_Store -/Assets/SGModule diff --git a/Assets/SGModule/ApplePay.meta b/Assets/SGModule/ApplePay.meta new file mode 100644 index 0000000..824f21c --- /dev/null +++ b/Assets/SGModule/ApplePay.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6eb32bc6ddeb6a54281dd51759c715a6 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ApplePay/README.md b/Assets/SGModule/ApplePay/README.md new file mode 100644 index 0000000..46e9e3b --- /dev/null +++ b/Assets/SGModule/ApplePay/README.md @@ -0,0 +1,3 @@ +# ApplePay + +2025 年 05 月 24 日 V1.0.0 提交初始版本 applepay 模块,该模块功能依赖通用模块,网络模块和数据模块,请一起拉取 diff --git a/Assets/SGModule/ApplePay/README.md.meta b/Assets/SGModule/ApplePay/README.md.meta new file mode 100644 index 0000000..173e892 --- /dev/null +++ b/Assets/SGModule/ApplePay/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f92f9691c788c414a82e03722722293e +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ApplePay/SGModule.meta b/Assets/SGModule/ApplePay/SGModule.meta new file mode 100644 index 0000000..c1ff908 --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 10ce64fc727c4edeb97e73ad29ef5eab +timeCreated: 1747906541 \ No newline at end of file diff --git a/Assets/SGModule/ApplePay/SGModule/Model.meta b/Assets/SGModule/ApplePay/SGModule/Model.meta new file mode 100644 index 0000000..23b0fbf --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Model.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f2da583c874f4b13acc3eb54eaf5a428 +timeCreated: 1747996053 \ No newline at end of file diff --git a/Assets/SGModule/ApplePay/SGModule/Model/ApplePayModel.cs b/Assets/SGModule/ApplePay/SGModule/Model/ApplePayModel.cs new file mode 100644 index 0000000..67722f5 --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Model/ApplePayModel.cs @@ -0,0 +1,43 @@ +using Newtonsoft.Json; + +namespace SGModule.ApplePay +{ + public class ApplePayData + { + [JsonProperty("innerOrderId")] + public string innerOrderId; + [JsonProperty("amount")] + public int amount; + [JsonProperty("sku")] + public string sku; + [JsonProperty("currency")] + public string currency = "USD"; + [JsonProperty("shopName")] + public string shopName; + [JsonProperty("type")] + public string type; + + } + + public class AppleCheckData + { + [JsonProperty("signedPayload")] + public string signedPayload; + [JsonProperty("innerOrderId")] + public string innerOrderId; + } + + public class AppleSubscribeData + { + [JsonProperty("signedPayload")] + public string signedPayload; + [JsonProperty("sku")] + public string sku; + [JsonProperty("currency")] + public string currency; + [JsonProperty("amount")] + public int amount; + [JsonProperty("expires_time")] + public long expires_time; + } +} \ No newline at end of file diff --git a/Assets/SGModule/ApplePay/SGModule/Model/ApplePayModel.cs.meta b/Assets/SGModule/ApplePay/SGModule/Model/ApplePayModel.cs.meta new file mode 100644 index 0000000..9735972 --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Model/ApplePayModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9dcbc72e1537449aaea5b71d67e7bf85 +timeCreated: 1747996070 \ No newline at end of file diff --git a/Assets/SGModule/ApplePay/SGModule/Scripts.meta b/Assets/SGModule/ApplePay/SGModule/Scripts.meta new file mode 100644 index 0000000..f90f3ee --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Scripts.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 69666ded8fdc4244a0d43d25f7831bca +timeCreated: 1747906570 \ No newline at end of file diff --git a/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayBackType.cs b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayBackType.cs new file mode 100644 index 0000000..96803fb --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayBackType.cs @@ -0,0 +1,18 @@ +namespace SGModule.ApplePay +{ + public enum ApplePayBackType + { + /// + ///创建支付订单 + /// + Create, + /// + ///验证支付订单 + /// + Check, + /// + ///取消支付订单 + /// + Cancel, + } +} \ No newline at end of file diff --git a/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayBackType.cs.meta b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayBackType.cs.meta new file mode 100644 index 0000000..9a439fa --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayBackType.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e83ae38d5d0e4880836c55d708e7083c +timeCreated: 1747995062 \ No newline at end of file diff --git a/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayManager.cs b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayManager.cs new file mode 100644 index 0000000..d546d2b --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayManager.cs @@ -0,0 +1,661 @@ +using SGModule.Common.Base; +using System; +using System.Collections.Generic; +using SGModule.Common.Helper; +using SGModule.NetKit; +using Newtonsoft.Json; + + +#if UNITY_IOS && UNITY_IAP +using System.Collections; +using System.Linq; +using DG.Tweening; +using SGModule.Common.Extensions; +using Newtonsoft.Json; +using SGModule.Net; +using UnityEngine; +using UnityEngine.Purchasing; +using UnityEngine.Purchasing.Extension; + +namespace SGModule.ApplePay +{ + public class ApplePayManager : SingletonMonoBehaviour, IDetailedStoreListener + { + private IStoreController _storeController; + private static IExtensionProvider _extensionProvider; + private static IAppleExtensions _appleExtension; + + private Action _failedCallback; + + private Action _successCallback; + + private Dictionary _products = new Dictionary(); + + private ApplePayData _payData; + + private string _packageName; + + private float _lastPayAttemptTime; + + + public void SendDebugToServer(string error, string stackTrace) { + + // ErrorLogKit.Send("debug", error, stackTrace,SuperApplication.Instance.attribution); + } + + private Dictionary _productConfigs = new Dictionary(); + + /// + /// 通过 ProductConfig 数组初始化商品 + /// + public void InitProduct(List configs, string packageName, Action successCallback) + { + var module = StandardPurchasingModule.Instance(); + ConfigurationBuilder builder = ConfigurationBuilder.Instance(module); + + _successCallback = successCallback; + _packageName = packageName; + SendDebugToServer("[Apple pay] InitProduct 开始------", Environment.StackTrace); + try + { + foreach (var config in configs) + { + // Debug.Log( $"[Apple pay] InitProduct ------{config.sku} , {config.type} "); + if (Enum.TryParse(config.type, true, out var productType)) + { + _productConfigs.Add(config.sku, config); + + builder.AddProduct(config.sku, productType); + } + else + { + SendDebugToServer($"无法解析 ProductType: {config.type}", Environment.StackTrace); + Debug.LogError($"无法解析 ProductType: {config.type}"); + // 可根据需要处理默认类型或跳过该商品 + } + } + + SendDebugToServer("[Apple pay] InitProduct 结束------", Environment.StackTrace); + UnityPurchasing.Initialize(this, builder); + } + catch (Exception e) + { + SendDebugToServer($" 初始化商品 失败 InitProduct: {e.Message}", Environment.StackTrace); + + Console.WriteLine(e); + throw; + } + + Debug.Log( $"[Apple pay] InitProduct -----2 "); + + } + + + private void SetPayData(string sku) + { + var payData = GetPayData(sku); + _payData = payData; + + } + + private ApplePayData GetPayData(string sku) + { + if (_productConfigs.TryGetValue(sku, out var data)) + { + Debug.Log( $"[Apple pay] InitProduct ------{data.sku} , {data.type} "); + return new ApplePayData + { + sku = sku, + currency = "USD", + amount = (int)Math.Round(data.price * 100), + }; + } + Debug.LogError($" set _payData error------_payData is null "); + return null; + } + + private Coroutine _payDataCheckCoroutine; + + /// + /// 启动_payData超时检测协程 + /// + private void StartPayDataTimeoutCheck() + { + if (_payDataCheckCoroutine != null) + { + StopCoroutine(_payDataCheckCoroutine); + } + _payDataCheckCoroutine = StartCoroutine(PayDataTimeoutCheck()); + } + + /// + /// 检测_payData是否超时的协程 + /// + private IEnumerator PayDataTimeoutCheck() + { + float startTime = Time.time; + float timeout = 60f; // 1分钟超时 + + while (Time.time - startTime < timeout) + { + // 如果_payData已经为null,停止检测 + if (_payData == null) + { + yield break; + } + yield return null; + } + + // 1分钟后检查,如果_payData仍然不为null,则设为null + if (_payData != null) + { + _payData = null; + Debug.Log("[Apple Pay] _payData超时,已自动设为null"); + } + } + + /// + /// 购买接口 + /// + /// 购买需要的字段存放 + /// 成功回调(ApplePayBackType为订单返回的类型:具体看 ApplePayBackType 枚举),作用:用来打点 + /// 失败回调 (string为失败原因) + public void Purchase(string sku, Action successCallback, Action failedCallback) + { + Debug.Log( $"[Apple Pay] Purchase: {JsonConvert.SerializeObject(_payData)}"); + + SendDebugToServer("[Apple pay] 购买 Purchase ------", Environment.StackTrace); + + if (Time.time - _lastPayAttemptTime < 5) + { + failedCallback?.Invoke("Clicks are too frequent"); + return; + } + + _lastPayAttemptTime = Time.time; + Debug.Log( $"[Apple Pay] Purchase-00---------{JsonConvert.SerializeObject(_payData)}"); + if (_payData != null) + { + // 启动超时检测 + StartPayDataTimeoutCheck(); + return; + } + + Debug.Log( $"[Apple Pay] Purchase-1---------"); + + if (!IsInitialized()) + { + failedCallback?.Invoke("Not Initialized"); + return; + } + + Debug.Log( $"[Apple Pay] Purchase-2---------"); + + var product = _storeController.products.WithID(sku); + if (product == null || !product.availableToPurchase) + { + failedCallback?.Invoke("Either is not found or is not available for purchase"); + return; + } + + _successCallback = successCallback; + _failedCallback = failedCallback; + + SetPayData(sku); + + _storeController.InitiatePurchase(product); + + Debug.Log( $"[Apple Pay] Purchase-3---------"); + + if (_payData != null) + { + var payData = new ApplePayData + { + sku = sku, + currency = "USD", + amount = _payData.amount, + }; + + ApplePayNet.ApplePayCreate(payData, (response) => + { + Debug.Log( $"[Apple Pay] Purchase-4---------"); + + if (response.IsSuccess) + { + _successCallback?.Invoke(ApplePayBackType.Create, null); + } + + if (_payData != null) _payData.innerOrderId = response.Data.innerOrderId; + SendDebugToServer($"[Apple Pay] Purchase-5-------创建内部ID innerOrderId--{_payData.innerOrderId}", Environment.StackTrace); + + Debug.Log( $"[Apple Pay] Purchase-5-------innerOrderId--{_payData.innerOrderId}"); + }); + } + } + + /// + /// IOS恢复内购 + /// 会在删除应用后,第一次安装是自动恢复 + /// + /// 恢复回调 + public void AppleRestore(Action restoreCallback) + { + if (!IsInitialized()) + { + Debug.LogWarning("[ApplePay] IAppleExtensions 未初始化"); + return; + } + + Debug.Log( "[ApplePay] 用户手动恢复购买"); + _appleExtension.RestoreTransactions((success, error) => + { + if (success) + { + Debug.Log( "[Apple Pay] Restore Transactions 成功"); + // 这里会触发 ProcessPurchase 回调 + restoreCallback(true, error); + } + else + { + Debug.LogError($"[Apple Pay] Restore Transactions 失败: {error}"); + // 可以提示用户重试 + } + }); + } + + #region 购买成功回调 + + public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent) + { + + SendDebugToServer($"[Apple pay] 购买成功回调 Purchase ---{JsonConvert.SerializeObject(purchaseEvent.purchasedProduct)}---", Environment.StackTrace); + + var product = purchaseEvent.purchasedProduct; + var productType = product.definition.type; + var sku = product.definition.id; + var receipt = product.receipt; + + + Debug.Log( + $" ProcessPurchase 1 Purchase: {JsonConvert.SerializeObject(purchaseEvent.purchasedProduct)}"); + + if (purchaseEvent is not { purchasedProduct: not null }) + { + Debug.LogError("[Apple Pay] ProcessPurchase 2 : purchaseEvent 或 purchasedProduct 为 null"); + return PurchaseProcessingResult.Complete; + } + + Debug.Log( $"购买商品类型: {productType}, SKU: {sku}"); + if (productType == ProductType.Subscription) + { + SendDebugToServer($"[Apple pay] 购买商品类型 Purchase ---{productType}-{sku}--", Environment.StackTrace); + + // 服务器验证 + UploadReceiptForValidation(sku, product.transactionID, isSuccess => + { + if (isSuccess) + { + // 验证成功后的逻辑 + // 验证成功,完成购买 + _storeController.ConfirmPendingPurchase(product); + } + }); + + return PurchaseProcessingResult.Pending; + } + + if (productType == ProductType.NonConsumable) + { + Debug.Log( + $" 识别到非消耗性商品 ----{DataMgr.ApplePayTransactionID.Value.Contains(product.transactionID)}"); + if (DataMgr.ApplePayTransactionID.Value.Contains(product.transactionID)) + { + return PurchaseProcessingResult.Complete; + } + + DataMgr.ApplePayTransactionID.Value.Add(product.transactionID); + } + + // 普通商品直接处理 + HandlePurchaseSuccess(product.transactionID, isSuccess => + { + if (isSuccess) + { + // 验证成功,完成购买 + _storeController.ConfirmPendingPurchase(product); + } + }); + + return PurchaseProcessingResult.Pending; + } + + /// + /// 支付测试代码 + /// + /// + /// + /// + public void ApplePayTest(ProductType type, string sku, string transactionID, Action successCallback) + { + + SetPayData(sku); + Debug.Log( $"[ApplePay] 测试支付 type: {type}, sku: {sku}, transactionID: {transactionID}" ); + + _successCallback = successCallback; + + if (type == ProductType.Subscription) + { + // 服务器验证 + UploadReceiptForValidation(sku, transactionID, isSuccess => + { + if (isSuccess) + { + Debug.Log( "订阅商品验证成功"); + } + }); + + return; + } + + if (type == ProductType.NonConsumable) + { + Debug.Log( + $" 识别到非消耗性商品 ----{DataMgr.ApplePayTransactionID.Value.Contains(transactionID)}"); + if (DataMgr.ApplePayTransactionID.Value.Contains(transactionID)) + { + return; + } + + DataMgr.ApplePayTransactionID.Value.Add(transactionID); + } + + // 普通商品直接处理 + HandlePurchaseSuccess(transactionID, isSuccess => + { + if (isSuccess) + { + Debug.Log( "普通商品验证成功"); + } + },true); + } + + //服务器验证 + private void UploadReceiptForValidation(string sku, string transactionID, Action onValidationComplete) + { + Debug.Log( "识别到订阅商品,准备进行订阅验证"); + SendDebugToServer($"[Apple pay] 识别到订阅商品,准备进行订阅验证", Environment.StackTrace); + + var productConfig = GetPayData(sku); + if (productConfig != null) + { + Debug.Log( $"订阅商品ID: {sku} transactionID: {transactionID} _payData.amount: {productConfig.amount}"); + + SendDebugToServer($"订阅商品ID: {sku} transactionID: {transactionID} _payData.amount: {productConfig.amount}", Environment.StackTrace); + + ApplePayNet.AppleSubscribeCheck( + transactionID, + sku, + productConfig.amount, + _packageName, + response => + { + bool isSuccess = response.IsSuccess; + + // 在这里返回验证结果 + onValidationComplete?.Invoke(isSuccess); + _payData = null; + if (isSuccess) + { + Debug.Log( "订阅验证成功"); + SendDebugToServer($"订阅验证成功", Environment.StackTrace); + + _successCallback?.Invoke(ApplePayBackType.Check, new AppleResponseData() + { + expires_time = response.Data.expires_time, + sku = sku + }); + } + else + { + Debug.LogWarning("[Apple Pay] 订阅验证失败"); + } + }); + } + } + + /// + /// 支付成功后的本地处理(订阅和普通商品共用) + /// + private void HandlePurchaseSuccess(string transactionID, Action onValidationComplete, bool isTest = false) + { + var payDataJson = GetApplePayData(); + Debug.Log( $" HandlePurchaseSuccess payDataJson: {JsonConvert.SerializeObject(payDataJson)}"); + + var statusDictionary = JsonConvert.DeserializeObject>(payDataJson) + ?? new Dictionary(); + + SendDebugToServer($"普通商品 HandlePurchaseSuccess: {transactionID}", Environment.StackTrace); + + if (!statusDictionary.ContainsKey(transactionID)) + { + Debug.Log( $"记录新交易 transactionID: {transactionID}"); + Debug.Log( $"-----_payData: {JsonConvert.SerializeObject(_payData)}" ); + if (_payData == null || string.IsNullOrWhiteSpace(_payData.innerOrderId)) + { + Debug.LogWarning("[Apple Pay] _payData 为空或 innerOrderId 无效"); + return; + } + + statusDictionary.Add(transactionID, _payData); + SaveApplePayData(statusDictionary); + _payData = null; + } + + if (statusDictionary.TryGetValue(transactionID, out var cValue)) + { + if (!string.IsNullOrWhiteSpace(cValue.innerOrderId) || isTest) + { + ApplePaySuccess(transactionID, onValidationComplete); + } + } + } + + private void SaveApplePayData(Dictionary payData) + { + // 保存更新后的数据 + string json = JsonConvert.SerializeObject(payData); + PlayerPrefs.SetString("SGModule_apple_pay_data", json); + } + + private string GetApplePayData() + { + string json = PlayerPrefs.GetString("SGModule_apple_pay_data", ""); + // GetString if (json == "") + // { + // json = DataWrapper.ApplePayData; + // } + return json; + } + + private void ApplePaySuccess(string transactionID, Action onValidationComplete) + { + Debug.Log( "apple 支付 StartCoroutine------"); + StartCoroutine(ProcessPayData(transactionID, onValidationComplete)); + } + + private IEnumerator ProcessPayData(string orderId, Action onValidationComplete) + { + // 发起请求 + ApplePayRequest(orderId, onValidationComplete); + + yield return null; // 等待本次请求完成 + } + + private void ApplePayRequest(string transactionID, Action onValidationComplete) + { + var payDataJson = GetApplePayData(); + Debug.Log( $"ApplePayRequest 1 payDataJson: {JsonConvert.SerializeObject(payDataJson)}"); + SendDebugToServer($"验单 普通商品: {transactionID}", Environment.StackTrace); + + var statusDictionary = JsonConvert.DeserializeObject>(payDataJson); + + if (statusDictionary.ContainsKey(transactionID)) + { + Debug.Log( $"ApplePayRequest 2 transactionID: {transactionID}"); + + var data = statusDictionary[transactionID]; + + ApplePayNet.ApplePayCheck(transactionID, data.innerOrderId, _packageName, (response) => + { + Debug.Log( + $"ApplePayRequest 3 response.IsSuccess: {JsonConvert.SerializeObject(response)}"); + + onValidationComplete?.Invoke(response.IsSuccess); + + if (response.IsSuccess) + { + _successCallback(ApplePayBackType.Check, null); + + statusDictionary.Remove(transactionID); + // 保存更新后的数据 + SaveApplePayData(statusDictionary); + } + + if (!new List() { 1021, 1026, 1027, 1028 }.Contains(response.Code)) + { + } + else + { + statusDictionary.Remove(transactionID); + // 保存更新后的数据 + SaveApplePayData(statusDictionary); + } + }); + } + } + + #endregion + + #region 初始化 + + private bool IsInitialized() + { + Debug.Log( "[barry] check IsInitialized======:"); + return _storeController != null && _extensionProvider != null; + } + + public void OnInitialized(IStoreController controller, IExtensionProvider extensions) + { + _storeController = controller; + _extensionProvider = extensions; + _appleExtension = extensions.GetExtension(); + } + + public void OnInitializeFailed(InitializationFailureReason error) + { + Debug.Log( "[barry] OnInitializeFailed1 Reason:" + error); + // throw new NotImplementedException(); + } + + public void OnInitializeFailed(InitializationFailureReason error, string message) + { + Debug.Log( "[barry] OnInitializeFailed2 Reason:" + error); + Debug.Log( "[barry] OnInitializeFailed2 message:" + message); + // throw new NotImplementedException(); + } + + #endregion + + #region 购买失败回调 + + public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason) + { + Debug.Log( " OnPurchaseFailed===1==:"); + HandleOnPurchaseFail(failureReason); + } + + + public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription) + { + Debug.Log( "OnPurchaseFailed===2==:"); + HandleOnPurchaseFail(failureDescription.reason); + } + + private void HandleOnPurchaseFail(PurchaseFailureReason failureReason) + { + Debug.Log( $" HandleOnPurchaseFail 1 "); + + if (_payData == null) return; + + Debug.Log( $" HandleOnPurchaseFail 2 "); + + ApplePayNet.ApplePayCancel(_payData, (response) => + { + string msg = ToFriendlyString(failureReason); + Debug.Log( "[barry] HandleOnPurchaseFail:" + response.IsSuccess + " reason: " + msg); + _failedCallback?.Invoke(msg); + _payData = null; + + _successCallback?.Invoke(ApplePayBackType.Cancel,null); + }); + } + + private static string ToFriendlyString(PurchaseFailureReason reason) + { + Debug.Log( $"ToFriendlyString 1 reason==={reason}"); + + return reason switch + { + PurchaseFailureReason.ProductUnavailable => "商品不可用", + PurchaseFailureReason.PurchasingUnavailable => "购买功能不可用", + PurchaseFailureReason.ExistingPurchasePending => "已有未完成的购买", + PurchaseFailureReason.SignatureInvalid => "签名验证失败", + PurchaseFailureReason.UserCancelled => "用户取消", + PurchaseFailureReason.PaymentDeclined => "支付被拒绝", + PurchaseFailureReason.DuplicateTransaction => "重复的交易ID", + PurchaseFailureReason.Unknown => "未知错误", + _ => $"未识别的错误: {(int)reason}" + }; + } + + #endregion + } +} +#else +namespace SGModule.ApplePay { + public class ApplePayManager: SingletonMonoBehaviour{ + public void StartPay() { + } + + public string GetApplePayName(string key) + { + return ""; + } + + public void Purchase(ApplePayData payData, Action successCallback, + Action failedCallback) { + var msg = "Apple Pay: Purchase Failed, No plugin is installed."; + Log.Info("[Apple IOS]",msg); + failedCallback?.Invoke(msg); + } + + public void AppleRestore(Action restoreCallback) + { + + } + // public void InitProduct(Listconfigs, string packageName) + // { + + // } + + } +} + +#endif +public class AppleResponseData +{ + [JsonProperty("expires_time")] + public long expires_time; + [JsonProperty("sku")] + public string sku; +} diff --git a/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayManager.cs.meta b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayManager.cs.meta new file mode 100644 index 0000000..1d99d97 --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8478e5310ad64f23a3805cd8a3fa024f +timeCreated: 1747907338 \ No newline at end of file diff --git a/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayNet.cs b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayNet.cs new file mode 100644 index 0000000..902b7ed --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayNet.cs @@ -0,0 +1,95 @@ +using SGModule.Common.Helper; +using SGModule.Net; +using UnityEngine.Events; + +namespace SGModule.ApplePay +{ + public static class ApplePayNet + { + #region IOSPay + /// + /// ios支付创建订单 + /// + /// + /// + public static void ApplePayCreate(ApplePayData data, UnityAction> onCompleted = null) + { + NetKit.NetKit.Instance.Post("shop/applePayCreate", data, + response => { onCompleted?.Invoke(response); }); + } + + /// + /// ios支付取消订单 + /// + /// + /// + public static void ApplePayCancel(ApplePayData data, UnityAction> onCompleted = null) + { + NetKit.NetKit.Instance.Post("shop/applePayCancel", data, + response => { onCompleted?.Invoke(response); }); + } + public static void ApplePaySubscriptionHistory(UnityAction> onCompleted = null) + { + NetKit.NetKit.Instance.Post("shop/subscribeHistory", null, + response => { onCompleted?.Invoke(response); }); + } + // public static void ApplePaySubscriptionCheck(HistoryObject obj,UnityAction> onCompleted = null) + // { + // NetKit.NetKit.Instance.Post("shop/subscribeCheck", obj, + // response => { onCompleted?.Invoke(response); }); + // } + + + /// + /// ios支付验证订单 + /// + /// apple支付返回的订单id + /// 内部订单id,创建订单时返回的 + /// 包名 + /// 回调 + public static void ApplePayCheck(string transactionID, string innerOrderId, + string key, UnityAction> onCompleted = null) + { + var test = new AppleCheckData + { + signedPayload = Common.Helper.Cryptor.Encrypt(transactionID, key), + innerOrderId = innerOrderId + }; + + NetKit.NetKit.Instance.Post("shop/applePayCheck", test, + response => { onCompleted?.Invoke(response); }); + } + /// + /// ios支付订阅 + /// + /// apple支付返回的订单id + /// 商品id + /// 价格 + /// 包名 + /// 回调 + public static void AppleSubscribeCheck(string transactionID, string sku, int amount, + string key, UnityAction> onCompleted = null) + { + var test = new AppleSubscribeData + { + signedPayload = Common.Helper.Cryptor.Encrypt(transactionID, key), + sku = sku, + amount = amount, + currency = "USD" + }; + Log.Info("[Apple pay]", $" AppleSubscribeCheck 开始...{sku}"); + + NetKit.NetKit.Instance.Post( + "shop/appleSubscribe", + test, + response => + { + Log.Info("[Apple pay]", $"AppleSubscribeCheck 结束...{response.IsSuccess}"); + onCompleted?.Invoke(response); + }); + + } + + #endregion + } +} diff --git a/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayNet.cs.meta b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayNet.cs.meta new file mode 100644 index 0000000..c1467a0 --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Scripts/ApplePayNet.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 760f78942ee949a9af90bc8ac6710be7 +timeCreated: 1747996461 \ No newline at end of file diff --git a/Assets/SGModule/ApplePay/SGModule/Scripts/ProductConfig.cs b/Assets/SGModule/ApplePay/SGModule/Scripts/ProductConfig.cs new file mode 100644 index 0000000..1e959ec --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Scripts/ProductConfig.cs @@ -0,0 +1,22 @@ +#if UNITY_IOS && UNITY_IAP +using Newtonsoft.Json; +using UnityEngine; +using UnityEngine.Purchasing; + +namespace SGModule.ApplePay +{ + [System.Serializable] + public class ProductConfig + { + [JsonProperty("name")] + public string name; + [JsonProperty("sku")] + public string sku; + [JsonProperty("price")] + public float price; + [JsonProperty("type")] + public string type; + + } +} +#endif diff --git a/Assets/SGModule/ApplePay/SGModule/Scripts/ProductConfig.cs.meta b/Assets/SGModule/ApplePay/SGModule/Scripts/ProductConfig.cs.meta new file mode 100644 index 0000000..2fff9e6 --- /dev/null +++ b/Assets/SGModule/ApplePay/SGModule/Scripts/ProductConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bab80a35d16a48e6856d995e175b82d3 +timeCreated: 1747911023 \ No newline at end of file diff --git a/Assets/SGModule/Common.meta b/Assets/SGModule/Common.meta new file mode 100644 index 0000000..d46587c --- /dev/null +++ b/Assets/SGModule/Common.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0d7663ebef8b88644a509c798b452728 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/README.md b/Assets/SGModule/Common/README.md new file mode 100644 index 0000000..72cdafe --- /dev/null +++ b/Assets/SGModule/Common/README.md @@ -0,0 +1,138 @@ +# 🧱 Common 公共模块 + +------ + +## 📖 概述 + +Common 模块是项目中最基础、最核心的模块,包含通用工具类、配置文件、扩展方法及基础系统组件。**所有其他模块都应依赖此模块**,务必在拉取其他模块前先行安装。 + +------ + +## 📁 功能总览 + +- ✅ 项目配置管理 +- ✅ 单例模式基类(支持非Mono与Mono行为) +- ✅ 常用工具类(加解密、日志、时间、设备信息) +- ✅ 扩展方法(数组、字符串、枚举等) +- ✅ 编辑器工具(自动生成配置文件) +- ✅ GM工具相关支持 + +------ + +## ⚙️ 核心系统详解 + +### 🧩 配置文件系统(GameConfig, NetworkConfig) + +📌 通过菜单栏 `SwhiteGames > Create GameConfig` 可在 `Resources/` 目录下自动创建 `GameConfig` 文件,包含以下配置字段: + +| 字段名 | 含义说明 | +| ------------- | ----------------------------------------- | +| `PackageName` | 游戏包名 | +| `IsRelease` | 是否为正式发布包(关联宏 `GAME_RELEASE`) | +| `EnabledLog` | 是否启用日志打印 | + +📦 获取配置示例: + +```csharp +var enabledLog = ConfigManager.GameConfig?.enabledLog; +var packageName = ConfigManager.GameConfig?.packageName; +``` + +------ + + +📌 通过菜单栏 `SwhiteGames > Create NetworkConfig` 可在 `Resources/` 目录下自动创建 `NetworkConfig` 文件,包含以下配置字段: + +| 字段名 | 含义说明 | +| ------------- |----------| +| `showNetworkLog` | 是否启用日志打印 | +| `debugHost` | 测试环境Host | +| `releaseHost` | 正式环境Host | +| `connectionMode` | 连接模式 | + +📦 获取配置示例: + +```csharp +var connectionMode = ConfigManager.NetworkConfig?.connectionMode; +var showNetworkLog = ConfigManager.NetworkConfig?.showNetworkLog; +``` + +------ +### 🔁 单例系统 + +- **SingletonMonoBehaviour**:MonoBehaviour 单例,自动创建 GameObject,跨场景不销毁 + +```csharp +// MonoBehaviour +public class AudioManager : SingletonMonoBehaviour { ... } +``` + +------ + +### 🛠️ 工具类一览(Helper) + +| 类名 | 功能说明 | +| ----------------- | ------------------------------------------- | +| `Log` | ✅日志打印(开发调试利器) | +| `Cryptor` | 🔐 加密解密支持(对称加密) | +| `TimeHelper` | 🕒 时间戳转换与格式化处理 | +| `DeviceHelper` | 📱 获取设备唯一标识 | +| `RandomHelper` | 🎲 权重随机、随机打乱等 | +| `SerializeHelper` | 🔄 JSON 序列化 / 反序列化(可使用As()替换) | +| `MD5Helper` | 🔑 快速生成MD5签名 | +| `Base64Helper` | 🧬 Base64编解码 | + +------ + +### 📌 日志打印统一用法 + +统一使用 `Log` 工具类进行日志输出,支持彩色分级,正式环境中可自动关闭日志输出。 + +```csharp +using SGModule.Common.Helper; + +Log.Info("标签", "信息内容"); // ✅绿色输出 +Log.Warning("标签", "警告内容"); // ⚠️橙色输出 +Log.Error("标签", "错误内容"); // ❌红色输出 +``` + +------ + +### ✨ 扩展方法一览 + +- **EnumExtensions**:获取枚举描述 `GameState.Ready.GetDescription()` +- **StringExtensions**:空值检查 `str.IsNullOrWhiteSpace()` +- **ObjectExtensions**:类型安全转换 `"123".As()` +- **ListExtensions**:列表随机元素 `items.Random()` +- **ArrayExtensions**:数组相关操作 + +------ + +## 🧠 最佳实践 + +| 模块 | 建议做法 | +| ---------- | ------------------------------------------------------------ | +| 管理器类 | Mono 类继承 `SingletonMonoBehaviour` | +| 日志打印 | 全局使用 `Log` 统一管理,按模块分类 | +| 类型转换 | 使用 `.As()` 替代传统强转,异常更少 | +| 加密数据 | 所有敏感数据使用 `Cryptor` 加密后存储 | +| 时间处理 | 使用 `TimeHelper` 保证时区一致性 | +| 随机操作 | 使用 `RandomHelper` 替代 `UnityEngine.Random` | +| 数据键管理 | 通过 `KeyRegistry` 注册和使用,避免硬编码 | + +------ + +## ⚠️ 注意事项 + +- ❗ `SingletonMonoBehaviour` 不要手动放入场景,会自动创建 +- 🔐 加密密钥需妥善保管,避免泄露 +- 🌏 时间处理请注意本地时区与 UTC 的转换 +- 🎲 请勿使用 `UnityEngine.Random`,统一使用 `RandomHelper` + +------ + +## 💡 扩展建议 + +- 🧩 新增扩展方法时,请分类放入 `Extensions/` 并补充完整 XML 注释 +- 🧰 新增工具类保持静态类设计,考虑线程安全 +- 📖 键系统支持从配置文件中加载,并支持按模块分组管理 \ No newline at end of file diff --git a/Assets/SGModule/Common/README.md.meta b/Assets/SGModule/Common/README.md.meta new file mode 100644 index 0000000..206e491 --- /dev/null +++ b/Assets/SGModule/Common/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0a5954894fd434e4f8726239c65e8497 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule.meta b/Assets/SGModule/Common/SGModule.meta new file mode 100644 index 0000000..42c1d25 --- /dev/null +++ b/Assets/SGModule/Common/SGModule.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1255dc405c83ca54ba0fe153fde0fd3c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Editor.meta b/Assets/SGModule/Common/SGModule/Editor.meta new file mode 100644 index 0000000..6ae76ca --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c7910bd51ff93d347891de376c8c6d3c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Editor/GameConfigCreator.cs b/Assets/SGModule/Common/SGModule/Editor/GameConfigCreator.cs new file mode 100644 index 0000000..93f017e --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Editor/GameConfigCreator.cs @@ -0,0 +1,75 @@ +using System.IO; +using SGModule.Common.Helper; +using UnityEditor; +using UnityEngine; + +namespace SwhiteGames.Editor { + public class GameConfigCreator : EditorWindow { + public string packName = ""; + public bool enabledLog = true; + public bool hardwareAcceleration = true; + + private string _configFileName = "GameConfig"; + + private void OnGUI() { + GUILayout.Label("GameConfig Settings", EditorStyles.boldLabel); + _configFileName = EditorGUILayout.TextField("Character Name", _configFileName); + + packName = EditorGUILayout.TextField(string.IsNullOrEmpty(packName) ? "请输入包名..." : "包名", + packName); + + enabledLog = EditorGUILayout.Toggle("开启日志", enabledLog); + +#if UNITY_ANDROID + hardwareAcceleration = EditorGUILayout.Toggle("硬件加速", hardwareAcceleration); +#endif + if (GUILayout.Button("Create")) { + if (string.IsNullOrEmpty(packName)) { + EditorUtility.DisplayDialog("请填写正确配置", + $"packName {!string.IsNullOrEmpty(packName)}", + "确定"); + return; + } + + CreateGameConfig(); + Close(); + } + } + + [MenuItem("SwhiteGames/Create GameConfig")] + public static void ShowWindow() { + GetWindow("Create GameConfig"); + } + + private void CreateGameConfig() { + // 确保 Resources 文件夹存在 + var resourcesPath = Path.Combine("Assets", "Resources"); + if (!Directory.Exists(resourcesPath)) { + Directory.CreateDirectory(resourcesPath); + AssetDatabase.Refresh(); // 刷新资源数据库 + + Log.Common.Info("Resources 文件夹已创建。"); + } + + // 检查同名文件 + var assetPath = Path.Combine(resourcesPath, _configFileName + ".asset"); + if (File.Exists(assetPath)) { + // 如果同名文件已存在,弹出提示并结束逻辑 + EditorUtility.DisplayDialog("文件已存在", $"配置文件 '{_configFileName}' 已存在于 Resources 文件夹中。", "确定"); + return; + } + + // 创建并设置 config 实例 + var gameConfig = CreateInstance(); + gameConfig.packageName = packName; + gameConfig.enabledLog = enabledLog; + gameConfig.hardwareAcceleration = hardwareAcceleration; + + // 将 ScriptableObject 实例保存到 Resources 文件夹中 + AssetDatabase.CreateAsset(gameConfig, assetPath); + AssetDatabase.SaveAssets(); + + Log.Common.Info("GameConfig 配置文件已成功创建在 " + assetPath); + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Editor/GameConfigCreator.cs.meta b/Assets/SGModule/Common/SGModule/Editor/GameConfigCreator.cs.meta new file mode 100644 index 0000000..a40a096 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Editor/GameConfigCreator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 88d46a9d0224446fb77e9864ebe4d4f5 +timeCreated: 1731660781 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Editor/GameConfigEditor.cs b/Assets/SGModule/Common/SGModule/Editor/GameConfigEditor.cs new file mode 100644 index 0000000..f792819 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Editor/GameConfigEditor.cs @@ -0,0 +1,39 @@ +using UnityEditor; +using UnityEngine; + +namespace SwhiteGames.Editor { + [CustomEditor(typeof(GameConfig))] + public class GameConfigEditor : UnityEditor.Editor { + public override void OnInspectorGUI() { + DrawDefaultInspector(); // 可选:绘制默认 Inspector + + var gameConfig = (GameConfig) target; + + // 包名 + gameConfig.packageName = EditorGUILayout.TextField("包名", gameConfig.packageName); + + // isRelease 选项 + EditorGUI.BeginDisabledGroup(true); + + EditorGUILayout.Toggle(new GUIContent("isRelease", "是否为发布版本, 由玩家设置中脚本定义符 GAME_RELEASE 决定"), + gameConfig.isRelease); + EditorGUI.EndDisabledGroup(); + + // 启用日志(随 isRelease 联动) + EditorGUI.BeginDisabledGroup(gameConfig.isRelease); + gameConfig.enabledLog = + EditorGUILayout.Toggle(new GUIContent("启用日志", "发布版本默认不可启动日志"), gameConfig.enabledLog); + EditorGUI.EndDisabledGroup(); + +#if UNITY_ANDROID + // 硬件加速 + gameConfig.hardwareAcceleration = EditorGUILayout.Toggle("硬件加速", gameConfig.hardwareAcceleration); +#endif + + // 标记对象已修改,确保更改能保存 + if (GUI.changed) { + EditorUtility.SetDirty(gameConfig); + } + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Editor/GameConfigEditor.cs.meta b/Assets/SGModule/Common/SGModule/Editor/GameConfigEditor.cs.meta new file mode 100644 index 0000000..055e4ab --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Editor/GameConfigEditor.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3d35d44cfe6b42dd8abc4fcee72c69c8 +timeCreated: 1743589873 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Editor/HardwareAccelerationSetter.cs b/Assets/SGModule/Common/SGModule/Editor/HardwareAccelerationSetter.cs new file mode 100644 index 0000000..1dc2007 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Editor/HardwareAccelerationSetter.cs @@ -0,0 +1,94 @@ +#if UNITY_ANDROID && UNITY_EDITOR +using System.IO; +using System.Xml; +using SGModule.Common; +using SGModule.Common.Helper; +using UnityEditor.Android; +using UnityEngine; + +namespace SwhiteGames.Editor { + public class HardwareAccelerationManager : IPostGenerateGradleAndroidProject { + public int callbackOrder => 99; + + private static bool EnableHardwareAcceleration => ConfigManager.GameConfig.hardwareAcceleration; + + public void OnPostGenerateGradleAndroidProject(string basePath) { + var manifestPath = GetManifestPath(basePath); + if (!File.Exists(manifestPath)) { + Log.Warning("HardwareAcceleration", $"Manifest not found at {manifestPath}"); + return; + } + + var manifest = new AndroidManifestHelper(manifestPath); + + var changed = manifest.SetHardwareAccelerated(EnableHardwareAcceleration); + + if (changed) { + manifest.Save(); + Log.Info("HardwareAcceleration", $"Updated manifest with hardwareAccelerated={EnableHardwareAcceleration}"); + } + } + + private string GetManifestPath(string basePath) { + return Path.Combine(basePath, "src/main/AndroidManifest.xml"); + } + } + + internal class AndroidManifestHelper { + private readonly XmlDocument _doc; + private readonly XmlNamespaceManager _nsMgr; + private const string AndroidNs = "http://schemas.android.com/apk/res/android"; + private readonly string _manifestPath; + + public AndroidManifestHelper(string path) { + _manifestPath = path; + _doc = new XmlDocument(); + _doc.Load(path); + + _nsMgr = new XmlNamespaceManager(_doc.NameTable); + _nsMgr.AddNamespace("android", AndroidNs); + } + + public bool SetHardwareAccelerated(bool enabled) { + var activity = GetMainActivity(); + if (activity == null) { + Debug.LogWarning("[HardwareAcceleration] Could not find main activity"); + return false; + } + + return SetHardwareAccelerated(activity, enabled); + } + + private bool SetHardwareAccelerated(XmlNode activity, bool enabled) { + var value = enabled ? "true" : "false"; + var attr = (activity as XmlElement)?.GetAttributeNode("hardwareAccelerated", AndroidNs); + + if (attr == null) { + attr = _doc.CreateAttribute("android", "hardwareAccelerated", AndroidNs); + activity.Attributes?.Append(attr); + attr.Value = value; + return true; + } + + if (attr.Value != value) { + attr.Value = value; + return true; + } + + return false; + } + + private XmlNode GetMainActivity() { + return _doc.SelectSingleNode( + "/manifest/application/activity[intent-filter/action/@android:name='android.intent.action.MAIN' and " + + "intent-filter/category/@android:name='android.intent.category.LAUNCHER']", + _nsMgr); + } + + public void Save() { + _doc.Save(_manifestPath); + } + } +} + +#endif diff --git a/Assets/SGModule/Common/SGModule/Editor/HardwareAccelerationSetter.cs.meta b/Assets/SGModule/Common/SGModule/Editor/HardwareAccelerationSetter.cs.meta new file mode 100644 index 0000000..9dfa214 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Editor/HardwareAccelerationSetter.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: dffc1d0f59e04033a4372c6e86992176 +timeCreated: 1753164058 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Editor/NetworkConfigCreator.cs b/Assets/SGModule/Common/SGModule/Editor/NetworkConfigCreator.cs new file mode 100644 index 0000000..6ba60bc --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Editor/NetworkConfigCreator.cs @@ -0,0 +1,78 @@ +using System.IO; +using SGModule.Common.Helper; +using UnityEditor; +using UnityEngine; + +namespace SGModule.Editor { + public class NetworkConfigCreator : EditorWindow { + private const string DefaultHost = "sandbox-api.swhitegames.tech"; + private const string ConfigFileName = "NetworkConfig"; + + public bool showNetworkLog = true; + public string debugHost = DefaultHost; + public string releaseHost = ""; + + public ConnectionMode model = ConnectionMode.Http; + + private void OnGUI() { + showNetworkLog = EditorGUILayout.Toggle("显示日志", showNetworkLog); + + debugHost = EditorGUILayout.TextField("Debug Host:", debugHost); + releaseHost = EditorGUILayout.TextField("Release Host:", releaseHost); + + model = (ConnectionMode) EditorGUILayout.EnumPopup("连接模式:", model); + + + if (GUILayout.Button("Create NetworkConfig")) { + if (string.IsNullOrEmpty(debugHost) || string.IsNullOrEmpty(releaseHost)) { + EditorUtility.DisplayDialog("请填写正确配置", + $"Debug Host {(string.IsNullOrEmpty(debugHost) ? "不存在" : "存在")}, Release Host {(string.IsNullOrEmpty(releaseHost) ? "不存在" : "存在")}", + "确定"); + return; + } + + CreateNetworkConfig(); + Close(); + } + } + + [MenuItem("SwhiteGames/Create NetworkConfig")] + public static void ShowWindow() { + GetWindow("Create NetworkConfig"); + } + + private void CreateNetworkConfig() { + // 确保 Resources 文件夹存在 + var resourcesPath = Path.Combine("Assets", "Resources"); + if (!Directory.Exists(resourcesPath)) { + Directory.CreateDirectory(resourcesPath); + AssetDatabase.Refresh(); // 刷新资源数据库 + Log.Common.Info("Resources 文件夹已创建。"); + } + + // 检查同名文件 + var assetPath = Path.Combine(resourcesPath, ConfigFileName + ".asset"); + if (File.Exists(assetPath)) { + // 如果同名文件已存在,弹出提示并结束逻辑 + EditorUtility.DisplayDialog("文件已存在", $"配置文件 '{ConfigFileName}' 已存在于 Resources 文件夹中。", "确定"); + return; + } + // 检查同名文件 + // string assetPath = Path.Combine(resourcesPath, _configFileName + ".asset"); + // string uniqueAssetPath = AssetDatabase.GenerateUniqueAssetPath(assetPath); // 生成唯一路径 + + // 创建并设置 config 实例 + var networkConfig = CreateInstance(); + networkConfig.showNetworkLog = showNetworkLog; + networkConfig.debugHost = debugHost; + networkConfig.releaseHost = releaseHost; + networkConfig.connectionMode = model; + + // 将 ScriptableObject 实例保存到 Resources 文件夹中 + AssetDatabase.CreateAsset(networkConfig, assetPath); + AssetDatabase.SaveAssets(); + + Log.Common.Info("NetworkConfig 配置文件已成功创建在 " + assetPath); + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Editor/NetworkConfigCreator.cs.meta b/Assets/SGModule/Common/SGModule/Editor/NetworkConfigCreator.cs.meta new file mode 100644 index 0000000..efbfb50 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Editor/NetworkConfigCreator.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 534fe38ef6ad460493d6cb0a852a7fb5 +timeCreated: 1731480153 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Plugins.meta b/Assets/SGModule/Common/SGModule/Plugins.meta new file mode 100644 index 0000000..b20cda3 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 306dc076af5dda247803b0ad907f4968 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Plugins/iOS.meta b/Assets/SGModule/Common/SGModule/Plugins/iOS.meta new file mode 100644 index 0000000..1377e4a --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Plugins/iOS.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3c18f1f3b9ea744f5b3d4a66286b726c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Plugins/iOS/KeychainPlugin.mm b/Assets/SGModule/Common/SGModule/Plugins/iOS/KeychainPlugin.mm new file mode 100644 index 0000000..bcb7040 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Plugins/iOS/KeychainPlugin.mm @@ -0,0 +1,66 @@ +#import +#import +#import + +extern "C" { + +// 保存数据到 Keychain +bool SaveToKeychain(const char* key, const char* value) { + NSString* keyString = [NSString stringWithUTF8String:key]; + NSString* valueString = [NSString stringWithUTF8String:value]; + + NSData* valueData = [valueString dataUsingEncoding:NSUTF8StringEncoding]; + + NSDictionary* query = @{ + (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, + (__bridge id)kSecAttrAccount : keyString, + }; + + SecItemDelete((__bridge CFDictionaryRef)query); + + NSDictionary* attributes = @{ + (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, + (__bridge id)kSecAttrAccount : keyString, + (__bridge id)kSecValueData : valueData, + }; + + OSStatus status = SecItemAdd((__bridge CFDictionaryRef)attributes, NULL); + return status == errSecSuccess; +} + +// 从 Keychain 中获取数据 +const char* GetFromKeychain(const char* key) { + NSString* keyString = [NSString stringWithUTF8String:key]; + + NSDictionary* query = @{ + (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, + (__bridge id)kSecAttrAccount : keyString, + (__bridge id)kSecReturnData : @YES, + (__bridge id)kSecMatchLimit : (__bridge id)kSecMatchLimitOne, + }; + + CFTypeRef result = NULL; + OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result); + + if (status == errSecSuccess) { + NSData* valueData = (__bridge_transfer NSData*)result; + NSString* valueString = [[NSString alloc] initWithData:valueData encoding:NSUTF8StringEncoding]; + return strdup([valueString UTF8String]); + } + + return NULL; +} + +// 删除 Keychain 中的数据 +bool DeleteFromKeychain(const char* key) { + NSString* keyString = [NSString stringWithUTF8String:key]; + + NSDictionary* query = @{ + (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, + (__bridge id)kSecAttrAccount : keyString, + }; + + OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query); + return status == errSecSuccess; +} +} \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Plugins/iOS/KeychainPlugin.mm.meta b/Assets/SGModule/Common/SGModule/Plugins/iOS/KeychainPlugin.mm.meta new file mode 100644 index 0000000..17a8d58 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Plugins/iOS/KeychainPlugin.mm.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9bc4268c12974c68bd77c36016e019ed +timeCreated: 1736750208 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts.meta b/Assets/SGModule/Common/SGModule/Scripts.meta new file mode 100644 index 0000000..3533620 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 53a17396f989d874b9b047cca52f77f8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Scripts/Base.meta b/Assets/SGModule/Common/SGModule/Scripts/Base.meta new file mode 100644 index 0000000..f3c4187 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Base.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f92c00a864347c945bec347302a061e0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Scripts/Base/SingletonMonoBehaviour.cs b/Assets/SGModule/Common/SGModule/Scripts/Base/SingletonMonoBehaviour.cs new file mode 100644 index 0000000..a9fde5f --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Base/SingletonMonoBehaviour.cs @@ -0,0 +1,57 @@ +using SGModule.Common.Helper; +using UnityEngine; + +namespace SGModule.Common.Base { + public class SingletonMonoBehaviour : MonoBehaviour where T : MonoBehaviour { + private static T _instance; + + /// + /// 初始化完成标记,有需要的地方可以使用 + /// + protected static bool IsInitComplete; + + // 存储所有单例的父对象 + private static GameObject _singletonParent; + + public static T Instance { + get { + if (_instance == null) { + // 尝试找到已存在的实例 + _instance = FindObjectOfType(); + + // 如果没有找到,则创建一个新的实例 + if (_instance == null) { + // 确保所有单例对象放到同一个父对象下 + if (_singletonParent == null) { + _singletonParent = GameObject.Find("Singletons") ?? new GameObject("Singletons"); + DontDestroyOnLoad(_singletonParent); // 不在场景切换时销毁 + } + + var singletonObject = new GameObject(typeof(T).Name); + singletonObject.transform.SetParent(_singletonParent.transform); // 设置父对象 + _instance = singletonObject.AddComponent(); + } + } + + return _instance; + } + } + + // 确保在场景中只存在一个实例 + protected virtual void Awake() { + if (_instance == null) { + _instance = this as T; + } + else if (_instance != this) { + Log.Common.Warning($"An instance of {typeof(T)} already exists! Destroying this instance."); + Destroy(gameObject); // 如果有其他实例,销毁当前对象 + } + } + + protected virtual void OnDestroy() { + if (_instance == this) { + _instance = null; // 清除引用 + } + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Base/SingletonMonoBehaviour.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Base/SingletonMonoBehaviour.cs.meta new file mode 100644 index 0000000..23e33b2 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Base/SingletonMonoBehaviour.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1a32d260789150d449d0313a73dcc5b1 +timeCreated: 1728986962 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/ConfigManager.cs b/Assets/SGModule/Common/SGModule/Scripts/ConfigManager.cs new file mode 100644 index 0000000..65c27d3 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/ConfigManager.cs @@ -0,0 +1,30 @@ +using SGModule.Common.Helper; +using UnityEngine; + +namespace SGModule.Common { + public static class ConfigManager { + private const string GameConfigFilePath = "GameConfig"; + private const string NetworkConfigFilePath = "NetworkConfig"; + + static ConfigManager() { + GameConfig = Resources.Load(GameConfigFilePath); + if (GameConfig == null) { + Log.Common.Error($"加载失败:未找到配置文件 {GameConfigFilePath},请确保它放在 Resources 文件夹下并命名正确"); + } + + NetworkConfig = Resources.Load(NetworkConfigFilePath); + if (NetworkConfig == null) { + Log.Common.Error($"加载失败:未找到配置文件 {NetworkConfigFilePath},请确保它放在 Resources 文件夹下并命名正确"); + } + } + + + public static GameConfig GameConfig { + get; + } + + public static NetworkConfig NetworkConfig { + get; + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/ConfigManager.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/ConfigManager.cs.meta new file mode 100644 index 0000000..a1e0945 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/ConfigManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8639bb4e64f34c3db2c6537cfdac4974 +timeCreated: 1731316175 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions.meta b/Assets/SGModule/Common/SGModule/Scripts/Extensions.meta new file mode 100644 index 0000000..b30c881 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f468ddf1f1fc08446865eb4fb41b74aa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/ArrayExtensions.cs b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ArrayExtensions.cs new file mode 100644 index 0000000..5889f72 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ArrayExtensions.cs @@ -0,0 +1,14 @@ +using SGModule.Common.Helper; +using SGModule.Common.Interface; + +namespace SGModule.Common.Extensions { + public static class ArrayExtensions { + public static T Random(this T[] items, T fallback = default) where T : class, IWeighted { + if (items == null || items.Length == 0) { + return fallback; + } + + return RandomHelper.RandomByWeight(items, fallback); + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/ArrayExtensions.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ArrayExtensions.cs.meta new file mode 100644 index 0000000..254cb88 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ArrayExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ea3b1bd83aa74285b19f87301391b906 +timeCreated: 1749197978 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/EnumExtensions.cs b/Assets/SGModule/Common/SGModule/Scripts/Extensions/EnumExtensions.cs new file mode 100644 index 0000000..b1945f5 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/EnumExtensions.cs @@ -0,0 +1,12 @@ +using System; +using System.ComponentModel; + +namespace SGModule.Common.Extensions { + public static class EnumExtensions { + public static string GetDescription(this Enum value) { + var field = value.GetType().GetField(value.ToString()); + var attribute = (DescriptionAttribute) Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)); + return attribute?.Description ?? value.ToString(); // 如果没有描述,就使用枚举名称 + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/EnumExtensions.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Extensions/EnumExtensions.cs.meta new file mode 100644 index 0000000..7e13fef --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/EnumExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4fb5c1462c4f411bb8c08fec74c0bb60 +timeCreated: 1731403821 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/ListExtensions.cs b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ListExtensions.cs new file mode 100644 index 0000000..caa7810 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ListExtensions.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using System.Linq; +using SGModule.Common.Helper; +using SGModule.Common.Interface; + +namespace SGModule.Common.Extensions { + public static class ListExtensions { + public static T Random(this IEnumerable items, T fallback = default) where T : class, IWeighted { + if (items == null) { + return fallback; + } + + var list = items as IList ?? items.ToList(); + + if (list.Count == 0) { + return fallback; + } + + return RandomHelper.RandomByWeight(list, fallback); + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/ListExtensions.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ListExtensions.cs.meta new file mode 100644 index 0000000..c455b8e --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ListExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f42389145cf940a0b4202dbd516228c4 +timeCreated: 1749198436 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/ObjectExtensions.cs b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ObjectExtensions.cs new file mode 100644 index 0000000..c45d46b --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ObjectExtensions.cs @@ -0,0 +1,302 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.Text; +using Newtonsoft.Json; +using SGModule.Common.Helper; + +namespace SGModule.Common.Extensions { + /// + /// 提供通用对象类型转换的扩展方法,支持数值类型、字符串、枚举、集合、时间等多种类型间的智能转换。 + /// + public static class ObjectExtensions { + /// + /// 将对象强制转换为目标类型 ,转换失败时返回默认值。 + /// + /// 目标类型 + /// 待转换的对象 + /// 转换失败时返回的默认值 + /// 可选格式字符串(如用于时间或数值格式化) + /// 格式化提供者,默认为当前区域设置 + /// 转换后的目标类型值,或 + /// + /// 字符串到基本类型 + /// + /// "123".As<int>(); // 输出 123 + /// "45.67".As<float>(); // 输出 45.67f + /// "true".As<bool>(); // 输出 true + /// "2023-01-01".As<DateTime>(); // 输出 2023-01-01 + /// "".As<int>(); // 输出 0 + /// ((string)null).As<int>(); // 输出 0 + /// "abc".As<int>(); // 输出 0(无法转换) + /// "1.23E+5".As<float>(); // 输出 123000f + /// ..... + /// + /// + public static T As(this object value, T defaultValue = default, string format = null, IFormatProvider formatProvider = null) { + return (T) As(value, typeof(T), defaultValue, format, formatProvider); + } + + /// + /// 将对象转换为指定的目标类型。 + /// 支持基础类型转换、字符串与 JSON 互转、枚举解析、集合映射、Base64 处理等。 + /// + /// 要转换的对象 + /// 目标类型 + /// 转换失败时的返回值 + /// 可选的格式字符串(用于时间、数字格式化) + /// 格式提供者(区域信息),默认为当前区域 + /// 转换结果或默认值 + public static object As(this object value, Type targetType, object defaultValue = null, string format = null, IFormatProvider formatProvider = null) { + if (value == null || value == DBNull.Value) { + return defaultValue; + } + + formatProvider ??= CultureInfo.CurrentCulture; + + try { + // 1. 类型兼容直接返回 + if (targetType.IsInstanceOfType(value)) { + return value; + } + + // 2. 数值类型之间转换(int, float, decimal 等) + if (value.IsNumericType() && targetType.IsNumericType()) { + return Convert.ChangeType(value, targetType, formatProvider); + } + + // 3. 字符串 ⇄ 字节数组 + if (targetType == typeof(byte[]) && value is string str) { + return Encoding.UTF8.GetBytes(str); + } + + if (targetType == typeof(string) && value is byte[] bytes) { + return Encoding.UTF8.GetString(bytes); + } + + // 4. 转为字符串 + if (targetType == typeof(string)) { + if (value is string s) { + return s; + } + + if (value.IsNumericType()) { + return string.Format(formatProvider, format ?? "{0}", value); + } + + if (value is DateTime dt) { + return string.IsNullOrEmpty(format) ? dt.ToString(formatProvider) : dt.ToString(format, formatProvider); + } + + try { + return JsonConvert.SerializeObject(value); + } + catch { + return defaultValue; + } + } + + // 5. 从字符串解析为目标类型 + if (value is string strValue) { + if (string.IsNullOrWhiteSpace(strValue)) { + return defaultValue; + } + + // 字符串 → 枚举 + if (targetType.IsEnum) { + try { + return Enum.Parse(targetType, strValue, true); + } + catch { + return defaultValue; + } + } + + // 字符串 → 数值 + if (targetType.IsNumericType()) { + return Convert.ChangeType(strValue, targetType, formatProvider); + } + + // 字符串 → 时间 + if (targetType == typeof(DateTime)) { + return string.IsNullOrEmpty(format) + ? DateTime.Parse(strValue, formatProvider) + : DateTime.ParseExact(strValue, format, formatProvider); + } + + // 字符串 → 自定义类(JSON) + if (targetType.IsClass && targetType != typeof(string)) { + try { + return JsonConvert.DeserializeObject(strValue, targetType); + } + catch { + return defaultValue; + } + } + } + + // 6. 集合类型转换(如 List -> List) + if (targetType.IsGenericListOrArray() && value is IEnumerable enumerable) { + var elementType = targetType.GetElementType() ?? targetType.GetGenericArguments()[0]; + var list = (IList) Activator.CreateInstance(typeof(List<>).MakeGenericType(elementType)); + + foreach (var item in enumerable) { + var converted = typeof(ObjectExtensions) + .GetMethod("As", new[] { typeof(object), typeof(Type), typeof(object), typeof(string), typeof(IFormatProvider) }) + ?.Invoke(null, new[] { item, elementType, null, format, formatProvider }); + + list.Add(converted); + } + + return targetType.IsArray ? list.ToArray(elementType) : list; + } + + // 7. 尝试通过 TypeConverter 转换(主要处理结构体、基础类型) + if (targetType.IsValueType || targetType == typeof(string)) { + var strVal = value.ToString(); + if (!string.IsNullOrWhiteSpace(strVal)) { + var converter = TypeDescriptor.GetConverter(targetType); + if (converter.CanConvertFrom(typeof(string))) { + return converter.ConvertFrom(null, formatProvider as CultureInfo, strVal); + } + } + } + + // 8. Fallback:通过 JSON 转换 + return JsonConvert.DeserializeObject(JsonConvert.SerializeObject(value), targetType); + } + catch { + return defaultValue; + } + } + + #region 🔧 辅助方法 + + private static bool IsNumericType(this Type type) { + return Type.GetTypeCode(type) switch { + TypeCode.Byte or TypeCode.SByte or TypeCode.UInt16 or TypeCode.UInt32 or + TypeCode.UInt64 or TypeCode.Int16 or TypeCode.Int32 or TypeCode.Int64 or + TypeCode.Decimal or TypeCode.Double or TypeCode.Single => true, + _ => false + }; + } + + private static bool IsNumericType(this object value) { + return value?.GetType().IsNumericType() ?? false; + } + + private static bool IsGenericListOrArray(this Type type) { + return type != null && (type.IsArray || + (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) + || type.GetGenericTypeDefinition() == typeof(IList<>)))); + } + + private static Array ToArray(this IList list, Type elementType) { + var array = Array.CreateInstance(elementType, list.Count); + list.CopyTo(array, 0); + return array; + } + + #endregion + } + + public static class ObjectExtensionsTest { + public static void AsTestRun() { + TestCase("int 到 int", 123.As(), 123); + TestCase("float 到 int", 123.1f.As(), 123); + TestCase("double 到 decimal", 99.99.As(), 99.99m); + TestCase("int 到 long", 100.As(), 100L); + + TestCase("字符串 到 int", "123".As(), 123); + TestCase("字符串 到 float", "45.67".As(), 45.67f); + TestCase("字符串 到 bool", "true".As(), true); + TestCase("字符串 到 DateTime", "2023-01-01".As(), new DateTime(2023, 1, 1)); + TestCase("空字符串 到 int", "".As(), 0); + TestCase("null字符串 到 int", ((string) null).As(), 0); + TestCase("非法字符串 到 int", "abc".As(), 0); + TestCase("科学计数法字符串 到 float", "1.23E+5".As(), 123000f); + + TestCase("int 到 字符串", 42.As(), "42"); + TestCase("float 到 字符串(en-US)", 3.14159f.As(formatProvider: new CultureInfo("en-US")), "3.14159"); + TestCase("float 到 字符串(de-DE)", 3.14159f.As(formatProvider: new CultureInfo("de-DE")), "3,14159"); + TestCase("DateTime 到 字符串(格式化)", new DateTime(2024, 5, 1).As(format: "yyyy-MM-dd"), "2024-05-01"); + + TestCase("null 到 int", ((object) null).As(), 0); + TestCase("null 到 string", ((object) null).As(), null); + TestCase("DBNull 到 int", DBNull.Value.As(), 0); + + TestCase("枚举 到 string", Color.Red.As(), "Red"); + TestCase("字符串 到 枚举", "Green".As(), Color.Green); + + var json = "{\"Name\":\"Alice\",\"Age\":30}"; + TestCase("JSON 字符串 到 Person", json.As().Name, "Alice"); + TestCase("对象 到 JSON 字符串", new Person { Name = "Alice", Age = 30 }.As(), JsonConvert.SerializeObject(new Person { Name = "Alice", Age = 30 })); + + TestCase("字符串数组 到 List", new[] { "1", "2", "3" }.As>(), new List { 1, 2, 3 }); + TestCase("List 到 float[]", new List { 1.1f, 2.2f }.As(), new[] { 1.1f, 2.2f }); + TestCase("空集合 到 int[]", new string[] { }.As(), new int[] { }); + + var str = "hello"; + var bytes = Encoding.UTF8.GetBytes(str); + TestCase("byte[] 到 base64 string", bytes.As(), str); + TestCase("base64 string 到 byte[]", BitConverter.ToString(str.As()), BitConverter.ToString(bytes)); + + TestCase("字符串小数(德语) 到 float", "1,23".As(formatProvider: new CultureInfo("de-DE")), 1.23f); + TestCase("字符串小数(英语) 到 float", "1.23".As(formatProvider: new CultureInfo("en-US")), 1.23f); + + TestCase("非法 JSON 到 Person(失败返回 null)", "{invalid}".As(), null); + TestCase("不能转的对象 到 int", new Person { Name = "A" }.As(), 0); + TestCase("不能转的对象 到 string(fallback 到 JsonConvert)", new Person { Name = "A", Age = 20 }.As(), JsonConvert.SerializeObject(new Person { Name = "A", Age = 20 })); + } + + private static void TestCase(string description, T actual, T expected) { + var isSuccess = CommonUtils.DeepEquals(actual, expected); + + var actualStr = FormatValue(actual); + var expectedStr = FormatValue(expected); + var msg = $"{description} => 结果: {actualStr}, 期望: {expectedStr}"; + if (isSuccess) { + Log.Info("As()", msg); + } + else { + Log.Warning("As()", msg); + } + } + + private static string FormatValue(T value) { + if (value == null) { + return "null"; + } + + if (value is byte[] byteArray) { + return $"[{string.Join(", ", byteArray)}]"; + } + + if (value is int[] intArray) { + return $"[{string.Join(", ", intArray)}]"; + } + + return value.ToString(); + } + + private enum Color { + Red, + Green, + Blue + } + + private class Person { + public string Name { + get; + set; + } + + public int Age { + get; + set; + } + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/ObjectExtensions.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ObjectExtensions.cs.meta new file mode 100644 index 0000000..e79aad7 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/ObjectExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: e6571543817d44e79cbd4f48a4d3616a +timeCreated: 1749716272 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/StringExtensions.cs b/Assets/SGModule/Common/SGModule/Scripts/Extensions/StringExtensions.cs new file mode 100644 index 0000000..51547c5 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/StringExtensions.cs @@ -0,0 +1,7 @@ +namespace SGModule.Common.Extensions { + public static class StringExtensions { + public static bool IsNullOrWhiteSpace(this string str) { + return string.IsNullOrWhiteSpace(str); + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Extensions/StringExtensions.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Extensions/StringExtensions.cs.meta new file mode 100644 index 0000000..14eaada --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Extensions/StringExtensions.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 562d871c5a8d49db9d78fb2921475549 +timeCreated: 1731309251 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/GM.meta b/Assets/SGModule/Common/SGModule/Scripts/GM.meta new file mode 100644 index 0000000..36cee61 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/GM.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 483f1710e0c24e53a773d154310180e8 +timeCreated: 1731657933 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/GM/GMTool.cs b/Assets/SGModule/Common/SGModule/Scripts/GM/GMTool.cs new file mode 100644 index 0000000..c7b08e2 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/GM/GMTool.cs @@ -0,0 +1,367 @@ +using System; +using System.Collections.Generic; +using SGModule.Common; +using SGModule.Common.Base; +using SGModule.Common.Helper; +using UnityEngine; + +public class GMTool : SingletonMonoBehaviour { + private readonly int buttonHeight = 50; + private readonly int fontSize = 35; // 字体大小 + + private readonly Dictionary inputFields = new(); + + private readonly List items = new(); + private readonly int spacing = 10; // 控件之间的间距 + private GUIStyle buttonStyle; + private int currentX; // 当前 X 坐标 + private int currentY; // 当前 Y 坐标 + private GUIStyle inputFieldStyle; + private GUIStyle labelStyle; + + private bool toggleDisplay; // 控制显示与隐藏 + private int windowWidth; // 屏幕宽度 + + + protected override void Awake() { + base.Awake(); + if (!ConfigManager.GameConfig.isRelease) { + IsInitComplete = true; + } + } + + private void OnGUI() { + if (!IsInitComplete) { + return; + } + + // 初始化样式 + if (buttonStyle == null || labelStyle == null || inputFieldStyle == null) { + InitializeStyles(); + } + + // 初始化布局 + StartLayout(); + + // 显示开关按钮 + AddButton(toggleDisplay ? "关闭 GM 工具" : "打开 GM 工具", () => { + toggleDisplay = !toggleDisplay; + }); + + if (!toggleDisplay) { + return; + } + + + // 添加控件示例 + AddLabel("GM 工具"); + // AddButton("初始化网络模块", () => + // { + // var gameConfig = ConfigManager.GetInstance.GetGameConfig(); + // NetworkKit.Instance.InitData(gameConfig.packageName, gameConfig.isRelease); + // }); + // AddButton("登录", () => + // { + // NetworkKit.Instance.LoginRequest("Test", false, (arg0, model) => + // { + // Debug.LogError($"登录结果 {arg0}"); + // }); + // }); + + + // AddButton($"加载配置模块初始化", () => + // { + // ConfigLoader.Instance.Init(NetworkKit.Instance.GetLoginModel().setting, + // NetworkKit.Instance.GetLoginModel().cdn_url, new List() + // { + // new CommonModel("Common"), + // new PrizeWheelDataModel("PrizeWheelData"), + // }, + // state => + // { + // Debug.LogError($"配置加载状态{state}"); + // }, + // (errorName, message) => + // { + // Debug.LogError($"配置解析错误 {errorName} 错误信息:{message}"); + // } + // ); + // }); + // AddButton($"读取Common配置", () => + // { + // var model = ConfigLoader.Instance.GetConfig(); + // Debug.LogError(model); + // }); + // AddButton($"读取PrizeWheelDataModel配置", () => + // { + // var model = ConfigLoader.Instance.GetConfig(); + // Debug.LogError(model.DataList.Count); + // }); + // AddButton($"测试解析为自定义配置", () => + // { + // Debug.LogError(ConfigLoader.Instance.ParesPersonalizedConfig(new PrizeWheelDataModel("PrizeWheelData"), "prize")); + // }); + // AddButton($"读取自定义配置", () => + // { + // var personalizedConfig = ConfigLoader.Instance.GetPersonalizedConfig("prize"); + // Debug.LogError(personalizedConfig.DataList.Count); + // }); + + + UpdateItems(); + + + // AddButton("退出游戏", Application.Quit); + } + + private void InitializeStyles() { + buttonStyle = new GUIStyle(GUI.skin.button) { + fontSize = fontSize, + alignment = TextAnchor.MiddleCenter, + normal = { textColor = Color.green } + }; + + labelStyle = new GUIStyle(GUI.skin.label) { + fontSize = fontSize, + normal = { textColor = Color.red } + }; + + inputFieldStyle = new GUIStyle(GUI.skin.textField) { + fontSize = fontSize, + alignment = TextAnchor.MiddleLeft + }; + } + + private void StartLayout() { + currentX = spacing; + currentY = spacing; + windowWidth = Screen.width; + } + + private void AddButton(string text, Action onClick) { + // 计算按钮宽度,基于标题内容自适应 + var buttonWidth = Mathf.Max(150, Mathf.CeilToInt(buttonStyle.CalcSize(new GUIContent(text)).x) + 20); + + // 换行检查 + if (currentX + buttonWidth + spacing > windowWidth) { + currentX = spacing; + currentY += buttonHeight + spacing; + } + + // 绘制按钮 + if (GUI.Button(new Rect(currentX, currentY, buttonWidth, buttonHeight), text, buttonStyle)) { + onClick?.Invoke(); + } + + // 更新下一个控件的位置 + currentX += buttonWidth + spacing; + } + + private void AddLabel(string text) { + // // 计算标签宽度和高度 + // Vector2 size = labelStyle.CalcSize(new GUIContent(text)); + // int labelWidth = Mathf.CeilToInt(size.x); + // int labelHeight = Mathf.CeilToInt(size.y); + // + // // 换行检查 + // if (currentX + labelWidth + spacing > windowWidth) + // { + // currentX = spacing; + // currentY += buttonHeight + spacing; + // } + // + // // 绘制标签 + // GUI.Label(new Rect(currentX, currentY, labelWidth, labelHeight), text, labelStyle); + // + // // 更新下一个控件的位置 + // currentX += labelWidth + spacing; + + // 启用自动换行 可用 + labelStyle.wordWrap = true; + + var size = labelStyle.CalcSize(new GUIContent(text)); + var labelWidth = Mathf.CeilToInt(size.x); + var labelHeight = Mathf.CeilToInt(size.y); + + // 计算标签宽度和高度 + var maxWidth = windowWidth - spacing * 2; // 标签最大宽度 + // float labelWidth = maxWidth; // 长文本直接占满一行 + var needNewRow = labelWidth / maxWidth > 0.6f; + if (needNewRow) { + labelWidth = maxWidth; + labelHeight = (int) labelStyle.CalcHeight(new GUIContent(text), labelWidth); + } + + // 换行逻辑:如果当前行剩余宽度不足,提前换行 + if (currentX + labelWidth + spacing > windowWidth) { + currentX = spacing; // 回到左侧 + currentY += buttonHeight + spacing; // 换到下一行 + } + + // 绘制标签 + GUI.Label(new Rect(currentX, currentY, labelWidth, labelHeight), text, labelStyle); + + // 更新位置:占满一整行,因此重置到新行 + if (needNewRow) { + currentX = spacing; + currentY += labelHeight + spacing; + } + else { + currentX += labelWidth + spacing; + } + } + + private void AddInputField(string key, string placeholder, string buttonText, Action onSubmit) { + var inputFieldWidth = Mathf.Max(200, Mathf.CeilToInt(inputFieldStyle.CalcSize(new GUIContent(placeholder)).x) + 20); + var buttonWidth = Mathf.Max(100, Mathf.CeilToInt(buttonStyle.CalcSize(new GUIContent(buttonText)).x) + 20); + + if (currentX + inputFieldWidth + buttonWidth + spacing * 2 > windowWidth) { + currentX = spacing; + currentY += buttonHeight + spacing; + } + + if (!inputFields.TryGetValue(key, out var inputField)) { + inputFields.Add(key, ""); + } + + + inputField = GUI.TextField(new Rect(currentX, currentY, inputFieldWidth, buttonHeight), inputField, inputFieldStyle); + currentX += inputFieldWidth + spacing; + + if (GUI.Button(new Rect(currentX, currentY, buttonWidth, buttonHeight), buttonText, buttonStyle)) { + onSubmit?.Invoke(inputField); + } + + inputFields[key] = inputField; + + currentX += buttonWidth + spacing; + } + + private void AddSeparator(string text = "") { + // 换行以确保分割线占据整行 + currentX = spacing; + currentY += buttonHeight + spacing; + + // // 分割线高度和宽度 + // int separatorHeight = Mathf.CeilToInt(fontSize * 1.5f); // 动态设置高度 + // int separatorWidth = windowWidth - spacing * 2; + // + // // 计算文字尺寸 + // Vector2 textSize = labelStyle.CalcSize(new GUIContent(text)); + // int textWidth = Mathf.CeilToInt(textSize.x); + // + // // 绘制分割线 + // Rect lineRect = new Rect(currentX, currentY + separatorHeight / 2, separatorWidth, 1); + // GUI.Box(lineRect, GUIContent.none); + // + // + // // 绘制文字 + // if (!string.IsNullOrEmpty(text)) + // { + // GUI.Label(new Rect((windowWidth - textWidth) / 2, currentY, textWidth, separatorHeight), text, labelStyle); + // } + + // 分割线宽度和高度 + var separatorWidth = windowWidth - spacing * 2; + var separatorHeight = Mathf.CeilToInt(fontSize * 1.5f); // 分割线高度(文字高度) + var lineHeight = Mathf.CeilToInt(fontSize * 0.1f); // 线条高度 + + if (string.IsNullOrEmpty(text)) { + // 如果没有文字,绘制整行分割线 + DrawLine(new Rect(currentX, currentY + separatorHeight / 2 - lineHeight / 2, separatorWidth, lineHeight)); + } + else { + // 计算文字尺寸 + var textSize = labelStyle.CalcSize(new GUIContent(text)); + var textWidth = Mathf.CeilToInt(textSize.x); + + // 计算分割线两侧长度 + var lineWidth = (separatorWidth - textWidth - spacing * 2) / 2; + + // 绘制左侧线条 + DrawLine(new Rect(currentX, currentY + separatorHeight / 2 - lineHeight / 2, lineWidth, lineHeight)); + + // 绘制文字 + GUI.Label(new Rect(currentX + lineWidth + spacing, currentY, textWidth, separatorHeight), text, labelStyle); + + // 绘制右侧线条 + DrawLine(new Rect(currentX + lineWidth + textWidth + spacing * 2, currentY + separatorHeight / 2 - lineHeight / 2, lineWidth, + lineHeight)); + } + + // 更新位置 + currentY += separatorHeight + spacing; + } + + private void DrawLine(Rect rect) { + // 设置线条颜色 + var originalColor = GUI.color; + GUI.color = Color.white; // 可以改成其他颜色 + + // 绘制线条 + GUI.DrawTexture(rect, Texture2D.whiteTexture); + + // 恢复原始颜色 + GUI.color = originalColor; + } + + public void AddItem(GMToolItem item) { + items.Add(item); + } + + private void UpdateItems() { + foreach (var item in items) { + switch (item.Type) { + case GUIType.Label: + AddLabel(item.TextFunc.Invoke()); + break; + case GUIType.Button: + AddButton(item.TextFunc.Invoke(), () => { + item.OnClick?.Invoke(null); + }); + break; + case GUIType.InputField: + AddInputField(item.Key, item.Placeholder, item.TextFunc.Invoke(), s => { + item.OnClick?.Invoke(s); + }); + break; + case GUIType.Separator: + AddSeparator(item.TextFunc?.Invoke()); + break; + default: + Log.Common.Error($"Unsupported GUIType: {item.Type}"); + break; + } + } + } +} + +public enum GUIType { + Label, + Button, + InputField, + Separator // 分割线类型 +} + +public class GMToolItem { + public string Key; + public Action OnClick; + public string Placeholder; + public Func TextFunc; + public GUIType Type; + + /// + /// + /// 控件类型 + /// 显示的文本,传入委托可以动态变化 + /// 点击委托,只有Button与InputField有效,Button可忽略字符串参数,InputField输入的内容会传入 + /// InputField 需要用到的key,记得保持唯一性,如果重复有可能会导致重复的输入框同步一样的内容 + /// 提示占位文本 + public GMToolItem(GUIType type, Func textFunc, Action onClick = null, string key = "", string placeholder = "") { + Type = type; + TextFunc = textFunc; + OnClick = onClick; + Key = key; + Placeholder = placeholder; + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/GM/GMTool.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/GM/GMTool.cs.meta new file mode 100644 index 0000000..6fcce96 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/GM/GMTool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d06d4a3e6b703474f8fd425530b85b87 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper.meta new file mode 100644 index 0000000..e970df5 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c8ac58d9307eb1c45849414a44d923ca +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/Base64Helper.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/Base64Helper.cs new file mode 100644 index 0000000..0eb43cb --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/Base64Helper.cs @@ -0,0 +1,26 @@ +using System; +using System.Text; + +namespace SGModule.Common.Helper { + public static class Base64Helper { + public static string Encode(string source) { + return Base64Encode(Encoding.UTF8, source); + } + + public static string Decode(string result) { + return Base64Decode(Encoding.UTF8, result); + } + + private static string Base64Encode(Encoding encoding, string source) { + var bytes = encoding.GetBytes(source); + var encode = Convert.ToBase64String(bytes); + return encode; + } + + private static string Base64Decode(Encoding encoding, string result) { + var bytes = Convert.FromBase64String(result); + var decode = encoding.GetString(bytes); + return decode; + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/Base64Helper.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/Base64Helper.cs.meta new file mode 100644 index 0000000..67dbe2c --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/Base64Helper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0078c84c6f3f4d0ba79a2ef151bf0545 +timeCreated: 1731309598 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/CommonUtils.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/CommonUtils.cs new file mode 100644 index 0000000..a44ae30 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/CommonUtils.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json.Linq; + +namespace SGModule.Common.Helper { + // 混合通用方法工具类(放置一些通用的静态函数) + public static class CommonUtils { + /// + /// 深度比较两个对象是否相等,支持复杂结构(如 List、Dictionary、嵌套对象) + /// + public static bool DeepEquals(T a, T b) { + if (a == null && b == null) { + return true; + } + + if (a == null || b == null) { + return false; + } + + return JToken.DeepEquals(JToken.FromObject(a), JToken.FromObject(b)); + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/CommonUtils.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/CommonUtils.cs.meta new file mode 100644 index 0000000..bc2a70c --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/CommonUtils.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cb253d0247f54d55b83685a0e7c51b70 +timeCreated: 1749455481 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/Cryptor.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/Cryptor.cs new file mode 100644 index 0000000..39e3c65 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/Cryptor.cs @@ -0,0 +1,35 @@ +using System.Text; + +namespace SGModule.Common.Helper { + public class Cryptor { + public static string Encrypt(string data, string key) { + var keyMD5 = MD5Helper.MD5String1(key); + var str = Base64Helper.Encode(data + keyMD5); + + var bytes = Encoding.UTF8.GetBytes(str); + for (int i = 0, j = bytes.Length - 1; i < j; i += 1, j -= 1) { + if (i % 2 == 0) { + (bytes[i], bytes[j]) = (bytes[j], bytes[i]); + } + } + + var loginData = Encoding.UTF8.GetString(bytes); + return loginData; + } + + public static string Decrypt(string data, string key) { + var bytes = Encoding.UTF8.GetBytes(data); + for (int i = 0, j = bytes.Length - 1; i < j; i += 1, j -= 1) { + if (i % 2 == 0) { + (bytes[i], bytes[j]) = (bytes[j], bytes[i]); + } + } + + var str = Encoding.UTF8.GetString(bytes); + var str1 = Base64Helper.Decode(str); + var keyMD5 = MD5Helper.MD5String1(key); + var result = str1.Replace(keyMD5, string.Empty); + return result; + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/Cryptor.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/Cryptor.cs.meta new file mode 100644 index 0000000..9c7ab26 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/Cryptor.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 957dffab93b34167b72cdfd2b0e709fe +timeCreated: 1731309567 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/DeviceHelper.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/DeviceHelper.cs new file mode 100644 index 0000000..e0123a1 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/DeviceHelper.cs @@ -0,0 +1,23 @@ +using UnityEngine; + +namespace SGModule.Common.Helper { + public static class DeviceHelper { + private const string Idfv = "IDFV"; + + public static string GetDeviceID(string deviceName = "TestUser001") { +#if UNITY_IOS && !UNITY_EDITOR + deviceName = Keychain.Get(Idfv); + if (string.IsNullOrEmpty(deviceName)) + { + deviceName = SystemInfo.deviceUniqueIdentifier; + Keychain.Save(Idfv, deviceName); + } + + return deviceName; +#elif UNITY_EDITOR + return deviceName; +#endif + return SystemInfo.deviceUniqueIdentifier; + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/DeviceHelper.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/DeviceHelper.cs.meta new file mode 100644 index 0000000..b8ecf02 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/DeviceHelper.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 121d8e1769529b440bc85f03a485ec10 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/Log.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/Log.cs new file mode 100644 index 0000000..c4274bc --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/Log.cs @@ -0,0 +1,115 @@ +using System; +using UnityEngine; + +namespace SGModule.Common.Helper { + public static class Log { + // 预定义模块实例 + public static readonly ModuleLogger Common = new("Common"); + public static readonly ModuleLogger Net = new("Net", ConfigManager.NetworkConfig?.showNetworkLog ?? false); + public static readonly ModuleLogger MarkdownKit = new("MarkdownKit"); + public static readonly ModuleLogger ApplePay = new("ApplePay"); + public static readonly ModuleLogger ConfigLoader = new("ConfigLoader"); + public static readonly ModuleLogger NetKit = new("NetKit"); + public static readonly ModuleLogger DataStorage = new("DataStorage"); + public static readonly ModuleLogger IAP = new("IAP"); + + private static bool IsEnabled => ConfigManager.GameConfig?.enabledLog ?? false; + + public static void Info(string label, string msg, bool showStack = true) { + if (IsEnabled) { + InternalLog(LogType.Log, label, msg, LogColors.Info, showStack); + } + } + + public static void Warning(string label, string msg, bool showStack = true) { + if (IsEnabled) { + InternalLog(LogType.Warning, label, msg, LogColors.Warning, showStack); + } + } + + public static void Error(string label, string msg, bool showStack = true) { + if (IsEnabled) { + InternalLog(LogType.Error, label, msg, LogColors.Error, showStack); + } + } + + public static void Exception(string label, Exception ex, bool showStack = true) { + if (!IsEnabled || ex == null) { + return; + } + + + var msg = $"Exception: {ex.Message}"; + if (showStack && !string.IsNullOrEmpty(ex.StackTrace)) { + msg += $"\n{ex.StackTrace}"; + } + + InternalLog(LogType.Error, label, msg, LogColors.Exception, showStack); + } + + internal static void InternalLog(LogType type, string label, string msg, string color, bool showStack) { + var formattedMsg = $"[{label}] {msg}"; + + var original = Application.GetStackTraceLogType(type); + if (!showStack) { + Application.SetStackTraceLogType(type, StackTraceLogType.None); + } + + Debug.unityLogger.Log(type, formattedMsg); + + if (!showStack) { + Application.SetStackTraceLogType(type, original); + } + } + } + + public class ModuleLogger { + private readonly bool _isEnabled; + private readonly string _label; + + public ModuleLogger(string label, bool isEnabled = true) { + _label = label; + _isEnabled = isEnabled; + } + + private bool IsEnabled => (ConfigManager.GameConfig?.enabledLog ?? false) && _isEnabled; + + public void Info(string msg, bool showStack = true) { + if (IsEnabled) { + Log.InternalLog(LogType.Log, _label, msg, LogColors.Info, showStack); + } + } + + public void Warning(string msg, bool showStack = true) { + if (IsEnabled) { + Log.InternalLog(LogType.Warning, _label, msg, LogColors.Warning, showStack); + } + } + + public void Error(string msg, bool showStack = true) { + if (IsEnabled) { + Log.InternalLog(LogType.Error, _label, msg, LogColors.Error, showStack); + } + } + + public void Exception(Exception ex, bool showStack = true) { + if (!IsEnabled || ex == null) { + return; + } + + var msg = $"Exception: {ex.Message}"; + if (showStack && !string.IsNullOrEmpty(ex.StackTrace)) { + msg += $"\n{ex.StackTrace}"; + } + + Log.InternalLog(LogType.Error, _label, msg, LogColors.Exception, showStack); + } + } + + public static class LogColors { + public const string Info = "#4CAF50"; + public const string Warning = "#CC9A06"; + public const string Error = "#CC423B"; + public const string Exception = "red"; // 可选保留原文 + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/Log.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/Log.cs.meta new file mode 100644 index 0000000..08c60c5 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/Log.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 451867446e034f4194f1319933be9cdd +timeCreated: 1748248695 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/MD5Helper.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/MD5Helper.cs new file mode 100644 index 0000000..ecd2405 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/MD5Helper.cs @@ -0,0 +1,60 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace SGModule.Common.Helper { + public class MD5Helper { + public static string GetFileMD5(string file) { + try { + var fs = new FileStream(file, FileMode.Open); + MD5 md5 = new MD5CryptoServiceProvider(); + var retVal = md5.ComputeHash(fs); + fs.Close(); + var sb = new StringBuilder(); + foreach (var str in retVal) { + sb.Append(str.ToString("X2")); + } + + return sb.ToString(); + } + catch (Exception ex) { + throw new Exception("GetFileMD5 fail error: " + ex.Message); + } + } + + /// + /// 获取字符串的MD5值 + /// + public static string GetStringMD5(string str) { + if (string.IsNullOrEmpty(str)) { + return null; + } + + MD5 md5 = new MD5CryptoServiceProvider(); + var bytResult = md5.ComputeHash(Encoding.UTF8.GetBytes(str)); + var strResult = BitConverter.ToString(bytResult); + strResult = strResult.Replace("-", string.Empty); + return strResult; + } + + public static string MD5String1(string text) { + var buffer = Encoding.Default.GetBytes(text); + var check = new MD5CryptoServiceProvider(); + var somme = check.ComputeHash(buffer); + var result = new StringBuilder(); + foreach (var a in somme) { + var value = a.ToString("X"); + if (a < 16) { + result.Append(0); + result.Append(value); + } + else { + result.Append(value); + } + } + + return result.ToString().ToLower(); + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/MD5Helper.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/MD5Helper.cs.meta new file mode 100644 index 0000000..4f46bc4 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/MD5Helper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0d8c3bafdc1d41ee87e8c72f54f42007 +timeCreated: 1731309631 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/ModuleVersion.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/ModuleVersion.cs new file mode 100644 index 0000000..7a07421 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/ModuleVersion.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.IO; +using UnityEngine; + +namespace SGModule.Common.Helper { + public static class ModuleVersion { + public static void Show() { + var path = Path.Combine(Application.dataPath, "../gupm.toml"); + + if (!File.Exists(path)) { + Log.Warning("Submodules", $"找不到配置文件: {path}"); + return; + } + + var insideSubmodules = false; + var submodules = new Dictionary(); + var lines = File.ReadAllLines(path); + + foreach (var rawLine in lines) { + var line = rawLine.Trim(); + + // 进入 [Submodules] 区块 + if (!insideSubmodules) { + if (line.Equals("[Submodules]", StringComparison.OrdinalIgnoreCase)) { + insideSubmodules = true; + } + + continue; + } + + // 如果遇到下一个区块就退出(可选) + if (line.StartsWith("[") && line.EndsWith("]")) { + break; + } + + // 忽略空行和注释 + if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#")) { + continue; + } + + // 使用 = 来切分 + var parts = line.Split(new[] { '=' }, 2); + if (parts.Length != 2) { + continue; + } + + var key = parts[0].Trim(); + var value = parts[1].Trim().Trim('"'); + + submodules[key] = value; + } + + foreach (var kv in submodules) { + Log.Info("Submodules", $"{kv.Key} : {kv.Value}"); + } + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/ModuleVersion.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/ModuleVersion.cs.meta new file mode 100644 index 0000000..62727d7 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/ModuleVersion.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b578d006bf7b47b8a7ec2d5b48a53c2b +timeCreated: 1748947020 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/RandomHelper.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/RandomHelper.cs new file mode 100644 index 0000000..c81b7d4 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/RandomHelper.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using SGModule.Common.Interface; + +namespace SGModule.Common.Helper { + public static class RandomHelper { + private static readonly Random _random = new(); + + public static T RandomByWeight(IList items, T fallback) where T : class, IWeighted { + var totalWeight = items.Sum(item => item.Weight); + if (totalWeight <= 0) { + return fallback; + } + + var roll = _random.Next(0, totalWeight); + var cumulative = 0; + + foreach (var item in items) { + cumulative += item.Weight; + if (roll < cumulative) { + return item; + } + } + + return items.Last(); + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/RandomHelper.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/RandomHelper.cs.meta new file mode 100644 index 0000000..7856ebe --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/RandomHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 45bcdda204c1483c84aaaf0d6ec0f251 +timeCreated: 1749198281 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/SerializeHelper.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/SerializeHelper.cs new file mode 100644 index 0000000..ea39b61 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/SerializeHelper.cs @@ -0,0 +1,40 @@ +using System; +using Newtonsoft.Json; + +namespace SGModule.Common.Helper { + public static class SerializeHelper { + private static readonly JsonSerializerSettings _defaultUseJsonSettings = new() { + Formatting = Formatting.None, + DateFormatString = "yyyy/MM/dd HH:mm:ss" + }; + + private static readonly JsonSerializerSettings _jsonIndentedSettings = new() { + Formatting = Formatting.Indented, + DateFormatString = "yyyy/MM/dd HH:mm:ss" + }; + + static SerializeHelper() { + JsonConvert.DefaultSettings = () => _defaultUseJsonSettings; + } + + public static string ToJson(object obj) { + return JsonConvert.SerializeObject(obj, _defaultUseJsonSettings); + } + + public static string ToJsonIndented(object obj) { + return JsonConvert.SerializeObject(obj, _jsonIndentedSettings); + } + + public static string ToJson(object obj, Type type) { + return JsonConvert.SerializeObject(obj, type, _defaultUseJsonSettings); + } + + public static string ToJson(object obj) { + return ToJson(obj, typeof(T)); + } + + public static T ToObject(string json) { + return JsonConvert.DeserializeObject(json); + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/SerializeHelper.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/SerializeHelper.cs.meta new file mode 100644 index 0000000..0804aa8 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/SerializeHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9879900ede554789a516d519840ef577 +timeCreated: 1731311911 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/TimeHelper.cs b/Assets/SGModule/Common/SGModule/Scripts/Helper/TimeHelper.cs new file mode 100644 index 0000000..2596739 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/TimeHelper.cs @@ -0,0 +1,54 @@ +using System; + +namespace SGModule.Common.Helper { + public static class TimeHelper { + /// + /// 将 Unix 时间戳转换为本地时间 + /// + /// 时间戳(秒) + /// 可读的本地时间字符串 + public static string ConvertToLocalTime(long timestamp) { + // Unix 时间戳起始时间 + var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + // 转换为本地时间 + var localTime = epoch.AddSeconds(timestamp).ToLocalTime(); + + return localTime.ToString("yyyy-MM-dd HH:mm:ss"); + } + + /// + /// 将 Unix 时间戳转换为 UTC 时间 + /// + /// 时间戳(秒) + /// 可读的 UTC 时间字符串 + public static string ConvertToUTCTime(long timestamp) { + // Unix 时间戳起始时间 + var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + // 转换为 UTC 时间 + var utcTime = epoch.AddSeconds(timestamp); + + return utcTime.ToString("yyyy-MM-dd HH:mm:ss"); + } + + public static string FormatTime(int totalSeconds) { + if (totalSeconds < 60) { + return $"{totalSeconds}s"; // 小于60秒,直接显示秒 + } + + if (totalSeconds < 3600) { + var minutes = totalSeconds / 60; + var seconds = totalSeconds % 60; + return $"{minutes}m {seconds}s"; // 小于1小时,显示分秒 + } + else { + var hours = totalSeconds / 3600; + var remainingSeconds = totalSeconds % 3600; + var minutes = remainingSeconds / 60; + var seconds = remainingSeconds % 60; + return $"{hours}h {minutes}m {seconds}s"; // 超过1小时,显示时分秒 + } + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Helper/TimeHelper.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Helper/TimeHelper.cs.meta new file mode 100644 index 0000000..ababd77 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Helper/TimeHelper.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f65b3d4cbd7c456bb9373c261aef0932 +timeCreated: 1731662312 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Interface.meta b/Assets/SGModule/Common/SGModule/Scripts/Interface.meta new file mode 100644 index 0000000..5001e38 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Interface.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f8e5eb462e8045f19663f3e4bb29c5e6 +timeCreated: 1749198053 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Interface/IWeighted.cs b/Assets/SGModule/Common/SGModule/Scripts/Interface/IWeighted.cs new file mode 100644 index 0000000..e6938c6 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Interface/IWeighted.cs @@ -0,0 +1,7 @@ +namespace SGModule.Common.Interface { + public interface IWeighted { + int Weight { + get; + } + } +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Interface/IWeighted.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Interface/IWeighted.cs.meta new file mode 100644 index 0000000..7ba79fa --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Interface/IWeighted.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c91fe8993478411f8d6a81ce2074a336 +timeCreated: 1749198110 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/Keychain.meta b/Assets/SGModule/Common/SGModule/Scripts/Keychain.meta new file mode 100644 index 0000000..626e213 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Keychain.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 26e8d993c96816f42bf326d832cd0f68 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Scripts/Keychain/Keychain.cs b/Assets/SGModule/Common/SGModule/Scripts/Keychain/Keychain.cs new file mode 100644 index 0000000..9933e8f --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Keychain/Keychain.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.InteropServices; +using SGModule.Common.Helper; + +public static class Keychain { + public static bool Save(string key, string value) { +#if UNITY_IOS + return SaveToKeychain(key, value); +#endif + Log.Common.Warning("Keychain is only supported on iOS."); + return false; + } + + public static string Get(string key) { +#if UNITY_IOS + var resultPtr = GetFromKeychain(key); + if (resultPtr != IntPtr.Zero) { + var result = Marshal.PtrToStringAuto(resultPtr); + return result; + } + + return null; +#endif + Log.Common.Warning("Keychain is only supported on iOS."); + return null; + } + + public static bool Delete(string key) { +#if UNITY_IOS + return DeleteFromKeychain(key); +#endif + Log.Common.Warning("Keychain is only supported on iOS."); + return false; + } +#if UNITY_IOS + + [DllImport("__Internal")] + private static extern bool SaveToKeychain(string key, string value); + + [DllImport("__Internal")] + private static extern IntPtr GetFromKeychain(string key); + + [DllImport("__Internal")] + private static extern bool DeleteFromKeychain(string key); +#endif +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/Keychain/Keychain.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/Keychain/Keychain.cs.meta new file mode 100644 index 0000000..924e33c --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/Keychain/Keychain.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: acd6a7aa2034443549cb53d6ae963143 \ No newline at end of file diff --git a/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects.meta b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects.meta new file mode 100644 index 0000000..799cc04 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5d82ad3c27862f549a7cd0bc3f5b4e9a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/GameConfig.cs b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/GameConfig.cs new file mode 100644 index 0000000..f2cba7e --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/GameConfig.cs @@ -0,0 +1,24 @@ +using UnityEngine; + +// [CreateAssetMenu(fileName = "GameConfig", menuName = "GameData/GameConfig")] +public class GameConfig : ScriptableObject { + [Header("全局配置")] [HideInInspector] public string packageName; + + +#if GAME_RELEASE + private const bool _isRelease = true; +#else + private const bool _isRelease = false; +#endif + + public bool isRelease => _isRelease; + + private bool _enabledLog = true; + + public bool enabledLog { + get => !isRelease && _enabledLog; + set => _enabledLog = !isRelease && value; + } + + [HideInInspector] public bool hardwareAcceleration = true; +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/GameConfig.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/GameConfig.cs.meta new file mode 100644 index 0000000..d7b22ee --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/GameConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c836612725633cc4093d7ac06e7d9ef1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/NetworkConfig.cs b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/NetworkConfig.cs new file mode 100644 index 0000000..13db33c --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/NetworkConfig.cs @@ -0,0 +1,18 @@ +using UnityEngine; + +// [CreateAssetMenu(fileName = "NetworkConfig", menuName = "GameData/NetworkConfig")] +public class NetworkConfig : ScriptableObject { + [Header("Network Config")] [Header("显示日志")] + public bool showNetworkLog = true; + + [Header("Url配置")] public string debugHost; + + public string releaseHost; + + [Header("连接模式")] public ConnectionMode connectionMode = ConnectionMode.Http; +} + +public enum ConnectionMode { + Http, // 基于 HTTP 协议的链接 + WebSocket // 基于 WebSocket 协议的链接 +} diff --git a/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/NetworkConfig.cs.meta b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/NetworkConfig.cs.meta new file mode 100644 index 0000000..ff90ba4 --- /dev/null +++ b/Assets/SGModule/Common/SGModule/Scripts/ScriptableObjects/NetworkConfig.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6161e194ecfb437f89a55349867a492e +timeCreated: 1731317249 \ No newline at end of file diff --git a/Assets/SGModule/ConfigLoader.meta b/Assets/SGModule/ConfigLoader.meta new file mode 100644 index 0000000..e827ffb --- /dev/null +++ b/Assets/SGModule/ConfigLoader.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1126f8fc6cfff6941a90361e0d733577 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ConfigLoader/README.md b/Assets/SGModule/ConfigLoader/README.md new file mode 100644 index 0000000..fe316e7 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/README.md @@ -0,0 +1,70 @@ +# ⚙️ ConfigLoader 配置加载模块 + +此模块负责配置文件的加载与检测,依赖于 `Common` 通用模块,请确保已安装该模块。 + +### 主要功能 + +- 📂 配置文件加载 +- 🔍 配置字段缺失检测 +- ❌ 配置字段冗余检测 +- ⚙️ 自动化插件安装 +- 📝 日志标准化输出 + +------ + +## ⚠️ 注意事项 + +导入项目后,会弹出插件安装提示框。点击“确定”后,插件将自动安装;若点击“取消”,脚本重新编译时仍会再次弹出提示。 + +- 插件安装需要一定时间,请耐心等待。安装完成后会有弹窗提示。 +- 安装完成后,会自动生成配置文件夹 `Configs`,请将游戏配置文件复制到此文件夹中。 +- **请勿修改配置文件名**。如需替换配置文件,请先删除旧文件,确保文件夹中每个配置只有一份。 +- 游戏首次运行时,会自动将该文件夹复制到游戏的数据存储位置。 + +------ + +## 🚀 使用指南 + +在登录成功后,调用 `ConfigLoader` 的 `Init` 方法传入所需参数,具体参数请查看方法注释。 + +> 注意: +> +> - **List 类型**的配置需继承 `ConfigModel`,不再需要之前的 `IDataList` 接口。 +> - **非 List 类型**配置继承 `ConfigModel`。 + +### 初始化示例 + +```csharp +var loginModel = NetworkKit.Instance.GetLoginModel(); +ConfigLoader.Instance.Init( + loginModel.setting, + loginModel.cdn_url, + new List { + new CommonModel("Common"), + new SignDailyRewardModel("SignDailyReward"), + new TurntableModel("turntable"), + // 其它配置... + }, + state => { + Debug.Log($"配置加载状态: {state}"); + }, + (errorName, message) => { + Debug.LogError($"配置解析错误: {errorName},错误信息:{message}"); + }); +``` + +------ + +## 🔍 读取配置示例 + +```csharp +// 读取基础配置 +var model = ConfigLoader.Instance.GetConfig(); + +// 解析自定义配置 +ConfigLoader.Instance.ParesPersonalizedConfig(new PrizeWheelDataModel("PrizeWheelData"), "prize"); + +// 获取自定义配置 +var personalizedConfig = ConfigLoader.Instance.GetPersonalizedConfig("prize"); +``` + diff --git a/Assets/SGModule/ConfigLoader/README.md.meta b/Assets/SGModule/ConfigLoader/README.md.meta new file mode 100644 index 0000000..0a6c16c --- /dev/null +++ b/Assets/SGModule/ConfigLoader/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b25e03cedceda0f4db9aebc261a5bf0a +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ConfigLoader/SGModule.meta b/Assets/SGModule/ConfigLoader/SGModule.meta new file mode 100644 index 0000000..5f9d9f7 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2c34977ebbc9d4440826289429a2adc3 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ConfigLoader/SGModule/Editor.meta b/Assets/SGModule/ConfigLoader/SGModule/Editor.meta new file mode 100644 index 0000000..9b48cdb --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c03491d9ce1584a408c18056b93f91d2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs b/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs new file mode 100644 index 0000000..574f2a0 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs @@ -0,0 +1,188 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using SGModule.Common.Helper; +using UnityEditor; +using UnityEditor.PackageManager; +using UnityEditor.PackageManager.Requests; +using PackageInfo = UnityEditor.PackageManager.PackageInfo; +#if USE_ADDRESSABLES +using UnityEditor.AddressableAssets; +#endif + +namespace SGModule.Editor { + [InitializeOnLoad] + public static class AddressablesManager { + private const string AddressablesPackageName = "com.unity.addressables"; + private const string AddressablesSymbol = "USE_ADDRESSABLES"; + private static AddRequest _addRequest; + + // 安装标记,避免重复弹窗 + private static bool _isInstallingAddressables; + + static AddressablesManager() { + EditorApplication.projectChanged += OnProjectChanged; // 监听项目变更 + + CheckAndSetupAddressables(); + } + + private static string DefaultConfigsPath => "Assets/Configs"; // 默认的 Addressables 配置路径 + + private static void CheckAndSetupAddressables() { + if (IsAddressablesInstalled()) { + Log.Info("ConfigLoader", "Addressables 已安装,正在初始化..."); + + AddScriptingDefineSymbol(AddressablesSymbol); + +#if USE_ADDRESSABLES + EnsureAddressablesConfigured(); +#endif + } + else { + RemoveScriptingDefineSymbol(AddressablesSymbol); + if (!_isInstallingAddressables) { + PromptToInstallAddressables(); + } + } + } + + private static bool IsAddressablesInstalled() { + return PackageInfo.GetAllRegisteredPackages().Any(package => package.name == AddressablesPackageName); + } + + private static void PromptToInstallAddressables() { + var install = EditorUtility.DisplayDialog( + "Addressables 未安装", + "当前插件依赖 Addressables 功能,请安装以确保正常使用。\n\n是否立即安装 Addressables?", + "安装", + "取消"); + + if (install) { + InstallAddressables(); + } + else { + Log.Warning("ConfigLoader", "用户取消安装 Addressables,部分功能可能无法正常使用!"); + } + } + + private static void InstallAddressables() { + if (_isInstallingAddressables) { + return; // 防止重复安装 + } + + Log.Info("ConfigLoader", "开始安装 Addressables..."); + + _isInstallingAddressables = true; // 标记正在安装,避免重复弹窗 + _addRequest = Client.Add(AddressablesPackageName); + + EditorApplication.update += MonitorAddRequest; + } + + private static void MonitorAddRequest() { + if (_addRequest == null || !_addRequest.IsCompleted) { + return; + } + + EditorApplication.update -= MonitorAddRequest; + + if (_addRequest.Status == StatusCode.Success) { + Log.Info("ConfigLoader", "Addressables 安装成功!"); + + EditorUtility.DisplayDialog("安装完成", "Addressables 安装成功,请稍候等待 Unity 刷新。", "确定"); + + CheckAndSetupAddressables(); + } + else if (_addRequest.Status >= StatusCode.Failure) { + Log.Error("ConfigLoader", $"安装 Addressables 失败:{_addRequest.Error.message}"); + + EditorUtility.DisplayDialog("安装失败", $"安装 Addressables 失败:{_addRequest.Error.message}", "确定"); + } + + _isInstallingAddressables = false; // 重置标记 + } + + private static void AddScriptingDefineSymbol(string symbol) { + var symbols = new List(PlayerSettings + .GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup).Split(';')); + if (symbols.Contains(symbol)) { + return; + } + + + symbols.Add(symbol); + PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, + string.Join(";", symbols)); + Log.Info("ConfigLoader", $"已添加脚本定义符号: {symbol}"); + } + + private static void RemoveScriptingDefineSymbol(string symbol) { + var symbols = new List(PlayerSettings + .GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup).Split(';')); + if (symbols.Contains(symbol)) { + symbols.Remove(symbol); + PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, + string.Join(";", symbols)); + + Log.Info("ConfigLoader", $"已移除脚本定义符号: {symbol}"); + } + } + + private static void OnProjectChanged() { + Log.Info("ConfigLoader", "检测到项目变更,重新检查 Addressables 状态..."); + + CheckAndSetupAddressables(); + } + +#if USE_ADDRESSABLES + private static void EnsureAddressablesConfigured() { + var settings = AddressableAssetSettingsDefaultObject.Settings; + + if (settings == null) { + Log.Info("ConfigLoader", "正在初始化 Addressables 设置..."); + + settings = AddressableAssetSettingsDefaultObject.GetSettings(true); // 自动创建配置 + } + + // 确保默认的 Configs 文件夹存在并被添加到 Addressables + var needRefresh = false; + if (!Directory.Exists(DefaultConfigsPath)) { + Directory.CreateDirectory(DefaultConfigsPath); + Log.Info("ConfigLoader", $"已创建文件夹: {DefaultConfigsPath}"); + + needRefresh = true; + } + + if (!IsFolderInAddressables(DefaultConfigsPath)) { + var guid = AssetDatabase.AssetPathToGUID(DefaultConfigsPath); + var group = settings.DefaultGroup; + settings.CreateOrMoveEntry(guid, group)?.SetLabel("config", true, true); + needRefresh = true; + } + + if (needRefresh) { + AssetDatabase.Refresh(); + } + } + + private static bool IsFolderInAddressables(string folderPath) { + var settings = AddressableAssetSettingsDefaultObject.Settings; + foreach (var group in settings.groups) + { + if (group) + { + foreach (var entry in group.entries) + { + if (AssetDatabase.GUIDToAssetPath(entry.guid) == folderPath) + { + return true; + } + } + } + } + + + return false; + } +#endif + } +} diff --git a/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs.meta b/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs.meta new file mode 100644 index 0000000..784773a --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Editor/AddressablesManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 383ac67f695b4c6e94ba988c9303cd5b +timeCreated: 1733734050 \ No newline at end of file diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts.meta b/Assets/SGModule/ConfigLoader/SGModule/Scripts.meta new file mode 100644 index 0000000..91bf863 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 34c8928adac69ec44ac63b385ef330d1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader.meta b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader.meta new file mode 100644 index 0000000..84dbf2c --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 53a14b320d93d7c439c59c8190a874ab +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigLoader.cs b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigLoader.cs new file mode 100644 index 0000000..684acb3 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigLoader.cs @@ -0,0 +1,418 @@ +using System; +using System.Collections.Generic; +using System.IO; +using JetBrains.Annotations; +using SGModule.Common; +using SGModule.Common.Base; +using SGModule.Common.Extensions; +using SGModule.Common.Helper; +using UnityEngine; +using UnityEngine.Events; + +namespace SGModule.ConfigLoader +{ + public enum ConfigLoaderState + { + None, + Failed, + JsonEmptyError, + Successful + } + + public class ConfigLoader : SingletonMonoBehaviour + { + private const int MaxErrorCount = 6; + private const string ConfigFileNameKey = "ConfigFileName"; + private readonly Dictionary _configData = new(); + private readonly Dictionary _userDefinedConfig = new(); + + private string _cdnConfigFileName; + private string _cdnUrl; + + private string _configJson; + + private int _initConfigErrorCount; + + private bool _isConfigLoaded; + private Dictionary _jsonDictionary = new(); + + // 暴露只读接口 + public IReadOnlyDictionary JsonDictionary => _jsonDictionary; + + /// + /// 初始化配置模块方法 + /// + /// 登录获得的配置文件名 + /// 下载配置的地址 + /// 需要初始化解析的配置 + /// 配置加载回调 + /// 配置解析错误回调 + public void Init(string cdnConfigFileName, string cdnUrl, List configs, + UnityAction configLoadCallback = null, + UnityAction parseErrorHandler = null) + { + _cdnConfigFileName = cdnConfigFileName; + _cdnUrl = cdnUrl; + + IsInitComplete = true; + + CheckConfigFile(state => + { + if (state == ConfigLoaderState.Successful) + { + InitConfigList(configs, parseErrorHandler); + } + + configLoadCallback?.Invoke(state); + }); + } + + /// + /// 批量解析配置文件 + /// + /// + /// + private void InitConfigList(List configs, UnityAction errorCallback = null) + { + foreach (var config in configs) + { + Pares(config, errorCallback); + } + } + + /// + /// 检查并加载配置文件 + /// + /// + private void CheckConfigFile(UnityAction callback) + { + if (!IsInitComplete) + { + Log.ConfigLoader.Warning("配置加载模块模块未初始化"); + + return; + } + + if (_initConfigErrorCount > MaxErrorCount) + { + callback?.Invoke(ConfigLoaderState.Failed); + return; + } + + if (IsFirstLaunch()) + { + FirstLaunchCopyConfig(callback); // 进行首次启动的操作 + return; + } + + bool needDownloadConfigFile = false; + if ((!string.IsNullOrEmpty(_cdnConfigFileName)) && PlayerPrefs.GetString(ConfigFileNameKey, "") != _cdnConfigFileName) needDownloadConfigFile = true; + //需要下载配置的话等待下载更新 + if (needDownloadConfigFile) + { + DownloadConfig(callback); + return; + } + + ReadLocalConfig(callback); + } + + /// + /// 判断是首次打开游戏 + /// + /// + private bool IsFirstLaunch() + { + return !PlayerPrefs.HasKey("FirstLaunch"); + } + + /// + /// 设置首次启动游戏 + /// + private void SetFirstLaunch() + { + PlayerPrefs.SetInt("FirstLaunch", 1); + } + + /// + /// 首次启动游戏拷贝配置文件到PersistentData目录下 + /// + private void FirstLaunchCopyConfig(UnityAction callback) + { + SetFirstLaunch(); + FileNetworkManager.Instance.CopyStreamingAssetsToPersistentDataPath(result => + { + var isSuccess = false; + if (result) + { + var names = + FileNetworkManager.Instance.GetFileNamesFromPersistentDataPath(FileNetworkManager.FolderName); + if (names.Length > 0) + { + PlayerPrefs.SetString(ConfigFileNameKey, names[0]); //项目当前文件中的配置版本 + isSuccess = true; + } + } + else + { + Log.ConfigLoader.Error("拷贝文件失败 请检查Configs文件夹是否有配置文件"); + } + + if (!isSuccess) + { + _initConfigErrorCount++; + } + + CheckConfigFile(callback); + }); + } + + /// + /// 下载配置文件 + /// + private void DownloadConfig(UnityAction callback) + { + FileNetworkManager.Instance.ReadData($"{_cdnUrl}/config/{_cdnConfigFileName}", result => + { + if (!string.IsNullOrEmpty(result)) + { + PlayerPrefs.SetString(ConfigFileNameKey, _cdnConfigFileName); //更新当前配置文件文件名 + FileNetworkManager.Instance.WriteToPersistentData(FileNetworkManager.Instance.GetConfigFOlderPath(), + _cdnConfigFileName, result); + ReloadConfig(result, callback); + } + else + { + _initConfigErrorCount++; + Log.ConfigLoader.Error("下载配置文件失败"); + ReadLocalConfig(callback); + } + }); + } + + /// + /// 读取本地配置文件 + /// + private void ReadLocalConfig(UnityAction callback) + { + var savedCfgName = PlayerPrefs.GetString(ConfigFileNameKey); + var path = Path.Combine(FileNetworkManager.Instance.GetConfigFOlderPath(), savedCfgName); + FileNetworkManager.Instance.ReadData(path, result => + { + if (!string.IsNullOrEmpty(result)) + { + ReloadConfig(result, callback); + } + else + { + _initConfigErrorCount++; + Log.ConfigLoader.Error("读取本地数据异常"); + + + //读取本地配置文件失败,重新从默认位置拷贝原始配置文件到配置文件夹下 + FirstLaunchCopyConfig(callback); + } + }); + } + + /// + /// 检查是否有新的配置 + /// + /// + private bool HasNewConfig() + { + if (!PlayerPrefs.HasKey(ConfigFileNameKey)) + { + return true; + } + + var savedCfgName = PlayerPrefs.GetString(ConfigFileNameKey); + var needDownloadConfigFile = false; + + if (!string.IsNullOrEmpty(_cdnConfigFileName)) + { + //如果本地Player Prefs里没有保存配置文件名 + if (string.IsNullOrEmpty(savedCfgName)) + { + needDownloadConfigFile = true; + } + else + { + //与CDN上的对比名称 + if (!savedCfgName.Equals(_cdnConfigFileName)) + { + needDownloadConfigFile = true; + } + } + } + + return needDownloadConfigFile; + } + + /// + /// 重新加载配置 + /// + /// + /// + private void ReloadConfig(string json, [NotNull] UnityAction callback) + { + ValidateConfigFile(json, callback); + } + + /// + /// 检查json + /// + /// + /// + private void ValidateConfigFile(string json, UnityAction callback) + { + if (json.IsNullOrWhiteSpace()) + { + callback?.Invoke(ConfigLoaderState.JsonEmptyError); + return; + } + + if (!json.StartsWith("{")) + { + var gameConfig = ConfigManager.GameConfig; + json = Cryptor.Decrypt(json, gameConfig.packageName); + } + + _configJson = json; + var dictionary = SerializeHelper.ToObject>(_configJson); + _jsonDictionary = dictionary; + + _isConfigLoaded = true; + callback?.Invoke(ConfigLoaderState.Successful); + + + // ParseGameConfig(dictionary, callback); + } + + + /// + /// 解析配置文件 + /// + /// 配置数据结构 + /// + /// + /// + public T ParseNewConfig(T config, UnityAction errorCallback = null) where T : ConfigModel + { + if (!_isConfigLoaded) + { + Log.ConfigLoader.Warning("配置文件未加载完成"); + return default; + } + + if (_configData.TryGetValue(config.GetType(), out var obj)) + { + Log.ConfigLoader.Warning("当前配置已经成功解析了"); + return obj as T; + } + + return Pares(config, errorCallback) as T; + } + + /// + /// 解析配置文件 + /// + /// 配置数据结构 + /// + /// 是否保存起来 + /// + private ConfigModel Pares(ConfigModel config, UnityAction errorCallback = null, + bool addToConfigData = true) + { + var configModel = config.Parse(JsonDictionary); + if (configModel != null) + { + if (addToConfigData) + { + var type = configModel.GetType(); + // if (!_configData.ContainsKey(type)) + // { + // _configData.Add(type, configModel); + // } + // else + // { + // Debug.LogWarning($"请注意,重复解析配置文件{type}"); + // _configData[type] = configModel; + // } + + _configData[type] = configModel; + } + } + else + { + errorCallback?.Invoke(config.GetType().Name, "解析异常"); + Log.ConfigLoader.Warning("解析异常"); + } + + return configModel as ConfigModel; + } + + /// + /// 解析自定义名称配置文件,将配置解析为自定义名称的配置文件并保存 + /// + /// 配置数据结构 + /// 数据结构类型 + /// + /// + public bool ParesPersonalizedConfig(ConfigModel config, string configName, + UnityAction errorCallback = null) + { + if (_userDefinedConfig.ContainsKey(configName)) + { + Log.ConfigLoader.Warning("存在相同名称的自定义配置"); + return false; + } + + var configModel = Pares(config, errorCallback, false); + if (configModel != null) + { + _userDefinedConfig.Add(configName, configModel); + return true; + } + + Log.ConfigLoader.Warning($"解析配置重新异常{config} {configName}"); + + return false; + } + + + /// + /// 获取自定义配置数据 + /// + /// 配置名称 + /// 对应数据结构 + /// + public T GetPersonalizedConfig(string configName) + { + if (_userDefinedConfig.TryGetValue(configName, out var value)) + { + if (value is T configModel) + { + return configModel; + } + + Log.ConfigLoader.Warning($"有{configName}的自定义配置,但类型不对,期望类型是{typeof(T).Name} 现有类型{value.GetType().Name} "); + + return default; + } + + return default; + } + + public T GetConfig() + { + return _configData.TryGetValue(typeof(T), out var value) ? (T)value : default; + } + + public void AddConfig(ConfigModel configModel) + { + var type = configModel.GetType(); + _configData[type] = configModel; + } + } +} diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigLoader.cs.meta b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigLoader.cs.meta new file mode 100644 index 0000000..c9c0141 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/ConfigLoader.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0cda67e479db4e8fbd10667fba04b197 +timeCreated: 1731984367 \ No newline at end of file diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs new file mode 100644 index 0000000..a9270fd --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs @@ -0,0 +1,236 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using SGModule.Common.Base; +using SGModule.Common.Helper; +using UnityEngine; +using UnityEngine.AddressableAssets; +using UnityEngine.Networking; +using UnityEngine.ResourceManagement.AsyncOperations; +#if UNITY_EDITOR +using UnityEditor; +#endif + +#if USE_ADDRESSABLES +#endif + +namespace SGModule.ConfigLoader { + public class FileNetworkManager : SingletonMonoBehaviour { + public const string FolderName = "Configs"; + private const string FolderLabel = "config"; + private string _configFolderPath; + + protected override void Awake() { + base.Awake(); + + _configFolderPath = Path.Combine(Application.persistentDataPath, FolderName); + } + + public string GetConfigFOlderPath() { + return _configFolderPath; + } + + // 示例解析文件列表方法(你可以根据实际需求实现) + private List ParseFileList(string data) { + // 假设 data 是文件列表的文本,解析文件名 + // 根据实际情况解析,例如通过换行符分割 + return data.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).ToList(); + } + + public void CopyStreamingAssetsToPersistentDataPath(Action onComplete = null) { + // 如果目标文件夹不存在,创建它 + if (!Directory.Exists(_configFolderPath)) { + Directory.CreateDirectory(_configFolderPath); + } + + StartCoroutine(CopyFile(onComplete)); + } + + private void HandleInitializationError() { + // 检查文件是否存在 + var path = $"{Application.dataPath}/Library/com.unity.addressables/aa/Android/settings.json"; + if (!File.Exists(path)) { + Log.ConfigLoader.Warning( + $"Settings file not found at: {path}. Rebuilding Addressables may be required."); + } + + + // 提示用户或执行其他逻辑 + // 比如:显示弹窗或退出程序 + } + + private IEnumerator CopyFile(Action onComplete = null) { +#if USE_ADDRESSABLES + var handle = Addressables.LoadResourceLocationsAsync(FolderLabel); + + yield return handle; + + if (handle.Status == AsyncOperationStatus.Succeeded) { + // 查找以 ".json" 结尾的文件 + var jsonLocation = handle.Result.FirstOrDefault(loc => loc.PrimaryKey.EndsWith(".txt")); + if (jsonLocation != null) { + var jsonFileName = Path.GetFileName(jsonLocation.PrimaryKey); + // 加载 JSON 文件 + var textAssetAsync = Addressables.LoadAssetAsync(jsonLocation); + + yield return textAssetAsync; + + if (textAssetAsync.Status == AsyncOperationStatus.Succeeded) { + var jsonFile = textAssetAsync.Result; + Log.ConfigLoader.Info($"Loaded JSON Name:{jsonFileName} content: " + jsonFile.text); + + + var destFilePath = Path.Combine(_configFolderPath, jsonFileName); + File.WriteAllBytes(destFilePath, jsonFile.bytes); + onComplete?.Invoke(true); + } + else { + Log.ConfigLoader.Error("Failed to load JSON file"); + + onComplete?.Invoke(false); + } + } + else { + Log.ConfigLoader.Error("No JSON file found in folder"); + + onComplete?.Invoke(false); + } + } + else { + Log.ConfigLoader.Error("Failed to load folder resources"); + + onComplete?.Invoke(false); + } +#else + Log.Error( "没有 Addressables 插件,请检查 "); + yield break; +#endif + } + + private IEnumerator CopyFile(string sourceFile, string destFile, Action onComplete = null) { + var filePath = "file://" + sourceFile; + + using (var www = UnityWebRequest.Get(filePath)) { + yield return www.SendWebRequest(); + + if (www.result == UnityWebRequest.Result.Success) { + File.WriteAllBytes(destFile, www.downloadHandler.data); + Log.ConfigLoader.Info($"File copied to {destFile}"); + onComplete?.Invoke(true); + } + else { + Log.ConfigLoader.Error("Failed to copy file: " + www.error); + + onComplete?.Invoke(false); + } + } + } + + /// + /// 读取或下载 + /// + /// + /// + public void ReadData(string path, Action callback) { + StartCoroutine(ReadDataEnumerator(path, callback)); + } + + /// + /// 读取或下载 + /// + /// + /// + /// + private IEnumerator ReadDataEnumerator(string path, Action callback) { + string fullPath; + + // 判断是网络URL还是本地文件路径 + if (path.StartsWith("http://") || path.StartsWith("https://")) { + fullPath = path; // 网络URL +#if UNITY_EDITOR + if (path.StartsWith("http://") && PlayerSettings.insecureHttpOption == InsecureHttpOption.NotAllowed) { + Log.ConfigLoader.Error("发起了 HTTP 链接,但设置了不允许非Https连接,请检查设置!!!"); + + callback?.Invoke(null); + yield break; + } +#endif + } + else { + // 本地文件路径 + fullPath = "file://" + path; + } + + // 使用UnityWebRequest读取数据 + using (var webRequest = UnityWebRequest.Get(fullPath)) { + yield return webRequest.SendWebRequest(); + + if (webRequest.result == UnityWebRequest.Result.ConnectionError || + webRequest.result == UnityWebRequest.Result.ProtocolError) { + Log.ConfigLoader.Error($"Error while reading file: {webRequest.error} path: {fullPath}"); + + callback?.Invoke(null); // 返回null表示出错 + } + else { + var data = webRequest.downloadHandler.text; + Log.ConfigLoader.Info($"Data read successfully:\n {data}"); + + callback?.Invoke(data); // 通过回调传出数据 + } + } + } + + /// + /// 将内容写入指定文件,并删除原有文件。 + /// + /// 文件夹名称 + /// 文件名称 + /// 要写入的内容 + public void WriteToPersistentData(string folderName, string fileName, string content) { + // 获取持久化数据路径 + var folderPath = Path.Combine(Application.persistentDataPath, folderName); + + // 如果文件夹不存在,则创建它 + if (!Directory.Exists(folderPath)) { + Directory.CreateDirectory(folderPath); + } + + // 删除原有文件 + var existingFiles = Directory.GetFiles(folderPath); + foreach (var file in existingFiles) { + File.Delete(file); + } + + // 完整文件路径 + var filePath = Path.Combine(folderPath, fileName); + + // 写入新文件 + File.WriteAllText(filePath, content); + + Log.ConfigLoader.Info($"File written to: {filePath}"); + } + + + /// + /// 提取指定目录下所有文件文件名 + /// + /// + /// + public string[] GetFileNamesFromPersistentDataPath(string subdirectory) { + var directoryPath = Path.Combine(Application.persistentDataPath, subdirectory); + + if (Directory.Exists(directoryPath)) + // 获取目录中的所有文件名 + { + return Directory.GetFiles(directoryPath) + .Select(Path.GetFileName) // 只提取文件名 + .ToArray(); + } + + Log.ConfigLoader.Warning($"Directory does not exist: {directoryPath}"); + return Array.Empty(); // 返回空数组 + } + } +} diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs.meta b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs.meta new file mode 100644 index 0000000..34ce11b --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/ConfigLoader/FileNetworkManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 35da25a8aaf547b8accde3b52c38a887 +timeCreated: 1731982304 \ No newline at end of file diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels.meta b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels.meta new file mode 100644 index 0000000..dd94fa8 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ed771f8b80c42a24e8b44eb1aa5d12bd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel.meta b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel.meta new file mode 100644 index 0000000..32197a3 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fb3fbe8a7d2b0ea4c822d6cefeee3708 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/ConfigModel.cs b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/ConfigModel.cs new file mode 100644 index 0000000..2b1421c --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/ConfigModel.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Newtonsoft.Json.Linq; +using SGModule.Common.Helper; +using UnityEngine.Events; + +namespace SGModule.ConfigLoader { + public class ConfigModel : ConfigModel where T : class { + public ConfigModel(string key) : base(key) { + DataList = new List(); + } + + public List DataList { + get; + set; + } + + public override object Parse(IReadOnlyDictionary dictionary, + UnityAction errorCallback = null) { + return LoadConfigList(dictionary, errorCallback); + } + + protected override T1 LoadConfigList(IReadOnlyDictionary dictionary, + UnityAction errorCallback = null) { + ParseConfig(dictionary, out List data, errorCallback); + DataList = data; + return this as T1; + } + } + + public class ConfigModel : ConfigModel { + public ConfigModel(string key) : base(key) { + } + + public override object Parse(IReadOnlyDictionary dictionary, + UnityAction errorCallback = null) { + return LoadConfig(dictionary, errorCallback); + } + } + + public class ConfigModel { + protected readonly string Key; + public bool IsList = false; + + protected ConfigModel(string key) { + Key = key; + } + + public virtual object Parse(IReadOnlyDictionary dictionary, + UnityAction errorCallback = null) { + return null; + } + + protected T LoadConfig(IReadOnlyDictionary dictionary, + UnityAction errorCallback = null) { + if (ParseConfig(dictionary, out T data, errorCallback)) { + return data; + } + + return default; + } + + protected virtual T LoadConfigList(IReadOnlyDictionary dictionary, + UnityAction errorCallback = null) where T : class { + return default; + } + + protected bool ParseConfig(IReadOnlyDictionary dictionary, out T obj, + UnityAction errorCallback = null) { + obj = default; + if (!dictionary.TryGetValue(Key, out var data)) { + errorCallback?.Invoke(Key, "Excel Not find Sheet"); + Log.ConfigLoader.Warning($"Excel Not find Sheet: {Key}"); + return false; + } + + var config = data.ToString(); + try { + var tempObj = SerializeHelper.ToObject(config); + + if (tempObj != null) { +#if !GAME_RELEASE + CheckFields(Key, tempObj, config, FieldCheckType.Missing); + CheckFields(Key, tempObj, config, FieldCheckType.Extra); +#endif + obj = tempObj; + return true; + } + } + catch (Exception ex) { + errorCallback?.Invoke(Key, ex.Message); + // 在此处添加异常处理逻辑,例如日志记录 + Log.ConfigLoader.Error("Error deserializing config data for type " + typeof(T).Name + ": " + ex.Message); + } + + return false; + } + + private void CheckFields(string key, T tempObj, string configValue, FieldCheckType checkType) { + List fields; + + if (tempObj is IEnumerable tempArray) { + fields = CheckFieldsInArray(tempArray.FirstOrDefault()?.GetType(), configValue, checkType); + } + else { + fields = CheckFields(tempObj.GetType(), configValue, checkType); + } + + if (fields.Count <= 0) { + return; + } + + var fieldType = checkType == FieldCheckType.Missing ? "Missing" : "Extra"; + Log.ConfigLoader.Warning($"Excel Sheet: {key} | {fieldType} fields in JSON: " + string.Join(", ", fields.Distinct())); + } + + private static List CheckFieldsInArray(Type objType, string jsonString, FieldCheckType checkType) { + var fields = new List(); + var jsonArray = JArray.Parse(jsonString); + + foreach (var item in jsonArray) { + fields.AddRange(CheckFields(objType, item.ToString(), checkType)); + } + + return fields; + } + + private static List CheckFields(Type objType, string jsonString, FieldCheckType checkType) { + var resultFields = new List(); + + try { + var jsonObject = SerializeHelper.ToObject>(jsonString); + var fieldNames = objType.GetFields(BindingFlags.Public | BindingFlags.Instance) + .Select(f => f.Name) + .ToHashSet(); + + switch (checkType) { + // 检查目标类中存在但 JSON 中缺失的字段 + case FieldCheckType.Missing: + resultFields.AddRange(fieldNames.Where(field => !jsonObject.ContainsKey(field))); + break; + // 检查 JSON 中存在但目标类中不存在的字段 + case FieldCheckType.Extra: + resultFields.AddRange(jsonObject.Keys.Where(key => !fieldNames.Contains(key))); + break; + default: + throw new ArgumentOutOfRangeException(nameof(checkType), checkType, null); + } + } + catch (Exception ex) { + Log.ConfigLoader.Error("Error checking fields for type " + objType.Name + ": " + ex.Message); + } + + return resultFields; + } + + private enum FieldCheckType { + Missing, // 检查缺失字段 + Extra // 检查多余字段 + } + } +} diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/ConfigModel.cs.meta b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/ConfigModel.cs.meta new file mode 100644 index 0000000..2a2c6c5 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/ConfigModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f1224984e6984416abd0e625b5b842ac +timeCreated: 1732095296 \ No newline at end of file diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestListModel.cs b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestListModel.cs new file mode 100644 index 0000000..d63fa22 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestListModel.cs @@ -0,0 +1,13 @@ +namespace SGModule.ConfigLoader { + // 列表形式的 数据Model类, 演示 + public class TestListModel : ConfigModel { + public TestListModel(string key) : base(key) { + } + } + + public class TestListOneModel { + public int Filed1; + public float Filed2; + public int Filed3; + } +} diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestListModel.cs.meta b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestListModel.cs.meta new file mode 100644 index 0000000..4c66428 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestListModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ed458f2acffd4b5b813691f3bd548d50 +timeCreated: 1732007715 \ No newline at end of file diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestSingleModel.cs b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestSingleModel.cs new file mode 100644 index 0000000..790f6d7 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestSingleModel.cs @@ -0,0 +1,10 @@ +namespace SGModule.ConfigLoader { + // KV形式的 数据Model类, 演示 + public class TestSingleModel : ConfigModel { + public int Field1; + public float Field2; + + public TestSingleModel(string key) : base(key) { + } + } +} diff --git a/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestSingleModel.cs.meta b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestSingleModel.cs.meta new file mode 100644 index 0000000..f683a72 --- /dev/null +++ b/Assets/SGModule/ConfigLoader/SGModule/Scripts/DataModels/ConfigModel/TestSingleModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 820d755e7f654e158e3d67e5965cea16 +timeCreated: 1732007669 \ No newline at end of file diff --git a/Assets/SGModule/DataStorage.meta b/Assets/SGModule/DataStorage.meta new file mode 100644 index 0000000..21c95eb --- /dev/null +++ b/Assets/SGModule/DataStorage.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 21d1db70569a5af43a0407e507a37ee7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/README.md b/Assets/SGModule/DataStorage/README.md new file mode 100644 index 0000000..6e07f3d --- /dev/null +++ b/Assets/SGModule/DataStorage/README.md @@ -0,0 +1,139 @@ +# 📦 DataStorage 数据存储模块 + +## ✨ 简介 + +该模块是一个基于 Unity + Easy Save 的本地数据存储系统,具备: + +- ✅ 本地缓存机制(避免频繁磁盘 IO) +- ✅ 自动保存机制(按时间间隔或调用次数) +- ✅ 云同步支持(支持上传 JSON,或导入云端数据) +- ✅ 数据版本控制 +- ✅ 类型安全的 `DataStorage` 封装 +- ✅ 可调试的 GM 工具接口 + +------ + +## 📁 使用说明 + +### 🔹 1. 定义数据键 + +在模块初始化之前,使用 `DataKeyDic.Register` 注册数据键名(通常在 `DataStorage` 构造时自动完成): + +```c# +var playerName = new DataStorage("PlayerName", "Guest"); +playerName.Value = "Pius123"; +``` + +或使用保存回调监听值变化: + +```c# +var coins = new DataStorage("CoinAmount", 0, (oldVal, newVal) => { + Debug.Log($"金币变化:{oldVal} -> {newVal}"); +}); +``` + +### 🔹 2. 保存和读取数据 + +```c# +coins.Value = 100; // 保存数据(自动缓存 + 标记待保存) +var coinAmount = coins.Value; // 从缓存读取(或回退至本地/云端) +coins.Save(); // 强制保存(即使值没变) +``` + +也可直接使用底层 API 操作(不建议): + +```c# +DataManager.Instance.SaveData("Level", 5); +int level = DataManager.Instance.LoadData("Level", 1); +``` + +### 🔹 3. 自动保存逻辑 + +模块会在以下时机自动保存数据到磁盘(使用 Easy Save): + +- ⏱ 每隔 15 秒(可配置) +- 🔁 累积 `SaveData` 达到 20 次(可配置) +- 🚫 App 暂停、退出时 +- 📡 数据版本每增加两次触发一次 `_saveCallback`(用于云上传) + +------ + +## 🌐 云同步支持 + +### ✅ 导出 JSON 上传云端 + +```c# +DataManager.Instance.AddSaveCallback((json, version, onQuit) => { + // 上传 json 到云端,携带版本 version +}); +``` + +每次本地数据保存时(根据频率控制)会自动回调此方法。 + +### ✅ 从云端导入数据 + +```c# +DataManager.Instance.ImportFromJson(jsonFromServer, versionFromServer); +``` + +- 若云端版本 > 本地版本:自动覆盖并保存到本地 +- 若云端版本 < 本地版本:会自动触发 `_saveCallback` 上传本地数据覆盖云端 + +------ + +## 🔧 GM 调试接口(可选) + +调用 `DataManager.Instance.Init()` 可注册 GM 工具按钮: + +- 🧹 清空所有数据 +- 🗂 打印所有缓存键值对 + +------ + +## 🧠 数据结构概览 + +| 类名 | 说明 | +| ---------------------------- | ---------------------------------------------- | +| `DataManager` | 核心数据存储与调度管理(自动保存、版本、缓存) | +| `DataStorage` | 泛型数据封装,提供属性式访问与变更通知 | +| `DataKeyDic` / `DataKeyBase` | 注册键名与云同步标记支持 | +| `ES3` | 第三方 Easy Save 工具(需另行导入) | + + + +------ + +## 📝 配置项 + +| 名称 | 默认值 | 说明 | +| ------------------------- | ------ | -------------------- | +| `InitialAutoSaveInterval` | `15s` | 自动保存时间间隔 | +| `SaveThreshold` | `20次` | 自动保存调用次数阈值 | +| `DataVersion` | `1` | 数据版本号,内部递增 | + + + +------ + +## 🔍 调试建议 + +- 使用 `DebugAllKeys()` 打印所有持久化键值 +- 使用 `DebugCache()` 打印当前缓存数据 +- 检查 `Log.Info/Error` 输出(默认已集成日志标记) + +------ + +## 📦 依赖项 + +- **Easy Save 3**:第三方持久化框架 +- **Newtonsoft.Json**:JSON 序列化与反序列化 +- **自定义框架组件**(如 `SingletonMonoBehaviour`、`Log`、`CommonUtils`、`GMTool` 等) + +------ + +## 📌 注意事项 + +- 云同步仅同步标记为 `CloudSave = true` 的键 +- `DataStorage` 会自动触发注册,但手动操作建议提前注册 +- 非线程安全,不建议多线程并发调用 +- 建议在游戏入口或登录成功后初始化模块并导入云数据 \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/README.md.meta b/Assets/SGModule/DataStorage/README.md.meta new file mode 100644 index 0000000..d0199a4 --- /dev/null +++ b/Assets/SGModule/DataStorage/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ce8e2605318941745b94c3ef79611bf6 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule.meta b/Assets/SGModule/DataStorage/SGModule.meta new file mode 100644 index 0000000..cfaed58 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 030532982443d94449af00fc7ebcaf95 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins.meta b/Assets/SGModule/DataStorage/SGModule/Plugins.meta new file mode 100644 index 0000000..dc423ac --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a855501e0627ebc49add798f2f023815 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3.meta new file mode 100644 index 0000000..58db944 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8174a0d08146bad4dad3838c423e1d5a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor.meta new file mode 100644 index 0000000..9e30c2e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1a8ecc2f6a355324ab2d92ace768db6b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AddES3Prefab.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AddES3Prefab.cs new file mode 100644 index 0000000..9277e27 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AddES3Prefab.cs @@ -0,0 +1,88 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using ES3Internal; +using System.Linq; +using UnityEngine.SceneManagement; + +namespace ES3Editor +{ + public class AddES3Prefab : Editor + { + [MenuItem("GameObject/Easy Save 3/Enable Easy Save for Prefab(s)", false, 1001)] + [MenuItem("Assets/Easy Save 3/Enable Easy Save for Prefab(s)", false, 1001)] + public static void Enable() + { + if (Selection.gameObjects == null || Selection.gameObjects.Length == 0) + return; + + foreach (var obj in Selection.gameObjects) + { + // Don't add the Component to a GameObject which already has it. + if (obj == null || (obj.GetComponent() != null)) + continue; + + var go = obj; + + #if UNITY_2018_3_OR_NEWER + if (PrefabUtility.GetPrefabInstanceStatus(go) != PrefabInstanceStatus.NotAPrefab) + { + go = (GameObject)PrefabUtility.GetCorrespondingObjectFromSource(go); + if (go == null) + continue; + } + #else + if(PrefabUtility.GetPrefabType(go) != PrefabType.Prefab) + { + go = (GameObject)PrefabUtility.GetPrefabParent(go); + if(go == null) + continue; + } + #endif + + var es3Prefab = Undo.AddComponent(go); + es3Prefab.GeneratePrefabReferences(); + + var mgr = ES3ReferenceMgr.GetManagerFromScene(SceneManager.GetActiveScene()); + if (mgr != null) + { + mgr.AddPrefab(es3Prefab); + EditorUtility.SetDirty(mgr); + } + } + } + + [MenuItem("GameObject/Easy Save 3/Enable Easy Save for Prefab(s)", true, 1001)] + [MenuItem("Assets/Easy Save 3/Enable Easy Save for Prefab(s)", true, 1001)] + public static bool Validate() + { + return Selection.gameObjects != null && Selection.gameObjects.Length > 0; + } + } + + public class RemoveES3Prefab : Editor + { + [MenuItem("GameObject/Easy Save 3/Disable Easy Save for Prefab(s)", false, 1001)] + [MenuItem("Assets/Easy Save 3/Disable Easy Save for Prefab(s)", false, 1001)] + public static void Enable() + { + if (Selection.gameObjects == null || Selection.gameObjects.Length == 0) + return; + + foreach (var obj in Selection.gameObjects) + { + var es3prefab = obj.GetComponent(); + if (es3prefab != null) + Undo.DestroyObjectImmediate(es3prefab); + } + } + + [MenuItem("GameObject/Easy Save 3/Disable Easy Save for Prefab(s)", true, 1001)] + [MenuItem("Assets/Easy Save 3/Disable Easy Save for Prefab(s)", true, 1001)] + public static bool Validate() + { + return Selection.gameObjects != null && Selection.gameObjects.Length > 0; + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AddES3Prefab.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AddES3Prefab.cs.meta new file mode 100644 index 0000000..745029b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AddES3Prefab.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 337c3be705d1942b3bf318b5b29aa7cb +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AutoSaveWindow.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AutoSaveWindow.cs new file mode 100644 index 0000000..ffb2ff3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AutoSaveWindow.cs @@ -0,0 +1,369 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using ES3Internal; +using UnityEngine.SceneManagement; +using UnityEditor.SceneManagement; + +namespace ES3Editor +{ + [System.Serializable] + public class AutoSaveWindow : SubWindow + { + public bool showAdvancedSettings = false; + + public ES3AutoSaveMgr mgr = null; + + private HierarchyItem[] hierarchy = null; + public HierarchyItem selected = null; + + private Vector2 hierarchyScrollPosition = Vector2.zero; + + private bool sceneOpen = true; + + private string searchTerm = ""; + + public AutoSaveWindow(EditorWindow window) : base("Auto Save", window) + { + EditorSceneManager.activeSceneChangedInEditMode += ChangedActiveScene; + } + + private void ChangedActiveScene(Scene current, Scene next) + { + mgr = null; + Init(); + } + + public override void OnGUI() + { + Init(); + + if(mgr == null) + { + EditorGUILayout.Space(); + if (GUILayout.Button("Enable Auto Save for this scene")) + mgr = ES3Postprocessor.AddManagerToScene().GetComponent(); + else + return; + } + + var style = EditorStyle.Get; + + using (var changeCheck = new EditorGUI.ChangeCheckScope()) + { + using (var vertical = new EditorGUILayout.VerticalScope(style.areaPadded)) + { + //GUILayout.Label("Settings for current scene", style.heading); + mgr.saveEvent = (ES3AutoSaveMgr.SaveEvent)EditorGUILayout.EnumPopup("Save Event", mgr.saveEvent); + mgr.loadEvent = (ES3AutoSaveMgr.LoadEvent)EditorGUILayout.EnumPopup("Load Event", mgr.loadEvent); + + EditorGUILayout.Space(); + + showAdvancedSettings = EditorGUILayout.Foldout(showAdvancedSettings, "Show Advanced Settings"); + if (showAdvancedSettings) + { + EditorGUI.indentLevel++; + mgr.key = EditorGUILayout.TextField("Key", mgr.key); + ES3SettingsEditor.Draw(mgr.settings); + EditorGUI.indentLevel--; + } + } + + // Display the menu. + using (var horizontal = new EditorGUILayout.HorizontalScope()) + { + if (GUILayout.Button("Scene", sceneOpen ? style.menuButtonSelected : style.menuButton)) + { + sceneOpen = true; + OnFocus(); + } + if (GUILayout.Button("Prefabs", sceneOpen ? style.menuButton : style.menuButtonSelected)) + { + sceneOpen = false; + OnFocus(); + } + } + + //EditorGUILayout.HelpBox("Select the Components you want to be saved.\nTo maximise performance, only select the Components with variables which need persisting.", MessageType.None, true); + + if (hierarchy == null || hierarchy.Length == 0) + { + EditorGUILayout.LabelField("Right-click a prefab and select 'Easy Save 3 > Enable Easy Save for Scene' to enable Auto Save for it.\n\nYour scene will also need to reference this prefab for it to be recognised.", style.area); + return; + } + + using (var scrollView = new EditorGUILayout.ScrollViewScope(hierarchyScrollPosition, style.areaPadded)) + { + hierarchyScrollPosition = scrollView.scrollPosition; + + using (new EditorGUILayout.HorizontalScope(GUILayout.Width(200))) + { + var searchTextFieldSkin = GUI.skin.FindStyle("ToolbarSearchTextField"); + if (searchTextFieldSkin == null) + searchTextFieldSkin = GUI.skin.FindStyle("ToolbarSeachTextField"); + + var searchButtonSkin = GUI.skin.FindStyle("ToolbarSearchCancelButton"); + if (searchButtonSkin == null) + searchButtonSkin = GUI.skin.FindStyle("ToolbarSeachCancelButton"); + + searchTerm = GUILayout.TextField(searchTerm, searchTextFieldSkin); + if (GUILayout.Button("", searchButtonSkin)) + { + // Remove focus if cleared + searchTerm = ""; + GUI.FocusControl(null); + } + } + + EditorGUILayout.Space(); + EditorGUILayout.Space(); + + foreach (var go in hierarchy) + if (go != null) + go.DrawHierarchy(searchTerm.ToLowerInvariant()); + } + if (changeCheck.changed) + EditorUtility.SetDirty(mgr); + } + } + + public void Init() + { + if (mgr == null) + foreach (var thisMgr in Resources.FindObjectsOfTypeAll()) + if (thisMgr != null && thisMgr.gameObject.scene == SceneManager.GetActiveScene()) + mgr = thisMgr; + + if (hierarchy == null) + OnFocus(); + } + + public override void OnFocus() + { + + GameObject[] parentObjects; + if (sceneOpen) + parentObjects = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(); + else // Prefabs + { + var mgr = ES3ReferenceMgr.GetManagerFromScene(SceneManager.GetActiveScene(), false); + var prefabs = mgr.prefabs; + parentObjects = new GameObject[prefabs.Count]; + for (int i = 0; i < prefabs.Count; i++) + if(prefabs[i] != null) + parentObjects[i] = prefabs[i].gameObject; + } + hierarchy = new HierarchyItem[parentObjects.Length]; + for (int i = 0; i < parentObjects.Length; i++) + if(parentObjects[i] != null) + hierarchy[i] = new HierarchyItem(parentObjects[i].transform, null, this); + } + + public class HierarchyItem + { + private ES3AutoSave autoSave; + private Transform t; + private Component[] components = null; + // Immediate children of this GameObject + private HierarchyItem[] children = new HierarchyItem[0]; + private bool showComponents = false; + //private AutoSaveWindow window; + + public HierarchyItem(Transform t, HierarchyItem parent, AutoSaveWindow window) + { + this.autoSave = t.GetComponent(); + this.t = t; + this.components = t.GetComponents(); + + children = new HierarchyItem[t.childCount]; + for (int i = 0; i < t.childCount; i++) + children[i] = new HierarchyItem(t.GetChild(i), this, window); + + //this.window = window; + } + + public void MergeDown(ES3AutoSave autoSave) + { + if (this.autoSave != autoSave) + { + if (this.autoSave != null) + { + autoSave.componentsToSave.AddRange(autoSave.componentsToSave); + Object.DestroyImmediate(this.autoSave); + } + this.autoSave = autoSave; + } + + foreach (var child in children) + MergeDown(autoSave); + } + + public void DrawHierarchy(string searchTerm) + { + bool containsSearchTerm = false; + + if (t != null) + { + // Filter by tag if it's prefixed by "tag:" + if (searchTerm.StartsWith("tag:") && t.tag.ToLowerInvariant().Contains(searchTerm.Remove(0,4))) + containsSearchTerm = true; + // Else filter by name + else + containsSearchTerm = t.name.ToLowerInvariant().Contains(searchTerm); + + if (containsSearchTerm) + { + GUIContent saveIcon; + EditorGUIUtility.SetIconSize(new Vector2(16, 16)); + + if (HasSelectedComponentsOrFields()) + saveIcon = new GUIContent(t.name, EditorStyle.Get.saveIconSelected, "There are Components on this GameObject which will be saved."); + else + saveIcon = new GUIContent(t.name, EditorStyle.Get.saveIconUnselected, "No Components on this GameObject will be saved"); + + GUIStyle style = GUI.skin.GetStyle("Foldout"); + if (Selection.activeTransform == t) + { + style = new GUIStyle(style); + style.fontStyle = FontStyle.Bold; + } + + var open = EditorGUILayout.Foldout(showComponents, saveIcon, style); + if (open) + { + // Ping the GameObject if this was previously closed + if (showComponents != open) + EditorGUIUtility.PingObject(t.gameObject); + DrawComponents(); + } + showComponents = open; + + EditorGUI.indentLevel += 1; + } + } + + // Draw children + if (children != null) + foreach (var child in children) + if (child != null) + child.DrawHierarchy(searchTerm); + + if (containsSearchTerm) + EditorGUI.indentLevel -= 1; + } + + public void DrawComponents() + { + EditorGUI.indentLevel += 3; + using (var scope = new EditorGUILayout.VerticalScope()) + { + bool toggle; + toggle = EditorGUILayout.ToggleLeft("active", autoSave != null ? autoSave.saveActive : false); + if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent() : autoSave) != null) + ApplyBool("saveActive", toggle); + + toggle = EditorGUILayout.ToggleLeft("hideFlags", autoSave != null ? autoSave.saveHideFlags : false); + if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent() : autoSave) != null) + ApplyBool("saveHideFlags", toggle); + + toggle = EditorGUILayout.ToggleLeft("layer", autoSave != null ? autoSave.saveLayer : false); + if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent() : autoSave) != null) + ApplyBool("saveLayer", toggle); + + toggle = EditorGUILayout.ToggleLeft("name", autoSave != null ? autoSave.saveName : false); + if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent() : autoSave) != null) + ApplyBool("saveName", toggle); + + toggle = EditorGUILayout.ToggleLeft("tag", autoSave != null ? autoSave.saveTag : false); + if ((autoSave = (toggle && autoSave == null) ? t.gameObject.AddComponent() : autoSave) != null) + ApplyBool("saveTag", toggle); + + foreach (var component in components) + { + if (component == null) + continue; + + using (var horizontalScope = new EditorGUILayout.HorizontalScope()) + { + bool saveComponent = false; + if (autoSave != null) + saveComponent = autoSave.componentsToSave.Contains(component); + + var newValue = EditorGUILayout.ToggleLeft(EditorGUIUtility.ObjectContent(component, component.GetType()), saveComponent); + // If the checkbox has changed, we want to save or not save a Component + if (newValue != saveComponent) + { + if (autoSave == null) + { + autoSave = Undo.AddComponent(t.gameObject); + var so = new SerializedObject(autoSave); + so.FindProperty("saveChildren").boolValue = false; + so.ApplyModifiedProperties(); + } + // If we've unchecked the box, remove the Component from the array. + if (newValue == false) + { + var so = new SerializedObject(autoSave); + var prop = so.FindProperty("componentsToSave"); + var index = autoSave.componentsToSave.IndexOf(component); + prop.DeleteArrayElementAtIndex(index); + so.ApplyModifiedProperties(); + } + // Else, add it to the array. + else + { + var so = new SerializedObject(autoSave); + var prop = so.FindProperty("componentsToSave"); + prop.arraySize++; + prop.GetArrayElementAtIndex(prop.arraySize - 1).objectReferenceValue = component; + so.ApplyModifiedProperties(); + } + } + if (GUILayout.Button(EditorGUIUtility.IconContent("_Popup"), new GUIStyle("Label"))) + ES3Window.InitAndShowTypes(component.GetType()); + } + } + } + + /*if(autoSave != null && isDirty) + { + EditorUtility.SetDirty(autoSave); + if (PrefabUtility.IsPartOfPrefabInstance(autoSave)) + PrefabUtility.RecordPrefabInstancePropertyModifications(autoSave.gameObject); + }*/ + + if (autoSave != null && (autoSave.componentsToSave == null || autoSave.componentsToSave.Count == 0) && !autoSave.saveActive && !autoSave.saveChildren && !autoSave.saveHideFlags && !autoSave.saveLayer && !autoSave.saveName && !autoSave.saveTag) + { + Undo.DestroyObjectImmediate(autoSave); + autoSave = null; + } + EditorGUI.indentLevel -= 3; + } + + public void ApplyBool(string propertyName, bool value) + { + var so = new SerializedObject(autoSave); + so.FindProperty(propertyName).boolValue = value; + so.ApplyModifiedProperties(); + } + + public bool HasSelectedComponentsOrFields() + { + if (autoSave == null) + return false; + + + foreach (var component in components) + if (component != null && autoSave.componentsToSave.Contains(component)) + return true; + + if (autoSave.saveActive || autoSave.saveHideFlags || autoSave.saveLayer || autoSave.saveName || autoSave.saveTag) + return true; + + return false; + } + } + } + +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AutoSaveWindow.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AutoSaveWindow.cs.meta new file mode 100644 index 0000000..9958209 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/AutoSaveWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6065cc5492e9f49728674de9a0c1fe84 +timeCreated: 1519132286 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ChangeReferenceID.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ChangeReferenceID.cs new file mode 100644 index 0000000..534010e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ChangeReferenceID.cs @@ -0,0 +1,93 @@ +using UnityEngine; +using UnityEditor; +using UnityEngine.SceneManagement; + +namespace ES3Internal +{ + public class SetReferenceID : EditorWindow + { + private long id = 0; + public UnityEngine.Object obj; + + [MenuItem("GameObject/Easy Save 3/Set Reference ID..", false, 33)] + [MenuItem("Assets/Easy Save 3/Set Reference ID..", false, 33)] + + public static void ShowWindow() + { + var selected = Selection.GetFiltered(SelectionMode.TopLevel); + + if (selected == null || selected.Length == 0) + EditorUtility.DisplayDialog("Could not set reference ID", "No reference was selected to set the ID of.", "Ok"); + else if (selected.Length > 1) + EditorUtility.DisplayDialog("Could not set reference ID", "Multiple references are selected. Please select a single reference.", "Ok"); + else + EditorWindow.GetWindow("Set Reference ID").obj = selected[0]; + } + + [MenuItem("CONTEXT/Component/Easy Save 3/Set Reference ID..", false, 33)] + public static void ShowWindowContext(MenuCommand command) + { + EditorWindow.GetWindow("Set Reference ID").obj = command.context; + } + + private void OnGUI() + { + GUILayout.Label("Enter new reference ID:", EditorStyles.boldLabel); + id = EditorGUILayout.LongField("Reference ID", id); + + if (GUILayout.Button("Apply")) + { + int setCount = 0; + + string sceneName = null; + + // If this is a scene object, only set the reference ID for the manager in the scene it belongs to. + if (!EditorUtility.IsPersistent(obj)) + { + if (obj is GameObject go) + sceneName = go.scene.name; + else if (obj is Component c) + sceneName = c.gameObject.scene.name; + } + + for (int i = 0; i < SceneManager.sceneCount; i++) + { + var loadedScene = SceneManager.GetSceneAt(i); + + if (loadedScene != null && loadedScene.IsValid()) + { + if (sceneName != null && loadedScene.name != sceneName) + continue; + + var mgr = ES3ReferenceMgr.GetManagerFromScene(loadedScene, false); + if (mgr != null) + { + Undo.RecordObject(mgr, "Changed reference ID in manager"); + mgr.Remove(obj); + mgr.Add(obj, id); + setCount++; + } + } + } + + if (setCount == 0) + { + this.Close(); + EditorUtility.DisplayDialog("Could not set reference ID", "No open scenes contain reference managers. Add a reference manager by going to Tools > Easy Save 3 > Add Manager to Scene.", "Ok"); + } + + this.Close(); + EditorUtility.DisplayDialog($"Reference ID successfully changed", $"Reference ID changed to {id} in {setCount} managers.", "Ok"); + } + } + + [MenuItem("GameObject/Easy Save 3/Set Reference ID..", true, 33)] + [MenuItem("Assets/Easy Save 3/Set Reference ID..", true, 33)] + private static bool CanSetReference() + { + var selected = Selection.GetFiltered(SelectionMode.TopLevel); + + return selected != null && selected.Length == 1 && ES3ReferenceMgr.Current != null; + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ChangeReferenceID.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ChangeReferenceID.cs.meta new file mode 100644 index 0000000..ca83970 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ChangeReferenceID.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c119866c01ca0044a7e5e08b8d22692 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveEditor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveEditor.cs new file mode 100644 index 0000000..a6786f4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveEditor.cs @@ -0,0 +1,21 @@ +using UnityEditor; +using UnityEngine; +using System; +using System.Collections; +using System.Collections.Generic; + +namespace ES3Internal +{ + [CustomEditor(typeof(ES3AutoSave))] + public class ES3AutoSaveEditor : Editor + { + public override void OnInspectorGUI() + { + if (target == null) + return; + + if (GUILayout.Button("Manage Auto Save Settings")) + ES3Editor.ES3Window.InitAndShowAutoSave(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveEditor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveEditor.cs.meta new file mode 100644 index 0000000..6b4bf60 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 54ded3aeb20a94008a877da330bfc45f +timeCreated: 1519132285 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveMgrEditor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveMgrEditor.cs new file mode 100644 index 0000000..854e218 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveMgrEditor.cs @@ -0,0 +1,20 @@ +using UnityEditor; +using UnityEngine; +using System; +using System.Collections; +using System.Collections.Generic; + +namespace ES3Internal +{ + [CustomEditor(typeof(ES3AutoSaveMgr))] + public class ES3AutoSaveMgrEditor : Editor + { + public override void OnInspectorGUI() + { + EditorGUILayout.HelpBox("This manages the saving and loading of GameObjects which have the Auto Save component attached to them.\n\nIf there are no Auto Save components in your scene, this component will do nothing.", MessageType.Info); + if(GUILayout.Button("Settings...")) + ES3Editor.ES3Window.InitAndShowAutoSave(); + } + } + +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveMgrEditor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveMgrEditor.cs.meta new file mode 100644 index 0000000..8983ad6 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3AutoSaveMgrEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f440317f3fd444daf83c27a3381af17c +timeCreated: 1519132300 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorStyle.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorStyle.cs new file mode 100644 index 0000000..fa5e9b4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorStyle.cs @@ -0,0 +1,84 @@ +using System.Collections; +using UnityEngine; +using UnityEditor; + +namespace ES3Editor +{ + public class EditorStyle + { + private static EditorStyle style = null; + + public GUIStyle area; + public GUIStyle areaPadded; + + public GUIStyle menuButton; + public GUIStyle menuButtonSelected; + public GUIStyle smallSquareButton; + + public GUIStyle heading; + public GUIStyle subheading; + public GUIStyle subheading2; + + public GUIStyle boldLabelNoStretch; + + public GUIStyle link; + + public GUIStyle toggle; + + public Texture2D saveIconSelected; + public Texture2D saveIconUnselected; + + public static EditorStyle Get { get{ if(style == null) style = new EditorStyle(); return style; } } + + public EditorStyle() + { + // An area with padding. + area = new GUIStyle(); + area.padding = new RectOffset(10, 10, 10, 10); + area.wordWrap = true; + + // An area with more padding. + areaPadded = new GUIStyle(); + areaPadded.padding = new RectOffset(20, 20, 20, 20); + areaPadded.wordWrap = true; + + // Unselected menu button. + menuButton = new GUIStyle(EditorStyles.toolbarButton); + menuButton.fontStyle = FontStyle.Normal; + menuButton.fontSize = 14; + menuButton.fixedHeight = 24; + + // Selected menu button. + menuButtonSelected = new GUIStyle(menuButton); + menuButtonSelected.fontStyle = FontStyle.Bold; + + // Main Headings + heading = new GUIStyle(EditorStyles.label); + heading.fontStyle = FontStyle.Bold; + heading.fontSize = 24; + + subheading = new GUIStyle(heading); + subheading.fontSize = 18; + + subheading2 = new GUIStyle(heading); + subheading2.fontSize = 14; + + boldLabelNoStretch = new GUIStyle(EditorStyles.label); + boldLabelNoStretch.stretchWidth = false; + boldLabelNoStretch.fontStyle = FontStyle.Bold; + + link = new GUIStyle(); + link.fontSize = 16; + if(EditorGUIUtility.isProSkin) + link.normal.textColor = new Color (0.262f, 0.670f, 0.788f); + else + link.normal.textColor = new Color (0.129f, 0.129f, 0.8f); + + toggle = new GUIStyle(EditorStyles.toggle); + toggle.stretchWidth = false; + + saveIconSelected = AssetDatabase.LoadAssetAtPath(ES3Settings.PathToEasySaveFolder() + "Editor/es3Logo16x16.png"); + saveIconUnselected = AssetDatabase.LoadAssetAtPath(ES3Settings.PathToEasySaveFolder() + "Editor/es3Logo16x16-bw.png"); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorStyle.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorStyle.cs.meta new file mode 100644 index 0000000..62aeda3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorStyle.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f556addc6753344019137cbc45d2c4ff +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorUtility.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorUtility.cs new file mode 100644 index 0000000..126d436 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorUtility.cs @@ -0,0 +1,60 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using System.IO; +using System.Linq; +using ES3Internal; + +public class ES3EditorUtility : Editor +{ + public static void DisplayLink(string label, string url) + { + var style = ES3Editor.EditorStyle.Get; + if(GUILayout.Button(label, style.link)) + Application.OpenURL(url); + + var buttonRect = GUILayoutUtility.GetLastRect(); + buttonRect.width = style.link.CalcSize(new GUIContent(label)).x; + + EditorGUIUtility.AddCursorRect(buttonRect, MouseCursor.Link); + } + + public static bool IsPrefabInAssets(UnityEngine.Object obj) + { + #if UNITY_2018_3_OR_NEWER + return PrefabUtility.IsPartOfPrefabAsset(obj); + #else + return (PrefabUtility.GetPrefabType(obj) == PrefabType.Prefab); + #endif + } + + /* + * Gets all children and components from a GameObject or GameObjects. + * We create our own method for this because EditorUtility.CollectDeepHierarchy isn't thread safe in the Editor. + */ + public static IEnumerable CollectDeepHierarchy(IEnumerable gos) + { + var deepHierarchy = new HashSet(); + foreach (var go in gos) + { + deepHierarchy.Add(go); + deepHierarchy.UnionWith(go.GetComponents()); + foreach (Transform t in go.transform) + deepHierarchy.UnionWith( CollectDeepHierarchy( new GameObject[] { t.gameObject } ) ); + } + return deepHierarchy; + } + + [MenuItem("Tools/Easy Save 3/Getting Started...", false, 0)] + public static void DisplayGettingStarted() + { + Application.OpenURL("https://docs.moodkie.com/easy-save-3/getting-started/"); + } + + [MenuItem("Tools/Easy Save 3/Manual...", false, 0)] + public static void DisplayManual() + { + Application.OpenURL("https://docs.moodkie.com/product/easy-save-3/"); + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorUtility.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorUtility.cs.meta new file mode 100644 index 0000000..f0d8af7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3EditorUtility.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 501719249e8124990973182985feaeb8 +timeCreated: 1519132285 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GameObjectEditor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GameObjectEditor.cs new file mode 100644 index 0000000..08dc8b0 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GameObjectEditor.cs @@ -0,0 +1,46 @@ +using UnityEditor; +using UnityEngine; + +namespace ES3Internal +{ + [CustomEditor(typeof(ES3GameObject))] + public class ES3GameObjectEditor : Editor + { + public override void OnInspectorGUI() + { + if (target == null) + return; + + var es3Go = (ES3GameObject)target; + + EditorGUILayout.HelpBox("This Component allows you to choose which Components are saved when this GameObject is saved using code.", MessageType.Info); + + if (es3Go.GetComponent() != null) + { + EditorGUILayout.HelpBox("This Component cannot be used on GameObjects which are already managed by Auto Save.", MessageType.Error); + return; + } + + foreach (var component in es3Go.GetComponents()) + { + var markedToBeSaved = es3Go.components.Contains(component); + var newMarkedToBeSaved = EditorGUILayout.Toggle(component.GetType().Name, markedToBeSaved); + + if(markedToBeSaved && !newMarkedToBeSaved) + { + Undo.RecordObject(es3Go, "Marked Component to save"); + es3Go.components.Remove(component); + } + + if (!markedToBeSaved && newMarkedToBeSaved) + { + Undo.RecordObject(es3Go, "Unmarked Component to save"); + es3Go.components.Add(component); + } + } + + if (es3Go.components.RemoveAll(t => t == null) > 0) + Undo.RecordObject(es3Go, "Removed null Component from ES3GameObject"); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GameObjectEditor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GameObjectEditor.cs.meta new file mode 100644 index 0000000..6fe8ba3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GameObjectEditor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b7d54ef20554e354eb3c0d40d2a6debe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GlobalReferencesEditor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GlobalReferencesEditor.cs new file mode 100644 index 0000000..d11c5c6 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GlobalReferencesEditor.cs @@ -0,0 +1,91 @@ +#if !ES3GLOBAL_DISABLED +using UnityEditor; +using UnityEngine; +using UnityEngine.SceneManagement; +using System; +using System.Collections; +using System.Collections.Generic; + +namespace ES3Internal +{ + [CustomEditor(typeof(ES3Internal.ES3GlobalReferences))] + [System.Serializable] + public class ES3GlobalReferencesEditor : Editor + { + private bool isDraggingOver = false; + private bool openReferences = false; + + private ES3Internal.ES3GlobalReferences _globalRefs = null; + private ES3Internal.ES3GlobalReferences globalRefs + { + get + { + if (_globalRefs == null) + _globalRefs = (ES3Internal.ES3GlobalReferences)serializedObject.targetObject; + return _globalRefs; + } + } + + public override void OnInspectorGUI() + { + EditorGUILayout.HelpBox("This stores references to objects in Assets, allowing them to be referenced with the same ID between scenes.", MessageType.Info); + + if (EditorGUILayout.Foldout(openReferences, "References") != openReferences) + { + openReferences = !openReferences; + if (openReferences == true) + openReferences = EditorUtility.DisplayDialog("Are you sure?", "Opening this list will display every reference in the manager, which for larger projects can cause the Editor to freeze\n\nIt is strongly recommended that you save your project before continuing.", "Open References", "Cancel"); + } + + // Make foldout drag-and-drop enabled for objects. + if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition)) + { + Event evt = Event.current; + + switch (evt.type) + { + case EventType.DragUpdated: + case EventType.DragPerform: + isDraggingOver = true; + break; + case EventType.DragExited: + isDraggingOver = false; + break; + } + + if (isDraggingOver) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + + if (evt.type == EventType.DragPerform) + { + DragAndDrop.AcceptDrag(); + Undo.RecordObject(globalRefs, "Add References to Easy Save 3 Reference List"); + foreach (UnityEngine.Object obj in DragAndDrop.objectReferences) + globalRefs.GetOrAdd(obj); + // Return now because otherwise we'll change the GUI during an event which doesn't allow it. + return; + } + } + } + + if (openReferences) + { + EditorGUI.indentLevel++; + + foreach (var kvp in globalRefs.refId) + { + EditorGUILayout.BeginHorizontal(); + + EditorGUILayout.ObjectField(kvp.Key, typeof(UnityEngine.Object), true); + EditorGUILayout.LongField(kvp.Value); + + EditorGUILayout.EndHorizontal(); + } + + EditorGUI.indentLevel--; + } + } + } +} +#endif diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GlobalReferencesEditor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GlobalReferencesEditor.cs.meta new file mode 100644 index 0000000..0203979 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3GlobalReferencesEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 286fb0c3863779e4d96bc682edb324ce +timeCreated: 1519132283 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3InspectorInfoEditor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3InspectorInfoEditor.cs new file mode 100644 index 0000000..efea1d9 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3InspectorInfoEditor.cs @@ -0,0 +1,14 @@ +using UnityEditor; +using UnityEngine; +using UnityEngine.SceneManagement; +using System; +using System.Collections; + +[CustomEditor(typeof(ES3InspectorInfo))] +public class ES3InspectorInfoEditor : Editor +{ + public override void OnInspectorGUI() + { + EditorGUILayout.HelpBox(((ES3InspectorInfo)target).message, MessageType.Info); + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3InspectorInfoEditor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3InspectorInfoEditor.cs.meta new file mode 100644 index 0000000..2bb545f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3InspectorInfoEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b344d685b614044aebf5285c5f59f52d +timeCreated: 1519132294 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PlayMakerEditor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PlayMakerEditor.cs new file mode 100644 index 0000000..f69c850 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PlayMakerEditor.cs @@ -0,0 +1,803 @@ +#if PLAYMAKER_1_8_OR_NEWER + +using UnityEngine; +using UnityEditor; +using HutongGames.PlayMaker; +using HutongGames.PlayMaker.Actions; +using HutongGames.PlayMakerEditor; +using System.Text.RegularExpressions; + +namespace ES3PlayMaker +{ + #region Base Actions + + public abstract class BaseEditor : CustomActionEditor + { + bool showErrorHandling = false; + + public abstract void DrawGUI(); + + public override bool OnGUI() + { + DrawGUI(); + + EditorGUILayout.Separator(); + + showErrorHandling = EditorGUILayout.Foldout(showErrorHandling, "Error Handling"); + if (showErrorHandling) + { + EditorGUI.indentLevel++; + EditField("errorEvent"); + EditField("errorMessage"); + EditorGUI.indentLevel--; + } + + return GUI.changed; + } + + // Displays the FsmVar field without the unnecessary Type field. + protected void FsmVarField(string fieldName) + { + if (target == null || target.State == null) + return; + + var fsmVar = (FsmVar)ES3Internal.ES3Reflection.GetField(target.GetType(), fieldName).GetValue(target); + + if (fsmVar == null) + { + fsmVar = new FsmVar(); + ES3Internal.ES3Reflection.GetField(target.GetType(), fieldName).SetValue(target, fsmVar); + } + + EditorGUILayout.BeginHorizontal(); + var label = Regex.Replace(fieldName, @"\p{Lu}", m => " " + m.Value.ToLowerInvariant()); + EditorGUILayout.PrefixLabel(char.ToUpperInvariant(label[0]) + label.Substring(1)); + + var localVariables = target.Fsm.Variables.GetAllNamedVariablesSorted(); + var globalVariables = FsmVariables.GlobalVariables.GetAllNamedVariablesSorted(); + + var variableNames = new string[localVariables.Length + globalVariables.Length]; + int selected = -1; + + for(int i=0; i= localVariables.Length ? globalVariables[i - localVariables.Length] : localVariables[i]; + variableNames[i] = i >= localVariables.Length ? "Globals/"+variable.Name : variable.Name; + if (fsmVar.NamedVar == variable) + selected = i; + } + + var newSelected = EditorGUILayout.Popup(selected, variableNames); + + + EditorGUILayout.EndHorizontal(); + + if (newSelected == -1) + return; + + if (selected != newSelected) + { + if (newSelected >= localVariables.Length) + fsmVar.NamedVar = globalVariables[newSelected - localVariables.Length]; + else + fsmVar.NamedVar = localVariables[newSelected]; + } + } + } + + public abstract class SettingsEditor : BaseEditor + { + public override bool OnGUI() + { + base.OnGUI(); + return DrawSettingsEditor(); + } + + public bool DrawSettingsEditor() + { + var action = target as ES3PlayMaker.SettingsAction; + if (action == null) + return false; + action.overrideDefaultSettings.Value = EditorGUILayout.ToggleLeft("Override Default Settings", action.overrideDefaultSettings.Value); + + if (action.overrideDefaultSettings.Value) + { + EditorGUI.indentLevel++; + + EditField("path"); + EditField("location"); + EditField("encryptionType"); + EditField("encryptionPassword"); + EditField("compressionType"); + EditField("directory"); + EditField("format"); + EditField("bufferSize"); + + EditorGUI.indentLevel--; + EditorGUILayout.Space(); + } + return GUI.changed; + } + } + + public abstract class KeyValueSettingsEditor : SettingsEditor + { + public override bool OnGUI() + { + EditField("key"); + EditField("value"); + + base.OnGUI(); + + return GUI.changed; + } + + public override void DrawGUI(){} + } + + public abstract class ES3FileActionEditor : BaseEditor + { + public override bool OnGUI() + { + EditField("fsmES3File"); + + base.OnGUI(); + + var action = target as ES3PlayMaker.ES3FileAction; + if (action == null) + return false; + + return GUI.changed; + } + } +#endregion + +#if !PLAYMAKER_1_9_OR_NEWER +#region Save Actions + + /*[CustomActionEditor(typeof(ES3PlayMaker.Save))] + public class SaveEditor : KeyValueSettingsEditor{}*/ + + /*[CustomActionEditor(typeof(ES3PlayMaker.SaveMultiple))] + public class SaveMultipleEditor : SettingsEditor + { + public override bool OnGUI() + { + return base.OnGUI(); + } + + public override void DrawGUI() + { + DrawDefaultInspector(); + } + }*/ + + [CustomActionEditor(typeof(ES3PlayMaker.SaveAll))] + public class SaveAllEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("key"); + EditField("saveFsmVariables"); + EditField("saveGlobalVariables"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.SaveRaw))] + public class SaveRawEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("str"); + EditField("useBase64Encoding"); + EditField("appendNewline"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.AppendRaw))] + public class AppendRawEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("str"); + EditField("useBase64Encoding"); + EditField("appendNewline"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.SaveImage))] + public class SaveImageEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("imagePath"); + EditField("texture2D"); + EditField("quality"); + } + } + +#endregion + +#region Load Actions + + [CustomActionEditor(typeof(ES3PlayMaker.Load))] + public class LoadEditor : KeyValueSettingsEditor + { + public override void DrawGUI() + { + EditorGUILayout.Space(); + EditField("defaultValue"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.LoadInto))] + public class LoadIntoEditor : KeyValueSettingsEditor{} + + [CustomActionEditor(typeof(ES3PlayMaker.LoadAll))] + public class LoadAllEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("key"); + EditField("loadFsmVariables"); + EditField("loadGlobalVariables"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.LoadAudio))] + public class LoadAudioEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("audioFilePath"); + EditField("audioClip"); +#if UNITY_2018_3_OR_NEWER + EditField("audioType"); +#endif + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.LoadImage))] + public class LoadImageEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("imagePath"); + EditField("texture2D"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.LoadRawString))] + public class LoadRawStringEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("str"); + EditField("useBase64Encoding"); + } + } + +#endregion + +#region Exists Actions + + [CustomActionEditor(typeof(ES3PlayMaker.KeyExists))] + public class KeyExistsEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("key"); + EditField("exists"); + EditorGUILayout.Separator(); + EditField("existsEvent"); + EditField("doesNotExistEvent"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.FileExists))] + public class FileExistsEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("filePath"); + EditField("exists"); + EditorGUILayout.Separator(); + EditField("existsEvent"); + EditField("doesNotExistEvent"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.DirectoryExists))] + public class DirectoryExistsEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("directoryPath"); + EditField("exists"); + EditorGUILayout.Separator(); + EditField("existsEvent"); + EditField("doesNotExistEvent"); + } + } + +#endregion + +#region Delete Actions + + [CustomActionEditor(typeof(ES3PlayMaker.DeleteKey))] + public class DeleteKeyEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("key"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.DeleteFile))] + public class DeleteFileEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("filePath"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.DeleteDirectory))] + public class DeleteDirectoryEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("directoryPath"); + } + } + +#endregion + +#region Backup Actions + + [CustomActionEditor(typeof(ES3PlayMaker.CreateBackup))] + public class CreateBackupEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("filePath"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.RestoreBackup))] + public class RestoreBackupEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("filePath"); + EditField("backupWasRestored"); + } + } + +#endregion + +#region Key, File and Directory methods + + [CustomActionEditor(typeof(ES3PlayMaker.RenameFile))] + public class RenameFileEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("oldFilePath"); + EditField("newFilePath"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.CopyFile))] + public class CopyFileEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("oldFilePath"); + EditField("newFilePath"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.CopyDirectory))] + public class CopyDirectoryEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("oldDirectoryPath"); + EditField("newDirectoryPath"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.GetKeys))] + public class GetKeysEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("filePath"); + EditField("keys"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.GetKeyCount))] + public class GetKeyCountEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("filePath"); + EditField("keyCount"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.GetFiles))] + public class GetFilesEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("directoryPath"); + EditField("files"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.GetDirectories))] + public class GetDirectoriesEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("directoryPath"); + EditField("directories"); + } + } + +#endregion + +#region ES3File Actions + + [CustomActionEditor(typeof(ES3PlayMaker.ES3FileCreate))] + public class ES3FileCreateEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("fsmES3File"); + EditField("filePath"); + EditField("syncWithFile"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3FileSync))] + public class ES3FileSyncEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("fsmES3File"); + } + } + + /*[CustomActionEditor(typeof(ES3PlayMaker.ES3FileSave))] + public class ES3FileSaveEditor : SaveEditor + { + public override void DrawGUI() + { + EditField("fsmES3File"); + base.DrawGUI(); + } + }*/ + + [CustomActionEditor(typeof(ES3PlayMaker.ES3FileLoad))] + public class ES3FileLoadEditor : LoadEditor + { + public override void DrawGUI() + { + EditField("fsmES3File"); + base.DrawGUI(); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3FileLoadInto))] + public class ES3FileLoadIntoEditor : LoadIntoEditor + { + public override void DrawGUI() + { + base.DrawGUI(); + EditField("fsmES3File"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3FileDeleteKey))] + public class ES3FileDeleteKeyEditor : DeleteKeyEditor + { + public override void DrawGUI() + { + base.DrawGUI(); + EditField("fsmES3File"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3FileKeyExists))] + public class ES3FileKeyExistsEditor : KeyExistsEditor + { + public override void DrawGUI() + { + EditField("fsmES3File"); + base.DrawGUI(); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3FileGetKeys))] + public class ES3FileGetKeysEditor : ES3FileActionEditor + { + public override void DrawGUI() + { + EditField("keys"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3FileClear))] + public class ES3FileClearEditor : BaseEditor + { + public override void DrawGUI() + { + EditField("fsmES3File"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3FileSize))] + public class ES3FileSizeEditor : BaseEditor + { + public override void DrawGUI() + { + EditField("size"); + EditField("fsmES3File"); + } + } + + +#endregion + +#region ES3Cloud Actions +#if !DISABLE_WEB + + public abstract class ES3CloudEditor : SettingsEditor + { + protected abstract void DrawChildGUI(); + + public override void DrawGUI() + { + EditField("url"); + EditField("apiKey"); + EditorGUILayout.Space(); + DrawChildGUI(); + EditorGUILayout.Space(); + EditField("errorCode"); + } + } + + public abstract class ES3CloudUserEditor : ES3CloudEditor + { + public bool showUser = false; + + protected override void DrawChildGUI() + { + if((showUser = EditorGUILayout.Foldout(showUser, "User (optional)"))) + { + EditorGUI.indentLevel++; + EditField("user"); + EditField("password"); + EditorGUI.indentLevel--; + } + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudSync))] + public class ES3CloudSyncEditor : ES3CloudUserEditor + { + protected override void DrawChildGUI() + { + EditField("path"); + base.DrawChildGUI(); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDownloadFile))] + public class ES3CloudDownloadFileEditor : ES3CloudUserEditor + { + protected override void DrawChildGUI() + { + EditField("path"); + base.DrawChildGUI(); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDownloadES3File))] + public class ES3CloudDownloadES3FileEditor : BaseEditor + { + public bool showUser = false; + public override void DrawGUI() + { + EditField("fsmES3File"); + EditField("url"); + EditField("apiKey"); + EditField("errorCode"); + if ((showUser = EditorGUILayout.Foldout(showUser, "User (optional)"))) + { + EditorGUI.indentLevel++; + EditField("user"); + EditField("password"); + EditorGUI.indentLevel--; + } + } + } + + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudUploadFile))] + public class ES3CloudUploadFileEditor : ES3CloudUserEditor + { + protected override void DrawChildGUI() + { + EditField("path"); + base.DrawChildGUI(); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudUploadES3File))] + public class ES3CloudUploadES3FileEditor : BaseEditor + { + public bool showUser = false; + public override void DrawGUI() + { + EditField("fsmES3File"); + EditField("url"); + EditField("apiKey"); + EditField("errorCode"); + if((showUser = EditorGUILayout.Foldout(showUser, "User (optional)"))) + { + EditorGUI.indentLevel++; + EditField("user"); + EditField("password"); + EditorGUI.indentLevel--; + } + } + } + + + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDeleteFile))] + public class ES3CloudDeleteFileEditor : ES3CloudUserEditor + { + protected override void DrawChildGUI() + { + EditField("path"); + base.DrawChildGUI(); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudRenameFile))] + public class ES3CloudRenameFileEditor : ES3CloudUserEditor + { + protected override void DrawChildGUI() + { + EditField("path"); + EditField("newFilename"); + base.DrawChildGUI(); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDownloadFilenames))] + public class ES3CloudDownloadFilenamesEditor : ES3CloudUserEditor + { + protected override void DrawChildGUI() + { + EditField("filenames"); + EditField("searchPattern"); + base.DrawChildGUI(); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudSearchFilenames))] + public class ES3CloudSearchFilenamesEditor : ES3CloudUserEditor + { + protected override void DrawChildGUI() + { + EditField("filenames"); + EditField("searchPattern"); + base.DrawChildGUI(); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3CloudDownloadTimestamp))] + public class ES3CloudDownloadTimestampEditor : ES3CloudUserEditor + { + protected override void DrawChildGUI() + { + EditField("path"); + EditField("timestamp"); + base.DrawChildGUI(); + } + } + +#endif + +#endregion + +#region ES3SpreadsheetActions + + + [CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetCreate))] + public class ES3SpreadsheetCreateEditor : BaseEditor + { + public override void DrawGUI() + { + EditField("fsmES3Spreadsheet"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetSetCell))] + public class ES3SpreadsheetSetCellEditor : BaseEditor + { + public override void DrawGUI() + { + EditField("fsmES3Spreadsheet"); + EditField("col"); + EditField("row"); + EditField("value"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetGetCell))] + public class ES3SpreadsheetGetCellEditor : BaseEditor + { + public override void DrawGUI() + { + EditField("fsmES3Spreadsheet"); + EditField("col"); + EditField("row"); + EditField("value"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetLoad))] + public class ES3SpreadsheetLoadEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("fsmES3Spreadsheet"); + EditField("filePath"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.ES3SpreadsheetSave))] + public class ES3SpreadsheetSaveEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("fsmES3Spreadsheet"); + EditField("filePath"); + EditField("append"); + } + } + +#endregion + +#region Caching + + [CustomActionEditor(typeof(ES3PlayMaker.CacheFile))] + public class CacheFileEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("filePath"); + } + } + + [CustomActionEditor(typeof(ES3PlayMaker.StoreCachedFile))] + public class StoreCachedFileEditor : SettingsEditor + { + public override void DrawGUI() + { + EditField("filePath"); + } + } + +#endregion +#endif +} +#endif diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PlayMakerEditor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PlayMakerEditor.cs.meta new file mode 100644 index 0000000..4b91200 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PlayMakerEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 61838eb75b8164d699b0f54416e0f0bc +timeCreated: 1497347459 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Postprocessor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Postprocessor.cs new file mode 100644 index 0000000..5788d48 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Postprocessor.cs @@ -0,0 +1,269 @@ +using UnityEngine; +using UnityEditor; +using UnityEditor.Callbacks; +using UnityEditor.SceneManagement; +using UnityEngine.SceneManagement; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using ES3Internal; + + +/* + * ---- How Postprocessing works for the reference manager ---- + * - When the manager is first added to the scene, all top-level dependencies are added to the manager (AddManagerToScene). + * - When the manager is first added to the scene, all prefabs with ES3Prefab components are added to the manager (AddManagerToScene). + * - All GameObjects and Components in the scene are added to the reference manager when we enter Playmode or the scene is saved (PlayModeStateChanged, OnWillSaveAssets -> AddGameObjectsAndComponentstoManager). + * - When a UnityEngine.Object field of a Component is modified, the new UnityEngine.Object reference is added to the reference manager (PostProcessModifications) + * - All prefabs with ES3Prefab Components are added to the reference manager when we enter Playmode or the scene is saved (PlayModeStateChanged, OnWillSaveAssets -> AddGameObjectsAndComponentstoManager). + * - Local references for prefabs are processed whenever a prefab with an ES3Prefab Component is deselected (SelectionChanged -> ProcessGameObject) + */ +[InitializeOnLoad] +public class ES3Postprocessor : UnityEditor.AssetModificationProcessor +{ + public static GameObject lastSelected = null; + + + // This constructor is also called once when playmode is activated and whenever recompilation happens + // because we have the [InitializeOnLoad] attribute assigned to the class. + static ES3Postprocessor() + { +#if UNITY_2020_2_OR_NEWER + ObjectChangeEvents.changesPublished += Changed; +#endif + ObjectFactory.componentWasAdded += ComponentWasAdded; + + // Open the Easy Save 3 window the first time ES3 is installed. + //ES3Editor.ES3Window.OpenEditorWindowOnStart(); + + EditorApplication.playModeStateChanged -= PlayModeStateChanged; + EditorApplication.playModeStateChanged += PlayModeStateChanged; + + EditorSceneManager.sceneOpened += OnSceneOpened; + } + + #region Reference Updating + + private static void PlayModeStateChanged(PlayModeStateChange state) + { + if (state == PlayModeStateChange.ExitingEditMode) + UpdateAssembliesContainingES3Types(); + } + + private static void OnSceneOpened(Scene scene, OpenSceneMode mode) + { + if (mode == OpenSceneMode.AdditiveWithoutLoading || Application.isPlaying) + return; + + if (ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences && ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneIsOpened) + RefreshScene(scene); + } + + private static void RefreshReferences(bool isEnteringPlayMode = false) + { + /*if (refreshed) // If we've already refreshed, do nothing. + return;*/ + + if (ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences) + for (int i = 0; i < SceneManager.sceneCount; i++) + RefreshScene(SceneManager.GetSceneAt(i)); + //refreshed = true; + } + + static void RefreshScene(Scene scene, bool isEnteringPlayMode = false) + { + if (scene != null && scene.isLoaded) + { + var mgr = (ES3ReferenceMgr)ES3ReferenceMgr.GetManagerFromScene(scene, false); + if (mgr != null) + mgr.RefreshDependencies(isEnteringPlayMode); + } + } + + static void ComponentWasAdded(Component c) + { + var scene = c.gameObject.scene; + + if (!scene.isLoaded) + return; + + var mgr = (ES3ReferenceMgr)ES3ReferenceMgr.GetManagerFromScene(scene, false); + + if (mgr != null && ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences && ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneChanges) + mgr.AddDependencies(c); + } + +#if UNITY_2020_2_OR_NEWER + static void Changed(ref ObjectChangeEventStream stream) + { + if (EditorApplication.isUpdating || Application.isPlaying || !ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences || !ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneChanges) + return; + + for (int i = 0; i < stream.length; i++) + { + var eventType = stream.GetEventType(i); + int[] instanceIds; + Scene scene; + + if (eventType == ObjectChangeKind.ChangeGameObjectOrComponentProperties) + { + ChangeGameObjectOrComponentPropertiesEventArgs evt; + stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out evt); + instanceIds = new int[] { evt.instanceId }; + scene = evt.scene; + } + else if (eventType == ObjectChangeKind.CreateGameObjectHierarchy) + { + CreateGameObjectHierarchyEventArgs evt; + stream.GetCreateGameObjectHierarchyEvent(i, out evt); + instanceIds = new int[] { evt.instanceId }; + scene = evt.scene; + } + /*else if (eventType == ObjectChangeKind.ChangeAssetObjectProperties) + { + ChangeAssetObjectPropertiesEventArgs evt; + stream.GetChangeAssetObjectPropertiesEvent(i, out evt); + instanceIds = new int[] { evt.instanceId }; + }*/ + else if (eventType == ObjectChangeKind.UpdatePrefabInstances) + { + UpdatePrefabInstancesEventArgs evt; + stream.GetUpdatePrefabInstancesEvent(i, out evt); + instanceIds = evt.instanceIds.ToArray(); + scene = evt.scene; + } + else + continue; + + var mgr = (ES3ReferenceMgr)ES3ReferenceMgr.GetManagerFromScene(scene, false); + + if (mgr == null) + return; + + foreach (var id in instanceIds) + { + try + { + var obj = EditorUtility.InstanceIDToObject(id); + + if (obj == null) + continue; + + mgr.AddDependencies(obj); + } + catch { } + } + } + } +#endif + + /*public static void PlayModeStateChanged(PlayModeStateChange state) + { + // Add all GameObjects and Components to the reference manager before we enter play mode. + if (state == PlayModeStateChange.ExitingEditMode && ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences) + RefreshReferences(true); + }*/ + + public static string[] OnWillSaveAssets(string[] paths) + { + // Don't refresh references when the application is playing. + if (!EditorApplication.isUpdating && !Application.isPlaying) + { + if(ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences && ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneIsSaved) + RefreshReferences(); + UpdateAssembliesContainingES3Types(); + } + return paths; + } + + #endregion + + + private static void UpdateAssembliesContainingES3Types() + { + var assemblies = UnityEditor.Compilation.CompilationPipeline.GetAssemblies(); + + if (assemblies == null || assemblies.Length == 0) + return; + + var defaults = ES3Settings.defaultSettingsScriptableObject; + var currentAssemblyNames = defaults.settings.assemblyNames; + + var assemblyNames = new List(); + + foreach (var assembly in assemblies) + { + // Don't include Editor assemblies. + if (assembly.flags.HasFlag(UnityEditor.Compilation.AssemblyFlags.EditorAssembly)) + continue; + + // Assemblies beginning with 'com.' are assumed to be internal. + if (assembly.name.StartsWith("com.")) + continue; + + // If this assembly begins with 'Unity', but isn't created from an Assembly Definition File, skip it. + if (assembly.name.StartsWith("Unity")) + { + bool isAssemblyDefinition = true; + + foreach (string sourceFile in assembly.sourceFiles) + { + if (!sourceFile.StartsWith("Assets/")) + { + isAssemblyDefinition = false; + break; + } + } + + if (!isAssemblyDefinition) + continue; + } + + assemblyNames.Add(assembly.name); + } + + // If there are no assembly names, + if (assemblyNames.Count == 0) + return; + + // Sort it alphabetically so that the order isn't constantly changing, which can affect version control. + assemblyNames.Sort(); + + // Only update if the list has changed. + for (int i = 0; i < assemblyNames.Count; i++) + { + if (currentAssemblyNames.Length != assemblyNames.Count || currentAssemblyNames[i] != assemblyNames[i]) + { + defaults.settings.assemblyNames = assemblyNames.ToArray(); + EditorUtility.SetDirty(defaults); + break; + } + } + } + + public static GameObject AddManagerToScene() + { + GameObject mgr = null; + + var mgrComponent = ES3ReferenceMgr.GetManagerFromScene(SceneManager.GetActiveScene(), false); + if (mgrComponent != null) + mgr = mgrComponent.gameObject; + + if (mgr == null) + mgr = new GameObject("Easy Save 3 Manager"); + + if (mgr.GetComponent() == null) + { + var refMgr = mgr.AddComponent(); + + if (!Application.isPlaying && ES3Settings.defaultSettingsScriptableObject.autoUpdateReferences) + refMgr.RefreshDependencies(); + } + + if (mgr.GetComponent() == null) + mgr.AddComponent(); + + Undo.RegisterCreatedObjectUndo(mgr, "Enabled Easy Save for Scene"); + return mgr; + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Postprocessor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Postprocessor.cs.meta new file mode 100644 index 0000000..f6726e4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Postprocessor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4256380692bcb4e57bdc0a5e13956389 +timeCreated: 1474041535 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PrefabEditor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PrefabEditor.cs new file mode 100644 index 0000000..03bed84 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PrefabEditor.cs @@ -0,0 +1,50 @@ +using UnityEditor; +using UnityEngine; +using UnityEngine.SceneManagement; +using System; +using System.Collections; +using ES3Internal; + +[CustomEditor(typeof(ES3Prefab))] +[System.Serializable] +public class ES3PrefabEditor : Editor +{ + bool showAdvanced = false; + bool openLocalRefs = false; + + public override void OnInspectorGUI() + { + var es3Prefab = (ES3Prefab)serializedObject.targetObject; + EditorGUILayout.HelpBox("Easy Save is enabled for this prefab, and can be saved and loaded with the ES3 methods.", MessageType.None); + + + showAdvanced = EditorGUILayout.Foldout(showAdvanced, "Advanced Settings"); + if(showAdvanced) + { + EditorGUI.indentLevel++; + es3Prefab.prefabId = EditorGUILayout.LongField("Prefab ID", es3Prefab.prefabId); + EditorGUILayout.LabelField("Reference count", es3Prefab.localRefs.Count.ToString()); + EditorGUI.indentLevel--; + + openLocalRefs = EditorGUILayout.Foldout(openLocalRefs, "localRefs"); + if (openLocalRefs) + { + EditorGUI.indentLevel++; + + EditorGUILayout.LabelField("It is not recommended to manually modify these."); + + foreach (var kvp in es3Prefab.localRefs) + { + EditorGUILayout.BeginHorizontal(); + + EditorGUILayout.ObjectField(kvp.Key, typeof(UnityEngine.Object), false); + EditorGUILayout.LongField(kvp.Value); + + EditorGUILayout.EndHorizontal(); + } + + EditorGUI.indentLevel--; + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PrefabEditor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PrefabEditor.cs.meta new file mode 100644 index 0000000..f0d7c5e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3PrefabEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9d25610c9233c4cdfa5a0744c9956f5c +timeCreated: 1519132292 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ReferenceMgrEditor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ReferenceMgrEditor.cs new file mode 100644 index 0000000..714c32b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ReferenceMgrEditor.cs @@ -0,0 +1,296 @@ +using UnityEditor; +using UnityEngine; +using UnityEngine.SceneManagement; +using System; +using System.Collections; +using System.Collections.Generic; + +[CustomEditor(typeof(ES3ReferenceMgr))] +[System.Serializable] +public class ES3ReferenceMgrEditor : Editor +{ + private bool isDraggingOver = false; + private bool openReferences = false; + + private ES3ReferenceMgr _mgr = null; + private ES3ReferenceMgr mgr + { + get + { + if (_mgr == null) + _mgr = (ES3ReferenceMgr)serializedObject.targetObject; + return _mgr; + } + } + + public override void OnInspectorGUI() + { + EditorGUILayout.HelpBox("This allows Easy Save to maintain references to objects in your scene.\n\nIt is automatically updated when you enter Playmode or build your project.", MessageType.Info); + + if (EditorGUILayout.Foldout(openReferences, "References") != openReferences) + { + openReferences = !openReferences; + if (openReferences == true) + openReferences = EditorUtility.DisplayDialog("Are you sure?", "Opening this list will display every reference in the manager, which for larger projects can cause the Editor to freeze\n\nIt is strongly recommended that you save your project before continuing.", "Open References", "Cancel"); + } + + // Make foldout drag-and-drop enabled for objects. + if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition)) + { + Event evt = Event.current; + + switch (evt.type) + { + case EventType.DragUpdated: + case EventType.DragPerform: + isDraggingOver = true; + break; + case EventType.DragExited: + isDraggingOver = false; + break; + } + + if (isDraggingOver) + { + DragAndDrop.visualMode = DragAndDropVisualMode.Copy; + + if (evt.type == EventType.DragPerform) + { + DragAndDrop.AcceptDrag(); + Undo.RecordObject(mgr, "Add References to Easy Save 3 Reference List"); + foreach (UnityEngine.Object obj in DragAndDrop.objectReferences) + mgr.Add(obj); + // Return now because otherwise we'll change the GUI during an event which doesn't allow it. + return; + } + } + } + + if (openReferences) + { + EditorGUI.indentLevel++; + + foreach (var kvp in mgr.idRef) + { + EditorGUILayout.BeginHorizontal(); + + var value = EditorGUILayout.ObjectField(kvp.Value, typeof(UnityEngine.Object), true); + var key = EditorGUILayout.LongField(kvp.Key); + + EditorGUILayout.EndHorizontal(); + + if (value != kvp.Value || key != kvp.Key) + { + Undo.RecordObject(mgr, "Change Easy Save 3 References"); + // If we're deleting a value, delete it. + if (value == null) + mgr.Remove(key); + // Else, update the ID. + else + mgr.ChangeId(kvp.Key, key); + // Break, as removing or changing Dictionary items will make the foreach out of sync. + break; + } + } + + EditorGUI.indentLevel--; + } + + mgr.openPrefabs = EditorGUILayout.Foldout(mgr.openPrefabs, "ES3Prefabs"); + if (mgr.openPrefabs) + { + EditorGUI.indentLevel++; + + foreach (var prefab in mgr.prefabs) + { + EditorGUILayout.BeginHorizontal(); + + EditorGUILayout.ObjectField(prefab, typeof(UnityEngine.Object), true); + + EditorGUILayout.EndHorizontal(); + } + + EditorGUI.indentLevel--; + } + + var sp = serializedObject.FindProperty("excludeObjects"); + EditorGUILayout.PropertyField(sp); + serializedObject.ApplyModifiedProperties(); + + EditorGUILayout.LabelField("Reference count", mgr.refId.Count.ToString()); + EditorGUILayout.LabelField("Prefab count", mgr.prefabs.Count.ToString()); + + if (GUILayout.Button("Refresh")) + { + mgr.RefreshDependencies(); + } + + if (GUILayout.Button("Optimize")) + { + mgr.Optimize(); + } + } + + [MenuItem("GameObject/Easy Save 3/Add Dependencies to Manager", false, 33)] + [MenuItem("Assets/Easy Save 3/Add Dependencies to Manager", false, 33)] + public static void AddDependenciesToManager() + { + var mgr = ES3ReferenceMgr.GetManagerFromScene(SceneManager.GetActiveScene()); + if (mgr == null) + { + EditorUtility.DisplayDialog("Could not add reference to manager", "This object could not be added to the reference manager because no reference manager exists in this scene. To create one, go to Tools > Easy Save 3 > Add Manager to Scene", "Ok"); + return; + } + + var selected = new HashSet(Selection.GetFiltered(SelectionMode.DeepAssets)); + selected.UnionWith(Selection.GetFiltered(SelectionMode.TopLevel)); + + if (selected == null || selected.Count == 0) + return; + + Undo.RecordObject(mgr, "Update Easy Save 3 Reference Manager"); + + foreach (var obj in selected) + { + if (obj == null) + continue; + + if (obj.GetType() == typeof(GameObject)) + { + var go = (GameObject)obj; + if (ES3EditorUtility.IsPrefabInAssets(go) && go.GetComponent() != null) + mgr.AddPrefab(go.GetComponent()); + } + + ((ES3ReferenceMgr)mgr).AddDependencies(obj); + } + } + + [MenuItem("GameObject/Easy Save 3/Add Reference(s) to Manager", false, 33)] + [MenuItem("Assets/Easy Save 3/Add Reference(s) to Manager", false, 33)] + public static void AddReferencesToManager() + { + var mgr = ES3ReferenceMgr.Current; + if (mgr == null) + { + EditorUtility.DisplayDialog("Could not add reference to manager", "This object could not be added to the reference manager because no reference manager exists in this scene. To create one, go to Tools > Easy Save 3 > Add Manager to Scene", "Ok"); + return; + } + + var selected = Selection.GetFiltered(SelectionMode.TopLevel); + + if (selected == null || selected.Length == 0) + return; + + Undo.RecordObject(mgr, "Update Easy Save 3 Reference Manager"); + + foreach (var obj in selected) + { + if (obj == null) + continue; + + if (obj.GetType() == typeof(GameObject)) + { + var go = (GameObject)obj; + if (ES3EditorUtility.IsPrefabInAssets(go) && go.GetComponent() != null) + mgr.AddPrefab(go.GetComponent()); + } + + ((ES3ReferenceMgr)mgr).Add(obj); + } + } + + [MenuItem("GameObject/Easy Save 3/Add Reference(s) to Manager", true, 33)] + [MenuItem("Assets/Easy Save 3/Add Reference(s) to Manager", true, 33)] + [MenuItem("GameObject/Easy Save 3/Add Dependencies to Manager", true, 33)] + [MenuItem("Assets/Easy Save 3/Add Dependencies to Manager", true, 33)] + private static bool CanAddReferenceToManager() + { + var selected = Selection.GetFiltered(SelectionMode.Deep); + return selected != null && selected.Length > 0 && ES3ReferenceMgr.Current != null; + } + + [MenuItem("GameObject/Easy Save 3/Exclude Reference(s) from Manager", false, 33)] + [MenuItem("Assets/Easy Save 3/Exclude Reference(s) from Manager", false, 33)] + public static void ExcludeReferenceFromManager() + { + var mgr = (ES3ReferenceMgr)ES3ReferenceMgr.Current; + if (mgr == null) + { + EditorUtility.DisplayDialog("Could not exclude reference from manager", "This object could not be excluded from the reference manager because no reference manager exists in this scene. To create one, go to Tools > Easy Save 3 > Add Manager to Scene", "Ok"); + return; + } + + var selected = Selection.GetFiltered(SelectionMode.TopLevel); + + if (selected == null || selected.Length == 0) + return; + + Undo.RecordObject(mgr, "Exclude from Easy Save 3 Reference Manager"); + + foreach (var obj in selected) + { + if (obj == null) + continue; + + mgr.ExcludeObject(obj); + } + + mgr.RemoveNullOrInvalidValues(); + } + + [MenuItem("GameObject/Easy Save 3/Exclude Dependencies from Manager", false, 33)] + [MenuItem("Assets/Easy Save 3/Exclude Dependencies from Manager", false, 33)] + public static void ExcludeDependenciesFromManager() + { + var mgr = (ES3ReferenceMgr)ES3ReferenceMgr.Current; + if (mgr == null) + { + EditorUtility.DisplayDialog("Could not exclude reference from manager", "This object could not be excluded from the reference manager because no reference manager exists in this scene. To create one, go to Tools > Easy Save 3 > Add Manager to Scene", "Ok"); + return; + } + + var selected = Selection.GetFiltered(SelectionMode.TopLevel); + + if (selected == null || selected.Length == 0) + return; + + Undo.RecordObject(mgr, "Exclude from Easy Save 3 Reference Manager"); + + var dependencies = EditorUtility.CollectDependencies(selected); + + foreach (var dependency in dependencies) + mgr.ExcludeObject(dependency); + + mgr.RemoveNullOrInvalidValues(); + } + + [MenuItem("GameObject/Easy Save 3/Exclude Dependencies from Manager", true, 33)] + [MenuItem("Assets/Easy Save 3/Exclude Dependencies from Manager", true, 33)] + [MenuItem("GameObject/Easy Save 3/Exclude Reference(s) from Manager", true, 33)] + [MenuItem("Assets/Easy Save 3/Exclude Reference(s) from Manager", true, 33)] + private static bool CanExcludeReferencesFromManager() + { + var selected = Selection.GetFiltered(SelectionMode.Deep); + return selected != null && selected.Length > 0 && ES3ReferenceMgr.Current != null; + } + + [MenuItem("GameObject/Easy Save 3/Add Manager to Scene", false, 33)] + [MenuItem("Assets/Easy Save 3/Add Manager to Scene", false, 33)] + [MenuItem("Tools/Easy Save 3/Add Manager to Scene", false, 150)] + public static void EnableForScene() + { + if(!SceneManager.GetActiveScene().isLoaded) + EditorUtility.DisplayDialog("Could not add manager to scene", "Could not add Easy Save 3 Manager to scene because there is not currently a scene open.", "Ok"); + Selection.activeObject = ES3Postprocessor.AddManagerToScene(); + } + + [MenuItem("GameObject/Easy Save 3/Add Manager to Scene", true, 33)] + [MenuItem("Assets/Easy Save 3/Add Manager to Scene", true, 33)] + [MenuItem("Tools/Easy Save 3/Add Manager to Scene", true, 150)] + private static bool CanEnableForScene() + { + return ES3ReferenceMgr.GetManagerFromScene(SceneManager.GetActiveScene(), false) == null; + } +} + diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ReferenceMgrEditor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ReferenceMgrEditor.cs.meta new file mode 100644 index 0000000..b60a7a3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ReferenceMgrEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3b43d266ed3464dedaa77757645ad61c +timeCreated: 1519132283 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ScriptingDefineSymbols.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ScriptingDefineSymbols.cs new file mode 100644 index 0000000..4a21d10 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ScriptingDefineSymbols.cs @@ -0,0 +1,128 @@ +using UnityEditor; +using UnityEngine; +using UnityEditor.Build; +using System.Collections.Generic; +using UnityEditor.Compilation; +using System.Reflection; +using System.Linq; +using System; + +[InitializeOnLoad] +public class ES3ScriptingDefineSymbols +{ + static ES3ScriptingDefineSymbols() + { + SetDefineSymbols(); + } + + static void SetDefineSymbols() + { + if (Type.GetType("Unity.VisualScripting.IncludeInSettingsAttribute, Unity.VisualScripting.Core") != null) + SetDefineSymbol("UNITY_VISUAL_SCRIPTING"); + + if (Type.GetType("Ludiq.IncludeInSettingsAttribute, Ludiq.Core.Runtime") != null) + SetDefineSymbol("BOLT_VISUAL_SCRIPTING"); + + if (Type.GetType("TMPro.TextMeshProUGUI, Unity.TextMeshPro") != null) + SetDefineSymbol("ES3_TMPRO"); + + if (Type.GetType("UnityEngine.EventSystems.EventSystem, UnityEngine.UI") != null) + SetDefineSymbol("ES3_UGUI"); + } + + internal static bool HasDefineSymbol(string symbol) + { +#if UNITY_2021_2_OR_NEWER + foreach (var target in GetAllNamedBuildTargets()) + { + string[] defines; + try + { + PlayerSettings.GetScriptingDefineSymbols(target, out defines); + if (defines.Contains(symbol)) + return true; + } + catch { } + } +#else + string definesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); + var allDefines = new HashSet(definesString.Split(';')); + if (allDefines.Contains(symbol)) + return true; +#endif + return false; + } + + internal static void SetDefineSymbol(string symbol) + { +#if UNITY_2021_2_OR_NEWER + foreach (var target in GetAllNamedBuildTargets()) + { + string[] defines; + try + { + PlayerSettings.GetScriptingDefineSymbols(target, out defines); + if (!defines.Contains(symbol)) + { + ArrayUtility.Add(ref defines, symbol); + PlayerSettings.SetScriptingDefineSymbols(target, defines); + } + } + catch { } + } +#else + string definesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); + var allDefines = new HashSet(definesString.Split(';')); + if (!allDefines.Contains(symbol)) + PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(";", allDefines.Concat(new string[] { symbol }).ToArray())); +#endif + return; + } + + internal static void RemoveDefineSymbol(string symbol) + { +#if UNITY_2021_2_OR_NEWER + foreach (var target in GetAllNamedBuildTargets()) + { + string[] defines; + try + { + PlayerSettings.GetScriptingDefineSymbols(target, out defines); + ArrayUtility.Remove(ref defines, symbol); + PlayerSettings.SetScriptingDefineSymbols(target, defines); + } + catch { } + } +#else + string definesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); + definesString.Replace(symbol + ";", ""); // With semicolon + definesString.Replace(symbol, ""); // Without semicolon + PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, definesString); +#endif + return; + } + +#if UNITY_2021_2_OR_NEWER + static List GetAllNamedBuildTargets() + { + var staticFields = typeof(NamedBuildTarget).GetFields(BindingFlags.Public | BindingFlags.Static); + var buildTargets = new List(); + + foreach (var staticField in staticFields) + { + // We exclude 'Unknown' because this can throw errors when used with certain methods. + if (staticField.Name == "Unknown") + continue; + + // A bug at Unity's end means that Stadia can throw an error. + if (staticField.Name == "Stadia") + continue; + + if (staticField.FieldType == typeof(NamedBuildTarget)) + buildTargets.Add((NamedBuildTarget)staticField.GetValue(null)); + } + + return buildTargets; + } +#endif +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ScriptingDefineSymbols.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ScriptingDefineSymbols.cs.meta new file mode 100644 index 0000000..ca2780c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3ScriptingDefineSymbols.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69b6276384d46d34fb2705f95689e8cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3SettingsEditor.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3SettingsEditor.cs new file mode 100644 index 0000000..9eef456 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3SettingsEditor.cs @@ -0,0 +1,56 @@ +using UnityEditor; +using UnityEngine; +using UnityEngine.SceneManagement; +using System; +using System.Collections; +using ES3Internal; + +namespace ES3Editor +{ + public static class ES3SettingsEditor + { + public static void Draw(ES3SerializableSettings settings) + { + var style = EditorStyle.Get; + + settings.location = (ES3.Location)EditorGUILayout.EnumPopup("Location", settings.location); + // If the location is File, show the Directory. + if(settings.location == ES3.Location.File) + settings.directory = (ES3.Directory)EditorGUILayout.EnumPopup("Directory", settings.directory); + + settings.path = EditorGUILayout.TextField("Default File Path", settings.path); + + EditorGUILayout.Space(); + + settings.encryptionType = (ES3.EncryptionType)EditorGUILayout.EnumPopup("Encryption", settings.encryptionType); + settings.encryptionPassword = EditorGUILayout.TextField("Encryption Password", settings.encryptionPassword); + + EditorGUILayout.Space(); + + settings.compressionType = (ES3.CompressionType)EditorGUILayout.EnumPopup("Compression", settings.compressionType); + + EditorGUILayout.Space(); + + settings.saveChildren = EditorGUILayout.Toggle("Save GameObject Children", settings.saveChildren); + + EditorGUILayout.Space(); + + if(settings.showAdvancedSettings = EditorGUILayout.Foldout(settings.showAdvancedSettings, "Advanced Settings")) + { + EditorGUILayout.BeginVertical(style.area); + + settings.format = (ES3.Format)EditorGUILayout.EnumPopup("Format", settings.format); + if (settings.format == ES3.Format.JSON) + settings.prettyPrint = EditorGUILayout.Toggle(new GUIContent("Pretty print JSON"), settings.prettyPrint); + settings.bufferSize = EditorGUILayout.IntField("Buffer Size", settings.bufferSize); + settings.memberReferenceMode = (ES3.ReferenceMode)EditorGUILayout.EnumPopup("Serialise Unity Object fields", settings.memberReferenceMode); + settings.serializationDepthLimit = EditorGUILayout.IntField("Serialisation Depth", settings.serializationDepthLimit); + settings.postprocessRawCachedData = EditorGUILayout.Toggle(new GUIContent("Postprocess raw cached data"), settings.postprocessRawCachedData); + + EditorGUILayout.Space(); + + EditorGUILayout.EndVertical(); + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3SettingsEditor.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3SettingsEditor.cs.meta new file mode 100644 index 0000000..be6af3c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3SettingsEditor.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 35659b9a083a341d7bee216c4b71f4bc +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Window.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Window.cs new file mode 100644 index 0000000..98d6aca --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Window.cs @@ -0,0 +1,238 @@ +using UnityEngine; +using UnityEditor; +using System.Linq; + +namespace ES3Editor +{ + public class ES3Window : EditorWindow + { + private SubWindow[] windows = null; + + public SubWindow currentWindow; + + [MenuItem("Window/Easy Save 3", false, 1000)] + [MenuItem("Assets/Easy Save 3/Open Easy Save 3 Window", false, 1000)] + public static void Init() + { + // Get existing open window or if none, make a new one: + ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window)); + if(window != null) + window.Show(); + } + + public static void InitAndShowHome() + { + // Get existing open window or if none, make a new one: + ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window)); + if (window != null) + { + window.Show(); + window.SetCurrentWindow(typeof(HomeWindow)); + } + } + + [MenuItem("Tools/Easy Save 3/Auto Save", false, 100)] + public static void InitAndShowAutoSave() + { + // Get existing open window or if none, make a new one: + ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window)); + if (window != null) + { + window.Show(); + window.SetCurrentWindow(typeof(AutoSaveWindow)); + } + } + + public static void InitAndShowReferences() + { + // Get existing open window or if none, make a new one: + ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window)); + if (window != null) + { + window.Show(); + window.SetCurrentWindow(typeof(ReferencesWindow)); + } + } + + [MenuItem("Tools/Easy Save 3/Types", false, 100)] + public static void InitAndShowTypes() + { + // Get existing open window or if none, make a new one: + ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window)); + if (window != null) + { + window.Show(); + window.SetCurrentWindow(typeof(TypesWindow)); + } + } + + public static void InitAndShowTypes(System.Type type) + { + // Get existing open window or if none, make a new one: + ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window)); + if (window != null) + { + window.Show(); + var typesWindow = (TypesWindow)window.SetCurrentWindow(typeof(TypesWindow)); + typesWindow.SelectType(type); + } + } + + [MenuItem("Tools/Easy Save 3/Settings", false, 100)] + public static void InitAndShowSettings() + { + // Get existing open window or if none, make a new one: + ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window)); + if (window != null) + { + window.Show(); + window.SetCurrentWindow(typeof(SettingsWindow)); + } + } + + [MenuItem("Tools/Easy Save 3/Tools", false, 100)] + public static void InitAndShowTools() + { + // Get existing open window or if none, make a new one: + ES3Window window = (ES3Window)EditorWindow.GetWindow(typeof(ES3Window)); + if (window != null) + { + window.Show(); + window.SetCurrentWindow(typeof(ToolsWindow)); + } + } + + public void InitSubWindows() + { + windows = new SubWindow[]{ + new HomeWindow(this), + new SettingsWindow(this), + new ToolsWindow(this), + new TypesWindow(this), + new AutoSaveWindow(this) + //, new ReferencesWindow(this) + }; + } + + void OnLostFocus() + { + if(currentWindow != null) + currentWindow.OnLostFocus(); + } + + private void OnFocus() + { + if (currentWindow != null) + currentWindow.OnFocus(); + } + + void OnDestroy() + { + if(currentWindow != null) + currentWindow.OnDestroy(); + } + + void OnEnable() + { + if(windows == null) + InitSubWindows(); + // Set the window name and icon. + var icon = AssetDatabase.LoadAssetAtPath(ES3Settings.PathToEasySaveFolder()+"Editor/es3Logo16x16.png"); + titleContent = new GUIContent("Easy Save", icon); + + // Get the last opened window and open it. + if(currentWindow == null) + { + var currentWindowName = EditorPrefs.GetString("ES3Editor.Window.currentWindow", windows[0].name); + for(int i=0; i w.GetType() == type); + EditorPrefs.SetString("ES3Editor.Window.currentWindow", currentWindow.name); + return currentWindow; + } + + // Shows the Easy Save Home window if it's not been disabled. + // This method is called from the Postprocessor. + public static void OpenEditorWindowOnStart() + { + if(EditorPrefs.GetBool("Show ES3 Window on Start", true)) + ES3Window.InitAndShowHome(); + EditorPrefs.SetBool("Show ES3 Window on Start", false); + } + } + + public abstract class SubWindow + { + public string name; + public EditorWindow parent; + public abstract void OnGUI(); + + public SubWindow(string name, EditorWindow parent) + { + this.name = name; + this.parent = parent; + } + + public virtual void OnLostFocus() + { + } + + public virtual void OnFocus() + { + } + + public virtual void OnDestroy() + { + } + + public virtual void OnHierarchyChange() + { + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Window.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Window.cs.meta new file mode 100644 index 0000000..0f5ce70 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ES3Window.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a95d98897f1cf4e7288b53b0fd8036c1 +timeCreated: 1519132293 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/EnableES3AssemblyDefinitions.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/EnableES3AssemblyDefinitions.cs new file mode 100644 index 0000000..e6be747 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/EnableES3AssemblyDefinitions.cs @@ -0,0 +1,23 @@ +using UnityEditor; +using System.IO; + +public class EnableES3AssemblyDefinitions : Editor +{ + [MenuItem("Tools/Easy Save 3/Enable Assembly Definition Files", false, 150)] + public static void EnableAsmDef() + { + var pathToEasySaveFolder = ES3Settings.PathToEasySaveFolder(); + File.Delete(pathToEasySaveFolder + "Editor/EasySave3.asmdef.disabled.meta"); + File.Delete(pathToEasySaveFolder + "Editor/EasySave3Editor.asmdef.disabled.meta"); + File.Move(pathToEasySaveFolder + "Editor/EasySave3Editor.asmdef.disabled", pathToEasySaveFolder + "Editor/EasySave3Editor.asmdef"); + File.Move(pathToEasySaveFolder + "Editor/EasySave3.asmdef.disabled", pathToEasySaveFolder + "EasySave3.asmdef"); + AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); + EditorUtility.DisplayDialog("Assembly definition files installed", "Assembly definition files for Easy Save 3 installed.\n\nYou may need to go to 'Assets > Reimport' to apply the changes.", "Done"); + } + + [MenuItem("Tools/Easy Save 3/Enable Assembly Definition Files", true, 150)] + public static bool CanEnableAsmDef() + { + return !File.Exists(ES3Settings.PathToEasySaveFolder() + "EasySave3.asmdef"); + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/EnableES3AssemblyDefinitions.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/EnableES3AssemblyDefinitions.cs.meta new file mode 100644 index 0000000..0144526 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/EnableES3AssemblyDefinitions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f53975dae5ac26947856dd0b0bd3be7e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/HomeWindow.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/HomeWindow.cs new file mode 100644 index 0000000..5e86054 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/HomeWindow.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; + +namespace ES3Editor +{ + public class HomeWindow : SubWindow + { + Vector2 scrollPos = Vector2.zero; + + public HomeWindow(EditorWindow window) : base("Home", window){} + + public override void OnGUI() + { + + var style = EditorStyle.Get; + + scrollPos = EditorGUILayout.BeginScrollView(scrollPos); + + EditorGUILayout.BeginVertical(style.area); + + GUILayout.Label("Welcome to Easy Save", style.heading); + + EditorGUILayout.BeginVertical(style.area); + GUILayout.Label("New To Easy Save?", style.subheading); + EditorGUILayout.BeginVertical(style.area); + ES3EditorUtility.DisplayLink("• See our Getting Started guide", "http://docs.moodkie.com/easy-save-3/getting-started/"); + EditorGUILayout.EndVertical(); + + GUILayout.Label("Support", style.subheading); + + EditorGUILayout.BeginVertical(style.area); + + ES3EditorUtility.DisplayLink("• Contact us directly", "http://www.moodkie.com/contact/"); + ES3EditorUtility.DisplayLink("• Ask a question in our Easy Save 3 forums", "http://moodkie.com/forum/viewforum.php?f=12"); + ES3EditorUtility.DisplayLink("• Ask a question in the Unity Forum thread","https://forum.unity3d.com/threads/easy-save-the-complete-save-load-asset-for-unity.91040/"); + EditorGUILayout.EndVertical(); + + GUILayout.Label("Documentation and Guides", style.subheading); + + EditorGUILayout.BeginVertical(style.area); + + ES3EditorUtility.DisplayLink("• Documentation", "http://docs.moodkie.com/product/easy-save-3/"); + ES3EditorUtility.DisplayLink("• Guides", "http://docs.moodkie.com/product/easy-save-3/es3-guides/"); + ES3EditorUtility.DisplayLink("• API Scripting Reference", "http://docs.moodkie.com/product/easy-save-3/es3-api/"); + ES3EditorUtility.DisplayLink("• Supported Types", "http://docs.moodkie.com/easy-save-3/es3-supported-types/"); + + + EditorGUILayout.EndVertical(); + + GUILayout.Label("PlayMaker Documentation", style.subheading); + + EditorGUILayout.BeginVertical(style.area); + + ES3EditorUtility.DisplayLink("• Actions", "http://docs.moodkie.com/product/easy-save-3/es3-playmaker/es3-playmaker-actions/"); + ES3EditorUtility.DisplayLink("• Actions Overview", "http://docs.moodkie.com/easy-save-3/es3-playmaker/playmaker-actions-overview/"); + + + EditorGUILayout.EndVertical(); + + EditorGUILayout.EndVertical(); + + EditorGUILayout.EndVertical(); + + EditorGUILayout.EndScrollView(); + + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/HomeWindow.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/HomeWindow.cs.meta new file mode 100644 index 0000000..cf019eb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/HomeWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 394cc2e77038849709526f44f7efdd22 +timeCreated: 1519132283 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ReferencesWindow.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ReferencesWindow.cs new file mode 100644 index 0000000..57c4441 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ReferencesWindow.cs @@ -0,0 +1,21 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using ES3Internal; + +namespace ES3Editor +{ + public class ReferencesWindow : SubWindow + { + + + public ReferencesWindow(EditorWindow window) : base("References", window){} + + public override void OnGUI() + { + + } + } + +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ReferencesWindow.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ReferencesWindow.cs.meta new file mode 100644 index 0000000..5e132e9 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ReferencesWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: af2d805793e784eef87fbcdebb11fa35 +timeCreated: 1519132291 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/SettingsWindow.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/SettingsWindow.cs new file mode 100644 index 0000000..0c3e4d6 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/SettingsWindow.cs @@ -0,0 +1,179 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using ES3Internal; + +namespace ES3Editor +{ + public class SettingsWindow : SubWindow + { + public ES3Defaults editorSettings = null; + public ES3SerializableSettings settings = null; + public SerializedObject so = null; + public SerializedProperty referenceFoldersProperty = null; + + Vector2 scrollPos = Vector2.zero; + const string disableGlobalDefineName = "ES3GLOBAL_DISABLED"; + + public SettingsWindow(EditorWindow window) : base("Settings", window){} + + public void OnEnable() + { + + } + + public override void OnGUI() + { + if(settings == null || editorSettings == null) + Init(); + + var style = EditorStyle.Get; + + var labelWidth = EditorGUIUtility.labelWidth; + + + EditorGUI.BeginChangeCheck(); + + using (var scrollView = new EditorGUILayout.ScrollViewScope(scrollPos, style.area)) + { + scrollPos = scrollView.scrollPosition; + + EditorGUIUtility.labelWidth = 160; + + GUILayout.Label("Runtime Settings", style.heading); + + using (new EditorGUILayout.VerticalScope(style.area)) + { + ES3SettingsEditor.Draw(settings); + } + + GUILayout.Label("Debug Settings", style.heading); + + using (new EditorGUILayout.VerticalScope(style.area)) + { + EditorGUIUtility.labelWidth = 100; + + using (new EditorGUILayout.HorizontalScope()) + { + EditorGUILayout.PrefixLabel("Log Info"); + editorSettings.logDebugInfo = EditorGUILayout.Toggle(editorSettings.logDebugInfo); + } + + using (new EditorGUILayout.HorizontalScope()) + { + EditorGUILayout.PrefixLabel("Log Warnings"); + editorSettings.logWarnings = EditorGUILayout.Toggle(editorSettings.logWarnings); + } + + using (new EditorGUILayout.HorizontalScope()) + { + EditorGUILayout.PrefixLabel("Log Errors"); + editorSettings.logErrors = EditorGUILayout.Toggle(editorSettings.logErrors); + } + + EditorGUILayout.Space(); + } + + GUILayout.Label("Editor Settings", style.heading); + + using (new EditorGUILayout.VerticalScope(style.area)) + { + EditorGUIUtility.labelWidth = 170; + + using (new EditorGUILayout.HorizontalScope()) + { + EditorGUILayout.PrefixLabel("Auto Update References"); + editorSettings.autoUpdateReferences = EditorGUILayout.Toggle(editorSettings.autoUpdateReferences); + } + + if (editorSettings.autoUpdateReferences) + { + using (new EditorGUILayout.HorizontalScope()) + { + var content = new GUIContent("-- When changes are made", "Should Easy Save update the reference manager when objects in your scene changes?"); + editorSettings.updateReferencesWhenSceneChanges = EditorGUILayout.Toggle(content, editorSettings.updateReferencesWhenSceneChanges); + } + + using (new EditorGUILayout.HorizontalScope()) + { + var content = new GUIContent("-- When scene is saved", "Should Easy Save update the reference manager when objects in your scene is saved?"); + editorSettings.updateReferencesWhenSceneIsSaved = EditorGUILayout.Toggle(content, editorSettings.updateReferencesWhenSceneIsSaved); + } + + using (new EditorGUILayout.HorizontalScope()) + { + var content = new GUIContent("-- When scene is opened", "Should Easy Save update the reference manager you open a scene in the Editor?"); + editorSettings.updateReferencesWhenSceneIsOpened = EditorGUILayout.Toggle(content, editorSettings.updateReferencesWhenSceneIsOpened); + } + EditorGUILayout.Space(); + } + + using (new EditorGUILayout.HorizontalScope()) + { + so.Update(); + EditorGUILayout.PropertyField(referenceFoldersProperty, true); + so.ApplyModifiedProperties(); + } + EditorGUILayout.Space(); + + /*using (new EditorGUILayout.HorizontalScope()) + { + var content = new GUIContent("Reference depth", "How deep should Easy Save look when gathering references from an object? Higher means deeper."); + EditorGUILayout.PrefixLabel(content); + editorSettings.collectDependenciesDepth = EditorGUILayout.IntField(editorSettings.collectDependenciesDepth); + }*/ + + using (new EditorGUILayout.HorizontalScope()) + { + var content = new GUIContent("Reference timeout (seconds)", "How many seconds should Easy Save taking collecting references for an object before timing out?"); + EditorGUILayout.PrefixLabel(content); + editorSettings.collectDependenciesTimeout = EditorGUILayout.IntField(editorSettings.collectDependenciesTimeout); + } + + using (new EditorGUILayout.HorizontalScope()) + { + EditorGUILayout.PrefixLabel("Use Global References"); + + bool useGlobalReferences = !ES3ScriptingDefineSymbols.HasDefineSymbol(disableGlobalDefineName); + if(EditorGUILayout.Toggle(useGlobalReferences) != useGlobalReferences) + { + // If global references is currently enabled, we want to disable it. + if (!useGlobalReferences) + { + ES3ScriptingDefineSymbols.RemoveDefineSymbol(disableGlobalDefineName); + EditorUtility.DisplayDialog("Global references disabled for build platform", "This will only disable Global References for this build platform. To disable it for other build platforms, open that platform in the Build Settings and uncheck this box again.", "Ok"); + } + // Else we want to enable it. + else + ES3ScriptingDefineSymbols.SetDefineSymbol(disableGlobalDefineName); + } + } + + using (new EditorGUILayout.HorizontalScope()) + { + var content = new GUIContent("Add All Prefabs to Manager", "Should all prefabs with ES3Prefab Components be added to the manager?"); + EditorGUILayout.PrefixLabel(content); + editorSettings.addAllPrefabsToManager = EditorGUILayout.Toggle(editorSettings.addAllPrefabsToManager); + } + + EditorGUILayout.Space(); + } + } + + if (EditorGUI.EndChangeCheck()) + EditorUtility.SetDirty(editorSettings); + + EditorGUIUtility.labelWidth = labelWidth; // Set the label width back to default + } + + public void Init() + { + editorSettings = ES3Settings.defaultSettingsScriptableObject; + settings = editorSettings.settings; + so = new SerializedObject(editorSettings); + referenceFoldersProperty = so.FindProperty("referenceFolders"); + } + } + +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/SettingsWindow.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/SettingsWindow.cs.meta new file mode 100644 index 0000000..d58da5f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/SettingsWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 95e7bbc9a5aee44feb088811fb5e7b80 +timeCreated: 1519132291 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ToolsWindow.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ToolsWindow.cs new file mode 100644 index 0000000..4518e37 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ToolsWindow.cs @@ -0,0 +1,155 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using System.IO; + +namespace ES3Editor +{ + public class ToolsWindow : SubWindow + { + public ToolsWindow(EditorWindow window) : base("Tools", window){} + + public override void OnGUI() + { + var style = EditorStyle.Get; + + EditorGUILayout.BeginHorizontal(style.area); + + if (GUILayout.Button("Open Persistent Data Path")) + OpenPersistentDataPath(); + + EditorGUILayout.EndHorizontal(); + + EditorGUILayout.BeginHorizontal(style.area); + + if (GUILayout.Button("Clear Persistent Data Path")) + ClearPersistentDataPath(); + + if (GUILayout.Button("Clear PlayerPrefs")) + ClearPlayerPrefs(); + + EditorGUILayout.EndHorizontal(); + } + + [MenuItem("Tools/Easy Save 3/Open Persistent Data Path", false, 200)] + private static void OpenPersistentDataPath() + { + EditorUtility.RevealInFinder(Application.persistentDataPath); + } + + [MenuItem("Tools/Easy Save 3/Clear Persistent Data Path", false, 200)] + private static void ClearPersistentDataPath() + { + if (EditorUtility.DisplayDialog("Clear Persistent Data Path", "Are you sure you wish to clear the persistent data path?\n This action cannot be reversed.", "Clear", "Cancel")) + { + System.IO.DirectoryInfo di = new DirectoryInfo(Application.persistentDataPath); + + foreach (FileInfo file in di.GetFiles()) + file.Delete(); + foreach (DirectoryInfo dir in di.GetDirectories()) + dir.Delete(true); + } + } + + [MenuItem("Tools/Easy Save 3/Clear PlayerPrefs", false, 200)] + private static void ClearPlayerPrefs() + { + if (EditorUtility.DisplayDialog("Clear PlayerPrefs", "Are you sure you wish to clear PlayerPrefs?\nThis action cannot be reversed.", "Clear", "Cancel")) + PlayerPrefs.DeleteAll(); + } + } + + /*public static class OSFileBrowser + { + public static bool IsInMacOS + { + get + { + return UnityEngine.SystemInfo.operatingSystem.IndexOf("Mac OS") != -1; + } + } + + public static bool IsInWinOS + { + get + { + return UnityEngine.SystemInfo.operatingSystem.IndexOf("Windows") != -1; + } + } + + public static void OpenInMac(string path) + { + bool openInsidesOfFolder = false; + + // try mac + string macPath = path.Replace("\\", "/"); // mac finder doesn't like backward slashes + + if ( System.IO.Directory.Exists(macPath) ) // if path requested is a folder, automatically open insides of that folder + { + openInsidesOfFolder = true; + } + + if ( !macPath.StartsWith("\"") ) + { + macPath = "\"" + macPath; + } + + if ( !macPath.EndsWith("\"") ) + { + macPath = macPath + "\""; + } + + string arguments = (openInsidesOfFolder ? "" : "-R ") + macPath; + + try + { + System.Diagnostics.Process.Start("open", arguments); + } + catch ( System.ComponentModel.Win32Exception e ) + { + // tried to open mac finder in windows + // just silently skip error + // we currently have no platform define for the current OS we are in, so we resort to this + e.HelpLink = ""; // do anything with this variable to silence warning about not using it + } + } + + public static void OpenInWin(string path) + { + bool openInsidesOfFolder = false; + + // try windows + string winPath = path.Replace("/", "\\"); // windows explorer doesn't like forward slashes + + if ( System.IO.Directory.Exists(winPath) ) // if path requested is a folder, automatically open insides of that folder + openInsidesOfFolder = true; + + try + { + System.Diagnostics.Process.Start("explorer.exe", (openInsidesOfFolder ? "/root," : "/select,") + "\"" + winPath + "\""); + } + catch ( System.ComponentModel.Win32Exception e ) + { + e.HelpLink = ""; + } + } + + public static void Open(string path) + { + if ( IsInWinOS ) + { + OpenInWin(path); + } + else if ( IsInMacOS ) + { + OpenInMac(path); + } + else // couldn't determine OS + { + OpenInWin(path); + OpenInMac(path); + } + } + }*/ +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ToolsWindow.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ToolsWindow.cs.meta new file mode 100644 index 0000000..c6fbe3f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/ToolsWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0d6114c1d40624e9e8575e814c45ac1a +timeCreated: 1519132280 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/TypesWindow.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/TypesWindow.cs new file mode 100644 index 0000000..37d83fb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/TypesWindow.cs @@ -0,0 +1,728 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEditor; +using System; +using System.Reflection; +using System.Linq; +using ES3Types; +using System.IO; +using ES3Internal; +using System.Text.RegularExpressions; + +namespace ES3Editor +{ + public class TypesWindow : SubWindow + { + TypeListItem[] types = null; + const int recentTypeCount = 5; + List recentTypes = null; + + Vector2 typeListScrollPos = Vector2.zero; + Vector2 typePaneScrollPos = Vector2.zero; + int leftPaneWidth = 300; + + string searchFieldValue = ""; + + int selectedType = -1; + private ES3Reflection.ES3ReflectedMember[] fields = new ES3Reflection.ES3ReflectedMember[0]; + private bool[] fieldSelected = new bool[0]; + + private Texture2D checkmark; + //private Texture2D checkmarkSmall; + + private GUIStyle searchBarStyle; + private GUIStyle searchBarCancelButtonStyle; + private GUIStyle leftPaneStyle; + private GUIStyle typeButtonStyle; + private GUIStyle selectedTypeButtonStyle; + private GUIStyle selectAllNoneButtonStyle; + + private string valueTemplateFile; + private string classTemplateFile; + private string componentTemplateFile; + private string scriptableObjectTemplateFile; + + private bool unsavedChanges = false; + + public TypesWindow(EditorWindow window) : base("Types", window){} + + public override void OnGUI() + { + if(types == null) + Init(); + + EditorGUILayout.BeginHorizontal(); + + EditorGUILayout.BeginVertical(leftPaneStyle); + SearchBar(); + TypeList(); + EditorGUILayout.EndVertical(); + EditorGUILayout.BeginVertical(); + TypePane(); + EditorGUILayout.EndVertical(); + + EditorGUILayout.EndHorizontal(); + } + + private void SearchBar() + { + var style = EditorStyle.Get; + + GUILayout.Label("Enter a type name in the field below\n* Type names are case-sensitive *", style.subheading2); + + EditorGUILayout.BeginHorizontal(); + + // Set control name so we can force a Focus reset for it. + string currentSearchFieldValue = EditorGUILayout.TextField(searchFieldValue, searchBarStyle); + + if(searchFieldValue != currentSearchFieldValue) + { + searchFieldValue = currentSearchFieldValue; + PerformSearch(currentSearchFieldValue); + } + + GUI.SetNextControlName("Clear"); + + if(GUILayout.Button("x", searchBarCancelButtonStyle)) + { + searchFieldValue = ""; + GUI.FocusControl("Clear"); + PerformSearch(""); + } + + EditorGUILayout.EndHorizontal(); + } + + private void RecentTypeList() + { + if(!string.IsNullOrEmpty(searchFieldValue) || recentTypes.Count == 0) + return; + + for(int i=recentTypes.Count-1; i>-1; i--) + TypeButton(recentTypes[i]); + + EditorGUILayout.TextArea("",GUI.skin.horizontalSlider); + + } + + private void TypeList() + { + if(!string.IsNullOrEmpty(searchFieldValue)) + GUILayout.Label("Search Results", EditorStyles.boldLabel); + + typeListScrollPos = EditorGUILayout.BeginScrollView(typeListScrollPos); + + RecentTypeList(); + + if(!string.IsNullOrEmpty(searchFieldValue)) + for(int i = 0; i < types.Length; i++) + TypeButton(i); + + EditorGUILayout.EndScrollView(); + } + + private void TypePane() + { + if(selectedType < 0) + return; + + var style = EditorStyle.Get; + + var typeListItem = types[selectedType]; + var type = typeListItem.type; + + typePaneScrollPos = EditorGUILayout.BeginScrollView(typePaneScrollPos, style.area); + + GUILayout.Label(typeListItem.name, style.subheading); + GUILayout.Label(typeListItem.namespaceName); + + EditorGUILayout.BeginVertical(style.area); + + bool hasParameterlessConstructor = ES3Reflection.HasParameterlessConstructor(type); + bool isComponent = ES3Reflection.IsAssignableFrom(typeof(Component), type); + + string path = GetOutputPath(types[selectedType].type); + // An ES3Type file already exists. + if(File.Exists(path)) + { + if(hasParameterlessConstructor || isComponent) + { + EditorGUILayout.BeginHorizontal(); + if(GUILayout.Button("Reset to Default")) + { + SelectNone(true, true); + AssetDatabase.MoveAssetToTrash("Assets" + path.Remove(0, Application.dataPath.Length)); + SelectType(selectedType); + } + if(GUILayout.Button("Edit ES3Type Script")) + AssetDatabase.OpenAsset(AssetDatabase.LoadMainAssetAtPath("Assets" + path.Remove(0, Application.dataPath.Length))); + EditorGUILayout.EndHorizontal(); + } + else + { + EditorGUILayout.HelpBox("This type has no public parameterless constructors.\n\nTo support this type you will need to modify the ES3Type script to use a specific constructor instead of the parameterless constructor.", MessageType.Info); + if(GUILayout.Button("Click here to edit the ES3Type script")) + AssetDatabase.OpenAsset(AssetDatabase.LoadMainAssetAtPath("Assets" + path.Remove(0, Application.dataPath.Length))); + if (GUILayout.Button("Reset to Default")) + { + SelectAll(true, true); + File.Delete(path); + AssetDatabase.Refresh(); + } + } + } + // No ES3Type file and no fields. + else if(fields.Length == 0) + { + if(!hasParameterlessConstructor && !isComponent) + EditorGUILayout.HelpBox("This type has no public parameterless constructors.\n\nTo support this type you will need to create an ES3Type script and modify it to use a specific constructor instead of the parameterless constructor.", MessageType.Info); + + if(GUILayout.Button("Create ES3Type Script")) + Generate(); + } + // No ES3Type file, but fields are selectable. + else + { + if(!hasParameterlessConstructor && !isComponent) + { + EditorGUILayout.HelpBox("This type has no public parameterless constructors.\n\nTo support this type you will need to select the fields you wish to serialize below, and then modify the generated ES3Type script to use a specific constructor instead of the parameterless constructor.", MessageType.Info); + if(GUILayout.Button("Select all fields and generate ES3Type script")) + { + SelectAll(true, false); + Generate(); + } + } + else + { + if(GUILayout.Button("Create ES3Type Script")) + Generate(); + } + } + + EditorGUILayout.EndVertical(); + + PropertyPane(); + + EditorGUILayout.EndScrollView(); + } + + private void PropertyPane() + { + var style = EditorStyle.Get; + + EditorGUILayout.BeginVertical(style.area); + + GUILayout.Label("Fields", EditorStyles.boldLabel); + + DisplayFieldsOrProperties(true, false); + EditorGUILayout.Space(); + + GUILayout.Label("Properties", EditorStyles.boldLabel); + + DisplayFieldsOrProperties(false, true); + EditorGUILayout.EndVertical(); + } + + private void DisplayFieldsOrProperties(bool showFields, bool showProperties) + { + // Get field and property counts. + int fieldCount = 0; + int propertyCount = 0; + for(int i=0; i 0 || propertyCount > 0) + { + EditorGUILayout.BeginHorizontal(); + + if(GUILayout.Button("Select All", selectAllNoneButtonStyle)) + { + SelectAll(showFields, showProperties); + Generate(); + } + + if(GUILayout.Button("Select None", selectAllNoneButtonStyle)) + { + SelectNone(showFields, showProperties); + Generate(); + } + EditorGUILayout.EndHorizontal(); + } + + for(int i=0; i item.Name == fields[i].Name); + return; + } + + // Get fields and whether they're selected. + var selectedFields = new List(); + var propertyAttributes = es3Type.GetType().GetCustomAttributes(typeof(ES3PropertiesAttribute), false); + if(propertyAttributes.Length > 0) + selectedFields.AddRange(((ES3PropertiesAttribute)propertyAttributes[0]).members); + + fieldSelected = new bool[fields.Length]; + + for(int i=0; i (); + + var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !assembly.FullName.Contains("Editor") && assembly.FullName != "ES3" && !assembly.FullName.Contains("ES3")).OrderBy(assembly => assembly.GetName().Name).ToArray(); + + foreach (var assembly in assemblies) + { + var assemblyTypes = assembly.GetTypes(); + + for(int i = 0; i < assemblyTypes.Length; i++) + { + var type = assemblyTypes [i]; + if(type.IsGenericType || type.IsEnum || type.IsNotPublic || type.IsAbstract || type.IsInterface) + continue; + + var typeName = type.Name; + if(typeName.Length >= 3 && typeName [0] == '$' || typeName [0] == '_' || typeName [0] == '<') + continue; + + var typeNamespace = type.Namespace; + var namespaceName = typeNamespace == null ? "" : typeNamespace.ToString(); + + tempTypes.Add(new TypeListItem (type.Name, namespaceName, type, true, HasExplicitES3Type(type))); + } + + } + types = tempTypes.OrderBy(type => type.name).ToArray(); + + // Load types and recent types. + if (recentTypes == null) + { + recentTypes = new List(); + for (int i = 0; i < recentTypeCount; i++) + { + int typeIndex = LoadTypeIndex("TypesWindowRecentType" + i); + if (typeIndex != -1) + recentTypes.Add(typeIndex); + } + SelectType(LoadTypeIndex("TypesWindowSelectedType")); + } + + + PerformSearch(searchFieldValue); + + // Init Assets. + string es3FolderPath = ES3Settings.PathToEasySaveFolder(); + checkmark = AssetDatabase.LoadAssetAtPath(es3FolderPath + "Editor/checkmark.png"); + //checkmarkSmall = AssetDatabase.LoadAssetAtPath(es3FolderPath + "Editor/checkmarkSmall.png"); + + // Init Styles. + searchBarCancelButtonStyle = new GUIStyle(EditorStyles.miniButton); + var cancelButtonSize = EditorStyles.miniTextField.CalcHeight(new GUIContent(""), 20); + searchBarCancelButtonStyle.fixedWidth = cancelButtonSize; + searchBarCancelButtonStyle.fixedHeight = cancelButtonSize; + searchBarCancelButtonStyle.fontSize = 8; + searchBarCancelButtonStyle.padding = new RectOffset(); + searchBarStyle = new GUIStyle(EditorStyles.toolbarTextField); + searchBarStyle.stretchWidth = true; + + typeButtonStyle = new GUIStyle(EditorStyles.largeLabel); + typeButtonStyle.alignment = TextAnchor.MiddleLeft; + typeButtonStyle.stretchWidth = false; + selectedTypeButtonStyle = new GUIStyle(typeButtonStyle); + selectedTypeButtonStyle.fontStyle = FontStyle.Bold; + + leftPaneStyle = new GUIStyle(); + leftPaneStyle.fixedWidth = leftPaneWidth; + leftPaneStyle.clipping = TextClipping.Clip; + leftPaneStyle.padding = new RectOffset(10, 10, 10, 10); + + selectAllNoneButtonStyle = new GUIStyle(EditorStyles.miniButton); + selectAllNoneButtonStyle.stretchWidth = false; + selectAllNoneButtonStyle.margin = new RectOffset(0,0,0,10); + } + + private void Generate() + { + var type = types[selectedType].type; + if(type == null) + { + EditorUtility.DisplayDialog("Type not selected", "Type not selected. Please ensure you select a type", "Ok"); + return; + } + + unsavedChanges = false; + + // Get the serializable fields of this class. + //var fields = ES3Reflection.GetSerializableES3Fields(type); + + // The string that we suffix to the class name. i.e. UnityEngine_UnityEngine_Transform. + string es3TypeSuffix = type.Name; + // The string for the full C#-safe type name. This name must be suitable for going inside typeof(). + string fullType = GetFullTypeName(type); + // The list of WriteProperty calls to write the properties of this type. + string writes = GenerateWrites(); + // The list of case statements and Read calls to read the properties of this type. + string reads = GenerateReads(); + // A comma-seperated string of fields we've supported in this type. + string propertyNames = ""; + + bool first = true; + for(int i=0; i(), instance);\r\n\t\t\t\t\tbreak;", field.Name, fieldTypeName); + else + reads += String.Format("\r\n\t\t\t\t\tcase \"{0}\":\r\n\t\t\t\t\tinstance = ([fullType])reader.SetPrivateField(\"{0}\", reader.Read<{1}>(), instance);\r\n\t\t\t\t\tbreak;", field.Name, fieldTypeName); + } + else + reads += String.Format("\r\n\t\t\t\t\tcase \"{0}\":\r\n\t\t\t\t\t\t{3}.{0} = reader.Read<{1}>({2});\r\n\t\t\t\t\t\tbreak;", field.Name, fieldTypeName, es3TypeParam, instance); + } + return reads; + } + + private string GetOutputPath(Type type) + { + return Application.dataPath + "/Easy Save 3/Types/ES3UserType_"+type.Name+".cs"; + } + + /* Gets the full Type name, replacing any syntax (such as '+') with a dot to make it a valid type name */ + private static string GetFullTypeName(Type type) + { + string typeName = type.ToString(); + + typeName = typeName.Replace('+','.'); + + // If it's a generic type, replace syntax with angled brackets. + int genericArgumentCount = type.GetGenericArguments().Length; + if(genericArgumentCount > 0) + { + return string.Format("{0}<{1}>", type.ToString().Split('`')[0], string.Join(", ", type.GetGenericArguments().Select(x => GetFullTypeName(x)).ToArray())); + } + + return typeName; + } + + /* Whether this type has an explicit ES3Type. For example, ES3ArrayType would return false, but ES3Vector3ArrayType would return true */ + private static bool HasExplicitES3Type(Type type) + { + var es3Type = ES3TypeMgr.GetES3Type(type); + if(es3Type == null) + return false; + // If this ES3Type has a static Instance property, return true. + if(es3Type.GetType().GetField("Instance", BindingFlags.Public | BindingFlags.Static) != null) + return true; + return false; + } + + private static bool HasExplicitES3Type(ES3Type es3Type) + { + if(es3Type == null) + return false; + // If this ES3Type has a static Instance property, return true. + if(es3Type.GetType().GetField("Instance", BindingFlags.Public | BindingFlags.Static) != null) + return true; + return false; + } + + public class TypeListItem + { + public string name; + public string lowercaseName; + public string namespaceName; + public Type type; + public bool showInList; + public bool hasExplicitES3Type; + + public TypeListItem(string name, string namespaceName, Type type, bool showInList, bool hasExplicitES3Type) + { + this.name = name; + this.lowercaseName = name.ToLowerInvariant(); + this.namespaceName = namespaceName; + this.type = type; + this.showInList = showInList; + this.hasExplicitES3Type = hasExplicitES3Type; + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/TypesWindow.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/TypesWindow.cs.meta new file mode 100644 index 0000000..7505034 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Editor/TypesWindow.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 600b987de172f4a82b182077ceb7fffa +timeCreated: 1519132286 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/PlayMaker.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/PlayMaker.meta new file mode 100644 index 0000000..9e13dbc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/PlayMaker.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6c2c381dbeebc6340b10fc96c19a56c2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/PlayMaker/ES3PlayMaker.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/PlayMaker/ES3PlayMaker.cs new file mode 100644 index 0000000..8d478c7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/PlayMaker/ES3PlayMaker.cs @@ -0,0 +1,1907 @@ +#if PLAYMAKER_1_8_OR_NEWER + +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using ES3Internal; +using HutongGames.PlayMaker.Actions; +using HutongGames.PlayMaker; +using System.Linq; +using System; +using Tooltip = HutongGames.PlayMaker.TooltipAttribute; + +public class FsmES3File : ScriptableObject +{ + public ES3File file; +} + +public class FsmES3Spreadsheet : ScriptableObject +{ + public ES3Spreadsheet spreadsheet; +} + +namespace ES3PlayMaker +{ + + #region Base Classes + + public abstract class ActionBase : FsmStateAction + { + [ActionSection("Error handling")] + [Tooltip("This event is triggered if an error occurs.")] + public FsmEvent errorEvent; + [Tooltip("If an error occurs, the error message will be stored in this variable.")] + public FsmString errorMessage; + + public abstract void Enter(); + public abstract void OnReset(); + + public override void OnEnter() + { + try + { + Enter(); + } + catch (System.Exception e) + { + HandleError(e.ToString()); + } + Finish(); + } + + public override void Reset() + { + errorEvent = null; + errorMessage = ""; + OnReset(); + } + + public void HandleError(string msg) + { + errorMessage.Value = msg; + if (errorEvent != null) + Fsm.Event(errorEvent); + else + LogError(msg); + } + } + + public abstract class SettingsAction : ActionBase + { + [ActionSection("Settings")] + public FsmBool overrideDefaultSettings = false; + [HutongGames.PlayMaker.HideIf("DefaultSettingsOverridden")] + [Tooltip("The path this ES3Settings object points to, if any.")] + public FsmString path; + [HutongGames.PlayMaker.HideIf("DefaultSettingsOverridden")] + [ObjectType(typeof(ES3.Location))] + [Tooltip("The storage location where we wish to store data by default.")] + public FsmEnum location; + [HutongGames.PlayMaker.HideIf("DefaultSettingsOverridden")] + [ObjectType(typeof(ES3.EncryptionType))] + [Tooltip("The type of encryption to use when encrypting data, if any.")] + public FsmEnum encryptionType; + [HutongGames.PlayMaker.HideIf("DefaultSettingsOverridden")] + [Tooltip("The password to use to encrypt the data if encryption is enabled.")] + public FsmString encryptionPassword; + [HutongGames.PlayMaker.HideIf("DefaultSettingsOverridden")] + [ObjectType(typeof(ES3.CompressionType))] + [Tooltip("The type of compression to use when compressing data, if any.")] + public FsmEnum compressionType; + [HutongGames.PlayMaker.HideIf("DefaultSettingsOverridden")] + [ObjectType(typeof(ES3.Directory))] + [Tooltip("The default directory in which to store files when using the File save location, and the location which relative paths should be relative to.")] + public FsmEnum directory; + [HutongGames.PlayMaker.HideIf("DefaultSettingsOverridden")] + [ObjectType(typeof(ES3.Format))] + [Tooltip("The format we should use when serializing and deserializing data.")] + public FsmEnum format; + [HutongGames.PlayMaker.HideIf("DefaultSettingsOverridden")] + [Tooltip("Any stream buffers will be set to this length in bytes.")] + public FsmInt bufferSize; + + public bool DefaultSettingsOverridden() + { + return !overrideDefaultSettings.Value; + } + + public override void Reset() + { + var settings = new ES3Settings(); + path = settings.path; + location = settings.location; + encryptionType = settings.encryptionType; + compressionType = settings.compressionType; + encryptionPassword = settings.encryptionPassword; + directory = settings.directory; + format = settings.format; + bufferSize = settings.bufferSize; + overrideDefaultSettings = false; + base.Reset(); + } + + public ES3Settings GetSettings() + { + var settings = new ES3Settings(); + if (overrideDefaultSettings.Value) + { + settings.path = path.Value; + settings.location = (ES3.Location)location.Value; + settings.encryptionType = (ES3.EncryptionType)encryptionType.Value; + settings.encryptionPassword = encryptionPassword.Value; + settings.compressionType = (ES3.CompressionType)compressionType.Value; + settings.directory = (ES3.Directory)directory.Value; + settings.format = (ES3.Format)format.Value; + settings.bufferSize = bufferSize.Value; + } + return settings; + } + } + + public abstract class ES3FileAction : ActionBase + { + [Tooltip("The ES3 File we are using, created using the Create ES3 File action.")] + [ObjectType(typeof(FsmES3File))] + [Title("ES3 File")] + [RequiredField] + public FsmObject fsmES3File; + + public ES3File es3File { get { return ((FsmES3File)fsmES3File.Value).file; } } + + public override void Reset() + { + fsmES3File = null; + base.Reset(); + } + } + + public abstract class ES3FileSettingsAction : SettingsAction + { + [Tooltip("The ES3File variable we're using.")] + [ObjectType(typeof(FsmES3File))] + [Title("ES3 File")] + [RequiredField] + public FsmObject fsmES3File; + + public ES3File es3File { get { return ((FsmES3File)fsmES3File.Value).file; } } + + public override void Reset() + { + fsmES3File = null; + base.Reset(); + } + } + + public abstract class ES3SpreadsheetAction : ActionBase + { + [Tooltip("The ES3 Spreadsheet we are using, created using the Create ES3 Spreadsheet action.")] + [ObjectType(typeof(FsmES3Spreadsheet))] + [Title("ES3 Spreadsheet")] + [RequiredField] + public FsmObject fsmES3Spreadsheet; + + public ES3Spreadsheet es3Spreadsheet { get { return ((FsmES3Spreadsheet)fsmES3Spreadsheet.Value).spreadsheet; } } + + public override void Reset() + { + fsmES3Spreadsheet = null; + base.Reset(); + } + } + + public abstract class ES3SpreadsheetSettingsAction : SettingsAction + { + [Tooltip("The ES3Spreadsheet variable we're using.")] + [ObjectType(typeof(FsmES3Spreadsheet))] + [Title("ES3 Spreadsheet")] + [RequiredField] + public FsmObject fsmES3Spreadsheet; + + public ES3Spreadsheet es3Spreadsheet { get { return ((FsmES3Spreadsheet)fsmES3Spreadsheet.Value).spreadsheet; } } + + public override void Reset() + { + fsmES3Spreadsheet = null; + base.Reset(); + } + } + + #endregion + + #region Save Actions + + [ActionCategory("Easy Save 3")] + [Tooltip("Saves the value to a file with the given key.")] + public class Save : SettingsAction + { + [Tooltip("The unique key we want to use to identity the data we are saving.")] + public FsmString key; + [Tooltip("The value we want to save.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar value; + + public override void OnReset() + { + key = "key"; + value = null; + } + + public override void Enter() + { + value.UpdateValue(); + + if (value.Type == VariableType.Array) + ES3.Save(key.Value, new PMDataWrapper(value.arrayValue.Values), GetSettings()); + else + ES3.Save(key.Value, value.GetValue(), GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Saves multiple values to a file with the given keys.")] + public class SaveMultiple : SettingsAction + { + [RequiredField] + [CompoundArray("Count", "Key", "Value")] + public FsmString[] keys; + [Tooltip("The value we want to save.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar[] variables; + + public override void OnReset() + { + keys = null; + variables = null; + } + + public override void Enter() + { + for (int i = 0; i < variables.Length; i++) + { + var key = keys[i]; + var value = variables[i]; + value.UpdateValue(); + + if (value.Type == VariableType.Array) + ES3.Save(key.Value, new PMDataWrapper(value.arrayValue.Values), GetSettings()); + else + ES3.Save(key.Value, value.GetValue(), GetSettings()); + } + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Saves all FsmVariables in this FSM to a file with the given key.")] + public class SaveAll : SettingsAction + { + [Tooltip("The unique key we want to use to identity the data we are saving.")] + public FsmString key; + + [Tooltip("Save the local variables accessible in this FSM?")] + public FsmBool saveFsmVariables = true; + [Tooltip("Save the global variables accessible in all FSMs?")] + public FsmBool saveGlobalVariables = true; + + public override void OnReset() + { + key = "key"; + } + + public override void Enter() + { + ES3.Save(key.Value, new PMDataWrapper(Fsm, saveFsmVariables.Value, saveGlobalVariables.Value), GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Saves a byte array as a file, overwriting any existing files.")] + public class SaveRaw : SettingsAction + { + [Tooltip("The string we want to save as a file.")] + public FsmString str; + [Tooltip("Whether to encode this string using Base-64 encoding. This will override any default encoding settings.")] + public FsmBool useBase64Encoding; + [Tooltip("Adds a newline to the end of the file.")] + public FsmBool appendNewline; + + public override void OnReset() + { + str = ""; + useBase64Encoding = false; + appendNewline = false; + } + + public override void Enter() + { + if (useBase64Encoding.Value) + ES3.SaveRaw(System.Convert.FromBase64String(str.Value + (appendNewline.Value ? "\n" : "")), GetSettings()); + else + ES3.SaveRaw(str.Value + (appendNewline.Value ? "\n" : ""), GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Appends a string to the end of a file.")] + public class AppendRaw : SettingsAction + { + [Tooltip("The string we want to append to a file.")] + public FsmString str; + [Tooltip("Whether to encode this string using Base-64 encoding. This will override any default encoding settings.")] + public FsmBool useBase64Encoding; + [Tooltip("If checked, a newline will be added after the data.")] + public FsmBool appendNewline; + + public override void OnReset() + { + str = ""; + useBase64Encoding = false; + appendNewline = false; + } + + public override void Enter() + { + if (useBase64Encoding.Value) + ES3.AppendRaw(System.Convert.FromBase64String(str.Value) + (appendNewline.Value ? "\n" : ""), GetSettings()); + else + ES3.AppendRaw(str.Value + (appendNewline.Value ? "\n" : ""), GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Saves a Texture2D as a PNG or a JPG, depending on the file extension of the supplied image path.")] + public class SaveImage : SettingsAction + { + [Tooltip("The relative or absolute path of the PNG or JPG file we want to store our image to.")] + public FsmString imagePath; + [Tooltip("The Texture2D we want to save as an image.")] + [ObjectType(typeof(Texture2D))] + public FsmTexture texture2D; + [Tooltip("The quality of the image when saving JPGs, from 1 to 100. Default is 75.")] + public FsmInt quality; + + public override void OnReset() + { + imagePath = "image.png"; + texture2D = null; + quality = 75; + } + + public override void Enter() + { + ES3.SaveImage((Texture2D)texture2D.Value, quality.Value, imagePath.Value, GetSettings()); + } + } + + #endregion + + #region Load Actions + + [ActionCategory("Easy Save 3")] + [Tooltip("Loads a value from a file with the given key.")] + public class Load : SettingsAction + { + [Tooltip("The unique key which identifies the data we're loading.")] + public FsmString key; + [Tooltip("The variable we want to use to store our loaded data.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar value; + [Tooltip("Optional: A value to return if the key does not exist.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar defaultValue; + + public override void OnReset() + { + key = "key"; + value = null; + defaultValue = null; + } + + public override void Enter() + { + defaultValue.UpdateValue(); + bool useDefaultVal = defaultValue.GetValue() != null && !defaultValue.IsNone; + + + if (value.Type == VariableType.Array) + { + if (useDefaultVal) + value.SetValue(ES3.Load(key.Value, new PMDataWrapper(defaultValue.arrayValue.Values), GetSettings()).array); + else + value.SetValue(ES3.Load(key.Value, GetSettings()).array); + } + else + { + if (useDefaultVal) + value.SetValue(ES3.Load(key.Value, defaultValue.GetValue(), GetSettings())); + else + value.SetValue(ES3.Load(key.Value, GetSettings())); + } + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Loads multiple values from a file with the given keys.")] + public class LoadMultiple : SettingsAction + { + [RequiredField] + [CompoundArray("Count", "Key", "Value")] + public FsmString[] keys; + [Tooltip("The variables we want to load into.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar[] variables; + + public override void OnReset() + { + keys = null; + variables = null; + } + + public override void Enter() + { + for (int i = 0; i < variables.Length; i++) + { + var key = keys[i]; + var value = variables[i]; + + if (value.Type == VariableType.Array) + value.SetValue(ES3.Load(key.Value, GetSettings()).array); + else + value.SetValue(ES3.Load(key.Value, GetSettings())); + } + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Loads a value from a file with the given key into an existing object, rather than creating a new instance.")] + public class LoadInto : SettingsAction + { + [Tooltip("The unique key which identifies the data we're loading.")] + public FsmString key; + [Tooltip("The object we want to load our data into.")] + [RequiredField] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar value; + + public override void OnReset() + { + key = "key"; + value = null; + } + + public override void Enter() + { + value.UpdateValue(); + if (value.IsNone || value.GetValue() == null) + HandleError("The 'Load Into' action requires an object to load the data into, but none was specified in the 'Value' field."); + else + { + ES3.LoadInto(key.Value, value.GetValue(), GetSettings()); + + if (value.Type == VariableType.Array) + HandleError("It's not possible to use LoadInto with arrays in PlayMaker as they are not strictly typed. Consider using Load instead."); + else + value.SetValue(ES3.Load(key.Value, GetSettings())); + } + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Loads all FsmVariables in this FSM to a file with the given key.")] + public class LoadAll : SettingsAction + { + [Tooltip("The key we used to save the data we're loading.")] + public FsmString key; + + [Tooltip("Load the local variables accessible in this FSM?")] + public FsmBool loadFsmVariables = true; + [Tooltip("Load the global variables accessible in all FSMs?")] + public FsmBool loadGlobalVariables = true; + + public override void OnReset() + { + key = "key"; + } + + public override void Enter() + { + ES3.Load(key.Value, GetSettings()).ApplyVariables(Fsm, loadFsmVariables.Value, loadGlobalVariables.Value); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Loads an entire file as a string.")] + public class LoadRawString : SettingsAction + { + [Tooltip("The variable we want to store our loaded string in.")] + public FsmString str; + [Tooltip("Whether or not the data we're loading is Base-64 encoded. Usually this should be left unchecked.")] + public FsmBool useBase64Encoding; + + public override void OnReset() + { + str = null; + useBase64Encoding = false; + } + + public override void Enter() + { + if (useBase64Encoding.Value) + str.Value = System.Convert.ToBase64String(ES3.LoadRawBytes(GetSettings())); + else + str.Value = ES3.LoadRawString(GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Loads a JPG or PNG image file as a Texture2D.")] + public class LoadImage : SettingsAction + { + [Tooltip("The relative or absolute path of the JPG or PNG image file we want to load.")] + public FsmString imagePath; + [Tooltip("The variable we want to use to store our loaded texture.")] + public FsmTexture texture2D; + + public override void OnReset() + { + imagePath = "image.png"; + texture2D = null; + } + + public override void Enter() + { + texture2D.Value = ES3.LoadImage(imagePath.Value, GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Loads an audio file as an AudioClip.")] + public class LoadAudio : SettingsAction + { + [Tooltip("The relative or absolute path of the audio file we want to load.")] + public FsmString audioFilePath; + [ObjectType(typeof(AudioClip))] + [Tooltip("The variable we want to use to store our loaded AudioClip.")] + public FsmObject audioClip; + +#if UNITY_2018_3_OR_NEWER + [Tooltip("The type of AudioClip we're loading.")] + [ObjectType(typeof(AudioType))] + public FsmEnum audioType; +#endif + + public override void OnReset() + { + audioFilePath = "audio.wav"; + audioClip = null; +#if UNITY_2018_3_OR_NEWER + audioType = AudioType.MPEG; +#endif + } + + public override void Enter() + { + audioClip.Value = ES3.LoadAudio(audioFilePath.Value, +#if UNITY_2018_3_OR_NEWER + (AudioType)audioType.Value, +#endif + GetSettings()); + } + } + + + #endregion + + #region Exists Actions + + [ActionCategory("Easy Save 3")] + [Tooltip("Checks whether a key exists in a file.")] + public class KeyExists : SettingsAction + { + [Tooltip("The key we want to check the existence of.")] + public FsmString key; + [Tooltip("Whether the key exists. This is set after the action runs.")] + public FsmBool exists; + + [Tooltip("This event is triggered if the key exists.")] + public FsmEvent existsEvent; + [Tooltip("This event is triggered if the key does not exist.")] + public FsmEvent doesNotExistEvent; + + public override void OnReset() + { + key = "key"; + exists = false; + existsEvent = null; + doesNotExistEvent = null; + } + + public override void Enter() + { + exists.Value = ES3.KeyExists(key.Value, GetSettings()); + + Fsm.Event(exists.Value ? existsEvent : doesNotExistEvent); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Checks whether a file exists in a directory.")] + public class FileExists : SettingsAction + { + [Tooltip("The file we want to check the existence of")] + public FsmString filePath; + [Tooltip("Whether the file exists. This is set after the action runs.")] + public FsmBool exists; + + [Tooltip("This event is triggered if the file exists.")] + public FsmEvent existsEvent; + [Tooltip("This event is triggered if the file does not exist.")] + public FsmEvent doesNotExistEvent; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + exists = false; + existsEvent = null; + doesNotExistEvent = null; + } + + public override void Enter() + { + exists.Value = ES3.FileExists(filePath.Value, GetSettings()); + + Fsm.Event(exists.Value ? existsEvent : doesNotExistEvent); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Checks whether a directory exists in another directory")] + public class DirectoryExists : SettingsAction + { + [Tooltip("The directory we want to check the existence of.")] + public FsmString directoryPath; + [Tooltip("Whether the directory exists. This is set after the action runs.")] + public FsmBool exists; + + [Tooltip("This event is triggered if the directory exists.")] + public FsmEvent existsEvent; + [Tooltip("This event is triggered if the directory does not exist.")] + public FsmEvent doesNotExistEvent; + + public override void OnReset() + { + directoryPath = ""; + exists = false; + existsEvent = null; + doesNotExistEvent = null; + } + + public override void Enter() + { + exists.Value = ES3.DirectoryExists(directoryPath.Value, GetSettings()); + + Fsm.Event(exists.Value ? existsEvent : doesNotExistEvent); + } + } + + #endregion + + #region Delete Actions + + [ActionCategory("Easy Save 3")] + [Tooltip("Deletes a key from a file.")] + public class DeleteKey : SettingsAction + { + [Tooltip("The key we want to delete.")] + public FsmString key; + + public override void OnReset() + { + key = "key"; + } + + public override void Enter() + { + ES3.DeleteKey(key.Value, GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Deletes a file.")] + public class DeleteFile : SettingsAction + { + [Tooltip("The relative or absolute path of the file we want to delete.")] + public FsmString filePath; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + } + + public override void Enter() + { + ES3.DeleteFile(filePath.Value, GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Deletes a directory and it's contents.")] + public class DeleteDirectory : SettingsAction + { + [Tooltip("The relative or absolute path of the directory we want to delete.")] + public FsmString directoryPath; + + public override void OnReset() + { + directoryPath = ""; + } + + public override void Enter() + { + ES3.DeleteDirectory(directoryPath.Value, GetSettings()); + } + } + + #endregion + + #region Backup Actions + + [ActionCategory("Easy Save 3")] + [Tooltip("Creates a backup of a file which can be restored using the Restore Backup action.")] + public class CreateBackup : SettingsAction + { + [Tooltip("The relative or absolute path of the file we want to backup.")] + public FsmString filePath; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + } + + public override void Enter() + { + ES3.CreateBackup(filePath.Value, GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Restores a backup of a file created using the Create Backup action.")] + public class RestoreBackup : SettingsAction + { + [Tooltip("The relative or absolute path of the file we want to restore the backup of.")] + public FsmString filePath; + [Tooltip("True if a backup was restored, or False if no backup could be found.")] + public FsmBool backupWasRestored; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + backupWasRestored = false; + } + + public override void Enter() + { + backupWasRestored.Value = ES3.RestoreBackup(filePath.Value, GetSettings()); + } + } + + #endregion + + #region Key, File and Directory Methods + + [ActionCategory("Easy Save 3")] + [Tooltip("Renames a file.")] + public class RenameFile : SettingsAction + { + [Tooltip("The relative or absolute path of the file we want to rename from.")] + public FsmString oldFilePath; + [Tooltip("The relative or absolute path of the file we want to rename to.")] + public FsmString newFilePath; + + public override void OnReset() + { + oldFilePath = "SaveFile.es3"; + newFilePath = ""; + } + + public override void Enter() + { + ES3.RenameFile(oldFilePath.Value, newFilePath.Value, GetSettings(), GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Copies a file.")] + public class CopyFile : SettingsAction + { + [Tooltip("The relative or absolute path of the file we want to copy.")] + public FsmString oldFilePath; + [Tooltip("The relative or absolute path of the file we want to create.")] + public FsmString newFilePath; + + public override void OnReset() + { + oldFilePath = "SaveFile.es3"; + newFilePath = ""; + } + + public override void Enter() + { + ES3.CopyFile(oldFilePath.Value, newFilePath.Value, GetSettings(), GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Copies a directory.")] + public class CopyDirectory : SettingsAction + { + [Tooltip("The relative or absolute path of the directory we want to copy.")] + public FsmString oldDirectoryPath; + [Tooltip("The relative or absolute path of the directory we want to create.")] + public FsmString newDirectoryPath; + + public override void OnReset() + { + oldDirectoryPath = ""; + newDirectoryPath = ""; + } + + public override void Enter() + { + ES3.CopyDirectory(oldDirectoryPath.Value, newDirectoryPath.Value, GetSettings(), GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Gets an array of key names from a file.")] + public class GetKeys : SettingsAction + { + [Tooltip("The relative or absolute path of the file we want to get the keys from.")] + public FsmString filePath; + [Tooltip("The string array variable we want to load our key names into.")] + [ArrayEditor(VariableType.String)] + public FsmArray keys; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + keys = null; + } + + public override void Enter() + { + keys.Values = ES3.GetKeys(filePath.Value, GetSettings()); + keys.SaveChanges(); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Gets how many keys are in a file.")] + public class GetKeyCount : SettingsAction + { + [Tooltip("The relative or absolute path of the file we want to count the keys of.")] + public FsmString filePath; + [Tooltip("The int variable we want to load our count into.")] + public FsmInt keyCount; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + keyCount = null; + } + + public override void Enter() + { + keyCount.Value = ES3.GetKeys(filePath.Value, GetSettings()).Length; + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Gets the names of the files in a given directory.")] + public class GetFiles : SettingsAction + { + [Tooltip("The relative or absolute path of the directory we want to get the file names from.")] + public FsmString directoryPath; + [Tooltip("The string array variable we want to load our file names into.")] + [ArrayEditor(VariableType.String)] + public FsmArray files; + + public override void OnReset() + { + directoryPath = ""; + files = null; + } + + public override void Enter() + { + files.Values = ES3.GetFiles(directoryPath.Value, GetSettings()); + files.SaveChanges(); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Gets the names of any directories in a given directory.")] + public class GetDirectories : SettingsAction + { + [Tooltip("The relative or absolute path of the directory we want to get the directory names from.")] + public FsmString directoryPath; + [Tooltip("The string array variable we want to load our directory names into.")] + [ArrayEditor(VariableType.String)] + public FsmArray directories; + + public override void OnReset() + { + directoryPath = ""; + directories = null; + } + + public override void Enter() + { + directories.Values = ES3.GetDirectories(directoryPath.Value, GetSettings()); + directories.SaveChanges(); + } + } + + #endregion + + #region ES3Spreadsheet Actions + + [ActionCategory("Easy Save 3")] + [Tooltip("Creates a new empty ES3Spreadsheet.")] + public class ES3SpreadsheetCreate : ES3SpreadsheetAction + { + public override void OnReset() + { + } + + public override void Enter() + { + var spreadsheet = ScriptableObject.CreateInstance(); + spreadsheet.spreadsheet = new ES3Spreadsheet(); + fsmES3Spreadsheet.Value = spreadsheet; + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Sets a given cell of the ES3Spreadsheet to the value provided.")] + public class ES3SpreadsheetSetCell : ES3SpreadsheetAction + { + [Tooltip("The column of the cell we want to set the value of.")] + public FsmInt col; + [Tooltip("The row of the cell we want to set the value of.")] + public FsmInt row; + + [Tooltip("The value we want to save.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar value; + + public override void OnReset() + { + value = null; + } + + public override void Enter() + { + value.UpdateValue(); + es3Spreadsheet.SetCell(col.Value, row.Value, value.GetValue()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Gets a given cell of the ES3Spreadsheet and loads it into the value field.")] + public class ES3SpreadsheetGetCell : ES3SpreadsheetAction + { + [Tooltip("The column of the cell we want to set the value of.")] + public FsmInt col; + [Tooltip("The row of the cell we want to set the value of.")] + public FsmInt row; + + [Tooltip("The value we want to save.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar value; + + public override void OnReset() + { + value = null; + } + + public override void Enter() + { + value.SetValue(es3Spreadsheet.GetCell(value.RealType, col.Value, row.Value)); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Saves the ES3Spreadsheet to file.")] + public class ES3SpreadsheetSave : ES3SpreadsheetSettingsAction + { + [Tooltip("The filename or path we want to use to save the spreadsheet.")] + public FsmString filePath; + [Tooltip("Whether we want to append this spreadsheet to an existing spreadsheet if one already exists.")] + public FsmBool append; + + public override void OnReset() + { + filePath = "ES3.csv"; + append = false; + } + + public override void Enter() + { + es3Spreadsheet.Save(filePath.Value, GetSettings(), append.Value); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Loads a a spreadsheet from a file into this ES3Spreadsheet.")] + public class ES3SpreadsheetLoad : ES3SpreadsheetSettingsAction + { + [Tooltip("The filename or path we want to use to save the spreadsheet.")] + public FsmString filePath; + + public override void OnReset() + { + filePath = "ES3.csv"; + + } + + public override void Enter() + { + es3Spreadsheet.Load(filePath.Value, GetSettings()); + } + } + #endregion + + #region ES3File Actions + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Creates a new ES3File, and optionally loads a file from storage into it.")] + public class ES3FileCreate : ES3FileSettingsAction + { + [Tooltip("The relative or absolute path of the file this ES3File represents in storage.")] + public FsmString filePath; + [Tooltip("Whether we should sync this ES3File with the one in storage immediately after creating it.")] + public FsmBool syncWithFile; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + syncWithFile = true; + } + + public override void Enter() + { + var file = ScriptableObject.CreateInstance(); + file.file = new ES3File(filePath.Value, GetSettings(), syncWithFile.Value); + fsmES3File.Value = file; + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Synchronises this ES3File with a file in storage.")] + public class ES3FileSync : ES3FileSettingsAction + { + [Tooltip("The relative or absolute path of the file we want to synchronise with in storage.")] + public FsmString filePath; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + } + + public override void Enter() + { + if (overrideDefaultSettings.Value) + es3File.Sync(GetSettings()); + else + es3File.Sync(); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Saves the value to the ES3File with the given key.")] + public class ES3FileSave : ES3FileAction + { + [Tooltip("The unique key we want to use to identity the data we are saving.")] + public FsmString key; + [Tooltip("The value we want to save.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar value; + + public override void OnReset() + { + key = "key"; + value = null; + } + + public override void Enter() + { + value.UpdateValue(); + es3File.Save(key.Value, value.GetValue()); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Loads a value with the given key from the ES3File")] + public class ES3FileLoad : ES3FileAction + { + [Tooltip("The unique key which identifies the data we're loading.")] + public FsmString key; + [Tooltip("The variable we want to use to store our loaded data.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar value; + [Tooltip("Optional: A value to return if the key does not exist.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar defaultValue; + + public override void OnReset() + { + key = "key"; + value = null; + defaultValue = null; + } + + public override void Enter() + { + defaultValue.UpdateValue(); + if (defaultValue.GetValue() != null && !defaultValue.IsNone) + value.SetValue(es3File.Load(key.Value, defaultValue.GetValue())); + else + value.SetValue(es3File.Load(key.Value)); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Loads a value with the given key from the ES3File into an existing object")] + public class ES3FileLoadInto : ES3FileAction + { + [Tooltip("The unique key which identifies the data we're loading.")] + public FsmString key; + [Tooltip("The variable we want to load our data into.")] + [UIHint(UIHint.Variable)] + [HideTypeFilter] + public FsmVar value; + + public override void OnReset() + { + key = "key"; + value = null; + } + + public override void Enter() + { + value.UpdateValue(); + es3File.LoadInto(key.Value, value.GetValue()); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Loads the entire ES3 File as a string")] + public class ES3FileLoadRawString : ES3FileAction + { + [Tooltip("The FsmArray variable we want to use to store our string representing the file.")] + public FsmString str; + [Tooltip("Whether or not the data we're loading is Base-64 encoded. Usually this should be left unchecked.")] + public FsmBool useBase64Encoding; + + public override void OnReset() + { + str = null; + useBase64Encoding = false; + } + + public override void Enter() + { + if (useBase64Encoding.Value) + str.Value = System.Convert.ToBase64String(es3File.LoadRawBytes()); + else + str.Value = es3File.LoadRawString(); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Deletes a key from an ES3 File.")] + public class ES3FileDeleteKey : ES3FileAction + { + [Tooltip("The key we want to delete.")] + public FsmString key; + + public override void OnReset() + { + key = "key"; + } + + public override void Enter() + { + es3File.DeleteKey(key.Value); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Checks whether a key exists in an ES3File.")] + public class ES3FileKeyExists : ES3FileAction + { + [Tooltip("The key we want to check the existence of.")] + public FsmString key; + [Tooltip("Whether the key exists. This is set after the action runs.")] + public FsmBool exists; + + [Tooltip("This event is triggered if the key exists.")] + public FsmEvent existsEvent; + [Tooltip("This event is triggered if the key does not exist.")] + public FsmEvent doesNotExistEvent; + + public override void OnReset() + { + key = "key"; + exists = false; + existsEvent = null; + doesNotExistEvent = null; + } + + public override void Enter() + { + exists.Value = es3File.KeyExists(key.Value); + + if (exists.Value && existsEvent != null) + Fsm.Event(existsEvent); + else if (doesNotExistEvent != null) + Fsm.Event(doesNotExistEvent); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Gets an array of key names from an ES3File.")] + public class ES3FileGetKeys : ES3FileAction + { + [Tooltip("The string array variable we want to load our key names into.")] + [ArrayEditor(VariableType.String)] + public FsmArray keys; + + public override void OnReset() + { + keys = null; + } + + public override void Enter() + { + keys.Values = es3File.GetKeys(); + keys.SaveChanges(); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Clears all keys from an ES3File.")] + public class ES3FileClear : ES3FileAction + { + public override void OnReset() { } + + public override void Enter() + { + es3File.Clear(); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Gets an array of key names from a file.")] + public class ES3FileSize : ES3FileAction + { + [Tooltip("The variable we want to put the file size into.")] + public FsmInt size; + + public override void OnReset() + { + size = 0; + } + + public override void Enter() + { + size.Value = es3File.Size(); + } + } + + #endregion + + #region ES3Cloud Actions + +#if !DISABLE_WEB + public abstract class ES3CloudAction : SettingsAction + { + [Tooltip("The URL to the ES3Cloud.php file on your server.")] + [RequiredField] + public FsmString url; + [Tooltip("The API key generated when installing ES3 Cloud on your server.")] + [RequiredField] + public FsmString apiKey; + + [Tooltip("The ES3File variable we're using.")] + [ObjectType(typeof(FsmES3File))] + [Title("ES3 File")] + [RequiredField] + public FsmObject fsmES3File; + + public ES3File es3File { get { return ((FsmES3File)fsmES3File.Value).file; } } + + [Tooltip("An error code if an error occurred.")] + public FsmInt errorCode; + + protected ES3Cloud cloud = null; + + public override void OnReset() + { + url = "http://www.myserver.com/ES3Cloud.php"; + errorCode = 0; + cloud = null; + fsmES3File = null; + } + + public override void OnEnter() + { + try + { + CreateES3Cloud(); + Enter(); + } + catch (System.Exception e) + { + HandleError(e.ToString()); + } + } + + public override void OnUpdate() + { + base.OnUpdate(); + if (cloud.isDone) + { + if (cloud.isError) + { + errorCode.Value = (int)cloud.errorCode; + errorMessage.Value = cloud.error; + Log("Error occurred when trying to perform operation with ES3Cloud: [Error " + cloud.errorCode + "] " + cloud.error); + Fsm.Event(errorEvent); + } + else + Finish(); + } + } + + protected void CreateES3Cloud() + { + cloud = new ES3Cloud(url.Value, apiKey.Value); + } + } + + public abstract class ES3CloudUserAction : ES3CloudAction + { + [ActionSection("User (optional)")] + public FsmString user; + public FsmString password; + + public override void OnReset() + { + base.OnReset(); + user = ""; + password = ""; + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Synchronises a file in storage with the server.")] + public class ES3CloudSync : ES3CloudUserAction + { + public override void Enter() + { + var settings = GetSettings(); + StartCoroutine(cloud.Sync(path.Value, settings)); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Uploads a file in storage to the server, overwriting any existing files.")] + public class ES3CloudUploadFile : ES3CloudUserAction + { + public override void Enter() + { + var settings = GetSettings(); + StartCoroutine(cloud.UploadFile(path.Value, user.Value, password.Value, settings)); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Uploads a file in storage to the server, overwriting any existing files.")] + public class ES3CloudUploadES3File : ES3CloudUserAction + { + public override void Enter() + { + var settings = GetSettings(); + StartCoroutine(cloud.UploadFile(es3File, user.Value, password.Value)); + } + } + + [ActionCategory("Deprecated Easy Save 3 actions")] + [Tooltip("Downloads a file from the server, overwriting any existing files, or returning error code 3 if no file exists on the server.")] + public class ES3CloudDownloadES3File : ES3CloudUserAction + { + public override void Enter() + { + var settings = GetSettings(); + StartCoroutine(cloud.DownloadFile(es3File, user.Value, password.Value)); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Downloads a file from the server into an file, or returning error code 3 if no file exists on the server.")] + public class ES3CloudDownloadFile : ES3CloudUserAction + { + public override void Enter() + { + var settings = GetSettings(); + StartCoroutine(cloud.DownloadFile(path.Value, user.Value, password.Value, settings)); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Downloads a file from the server, overwriting any existing files, or returning error code 3 if no file exists on the server.")] + public class ES3CloudDeleteFile : ES3CloudUserAction + { + public override void Enter() + { + var settings = GetSettings(); + StartCoroutine(cloud.DeleteFile(path.Value, user.Value, password.Value, settings)); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Renames a file on the server, overwriting any existing files, or returning error code 3 if no file exists on the server.")] + public class ES3CloudRenameFile : ES3CloudUserAction + { + [Tooltip("The name we want to rename the file to.")] + public FsmString newFilename; + + public override void Enter() + { + var settings = GetSettings(); + StartCoroutine(cloud.RenameFile(path.Value, newFilename.Value, user.Value, password.Value, settings)); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Downloads the names of all of the files on the server for the given user.")] + public class ES3CloudDownloadFilenames : ES3CloudUserAction + { + [Tooltip("The string array variable we want to load our file names into.")] + [ArrayEditor(VariableType.String)] + public FsmArray filenames; + + [Tooltip("An optional search pattern containing '%' or '_' wildcards where '%' represents zero, one, or multiple characters, and '_' represents a single character. See https://www.w3schools.com/sql/sql_like.asp for more info.")] + public FsmString searchPattern; + + public override void OnReset() + { + filenames = null; + searchPattern = ""; + } + + public override void Enter() + { + StartCoroutine(cloud.SearchFilenames(string.IsNullOrEmpty(searchPattern.Value) ? "%" : searchPattern.Value, user.Value, password.Value)); + } + + public override void OnUpdate() + { + if (cloud != null && cloud.isDone) + { + var downloadedFilenames = cloud.filenames; + filenames.Resize(cloud.filenames.Length); + for (int i = 0; i < downloadedFilenames.Length; i++) + filenames.Set(i, downloadedFilenames[i]); + filenames.SaveChanges(); + } + base.OnUpdate(); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Downloads the names of all of the files on the server for the given user.")] + public class ES3CloudSearchFilenames : ES3CloudUserAction + { + [Tooltip("The string array variable we want to load our file names into.")] + [ArrayEditor(VariableType.String)] + public FsmArray filenames; + + [Tooltip("An optional search pattern containing '%' or '_' wildcards where '%' represents zero, one, or multiple characters, and '_' represents a single character. See https://www.w3schools.com/sql/sql_like.asp for more info.")] + public FsmString searchPattern; + + public override void OnReset() + { + filenames = null; + searchPattern = ""; + } + + public override void Enter() + { + StartCoroutine(cloud.SearchFilenames(string.IsNullOrEmpty(searchPattern.Value) ? "%" : searchPattern.Value, user.Value, password.Value)); + } + + public override void OnUpdate() + { + if (cloud != null && cloud.isDone) + { + var downloadedFilenames = cloud.filenames; + filenames.Resize(cloud.filenames.Length); + for (int i = 0; i < downloadedFilenames.Length; i++) + filenames.Set(i, downloadedFilenames[i]); + filenames.SaveChanges(); + } + base.OnUpdate(); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Determines when a file was last updated.")] + public class ES3CloudDownloadTimestamp : ES3CloudUserAction + { + [Tooltip("The Date and time the file was last updated, as a string formatted as yyyy-MM-ddTHH:mm:ss.")] + public FsmString timestamp; + + public override void OnReset() + { + timestamp = ""; + } + + public override void Enter() + { + StartCoroutine(cloud.DownloadTimestamp(path.Value, user.Value, password.Value)); + } + + public override void OnUpdate() + { + if (cloud != null && cloud.isDone) + timestamp.Value = cloud.timestamp.ToString("s"); + base.OnUpdate(); + } + } + +#endif + #endregion + + #region ES3AutoSave actions + + [ActionCategory("Easy Save 3")] + [Tooltip("Triggers Auto Save's Save method.")] + public class ES3AutoSaveSave : FsmStateAction + { + public override void OnEnter() + { + GameObject.Find("Easy Save 3 Manager").GetComponent().Save(); + Finish(); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Triggers Auto Save's Load method.")] + public class ES3AutoSaveLoad : FsmStateAction + { + public override void OnEnter() + { + GameObject.Find("Easy Save 3 Manager").GetComponent().Load(); + Finish(); + } + } + + #endregion + + #region ES3Cache actions + + [ActionCategory("Easy Save 3")] + [Tooltip("Caches a locally-stored file into memory.")] + public class CacheFile : SettingsAction + { + [Tooltip("The filename or file path of the file we want to cache.")] + public FsmString filePath; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + } + + public override void Enter() + { + ES3.CacheFile(filePath.Value, GetSettings()); + } + } + + [ActionCategory("Easy Save 3")] + [Tooltip("Stores a file in the cache to a local file.")] + public class StoreCachedFile : SettingsAction + { + [Tooltip("The filename or file path of the file we want to store.")] + public FsmString filePath; + + public override void OnReset() + { + filePath = "SaveFile.es3"; + } + + public override void Enter() + { + ES3.StoreCachedFile(filePath.Value, GetSettings()); + } + } + + #endregion + + #region Misc actions + + [ActionCategory("Easy Save 3")] + [Tooltip("Gets the Streaming Assets path (see https://docs.unity3d.com/Manual/StreamingAssets.html), and optionally appends onto it. It is strongly recommended to use Easy Save's default of Persistent Data Path instead as this works on all platforms.")] + public class GetStreamingAssetsPath : FsmStateAction + { + [Tooltip("The variable we want to output the Streaming Assets path to.")] + public FsmString output; + [Tooltip("[Optional] A string to append to the path, for example a filename. A forward slash is automatically added for you.")] + public FsmString append; + + public override void Reset() + { + output = null; + append = null; + } + + public override void OnEnter() + { + if (!string.IsNullOrEmpty(append.Value)) + output.Value = Application.streamingAssetsPath + "/" + append.Value; + else + output.Value = Application.streamingAssetsPath; + Finish(); + } + } + + #endregion + + public class PMDataWrapper + { + public Dictionary objs = null; + public Dictionary arrays = null; + + public object obj = null; + public object[] array = null; + + public PMDataWrapper(Fsm fsm, bool fsmVariables, bool globalVariables) + { + objs = new Dictionary(); + arrays = new Dictionary(); + + if (fsm == null) + return; + + // Get FSMVariables objects required based on whether the user wants to save local variables, global variables or both. + var variableLists = new List(); + if (fsmVariables) + variableLists.Add(fsm.Variables); + if (globalVariables) + variableLists.Add(FsmVariables.GlobalVariables); + + foreach (var variableList in variableLists) + { + foreach (var fsmVariable in variableList.GetAllNamedVariables()) + { + if (string.IsNullOrEmpty(fsmVariable.Name)) + continue; + + if (fsmVariable.GetType() == typeof(FsmArray)) + arrays.Add(fsmVariable.Name, ((FsmArray)fsmVariable).Values); + else + objs.Add(fsmVariable.Name, fsmVariable.RawValue); + } + } + } + + public PMDataWrapper(Dictionary objs, Dictionary arrays) + { + this.objs = objs; + this.arrays = arrays; + } + + public PMDataWrapper(object obj) + { + this.obj = obj; + } + + public PMDataWrapper(object[] array) + { + this.array = array; + } + + public PMDataWrapper() { } + + public void ApplyVariables(Fsm fsm, bool fsmVariables, bool globalVariables) + { + // Get FSMVariables objects required based on whether the user wants to save local variables, global variables or both. + var variableLists = new List(); + + if (fsmVariables) + variableLists.Add(fsm.Variables); + if (globalVariables) + variableLists.Add(FsmVariables.GlobalVariables); + + foreach (var variableList in variableLists) + { + foreach (var fsmVariable in variableList.GetAllNamedVariables()) + { + if (fsmVariable.GetType() == typeof(FsmArray)) + { + if (arrays.ContainsKey(fsmVariable.Name)) + ((FsmArray)fsmVariable).Values = arrays[fsmVariable.Name]; + } + else + { + if (objs.ContainsKey(fsmVariable.Name)) + fsmVariable.RawValue = objs[fsmVariable.Name]; + } + } + } + } + } +} + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3Properties("objs", "arrays", "obj", "array")] + public class ES3Type_PMDataWrapper : ES3ObjectType + { + public static ES3Type Instance = null; + + public ES3Type_PMDataWrapper() : base(typeof(ES3PlayMaker.PMDataWrapper)) { Instance = this; priority = 1; } + + + protected override void WriteObject(object obj, ES3Writer writer) + { + var instance = (ES3PlayMaker.PMDataWrapper)obj; + + writer.WriteProperty("objs", instance.objs); + writer.WriteProperty("arrays", instance.arrays); + writer.WriteProperty("obj", instance.obj); + writer.WriteProperty("array", instance.array); + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var instance = (ES3PlayMaker.PMDataWrapper)obj; + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + + case "objs": + instance.objs = reader.Read>(); + break; + case "arrays": + instance.arrays = reader.Read>(); + break; + case "obj": + instance.obj = reader.Read(); + break; + case "array": + instance.array = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadObject(ES3Reader reader) + { + var instance = new ES3PlayMaker.PMDataWrapper(); + ReadObject(reader, instance); + return instance; + } + } + + [UnityEngine.Scripting.Preserve] + [ES3Properties("ActiveStateName")] + public class ES3Type_Fsm : ES3ObjectType + { + public static ES3Type Instance = null; + + public ES3Type_Fsm() : base(typeof(Fsm)) { Instance = this; priority = 1; } + + + protected override void WriteObject(object obj, ES3Writer writer) + { + var instance = (Fsm)obj; + writer.WriteProperty("ActiveStateName", instance.ActiveStateName, ES3Type_string.Instance); + writer.WriteProperty("Variables", new ES3PlayMaker.PMDataWrapper(instance, true, false), ES3Type_PMDataWrapper.Instance); + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var instance = (Fsm)obj; + if(!instance.Initialized) + { + // Toggle FSM Component twice to trigger initialisation. + instance.FsmComponent.enabled = !instance.FsmComponent.enabled; + instance.FsmComponent.enabled = !instance.FsmComponent.enabled; + } + + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + case "ActiveStateName": + instance.SetState(reader.Read(ES3Type_string.Instance)); + break; + case "Variables": + reader.Read(ES3Type_PMDataWrapper.Instance).ApplyVariables(instance, true, false); + break; + } + } + } + + protected override object ReadObject(ES3Reader reader) + { + var instance = new HutongGames.PlayMaker.Fsm(); + ReadObject(reader, instance); + return instance; + } + } + + /*[UnityEngine.Scripting.Preserve] + [ES3Properties("Fsm")] + public class ES3Type_PlayMakerFSM : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_PlayMakerFSM() : base(typeof(PlayMakerFSM)) + { + Instance = this; + priority = 1; + } + + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (PlayMakerFSM)obj; + + writer.WriteProperty("enabled", instance.enabled); + writer.WriteProperty("Fsm", instance.Fsm, ES3Type_Fsm.Instance); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (PlayMakerFSM)obj; + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "Fsm": + reader.ReadInto(instance.Fsm); + break; + default: + reader.Skip(); + break; + } + } + } + }*/ +} + + +#endif diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/PlayMaker/ES3PlayMaker.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/PlayMaker/ES3PlayMaker.cs.meta new file mode 100644 index 0000000..4f8898a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/PlayMaker/ES3PlayMaker.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5989e48214df74e2b9cced724ec2e5c8 +timeCreated: 1497259720 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources.meta new file mode 100644 index 0000000..8703ed0 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 21ce5c6c627d1104abe370a16034b267 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources/ES3.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources/ES3.meta new file mode 100644 index 0000000..06efaff --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources/ES3.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 37947a5e91cbdb442b2655a7e75325b8 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources/ES3/ES3Defaults.asset b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources/ES3/ES3Defaults.asset new file mode 100644 index 0000000..22ba73a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources/ES3/ES3Defaults.asset @@ -0,0 +1,54 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 7b340139c9e4d054f904d8b452798652, type: 3} + m_Name: ES3Defaults + m_EditorClassIdentifier: + settings: + _location: 0 + path: SaveFile.es3 + encryptionType: 0 + compressionType: 0 + encryptionPassword: password + directory: 0 + format: 0 + prettyPrint: 1 + bufferSize: 2048 + saveChildren: 1 + postprocessRawCachedData: 0 + typeChecking: 1 + safeReflection: 1 + memberReferenceMode: 0 + referenceMode: 2 + serializationDepthLimit: 64 + assemblyNames: + - AppsFlyer + - Assembly-CSharp + - DOTween.Modules + - DOTweenPro.Scripts + - endel.nativewebsocket + - IngameDebugConsole.Runtime + - MaxSdk.Scripts + - OPS.Obfuscator + - spine-unity + showAdvancedSettings: 0 + addMgrToSceneAutomatically: 0 + autoUpdateReferences: 1 + addAllPrefabsToManager: 1 + collectDependenciesDepth: 4 + collectDependenciesTimeout: 10 + updateReferencesWhenSceneChanges: 1 + updateReferencesWhenSceneIsSaved: 1 + updateReferencesWhenSceneIsOpened: 1 + referenceFolders: [] + logDebugInfo: 0 + logWarnings: 1 + logErrors: 1 diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources/ES3/ES3Defaults.asset.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources/ES3/ES3Defaults.asset.meta new file mode 100644 index 0000000..ca2338c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Resources/ES3/ES3Defaults.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ca4d43647cdf3fb4aaa948a958e8c0e0 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts.meta new file mode 100644 index 0000000..eb96a10 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4416904d454a58c429d3b39b1f2dc050 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Attributes.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Attributes.meta new file mode 100644 index 0000000..30efc10 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Attributes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1adc48a002c61c7408132284b5926511 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Attributes/ES3Attributes.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Attributes/ES3Attributes.cs new file mode 100644 index 0000000..242a790 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Attributes/ES3Attributes.cs @@ -0,0 +1,7 @@ +using System; + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property)] +public class ES3Serializable : Attribute{} + +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property)] +public class ES3NonSerializable : Attribute { } diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Attributes/ES3Attributes.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Attributes/ES3Attributes.cs.meta new file mode 100644 index 0000000..e18e2d3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Attributes/ES3Attributes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e29c69181d1dff642b20c218819fe2e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save.meta new file mode 100644 index 0000000..7ab74c7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8df6646c090cd1043985f6648f2a39aa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSave.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSave.cs new file mode 100644 index 0000000..806914b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSave.cs @@ -0,0 +1,55 @@ +using UnityEngine; +using System.Collections.Generic; + +public class ES3AutoSave : MonoBehaviour, ISerializationCallbackReceiver +{ + public bool saveLayer = true; + public bool saveTag = true; + public bool saveName = true; + public bool saveHideFlags = true; + public bool saveActive = true; + public bool saveChildren = false; + + private bool isQuitting = false; + + //[HideInInspector] + public List componentsToSave = new List(); + + public void Reset() + { + // Initialise saveLayer (etc) to false for all new Components. + saveLayer = false; + saveTag = false; + saveName = false; + saveHideFlags = false; + saveActive = false; + saveChildren = false; + } + + public void Awake() + { + if (ES3AutoSaveMgr.Current == null) + ES3Internal.ES3Debug.LogWarning("No GameObjects in this scene will be autosaved because there is no Easy Save 3 Manager. To add a manager to this scene, exit playmode and go to Assets > Easy Save 3 > Add Manager to Scene.", this); + else + ES3AutoSaveMgr.AddAutoSave(this); + } + + public void OnApplicationQuit() + { + isQuitting = true; + } + + public void OnDestroy() + { + // If this is being destroyed, but not because the application is quitting, + // remove the AutoSave from the manager. + if (!isQuitting) + ES3AutoSaveMgr.RemoveAutoSave(this); + } + public void OnBeforeSerialize() { } + public void OnAfterDeserialize() + { + // Remove any null Components + componentsToSave.RemoveAll(c => c == null || c.GetType() == typeof(Component)); + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSave.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSave.cs.meta new file mode 100644 index 0000000..1bc7333 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSave.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9cfcc9ceea0bf419cb3bcaf548c2600d +timeCreated: 1519132292 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSaveMgr.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSaveMgr.cs new file mode 100644 index 0000000..f1f32d4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSaveMgr.cs @@ -0,0 +1,195 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.SceneManagement; +using System.Linq; + +#if UNITY_VISUAL_SCRIPTING +[Unity.VisualScripting.IncludeInSettings(true)] +#elif BOLT_VISUAL_SCRIPTING +[Ludiq.IncludeInSettings(true)] +#endif +public class ES3AutoSaveMgr : MonoBehaviour +{ + public static ES3AutoSaveMgr _current = null; + public static ES3AutoSaveMgr Current + { + get + { + if (_current == null /*|| _current.gameObject.scene != SceneManager.GetActiveScene()*/) + { + var scene = SceneManager.GetActiveScene(); + var roots = scene.GetRootGameObjects(); + + // First, look for Easy Save 3 Manager in the top-level. + foreach (var root in roots) + if (root.name == "Easy Save 3 Manager") + return _current = root.GetComponent(); + + // If the user has moved or renamed the Easy Save 3 Manager, we need to perform a deep search. + foreach (var root in roots) + if ((_current = root.GetComponentInChildren()) != null) + return _current; + } + return _current; + } + } + + public static Dictionary managers = new Dictionary(); + + // Included for backwards compatibility. + public static ES3AutoSaveMgr Instance + { + get { return Current; } + } + + public enum LoadEvent { None, Awake, Start } + public enum SaveEvent { None, OnApplicationQuit, OnApplicationPause } + + public string key = System.Guid.NewGuid().ToString(); + public SaveEvent saveEvent = SaveEvent.OnApplicationQuit; + public LoadEvent loadEvent = LoadEvent.Start; + public ES3SerializableSettings settings = new ES3SerializableSettings("SaveFile.es3", ES3.Location.Cache); + + public HashSet autoSaves = new HashSet(); + + public void Save() + { + if (autoSaves == null || autoSaves.Count == 0) + return; + + ManageSlots(); + + // If we're using caching and we've not already cached this file, cache it. + if (settings.location == ES3.Location.Cache && !ES3.FileExists(settings)) + ES3.CacheFile(settings); + + if (autoSaves == null || autoSaves.Count == 0) + { + ES3.DeleteKey(key, settings); + } + else + { + var gameObjects = new List(); + foreach (var autoSave in autoSaves) + { + // If the ES3AutoSave component is disabled, don't save it. + if (autoSave != null && autoSave.enabled) + gameObjects.Add(autoSave.gameObject); + } + // Save in the same order as their depth in the hierarchy. + ES3.Save(key, gameObjects.OrderBy(x => GetDepth(x.transform)).ToArray(), settings); + } + + if(settings.location == ES3.Location.Cache && ES3.FileExists(settings)) + ES3.StoreCachedFile(settings); + } + + public void Load() + { + ManageSlots(); + + try + { + // If we're using caching and we've not already cached this file, cache it. + if (settings.location == ES3.Location.Cache && !ES3.FileExists(settings)) + ES3.CacheFile(settings); + } + catch { } + + + // Ensure that the reference manager for this scene has been initialised. + var mgr = ES3ReferenceMgr.GetManagerFromScene(this.gameObject.scene, false); + mgr.Awake(); + + var gameObjects = ES3.Load(key, new GameObject[0], settings); + } + + void Start() + { + if(loadEvent == LoadEvent.Start) + Load(); + } + + public void Awake() + { + managers[this.gameObject.scene] = this; + GetAutoSaves(); + + if (loadEvent == LoadEvent.Awake) + Load(); + } + + void OnApplicationQuit() + { + if(saveEvent == SaveEvent.OnApplicationQuit) + Save(); + } + + void OnApplicationPause(bool paused) + { + if( (saveEvent == SaveEvent.OnApplicationPause || + (Application.isMobilePlatform && saveEvent == SaveEvent.OnApplicationQuit)) && paused) + Save(); + } + + /* Register an ES3AutoSave with the ES3AutoSaveMgr, if there is one */ + public static void AddAutoSave(ES3AutoSave autoSave) + { + if (autoSave == null) + return; + + ES3AutoSaveMgr mgr; + if (managers.TryGetValue(autoSave.gameObject.scene, out mgr)) + mgr.autoSaves.Add(autoSave); + + /*if(ES3AutoSaveMgr.Current != null) + ES3AutoSaveMgr.Current.autoSaves.Add(autoSave);*/ + } + + /* Remove an ES3AutoSave from the ES3AutoSaveMgr, for example if it's GameObject has been destroyed */ + public static void RemoveAutoSave(ES3AutoSave autoSave) + { + if (autoSave == null) + return; + + ES3AutoSaveMgr mgr; + if (managers.TryGetValue(autoSave.gameObject.scene, out mgr)) + mgr.autoSaves.Remove(autoSave); + + /*if (ES3AutoSaveMgr.Current != null) + ES3AutoSaveMgr.Current.autoSaves.Remove(autoSave);*/ + } + + /* Gathers all of the ES3AutoSave Components in the scene and registers them with the manager */ + public void GetAutoSaves() + { + autoSaves = new HashSet(); + + foreach (var go in this.gameObject.scene.GetRootGameObjects()) + autoSaves.UnionWith(go.GetComponentsInChildren(true)); + } + + // Gets the depth of a Transform in the hierarchy. + static int GetDepth(Transform t) + { + int depth = 0; + + while (t.parent != null) + { + t = t.parent; + depth++; + } + + return depth; + } + + // Changes the path for this ES3AutoSave if we're using save slots. + void ManageSlots() + { +#if ES3_TMPRO && ES3_UGUI + if (ES3SlotManager.selectedSlotPath != null) + settings.path = ES3SlotManager.selectedSlotPath; +#endif + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSaveMgr.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSaveMgr.cs.meta new file mode 100644 index 0000000..39da0af --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Auto Save/ES3AutoSaveMgr.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9107aee0ced90422da95f0b31680501f +timeCreated: 1519132291 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Debugging.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Debugging.meta new file mode 100644 index 0000000..90e0770 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Debugging.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8af5038c70c9da64eb4fa2c079107361 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Debugging/ES3Debug.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Debugging/ES3Debug.cs new file mode 100644 index 0000000..b583b5d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Debugging/ES3Debug.cs @@ -0,0 +1,52 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace ES3Internal +{ + internal static class ES3Debug + { + private const string disableInfoMsg = "\nTo disable these messages from Easy Save, go to Window > Easy Save 3 > Settings, and uncheck 'Log Info'"; + private const string disableWarningMsg = "\nTo disable warnings from Easy Save, go to Window > Easy Save 3 > Settings, and uncheck 'Log Warnings'"; + private const string disableErrorMsg = "\nTo disable these error messages from Easy Save, go to Window > Easy Save 3 > Settings, and uncheck 'Log Errors'"; + + private const char indentChar = '-'; + + public static void Log(string msg, Object context = null, int indent=0) + { + if (!ES3Settings.defaultSettingsScriptableObject.logDebugInfo) + return; + else if (context != null) + Debug.LogFormat(context, Indent(indent) + msg + disableInfoMsg); + else + Debug.LogFormat(context, Indent(indent) + msg); + } + + public static void LogWarning(string msg, Object context=null, int indent = 0) + { + if (!ES3Settings.defaultSettingsScriptableObject.logWarnings) + return; + else if (context != null) + Debug.LogWarningFormat(context, Indent(indent) + msg + disableWarningMsg); + else + Debug.LogWarningFormat(context, Indent(indent) + msg + disableWarningMsg); + } + + public static void LogError(string msg, Object context = null, int indent = 0) + { + if (!ES3Settings.defaultSettingsScriptableObject.logErrors) + return; + else if (context != null) + Debug.LogErrorFormat(context, Indent(indent) + msg + disableErrorMsg); + else + Debug.LogErrorFormat(context, Indent(indent) + msg + disableErrorMsg); + } + + private static string Indent(int size) + { + if (size < 0) + return ""; + return new string(indentChar, size); + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Debugging/ES3Debug.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Debugging/ES3Debug.cs.meta new file mode 100644 index 0000000..d26c5ba --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Debugging/ES3Debug.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9f97d288c55524622a117171a19d3225 +timeCreated: 1518175265 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3.cs new file mode 100644 index 0000000..3856504 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3.cs @@ -0,0 +1,1660 @@ +using UnityEngine; +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; +#if UNITY_2018_3_OR_NEWER +using UnityEngine.Networking; +#endif + +/// +/// The main class for Easy Save methods. All methods in this class are static. +/// +#if UNITY_VISUAL_SCRIPTING +[Unity.VisualScripting.IncludeInSettings(true)] +#elif BOLT_VISUAL_SCRIPTING +[Ludiq.IncludeInSettings(true)] +#endif +public class ES3 +{ + public enum Location { File, PlayerPrefs, InternalMS, Resources, Cache }; + public enum Directory { PersistentDataPath, DataPath } + public enum EncryptionType { None, AES }; + public enum CompressionType { None, Gzip}; + public enum Format { JSON }; + public enum ReferenceMode { ByRef, ByValue, ByRefAndValue}; + public enum ImageType { JPEG, PNG }; + + #region ES3.Save + + // Saves the value to the default file with the given key. + /// The key we want to use to identify our value in the file. + /// The value we want to save. + public static void Save(string key, object value) + { + Save(key, value, new ES3Settings()); + } + + /// Saves the value to a file with the given key. + /// The key we want to use to identify our value in the file. + /// The value we want to save. + /// The relative or absolute path of the file we want to store our value to. + public static void Save(string key, object value, string filePath) + { + Save(key, value, new ES3Settings(filePath)); + } + + /// Saves the value to a file with the given key. + /// The key we want to use to identify our value in the file. + /// The value we want to save. + /// The relative or absolute path of the file we want to store our value to. + /// The settings we want to use to override the default settings. + public static void Save(string key, object value, string filePath, ES3Settings settings) + { + Save(key, value, new ES3Settings(filePath, settings)); + } + + /// Saves the value to a file with the given key. + /// The key we want to use to identify our value in the file. + /// The value we want to save. + /// The settings we want to use to override the default settings. + public static void Save(string key, object value, ES3Settings settings) + { + Save(key, value, settings); + } + + /// Saves the value to the default file with the given key. + /// The type of the data that we want to save. + /// The key we want to use to identify our value in the file. + /// The value we want to save. + public static void Save(string key, T value) + { + Save(key, value, new ES3Settings()); + } + + /// Saves the value to a file with the given key. + /// The type of the data that we want to save. + /// The key we want to use to identify our value in the file. + /// The value we want to save. + /// The relative or absolute path of the file we want to store our value to. + public static void Save(string key, T value, string filePath) + { + Save(key, value, new ES3Settings(filePath)); + } + + /// Saves the value to a file with the given key. + /// The type of the data that we want to save. + /// The key we want to use to identify our value in the file. + /// The value we want to save. + /// The relative or absolute path of the file we want to store our value to. + /// The settings we want to use to override the default settings. + public static void Save(string key, T value, string filePath, ES3Settings settings) + { + Save(key, value, new ES3Settings(filePath, settings)); + } + + /// Saves the value to a file with the given key. + /// The type of the data that we want to save. + /// The key we want to use to identify our value in the file. + /// The value we want to save. + /// The settings we want to use to override the default settings. + public static void Save(string key, T value, ES3Settings settings) + { + if (settings.location == Location.Cache) + { + ES3File.GetOrCreateCachedFile(settings).Save(key, value); + return; + } + + using (var writer = ES3Writer.Create(settings)) + { + writer.Write(key, value); + writer.Save(); + } + } + + /// Creates or overwrites a file with the specified raw bytes. + /// The bytes we want to store. + public static void SaveRaw(byte[] bytes) + { + SaveRaw(bytes, new ES3Settings()); + } + + /// Creates or overwrites a file with the specified raw bytes. + /// The bytes we want to store. + /// The relative or absolute path of the file we want to store our bytes to. + public static void SaveRaw(byte[] bytes, string filePath) + { + SaveRaw(bytes, new ES3Settings(filePath)); + } + + /// Creates or overwrites a file with the specified raw bytes. + /// The bytes we want to store. + /// The relative or absolute path of the file we want to store our bytes to. + /// The settings we want to use to override the default settings. + public static void SaveRaw(byte[] bytes, string filePath, ES3Settings settings) + { + SaveRaw(bytes, new ES3Settings(filePath, settings)); + } + + /// Creates or overwrites a file with the specified raw bytes. + /// The bytes we want to store. + /// The settings we want to use to override the default settings. + public static void SaveRaw(byte[] bytes, ES3Settings settings) + { + if (settings.location == Location.Cache) + { + ES3File.GetOrCreateCachedFile(settings).SaveRaw(bytes, settings); + return; + } + + using (var stream = ES3Stream.CreateStream(settings, ES3FileMode.Write)) + { + stream.Write(bytes, 0, bytes.Length); + } + ES3IO.CommitBackup(settings); + } + + /// Creates or overwrites the default file with the specified raw bytes. + /// The string we want to store. + public static void SaveRaw(string str) + { + SaveRaw(str, new ES3Settings()); + } + + /// Creates or overwrites the default file with the specified raw bytes. + /// The string we want to store. + /// The relative or absolute path of the file we want to store our bytes to. + public static void SaveRaw(string str, string filePath) + { + SaveRaw(str, new ES3Settings(filePath)); + } + + /// Creates or overwrites a file with the specified raw bytes. + /// The string we want to store. + /// The relative or absolute path of the file we want to store our bytes to. + /// The settings we want to use to override the default settings. + public static void SaveRaw(string str, string filePath, ES3Settings settings) + { + SaveRaw(str, new ES3Settings(filePath, settings)); + } + + /// Creates or overwrites a file with the specified raw bytes. + /// The string we want to store. + /// The settings we want to use to override the default settings. + public static void SaveRaw(string str, ES3Settings settings) + { + var bytes = settings.encoding.GetBytes(str); + SaveRaw(bytes, settings); + } + + /// Creates or appends the specified bytes to a file. + /// The bytes we want to append. + public static void AppendRaw(byte[] bytes) + { + AppendRaw(bytes, new ES3Settings()); + } + + /// Creates or appends the specified bytes to a file. + /// The bytes we want to append. + /// The relative or absolute path of the file we want to append our bytes to. + /// The settings we want to use to override the default settings. + public static void AppendRaw(byte[] bytes, string filePath, ES3Settings settings) + { + AppendRaw(bytes, new ES3Settings(filePath, settings)); + } + + /// Creates or appends the specified bytes to a file. + /// The bytes we want to append. + /// The settings we want to use to override the default settings. + public static void AppendRaw(byte[] bytes, ES3Settings settings) + { + if (settings.location == Location.Cache) + { + ES3File.GetOrCreateCachedFile(settings).AppendRaw(bytes); + return; + } + + ES3Settings newSettings = new ES3Settings(settings.path, settings); + newSettings.encryptionType = EncryptionType.None; + newSettings.compressionType = CompressionType.None; + + using (var stream = ES3Stream.CreateStream(newSettings, ES3FileMode.Append)) + stream.Write(bytes, 0, bytes.Length); + } + + /// Creates or appends the specified string to the default file. + /// The string we want to append. + public static void AppendRaw(string str) + { + AppendRaw(str, new ES3Settings()); + } + + /// Creates or appends the specified string to the default file. + /// The string we want to append. + /// The relative or absolute path of the file we want to append our string to. + public static void AppendRaw(string str, string filePath) + { + AppendRaw(str, new ES3Settings(filePath)); + } + + /// Creates or appends the specified string to the default file. + /// The string we want to append. + /// The relative or absolute path of the file we want to append our string to. + /// The settings we want to use to override the default settings. + public static void AppendRaw(string str, string filePath, ES3Settings settings) + { + AppendRaw(str, new ES3Settings(filePath, settings)); + } + + /// Creates or appends the specified string to the default file. + /// The string we want to append. + /// The settings we want to use to override the default settings. + public static void AppendRaw(string str, ES3Settings settings) + { + var bytes = settings.encoding.GetBytes(str); + ES3Settings newSettings = new ES3Settings(settings.path, settings); + newSettings.encryptionType = EncryptionType.None; + newSettings.compressionType = CompressionType.None; + + if (settings.location == Location.Cache) + { + ES3File.GetOrCreateCachedFile(settings).SaveRaw(bytes); + return; + } + + using (var stream = ES3Stream.CreateStream(newSettings, ES3FileMode.Append)) + stream.Write(bytes, 0, bytes.Length); + } + + /// Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath. + /// The Texture2D we want to save as a JPG or PNG. + /// The relative or absolute path of the PNG or JPG file we want to create. + public static void SaveImage(Texture2D texture, string imagePath) + { + SaveImage(texture, new ES3Settings(imagePath)); + } + + /// Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath. + /// The Texture2D we want to save as a JPG or PNG. + /// The relative or absolute path of the PNG or JPG file we want to create. + public static void SaveImage(Texture2D texture, string imagePath, ES3Settings settings) + { + SaveImage(texture, new ES3Settings(imagePath, settings)); + } + + /// Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath. + /// The Texture2D we want to save as a JPG or PNG. + /// The settings we want to use to override the default settings. + public static void SaveImage(Texture2D texture, ES3Settings settings) + { + SaveImage(texture, 75, settings); + } + + /// Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath. + /// The Texture2D we want to save as a JPG or PNG. + /// Quality to encode with, where 1 is minimum and 100 is maximum. Note that this only applies to JPGs. + /// The relative or absolute path of the PNG or JPG file we want to create. + public static void SaveImage(Texture2D texture, int quality, string imagePath) + { + SaveImage(texture, quality, new ES3Settings(imagePath)); + } + + /// Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath. + /// The Texture2D we want to save as a JPG or PNG. + /// Quality to encode with, where 1 is minimum and 100 is maximum. Note that this only applies to JPGs. + /// The relative or absolute path of the PNG or JPG file we want to create. + public static void SaveImage(Texture2D texture, int quality, string imagePath, ES3Settings settings) + { + SaveImage(texture, quality, new ES3Settings(imagePath, settings)); + } + + /// Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath. + /// The Texture2D we want to save as a JPG or PNG. + /// Quality to encode with, where 1 is minimum and 100 is maximum. Note that this only applies to JPGs. + /// The settings we want to use to override the default settings. + public static void SaveImage(Texture2D texture, int quality, ES3Settings settings) + { + // Get the file extension to determine what format we want to save the image as. + string extension = ES3IO.GetExtension(settings.path).ToLower(); + if (string.IsNullOrEmpty(extension)) + throw new System.ArgumentException("File path must have a file extension when using ES3.SaveImage."); + byte[] bytes; + if (extension == ".jpg" || extension == ".jpeg") + bytes = texture.EncodeToJPG(quality); + else if (extension == ".png") + bytes = texture.EncodeToPNG(); + else + throw new System.ArgumentException("File path must have extension of .png, .jpg or .jpeg when using ES3.SaveImage."); + + ES3.SaveRaw(bytes, settings); + } + + + /// Saves a Texture2D as a PNG or JPG, depending on the file extension used for the filePath. + /// The Texture2D we want to save as a JPG or PNG. + /// Quality to encode with, where 1 is minimum and 100 is maximum. Note that this only applies to JPGs. + public static byte[] SaveImageToBytes(Texture2D texture, int quality, ES3.ImageType imageType) + { + if (imageType == ImageType.JPEG) + return texture.EncodeToJPG(quality); + else + return texture.EncodeToPNG(); + } + + #endregion + + #region ES3.Load + + /* Standard load methods */ + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + public static object Load(string key) + { + return Load(key, new ES3Settings()); + } + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + public static object Load(string key, string filePath) + { + return Load(key, new ES3Settings(filePath)); + } + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The settings we want to use to override the default settings. + public static object Load(string key, string filePath, ES3Settings settings) + { + return Load(key, new ES3Settings(filePath, settings)); + } + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + /// The settings we want to use to override the default settings. + public static object Load(string key, ES3Settings settings) + { + return Load(key, settings); + } + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + /// The value we want to return if the file or key does not exist. + public static object Load(string key, object defaultValue) + { + return Load(key, defaultValue, new ES3Settings()); + } + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The value we want to return if the file or key does not exist. + public static object Load(string key, string filePath, object defaultValue) + { + return Load(key, defaultValue, new ES3Settings(filePath)); + } + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The value we want to return if the file or key does not exist. + /// The settings we want to use to override the default settings. + public static object Load(string key, string filePath, object defaultValue, ES3Settings settings) + { + return Load(key, defaultValue, new ES3Settings(filePath, settings)); + } + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + /// The value we want to return if the file or key does not exist. + /// The settings we want to use to override the default settings. + public static object Load(string key, object defaultValue, ES3Settings settings) + { + return Load(key, defaultValue, settings); + } + + /// Loads the value from a file with the given key. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + public static T Load(string key) + { + return Load(key, new ES3Settings()); + } + + /// Loads the value from a file with the given key. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + public static T Load(string key, string filePath) + { + return Load(key, new ES3Settings(filePath)); + } + + /// Loads the value from a file with the given key. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The settings we want to use to override the default settings. + public static T Load(string key, string filePath, ES3Settings settings) + { + if (typeof(T) == typeof(string)) + ES3Debug.LogWarning("Using ES3.Load(string, string) to load a string, but the second parameter is ambiguous between defaultValue and filePath. By default C# will assume that the second parameter is the filePath. If you want the second parameter to be the defaultValue, use a named parameter. E.g. ES3.Load(\"key\", defaultValue: \"myDefaultValue\")"); + + return Load(key, new ES3Settings(filePath, settings)); + } + + /// Loads the value from a file with the given key. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The settings we want to use to override the default settings. + public static T Load(string key, ES3Settings settings) + { + if (settings.location == Location.Cache) + return ES3File.GetOrCreateCachedFile(settings).Load(key); + + using (var reader = ES3Reader.Create(settings)) + { + if (reader == null) + throw new System.IO.FileNotFoundException("File \"" + settings.FullPath + "\" could not be found."); + return reader.Read(key); + } + } + + /// Loads the value from a file with the given key. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The value we want to return if the file or key does not exist. + public static T Load(string key, T defaultValue) + { + return Load(key, defaultValue, new ES3Settings()); + } + + /// Loads the value from a file with the given key. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The value we want to return if the file or key does not exist. + public static T Load(string key, string filePath, T defaultValue) + { + return Load(key, defaultValue, new ES3Settings(filePath)); + } + + /// Loads the value from a file with the given key. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The value we want to return if the file or key does not exist. + /// The settings we want to use to override the default settings. + public static T Load(string key, string filePath, T defaultValue, ES3Settings settings) + { + return Load(key, defaultValue, new ES3Settings(filePath, settings)); + } + + /// Loads the value from a file with the given key. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The value we want to return if the file or key does not exist. + /// The settings we want to use to override the default settings. + public static T Load(string key, T defaultValue, ES3Settings settings) + { + if (settings.location == Location.Cache) + return ES3File.GetOrCreateCachedFile(settings).Load(key, defaultValue); + + Debug.Log(settings.FullPath + " " + settings.location); + + using (var reader = ES3Reader.Create(settings)) + { + if (reader == null) + return defaultValue; + return reader.Read(key, defaultValue); + } + } + + /* Self-assigning load methods */ + + /// Loads the value from a file with the given key into an existing object, rather than creating a new instance. + /// The key which identifies the value we want to load. + /// The object we want to load the value into. + public static void LoadInto(string key, object obj) where T : class + { + LoadInto(key, obj, new ES3Settings()); + } + + /// Loads the value from a file with the given key into an existing object, rather than creating a new instance. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The object we want to load the value into. + public static void LoadInto(string key, string filePath, object obj) + { + LoadInto(key, obj, new ES3Settings(filePath)); + } + + /// Loads the value from a file with the given key into an existing object, rather than creating a new instance. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The object we want to load the value into. + /// The settings we want to use to override the default settings. + public static void LoadInto(string key, string filePath, object obj, ES3Settings settings) + { + LoadInto(key, obj, new ES3Settings(filePath, settings)); + } + + /// Loads the value from a file with the given key into an existing object, rather than creating a new instance. + /// The key which identifies the value we want to load. + /// The object we want to load the value into. + /// The settings we want to use to override the default settings. + public static void LoadInto(string key, object obj, ES3Settings settings) + { + LoadInto(key, obj, settings); + } + + /// Loads the value from a file with the given key into an existing object, rather than creating a new instance. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The object we want to load the value into. + public static void LoadInto(string key, T obj) where T : class + { + LoadInto(key, obj, new ES3Settings()); + } + + /// Loads the value from a file with the given key into an existing object, rather than creating a new instance. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The object we want to load the value into. + public static void LoadInto(string key, string filePath, T obj) where T : class + { + LoadInto(key, obj, new ES3Settings(filePath)); + } + + /// Loads the value from a file with the given key into an existing object, rather than creating a new instance. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The relative or absolute path of the file we want to load from. + /// The object we want to load the value into. + /// The settings we want to use to override the default settings. + public static void LoadInto(string key, string filePath, T obj, ES3Settings settings) where T : class + { + LoadInto(key, obj, new ES3Settings(filePath, settings)); + } + + /// Loads the value from a file with the given key into an existing object, rather than creating a new instance. + /// The type of the data that we want to load. + /// The key which identifies the value we want to load. + /// The object we want to load the value into. + /// The settings we want to use to override the default settings. + public static void LoadInto(string key, T obj, ES3Settings settings) where T : class + { + if (ES3Reflection.IsValueType(obj.GetType())) + throw new InvalidOperationException("ES3.LoadInto can only be used with reference types, but the data you're loading is a value type. Use ES3.Load instead."); + + if (settings.location == Location.Cache) + { + ES3File.GetOrCreateCachedFile(settings).LoadInto(key, obj); + return; + } + + if (settings == null) settings = new ES3Settings(); + using (var reader = ES3Reader.Create(settings)) + { + if (reader == null) + throw new System.IO.FileNotFoundException("File \"" + settings.FullPath + "\" could not be found."); + reader.ReadInto(key, obj); + } + } + + /* LoadString method, as this can be difficult with overloads. */ + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + /// The value we want to return if the file or key does not exist. + /// The settings we want to use to override the default settings. + public static string LoadString(string key, string defaultValue, ES3Settings settings) + { + return Load(key, null, defaultValue, settings); + } + + /// Loads the value from a file with the given key. + /// The key which identifies the value we want to load. + /// The value we want to return if the file or key does not exist. + /// The relative or absolute path of the file we want to load from. + /// The settings we want to use to override the default settings. + public static string LoadString(string key, string defaultValue, string filePath = null, ES3Settings settings = null) + { + return Load(key, filePath, defaultValue, settings); + } + + #endregion + + #region Other ES3.Load Methods + + /// Loads the default file as a byte array. + public static byte[] LoadRawBytes() + { + return LoadRawBytes(new ES3Settings()); + } + + /// Loads a file as a byte array. + /// The relative or absolute path of the file we want to load as a byte array. + public static byte[] LoadRawBytes(string filePath) + { + return LoadRawBytes(new ES3Settings(filePath)); + } + + /// Loads a file as a byte array. + /// The relative or absolute path of the file we want to load as a byte array. + /// The settings we want to use to override the default settings. + public static byte[] LoadRawBytes(string filePath, ES3Settings settings) + { + return LoadRawBytes(new ES3Settings(filePath, settings)); + } + + /// Loads the default file as a byte array. + /// The settings we want to use to override the default settings. + public static byte[] LoadRawBytes(ES3Settings settings) + { + if (settings.location == Location.Cache) + return ES3File.GetOrCreateCachedFile(settings).LoadRawBytes(); + + using (var stream = ES3Stream.CreateStream(settings, ES3FileMode.Read)) + { + if (stream == null) + throw new System.IO.FileNotFoundException("File "+settings.path+" could not be found"); + + if (stream.GetType() == typeof(System.IO.Compression.GZipStream)) + { + var gZipStream = (System.IO.Compression.GZipStream)stream; + using (var ms = new System.IO.MemoryStream()) + { + ES3Stream.CopyTo(gZipStream, ms); + return ms.ToArray(); + } + } + else + { + var bytes = new byte[stream.Length]; + stream.Read(bytes, 0, bytes.Length); + return bytes; + } + } + + /*if(settings.location == Location.File) + return ES3IO.ReadAllBytes(settings.FullPath); + else if(settings.location == Location.PlayerPrefs) + return System.Convert.FromBase64String(PlayerPrefs.GetString(settings.FullPath)); + else if(settings.location == Location.Resources) + { + var textAsset = Resources.Load(settings.FullPath); + return textAsset.bytes; + } + return null;*/ + } + + /// Loads the default file as a byte array. + public static string LoadRawString() + { + return LoadRawString(new ES3Settings()); + } + + /// Loads a file as a byte array. + /// The relative or absolute path of the file we want to load as a byte array. + /// The settings we want to use to override the default settings. + public static string LoadRawString(string filePath) + { + return LoadRawString(new ES3Settings(filePath)); + } + + /// Loads a file as a byte array. + /// The relative or absolute path of the file we want to load as a byte array. + /// The settings we want to use to override the default settings. + public static string LoadRawString(string filePath, ES3Settings settings) + { + return LoadRawString(new ES3Settings(filePath, settings)); + } + + /// Loads the default file as a byte array. + /// The settings we want to use to override the default settings. + public static string LoadRawString(ES3Settings settings) + { + var bytes = ES3.LoadRawBytes(settings); + return settings.encoding.GetString(bytes, 0, bytes.Length); + } + + /// Loads a PNG or JPG as a Texture2D. + /// The relative or absolute path of the PNG or JPG file we want to load as a Texture2D. + /// The settings we want to use to override the default settings. + public static Texture2D LoadImage(string imagePath) + { + return LoadImage(new ES3Settings(imagePath)); + } + + /// Loads a PNG or JPG as a Texture2D. + /// The relative or absolute path of the PNG or JPG file we want to load as a Texture2D. + /// The settings we want to use to override the default settings. + public static Texture2D LoadImage(string imagePath, ES3Settings settings) + { + return LoadImage(new ES3Settings(imagePath, settings)); + } + + /// Loads a PNG or JPG as a Texture2D. + /// The settings we want to use to override the default settings. + public static Texture2D LoadImage(ES3Settings settings) + { + byte[] bytes = ES3.LoadRawBytes(settings); + return LoadImage(bytes); + } + + /// Loads a PNG or JPG as a Texture2D. + /// The raw bytes of the PNG or JPG. + public static Texture2D LoadImage(byte[] bytes) + { + var texture = new Texture2D(1, 1); + texture.LoadImage(bytes); + return texture; + } + + /// Loads an audio file as an AudioClip. Note that MP3 files are not supported on standalone platforms and Ogg Vorbis files are not supported on mobile platforms. + /// The relative or absolute path of the audio file we want to load as an AudioClip. + public static AudioClip LoadAudio(string audioFilePath +#if UNITY_2018_3_OR_NEWER + , AudioType audioType +#endif + ) + { + return LoadAudio(audioFilePath, +#if UNITY_2018_3_OR_NEWER + audioType, +#endif + new ES3Settings()); + } + + /// Loads an audio file as an AudioClip. Note that MP3 files are not supported on standalone platforms and Ogg Vorbis files are not supported on mobile platforms. + /// The relative or absolute path of the audio file we want to load as an AudioClip. + /// The settings we want to use to override the default settings. + public static AudioClip LoadAudio(string audioFilePath, +#if UNITY_2018_3_OR_NEWER + AudioType audioType, +#endif + ES3Settings settings) + { + if (settings.location != Location.File) + throw new InvalidOperationException("ES3.LoadAudio can only be used with the File save location"); + + if (Application.platform == RuntimePlatform.WebGLPlayer) + throw new InvalidOperationException("You cannot use ES3.LoadAudio with WebGL"); + + string extension = ES3IO.GetExtension(audioFilePath).ToLower(); + + if (extension == ".mp3" && (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXPlayer)) + throw new System.InvalidOperationException("You can only load Ogg, WAV, XM, IT, MOD or S3M on Unity Standalone"); + + if (extension == ".ogg" && (Application.platform == RuntimePlatform.IPhonePlayer + || Application.platform == RuntimePlatform.Android + || Application.platform == RuntimePlatform.WSAPlayerARM)) + throw new System.InvalidOperationException("You can only load MP3, WAV, XM, IT, MOD or S3M on Unity Standalone"); + + var newSettings = new ES3Settings(audioFilePath, settings); + +#if UNITY_2018_3_OR_NEWER + using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip("file://" + newSettings.FullPath, audioType)) + { + www.SendWebRequest(); + + while (!www.isDone) + { + // Wait for it to load. + } + + if (ES3WebClass.IsNetworkError(www)) + throw new System.Exception(www.error); + else + return DownloadHandlerAudioClip.GetContent(www); + } +#elif UNITY_2017_1_OR_NEWER + WWW www = new WWW(newSettings.FullPath); + + while(!www.isDone) + { + // Wait for it to load. + } + + if(!string.IsNullOrEmpty(www.error)) + throw new System.Exception(www.error); +#else + WWW www = new WWW("file://"+newSettings.FullPath); + + while(!www.isDone) + { + // Wait for it to load. + } + + if(!string.IsNullOrEmpty(www.error)) + throw new System.Exception(www.error); +#endif + +#if UNITY_2017_3_OR_NEWER && !UNITY_2018_3_OR_NEWER + return www.GetAudioClip(true); +#elif UNITY_5_6_OR_NEWER && !UNITY_2018_3_OR_NEWER + return WWWAudioExtensions.GetAudioClip(www); +#endif + } + + #endregion + + #region Serialize/Deserialize + + public static byte[] Serialize(T value, ES3Settings settings=null) + { + return Serialize(value, ES3TypeMgr.GetOrCreateES3Type(typeof(T)), settings); + } + + internal static byte[] Serialize(object value, ES3Types.ES3Type type, ES3Settings settings = null) + { + if (settings == null) settings = new ES3Settings(); + + using (var ms = new System.IO.MemoryStream()) + { + using (var stream = ES3Stream.CreateStream(ms, settings, ES3FileMode.Write)) + { + using (var baseWriter = ES3Writer.Create(stream, settings, false, false)) + { + // If T is object, use the value to get it's type. Otherwise, use T so that it works with inheritence. + //var type = typeof(T) != typeof(object) ? typeof(T) : (value == null ? typeof(T) : value.GetType()); + baseWriter.Write(value, type, settings.referenceMode); + } + + return ms.ToArray(); + } + } + } + + public static T Deserialize(byte[] bytes, ES3Settings settings=null) + { + return (T)Deserialize(ES3TypeMgr.GetOrCreateES3Type(typeof(T)), bytes, settings); + } + + internal static object Deserialize(ES3Types.ES3Type type, byte[] bytes, ES3Settings settings = null) + { + if (settings == null) + settings = new ES3Settings(); + + using (var ms = new System.IO.MemoryStream(bytes, false)) + using (var stream = ES3Stream.CreateStream(ms, settings, ES3FileMode.Read)) + using (var reader = ES3Reader.Create(stream, settings, false)) + return reader.Read(type); + } + + public static void DeserializeInto(byte[] bytes, T obj, ES3Settings settings = null) where T : class + { + DeserializeInto(ES3TypeMgr.GetOrCreateES3Type(typeof(T)), bytes, obj, settings); + } + + public static void DeserializeInto(ES3Types.ES3Type type, byte[] bytes, T obj, ES3Settings settings = null) where T : class + { + if (settings == null) + settings = new ES3Settings(); + + using (var ms = new System.IO.MemoryStream(bytes, false)) + using (var reader = ES3Reader.Create(ms, settings, false)) + reader.ReadInto(obj, type); + } + + #endregion + + #region Other ES3 Methods + +#if !DISABLE_ENCRYPTION + + public static byte[] EncryptBytes(byte[] bytes, string password=null) + { + if (string.IsNullOrEmpty(password)) + password = ES3Settings.defaultSettings.encryptionPassword; + return new AESEncryptionAlgorithm().Encrypt(bytes, password, ES3Settings.defaultSettings.bufferSize); + } + + public static byte[] DecryptBytes(byte[] bytes, string password=null) + { + if (string.IsNullOrEmpty(password)) + password = ES3Settings.defaultSettings.encryptionPassword; + return new AESEncryptionAlgorithm().Decrypt(bytes, password, ES3Settings.defaultSettings.bufferSize); + } + + public static string EncryptString(string str, string password=null) + { + return Convert.ToBase64String(EncryptBytes(ES3Settings.defaultSettings.encoding.GetBytes(str), password)); + } + + public static string DecryptString(string str, string password=null) + { + return ES3Settings.defaultSettings.encoding.GetString(DecryptBytes(Convert.FromBase64String(str), password)); + } + +#endif + + public static byte[] CompressBytes(byte[] bytes) + { + using (var ms = new System.IO.MemoryStream()) + { + var settings = new ES3Settings(); + settings.location = ES3.Location.InternalMS; + settings.compressionType = ES3.CompressionType.Gzip; + settings.encryptionType = EncryptionType.None; + + using (var stream = ES3Stream.CreateStream(ms, settings, ES3FileMode.Write)) + stream.Write(bytes, 0, bytes.Length); + + return ms.ToArray(); + } + } + + public static byte[] DecompressBytes(byte[] bytes) + { + using (var ms = new System.IO.MemoryStream(bytes)) + { + var settings = new ES3Settings(); + settings.location = ES3.Location.InternalMS; + settings.compressionType = ES3.CompressionType.Gzip; + settings.encryptionType = EncryptionType.None; + + using (var output = new System.IO.MemoryStream()) + { + using (var input = ES3Stream.CreateStream(ms, settings, ES3FileMode.Read)) + ES3Stream.CopyTo(input, output); + return output.ToArray(); + } + } + } + + public static string CompressString(string str) + { + return Convert.ToBase64String(CompressBytes(ES3Settings.defaultSettings.encoding.GetBytes(str))); + } + + public static string DecompressString(string str) + { + return ES3Settings.defaultSettings.encoding.GetString(DecompressBytes(Convert.FromBase64String(str))); + } + + /// Deletes the default file. + public static void DeleteFile() + { + DeleteFile(new ES3Settings()); + } + + /// Deletes the file at the given path using the default settings. + /// The relative or absolute path of the file we wish to delete. + public static void DeleteFile(string filePath) + { + DeleteFile(new ES3Settings(filePath)); + } + + /// Deletes the file at the given path using the settings provided. + /// The relative or absolute path of the file we wish to delete. + /// The settings we want to use to override the default settings. + public static void DeleteFile(string filePath, ES3Settings settings) + { + DeleteFile(new ES3Settings(filePath, settings)); + } + + /// Deletes the file specified by the ES3Settings object provided as a parameter. + /// The settings we want to use to override the default settings. + public static void DeleteFile(ES3Settings settings) + { + if (settings.location == Location.File) + ES3IO.DeleteFile(settings.FullPath); + else if (settings.location == Location.PlayerPrefs) + PlayerPrefs.DeleteKey(settings.FullPath); + else if (settings.location == Location.Cache) + ES3File.RemoveCachedFile(settings); + else if (settings.location == Location.Resources) + throw new System.NotSupportedException("Deleting files from Resources is not possible."); + } + + /// Copies a file from one path to another. + /// The relative or absolute path of the file we want to copy. + /// The relative or absolute path of the copy we want to create. + public static void CopyFile(string oldFilePath, string newFilePath) + { + CopyFile(new ES3Settings(oldFilePath), new ES3Settings(newFilePath)); + } + + /// Copies a file from one location to another, using the ES3Settings provided to override any default settings. + /// The relative or absolute path of the file we want to copy. + /// The relative or absolute path of the copy we want to create. + /// The settings we want to use when copying the old file. + /// The settings we want to use when creating the new file. + public static void CopyFile(string oldFilePath, string newFilePath, ES3Settings oldSettings, ES3Settings newSettings) + { + CopyFile(new ES3Settings(oldFilePath, oldSettings), new ES3Settings(newFilePath, newSettings)); + } + + /// Copies a file from one location to another, using the ES3Settings provided to determine the locations. + /// The settings we want to use when copying the old file. + /// The settings we want to use when creating the new file. + public static void CopyFile(ES3Settings oldSettings, ES3Settings newSettings) + { + if (oldSettings.location != newSettings.location) + throw new InvalidOperationException("Cannot copy file from " + oldSettings.location + " to " + newSettings.location + ". Location must be the same for both source and destination."); + + if (oldSettings.location == Location.File) + { + if (ES3IO.FileExists(oldSettings.FullPath)) + { + // Create the new directory if it doesn't exist. + string newDirectory = ES3IO.GetDirectoryPath(newSettings.FullPath); + if (!ES3IO.DirectoryExists(newDirectory)) + ES3IO.CreateDirectory(newDirectory); + // Otherwise delete the existing file so that we can overwrite it. + else + ES3IO.DeleteFile(newSettings.FullPath); + ES3IO.CopyFile(oldSettings.FullPath, newSettings.FullPath); + } + } + else if (oldSettings.location == Location.PlayerPrefs) + { + PlayerPrefs.SetString(newSettings.FullPath, PlayerPrefs.GetString(oldSettings.FullPath)); + } + else if (oldSettings.location == Location.Cache) + { + ES3File.CopyCachedFile(oldSettings, newSettings); + } + else if (oldSettings.location == Location.Resources) + throw new System.NotSupportedException("Modifying files from Resources is not allowed."); + } + + /// Renames a file. + /// The relative or absolute path of the file we want to rename. + /// The relative or absolute path we want to rename the file to. + public static void RenameFile(string oldFilePath, string newFilePath) + { + RenameFile(new ES3Settings(oldFilePath), new ES3Settings(newFilePath)); + } + + /// Renames a file. + /// The relative or absolute path of the file we want to rename. + /// The relative or absolute path we want to rename the file to. + /// The settings for the file we want to rename. + /// The settings for the file we want our source file to be renamed to. + public static void RenameFile(string oldFilePath, string newFilePath, ES3Settings oldSettings, ES3Settings newSettings) + { + RenameFile(new ES3Settings(oldFilePath, oldSettings), new ES3Settings(newFilePath, newSettings)); + } + + /// Renames a file. + /// The settings for the file we want to rename. + /// The settings for the file we want our source file to be renamed to. + public static void RenameFile(ES3Settings oldSettings, ES3Settings newSettings) + { + if (oldSettings.location != newSettings.location) + throw new InvalidOperationException("Cannot rename file in " + oldSettings.location + " to " + newSettings.location + ". Location must be the same for both source and destination."); + + if (oldSettings.location == Location.File) + { + if (ES3IO.FileExists(oldSettings.FullPath)) + { + ES3IO.DeleteFile(newSettings.FullPath); + ES3IO.MoveFile(oldSettings.FullPath, newSettings.FullPath); + } + } + else if (oldSettings.location == Location.PlayerPrefs) + { + PlayerPrefs.SetString(newSettings.FullPath, PlayerPrefs.GetString(oldSettings.FullPath)); + PlayerPrefs.DeleteKey(oldSettings.FullPath); + } + else if (oldSettings.location == Location.Cache) + { + ES3File.CopyCachedFile(oldSettings, newSettings); + ES3File.RemoveCachedFile(oldSettings); + } + else if (oldSettings.location == Location.Resources) + throw new System.NotSupportedException("Modifying files from Resources is not allowed."); + } + + /// Copies a file from one path to another. + /// The relative or absolute path of the directory we want to copy. + /// The relative or absolute path of the copy we want to create. + public static void CopyDirectory(string oldDirectoryPath, string newDirectoryPath) + { + CopyDirectory(new ES3Settings(oldDirectoryPath), new ES3Settings(newDirectoryPath)); + } + + /// Copies a file from one location to another, using the ES3Settings provided to override any default settings. + /// The relative or absolute path of the directory we want to copy. + /// The relative or absolute path of the copy we want to create. + /// The settings we want to use when copying the old directory. + /// The settings we want to use when creating the new directory. + public static void CopyDirectory(string oldDirectoryPath, string newDirectoryPath, ES3Settings oldSettings, ES3Settings newSettings) + { + CopyDirectory(new ES3Settings(oldDirectoryPath, oldSettings), new ES3Settings(newDirectoryPath, newSettings)); + } + + /// Copies a file from one location to another, using the ES3Settings provided to determine the locations. + /// The settings we want to use when copying the old file. + /// The settings we want to use when creating the new file. + public static void CopyDirectory(ES3Settings oldSettings, ES3Settings newSettings) + { + if (oldSettings.location != Location.File) + throw new InvalidOperationException("ES3.CopyDirectory can only be used when the save location is 'File'"); + + if (!DirectoryExists(oldSettings)) + throw new System.IO.DirectoryNotFoundException("Directory " + oldSettings.FullPath + " not found"); + + if (!DirectoryExists(newSettings)) + ES3IO.CreateDirectory(newSettings.FullPath); + + foreach (var fileName in ES3.GetFiles(oldSettings)) + CopyFile(ES3IO.CombinePathAndFilename(oldSettings.path, fileName), + ES3IO.CombinePathAndFilename(newSettings.path, fileName)); + + foreach (var directoryName in GetDirectories(oldSettings)) + CopyDirectory(ES3IO.CombinePathAndFilename(oldSettings.path, directoryName), + ES3IO.CombinePathAndFilename(newSettings.path, directoryName)); + } + + /// Renames a file. + /// The relative or absolute path of the file we want to rename. + /// The relative or absolute path we want to rename the file to. + public static void RenameDirectory(string oldDirectoryPath, string newDirectoryPath) + { + RenameDirectory(new ES3Settings(oldDirectoryPath), new ES3Settings(newDirectoryPath)); + } + + /// Renames a file. + /// The relative or absolute path of the file we want to rename. + /// The relative or absolute path we want to rename the file to. + /// The settings for the file we want to rename. + /// The settings for the file we want our source file to be renamed to. + public static void RenameDirectory(string oldDirectoryPath, string newDirectoryPath, ES3Settings oldSettings, ES3Settings newSettings) + { + RenameDirectory(new ES3Settings(oldDirectoryPath, oldSettings), new ES3Settings(newDirectoryPath, newSettings)); + } + + /// Renames a file. + /// The settings for the file we want to rename. + /// The settings for the file we want our source file to be renamed to. + public static void RenameDirectory(ES3Settings oldSettings, ES3Settings newSettings) + { + if (oldSettings.location == Location.File) + { + if (ES3IO.DirectoryExists(oldSettings.FullPath)) + { + ES3IO.DeleteDirectory(newSettings.FullPath); + ES3IO.MoveDirectory(oldSettings.FullPath, newSettings.FullPath); + } + } + else if (oldSettings.location == Location.PlayerPrefs || oldSettings.location == Location.Cache) + throw new System.NotSupportedException("Directories cannot be renamed when saving to Cache, PlayerPrefs, tvOS or using WebGL."); + else if (oldSettings.location == Location.Resources) + throw new System.NotSupportedException("Modifying files from Resources is not allowed."); + } + + /// Deletes the directory at the given path using the settings provided. + /// The relative or absolute path of the folder we wish to delete. + public static void DeleteDirectory(string directoryPath) + { + DeleteDirectory(new ES3Settings(directoryPath)); + } + + /// Deletes the directory at the given path using the settings provided. + /// The relative or absolute path of the folder we wish to delete. + /// The settings we want to use to override the default settings. + public static void DeleteDirectory(string directoryPath, ES3Settings settings) + { + DeleteDirectory(new ES3Settings(directoryPath, settings)); + } + + /// Deletes the directory at the given path using the settings provided. + /// The settings we want to use to override the default settings. + public static void DeleteDirectory(ES3Settings settings) + { + if (settings.location == Location.File) + ES3IO.DeleteDirectory(settings.FullPath); + else if (settings.location == Location.PlayerPrefs || settings.location == Location.Cache) + throw new System.NotSupportedException("Deleting Directories using Cache or PlayerPrefs is not supported."); + else if (settings.location == Location.Resources) + throw new System.NotSupportedException("Deleting directories from Resources is not allowed."); + } + + /// Deletes a key in the default file. + /// The key we want to delete. + public static void DeleteKey(string key) + { + DeleteKey(key, new ES3Settings()); + } + + public static void DeleteKey(string key, string filePath) + { + DeleteKey(key, new ES3Settings(filePath)); + } + + /// Deletes a key in the file specified. + /// The key we want to delete. + /// The relative or absolute path of the file we want to delete the key from. + /// The settings we want to use to override the default settings. + public static void DeleteKey(string key, string filePath, ES3Settings settings) + { + DeleteKey(key, new ES3Settings(filePath, settings)); + } + + /// Deletes a key in the file specified by the ES3Settings object. + /// The key we want to delete. + /// The settings we want to use to override the default settings. + public static void DeleteKey(string key, ES3Settings settings) + { + if (settings.location == Location.Resources) + throw new System.NotSupportedException("Modifying files in Resources is not allowed."); + else if (settings.location == Location.Cache) + ES3File.DeleteKey(key, settings); + else if (ES3.FileExists(settings)) + { + using (var writer = ES3Writer.Create(settings)) + { + writer.MarkKeyForDeletion(key); + writer.Save(); + } + } + } + + /// Checks whether a key exists in the default file. + /// The key we want to check the existence of. + /// True if the key exists, otherwise False. + public static bool KeyExists(string key) + { + return KeyExists(key, new ES3Settings()); + } + + /// Checks whether a key exists in the specified file. + /// The key we want to check the existence of. + /// The relative or absolute path of the file we want to search. + /// True if the key exists, otherwise False. + public static bool KeyExists(string key, string filePath) + { + return KeyExists(key, new ES3Settings(filePath)); + } + + /// Checks whether a key exists in the default file. + /// The key we want to check the existence of. + /// The relative or absolute path of the file we want to search. + /// The settings we want to use to override the default settings. + /// True if the key exists, otherwise False. + public static bool KeyExists(string key, string filePath, ES3Settings settings) + { + return KeyExists(key, new ES3Settings(filePath, settings)); + } + + /// Checks whether a key exists in a file. + /// The key we want to check the existence of. + /// The settings we want to use to override the default settings. + /// True if the file exists, otherwise False. + public static bool KeyExists(string key, ES3Settings settings) + { + if (settings.location == Location.Cache) + return ES3File.KeyExists(key, settings); + + using (var reader = ES3Reader.Create(settings)) + { + if (reader == null) + return false; + return reader.Goto(key); + } + } + + /// Checks whether the default file exists. + /// The relative or absolute path of the file we want to check the existence of. + /// True if the file exists, otherwise False. + public static bool FileExists() + { + return FileExists(new ES3Settings()); + } + + /// Checks whether a file exists. + /// The relative or absolute path of the file we want to check the existence of. + /// True if the file exists, otherwise False. + public static bool FileExists(string filePath) + { + return FileExists(new ES3Settings(filePath)); + } + + /// Checks whether a file exists. + /// The relative or absolute path of the file we want to check the existence of. + /// The settings we want to use to override the default settings. + /// True if the file exists, otherwise False. + public static bool FileExists(string filePath, ES3Settings settings) + { + return FileExists(new ES3Settings(filePath, settings)); + } + + /// Checks whether a file exists. + /// The settings we want to use to override the default settings. + /// True if the file exists, otherwise False. + public static bool FileExists(ES3Settings settings) + { + if (settings.location == Location.File) + return ES3IO.FileExists(settings.FullPath); + else if (settings.location == Location.PlayerPrefs) + return PlayerPrefs.HasKey(settings.FullPath); + else if (settings.location == Location.Cache) + return ES3File.FileExists(settings); + else if (settings.location == Location.Resources) + return Resources.Load(settings.FullPath) != null; + return false; + } + + /// Checks whether a folder exists. + /// The relative or absolute path of the folder we want to check the existence of. + /// True if the folder exists, otherwise False. + public static bool DirectoryExists(string folderPath) + { + return DirectoryExists(new ES3Settings(folderPath)); + } + + /// Checks whether a file exists. + /// The relative or absolute path of the folder we want to check the existence of. + /// The settings we want to use to override the default settings. + /// True if the folder exists, otherwise False. + + public static bool DirectoryExists(string folderPath, ES3Settings settings) + { + return DirectoryExists(new ES3Settings(folderPath, settings)); + } + + /// Checks whether a folder exists. + /// The settings we want to use to override the default settings. + /// True if the folder exists, otherwise False. + public static bool DirectoryExists(ES3Settings settings) + { + if (settings.location == Location.File) + return ES3IO.DirectoryExists(settings.FullPath); + else if (settings.location == Location.PlayerPrefs || settings.location == Location.Cache) + throw new System.NotSupportedException("Directories are not supported for the Cache and PlayerPrefs location."); + else if (settings.location == Location.Resources) + throw new System.NotSupportedException("Checking existence of folder in Resources not supported."); + return false; + } + + /// Gets an array of all of the key names in the default file. + public static string[] GetKeys() + { + return GetKeys(new ES3Settings()); + } + + /// Gets an array of all of the key names in a file. + /// The relative or absolute path of the file we want to get the key names from. + public static string[] GetKeys(string filePath) + { + return GetKeys(new ES3Settings(filePath)); + } + + /// Gets an array of all of the key names in a file. + /// The relative or absolute path of the file we want to get the key names from. + /// The settings we want to use to override the default settings. + public static string[] GetKeys(string filePath, ES3Settings settings) + { + return GetKeys(new ES3Settings(filePath, settings)); + } + + /// Gets an array of all of the key names in a file. + /// The settings we want to use to override the default settings. + public static string[] GetKeys(ES3Settings settings) + { + + if (settings.location == Location.Cache) + return ES3File.GetKeys(settings); + + var keys = new List(); + using (var reader = ES3Reader.Create(settings)) + { + if (reader == null) + throw new System.IO.FileNotFoundException("Could not get keys from file "+settings.FullPath+" as file does not exist"); + + foreach (string key in reader.Properties) + { + keys.Add(key); + reader.Skip(); + } + } + return keys.ToArray(); + } + + /// Gets an array of all of the file names in a directory. + public static string[] GetFiles() + { + var settings = new ES3Settings(); + if (settings.location == ES3.Location.File) + { + if (settings.directory == ES3.Directory.PersistentDataPath) + settings.path = ES3IO.persistentDataPath; + else + settings.path = ES3IO.dataPath; + } + return GetFiles(new ES3Settings()); + } + + /// Gets an array of all of the file names in a directory. + /// The relative or absolute path of the directory we want to get the file names from. + public static string[] GetFiles(string directoryPath) + { + return GetFiles(new ES3Settings(directoryPath)); + } + + /// Gets an array of all of the file names in a directory. + /// The relative or absolute path of the directory we want to get the file names from. + /// The settings we want to use to override the default settings. + public static string[] GetFiles(string directoryPath, ES3Settings settings) + { + return GetFiles(new ES3Settings(directoryPath, settings)); + } + + /// Gets an array of all of the file names in a directory. + /// The settings we want to use to override the default settings. + public static string[] GetFiles(ES3Settings settings) + { + if (settings.location == Location.Cache) + return ES3File.GetFiles(); + else if (settings.location != ES3.Location.File) + throw new System.NotSupportedException("ES3.GetFiles can only be used when the location is set to File or Cache."); + return ES3IO.GetFiles(settings.FullPath, false); + } + + /// Gets an array of all of the sub-directory names in a directory. + public static string[] GetDirectories() + { + return GetDirectories(new ES3Settings()); + } + + /// Gets an array of all of the sub-directory names in a directory. + /// The relative or absolute path of the directory we want to get the sub-directory names from. + public static string[] GetDirectories(string directoryPath) + { + return GetDirectories(new ES3Settings(directoryPath)); + } + + /// Gets an array of all of the sub-directory names in a directory. + /// The relative or absolute path of the directory we want to get the sub-directory names from. + /// The settings we want to use to override the default settings. + public static string[] GetDirectories(string directoryPath, ES3Settings settings) + { + return GetDirectories(new ES3Settings(directoryPath, settings)); + } + + /// Gets an array of all of the sub-directory names in a directory. + /// The settings we want to use to override the default settings. + public static string[] GetDirectories(ES3Settings settings) + { + if (settings.location != ES3.Location.File) + throw new System.NotSupportedException("ES3.GetDirectories can only be used when the location is set to File."); + return ES3IO.GetDirectories(settings.FullPath, false); + } + + /// Creates a backup of the default file . + /// A backup is created by copying the file and giving it a .bak extension. + /// If a backup already exists it will be overwritten, so you will need to ensure that the old backup will not be required before calling this method. + public static void CreateBackup() + { + CreateBackup(new ES3Settings()); + } + + /// Creates a backup of a file. + /// A backup is created by copying the file and giving it a .bak extension. + /// If a backup already exists it will be overwritten, so you will need to ensure that the old backup will not be required before calling this method. + /// The relative or absolute path of the file we wish to create a backup of. + public static void CreateBackup(string filePath) + { + CreateBackup(new ES3Settings(filePath)); + } + + /// Creates a backup of a file. + /// A backup is created by copying the file and giving it a .bak extension. + /// If a backup already exists it will be overwritten, so you will need to ensure that the old backup will not be required before calling this method. + /// The relative or absolute path of the file we wish to create a backup of. + /// The settings we want to use to override the default settings. + public static void CreateBackup(string filePath, ES3Settings settings) + { + CreateBackup(new ES3Settings(filePath, settings)); + } + + /// Creates a backup of a file. + /// A backup is created by copying the file and giving it a .bak extension. + /// If a backup already exists it will be overwritten, so you will need to ensure that the old backup will not be required before calling this method. + /// The settings we want to use to override the default settings. + public static void CreateBackup(ES3Settings settings) + { + var backupSettings = new ES3Settings(settings.path + ES3IO.backupFileSuffix, settings); + ES3.CopyFile(settings, backupSettings); + } + + /// Restores a backup of a file. + /// The relative or absolute path of the file we wish to restore the backup of. + /// True if a backup was restored, or False if no backup could be found. + public static bool RestoreBackup(string filePath) + { + return RestoreBackup(new ES3Settings(filePath)); + } + + /// Restores a backup of a file. + /// The relative or absolute path of the file we wish to restore the backup of. + /// The settings we want to use to override the default settings. + /// True if a backup was restored, or False if no backup could be found. + public static bool RestoreBackup(string filePath, ES3Settings settings) + { + return RestoreBackup(new ES3Settings(filePath, settings)); + } + + /// Restores a backup of a file. + /// The settings we want to use to override the default settings. + /// True if a backup was restored, or False if no backup could be found. + public static bool RestoreBackup(ES3Settings settings) + { + var backupSettings = new ES3Settings(settings.path + ES3IO.backupFileSuffix, settings); + + if (!FileExists(backupSettings)) + return false; + + ES3.RenameFile(backupSettings, settings); + + return true; + } + + public static DateTime GetTimestamp() + { + return GetTimestamp(new ES3Settings()); + } + + public static DateTime GetTimestamp(string filePath) + { + return GetTimestamp(new ES3Settings(filePath)); + } + + public static DateTime GetTimestamp(string filePath, ES3Settings settings) + { + return GetTimestamp(new ES3Settings(filePath, settings)); + } + + /// Gets the date and time the file was last updated, in the UTC timezone. + /// The settings we want to use to override the default settings. + /// A DateTime object represeting the UTC date and time the file was last updated. + public static DateTime GetTimestamp(ES3Settings settings) + { + if (settings.location == Location.File) + return ES3IO.GetTimestamp(settings.FullPath); + else if (settings.location == Location.PlayerPrefs) + return new DateTime(long.Parse(PlayerPrefs.GetString("timestamp_" + settings.FullPath, "0")), DateTimeKind.Utc); + else if (settings.location == Location.Cache) + return ES3File.GetTimestamp(settings); + else + return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + } + + /// Stores the default cached file to persistent storage. + /// A backup is created by copying the file and giving it a .bak extension. + /// If a backup already exists it will be overwritten, so you will need to ensure that the old backup will not be required before calling this method. + public static void StoreCachedFile() + { + ES3File.Store(); + } + + /// Stores a cached file to persistent storage. + /// The filename or path of the file we want to store the cached file to. + public static void StoreCachedFile(string filePath) + { + StoreCachedFile(new ES3Settings(filePath)); + } + + /// Creates a backup of a file. + /// The filename or path of the file we want to store the cached file to. + /// The settings of the file we want to store to. + public static void StoreCachedFile(string filePath, ES3Settings settings) + { + StoreCachedFile(new ES3Settings(filePath, settings)); + } + + /// Stores a cached file to persistent storage. + /// The settings of the file we want to store to. + public static void StoreCachedFile(ES3Settings settings) + { + ES3File.Store(settings); + } + + /// Loads the default file in persistent storage into the cache. + /// A backup is created by copying the file and giving it a .bak extension. + /// If a backup already exists it will be overwritten, so you will need to ensure that the old backup will not be required before calling this method. + public static void CacheFile() + { + CacheFile(new ES3Settings()); + } + + /// Loads a file from persistent storage into the cache. + /// The filename or path of the file we want to store the cached file to. + public static void CacheFile(string filePath) + { + CacheFile(new ES3Settings(filePath)); + } + + /// Loads a file from persistent storage into the cache. + /// The filename or path of the file we want to store the cached file to. + /// The settings of the file we want to cache. + public static void CacheFile(string filePath, ES3Settings settings) + { + CacheFile(new ES3Settings(filePath, settings)); + } + + /// Loads a file from persistent storage into the cache. + /// The settings of the file we want to cache. + public static void CacheFile(ES3Settings settings) + { + ES3File.CacheFile(settings); + } + + /// Initialises Easy Save. This happens automatically when any ES3 methods are called, but is useful if you want to perform initialisation before calling an ES3 method. + public static void Init() + { + var settings = ES3Settings.defaultSettings; + var pdp = ES3IO.persistentDataPath; // Call this to initialise ES3IO for threading purposes. + ES3TypeMgr.Init(); + } + + #endregion +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3.cs.meta new file mode 100644 index 0000000..e5d6900 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ca1cdcde6d39a44b39ee5f5b86ddfd73 +timeCreated: 1499764822 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Crypto.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Crypto.cs new file mode 100644 index 0000000..b7ef8dc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Crypto.cs @@ -0,0 +1,208 @@ +#if !DISABLE_ENCRYPTION +using System.IO; +using System.Security.Cryptography; +#if NETFX_CORE +using Windows.Security.Cryptography; +using Windows.Security.Cryptography.Core; +using Windows.Storage.Streams; +using System.Runtime.InteropServices.WindowsRuntime; +#endif + +namespace ES3Internal +{ + public static class ES3Hash + { +#if NETFX_CORE + public static string SHA1Hash(string input) + { + return System.Text.Encoding.UTF8.GetString(UnityEngine.Windows.Crypto.ComputeSHA1Hash(System.Text.Encoding.UTF8.GetBytes(input))); + } +#else + public static string SHA1Hash(string input) + { + using (SHA1Managed sha1 = new SHA1Managed()) + return System.Text.Encoding.UTF8.GetString(sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(input))); + } +#endif + } + + public abstract class EncryptionAlgorithm + { + public abstract byte[] Encrypt(byte[] bytes, string password, int bufferSize); + public abstract byte[] Decrypt(byte[] bytes, string password, int bufferSize); + public abstract void Encrypt(Stream input, Stream output, string password, int bufferSize); + public abstract void Decrypt(Stream input, Stream output, string password, int bufferSize); + + protected static void CopyStream(Stream input, Stream output, int bufferSize) + { + byte[] buffer = new byte[bufferSize]; + int read; + while ((read = input.Read(buffer, 0, bufferSize)) > 0) + output.Write(buffer, 0, read); + } + } + + public class AESEncryptionAlgorithm : EncryptionAlgorithm + { + private const int ivSize = 16; + private const int keySize = 16; + private const int pwIterations = 100; + + public override byte[] Encrypt(byte[] bytes, string password, int bufferSize) + { + using (var input = new MemoryStream(bytes)) + { + using (var output = new MemoryStream()) + { + Encrypt(input, output, password, bufferSize); + return output.ToArray(); + } + } + } + + public override byte[] Decrypt(byte[] bytes, string password, int bufferSize) + { + using (var input = new MemoryStream(bytes)) + { + using (var output = new MemoryStream()) + { + Decrypt(input, output, password, bufferSize); + return output.ToArray(); + } + } + } + + public override void Encrypt(Stream input, Stream output, string password, int bufferSize) + { + input.Position = 0; + +#if NETFX_CORE + // Generate an IV and write it to the output. + var iv = CryptographicBuffer.GenerateRandom(ivSize); + output.Write(iv.ToArray(), 0, ivSize); + + var pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); + var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); + KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(iv, pwIterations); + // Create a key based on original key and derivation parmaters + CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); + IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, keySize); + + var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); + var key = provider.CreateSymmetricKey(keyMaterial); + + // Get the input stream as an IBuffer. + IBuffer msg; + using(var ms = new MemoryStream()) + { + input.CopyTo(ms); + msg = ms.ToArray().AsBuffer(); + } + + var buffEncrypt = CryptographicEngine.Encrypt(key, msg, iv); + + + output.Write(buffEncrypt.ToArray(), 0, (int)buffEncrypt.Length); + output.Dispose(); +#else + using (var alg = Aes.Create()) + { + alg.Mode = CipherMode.CBC; + alg.Padding = PaddingMode.PKCS7; + alg.GenerateIV(); + var key = new Rfc2898DeriveBytes(password, alg.IV, pwIterations); + alg.Key = key.GetBytes(keySize); + // Write the IV to the output stream. + output.Write(alg.IV, 0, ivSize); + using(var encryptor = alg.CreateEncryptor()) + using(var cs = new CryptoStream(output, encryptor, CryptoStreamMode.Write)) + CopyStream(input, cs, bufferSize); + } +#endif + } + + public override void Decrypt(Stream input, Stream output, string password, int bufferSize) + { +#if NETFX_CORE + var thisIV = new byte[ivSize]; + input.Read(thisIV, 0, ivSize); + var iv = thisIV.AsBuffer(); + + var pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8); + + var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1"); + KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(iv, pwIterations); + // Create a key based on original key and derivation parameters. + CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer); + IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, keySize); + + var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7); + var key = provider.CreateSymmetricKey(keyMaterial); + + // Get the input stream as an IBuffer. + IBuffer msg; + using(var ms = new MemoryStream()) + { + input.CopyTo(ms); + msg = ms.ToArray().AsBuffer(); + } + + var buffDecrypt = CryptographicEngine.Decrypt(key, msg, iv); + + output.Write(buffDecrypt.ToArray(), 0, (int)buffDecrypt.Length); +#else + using (var alg = Aes.Create()) + { + var thisIV = new byte[ivSize]; + input.Read(thisIV, 0, ivSize); + alg.IV = thisIV; + + var key = new Rfc2898DeriveBytes(password, alg.IV, pwIterations); + alg.Key = key.GetBytes(keySize); + + using(var decryptor = alg.CreateDecryptor()) + using(var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read)) + CopyStream(cryptoStream, output, bufferSize); + + } +#endif + output.Position = 0; + } + } + + public class UnbufferedCryptoStream : MemoryStream + { + private readonly Stream stream; + private readonly bool isReadStream; + private string password; + private int bufferSize; + private EncryptionAlgorithm alg; + private bool disposed = false; + + public UnbufferedCryptoStream(Stream stream, bool isReadStream, string password, int bufferSize, EncryptionAlgorithm alg) : base() + { + this.stream = stream; + this.isReadStream = isReadStream; + this.password = password; + this.bufferSize = bufferSize; + this.alg = alg; + + + if (isReadStream) + alg.Decrypt(stream, this, password, bufferSize); + } + + protected override void Dispose(bool disposing) + { + if (disposed) + return; + disposed = true; + + if (!isReadStream) + alg.Encrypt(this, stream, password, bufferSize); + stream.Dispose(); + base.Dispose(disposing); + } + } +} +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Crypto.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Crypto.cs.meta new file mode 100644 index 0000000..5d39d6d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Crypto.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d2b3b6335276042569261b3e6bed694e +timeCreated: 1519132297 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3File.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3File.cs new file mode 100644 index 0000000..e1db729 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3File.cs @@ -0,0 +1,524 @@ +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System; +using ES3Types; +using UnityEngine; +using ES3Internal; +using System.Linq; + +/// Represents a cached file which can be saved to and loaded from, and commited to storage when necessary. +public class ES3File +{ + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public static Dictionary cachedFiles = new Dictionary(); + + + + + public ES3Settings settings; + private Dictionary cache = new Dictionary(); + private bool syncWithFile = false; + private DateTime timestamp = DateTime.UtcNow; + + /// Creates a new ES3File and loads the default file into the ES3File if there is data to load. + public ES3File() : this(new ES3Settings(), true) { } + + /// Creates a new ES3File and loads the specified file into the ES3File if there is data to load. + /// The relative or absolute path of the file in storage our ES3File is associated with. + public ES3File(string filePath) : this(new ES3Settings(filePath), true) { } + + /// Creates a new ES3File and loads the specified file into the ES3File if there is data to load. + /// The relative or absolute path of the file in storage our ES3File is associated with. + /// The settings we want to use to override the default settings. + public ES3File(string filePath, ES3Settings settings) : this(new ES3Settings(filePath, settings), true) { } + + /// Creates a new ES3File and loads the specified file into the ES3File if there is data to load. + /// The settings we want to use to override the default settings. + public ES3File(ES3Settings settings) : this(settings, true) { } + + /// Creates a new ES3File and only loads the default file into it if syncWithFile is set to true. + /// Whether we should sync this ES3File with the one in storage immediately after creating it. + public ES3File(bool syncWithFile) : this(new ES3Settings(), syncWithFile) { } + /// Creates a new ES3File and only loads the specified file into it if syncWithFile is set to true. + /// The relative or absolute path of the file in storage our ES3File is associated with. + /// Whether we should sync this ES3File with the one in storage immediately after creating it. + public ES3File(string filePath, bool syncWithFile) : this(new ES3Settings(filePath), syncWithFile) { } + /// Creates a new ES3File and only loads the specified file into it if syncWithFile is set to true. + /// The relative or absolute path of the file in storage our ES3File is associated with. + /// The settings we want to use to override the default settings. + /// Whether we should sync this ES3File with the one in storage immediately after creating it. + public ES3File(string filePath, ES3Settings settings, bool syncWithFile) : this(new ES3Settings(filePath, settings), syncWithFile) { } + + /// Creates a new ES3File and loads the specified file into the ES3File if there is data to load. + /// The settings we want to use to override the default settings. + /// Whether we should sync this ES3File with the one in storage immediately after creating it. + public ES3File(ES3Settings settings, bool syncWithFile) + { + this.settings = settings; + this.syncWithFile = syncWithFile; + if (syncWithFile) + { + // Type checking must be enabled when syncing. + var settingsWithTypeChecking = (ES3Settings)settings.Clone(); + settingsWithTypeChecking.typeChecking = true; + + using (var reader = ES3Reader.Create(settingsWithTypeChecking)) + { + if (reader == null) + return; + foreach (KeyValuePair kvp in reader.RawEnumerator) + cache[kvp.Key] = kvp.Value; + } + + timestamp = ES3.GetTimestamp(settingsWithTypeChecking); + } + } + + /// Creates a new ES3File and loads the bytes into the ES3File. Note the bytes must represent that of a file. + /// The bytes representing our file. + /// The settings we want to use to override the default settings. + /// Whether we should sync this ES3File with the one in storage immediately after creating it. + public ES3File(byte[] bytes, ES3Settings settings = null) + { + if (settings == null) + this.settings = new ES3Settings(); + else + this.settings = settings; + + syncWithFile = true; // This ensures that the file won't be merged, which would prevent deleted keys from being deleted. + + SaveRaw(bytes, settings); + } + + /// Synchronises this ES3File with a file in storage. + public void Sync() + { + Sync(this.settings); + } + + /// Synchronises this ES3File with a file in storage. + /// The relative or absolute path of the file in storage we want to synchronise with. + /// The settings we want to use to override the default settings. + public void Sync(string filePath, ES3Settings settings = null) + { + Sync(new ES3Settings(filePath, settings)); + } + + /// Synchronises this ES3File with a file in storage. + /// The settings we want to use to override the default settings. + public void Sync(ES3Settings settings = null) + { + if (settings == null) + settings = new ES3Settings(); + + if (cache.Count == 0) + { + ES3.DeleteFile(settings); + return; + } + + using (var baseWriter = ES3Writer.Create(settings, true, !syncWithFile, false)) + { + foreach (var kvp in cache) + { + // If we change the name of a type, the type may be null. + // In this case, use System.Object as the type. + Type type; + if (kvp.Value.type == null) + type = typeof(System.Object); + else + type = kvp.Value.type.type; + baseWriter.Write(kvp.Key, type, kvp.Value.bytes); + } + baseWriter.Save(!syncWithFile); + } + } + + /// Removes the data stored in this ES3File. The ES3File will be empty after calling this method. + public void Clear() + { + cache.Clear(); + } + + /// Returns an array of all of the key names in this ES3File. + public string[] GetKeys() + { + var keyCollection = cache.Keys; + var keys = new string[keyCollection.Count]; + keyCollection.CopyTo(keys, 0); + return keys; + } + + #region Save Methods + + /// Saves a value to a key in this ES3File. + /// The key we want to use to identify our value in the file. + /// The value we want to save. + public void Save(string key, T value) + { + var unencryptedSettings = (ES3Settings)settings.Clone(); + unencryptedSettings.encryptionType = ES3.EncryptionType.None; + unencryptedSettings.compressionType = ES3.CompressionType.None; + + // If T is object, use the value to get it's type. Otherwise, use T so that it works with inheritence. + Type type; + if (value == null) + type = typeof(T); + else + type = value.GetType(); + + ES3Type es3Type = ES3TypeMgr.GetOrCreateES3Type(type); + + cache[key] = new ES3Data(es3Type, ES3.Serialize(value, es3Type, unencryptedSettings)); + } + + /// Merges the data specified by the bytes parameter into this ES3File. + /// The bytes we want to merge with this ES3File. + /// The settings we want to use to override the default settings. + public void SaveRaw(byte[] bytes, ES3Settings settings = null) + { + if (settings == null) + settings = new ES3Settings(); + + // Type checking must be enabled when syncing. + var settingsWithTypeChecking = (ES3Settings)settings.Clone(); + settingsWithTypeChecking.typeChecking = true; + + using (var reader = ES3Reader.Create(bytes, settingsWithTypeChecking)) + { + if (reader == null) + return; + foreach (KeyValuePair kvp in reader.RawEnumerator) + cache[kvp.Key] = kvp.Value; + } + } + + /// Merges the data specified by the bytes parameter into this ES3File. + /// The bytes we want to merge with this ES3File. + /// The settings we want to use to override the default settings. + public void AppendRaw(byte[] bytes, ES3Settings settings = null) + { + if (settings == null) + settings = new ES3Settings(); + // AppendRaw just does the same thing as SaveRaw in ES3File. + SaveRaw(bytes, settings); + } + + #endregion + + #region Load Methods + + /* Standard load methods */ + + /// Loads the value from this ES3File with the given key. + /// The key which identifies the value we want to load. + public object Load(string key) + { + return Load(key); + } + + /// Loads the value from this ES3File with the given key. + /// The key which identifies the value we want to load. + /// The value we want to return if the key does not exist in this ES3File. + public object Load(string key, object defaultValue) + { + return Load(key, defaultValue); + } + + /// Loads the value from this ES3File with the given key. + /// The key which identifies the value we want to load. + public T Load(string key) + { + ES3Data es3Data; + + if (!cache.TryGetValue(key, out es3Data)) + throw new KeyNotFoundException("Key \"" + key + "\" was not found in this ES3File. Use Load(key, defaultValue) if you want to return a default value if the key does not exist."); + + var unencryptedSettings = (ES3Settings)this.settings.Clone(); + unencryptedSettings.encryptionType = ES3.EncryptionType.None; + unencryptedSettings.compressionType = ES3.CompressionType.None; + + // If we're loading a derived type using it's parent type, ensure that we use the ES3Type from the ES3Data. + if (typeof(T) != es3Data.type.type && ES3Reflection.IsAssignableFrom(typeof(T), es3Data.type.type)) + return (T)ES3.Deserialize(es3Data.type, es3Data.bytes, unencryptedSettings); + return ES3.Deserialize(es3Data.bytes, unencryptedSettings); + } + + /// Loads the value from this ES3File with the given key. + /// The key which identifies the value we want to load. + /// The value we want to return if the key does not exist in this ES3File. + public T Load(string key, T defaultValue) + { + ES3Data es3Data; + + if (!cache.TryGetValue(key, out es3Data)) + return defaultValue; + var unencryptedSettings = (ES3Settings)this.settings.Clone(); + unencryptedSettings.encryptionType = ES3.EncryptionType.None; + unencryptedSettings.compressionType = ES3.CompressionType.None; + + // If we're loading a derived type using it's parent type, ensure that we use the ES3Type from the ES3Data. + if (typeof(T) != es3Data.type.type && ES3Reflection.IsAssignableFrom(typeof(T), es3Data.type.type)) + return (T)ES3.Deserialize(es3Data.type, es3Data.bytes, unencryptedSettings); + return ES3.Deserialize(es3Data.bytes, unencryptedSettings); + } + + /// Loads the value from this ES3File with the given key into an existing object. + /// The key which identifies the value we want to load. + /// The object we want to load the value into. + public void LoadInto(string key, T obj) where T : class + { + ES3Data es3Data; + + if (!cache.TryGetValue(key, out es3Data)) + throw new KeyNotFoundException("Key \"" + key + "\" was not found in this ES3File. Use Load(key, defaultValue) if you want to return a default value if the key does not exist."); + + var unencryptedSettings = (ES3Settings)this.settings.Clone(); + unencryptedSettings.encryptionType = ES3.EncryptionType.None; + unencryptedSettings.compressionType = ES3.CompressionType.None; + + // If we're loading a derived type using it's parent type, ensure that we use the ES3Type from the ES3Data. + if (typeof(T) != es3Data.type.type && ES3Reflection.IsAssignableFrom(typeof(T), es3Data.type.type)) + ES3.DeserializeInto(es3Data.type, es3Data.bytes, obj, unencryptedSettings); + else + ES3.DeserializeInto(es3Data.bytes, obj, unencryptedSettings); + } + + #endregion + + #region Load Raw Methods + + /// Loads the ES3File as a raw, unencrypted, uncompressed byte array. + public byte[] LoadRawBytes() + { + var newSettings = (ES3Settings)settings.Clone(); + if (!newSettings.postprocessRawCachedData) + { + newSettings.encryptionType = ES3.EncryptionType.None; + newSettings.compressionType = ES3.CompressionType.None; + } + return GetBytes(newSettings); + } + + /// Loads the ES3File as a raw, unencrypted, uncompressed string, using the encoding defined in the ES3File's settings variable. + public string LoadRawString() + { + if (cache.Count == 0) + return ""; + return settings.encoding.GetString(LoadRawBytes()); + } + + /* + * Same as LoadRawString, except it will return an encrypted/compressed file if these are enabled. + */ + internal byte[] GetBytes(ES3Settings settings = null) + { + if (cache.Count == 0) + return new byte[0]; + + if (settings == null) + settings = this.settings; + + using (var ms = new System.IO.MemoryStream()) + { + var memorySettings = (ES3Settings)settings.Clone(); + memorySettings.location = ES3.Location.InternalMS; + // Ensure we return unencrypted bytes. + if (!memorySettings.postprocessRawCachedData) + { + memorySettings.encryptionType = ES3.EncryptionType.None; + memorySettings.compressionType = ES3.CompressionType.None; + } + + using (var baseWriter = ES3Writer.Create(ES3Stream.CreateStream(ms, memorySettings, ES3FileMode.Write), memorySettings, true, false)) + { + foreach (var kvp in cache) + baseWriter.Write(kvp.Key, kvp.Value.type.type, kvp.Value.bytes); + baseWriter.Save(false); + } + + return ms.ToArray(); + } + } + + #endregion + + #region Other ES3 Methods + + /// Deletes a key from this ES3File. + /// The key we want to delete. + public void DeleteKey(string key) + { + cache.Remove(key); + } + + /// Checks whether a key exists in this ES3File. + /// The key we want to check the existence of. + /// True if the key exists, otherwise False. + public bool KeyExists(string key) + { + return cache.ContainsKey(key); + } + + /// Gets the size of the cached data in bytes. + public int Size() + { + int size = 0; + foreach (var kvp in cache) + size += kvp.Value.bytes.Length; + return size; + } + + public Type GetKeyType(string key) + { + ES3Data es3data; + if (!cache.TryGetValue(key, out es3data)) + throw new KeyNotFoundException("Key \"" + key + "\" was not found in this ES3File. Use Load(key, defaultValue) if you want to return a default value if the key does not exist."); + + return es3data.type.type; + } + + #endregion + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal static ES3File GetOrCreateCachedFile(ES3Settings settings) + { + ES3File cachedFile; + if (!cachedFiles.TryGetValue(settings.path, out cachedFile)) + { + cachedFile = new ES3File(settings, false); + cachedFiles.Add(settings.path, cachedFile); + cachedFile.syncWithFile = true; // This ensures that the file won't be merged, which would prevent deleted keys from being deleted. + } + // Settings might refer to the same file, but might have changed. + // To account for this, we update the settings of the ES3File each time we access it. + cachedFile.settings = settings; + return cachedFile; + } + + internal static void CacheFile(ES3Settings settings) + { + // If we're still using cached settings, set it to the default location. + if (settings.location == ES3.Location.Cache) + { + settings = (ES3Settings)settings.Clone(); + // If the default settings are also set to cache, assume ES3.Location.File. Otherwise, set it to the default location. + settings.location = ES3Settings.defaultSettings.location == ES3.Location.Cache ? ES3.Location.File : ES3Settings.defaultSettings.location; + } + + if (!ES3.FileExists(settings)) + return; + + // Disable compression and encryption when loading the raw bytes, and the ES3File constructor will expect encrypted/compressed bytes. + var loadSettings = (ES3Settings)settings.Clone(); + loadSettings.compressionType = ES3.CompressionType.None; + loadSettings.encryptionType = ES3.EncryptionType.None; + + cachedFiles[settings.path] = new ES3File(ES3.LoadRawBytes(loadSettings), settings); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal static void Store(ES3Settings settings = null) + { + if (settings == null) + settings = new ES3Settings(ES3.Location.File); + // If we're still using cached settings, set it to the default location. + else if (settings.location == ES3.Location.Cache) + { + settings = (ES3Settings)settings.Clone(); + // If the default settings are also set to cache, assume ES3.Location.File. Otherwise, set it to the default location. + settings.location = ES3Settings.defaultSettings.location == ES3.Location.Cache ? ES3.Location.File : ES3Settings.defaultSettings.location; + } + + ES3File cachedFile; + if (!cachedFiles.TryGetValue(settings.path, out cachedFile)) + throw new FileNotFoundException("The file '" + settings.path + "' could not be stored because it could not be found in the cache."); + cachedFile.Sync(settings); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal static void RemoveCachedFile(ES3Settings settings) + { + cachedFiles.Remove(settings.path); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal static void CopyCachedFile(ES3Settings oldSettings, ES3Settings newSettings) + { + ES3File cachedFile; + if (!cachedFiles.TryGetValue(oldSettings.path, out cachedFile)) + throw new FileNotFoundException("The file '" + oldSettings.path + "' could not be copied because it could not be found in the cache."); + if (cachedFiles.ContainsKey(newSettings.path)) + throw new InvalidOperationException("Cannot copy file '" + oldSettings.path + "' to '" + newSettings.path + "' because '" + newSettings.path + "' already exists"); + + cachedFiles.Add(newSettings.path, (ES3File)cachedFile.MemberwiseClone()); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal static void DeleteKey(string key, ES3Settings settings) + { + ES3File cachedFile; + if (cachedFiles.TryGetValue(settings.path, out cachedFile)) + cachedFile.DeleteKey(key); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal static bool KeyExists(string key, ES3Settings settings) + { + ES3File cachedFile; + if (cachedFiles.TryGetValue(settings.path, out cachedFile)) + return cachedFile.KeyExists(key); + return false; + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal static bool FileExists(ES3Settings settings) + { + return cachedFiles.ContainsKey(settings.path); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal static string[] GetKeys(ES3Settings settings) + { + ES3File cachedFile; + if (!cachedFiles.TryGetValue(settings.path, out cachedFile)) + throw new FileNotFoundException("Could not get keys from the file '" + settings.path + "' because it could not be found in the cache."); + return cachedFile.cache.Keys.ToArray(); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal static string[] GetFiles() + { + return cachedFiles.Keys.ToArray(); + } + + internal static DateTime GetTimestamp(ES3Settings settings) + { + ES3File cachedFile; + if (!cachedFiles.TryGetValue(settings.path, out cachedFile)) + return new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); + return cachedFile.timestamp; + } +} + +namespace ES3Internal +{ + public struct ES3Data + { + public ES3Type type; + public byte[] bytes; + + public ES3Data(Type type, byte[] bytes) + { + this.type = type == null ? null : ES3TypeMgr.GetOrCreateES3Type(type); + this.bytes = bytes; + } + + public ES3Data(ES3Type type, byte[] bytes) + { + this.type = type; + this.bytes = bytes; + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3File.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3File.cs.meta new file mode 100644 index 0000000..43f99ff --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3File.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2cd9723dc51904030be3c30362442d47 +timeCreated: 1499764821 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3GameObject.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3GameObject.cs new file mode 100644 index 0000000..f340c7f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3GameObject.cs @@ -0,0 +1,20 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +[ExecuteInEditMode] +public class ES3GameObject : MonoBehaviour +{ + public List components = new List(); + + /* Ensures that this Component is always last in the List to guarantee that it's loaded after any Components it references */ + private void Update() + { + if (Application.isPlaying) + return; + +#if UNITY_EDITOR + UnityEditorInternal.ComponentUtility.MoveComponentDown(this); +#endif + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3GameObject.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3GameObject.cs.meta new file mode 100644 index 0000000..25a8d9b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3GameObject.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7e2cacabe81aea8468e08e911727ee97 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3IO.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3IO.cs new file mode 100644 index 0000000..de5ced3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3IO.cs @@ -0,0 +1,181 @@ +using System.IO; +using System; +using UnityEngine; + +namespace ES3Internal +{ + public static class ES3IO + { +#if UNITY_SWITCH + internal static readonly string persistentDataPath = ""; + internal static readonly string dataPath = ""; +#else + internal static readonly string persistentDataPath = Application.persistentDataPath; + internal static readonly string dataPath = Application.dataPath; +#endif + + internal const string backupFileSuffix = ".bac"; + internal const string temporaryFileSuffix = ".tmp"; + + public enum ES3FileMode { Read, Write, Append } + + public static DateTime GetTimestamp(string filePath) + { + if (!FileExists(filePath)) + return new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); + return File.GetLastWriteTime(filePath).ToUniversalTime(); + } + + public static string GetExtension(string path) + { + return Path.GetExtension(path); + } + + public static void DeleteFile(string filePath) + { + if (FileExists(filePath)) + File.Delete(filePath); + } + + public static bool FileExists(string filePath) { return File.Exists(filePath); } + public static void MoveFile(string sourcePath, string destPath) { File.Move(sourcePath, destPath); } + public static void CopyFile(string sourcePath, string destPath) { File.Copy(sourcePath, destPath); } + + public static void MoveDirectory(string sourcePath, string destPath) { Directory.Move(sourcePath, destPath); } + public static void CreateDirectory(string directoryPath) { Directory.CreateDirectory(directoryPath); } + public static bool DirectoryExists(string directoryPath) { return Directory.Exists(directoryPath); } + + /* + * Given a path, it returns the directory that path points to. + * eg. "C:/myFolder/thisFolder/myFile.txt" will return "C:/myFolder/thisFolder". + */ + public static string GetDirectoryPath(string path, char seperator = '/') + { + //return Path.GetDirectoryName(path); + // Path.GetDirectoryName turns forward slashes to backslashes in some cases on Windows, which is why + // Substring is used instead. + char slashChar = UsesForwardSlash(path) ? '/' : '\\'; + + int slash = path.LastIndexOf(slashChar); + + // If this path ends in a slash it is assumed to already be a path to a Directory. + if (slash == path.Length - 1) + return path; + + // Ignore trailing slash if necessary. + if (slash == (path.Length - 1)) + slash = path.Substring(0, slash).LastIndexOf(slashChar); + if (slash == -1) + ES3Debug.LogError("Path provided is not a directory path as it contains no slashes."); + return path.Substring(0, slash); + } + + public static bool UsesForwardSlash(string path) + { + if (path.Contains("/")) + return true; + return false; + } + + // Takes a directory path and a file or directory name and combines them into a single path. + public static string CombinePathAndFilename(string directoryPath, string fileOrDirectoryName) + { + if (directoryPath[directoryPath.Length - 1] != '/' && directoryPath[directoryPath.Length - 1] != '\\') + directoryPath += '/'; + return directoryPath + fileOrDirectoryName; + } + + public static string[] GetDirectories(string path, bool getFullPaths = true) + { + var paths = Directory.GetDirectories(path); + for (int i = 0; i < paths.Length; i++) + { + if (!getFullPaths) + paths[i] = Path.GetFileName(paths[i]); + // GetDirectories sometimes returns backslashes, so we need to convert them to + // forward slashes. + paths[i].Replace("\\", "/"); + } + return paths; + } + + public static void DeleteDirectory(string directoryPath) + { + if (DirectoryExists(directoryPath)) + Directory.Delete(directoryPath, true); + } + + // Note: Paths not ending in a slash are assumed to be a path to a file. + // In this case the Directory containing the file will be searched. + public static string[] GetFiles(string path, bool getFullPaths = true) + { + // If this is pointing to a filename, get the path to it's directory. + var directoryPath = path.EndsWith("/") || path.EndsWith("\\") ? path : GetDirectoryPath(path); + + var paths = Directory.GetFiles(directoryPath); + if (!getFullPaths) + { + for (int i = 0; i < paths.Length; i++) + paths[i] = Path.GetFileName(paths[i]); + } + return paths; + } + + public static byte[] ReadAllBytes(string path) + { + return File.ReadAllBytes(path); + } + + public static void WriteAllBytes(string path, byte[] bytes) + { + File.WriteAllBytes(path, bytes); + } + + public static void CommitBackup(ES3Settings settings) + { + ES3Debug.Log("Committing backup for " + settings.path + " to storage location " + settings.location); + + var temporaryFilePath = settings.FullPath + temporaryFileSuffix; + + if (settings.location == ES3.Location.File) + { + var oldFileBackup = settings.FullPath + temporaryFileSuffix + ".bak"; + + // If there's existing save data to overwrite ... + if (FileExists(settings.FullPath)) + { + // Delete any old backups. + DeleteFile(oldFileBackup); + // Rename the old file so we can restore it if it fails. + CopyFile(settings.FullPath, oldFileBackup); + + try + { + // Delete the old file so that we can move it. + DeleteFile(settings.FullPath); + // Now rename the temporary file to the name of the save file. + MoveFile(temporaryFilePath, settings.FullPath); + } + catch (Exception e) + { + // If any exceptions occur, restore the original save file. + try { DeleteFile(settings.FullPath); } catch { } + MoveFile(oldFileBackup, settings.FullPath); + throw e; + } + + DeleteFile(oldFileBackup); + } + // Else just rename the temporary file to the main file. + else + MoveFile(temporaryFilePath, settings.FullPath); + } + else if (settings.location == ES3.Location.PlayerPrefs) + { + PlayerPrefs.SetString(settings.FullPath, PlayerPrefs.GetString(temporaryFilePath)); + PlayerPrefs.DeleteKey(temporaryFilePath); + PlayerPrefs.Save(); + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3IO.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3IO.cs.meta new file mode 100644 index 0000000..2d3c49c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3IO.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0e3e89d69f37e4fa9b4d60467722ac73 +timeCreated: 1499764821 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3InspectorInfo.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3InspectorInfo.cs new file mode 100644 index 0000000..61a94ae --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3InspectorInfo.cs @@ -0,0 +1,19 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +/* + * Displays an info message in the inspector. + * Only available in the Editor. + */ +public class ES3InspectorInfo : MonoBehaviour +{ + #if UNITY_EDITOR + public string message = ""; + + public void SetMessage(string message) + { + this.message = message; + } + #endif +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3InspectorInfo.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3InspectorInfo.cs.meta new file mode 100644 index 0000000..c48e539 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3InspectorInfo.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8714d999c5ae749538494c1347e5a3ca +timeCreated: 1519132290 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Prefab.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Prefab.cs new file mode 100644 index 0000000..9d56395 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Prefab.cs @@ -0,0 +1,218 @@ +using System.Collections.Generic; +using UnityEngine; +using ES3Internal; +#if UNITY_EDITOR +using UnityEditor; +#endif + + +namespace ES3Internal +{ + public class ES3Prefab : MonoBehaviour + { + public long prefabId = GetNewRefID(); + /* + * We need to store references to all dependencies of the prefab because only supported scripts will be serialised. + * This means that although supported scripts have their dependencies added to the reference manager when we load the prefab, + * there will not be any dependencies in the reference manager for scripts which are not supported. So it will not be possible to save any reference to these. + */ + public ES3RefIdDictionary localRefs = new ES3RefIdDictionary(); + + public void Awake() + { + // Add the references to the reference list when this prefab is instantiated. + var mgr = ES3ReferenceMgrBase.Current; + + if (mgr == null) + return; + + foreach (var kvp in localRefs) + if (kvp.Key != null) + mgr.Add(kvp.Key); + } + + public long Get(UnityEngine.Object obj) + { + long id; + if (localRefs.TryGetValue(obj, out id)) + return id; + return -1; + } + + public long Add(UnityEngine.Object obj) + { + long id; + if (localRefs.TryGetValue(obj, out id)) + return id; + + if (!ES3ReferenceMgr.CanBeSaved(obj)) + return -1; + id = GetNewRefID(); + localRefs.Add(obj, id); + return id; + } + + public Dictionary GetReferences() + { + var localToGlobal = new Dictionary(); + + var refMgr = ES3ReferenceMgr.Current; + + if (refMgr == null) + return localToGlobal; + + foreach (var kvp in localRefs) + { + long id = refMgr.Add(kvp.Key); + localToGlobal[kvp.Value.ToString()] = id.ToString(); + } + return localToGlobal; + } + + public void ApplyReferences(Dictionary localToGlobal) + { + if (ES3ReferenceMgrBase.Current == null) + return; + + foreach (var localRef in localRefs) + { + long globalId; + if (localToGlobal.TryGetValue(localRef.Value, out globalId)) + ES3ReferenceMgrBase.Current.Add(localRef.Key, globalId); + } + } + + public static long GetNewRefID() + { + return ES3ReferenceMgrBase.GetNewRefID(); + } +#if UNITY_EDITOR + public void GeneratePrefabReferences() + { +#if UNITY_2021_3_OR_NEWER + if (this.gameObject.scene.name != null || UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage() != null) +#elif UNITY_2018_3_OR_NEWER + if (this.gameObject.scene.name != null || UnityEditor.Experimental.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage() != null) +#else + if (this.gameObject.scene.name != null) +#endif + return; + + // Create a new reference list so that any objects which are no longer dependencies are removed. + var tempLocalRefs = new ES3RefIdDictionary(); + + // Get dependencies of children also. + var transforms = GetComponentsInChildren(); + var gos = new GameObject[transforms.Length]; + for (int i = 0; i < transforms.Length; i++) + gos[i] = transforms[i].gameObject; + + bool addedNewReference = false; + + // Add the GameObject's dependencies to the reference list. + foreach (var obj in EditorUtility.CollectDependencies(gos)) + { + var dependency = (UnityEngine.Object)obj; + if (obj == null || !ES3ReferenceMgr.CanBeSaved(dependency)) + continue; + + var id = Get(dependency); + // If we're adding a new reference, do an Undo.RecordObject to ensure it persists. + if (id == -1) + { + addedNewReference = true; + Undo.RecordObject(this, "Update Easy Save 3 Prefab"); + EditorUtility.SetDirty(this); + } + tempLocalRefs.Add(dependency, id == -1 ? GetNewRefID() : id); + } + + if (addedNewReference || tempLocalRefs.Count != localRefs.Count) + localRefs = tempLocalRefs; + } +#endif + } +} + +/* + * Create a blank ES3Type for ES3Prefab as it does not require serialising/deserialising when stored as a Component. + */ +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_ES3Prefab : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_ES3Prefab() : base(typeof(ES3Prefab)) { Instance = this; } + + public override void Write(object obj, ES3Writer writer) + { + } + + public override object Read(ES3Reader reader) + { + return null; + } + } + + /* + * Use this ES3Type to serialise the . + */ + public class ES3Type_ES3PrefabInternal : ES3Type + { + public static ES3Type Instance = new ES3Type_ES3PrefabInternal(); + + public ES3Type_ES3PrefabInternal() : base(typeof(ES3Type_ES3PrefabInternal)) { Instance = this; } + + public override void Write(object obj, ES3Writer writer) + { + ES3Prefab es3Prefab = (ES3Prefab)obj; + + writer.WriteProperty("prefabId", es3Prefab.prefabId.ToString(), ES3Type_string.Instance); + writer.WriteProperty("refs", es3Prefab.GetReferences()); + } + + public override object Read(ES3Reader reader) + { + var prefabId = reader.ReadRefProperty(); + + if (ES3ReferenceMgrBase.Current == null) + return null; + + var es3Prefab = ES3ReferenceMgrBase.Current.GetPrefab(prefabId); + if (es3Prefab == null) + throw new MissingReferenceException("Prefab with ID " + prefabId + " could not be found.\nPress the 'Refresh References' button on the ES3ReferenceMgr Component of the Easy Save 3 Manager in the scene to refresh prefabs."); + + +#if UNITY_EDITOR + // Use PrefabUtility.InstantiatePrefab if we're saving in the Editor and the application isn't playing. + // This keeps the connection to the prefab, which is useful for Editor scripts saving data outside of runtime. + var instance = Application.isPlaying ? GameObject.Instantiate(es3Prefab.gameObject) : PrefabUtility.InstantiatePrefab(es3Prefab.gameObject); +#else + var instance = GameObject.Instantiate(es3Prefab.gameObject); +#endif + var instanceES3Prefab = ((GameObject)instance).GetComponent(); + if (instanceES3Prefab == null) + throw new MissingReferenceException("Prefab with ID " + prefabId + " was found, but it does not have an ES3Prefab component attached."); + + ReadInto(reader, instance); + + return instanceES3Prefab.gameObject; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + // Load as ES3Refs and convert to longs. + var localToGlobal_refs = reader.ReadProperty>(ES3Type_ES3RefDictionary.Instance); + var localToGlobal = new Dictionary(); + foreach (var kvp in localToGlobal_refs) + localToGlobal.Add(kvp.Key.id, kvp.Value.id); + + if (ES3ReferenceMgrBase.Current == null) + return; + + ((GameObject)obj).GetComponent().ApplyReferences(localToGlobal); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Prefab.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Prefab.cs.meta new file mode 100644 index 0000000..4c771c9 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Prefab.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: baff8732cd3074ef88b34f9cc487846d +timeCreated: 1519132295 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgr.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgr.cs new file mode 100644 index 0000000..ed65428 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgr.cs @@ -0,0 +1,262 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using ES3Internal; +using UnityEngine.SceneManagement; +#if UNITY_EDITOR +using UnityEditor; +using UnityEditor.SceneManagement; +using System.Reflection; +using System; +using System.Linq; +using UnityEngine.U2D; +#endif + +#if UNITY_VISUAL_SCRIPTING +using Unity.VisualScripting; +[IncludeInSettings(true)] +#endif +public class ES3ReferenceMgr : ES3ReferenceMgrBase +{ +#if UNITY_EDITOR + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void RefreshDependencies(bool isEnteringPlayMode = false) + { + // Empty the refId so it has to be refreshed. + refId = null; + + ES3ReferenceMgrBase.isEnteringPlayMode = isEnteringPlayMode; + + // This will get the dependencies for all GameObjects and Components from the active scene. + AddDependencies(this.gameObject.scene.GetRootGameObjects()); + AddDependenciesFromFolders(); + AddPrefabsToManager(); + RemoveNullOrInvalidValues(); + + ES3ReferenceMgrBase.isEnteringPlayMode = false; + } + + [MenuItem("Tools/Easy Save 3/Refresh References for All Scenes", false, 150)] + static void RefreshDependenciesInAllScenes() + { + if (!EditorUtility.DisplayDialog("Refresh references in all scenes", "This will open each scene which is enabled in your Build Settings, refresh each reference manager, and save the scene.\n\nWe recommend making a backup of your project before doing this for the first time.", "Ok", "Cancel", DialogOptOutDecisionType.ForThisMachine, "ES3RefreshAllOptOut")) + return; + + // Get a list of loaded scenes so we know whether we need to close them after refreshing references or not. + var loadedScenePaths = new string[SceneManager.sceneCount]; + for (int i = 0; i < SceneManager.sceneCount; i++) + loadedScenePaths[i] = SceneManager.GetSceneAt(i).path; + + var scenes = EditorBuildSettings.scenes; + var sceneNameList = ""; // We use this so we can display a list of scenes at the end. + + for (int i = 0; i < scenes.Length; i++) + { + var buildSettingsScene = scenes[i]; + + if (!buildSettingsScene.enabled) + continue; + + if (EditorUtility.DisplayCancelableProgressBar("Refreshing references", $"Refreshing references for scene {buildSettingsScene.path}.", i / scenes.Length)) + return; + + var sceneWasOpen = loadedScenePaths.Contains(buildSettingsScene.path); + var scene = EditorSceneManager.OpenScene(buildSettingsScene.path, OpenSceneMode.Additive); + + var mgr = ES3ReferenceMgr.GetManagerFromScene(scene, false); + + if (mgr != null) + { + try + { + ((ES3ReferenceMgr)mgr).RefreshDependencies(); + } + catch(Exception e) + { + ES3Debug.LogError($"Couldn't update references for scene {scene.name} as the following exception occurred:\n\n" + e); + } + } + + sceneNameList += $"{scene.name}\n"; + + // If the scene wasn't originally open, save it and close it. + if (!sceneWasOpen) + { + // Temporarily disable refreshing on save so that it doesn't refresh again. + var updateReferencesOnSave = ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneIsSaved; + ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneIsSaved = false; + + EditorSceneManager.SaveScene(scene); + EditorSceneManager.CloseScene(scene, true); + + ES3Settings.defaultSettingsScriptableObject.updateReferencesWhenSceneIsSaved = updateReferencesOnSave; + } + } + EditorUtility.ClearProgressBar(); + + EditorUtility.DisplayDialog("References refreshed", $"Refrences updated for scenes:\n\n{sceneNameList}", "Ok", DialogOptOutDecisionType.ForThisMachine, "ES3RefreshAllCompleteOptOut"); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void Optimize() + { + var dependencies = EditorUtility.CollectDependencies(this.gameObject.scene.GetRootGameObjects().Where(go => go != this.gameObject).ToArray()); + var notDependenciesOfScene = new HashSet(); + + foreach (var kvp in idRef) + if (!dependencies.Contains(kvp.Value)) + notDependenciesOfScene.Add(kvp.Value); + + foreach (var obj in notDependenciesOfScene) + Remove(obj); + } + + /* Adds all dependencies from this scene to the manager */ + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void AddDependencies() + { + var rootGameObjects = gameObject.scene.GetRootGameObjects(); + + for (int j = 0; j < rootGameObjects.Length; j++) + { + var go = rootGameObjects[j]; + + if (EditorUtility.DisplayCancelableProgressBar("Gathering references", "Populating reference manager with your scene dependencies so they can be saved and loaded by reference.", j / rootGameObjects.Length)) + return; + + AddDependencies(go); + } + + EditorUtility.ClearProgressBar(); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void AddDependencies(UnityEngine.Object[] objs) + { + var timeStarted = EditorApplication.timeSinceStartup; + var timeout = ES3Settings.defaultSettingsScriptableObject.collectDependenciesTimeout; + + foreach (var obj in objs) + { + if (obj == null || obj.name == "Easy Save 3 Manager") + continue; + + var excludeTextures = new List(); + + foreach (var dependency in EditorUtility.CollectDependencies(new UnityEngine.Object[] { obj })) + { + if (EditorApplication.timeSinceStartup - timeStarted > timeout) + { + ES3Debug.LogWarning($"Easy Save cancelled gathering of references for object {obj.name} because it took longer than {timeout} seconds. You can increase the timeout length in Tools > Easy Save 3 > Settings > Reference Gathering Timeout, or adjust the settings so that fewer objects are referenced in your scene."); + return; + } + + // Exclude all Texture2Ds which are packed into a SpriteAtlas from this manager. + if (dependency is SpriteAtlas) + foreach (var atlasDependency in EditorUtility.CollectDependencies(new UnityEngine.Object[] { dependency })) + if (atlasDependency is Texture2D) + ExcludeObject(atlasDependency); + + Add(dependency); + + if (obj is ES3Prefab prefab) + AddPrefabToManager(prefab); + } + } + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void AddDependenciesFromFolders() + { + var folders = ES3Settings.defaultSettingsScriptableObject.referenceFolders; + + // Remove null or empty values. + ArrayUtility.Remove(ref folders, ""); + ArrayUtility.Remove(ref folders, null); + + if (folders == null || folders.Length == 0) + return; + + var guids = AssetDatabase.FindAssets("t:Object", folders); + + foreach (var guid in guids) + { + var path = AssetDatabase.GUIDToAssetPath(guid); + var obj = AssetDatabase.LoadAssetAtPath(path); + + if(obj != null) + AddDependencies(obj); + } + } + + /*[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void AddDependenciesLegacy(UnityEngine.Object[] objs) + { + for (int i = 0; i < objs.Length; i++) + { + var obj = objs[i]; + + if (obj.name == "Easy Save 3 Manager") + continue; + + var dependencies = CollectDependenciesLegacy(obj); + + foreach (var dependency in dependencies) + { + if (dependency != null) + { + Add(dependency); + + // Add the prefab if it's referenced by this scene. + if (dependency.GetType() == typeof(ES3Prefab)) + AddPrefabToManager((ES3Prefab)dependency); + } + } + } + + Undo.RecordObject(this, "Update Easy Save 3 Reference List"); + }*/ + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void AddDependencies(UnityEngine.Object obj) + { + AddDependencies(new UnityEngine.Object[] { obj }); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void GeneratePrefabReferences() + { + AddPrefabsToManager(); + foreach (var es3Prefab in prefabs) + es3Prefab.GeneratePrefabReferences(); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void AddPrefabsToManager() + { + if (ES3Settings.defaultSettingsScriptableObject.addAllPrefabsToManager) + { + // Clear any null values. This isn't necessary if we're not adding all prefabs to manager as the list is cleared each time. + if (this.prefabs.RemoveAll(item => item == null) > 0) + Undo.RecordObject(this, "Update Easy Save 3 Reference List"); + + foreach (var es3Prefab in Resources.FindObjectsOfTypeAll()) + AddPrefabToManager(es3Prefab); + } + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + private void AddPrefabToManager(ES3Prefab es3Prefab) + { + try + { + if (es3Prefab != null && EditorUtility.IsPersistent(es3Prefab)) + if(AddPrefab(es3Prefab)) + Undo.RecordObject(this, "Update Easy Save 3 Reference List"); + es3Prefab.GeneratePrefabReferences(); + } + catch { } + } +#endif +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgr.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgr.cs.meta new file mode 100644 index 0000000..d1c37c6 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgr.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9a83408fcc9044c4fbc7e5d09a369ab6 +timeCreated: 1503395115 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgrBase.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgrBase.cs new file mode 100644 index 0000000..97263bb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgrBase.cs @@ -0,0 +1,758 @@ +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System; +using UnityEngine.SceneManagement; + +namespace ES3Internal +{ + [System.Serializable] + [DisallowMultipleComponent] + public abstract class ES3ReferenceMgrBase : MonoBehaviour + { + internal object _lock = new object(); + + public const string referencePropertyName = "_ES3Ref"; + private static ES3ReferenceMgrBase _current = null; + private static HashSet mgrs = new HashSet(); +#if UNITY_EDITOR + protected static bool isEnteringPlayMode = false; + static readonly HideFlags[] invalidHideFlags = new HideFlags[] { HideFlags.DontSave, HideFlags.DontSaveInBuild, HideFlags.DontSaveInEditor, HideFlags.HideAndDontSave }; +#endif + +#if !UNITY_EDITOR + [NonSerialized] +#endif + public List excludeObjects = new List(); + + private static System.Random rng; + + [HideInInspector] + public bool openPrefabs = false; // Whether the prefab list should be open in the Editor. + + public List prefabs = new List(); + + public static ES3ReferenceMgrBase Current + { + get + { + // If the reference manager hasn't been assigned, or we've got a reference to a manager in a different scene which isn't marked as DontDestroyOnLoad, look for this scene's manager. + if (_current == null /*|| (_current.gameObject.scene.buildIndex != -1 && _current.gameObject.scene != SceneManager.GetActiveScene())*/) + { + ES3ReferenceMgrBase mgr = GetManagerFromScene(SceneManager.GetActiveScene()); + if (mgr != null) + mgrs.Add(_current = mgr); + } + return _current; + } + } + + public static ES3ReferenceMgrBase GetManagerFromScene(Scene scene, bool getAnyManagerIfNotInScene = true) + { + // This has been removed as isLoaded is false during the initial Awake(). + /*if (!scene.isLoaded) + return null;*/ + + // If this is a valid scene, search it for the manager. + if (scene.IsValid()) + { + // Check whether the mgr is already in the mgr list. + foreach (var addedMgr in mgrs) + if (addedMgr != null && addedMgr.gameObject.scene == scene) + return addedMgr; + + GameObject[] roots; + try + { + roots = scene.GetRootGameObjects(); + } + catch + { + return null; + } + + // First, look for Easy Save 3 Manager in the top-level. + foreach (var root in roots) + { + if (root.name == "Easy Save 3 Manager") + { + var mgr = root.GetComponent(); + if(mgr != null) + return mgr; + } + } + + // If the user has moved or renamed the Easy Save 3 Manager, we need to perform a deep search. + foreach (var root in roots) + { + var mgr = root.GetComponentInChildren(); + if(mgr != null) + return mgr; + } + } + + // If we can't find a manager in this scene (for example we're in DontDestroyOnLoad), find a manager in any scene. + if (getAnyManagerIfNotInScene) + { + for (int i = 0; i < SceneManager.sceneCount; i++) + { + var loadedScene = SceneManager.GetSceneAt(i); + + if (loadedScene != null && loadedScene != scene && loadedScene.IsValid()) + { + var mgr = GetManagerFromScene(loadedScene, false); + if (mgr != null) + { + ES3Debug.LogWarning($"The reference you're trying to save does not exist in any scene, or the scene it belongs to does not contain an Easy Save 3 Manager. Using the reference manager from scene {loadedScene.name} instead. This may cause unexpected behaviour or leak memory in some situations. See the Saving and Loading References guide for more information."); + return mgr; + } + } + } + } + return null; + } + + public bool IsInitialised { get { return idRef.Count > 0; } } + + [SerializeField] + public ES3IdRefDictionary idRef = new ES3IdRefDictionary(); + private ES3RefIdDictionary _refId = null; + + public ES3RefIdDictionary refId + { + get + { + if (_refId == null) + { + _refId = new ES3RefIdDictionary(); + // Populate the reverse dictionary with the items from the normal dictionary. + foreach (var kvp in idRef) + if (kvp.Value != null) + _refId[kvp.Value] = kvp.Key; + } + return _refId; + } + set + { + _refId = value; + } + } + + public ES3GlobalReferences GlobalReferences + { + get + { + return ES3GlobalReferences.Instance; + } + } + + // Reset static variables to handle disabled domain reloading. + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] + private static void Init() + { + _current = null; + mgrs = new HashSet(); +#if UNITY_EDITOR + isEnteringPlayMode = false; +#endif + rng = null; + } + + internal void Awake() + { + if (_current != null && _current != this) + { + var existing = _current; + + /* We intentionally use Current rather than _current here, as _current may contain a reference to a manager in another scene, + * but Current only returns the Manager for the active scene. */ + if (Current != null) + { + RemoveNullValues(); + + //existing.Merge(this); + //Destroy(this); + _current = existing; // Undo the call to Current, which may have set it to NULL. + } + } + else + _current = this; + mgrs.Add(this); + } + + private void OnDestroy() + { + if (_current == this) + _current = null; + mgrs.Remove(this); + } + + // Merges two managers, not allowing any clashes of IDs + public void Merge(ES3ReferenceMgrBase otherMgr) + { + foreach (var kvp in otherMgr.idRef) + Add(kvp.Value, kvp.Key); + } + + public long Get(UnityEngine.Object obj) + { + if (!mgrs.Contains(this)) + mgrs.Add(this); + + foreach (var mgr in mgrs) + { + if (mgr == null) + continue; + + if (obj == null) + return -1; + + long id; + if (mgr.refId.TryGetValue(obj, out id)) + return id; + } + return -1; + } + + internal UnityEngine.Object Get(long id, Type type, bool suppressWarnings = false) + { + if (!mgrs.Contains(this)) + mgrs.Add(this); + + foreach (var mgr in mgrs) + { + if (mgr == null) + continue; + + if (id == -1) + return null; + + UnityEngine.Object obj; + if (mgr.idRef.TryGetValue(id, out obj)) + { + if (obj == null) // If obj has been marked as destroyed but not yet destroyed, don't return it. + return null; + return obj; + } + } + + if (GlobalReferences != null) + { + var globalRef = GlobalReferences.Get(id); + if (globalRef != null) + return globalRef; + } + + if (type != null) + ES3Debug.LogWarning("Reference for " + type + " with ID " + id + " could not be found in Easy Save's reference manager. See the Saving and Loading References guide for more information.", this); + else + ES3Debug.LogWarning("Reference with ID " + id + " could not be found in Easy Save's reference manager. See the Saving and Loading References guide for more information.", this); + + return null; + } + + public UnityEngine.Object Get(long id, bool suppressWarnings = false) + { + return Get(id, null, suppressWarnings); + } + + public ES3Prefab GetPrefab(long id, bool suppressWarnings = false) + { + if (!mgrs.Contains(this)) + mgrs.Add(this); + + foreach (var mgr in mgrs) + { + if (mgr == null) + continue; + + foreach (var prefab in mgr.prefabs) + if (prefab != null && prefab.prefabId == id) + return prefab; + } + if (!suppressWarnings) + ES3Debug.LogWarning("Prefab with ID " + id + " could not be found in Easy Save's reference manager. Try pressing the Refresh References button on the ES3ReferenceMgr Component of the Easy Save 3 Manager in your scene, or exit play mode and right-click the prefab and select Easy Save 3 > Add Reference(s) to Manager.", this); + return null; + } + + public long GetPrefab(ES3Prefab prefabToFind, bool suppressWarnings = false) + { + if (!mgrs.Contains(this)) + mgrs.Add(this); + + foreach (var mgr in mgrs) + { + if (mgr == null) + continue; + + foreach (var prefab in prefabs) + if (prefab == prefabToFind) + return prefab.prefabId; + } + if (!suppressWarnings) + ES3Debug.LogWarning("Prefab with name " + prefabToFind.name + " could not be found in Easy Save's reference manager. Try pressing the Refresh References button on the ES3ReferenceMgr Component of the Easy Save 3 Manager in your scene, or exit play mode and right-click the prefab and select Easy Save 3 > Add Reference(s) to Manager.", prefabToFind); + return -1; + } + + public long Add(UnityEngine.Object obj) + { + if (obj == null) + return -1; + + if (!CanBeSaved(obj)) + return -1; + + long id; + // If it already exists in the list, do nothing. + if (refId.TryGetValue(obj, out id)) + return id; + + if (GlobalReferences != null) + { + id = GlobalReferences.GetOrAdd(obj); + if (id != -1) + { + Add(obj, id); + return id; + } + } + + lock (_lock) + { + // Add the reference to the Dictionary. + id = GetNewRefID(); + return Add(obj, id); + } + } + + public long Add(UnityEngine.Object obj, long id) + { + if (obj == null) + return -1; + + if (!CanBeSaved(obj)) + return -1; + + // If the ID is -1, auto-generate an ID. + if (id == -1) + id = GetNewRefID(); + // Add the reference to the Dictionary. + lock (_lock) + { + idRef[id] = obj; + if (obj != null) + refId[obj] = id; + } + return id; + } + + public bool AddPrefab(ES3Prefab prefab) + { + if (!prefabs.Contains(prefab)) + { + prefabs.Add(prefab); + return true; + } + return false; + } + + public void Remove(UnityEngine.Object obj) + { + if (!mgrs.Contains(this)) + mgrs.Add(this); + + foreach (var mgr in mgrs) + { + if (mgr == null) + continue; + + // Only remove from this manager if we're in the Editor. + if (!Application.isPlaying && mgr != this) + continue; + + lock (mgr._lock) + { + mgr.refId.Remove(obj); + // There may be multiple references with the same ID, so remove them all. + foreach (var item in mgr.idRef.Where(kvp => kvp.Value == obj).ToList()) + mgr.idRef.Remove(item.Key); + } + } + } + + public void Remove(long referenceID) + { + foreach (var mgr in mgrs) + { + if (mgr == null) + continue; + + lock (mgr._lock) + { + mgr.idRef.Remove(referenceID); + // There may be multiple references with the same ID, so remove them all. + foreach (var item in mgr.refId.Where(kvp => kvp.Value == referenceID).ToList()) + mgr.refId.Remove(item.Key); + } + } + } + + public void RemoveNullValues() + { + var nullKeys = idRef.Where(pair => pair.Value == null).Select(pair => pair.Key).ToList(); + foreach (var key in nullKeys) + idRef.Remove(key); + } + + public void RemoveNullOrInvalidValues() + { + var nullKeys = idRef.Where(pair => pair.Value == null || !CanBeSaved(pair.Value) || excludeObjects.Contains(pair.Value)).Select(pair => pair.Key).ToList(); + foreach (var key in nullKeys) + idRef.Remove(key); + + if (GlobalReferences != null) + GlobalReferences.RemoveInvalidKeys(); + } + + public void Clear() + { + lock (_lock) + { + refId.Clear(); + idRef.Clear(); + } + } + + public bool Contains(UnityEngine.Object obj) + { + return refId.ContainsKey(obj); + } + + public bool Contains(long referenceID) + { + return idRef.ContainsKey(referenceID); + } + + public void ChangeId(long oldId, long newId) + { + idRef.ChangeKey(oldId, newId); + // Empty the refId so it has to be refreshed. + refId = null; + } + + internal static long GetNewRefID() + { + if (rng == null) + rng = new System.Random(); + + byte[] buf = new byte[8]; + rng.NextBytes(buf); + long longRand = BitConverter.ToInt64(buf, 0); + + return (System.Math.Abs(longRand % (long.MaxValue - 0)) + 0); + } + + /*#if UNITY_EDITOR + public static HashSet CollectDependenciesLegacy(UnityEngine.Object obj, HashSet dependencies = null, int depth = int.MinValue) + { + return CollectDependenciesLegacy(new UnityEngine.Object[] { obj }, dependencies, depth); + } + + + //Collects all top-level dependencies of an object. + //For GameObjects, it will traverse all children. + //For Components or ScriptableObjects, it will get all serialisable UnityEngine.Object fields/properties as dependencies. + public static HashSet CollectDependenciesLegacy(UnityEngine.Object[] objs, HashSet dependencies = null, int depth = int.MinValue) + { + if (depth == int.MinValue) + depth = ES3Settings.defaultSettingsScriptableObject.collectDependenciesDepth; + + if (depth < 0) + return dependencies; + + if (dependencies == null) + dependencies = new HashSet(); + + foreach (var obj in objs) + { + if (obj == null) + continue; + + var type = obj.GetType(); + + // Skip types which don't need processing + if (type == typeof(ES3ReferenceMgr) || type == typeof(ES3AutoSaveMgr) || type == typeof(ES3AutoSave) || type == typeof(ES3InspectorInfo)) + continue; + + // Add the prefab to the manager but don't process it. We'll use this to work out what prefabs to add to the prefabs list later. + if (type == typeof(ES3Prefab)) + { + dependencies.Add(obj); + continue; + } + + // If it's a GameObject, get the GameObject's Components and collect their dependencies. + if (type == typeof(GameObject)) + { + var go = (GameObject)obj; + // If we've not already processed this GameObject ... + if (dependencies.Add(go)) + { + // Get the dependencies of each Component in the GameObject. + CollectDependenciesLegacy(go.GetComponents(), dependencies, depth - 1); + // Get the dependencies of each child in the GameObject. + foreach (Transform child in go.transform) + CollectDependenciesLegacy(child.gameObject, dependencies, depth); // Don't decrement child, as we consider this a top-level object. + } + } + // Else if it's a Component or ScriptableObject, add the values of any UnityEngine.Object fields as dependencies. + else + CollectDependenciesFromFieldsLegacy(obj, dependencies, depth - 1); + } + + return dependencies; + } + + private static void CollectDependenciesFromFieldsLegacy(UnityEngine.Object obj, HashSet dependencies, int depth) + { + // If we've already collected dependencies for this, do nothing. + if (!dependencies.Add(obj)) + return; + + if (depth == int.MinValue) + depth = ES3Settings.defaultSettingsScriptableObject.collectDependenciesDepth; + + if (depth < 0) + return; + + var type = obj.GetType(); + + if (isEnteringPlayMode && type == typeof(UnityEngine.UI.Text)) + return; + + try + { + // SerializedObject is expensive, so for known classes we manually gather references. + + if (type == typeof(Animator) || obj is Transform || type == typeof(CanvasRenderer) || type == typeof(Mesh) || type == typeof(AudioClip) || type == typeof(Rigidbody) || obj is HorizontalOrVerticalLayoutGroup) + return; + + if(obj is Texture) + { + // This ensures that Sprites which are children of the Texture are also added. In the Editor you would otherwise need to expand the Texture to add the Sprite. + foreach(var dependency in UnityEditor.AssetDatabase.LoadAllAssetsAtPath(UnityEditor.AssetDatabase.GetAssetPath(obj))) + if (dependency != obj) + dependencies.Add(dependency); + } + + if (obj is Graphic) + { + var m = (Graphic)obj; + dependencies.Add(m.material); + dependencies.Add(m.defaultMaterial); + dependencies.Add(m.mainTexture); + + if (type == typeof(Text)) + { + var text = (Text)obj; + dependencies.Add(text.font); + } + else if (type == typeof(Image)) + { + var img = (Image)obj; + dependencies.Add(img.sprite); + } + return; + } + + if (type == typeof(Mesh)) + { + if (UnityEditor.AssetDatabase.Contains(obj)) + dependencies.Add(obj); + return; + } + + if (type == typeof(Material)) + { + var material = (Material)obj; + var shader = material.shader; + if (shader != null) + { + dependencies.Add(material.shader); + + #if UNITY_2019_3_OR_NEWER + for (int i = 0; i < shader.GetPropertyCount(); i++) + if (shader.GetPropertyType(i) == UnityEngine.Rendering.ShaderPropertyType.Texture) + dependencies.Add(material.GetTexture(shader.GetPropertyName(i))); + } + #endif + + return; + } + + if (type == typeof(MeshFilter)) + { + dependencies.Add(((MeshFilter)obj).sharedMesh); + return; + } + + if (type == typeof(MeshCollider)) + { + var mc = (MeshCollider)obj; + dependencies.Add(mc.sharedMesh); + dependencies.Add(mc.sharedMaterial); + dependencies.Add(mc.attachedRigidbody); + return; + } + + if (type == typeof(Camera)) + { + var c = (Camera)obj; + dependencies.Add(c.targetTexture); + return; + } + + if (type == typeof(SkinnedMeshRenderer)) + dependencies.Add(((SkinnedMeshRenderer)obj).sharedMesh); // Don't return. Let this fall through to the if(obj is renderer) call. + else if (type == typeof(SpriteRenderer)) + dependencies.Add(((SpriteRenderer)obj).sprite); // Don't return. Let this fall through to the if(obj is renderer) call. + else if (type == typeof(ParticleSystemRenderer)) + dependencies.Add(((ParticleSystemRenderer)obj).mesh); // Don't return. Let this fall through to the if(obj is renderer) call. + + if (obj is Renderer) + { + var renderer = (Renderer)obj; + foreach (var material in renderer.sharedMaterials) + CollectDependenciesFromFieldsLegacy(material, dependencies, depth - 1); + return; + } + } + catch { } + + var so = new UnityEditor.SerializedObject(obj); + if (so == null) + return; + + var property = so.GetIterator(); + if (property == null) + return; + + // Iterate through each of this object's properties. + while (property.NextVisible(true)) + { + try + { + // If it's an array which contains UnityEngine.Objects, add them as dependencies. + if (property.isArray && property.propertyType != UnityEditor.SerializedPropertyType.String) + { + for (int i = 0; i < property.arraySize; i++) + { + var element = property.GetArrayElementAtIndex(i); + + // If the array contains UnityEngine.Object types, add them to the dependencies. + if (element.propertyType == UnityEditor.SerializedPropertyType.ObjectReference) + { + var elementValue = element.objectReferenceValue; + var elementType = elementValue.GetType(); + + // If it's a GameObject, use CollectDependencies so that Components are also added. + if (elementType == typeof(GameObject)) + CollectDependenciesLegacy(elementValue, dependencies, depth - 1); + else + CollectDependenciesFromFieldsLegacy(elementValue, dependencies, depth - 1); + } + // Otherwise this array does not contain UnityEngine.Object types, so we should stop. + else + break; + } + } + // Else if it's a normal UnityEngine.Object field, add it. + else if (property.propertyType == UnityEditor.SerializedPropertyType.ObjectReference) + { + var propertyValue = property.objectReferenceValue; + if (propertyValue == null) + continue; + + // If it's a GameObject, use CollectDependencies so that Components are also added. + if (propertyValue.GetType() == typeof(GameObject)) + CollectDependenciesLegacy(propertyValue, dependencies, depth - 1); + else + CollectDependenciesFromFieldsLegacy(propertyValue, dependencies, depth - 1); + } + } + catch { } + } + } + + // Called in the Editor when this Component is added. + private void Reset() + { + // Ensure that Component can only be added by going to Assets > Easy Save 3 > Add Manager to Scene. + if (gameObject.name != "Easy Save 3 Manager") + { + UnityEditor.EditorUtility.DisplayDialog("Cannot add ES3ReferenceMgr directly", "Please go to 'Tools > Easy Save 3 > Add Manager to Scene' to add an Easy Save 3 Manager to your scene.", "Ok"); + DestroyImmediate(this); + } + } + #endif*/ + + internal static bool CanBeSaved(UnityEngine.Object obj) + { +#if UNITY_EDITOR + if (obj == null) + return true; + + foreach (var flag in invalidHideFlags) + if ((obj.hideFlags & flag) != 0 && obj.hideFlags != HideFlags.HideInHierarchy && obj.hideFlags != HideFlags.HideInInspector && obj.hideFlags != HideFlags.NotEditable) + if (!(obj is Mesh || obj is Material)) + return false; + + // Exclude the Easy Save 3 Manager, and all components attached to it. + if (obj.name == "Easy Save 3 Manager") + return false; +#endif + return true; + } + +#if UNITY_EDITOR + public void ExcludeObject(UnityEngine.Object obj) + { + if (excludeObjects == null) + excludeObjects = new List(); + + if (!excludeObjects.Contains(obj)) + excludeObjects.Add(obj); + } +#endif + } + + [System.Serializable] + public class ES3IdRefDictionary : ES3SerializableDictionary + { + protected override bool KeysAreEqual(long a, long b) + { + return a == b; + } + + protected override bool ValuesAreEqual(UnityEngine.Object a, UnityEngine.Object b) + { + return a == b; + } + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + [System.Serializable] + public class ES3RefIdDictionary : ES3SerializableDictionary + { + protected override bool KeysAreEqual(UnityEngine.Object a, UnityEngine.Object b) + { + return a == b; + } + + protected override bool ValuesAreEqual(long a, long b) + { + return a == b; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgrBase.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgrBase.cs.meta new file mode 100644 index 0000000..be51e29 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3ReferenceMgrBase.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f659e3ad478b6470d9744732042e7515 +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Reflection.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Reflection.cs new file mode 100644 index 0000000..0efe486 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Reflection.cs @@ -0,0 +1,794 @@ +using System.Collections; +using System.Collections.Generic; +using System; +using System.Linq; +using System.Reflection; +using System.ComponentModel; +using UnityEngine; +using ES3Types; + +namespace ES3Internal +{ + public static class ES3Reflection + { + public const string memberFieldPrefix = "m_"; + public const string componentTagFieldName = "tag"; + public const string componentNameFieldName = "name"; + public static readonly string[] excludedPropertyNames = new string[] { "runInEditMode", "useGUILayout", "hideFlags" }; + + public static readonly Type serializableAttributeType = typeof(System.SerializableAttribute); + public static readonly Type serializeFieldAttributeType = typeof(SerializeField); + public static readonly Type obsoleteAttributeType = typeof(System.ObsoleteAttribute); + public static readonly Type nonSerializedAttributeType = typeof(System.NonSerializedAttribute); + public static readonly Type es3SerializableAttributeType = typeof(ES3Serializable); + public static readonly Type es3NonSerializableAttributeType = typeof(ES3NonSerializable); + + public static Type[] EmptyTypes = new Type[0]; + + private static Assembly[] _assemblies = null; + private static Assembly[] Assemblies + { + get + { + + if (_assemblies == null) + { + var assemblyNames = new ES3Settings().assemblyNames; + var assemblyList = new List(); + + /* We only use a try/catch block for UWP because exceptions can be disabled on some other platforms (e.g. WebGL), but the non-try/catch method doesn't work on UWP */ +#if NETFX_CORE + for (int i = 0; i < assemblyNames.Length; i++) + { + try + { + var assembly = Assembly.Load(new AssemblyName(assemblyNames[i])); + if (assembly != null) + assemblyList.Add(assembly); + } + catch { } + } + +#else + var assemblies = AppDomain.CurrentDomain.GetAssemblies(); + foreach (var assembly in assemblies) + { + // This try/catch block is here to catch errors such as assemblies containing double-byte characters in their path. + // This obviously won't work if exceptions are disabled. + try + { + if (assemblyNames.Contains(assembly.GetName().Name)) + { + assemblyList.Add(assembly); + } + } + catch { } + } +#endif + _assemblies = assemblyList.ToArray(); + } + return _assemblies; + } + } + + /* + * Gets the element type of a collection or array. + * Returns null if type is not a collection type. + */ + public static Type[] GetElementTypes(Type type) + { + if (IsGenericType(type)) + return ES3Reflection.GetGenericArguments(type); + else if (type.IsArray) + return new Type[] { ES3Reflection.GetElementType(type) }; + else + return null; + } + + public static List GetSerializableFields(Type type, List serializableFields = null, bool safe = true, string[] memberNames = null, BindingFlags bindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly) + { + if (type == null) + return new List(); + + var fields = type.GetFields(bindings); + + if (serializableFields == null) + serializableFields = new List(); + + foreach (var field in fields) + { + var fieldName = field.Name; + + // If a members array was provided as a parameter, only include the field if it's in the array. + if (memberNames != null) + if (!memberNames.Contains(fieldName)) + continue; + + var fieldType = field.FieldType; + + if (AttributeIsDefined(field, es3SerializableAttributeType)) + { + serializableFields.Add(field); + continue; + } + + if (AttributeIsDefined(field, es3NonSerializableAttributeType)) + continue; + + if (safe) + { + // If the field is private, only serialize it if it's explicitly marked as serializable. + if (!field.IsPublic && !AttributeIsDefined(field, serializeFieldAttributeType)) + continue; + } + + // Exclude const or readonly fields. + if (field.IsLiteral || field.IsInitOnly) + continue; + + // Don't store fields whose type is the same as the class the field is housed in unless it's stored by reference (to prevent cyclic references) + if (fieldType == type && !IsAssignableFrom(typeof(UnityEngine.Object), fieldType)) + continue; + + // If property is marked as obsolete or non-serialized, don't serialize it. + if (AttributeIsDefined(field, nonSerializedAttributeType) || AttributeIsDefined(field, obsoleteAttributeType)) + continue; + + if (!TypeIsSerializable(field.FieldType)) + continue; + + // Don't serialize member fields. + if (safe && fieldName.StartsWith(memberFieldPrefix) && field.DeclaringType.Namespace != null && field.DeclaringType.Namespace.Contains("UnityEngine")) + continue; + + serializableFields.Add(field); + } + + var baseType = BaseType(type); + if (baseType != null && baseType != typeof(System.Object) && baseType != typeof(UnityEngine.Object)) + GetSerializableFields(BaseType(type), serializableFields, safe, memberNames); + + return serializableFields; + } + + public static List GetSerializableProperties(Type type, List serializableProperties = null, bool safe = true, string[] memberNames = null, BindingFlags bindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly) + { + bool isComponent = IsAssignableFrom(typeof(UnityEngine.Component), type); + + // Only get private properties if we're not getting properties safely. + if (!safe) + bindings = bindings | BindingFlags.NonPublic; + + var properties = type.GetProperties(bindings); + + if (serializableProperties == null) + serializableProperties = new List(); + + foreach (var p in properties) + { + if (AttributeIsDefined(p, es3SerializableAttributeType)) + { + serializableProperties.Add(p); + continue; + } + + if (AttributeIsDefined(p, es3NonSerializableAttributeType)) + continue; + + var propertyName = p.Name; + + if (excludedPropertyNames.Contains(propertyName)) + continue; + + // If a members array was provided as a parameter, only include the property if it's in the array. + if (memberNames != null) + if (!memberNames.Contains(propertyName)) + continue; + + if (safe) + { + // If safe serialization is enabled, only get properties which are explicitly marked as serializable. + if (!AttributeIsDefined(p, serializeFieldAttributeType) && !AttributeIsDefined(p, es3SerializableAttributeType)) + continue; + } + + var propertyType = p.PropertyType; + + // Don't store properties whose type is the same as the class the property is housed in unless it's stored by reference (to prevent cyclic references) + if (propertyType == type && !IsAssignableFrom(typeof(UnityEngine.Object), propertyType)) + continue; + + if (!p.CanRead || !p.CanWrite) + continue; + + // Only support properties with indexing if they're an array. + if (p.GetIndexParameters().Length != 0 && !propertyType.IsArray) + continue; + + // Check that the type of the property is one which we can serialize. + // Also check whether an ES3Type exists for it. + if (!TypeIsSerializable(propertyType)) + continue; + + // Ignore certain properties on components. + if (isComponent) + { + // Ignore properties which are accessors for GameObject fields. + if (propertyName == componentTagFieldName || propertyName == componentNameFieldName) + continue; + } + + // If property is marked as obsolete or non-serialized, don't serialize it. + if (AttributeIsDefined(p, obsoleteAttributeType) || AttributeIsDefined(p, nonSerializedAttributeType)) + continue; + + serializableProperties.Add(p); + } + + var baseType = BaseType(type); + if (baseType != null && baseType != typeof(System.Object)) + GetSerializableProperties(baseType, serializableProperties, safe, memberNames); + + return serializableProperties; + } + + public static bool TypeIsSerializable(Type type) + { + if (type == null) + return false; + + if (AttributeIsDefined(type, es3NonSerializableAttributeType)) + return false; + + if (IsPrimitive(type) || IsValueType(type) || IsAssignableFrom(typeof(UnityEngine.Component), type) || IsAssignableFrom(typeof(UnityEngine.ScriptableObject), type)) + return true; + + var es3Type = ES3TypeMgr.GetOrCreateES3Type(type, false); + + if (es3Type != null && !es3Type.isUnsupported) + return true; + + if (TypeIsArray(type)) + { + if (TypeIsSerializable(type.GetElementType())) + return true; + return false; + } + + var genericArgs = type.GetGenericArguments(); + for (int i = 0; i < genericArgs.Length; i++) + if (!TypeIsSerializable(genericArgs[i])) + return false; + + /*if (HasParameterlessConstructor(type)) + return true;*/ + return false; + } + + public static System.Object CreateInstance(Type type) + { + if (IsAssignableFrom(typeof(UnityEngine.Component), type)) + return ES3ComponentType.CreateComponent(type); + else if (IsAssignableFrom(typeof(ScriptableObject), type)) + return ScriptableObject.CreateInstance(type); + else if (ES3Reflection.HasParameterlessConstructor(type)) + return Activator.CreateInstance(type); + else + { +#if NETFX_CORE + throw new NotSupportedException($"Cannot create an instance of {type} because it does not have a parameterless constructor, which is required on Universal Windows platform."); +#else + return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type); +#endif + } + } + + public static System.Object CreateInstance(Type type, params object[] args) + { + if (IsAssignableFrom(typeof(UnityEngine.Component), type)) + return ES3ComponentType.CreateComponent(type); + else if (IsAssignableFrom(typeof(ScriptableObject), type)) + return ScriptableObject.CreateInstance(type); + return Activator.CreateInstance(type, args); + } + + public static Array ArrayCreateInstance(Type type, int length) + { + return Array.CreateInstance(type, new int[] { length }); + } + + public static Array ArrayCreateInstance(Type type, int[] dimensions) + { + return Array.CreateInstance(type, dimensions); + } + + public static Type MakeGenericType(Type type, Type genericParam) + { + return type.MakeGenericType(genericParam); + } + + public static ES3ReflectedMember[] GetSerializableMembers(Type type, bool safe = true, string[] memberNames = null) + { + if (type == null) + return new ES3ReflectedMember[0]; + + var fieldInfos = GetSerializableFields(type, new List(), safe, memberNames); + var propertyInfos = GetSerializableProperties(type, new List(), safe, memberNames); + var reflectedFields = new ES3ReflectedMember[fieldInfos.Count + propertyInfos.Count]; + + for (int i = 0; i < fieldInfos.Count; i++) + reflectedFields[i] = new ES3ReflectedMember(fieldInfos[i]); + for (int i = 0; i < propertyInfos.Count; i++) + reflectedFields[i + fieldInfos.Count] = new ES3ReflectedMember(propertyInfos[i]); + + return reflectedFields; + } + + public static ES3ReflectedMember GetES3ReflectedProperty(Type type, string propertyName) + { + var propertyInfo = ES3Reflection.GetProperty(type, propertyName); + return new ES3ReflectedMember(propertyInfo); + } + + public static ES3ReflectedMember GetES3ReflectedMember(Type type, string fieldName) + { + var fieldInfo = ES3Reflection.GetField(type, fieldName); + return new ES3ReflectedMember(fieldInfo); + } + + /* + * Finds all classes of a specific type, and then returns an instance of each. + * Ignores classes which can't be instantiated (i.e. abstract classes, those without parameterless constructors). + */ + public static IList GetInstances() + { + var instances = new List(); + foreach (var assembly in Assemblies) + foreach (var type in assembly.GetTypes()) + if (IsAssignableFrom(typeof(T), type) && ES3Reflection.HasParameterlessConstructor(type) && !ES3Reflection.IsAbstract(type)) + instances.Add((T)Activator.CreateInstance(type)); + return instances; + } + + public static IList GetDerivedTypes(Type derivedType) + { + return + ( + from assembly in Assemblies + from type in assembly.GetTypes() + where IsAssignableFrom(derivedType, type) + select type + ).ToList(); + } + + public static bool IsAssignableFrom(Type a, Type b) + { + return a.IsAssignableFrom(b); + } + + public static Type GetGenericTypeDefinition(Type type) + { + return type.GetGenericTypeDefinition(); + } + + public static Type[] GetGenericArguments(Type type) + { + return type.GetGenericArguments(); + } + + public static int GetArrayRank(Type type) + { + return type.GetArrayRank(); + } + + public static string GetAssemblyQualifiedName(Type type) + { + return type.AssemblyQualifiedName; + } + + public static ES3ReflectedMethod GetMethod(Type type, string methodName, Type[] genericParameters, Type[] parameterTypes) + { + return new ES3ReflectedMethod(type, methodName, genericParameters, parameterTypes); + } + + public static bool TypeIsArray(Type type) + { + return type.IsArray; + } + + public static Type GetElementType(Type type) + { + return type.GetElementType(); + } + +#if NETFX_CORE + public static bool IsAbstract(Type type) + { + return type.GetTypeInfo().IsAbstract; + } + + public static bool IsInterface(Type type) + { + return type.GetTypeInfo().IsInterface; + } + + public static bool IsGenericType(Type type) + { + return type.GetTypeInfo().IsGenericType; + } + + public static bool IsValueType(Type type) + { + return type.GetTypeInfo().IsValueType; + } + + public static bool IsEnum(Type type) + { + return type.GetTypeInfo().IsEnum; + } + + public static bool HasParameterlessConstructor(Type type) + { + return GetParameterlessConstructor(type) != null; + } + + public static ConstructorInfo GetParameterlessConstructor(Type type) + { + foreach (var cInfo in type.GetTypeInfo().DeclaredConstructors) + if (!cInfo.IsStatic && cInfo.GetParameters().Length == 0) + return cInfo; + return null; + } + + public static string GetShortAssemblyQualifiedName(Type type) + { + if (IsPrimitive (type)) + return type.ToString (); + return type.FullName + "," + type.GetTypeInfo().Assembly.GetName().Name; + } + + public static PropertyInfo GetProperty(Type type, string propertyName) + { + var property = type.GetTypeInfo().GetDeclaredProperty(propertyName); + if (property == null && type.BaseType != typeof(object)) + return GetProperty(type.BaseType, propertyName); + return property; + } + + public static FieldInfo GetField(Type type, string fieldName) + { + return type.GetTypeInfo().GetDeclaredField(fieldName); + } + + public static MethodInfo[] GetMethods(Type type, string methodName) + { + return type.GetTypeInfo().GetDeclaredMethods(methodName); + } + + public static bool IsPrimitive(Type type) + { + return (type.GetTypeInfo().IsPrimitive || type == typeof(string) || type == typeof(decimal)); + } + + public static bool AttributeIsDefined(MemberInfo info, Type attributeType) + { + var attributes = info.GetCustomAttributes(attributeType, true); + foreach(var attribute in attributes) + return true; + return false; + } + + public static bool AttributeIsDefined(Type type, Type attributeType) + { + var attributes = type.GetTypeInfo().GetCustomAttributes(attributeType, true); + foreach(var attribute in attributes) + return true; + return false; + } + + public static bool ImplementsInterface(Type type, Type interfaceType) + { + return type.GetTypeInfo().ImplementedInterfaces.Contains(interfaceType); + } + + public static Type BaseType(Type type) + { + return type.GetTypeInfo().BaseType; + } +#else + public static bool IsAbstract(Type type) + { + return type.IsAbstract; + } + + public static bool IsInterface(Type type) + { + return type.IsInterface; + } + + public static bool IsGenericType(Type type) + { + return type.IsGenericType; + } + + public static bool IsValueType(Type type) + { + return type.IsValueType; + } + + public static bool IsEnum(Type type) + { + return type.IsEnum; + } + + public static bool HasParameterlessConstructor(Type type) + { + if (IsValueType(type) || GetParameterlessConstructor(type) != null) + return true; + return false; + } + + public static ConstructorInfo GetParameterlessConstructor(Type type) + { + var constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + + foreach (var constructor in constructors) + if (constructor.GetParameters().Length == 0) + return constructor; + return null; + } + + public static string GetShortAssemblyQualifiedName(Type type) + { + if (IsPrimitive(type)) + return type.ToString(); + return type.FullName + "," + type.Assembly.GetName().Name; + } + + public static PropertyInfo GetProperty(Type type, string propertyName) + { + var property = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + if (property == null && BaseType(type) != typeof(object)) + return GetProperty(BaseType(type), propertyName); + return property; + } + + public static FieldInfo GetField(Type type, string fieldName) + { + var field = type.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + if (field == null && BaseType(type) != typeof(object)) + return GetField(BaseType(type), fieldName); + return field; + } + + public static MethodInfo[] GetMethods(Type type, string methodName) + { + return type.GetMethods().Where(t => t.Name == methodName).ToArray(); + } + + public static bool IsPrimitive(Type type) + { + return (type.IsPrimitive || type == typeof(string) || type == typeof(decimal)); + } + + public static bool AttributeIsDefined(MemberInfo info, Type attributeType) + { + return Attribute.IsDefined(info, attributeType, true); + } + + public static bool AttributeIsDefined(Type type, Type attributeType) + { + return type.IsDefined(attributeType, true); + } + + public static bool ImplementsInterface(Type type, Type interfaceType) + { + return (type.GetInterface(interfaceType.Name) != null); + } + + public static Type BaseType(Type type) + { + return type.BaseType; + } + + public static Type GetType(string typeString) + { + switch (typeString) + { + case "bool": + return typeof(bool); + case "byte": + return typeof(byte); + case "sbyte": + return typeof(sbyte); + case "char": + return typeof(char); + case "decimal": + return typeof(decimal); + case "double": + return typeof(double); + case "float": + return typeof(float); + case "int": + return typeof(int); + case "uint": + return typeof(uint); + case "long": + return typeof(long); + case "ulong": + return typeof(ulong); + case "short": + return typeof(short); + case "ushort": + return typeof(ushort); + case "string": + return typeof(string); + case "Vector2": + return typeof(Vector2); + case "Vector3": + return typeof(Vector3); + case "Vector4": + return typeof(Vector4); + case "Color": + return typeof(Color); + case "Transform": + return typeof(Transform); + case "Component": + return typeof(UnityEngine.Component); + case "GameObject": + return typeof(GameObject); + case "MeshFilter": + return typeof(MeshFilter); + case "Material": + return typeof(Material); + case "Texture2D": + return typeof(Texture2D); + case "UnityEngine.Object": + return typeof(UnityEngine.Object); + case "System.Object": + return typeof(object); + default: + return Type.GetType(typeString); + } + } + + public static string GetTypeString(Type type) + { + if (type == typeof(bool)) + return "bool"; + else if (type == typeof(byte)) + return "byte"; + else if (type == typeof(sbyte)) + return "sbyte"; + else if (type == typeof(char)) + return "char"; + else if (type == typeof(decimal)) + return "decimal"; + else if (type == typeof(double)) + return "double"; + else if (type == typeof(float)) + return "float"; + else if (type == typeof(int)) + return "int"; + else if (type == typeof(uint)) + return "uint"; + else if (type == typeof(long)) + return "long"; + else if (type == typeof(ulong)) + return "ulong"; + else if (type == typeof(short)) + return "short"; + else if (type == typeof(ushort)) + return "ushort"; + else if (type == typeof(string)) + return "string"; + else if (type == typeof(Vector2)) + return "Vector2"; + else if (type == typeof(Vector3)) + return "Vector3"; + else if (type == typeof(Vector4)) + return "Vector4"; + else if (type == typeof(Color)) + return "Color"; + else if (type == typeof(Transform)) + return "Transform"; + else if (type == typeof(UnityEngine.Component)) + return "Component"; + else if (type == typeof(GameObject)) + return "GameObject"; + else if (type == typeof(MeshFilter)) + return "MeshFilter"; + else if (type == typeof(Material)) + return "Material"; + else if (type == typeof(Texture2D)) + return "Texture2D"; + else if (type == typeof(UnityEngine.Object)) + return "UnityEngine.Object"; + else if (type == typeof(object)) + return "System.Object"; + else + return GetShortAssemblyQualifiedName(type); + } +#endif + + /* + * Allows us to use FieldInfo and PropertyInfo interchangably. + */ + public struct ES3ReflectedMember + { + // The FieldInfo or PropertyInfo for this field. + private FieldInfo fieldInfo; + private PropertyInfo propertyInfo; + public bool isProperty; + + public bool IsNull { get { return fieldInfo == null && propertyInfo == null; } } + public string Name { get { return (isProperty ? propertyInfo.Name : fieldInfo.Name); } } + public Type MemberType { get { return (isProperty ? propertyInfo.PropertyType : fieldInfo.FieldType); } } + public bool IsPublic { get { return (isProperty ? (propertyInfo.GetGetMethod(true).IsPublic && propertyInfo.GetSetMethod(true).IsPublic) : fieldInfo.IsPublic); } } + public bool IsProtected { get { return (isProperty ? (propertyInfo.GetGetMethod(true).IsFamily) : fieldInfo.IsFamily); } } + public bool IsStatic { get { return (isProperty ? (propertyInfo.GetGetMethod(true).IsStatic) : fieldInfo.IsStatic); } } + + public ES3ReflectedMember(System.Object fieldPropertyInfo) + { + if (fieldPropertyInfo == null) + { + this.propertyInfo = null; + this.fieldInfo = null; + isProperty = false; + return; + } + + isProperty = ES3Reflection.IsAssignableFrom(typeof(PropertyInfo), fieldPropertyInfo.GetType()); + if (isProperty) + { + this.propertyInfo = (PropertyInfo)fieldPropertyInfo; + this.fieldInfo = null; + } + else + { + this.fieldInfo = (FieldInfo)fieldPropertyInfo; + this.propertyInfo = null; + } + } + + public void SetValue(System.Object obj, System.Object value) + { + if (isProperty) + propertyInfo.SetValue(obj, value, null); + else + fieldInfo.SetValue(obj, value); + } + + public System.Object GetValue(System.Object obj) + { + if (isProperty) + return propertyInfo.GetValue(obj, null); + else + return fieldInfo.GetValue(obj); + } + } + + public class ES3ReflectedMethod + { + private MethodInfo method; + + public ES3ReflectedMethod(Type type, string methodName, Type[] genericParameters, Type[] parameterTypes) + { + MethodInfo nonGenericMethod = type.GetMethod(methodName, parameterTypes); + this.method = nonGenericMethod.MakeGenericMethod(genericParameters); + } + + public ES3ReflectedMethod(Type type, string methodName, Type[] genericParameters, Type[] parameterTypes, BindingFlags bindingAttr) + { + MethodInfo nonGenericMethod = type.GetMethod(methodName, bindingAttr, null, parameterTypes, null); + this.method = nonGenericMethod.MakeGenericMethod(genericParameters); + } + + public object Invoke(object obj, object[] parameters = null) + { + return method.Invoke(obj, parameters); + } + } + + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Reflection.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Reflection.cs.meta new file mode 100644 index 0000000..e8d30de --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Reflection.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 499c212fb9e3c410dacca179f55ba150 +timeCreated: 1499764821 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3SerializableDictionary.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3SerializableDictionary.cs new file mode 100644 index 0000000..74a76a8 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3SerializableDictionary.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using System.Linq; + +namespace ES3Internal +{ + [System.Serializable] + public abstract class ES3SerializableDictionary : Dictionary, ISerializationCallbackReceiver + { + [SerializeField] + private List _Keys; + [SerializeField] + private List _Values; + + protected abstract bool KeysAreEqual(TKey a, TKey b); + protected abstract bool ValuesAreEqual(TVal a, TVal b); + + public void OnBeforeSerialize() + { + _Keys = new List(); + _Values = new List(); + foreach(KeyValuePair pair in this) + { + try + { + _Keys.Add(pair.Key); + _Values.Add(pair.Value); + } + catch { } + } + } + + // load dictionary from lists + public void OnAfterDeserialize() + { + // There are some situations where Unity will not get the serialized data correctly, returning null. + // In this case we don't want to change anything, otherwise we'll lose the data entirely. + if (_Keys == null || _Values == null) + return; + + if(_Keys.Count != _Values.Count) + throw new System.Exception(string.Format("Key count is different to value count after deserialising dictionary.")); + + this.Clear(); + + for (int i = 0; i < _Keys.Count; i++) + { + if (_Keys[i] != null) + { + try + { + this.Add(_Keys[i], _Values[i]); + } + catch { } + } + } + + _Keys = null; + _Values = null; + } + + public int RemoveNullValues() + { + var nullKeys = this.Where(pair => pair.Value == null) + .Select(pair => pair.Key) + .ToList(); + foreach (var nullKey in nullKeys) + Remove(nullKey); + return nullKeys.Count; + } + + // Changes the key of a value without changing it's position in the underlying Lists. + // Mainly used in the Editor where position might otherwise change while the user is editing it. + // Returns true if a change was made. + public bool ChangeKey(TKey oldKey, TKey newKey) + { + if(KeysAreEqual(oldKey, newKey)) + return false; + + var val = this [oldKey]; + Remove(oldKey); + this [newKey] = val; + return true; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3SerializableDictionary.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3SerializableDictionary.cs.meta new file mode 100644 index 0000000..50a99d2 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3SerializableDictionary.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 681896bd0089c4f7296b3ecbd899f44d +timeCreated: 1519132287 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Spreadsheet.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Spreadsheet.cs new file mode 100644 index 0000000..cd3c1cc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Spreadsheet.cs @@ -0,0 +1,307 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using System.IO; +using ES3Internal; + +#if UNITY_VISUAL_SCRIPTING +[Unity.VisualScripting.IncludeInSettings(true)] +#elif BOLT_VISUAL_SCRIPTING +[Ludiq.IncludeInSettings(true)] +#endif +public class ES3Spreadsheet +{ + private int cols = 0; + private int rows = 0; + private Dictionary cells = new Dictionary(); + + private const string QUOTE = "\""; + private const char QUOTE_CHAR = '"'; + private const char COMMA_CHAR = ','; + private const char NEWLINE_CHAR = '\n'; + private const string ESCAPED_QUOTE = "\"\""; + private static char[] CHARS_TO_ESCAPE = { ',', '"', '\n', ' ' }; + + public int ColumnCount + { + get{ return cols; } + } + + public int RowCount + { + get{ return rows; } + } + + public int GetColumnLength(int col) + { + if (col >= cols) + return 0; + + int maxRow = -1; + + foreach(var index in cells.Keys) + if (index.col == col && index.row > maxRow) + maxRow = index.row; + + return maxRow+1; + } + + public int GetRowLength(int row) + { + if (row >= rows) + return 0; + + int maxCol = -1; + + foreach (var index in cells.Keys) + if (index.row == row && index.col > maxCol) + maxCol = index.col; + + return maxCol + 1; + } + + public void SetCell(int col, int row, object value) + { + var type = value.GetType(); + + // If we're writing a string, add it without formatting. + if (type == typeof(string)) + { + SetCellString(col, row, (string)value); + return; + } + + var settings = new ES3Settings(); + if (ES3Reflection.IsPrimitive(type)) + SetCellString(col, row, value.ToString()); + else + SetCellString(col, row, settings.encoding.GetString(ES3.Serialize(value, ES3TypeMgr.GetOrCreateES3Type(type)))); + + // Expand the spreadsheet if necessary. + if (col >= cols) + cols = (col + 1); + if (row >= rows) + rows = (row + 1); + } + + private void SetCellString(int col, int row, string value) + { + cells [new Index (col, row)] = value; + + // Expand the spreadsheet if necessary. + if(col >= cols) + cols = (col+1); + if (row >= rows) + rows = (row + 1); + } + + + // Don't create non-generic version of this. Generic parameter is necessary as no type data is stored in the CSV file. + public T GetCell(int col, int row) + { + var val = GetCell(typeof(T), col, row); + + if (val == null) + return default(T); + return (T)val; + } + + public object GetCell(System.Type type, int col, int row) + { + string value; + + if (col >= cols || row >= rows) + throw new System.IndexOutOfRangeException("Cell (" + col + ", " + row + ") is out of bounds of spreadsheet (" + cols + ", " + rows + ")."); + + if (!cells.TryGetValue(new Index(col, row), out value) || value == null) + return null; + + // If we're loading a string, simply return the string value. + if (type == typeof(string)) + { + var str = (object)value; + return str; + } + + var settings = new ES3Settings(); + return ES3.Deserialize(ES3TypeMgr.GetOrCreateES3Type(type, true), settings.encoding.GetBytes(value), settings); + } + + public void Load(string filePath) + { + Load(new ES3Settings (filePath)); + } + + public void Load(string filePath, ES3Settings settings) + { + Load(new ES3Settings (filePath, settings)); + } + + public void Load(ES3Settings settings) + { + Load(ES3Stream.CreateStream(settings, ES3FileMode.Read), settings); + } + + public void LoadRaw(string str) + { + Load(new MemoryStream (((new ES3Settings ()).encoding).GetBytes(str)), new ES3Settings()); + } + + public void LoadRaw(string str, ES3Settings settings) + { + Load(new MemoryStream ((settings.encoding).GetBytes(str)), settings); + } + + private void Load(Stream stream, ES3Settings settings) + { + using (var reader = new StreamReader(stream)) + { + int c_int; + char c; + string value = ""; + int col = 0; + int row = 0; + + // Read until the end of the stream. + while(true) + { + c_int = reader.Read(); + c = (char)c_int; + if(c == QUOTE_CHAR) + { + while (true) + { + c = (char)reader.Read(); + + if(c == QUOTE_CHAR) + { + // If this quote isn't escaped by another, it is the last quote, so we should stop parsing this value. + if(((char)reader.Peek()) != QUOTE_CHAR) + break; + else + c = (char)reader.Read(); + } + value += c; + } + } + // If this is the end of a column, row, or the stream, add the value to the spreadsheet. + else if(c == COMMA_CHAR || c == NEWLINE_CHAR || c_int == -1) + { + SetCell(col, row, value); + value = ""; + if(c == COMMA_CHAR) + col++; + else if(c == NEWLINE_CHAR) + { + col = 0; + row++; + } + else + break; + } + else + value += c; + } + } + } + + public void Save(string filePath) + { + Save(new ES3Settings (filePath), false); + } + + public void Save(string filePath, ES3Settings settings) + { + Save(new ES3Settings (filePath, settings), false); + } + + public void Save(ES3Settings settings) + { + Save(settings, false); + } + + public void Save(string filePath, bool append) + { + Save(new ES3Settings (filePath), append); + } + + public void Save(string filePath, ES3Settings settings, bool append) + { + Save(new ES3Settings (filePath, settings), append); + } + + public void Save(ES3Settings settings, bool append) + { + using (var writer = new StreamWriter(ES3Stream.CreateStream(settings, append ? ES3FileMode.Append : ES3FileMode.Write))) + { + // If data already exists and we're appending, we need to prepend a newline. + if(append && ES3.FileExists(settings)) + writer.Write(NEWLINE_CHAR); + + var array = ToArray(); + for(int row = 0; row < rows; row++) + { + if(row != 0) + writer.Write(NEWLINE_CHAR); + + for(int col = 0; col < cols; col++) + { + if(col != 0) + writer.Write(COMMA_CHAR); + + writer.Write( Escape(array [col, row]) ); + } + } + } + if(!append) + ES3IO.CommitBackup(settings); + } + + private static string Escape(string str, bool isAlreadyWrappedInQuotes=false) + { + if (str == "") + return "\"\""; + else if(str == null) + return null; + + // Now escape any other quotes. + if(str.Contains(QUOTE)) + str = str.Replace(QUOTE, ESCAPED_QUOTE); + + // If there's chars to escape, wrap the value in quotes. + if(str.IndexOfAny(CHARS_TO_ESCAPE) > -1) + str = QUOTE + str + QUOTE; + return str; + } + + private static string Unescape(string str) + { + if(str.StartsWith(QUOTE) && str.EndsWith(QUOTE)) + { + str = str.Substring(1, str.Length-2); + if(str.Contains(ESCAPED_QUOTE)) + str = str.Replace(ESCAPED_QUOTE, QUOTE); + } + return str; + } + + private string[,] ToArray() + { + var array = new string[cols, rows]; + foreach (var cell in cells) + array [cell.Key.col, cell.Key.row] = cell.Value; + return array; + } + + protected struct Index + { + public int col; + public int row; + + public Index(int col, int row) + { + this.col = col; + this.row = row; + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Spreadsheet.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Spreadsheet.cs.meta new file mode 100644 index 0000000..ad2f748 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/ES3Spreadsheet.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: bb1f812633929432dabb61bb8de267ba +timeCreated: 1508838134 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers.meta new file mode 100644 index 0000000..bef3d18 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ad87ae223ed42a54c9eb2a3c28ef0a95 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3JSONReader.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3JSONReader.cs new file mode 100644 index 0000000..fb3e06b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3JSONReader.cs @@ -0,0 +1,571 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using System.IO; +using System.Text; +using System; +using ES3Types; +using System.Globalization; + +namespace ES3Internal +{ + /* + * Specific ES3Reader for reading JSON data. + * + * Note: Leading & trailing whitespace is ignored whenever + * reading characters which are part of the JSON syntax, + * i.e. { } [ ] , " " : + */ + public class ES3JSONReader : ES3Reader + { + private const char endOfStreamChar = (char)65535; + + public StreamReader baseReader; + + internal ES3JSONReader(Stream stream, ES3Settings settings, bool readHeaderAndFooter = true) : base(settings, readHeaderAndFooter) + { + this.baseReader = new StreamReader(stream); + + // Read opening brace from file if we're loading straight from file. + if(readHeaderAndFooter) + { + try + { + SkipOpeningBraceOfFile(); + } + catch + { + this.Dispose(); + throw new FormatException("Cannot load from file because the data in it is not JSON data, or the data is encrypted.\nIf the save data is encrypted, please ensure that encryption is enabled when you load, and that you are using the same password used to encrypt the data."); + } + } + } + + #region Property/Key Methods + + /* + * Reads the name of a property, and must be positioned (with or without whitespace) either: + * - Before the '"' of a property name. + * - Before the ',' separating properties. + * - Before the '}' or ']' terminating this list of properties. + * Can be used in conjunction with Read(ES3Type) to read a property. + */ + public override string ReadPropertyName() + { + char c = PeekCharIgnoreWhitespace(); + + // Check whether there are any properties left to read. + if(IsTerminator(c)) + return null; + else if(c == ',') + ReadCharIgnoreWhitespace(); + else if(!IsQuotationMark(c)) + throw new FormatException("Expected ',' separating properties or '\"' before property name, found '"+c+"'."); + + var propertyName = Read_string(); + if(propertyName == null) + throw new FormatException("Stream isn't positioned before a property."); + + ES3Debug.Log(""+propertyName+" (reading property)", null, serializationDepth); + + // Skip the ':' seperating property and value. + ReadCharIgnoreWhitespace(':'); + + return propertyName; + } + + /* + * Reads the type data prefixed to this key. + * If ignore is true, it will return null to save the computation of converting + * the string to a Type. + */ + protected override Type ReadKeyPrefix(bool ignoreType=false) + { + StartReadObject(); + + Type dataType = null; + + string propertyName = ReadPropertyName(); + if(propertyName == ES3Type.typeFieldName) + { + string typeString = Read_string(); + dataType = ignoreType ? null : ES3Reflection.GetType(typeString); + propertyName = ReadPropertyName(); + } + + if(propertyName != "value") + throw new FormatException("This data is not Easy Save Key Value data. Expected property name \"value\", found \""+propertyName+"\"."); + + return dataType; + } + + protected override void ReadKeySuffix() + { + EndReadObject(); + } + + + internal override bool StartReadObject() + { + base.StartReadObject(); + return ReadNullOrCharIgnoreWhitespace('{'); + } + + internal override void EndReadObject() + { + ReadCharIgnoreWhitespace('}'); + base.EndReadObject(); + } + + + internal override bool StartReadDictionary() + { + return StartReadObject(); + } + + internal override void EndReadDictionary(){} + + internal override bool StartReadDictionaryKey() + { + // If this is an empty Dictionary, return false. + if(PeekCharIgnoreWhitespace() == '}') + { + ReadCharIgnoreWhitespace(); + return false; + } + return true; + } + + internal override void EndReadDictionaryKey() + { + ReadCharIgnoreWhitespace(':'); + } + + internal override void StartReadDictionaryValue(){} + + internal override bool EndReadDictionaryValue() + { + char c = ReadCharIgnoreWhitespace(); + // If we find a ']', we reached the end of the array. + if(c == '}') + return true; + // Else, we should expect a comma. + else if(c != ',') + throw new FormatException("Expected ',' seperating Dictionary items or '}' terminating Dictionary, found '"+c+"'."); + return false; + } + + + internal override bool StartReadCollection() + { + return ReadNullOrCharIgnoreWhitespace('['); + } + + internal override void EndReadCollection(){} + + internal override bool StartReadCollectionItem() + { + // If this is an empty collection, return false. + if(PeekCharIgnoreWhitespace() == ']') + { + ReadCharIgnoreWhitespace(); + return false; + } + return true; + } + + internal override bool EndReadCollectionItem() + { + char c = ReadCharIgnoreWhitespace(); + // If we find a ']', we reached the end of the array. + if(c == ']') + return true; + // Else, we should expect a comma. + else if(c != ',') + throw new FormatException("Expected ',' seperating collection items or ']' terminating collection, found '"+c+"'."); + return false; + } + + #endregion + + #region Seeking Methods + + /* + * Reads a string value into a StreamWriter. + * Reader should be positioned after the opening quotation mark. + * Will also read the closing quotation mark. + * If the 'skip' parameter is true, data will not be written into a StreamWriter and will return null. + */ + private void ReadString(StreamWriter writer, bool skip=false) + { + bool endOfString = false; + // Read to end of string, or throw error if we reach end of stream. + while(!endOfString) + { + char c = ReadOrSkipChar(writer, skip); + switch(c) + { + case endOfStreamChar: + throw new FormatException("String without closing quotation mark detected."); + case '\\': + ReadOrSkipChar(writer, skip); + break; + default: + if(IsQuotationMark(c)) + endOfString = true; + break; + } + } + } + + /* + * Reads the current object in the stream. + * Stream position should be somewhere before the opening brace for the object. + * When this method successfully exits, it will be on the closing brace for the object. + * If the 'skip' parameter is true, data will not be written into a StreamWriter and will return null. + */ + internal override byte[] ReadElement(bool skip=false) + { + // If 'skip' is enabled, don't create a stream or writer as we'll discard all bytes we read. + StreamWriter writer = skip ? null : new StreamWriter(new MemoryStream(settings.bufferSize)); + + using(writer) + { + int nesting = 0; + char c = (char)baseReader.Peek(); + + // Determine if we're skipping a primitive type. + // First check if it's an opening object or array brace. + if(!IsOpeningBrace(c)) + { + // If we're skipping a string, use SkipString(). + if(c == '\"') + { + // Skip initial quotation mark as SkipString() requires this. + ReadOrSkipChar(writer, skip); + ReadString(writer, skip); + } + // Else we just need to read until we reach a closing brace. + else + // While we've not peeked a closing brace. + while(!IsEndOfValue((char)baseReader.Peek())) + ReadOrSkipChar(writer, skip); + + if(skip) + return null; + writer.Flush(); + return ((MemoryStream)writer.BaseStream).ToArray(); + } + + // Else, we're skipping a type surrounded by braces. + // Iterate through every character, logging nesting. + while(true) + { + c = ReadOrSkipChar(writer, skip); + + if(c == endOfStreamChar) // Detect premature end of stream, which denotes missing closing brace. + throw new FormatException("Missing closing brace detected, as end of stream was reached before finding it."); + + // Handle quoted strings. + // According to the RFC, only '\' and '"' must be escaped in strings. + if(IsQuotationMark(c)) + { + ReadString(writer, skip); + continue; + } + + // Handle braces and other characters. + switch(c) + { + case '{': // Entered another level of nesting. + case '[': + nesting++; + break; + case '}': // Exited a level of nesting. + case ']': + nesting--; + // If nesting < 1, we've come to the end of the object. + if(nesting<1) + { + if(skip) + return null; + writer.Flush(); + return ((MemoryStream)writer.BaseStream).ToArray(); + } + break; + default: + break; + } + } + } + } + + /* + * Reads the next char into a stream, or ignores it if 'skip' is true. + */ + private char ReadOrSkipChar(StreamWriter writer, bool skip) + { + char c = (char)baseReader.Read(); + if(!skip) writer.Write(c); + return c; + } + + #endregion + + #region JSON-specific methods. + + /* + * Reads a char from the stream and ignores leading and trailing whitespace. + */ + private char ReadCharIgnoreWhitespace(bool ignoreTrailingWhitespace=true) + { + char c; + // Skip leading whitespace and read char. + while(IsWhiteSpace(c = (char)baseReader.Read())) + {} + + // Skip trailing whitespace. + if(ignoreTrailingWhitespace) + while(IsWhiteSpace((char)baseReader.Peek())) + baseReader.Read(); + + return c; + } + + /* + * Reads a char, or the NULL value, from the stream and ignores leading and trailing whitespace. + * Returns true if NULL was read. + */ + private bool ReadNullOrCharIgnoreWhitespace(char expectedChar) + { + char c = ReadCharIgnoreWhitespace(); + + // Check for null + if(c == 'n') + { + var chars = new char[3]; + baseReader.ReadBlock(chars, 0, 3); + if((char)chars[0] == 'u' && (char)chars[1] == 'l' && (char)chars[2] == 'l') + return true; + } + + if(c != expectedChar) + { + if(c == endOfStreamChar) + throw new FormatException("End of stream reached when expecting '"+expectedChar+"'."); + else + throw new FormatException("Expected \'"+expectedChar+"\' or \"null\", found \'"+c+"\'."); + } + return false; + } + + /* + * Reads a char from the stream and ignores leading and trailing whitespace. + * Throws an error if the char isn't equal to the one specificed as a parameter, or if it's the end of stream. + */ + private char ReadCharIgnoreWhitespace(char expectedChar) + { + char c = ReadCharIgnoreWhitespace(); + if(c != expectedChar) + { + if(c == endOfStreamChar) + throw new FormatException("End of stream reached when expecting '"+expectedChar+"'."); + else + throw new FormatException("Expected \'"+expectedChar+"\', found \'"+c+"\'."); + } + return c; + } + + private bool ReadQuotationMarkOrNullIgnoreWhitespace() + { + char c = ReadCharIgnoreWhitespace(false); // Don't read trailing whitespace as this is the value. + + if(c == 'n') + { + var chars = new char[3]; + baseReader.ReadBlock(chars, 0, 3); + if((char)chars[0] == 'u' && (char)chars[1] == 'l' && (char)chars[2] == 'l') + return true; + } + else if(!IsQuotationMark(c)) + { + if(c == endOfStreamChar) + throw new FormatException("End of stream reached when expecting quotation mark."); + else + throw new FormatException("Expected quotation mark, found \'"+c+"\'."); + } + return false; + } + + /* + * Peeks the next char in the stream, ignoring leading whitespace, but not trailing whitespace. + */ + private char PeekCharIgnoreWhitespace(char expectedChar) + { + char c = PeekCharIgnoreWhitespace(); + if(c != expectedChar) + { + if(c == endOfStreamChar) + throw new FormatException("End of stream reached while peeking, when expecting '"+expectedChar+"'."); + else + throw new FormatException("Expected \'"+expectedChar+"\', found \'"+c+"\'."); + } + return c; + } + + /* + * Peeks the next char in the stream, ignoring leading whitespace, but not trailing whitespace. + * Throws an error if the char isn't equal to the one specificed as a parameter. + */ + private char PeekCharIgnoreWhitespace() + { + char c; + // Skip leading whitespace and read char. + while(IsWhiteSpace(c = (char)baseReader.Peek())) + baseReader.Read(); + return c; + } + + // Skips all whitespace immediately after the current position. + private void SkipWhiteSpace() + { + while(IsWhiteSpace((char)baseReader.Peek())) + baseReader.Read(); + } + + private void SkipOpeningBraceOfFile() + { + // Skip the whitespace and '{' at the beginning of the JSON file. + char firstChar = ReadCharIgnoreWhitespace(); + if(firstChar != '{') // If first char isn't '{', it's not valid JSON. + throw new FormatException("File is not valid JSON. Expected '{' at beginning of file, but found '"+firstChar+"'."); + } + + private static bool IsWhiteSpace(char c) + { + return (c == ' ' || c == '\t' || c == '\n' || c == '\r'); + } + + private static bool IsOpeningBrace(char c) + { + return (c == '{' || c == '['); + } + + private static bool IsEndOfValue(char c) + { + return (c == '}' || c == ' ' || c == '\t' || c == ']' || c == ',' || c== ':' || c == endOfStreamChar || c == '\n' || c == '\r'); + } + + private static bool IsTerminator(char c) + { + return (c == '}' || c == ']'); + } + + private static bool IsQuotationMark(char c) + { + return c == '\"' || c == '“' || c == '”'; + } + + private static bool IsEndOfStream(char c) + { + return c == endOfStreamChar; + } + + /* + * Reads a value (i.e. non-string, non-object) from the stream as a string. + * Used mostly in Read_[type]() methods. + */ + private string GetValueString() + { + StringBuilder builder = new StringBuilder(); + + while(!IsEndOfValue(PeekCharIgnoreWhitespace())) + builder.Append((char)baseReader.Read()); + + // If it's an empty value, return null. + if(builder.Length == 0) + return null; + return builder.ToString(); + } + + #endregion + + #region Primitive Read() Methods. + + internal override string Read_string() + { + if(ReadQuotationMarkOrNullIgnoreWhitespace()) + return null; + char c; + + StringBuilder sb = new StringBuilder(); + + while(!IsQuotationMark((c = (char)baseReader.Read()))) + { + // If escape mark is found, generate correct escaped character. + if(c == '\\') + { + c = (char)baseReader.Read(); + if(IsEndOfStream(c)) + throw new FormatException("Reached end of stream while trying to read string literal."); + + switch(c) + { + case 'b': + c = '\b'; + break; + case 'f': + c = '\f'; + break; + case 'n': + c = '\n'; + break; + case 'r': + c = '\r'; + break; + case 't': + c = '\t'; + break; + default: + break; + } + } + sb.Append(c); + } + return sb.ToString(); + } + + internal override long Read_ref() + { + if (ES3ReferenceMgr.Current == null) + throw new InvalidOperationException("An Easy Save 3 Manager is required to load references. To add one to your scene, exit playmode and go to Tools > Easy Save 3 > Add Manager to Scene"); + if (IsQuotationMark(PeekCharIgnoreWhitespace())) + return long.Parse(Read_string()); + return Read_long(); + } + + internal override char Read_char() { return char.Parse( Read_string()); } + internal override float Read_float() { return float.Parse( GetValueString(), CultureInfo.InvariantCulture); } + internal override int Read_int() { return int.Parse( GetValueString()); } + internal override bool Read_bool() { return bool.Parse( GetValueString()); } + internal override decimal Read_decimal() { return decimal.Parse( GetValueString(), CultureInfo.InvariantCulture); } + internal override double Read_double() { return double.Parse( GetValueString(), CultureInfo.InvariantCulture); } + internal override long Read_long() { return long.Parse( GetValueString()); } + internal override ulong Read_ulong() { return ulong.Parse( GetValueString()); } + internal override uint Read_uint() { return uint.Parse( GetValueString()); } + internal override byte Read_byte() { return (byte)int.Parse( GetValueString()); } + internal override sbyte Read_sbyte() { return (sbyte)int.Parse( GetValueString()); } + internal override short Read_short() { return (short)int.Parse( GetValueString()); } + internal override ushort Read_ushort() { return (ushort)int.Parse( GetValueString()); } + + internal override byte[] Read_byteArray(){ return System.Convert.FromBase64String(Read_string()); } + + #endregion + + + public override void Dispose() + { + baseReader.Dispose(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3JSONReader.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3JSONReader.cs.meta new file mode 100644 index 0000000..663a6bb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3JSONReader.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8757682770a6c4537a3dcbed278277bc +timeCreated: 1499764822 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3Reader.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3Reader.cs new file mode 100644 index 0000000..51d9653 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3Reader.cs @@ -0,0 +1,459 @@ +using UnityEngine; +using System.IO; +using System.Collections; +using System.Collections.Generic; +using System; +using System.ComponentModel; +using ES3Types; +using ES3Internal; + +public abstract class ES3Reader : System.IDisposable +{ + /// The settings used to create this reader. + public ES3Settings settings; + + protected int serializationDepth = 0; + + #region ES3Reader Abstract Methods + + internal abstract int Read_int(); + internal abstract float Read_float(); + internal abstract bool Read_bool(); + internal abstract char Read_char(); + internal abstract decimal Read_decimal(); + internal abstract double Read_double(); + internal abstract long Read_long(); + internal abstract ulong Read_ulong(); + internal abstract byte Read_byte(); + internal abstract sbyte Read_sbyte(); + internal abstract short Read_short(); + internal abstract ushort Read_ushort(); + internal abstract uint Read_uint(); + internal abstract string Read_string(); + internal abstract byte[] Read_byteArray(); + internal abstract long Read_ref(); + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public abstract string ReadPropertyName(); + + protected abstract Type ReadKeyPrefix(bool ignore = false); + protected abstract void ReadKeySuffix(); + internal abstract byte[] ReadElement(bool skip=false); + + /// Disposes of the reader and it's underlying stream. + public abstract void Dispose(); + + // Seeks to the given key. Note that the stream position will not be reset. + internal virtual bool Goto(string key) + { + if (key == null) + throw new ArgumentNullException("Key cannot be NULL when loading data."); + + string currentKey; + while ((currentKey = ReadPropertyName()) != key) + { + if (currentKey == null) + return false; + Skip(); + } + return true; + } + + internal virtual bool StartReadObject() + { + serializationDepth++; + return false; + } + + internal virtual void EndReadObject() + { + serializationDepth--; + } + + internal abstract bool StartReadDictionary(); + internal abstract void EndReadDictionary(); + internal abstract bool StartReadDictionaryKey(); + internal abstract void EndReadDictionaryKey(); + internal abstract void StartReadDictionaryValue(); + internal abstract bool EndReadDictionaryValue(); + + internal abstract bool StartReadCollection(); + internal abstract void EndReadCollection(); + internal abstract bool StartReadCollectionItem(); + internal abstract bool EndReadCollectionItem(); + + #endregion + + internal ES3Reader(ES3Settings settings, bool readHeaderAndFooter = true) + { + this.settings = settings; + } + + // If this is not null, the next call to the Properties will return this name. + internal string overridePropertiesName = null; + /// Allows you to enumerate over each field name. This should only be used within an ES3Type file. + public virtual ES3ReaderPropertyEnumerator Properties + { + get + { + return new ES3ReaderPropertyEnumerator (this); + } + } + + internal virtual ES3ReaderRawEnumerator RawEnumerator + { + get + { + return new ES3ReaderRawEnumerator (this); + } + } + + /* + * Skips the current object in the stream. + * Stream position should be somewhere before the opening brace for the object. + * When this method successfully exits, it will be on the closing brace for the object. + */ + /// Skips the current object in the stream. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual void Skip() + { + ReadElement(true); + } + + /// Reads a value of type T from the reader. + public virtual T Read() + { + return Read(ES3TypeMgr.GetOrCreateES3Type(typeof(T))); + } + + /// Reads a value of type T from the reader into an existing object. + /// The object we want to read our value into. + public virtual void ReadInto(object obj) + { + ReadInto(obj, ES3TypeMgr.GetOrCreateES3Type(typeof(T))); + } + + /// Reads a property (i.e. a property name and value) from the reader, ignoring the property name and only returning the value. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public T ReadProperty() + { + return ReadProperty(ES3TypeMgr.GetOrCreateES3Type(typeof(T))); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public T ReadProperty(ES3Type type) + { + ReadPropertyName(); + return Read(type); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public long ReadRefProperty() + { + ReadPropertyName(); + return Read_ref(); + } + + internal Type ReadType() + { + return ES3Reflection.GetType(Read(ES3Type_string.Instance)); + } + + /// Sets the value of a private property on an object. + /// The name of the property we want to set. + /// The value we want to set the property to. + /// The object containing the property we want to set. + /// The objectContainingProperty object. This is helpful if you're setting a private property on a struct or other immutable type and need to return the boxed value. + public object SetPrivateProperty(string name, object value, object objectContainingProperty) + { + var property = ES3Reflection.GetES3ReflectedProperty(objectContainingProperty.GetType(), name); + if (property.IsNull) + throw new MissingMemberException("A private property named " + name + " does not exist in the type " + objectContainingProperty.GetType()); + property.SetValue(objectContainingProperty, value); + return objectContainingProperty; + } + + /// Sets the value of a private field on an object. + /// The name of the field we want to set. + /// The value we want to set the field to. + /// The object containing the field we want to set. + /// The objectContainingField object. This is helpful if you're setting a private property on a struct or other immutable type and need to return the boxed value. + public object SetPrivateField(string name, object value, object objectContainingField) + { + var field = ES3Reflection.GetES3ReflectedMember(objectContainingField.GetType(), name); + if(field.IsNull) + throw new MissingMemberException("A private field named "+ name + " does not exist in the type "+objectContainingField.GetType()); + field.SetValue(objectContainingField, value); + return objectContainingField; + } + + #region Read(key) & Read(key, obj) methods + + /// Reads a value from the reader with the given key. + /// The key which uniquely identifies our value. + public virtual T Read(string key) + { + if(!Goto(key)) + throw new KeyNotFoundException("Key \"" + key + "\" was not found in file \""+settings.FullPath+"\". Use Load(key, defaultValue) if you want to return a default value if the key does not exist."); + + Type type = ReadTypeFromHeader(); + + T obj = Read(ES3TypeMgr.GetOrCreateES3Type(type)); + + //ReadKeySuffix(); //No need to read key suffix as we're returning. Doing so would throw an error at this point for BinaryReaders. + return obj; + } + + /// Reads a value from the reader with the given key, returning the default value if the key does not exist. + /// The key which uniquely identifies our value. + /// The value we want to return if this key does not exist in the reader. + public virtual T Read(string key, T defaultValue) + { + if(!Goto(key)) + return defaultValue; + + Type type = ReadTypeFromHeader(); + T obj = Read(ES3TypeMgr.GetOrCreateES3Type(type)); + + //ReadKeySuffix(); //No need to read key suffix as we're returning. Doing so would throw an error at this point for BinaryReaders. + return obj; + } + + /// Reads a value from the reader with the given key into the provided object. + /// The key which uniquely identifies our value. + /// The object we want to load the value into. + public virtual void ReadInto(string key, T obj) where T : class + { + if(!Goto(key)) + throw new KeyNotFoundException("Key \"" + key + "\" was not found in file \""+settings.FullPath+"\""); + + Type type = ReadTypeFromHeader(); + + ReadInto(obj, ES3TypeMgr.GetOrCreateES3Type(type)); + + //ReadKeySuffix(); //No need to read key suffix as we're returning. Doing so would throw an error at this point for BinaryReaders. + } + + protected virtual void ReadObject(object obj, ES3Type type) + { + // Check for null. + if(StartReadObject()) + return; + + type.ReadInto(this, obj); + + EndReadObject(); + } + + protected virtual T ReadObject(ES3Type type) + { + if(StartReadObject()) + return default(T); + + object obj = type.Read(this); + + EndReadObject(); + return (T)obj; + } + + + #endregion + + #region Read(ES3Type) & Read(obj,ES3Type) methods + + /* + * Parses the next JSON Object in the stream (i.e. must be between '{' and '}' chars). + * If the first character in the Stream is not a '{', it will throw an error. + * Will also read the terminating '}'. + * If we have reached the end of stream, it will return null. + */ + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual T Read(ES3Type type) + { + if (type == null || type.isUnsupported) + throw new NotSupportedException("Type of " + type + " is not currently supported, and could not be loaded using reflection."); + else if (type.isPrimitive) + return (T)type.Read(this); + else if (type.isCollection) + return (T)((ES3CollectionType)type).Read(this); + else if (type.isDictionary) + return (T)((ES3DictionaryType)type).Read(this); + else + return ReadObject(type); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual void ReadInto(object obj, ES3Type type) + { + if(type == null || type.isUnsupported) + throw new NotSupportedException("Type of "+obj.GetType()+" is not currently supported, and could not be loaded using reflection."); + + else if(type.isCollection) + ((ES3CollectionType)type).ReadInto(this, obj); + else if(type.isDictionary) + ((ES3DictionaryType)type).ReadInto(this, obj); + else + ReadObject(obj, type); + } + + + #endregion + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal Type ReadTypeFromHeader() + { + // Check whether we need to determine the type by reading the header. + if(typeof(T) == typeof(object)) + return ReadKeyPrefix(); + else if(settings.typeChecking) + { + Type type = ReadKeyPrefix(); + + if(type == null) + throw new TypeLoadException("Trying to load data of type " + typeof(T) + ", but the type of data contained in file no longer exists. This may be because the type has been removed from your project or renamed."); + else if (type != typeof(T)) + throw new InvalidOperationException("Trying to load data of type " + typeof(T) + ", but data contained in file is type of " + type + "."); + + return type; + } + else + { + ReadKeyPrefix(true); + return typeof(T); + } + } + + /// Creates a new ES3Reader and loads the default file into it. + public static ES3Reader Create() + { + return Create(new ES3Settings()); + } + + /// Creates a new ES3Reader and loads a file in storage into it. + /// The relative or absolute path of the file we want to load into the reader. + public static ES3Reader Create(string filePath) + { + return Create(new ES3Settings(filePath)); + } + + /// Creates a new ES3Reader and loads a file in storage into it. + /// The relative or absolute path of the file we want to load into the reader. + /// The settings we want to use to override the default settings. + public static ES3Reader Create(string filePath, ES3Settings settings) + { + return Create(new ES3Settings(filePath, settings)); + } + + /// Creates a new ES3Reader and loads a file in storage into it. + /// The settings we want to use to override the default settings. + public static ES3Reader Create(ES3Settings settings) + { + Stream stream = ES3Stream.CreateStream(settings, ES3FileMode.Read); + if(stream == null) + return null; + + // Get the baseWriter using the given Stream. + if (settings.format == ES3.Format.JSON) + return new ES3JSONReader(stream, settings); + return null; + } + + /// Creates a new ES3Reader and loads the bytes provided into it. + public static ES3Reader Create(byte[] bytes) + { + return Create(bytes, new ES3Settings()); + } + + /// Creates a new ES3Reader and loads the bytes provided into it. + /// The settings we want to use to override the default settings. + public static ES3Reader Create(byte[] bytes, ES3Settings settings) + { + Stream stream = ES3Stream.CreateStream(new MemoryStream(bytes), settings, ES3FileMode.Read); + if(stream == null) + return null; + + // Get the baseWriter using the given Stream. + if(settings.format == ES3.Format.JSON) + return new ES3JSONReader(stream, settings); + return null; + } + + internal static ES3Reader Create(Stream stream, ES3Settings settings) + { + stream = ES3Stream.CreateStream(stream, settings, ES3FileMode.Read); + + // Get the baseWriter using the given Stream. + if(settings.format == ES3.Format.JSON) + return new ES3JSONReader(stream, settings); + return null; + } + + internal static ES3Reader Create(Stream stream, ES3Settings settings, bool readHeaderAndFooter) + { + // Get the baseWriter using the given Stream. + if(settings.format == ES3.Format.JSON) + return new ES3JSONReader(stream, settings, readHeaderAndFooter); + return null; + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public class ES3ReaderPropertyEnumerator + { + public ES3Reader reader; + + public ES3ReaderPropertyEnumerator(ES3Reader reader) + { + this.reader = reader; + } + + public IEnumerator GetEnumerator() + { + string propertyName; + while(true) + { + // Allows us to repeat a property name or insert one of our own. + if(reader.overridePropertiesName != null) + { + string tempName = reader.overridePropertiesName; + reader.overridePropertiesName = null; + yield return tempName; + } + else + { + if((propertyName = reader.ReadPropertyName()) == null) + yield break; + yield return propertyName; + } + } + } + } + + [EditorBrowsable(EditorBrowsableState.Never)] + public class ES3ReaderRawEnumerator + { + public ES3Reader reader; + + public ES3ReaderRawEnumerator(ES3Reader reader) + { + this.reader = reader; + } + + public IEnumerator GetEnumerator() + { + while(true) + { + string key = reader.ReadPropertyName(); + if(key == null) + yield break; + + Type type = reader.ReadTypeFromHeader(); + + byte[] bytes = reader.ReadElement(); + + reader.ReadKeySuffix(); + + if(type != null) + yield return new KeyValuePair(key, new ES3Data(type, bytes)); + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3Reader.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3Reader.cs.meta new file mode 100644 index 0000000..48dcb67 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3Reader.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f511cfa2663a045aeac7dfe13754efba +timeCreated: 1519132300 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3XMLReader.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3XMLReader.cs new file mode 100644 index 0000000..3b73629 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3XMLReader.cs @@ -0,0 +1,5 @@ + +public class ES3XMLReader +{ + // Not Implemented +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3XMLReader.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3XMLReader.cs.meta new file mode 100644 index 0000000..b824bde --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Readers/ES3XMLReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2ef972c40e0163f4c873b7e18c0e24fb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Referencing.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Referencing.meta new file mode 100644 index 0000000..d3adddc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Referencing.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8db2646014f047848b3a06fed0823555 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Referencing/ES3GlobalReferences.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Referencing/ES3GlobalReferences.cs new file mode 100644 index 0000000..eb09e31 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Referencing/ES3GlobalReferences.cs @@ -0,0 +1,129 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace ES3Internal +{ + public class ES3GlobalReferences : ScriptableObject + { +#if !UNITY_EDITOR || ES3GLOBAL_DISABLED + public static ES3GlobalReferences Instance{ get{ return null; } } + public UnityEngine.Object Get(long id){return null;} + public long GetOrAdd(UnityEngine.Object obj){return -1;} + public void RemoveInvalidKeys(){} +#else + +#if ES3GLOBAL_DISABLED + private static bool useGlobalReferences = false; +#else + private static bool useGlobalReferences = true; +#endif + + private const string globalReferencesPath = "ES3/ES3GlobalReferences"; + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public ES3RefIdDictionary refId = new ES3RefIdDictionary(); + + private static ES3GlobalReferences _globalReferences = null; + public static ES3GlobalReferences Instance + { + get + { + if (Application.isPlaying) + return null; + + if (!useGlobalReferences) + return null; + + if (_globalReferences == null) + { + _globalReferences = Resources.Load(globalReferencesPath); + + if (_globalReferences == null) + { + _globalReferences = ScriptableObject.CreateInstance(); + + // If this is the version being submitted to the Asset Store, don't include ES3Defaults. + if (Application.productName.Contains("ES3 Release")) + { + Debug.Log("This has been identified as a release build as the title contains 'ES3 Release', so ES3GlobalReferences will not be created."); + return _globalReferences; + } + + ES3Settings.CreateDefaultSettingsFolder(); + UnityEditor.AssetDatabase.CreateAsset(_globalReferences, PathToGlobalReferences()); + UnityEditor.AssetDatabase.SaveAssets(); + } + + } + + return _globalReferences; + } + } + + private long Get(UnityEngine.Object obj) + { + if (obj == null) + return -1; + + long id; + if (!refId.TryGetValue(obj, out id)) + return -1; + return id; + } + + public UnityEngine.Object Get(long id) + { + foreach(var kvp in refId) + if (kvp.Value == id) + return kvp.Key; + return null; + } + + public void RemoveInvalidKeys() + { + var newRefId = new ES3RefIdDictionary(); + foreach (var kvp in refId) + { + var obj = kvp.Key; + if (obj == null) + continue; + + if ((((obj.hideFlags & HideFlags.DontSave) == HideFlags.DontSave) || + ((obj.hideFlags & HideFlags.DontSaveInBuild) == HideFlags.DontSaveInBuild) || + ((obj.hideFlags & HideFlags.DontSaveInEditor) == HideFlags.DontSaveInEditor) || + ((obj.hideFlags & HideFlags.HideAndDontSave) == HideFlags.HideAndDontSave))) + { + var type = obj.GetType(); + // Meshes are marked with HideAndDontSave, but shouldn't be ignored. + if (type != typeof(Mesh) && type != typeof(Material)) + continue; + } + newRefId[obj] = kvp.Value; + } + refId = newRefId; + } + + public long GetOrAdd(UnityEngine.Object obj) + { + var id = Get(obj); + + // Only add items to global references when it's not playing. + if (!Application.isPlaying && id == -1 && UnityEditor.AssetDatabase.Contains(obj) && ES3ReferenceMgr.CanBeSaved(obj)) + { + id = ES3ReferenceMgrBase.GetNewRefID(); + refId.Add(obj, id); + + UnityEditor.EditorUtility.SetDirty(this); + } + + return id; + } + + private static string PathToGlobalReferences() + { + return ES3Settings.PathToEasySaveFolder() + "Resources/" + globalReferencesPath +".asset"; + } +#endif + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Referencing/ES3GlobalReferences.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Referencing/ES3GlobalReferences.cs.meta new file mode 100644 index 0000000..591df09 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Referencing/ES3GlobalReferences.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e6b16dc7c203450459bb86e24305f9ca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots.meta new file mode 100644 index 0000000..64074af --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 25ed03dc31ee4cf4891c6c5e299f9944 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3CreateSlot.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3CreateSlot.cs new file mode 100644 index 0000000..849c1b9 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3CreateSlot.cs @@ -0,0 +1,82 @@ +#if ES3_TMPRO && ES3_UGUI + +using System; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +/// +/// A script attached to the Create Slot button to manage slot creation. +/// +public class ES3CreateSlot : MonoBehaviour +{ + [Tooltip("The button used to bring up the 'Create Slot' dialog.")] + public Button createButton; + [Tooltip("The ES3SlotDialog Component of the Create Slot dialog")] + public ES3SlotDialog createDialog; + [Tooltip("The TMP_Text input text field of the create slot dialog.")] + public TMP_InputField inputField; + [Tooltip("The ES3SlotManager this Create Slot Dialog belongs to.")] + public ES3SlotManager mgr; + + protected virtual void OnEnable() + { + // Whether we should show or hide this Create Slot button based on the settings in the slot manager. + gameObject.SetActive(mgr.showCreateSlotButton); + + // Make it so the Create Slot button brings up the Create Slot dialog. + createButton.onClick.AddListener(() => createDialog.gameObject.SetActive(true)); + + // Add listener to the confirmation button. + createDialog.confirmButton.onClick.AddListener(TryCreateNewSlot); + } + + protected virtual void OnDisable() + { + // Make sure the text field is empty for next time. + inputField.text = string.Empty; + // Remove all listeners. + createButton.onClick.RemoveAllListeners(); + createDialog.confirmButton.onClick.RemoveAllListeners(); + } + + // Called when the Create button is pressed in the Create New Slot dialog. + public virtual void TryCreateNewSlot() + { + // If the user hasn't specified a name, throw an error. + // Note that no other validation of the name is a required as this is handled using a REGEX in the TMP_InputField Component. + if (string.IsNullOrEmpty(inputField.text)) + { + mgr.ShowErrorDialog("You must specify a name for your save slot"); + return; + } + + // If a slot with this name already exists, require the user to enter a different name. + if (ES3.FileExists(mgr.GetSlotPath(inputField.text))) + { + mgr.ShowErrorDialog("A slot already exists with this name. Please choose a different name."); + return; + } + + // Create the slot. + CreateNewSlot(inputField.text); + // Clear the input field so the value isn't there when we reopen it. + inputField.text = ""; + // Hide the dialog. + createDialog.gameObject.SetActive(false); + } + + + // Creates a new slot by instantiating it in the UI and creating a save file for it. + protected virtual void CreateNewSlot(string slotName) + { + // Get the current timestamp. + var creationTimestamp = DateTime.Now; + // Create the slot in the UI. + var slot = mgr.InstantiateSlot(slotName, creationTimestamp); + // Move the slot to the top of the list. + slot.transform.SetSiblingIndex(1); + } +} + +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3CreateSlot.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3CreateSlot.cs.meta new file mode 100644 index 0000000..33c82c8 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3CreateSlot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2f4ce35662bad7843b3b34f527102454 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3Slot.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3Slot.cs new file mode 100644 index 0000000..2239e2d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3Slot.cs @@ -0,0 +1,150 @@ +#if ES3_TMPRO && ES3_UGUI + +using TMPro; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.UI; + +/// +/// A Component added to a save slot to allow it to be selected, deleted, and un-deleted. +/// +public class ES3Slot : MonoBehaviour +{ + [Tooltip("The text label containing the slot name.")] + public TMP_Text nameLabel; + [Tooltip("The text label containing the last updated timestamp for the slot.")] + public TMP_Text timestampLabel; + + [Tooltip("The confirmation dialog to show if showConfirmationIfExists is true.")] + public GameObject confirmationDialog; + + // The manager this slot belongs to. This is set by the manager which creates it. + public ES3SlotManager mgr; + + [Tooltip("The button for selecting this slot.")] + public Button selectButton; + [Tooltip("The button for deleting this slot.")] + public Button deleteButton; + [Tooltip("The button for undoing the deletion of this slot.")] + public Button undoButton; + + // Whether this slot has been marked for deletion. + protected bool markedForDeletion = false; + +#region Initialisation and Clean-up + + // See Unity's docs for more info: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnEnable.html + public virtual void OnEnable() + { + // Add the button press listeners. + selectButton.onClick.AddListener(TrySelectSlot); + deleteButton.onClick.AddListener(MarkSlotForDeletion); + undoButton.onClick.AddListener(UnmarkSlotForDeletion); + } + + // See Unity's docs for more info: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDisable.html + public virtual void OnDisable() + { + // Remove all button press listeners. + selectButton.onClick.RemoveAllListeners(); + deleteButton.onClick.RemoveAllListeners(); + undoButton.onClick.RemoveAllListeners(); + + // If this slot is marked for deletion, delete it. + if (markedForDeletion) + DeleteSlot(); + } + +#endregion + +#region Select methods + + // Called when the Select Slot button is pressed. + protected virtual void TrySelectSlot() + { + // Manage the confirmation dialog if necessary. + if(mgr.showConfirmationIfExists) + { + if (confirmationDialog == null) + Debug.LogError("The confirmationDialog field of this ES3SelectSlot Component hasn't been set in the inspector.", this); + + // Display a confirmation dialog if we're overwriting a save slot. + if (ES3.FileExists(GetSlotPath())) + { + // Show the dialog. + confirmationDialog.SetActive(true); + // Register the event for the confirmation button. + confirmationDialog.GetComponent().confirmButton.onClick.AddListener(SelectSlot); + return; + } + } + + SelectSlot(); + } + + // Selects a slot and calls post-selection events if applicable. + protected virtual void SelectSlot() + { + // Hide the confirmation dialog if it's open. + confirmationDialog?.SetActive(false); + + // Set the path used by Auto Save. + ES3SlotManager.selectedSlotPath = GetSlotPath(); + + // When the default path used by Easy Save's methods. + ES3Settings.defaultSettings.path = ES3SlotManager.selectedSlotPath; + + // If we've specified an event to be called after the user selects a slot, invoke it. + mgr.onAfterSelectSlot?.Invoke(); + + // If we've specified a scene to load after the user selects a slot, load it. + if (!string.IsNullOrEmpty(mgr.loadSceneAfterSelectSlot)) + SceneManager.LoadScene(mgr.loadSceneAfterSelectSlot); + } + +#endregion + +#region Delete methods + + // Marks a slot to be deleted and displays an undo button. + protected virtual void MarkSlotForDeletion() + { + markedForDeletion = true; + // Make the Undo button visible and hide the Delete button. + undoButton.gameObject.SetActive(true); + deleteButton.gameObject.SetActive(false); + } + + // Unmarks a slot to be deleted and displays an delete button again. + protected virtual void UnmarkSlotForDeletion() + { + markedForDeletion = false; + // Make the Undo button visible and hide the Delete button. + undoButton.gameObject.SetActive(false); + deleteButton.gameObject.SetActive(true); + } + + // Deletes a save slot. + protected virtual void DeleteSlot() + { + // Delete the file linked to this slot. + ES3.DeleteFile(GetSlotPath()); + // Destroy this slot. + Destroy(this.gameObject); + } + +#endregion + +#region Utility methods + + // Gets the relative file path of the slot with the given slot name. + public virtual string GetSlotPath() + { + // Get the slot path from the manager. + return mgr.GetSlotPath(nameLabel.text); + } + +#endregion +} + +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3Slot.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3Slot.cs.meta new file mode 100644 index 0000000..c230458 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3Slot.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a276080975dbd4a46b4ef11085e19980 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotDialog.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotDialog.cs new file mode 100644 index 0000000..5335a4c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotDialog.cs @@ -0,0 +1,29 @@ +#if ES3_TMPRO && ES3_UGUI + +using UnityEngine; +using UnityEngine.UI; + +/// +/// A script attached to the error dialog and confirm dialog to provide events which other scripts can receive. +/// +public class ES3SlotDialog : MonoBehaviour +{ + [Tooltip("The UnityEngine.UI.Button Component for the Confirm button.")] + public Button confirmButton; + [Tooltip("The UnityEngine.UI.Button Component for the Cancel button.")] + public Button cancelButton; + + protected virtual void OnEnable() + { + // Make it so that the cancel button deactivates the dialog. + cancelButton.onClick.AddListener(() => gameObject.SetActive(false)); + } + + protected virtual void OnDisable() + { + // Remove any listeners when disabling this dialog. + cancelButton.onClick.RemoveAllListeners(); + } +} + +#endif diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotDialog.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotDialog.cs.meta new file mode 100644 index 0000000..3baa4d7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotDialog.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 343f4b43e9b862d42873f3e0af2c1f7e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotManager.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotManager.cs new file mode 100644 index 0000000..5c90346 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotManager.cs @@ -0,0 +1,208 @@ +using UnityEngine; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +#if ES3_TMPRO && ES3_UGUI + +using System; +using System.Collections.Generic; +using System.Linq; +using System.IO; +using TMPro; +using System.Text.RegularExpressions; +using UnityEngine.Events; +using UnityEngine.SceneManagement; + +public class ES3SlotManager : MonoBehaviour +{ + [Tooltip("Shows a confirmation if this slot already exists when we select it.")] + public bool showConfirmationIfExists = true; + [Tooltip("Whether the Create new slot button should be visible.")] + public bool showCreateSlotButton = true; + + [Space(16)] + + [Tooltip("The name of a scene to load after the user chooses a slot.")] + public string loadSceneAfterSelectSlot; + + [Space(16)] + + [Tooltip("An event called after a slot is selected, but before the scene specified by loadSceneAfterSelectSlot is loaded.")] + public UnityEvent onAfterSelectSlot; + + [Space(16)] + + [Tooltip("The subfolder we want to store our save files in. If this is a relative path, it will be relative to Application.persistentDataPath.")] + public string slotDirectory = "slots/"; + [Tooltip("The extension we want to use for our save files.")] + public string slotExtension = ".es3"; + + [Space(16)] + + [Tooltip("The template we'll instantiate to create our slots.")] + public GameObject slotTemplate; + [Tooltip("The dialog box for creating a new slot.")] + public GameObject createDialog; + [Tooltip("The dialog box for displaying an error to the user.")] + public GameObject errorDialog; + + // The relative path of the slot which has been selected, or null if none have been selected. + public static string selectedSlotPath = null; + + // A list of slots which have been created. + protected List slots = new List(); + + // If a file doesn't have a timestamp, it will return have this DateTime. + static DateTime falseDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + + // See Unity's docs for more info: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnEnable.html + protected virtual void OnEnable() + { + // Deactivate the slot template so it's not visible. + slotTemplate.SetActive(false); + // Destroy any existing slots and start from fresh if necessary. + DestroySlots(); + // Create our save slots if any exist. + InstantiateSlots(); + } + + // Finds the save slot files and instantiates a save slot for each of them. + protected virtual void InstantiateSlots() + { + // A list used to store our save slots so we can order them. + List<(string Name, DateTime Timestamp)> slots = new List<(string Name, DateTime Timestamp)>(); + + // If there are no slots to load, do nothing. + if (!ES3.DirectoryExists(slotDirectory)) + return; + + // Put each of our slots into a List so we can order them. + foreach (var file in ES3.GetFiles(slotDirectory)) + { + // Get the slot name, which is the filename without the extension. + var slotName = Path.GetFileNameWithoutExtension(file); + // Get the timestamp so that we can display this to the user and use it to order the slots. + var timestamp = ES3.GetTimestamp(GetSlotPath(slotName)); + // Add the data to the slot list. + slots.Add((Name: slotName, Timestamp: timestamp)); + } + + // Now order the slots by the timestamp. + slots = slots.OrderByDescending(x => x.Timestamp).ToList(); + + // Now create the slots. + foreach (var slot in slots) + InstantiateSlot(slot.Name, slot.Timestamp); + } + + // Instantiates a single save slot with a given slot name and timestamp. + public virtual GameObject InstantiateSlot(string slotName, DateTime timestamp) + { + // Create an instance of our slot. + var slot = Instantiate(slotTemplate, slotTemplate.transform.parent); + + // Add it to our slot list. + slots.Add(slot); + + // Ensure that we make it active as the template will be inactive. + slot.SetActive(true); + + var es3SelectSlot = slot.GetComponent(); + es3SelectSlot.nameLabel.text = slotName.Replace('_', ' '); + + // If the file doesn't have a timestamp, don't display the timestamp. + if (timestamp == falseDateTime) + es3SelectSlot.timestampLabel.text = ""; + // Otherwise, set the label for the timestamp. + else + es3SelectSlot.timestampLabel.text = $"{timestamp.ToString("yyyy-MM-dd")}\n{timestamp.ToString("HH:mm:ss")}"; + + return slot; + } + + // Shows the dialog displaying an error to the user. + public virtual void ShowErrorDialog(string errorMessage) + { + errorDialog.transform.Find("Dialog Box/Message").GetComponent().text = errorMessage; + errorDialog.SetActive(true); + } + + #region Utility Methods + + // Closes the slot window. + public virtual void Close() + { + gameObject.SetActive(false); + } + + // Destroys all slots which have been created, but doesn't delete their underlying save files. + protected virtual void DestroySlots() + { + foreach (var slot in slots) + Destroy(slot); + } + + // Gets the relative file path of the slot with the given slot name. + public virtual string GetSlotPath(string slotName) + { + // We convert any whitespace characters to underscores at this point to make the file more portable. + return slotDirectory + Regex.Replace(slotName, @"\s+", "_") + slotExtension; + } + #endregion +} +#endif + + +#if UNITY_EDITOR +// Manages the context menu items for creating the slots. +public class ES3SlotMenuItems : MonoBehaviour +{ + + [MenuItem("GameObject/Easy Save 3/Add Save Slots to Scene", false, 33)] + [MenuItem("Assets/Easy Save 3/Add Save Slots to Scene", false, 33)] + [MenuItem("Tools/Easy Save 3/Add Save Slots to Scene", false, 150)] + public static void AddSaveSlotsToScene() + { +#if !ES3_TMPRO || !ES3_UGUI + EditorUtility.DisplayDialog("Cannot create save slots", "The 'TextMeshPro' and 'Unity UI' packages must be installed in Window > Package Manager to use Easy Save's slot functionality.", "Ok"); +#else + var mgr = AddSlotsToScene(); + mgr.showConfirmationIfExists = true; + mgr.showCreateSlotButton = true; +#endif + } + + [MenuItem("GameObject/Easy Save 3/Add Load Slots to Scene", false, 33)] + [MenuItem("Assets/Easy Save 3/Add Load Slots to Scene", false, 33)] + [MenuItem("Tools/Easy Save 3/Add Load Slots to Scene", false, 150)] + public static void AddLoadSlotsToScene() + { +#if !ES3_TMPRO || !ES3_UGUI + EditorUtility.DisplayDialog("Cannot create save slots", "The 'TextMeshPro' and 'Unity UI' packages must be installed in Window > Package Manager to use Easy Save's slot functionality.", "Ok"); +#else + var mgr = AddSlotsToScene(); + mgr.showConfirmationIfExists = false; + mgr.showCreateSlotButton = false; + mgr.GetComponentInChildren().gameObject.SetActive(false); +#endif + } + +#if ES3_TMPRO && ES3_UGUI + static ES3SlotManager AddSlotsToScene() + { + if (!SceneManager.GetActiveScene().isLoaded) + EditorUtility.DisplayDialog("Could not add manager to scene", "Could not add Save Slots to scene because there is not currently a scene open.", "Ok"); + + var pathToEasySaveFolder = ES3Settings.PathToEasySaveFolder(); + + var prefab = AssetDatabase.LoadAssetAtPath(pathToEasySaveFolder + "Scripts/Save Slots/Easy Save Slots Canvas.prefab"); + var instance = (GameObject)Instantiate(prefab); + Undo.RegisterCreatedObjectUndo(instance, "Added Save Slots to Scene"); + + return instance.GetComponentInChildren(); + } +#endif +} +#endif diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotManager.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotManager.cs.meta new file mode 100644 index 0000000..676d668 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Save Slots/ES3SlotManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3de4c36c55c98254bb7ff7a0e8abb993 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings.meta new file mode 100644 index 0000000..3dc3adb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 56b5103c4fdfa1749a8d83f5a361f4fb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3DefaultSettings.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3DefaultSettings.cs new file mode 100644 index 0000000..26e08ba --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3DefaultSettings.cs @@ -0,0 +1,13 @@ +using UnityEngine; +using System.Collections.Generic; + +namespace ES3Internal +{ + public class ES3DefaultSettings : MonoBehaviour + { + [SerializeField] + public ES3SerializableSettings settings = null; + + public bool autoUpdateReferences = true; + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3DefaultSettings.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3DefaultSettings.cs.meta new file mode 100644 index 0000000..5cb6de2 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3DefaultSettings.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c6d233887d0c64d7e8f3ebcb39bc8c82 +timeCreated: 1519132296 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Defaults.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Defaults.cs new file mode 100644 index 0000000..61e7a1a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Defaults.cs @@ -0,0 +1,24 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class ES3Defaults : ScriptableObject +{ + [SerializeField] + public ES3SerializableSettings settings = new ES3SerializableSettings(); + + public bool addMgrToSceneAutomatically = false; + public bool autoUpdateReferences = true; + public bool addAllPrefabsToManager = true; + public int collectDependenciesDepth = 4; + public int collectDependenciesTimeout = 10; + public bool updateReferencesWhenSceneChanges = true; + public bool updateReferencesWhenSceneIsSaved = true; + public bool updateReferencesWhenSceneIsOpened = true; + [Tooltip("Folders listed here will be searched for references every time the reference manager is refreshed. Path should be relative to the project folder.")] + public string[] referenceFolders = new string[0]; + + public bool logDebugInfo = false; + public bool logWarnings = true; + public bool logErrors = true; +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Defaults.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Defaults.cs.meta new file mode 100644 index 0000000..4a6af3f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Defaults.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7b340139c9e4d054f904d8b452798652 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Settings.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Settings.cs new file mode 100644 index 0000000..beb0f71 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Settings.cs @@ -0,0 +1,386 @@ +using UnityEngine; +using ES3Internal; +#if UNITY_EDITOR +using UnityEditor; +#endif + +#if UNITY_VISUAL_SCRIPTING +[Unity.VisualScripting.IncludeInSettings(true)] +#elif BOLT_VISUAL_SCRIPTING +[Ludiq.IncludeInSettings(true)] +#endif +public class ES3Settings : System.ICloneable +{ + + #region Default settings + private static ES3Settings _defaults = null; + private static ES3Defaults _defaultSettingsScriptableObject; + private const string defaultSettingsPath = "ES3/ES3Defaults"; + + public static ES3Defaults defaultSettingsScriptableObject + { + get + { + if (_defaultSettingsScriptableObject == null) + { + _defaultSettingsScriptableObject = Resources.Load(defaultSettingsPath); + +#if UNITY_EDITOR + if (_defaultSettingsScriptableObject == null) + { + _defaultSettingsScriptableObject = ScriptableObject.CreateInstance(); + + // If this is the version being submitted to the Asset Store, don't include ES3Defaults. + if (Application.productName.Contains("ES3 Release")) + { + Debug.Log("This has been identified as a release build as the title contains 'ES3 Release', so ES3Defaults will not be created."); + return _defaultSettingsScriptableObject; + } + + // Convert the old settings to the new settings if necessary. + var oldSettings = GetOldSettings(); + if (oldSettings != null) + { + oldSettings.CopyInto(_defaultSettingsScriptableObject.settings); + // Only enable warning logs by default for new installs as this may look like unexpected behaviour to some. + _defaultSettingsScriptableObject.logWarnings = false; + RemoveOldSettings(); + } + + CreateDefaultSettingsFolder(); + AssetDatabase.CreateAsset(_defaultSettingsScriptableObject, PathToDefaultSettings()); + AssetDatabase.SaveAssets(); + } +#endif + } + return _defaultSettingsScriptableObject; + } + } + + public static ES3Settings defaultSettings + { + get + { + if(_defaults == null) + { + if(defaultSettingsScriptableObject != null) + _defaults = defaultSettingsScriptableObject.settings; + } + return _defaults; + } + } + + private static ES3Settings _unencryptedUncompressedSettings = null; + internal static ES3Settings unencryptedUncompressedSettings + { + get + { + if (_unencryptedUncompressedSettings == null) + _unencryptedUncompressedSettings = new ES3Settings(ES3.EncryptionType.None, ES3.CompressionType.None); + return _unencryptedUncompressedSettings; + } + } + + #endregion + + #region Fields + + private static readonly string[] resourcesExtensions = new string[]{".txt", ".htm", ".html", ".xml", ".bytes", ".json", ".csv", ".yaml", ".fnt" }; + + [SerializeField] + private ES3.Location _location; + /// The location where we wish to store data. As it's not possible to save/load from File in WebGL, if the default location is File it will use PlayerPrefs instead. + public ES3.Location location + { + get + { + if(_location == ES3.Location.File && (Application.platform == RuntimePlatform.WebGLPlayer || Application.platform == RuntimePlatform.tvOS)) + return ES3.Location.PlayerPrefs; + return _location; + } + set{ _location = value; } + } + + /// The path associated with this ES3Settings object, if any. + public string path = "SaveFile.es3"; + /// The type of encryption to use when encrypting data, if any. + public ES3.EncryptionType encryptionType = ES3.EncryptionType.None; + /// The type of encryption to use when encrypting data, if any. + public ES3.CompressionType compressionType = ES3.CompressionType.None; + /// The password to use when encrypting data. + public string encryptionPassword = "password"; + /// The default directory in which to store files, and the location which relative paths should be relative to. + public ES3.Directory directory = ES3.Directory.PersistentDataPath; + /// What format to use when serialising and deserialising data. + public ES3.Format format = ES3.Format.JSON; + /// Whether we want to pretty print JSON. + public bool prettyPrint = true; + /// Any stream buffers will be set to this length in bytes. + public int bufferSize = 2048; + /// The text encoding to use for text-based format. Note that changing this may invalidate previous save data. + public System.Text.Encoding encoding = System.Text.Encoding.UTF8; + // Whether we should serialise children when serialising a GameObject. + public bool saveChildren = true; + // Whether we should apply encryption and/or compression to raw cached data if they're specified in the cached data's settings. + public bool postprocessRawCachedData = false; + + /// Whether we should check that the data we are loading from a file matches the method we are using to load it. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public bool typeChecking = true; + + /// Enabling this ensures that only serialisable fields are serialised. Otherwise, possibly unsafe fields and properties will be serialised. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public bool safeReflection = true; + /// Whether UnityEngine.Object members should be stored by value, reference or both. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public ES3.ReferenceMode memberReferenceMode = ES3.ReferenceMode.ByRef; + /// Whether the main save methods should save UnityEngine.Objects by value, reference, or both. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public ES3.ReferenceMode referenceMode = ES3.ReferenceMode.ByRefAndValue; + + /// How many levels of hierarchy Easy Save will serialise. This is used to protect against cyclic references. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public int serializationDepthLimit = 64; + + /// The names of the Assemblies we should try to load our ES3Types from. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public string[] assemblyNames = new string[] { "Assembly-CSharp-firstpass", "Assembly-CSharp"}; + + /// Gets the full, absolute path which this ES3Settings object identifies. + public string FullPath + { + get + { + if (path == null) + throw new System.NullReferenceException("The 'path' field of this ES3Settings is null, indicating that it was not possible to load the default settings from Resources. Please check that the ES3 Default Settings.prefab exists in Assets/Plugins/Resources/ES3/"); + + if(IsAbsolute(path)) + return path; + + if(location == ES3.Location.File) + { + if(directory == ES3.Directory.PersistentDataPath) + return ES3IO.persistentDataPath + "/" + path; + if(directory == ES3.Directory.DataPath) + return Application.dataPath + "/" + path; + throw new System.NotImplementedException("File directory \""+directory+"\" has not been implemented."); + } + if(location == ES3.Location.Resources) + { + // Check that it has valid extension + var extension = System.IO.Path.GetExtension(path); + bool hasValidExtension = false; + foreach (var ext in resourcesExtensions) + { + if (extension == ext) + { + hasValidExtension = true; + break; + } + } + + if(!hasValidExtension) + throw new System.ArgumentException("Extension of file in Resources must be .json, .bytes, .txt, .csv, .htm, .html, .xml, .yaml or .fnt, but path given was \"" + path + "\""); + + // Remove extension + string resourcesPath = path.Replace(extension, ""); + return resourcesPath; + } + return path; + } + } + + #endregion + + #region Constructors + + /// Creates a new ES3Settings object with the given path. + /// The path associated with this ES3Settings object. + /// The settings we want to use to override the default settings. + public ES3Settings(string path = null, ES3Settings settings = null) : this(true) + { + // if there are settings to merge, merge them. + if (settings != null) + settings.CopyInto(this); + + if (path != null) + this.path = path; + } + + /// Creates a new ES3Settings object with the given path. + /// The path associated with this ES3Settings object. + /// Accepts an ES3.EncryptionType, ES3.CompressionType, ES3.Location, ES3.Directory or ES3.ReferenceMode. + public ES3Settings(string path, params System.Enum[] enums) : this(enums) + { + if (path != null) + this.path = path; + } + + + /// Creates a new ES3Settings object with the given path. + /// The path associated with this ES3Settings object. + /// Accepts an ES3.EncryptionType, ES3.CompressionType, ES3.Location, ES3.Directory or ES3.ReferenceMode. + public ES3Settings(params System.Enum[] enums) : this(true) + { + foreach (var setting in enums) + { + if (setting is ES3.EncryptionType) + this.encryptionType = (ES3.EncryptionType)setting; + else if (setting is ES3.Location) + this.location = (ES3.Location)setting; + else if (setting is ES3.CompressionType) + this.compressionType = (ES3.CompressionType)setting; + else if (setting is ES3.ReferenceMode) + this.referenceMode = (ES3.ReferenceMode)setting; + else if (setting is ES3.Format) + this.format = (ES3.Format)setting; + else if (setting is ES3.Directory) + this.directory = (ES3.Directory)setting; + } + } + + /// Creates a new ES3Settings object with the given encryption settings. + /// The type of encryption to use, if any. + /// The password to use when encrypting data. + public ES3Settings(ES3.EncryptionType encryptionType, string encryptionPassword) : this(true) + { + this.encryptionType = encryptionType; + this.encryptionPassword = encryptionPassword; + } + + /// Creates a new ES3Settings object with the given path and encryption settings. + /// The path associated with this ES3Settings object. + /// The type of encryption to use, if any. + /// The password to use when encrypting data. + /// The settings we want to use to override the default settings. + public ES3Settings(string path, ES3.EncryptionType encryptionType, string encryptionPassword, ES3Settings settings = null) : this(path, settings) + { + this.encryptionType = encryptionType; + this.encryptionPassword = encryptionPassword; + } + + /* Base constructor which allows us to bypass defaults so it can be called by Editor serialization */ + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public ES3Settings(bool applyDefaults) + { + if (applyDefaults) + if (defaultSettings != null) + _defaults.CopyInto(this); + } + + #endregion + + #region Editor methods +#if UNITY_EDITOR + public static string pathToEasySaveFolder = null; + + public static string PathToEasySaveFolder() + { + // If the path has not yet been cached, get the path and cache it. + if (string.IsNullOrEmpty(pathToEasySaveFolder)) + { + string[] guids = AssetDatabase.FindAssets("ES3Window"); + if (guids.Length == 0) + ES3Debug.LogError("Could not locate the Easy Save 3 folder because the ES3Window script has been moved or removed."); + if (guids.Length > 1) + ES3Debug.LogError("Could not locate the Easy Save 3 folder because more than one ES3Window script exists in the project, but this needs to be unique to locate the folder."); + + pathToEasySaveFolder = AssetDatabase.GUIDToAssetPath(guids[0]).Split(new string[] { "Editor" }, System.StringSplitOptions.RemoveEmptyEntries)[0]; + } + return pathToEasySaveFolder; + } + + internal static string PathToDefaultSettings() + { + return PathToEasySaveFolder() + "Resources/"+defaultSettingsPath+".asset"; + } + + internal static void CreateDefaultSettingsFolder() + { + if (AssetDatabase.IsValidFolder(PathToEasySaveFolder() + "Resources/ES3")) + return; + // Remove leading slash from PathToEasySaveFolder. + AssetDatabase.CreateFolder(PathToEasySaveFolder().Remove(PathToEasySaveFolder().Length - 1, 1), "Resources"); + AssetDatabase.CreateFolder(PathToEasySaveFolder() + "Resources", "ES3"); + } + + private static ES3SerializableSettings GetOldSettings() + { + var go = Resources.Load(defaultSettingsPath.Replace("ES3Defaults", "ES3 Default Settings")); + if(go != null) + { + var c = go.GetComponent(); + if (c != null && c.settings != null) + return c.settings; + } + return null; + } + + private static void RemoveOldSettings() + { + AssetDatabase.DeleteAsset(PathToDefaultSettings().Replace("ES3Defaults.asset", "ES3 Default Settings.prefab")); + } +#endif + #endregion + + #region Utility methods + + private static bool IsAbsolute(string path) + { + if (path.Length > 0 && (path[0] == '/' || path[0] == '\\')) + return true; + if (path.Length > 1 && path[1] == ':') + return true; + return false; + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public object Clone() + { + var settings = new ES3Settings(); + CopyInto(settings); + return settings; + } + + private void CopyInto(ES3Settings newSettings) + { + newSettings._location = _location; + newSettings.directory = directory; + newSettings.format = format; + newSettings.prettyPrint = prettyPrint; + newSettings.path = path; + newSettings.encryptionType = encryptionType; + newSettings.encryptionPassword = encryptionPassword; + newSettings.compressionType = compressionType; + newSettings.bufferSize = bufferSize; + newSettings.encoding = encoding; + newSettings.typeChecking = typeChecking; + newSettings.safeReflection = safeReflection; + newSettings.referenceMode = referenceMode; + newSettings.memberReferenceMode = memberReferenceMode; + newSettings.assemblyNames = assemblyNames; + newSettings.saveChildren = saveChildren; + newSettings.serializationDepthLimit = serializationDepthLimit; + newSettings.postprocessRawCachedData = postprocessRawCachedData; + } + + #endregion +} + +/* + * A serializable version of the settings we can use as a field in the Editor, which doesn't automatically + * assign defaults to itself, so we get no serialization errors. + */ +[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] +[System.Serializable] +public class ES3SerializableSettings : ES3Settings +{ + public ES3SerializableSettings() : base(false){} + public ES3SerializableSettings(bool applyDefaults) : base(applyDefaults){} + public ES3SerializableSettings(string path) : base(false) { this.path = path; } + public ES3SerializableSettings(string path, ES3.Location location) : base(false) { this.location = location; } + +#if UNITY_EDITOR + public bool showAdvancedSettings = false; +#endif +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Settings.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Settings.cs.meta new file mode 100644 index 0000000..2b45b24 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Settings/ES3Settings.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b7b35a33d52a04187b51d5e2e2e5b0c8 +timeCreated: 1519132294 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams.meta new file mode 100644 index 0000000..9073820 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0c77ee5c201c7d841a279a490dbe351b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3FileStream.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3FileStream.cs new file mode 100644 index 0000000..43a23b5 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3FileStream.cs @@ -0,0 +1,68 @@ +using System.IO; + +namespace ES3Internal +{ + public enum ES3FileMode {Read, Write, Append} + + public class ES3FileStream : FileStream + { + private bool isDisposed = false; + + public ES3FileStream( string path, ES3FileMode fileMode, int bufferSize, bool useAsync) + : base( GetPath(path, fileMode), GetFileMode(fileMode), GetFileAccess(fileMode), FileShare.None, bufferSize, useAsync) + { + } + + // Gets a temporary path if necessary. + protected static string GetPath(string path, ES3FileMode fileMode) + { + string directoryPath = ES3IO.GetDirectoryPath(path); + // Attempt to create the directory incase it does not exist if we are storing data. + if (fileMode != ES3FileMode.Read && directoryPath != ES3IO.persistentDataPath) + ES3IO.CreateDirectory(directoryPath); + if(fileMode != ES3FileMode.Write || fileMode == ES3FileMode.Append) + return path; + return (fileMode == ES3FileMode.Write) ? path + ES3IO.temporaryFileSuffix : path; + } + + protected static FileMode GetFileMode(ES3FileMode fileMode) + { + if (fileMode == ES3FileMode.Read) + return FileMode.Open; + else if (fileMode == ES3FileMode.Write) + return FileMode.Create; + else + return FileMode.Append; + } + + protected static FileAccess GetFileAccess(ES3FileMode fileMode) + { + if (fileMode == ES3FileMode.Read) + return FileAccess.Read; + else if (fileMode == ES3FileMode.Write) + return FileAccess.Write; + else + return FileAccess.Write; + } + + protected override void Dispose (bool disposing) + { + // Ensure we only perform disposable once. + if(isDisposed) + return; + isDisposed = true; + + base.Dispose(disposing); + + + // If this is a file writer, we need to replace the temp file. + /*if(fileMode == ES3FileMode.Write && fileMode != ES3FileMode.Append) + { + // Delete the old file before overwriting it. + ES3IO.DeleteFile(path); + // Rename temporary file to new file. + ES3IO.MoveFile(path + ES3.temporaryFileSuffix, path); + }*/ + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3FileStream.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3FileStream.cs.meta new file mode 100644 index 0000000..40077cf --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3FileStream.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0daff17c3279448f994a7a93d305046a +timeCreated: 1499764821 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3PlayerPrefsStream.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3PlayerPrefsStream.cs new file mode 100644 index 0000000..95606ff --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3PlayerPrefsStream.cs @@ -0,0 +1,63 @@ +using System.IO; +using UnityEngine; + +namespace ES3Internal +{ + internal class ES3PlayerPrefsStream : MemoryStream + { + private string path; + private bool append; + private bool isWriteStream = false; + private bool isDisposed = false; + + // This constructor should be used for read streams only. + public ES3PlayerPrefsStream(string path) : base(GetData(path,false)) + { + this.path = path; + this.append = false; + } + + // This constructor should be used for write streams only. + public ES3PlayerPrefsStream(string path, int bufferSize, bool append=false) : base(bufferSize) + { + this.path = path; + this.append = append; + this.isWriteStream = true; + } + + private static byte[] GetData(string path, bool isWriteStream) + { + if(!PlayerPrefs.HasKey(path)) + throw new FileNotFoundException("File \""+path+"\" could not be found in PlayerPrefs"); + return System.Convert.FromBase64String(PlayerPrefs.GetString(path)); + } + + protected override void Dispose (bool disposing) + { + if(isDisposed) + return; + isDisposed = true; + if(isWriteStream && this.Length > 0) + { + if (append) + { + // Convert data back to bytes before appending, as appending Base-64 strings directly can corrupt the data. + var sourceBytes = System.Convert.FromBase64String(PlayerPrefs.GetString(path)); + var appendBytes = this.ToArray(); + var finalBytes = new byte[sourceBytes.Length + appendBytes.Length]; + System.Buffer.BlockCopy(sourceBytes, 0, finalBytes, 0, sourceBytes.Length); + System.Buffer.BlockCopy(appendBytes, 0, finalBytes, sourceBytes.Length, appendBytes.Length); + + PlayerPrefs.SetString(path, System.Convert.ToBase64String(finalBytes)); + + PlayerPrefs.Save(); + } + else + PlayerPrefs.SetString(path + ES3IO.temporaryFileSuffix, System.Convert.ToBase64String(this.ToArray())); + // Save the timestamp to a separate key. + PlayerPrefs.SetString("timestamp_" + path, System.DateTime.UtcNow.Ticks.ToString()); + } + base.Dispose(disposing); + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3PlayerPrefsStream.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3PlayerPrefsStream.cs.meta new file mode 100644 index 0000000..690bef4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3PlayerPrefsStream.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: df45161eabf2549c28f00352d4f970dc +timeCreated: 1499764823 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3ResourcesStream.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3ResourcesStream.cs new file mode 100644 index 0000000..fcbe196 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3ResourcesStream.cs @@ -0,0 +1,32 @@ +using System.IO; +using UnityEngine; + +namespace ES3Internal +{ + internal class ES3ResourcesStream : MemoryStream + { + // Check that data exists by checking stream is not empty. + public bool Exists{ get{ return this.Length > 0; } } + + // Used when creating + public ES3ResourcesStream(string path) : base(GetData(path)) + { + } + + private static byte[] GetData(string path) + { + var textAsset = Resources.Load(path) as TextAsset; + + // If data doesn't exist in Resources, return an empty byte array. + if(textAsset == null) + return new byte[0]; + + return textAsset.bytes; + } + + protected override void Dispose (bool disposing) + { + base.Dispose(disposing); + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3ResourcesStream.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3ResourcesStream.cs.meta new file mode 100644 index 0000000..06046cf --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3ResourcesStream.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fe24380d3aca84a4d97e668349d86d37 +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3Stream.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3Stream.cs new file mode 100644 index 0000000..99fcb63 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3Stream.cs @@ -0,0 +1,123 @@ +using System.IO; +using System.IO.Compression; +using UnityEngine; +using System; + +namespace ES3Internal +{ + public static class ES3Stream + { + public static Stream CreateStream(ES3Settings settings, ES3FileMode fileMode) + { + bool isWriteStream = (fileMode != ES3FileMode.Read); + Stream stream = null; + + // If we're using File as our location, check that the path is in a valid format. + if(settings.location == ES3.Location.File) + new FileInfo(settings.FullPath); + + try + { + if (settings.location == ES3.Location.InternalMS) + { + // There's no point in creating an empty MemoryStream if we're only reading from it. + if (!isWriteStream) + return null; + stream = new MemoryStream(settings.bufferSize); + } + else if (settings.location == ES3.Location.File) + { + if (!isWriteStream && !ES3IO.FileExists(settings.FullPath)) + return null; + stream = new ES3FileStream(settings.FullPath, fileMode, settings.bufferSize, false); + } + else if (settings.location == ES3.Location.PlayerPrefs) + { + if (isWriteStream) + stream = new ES3PlayerPrefsStream(settings.FullPath, settings.bufferSize, (fileMode == ES3FileMode.Append)); + else + { + if (!PlayerPrefs.HasKey(settings.FullPath)) + return null; + stream = new ES3PlayerPrefsStream(settings.FullPath); + } + } + else if (settings.location == ES3.Location.Resources) + { + if (!isWriteStream) + { + var resourcesStream = new ES3ResourcesStream(settings.FullPath); + if (resourcesStream.Exists) + stream = resourcesStream; + else + { + resourcesStream.Dispose(); + return null; + } + } + else if (UnityEngine.Application.isEditor) + throw new System.NotSupportedException("Cannot write directly to Resources folder. Try writing to a directory outside of Resources, and then manually move the file there."); + else + throw new System.NotSupportedException("Cannot write to Resources folder at runtime. Use a different save location at runtime instead."); + } + + return CreateStream(stream, settings, fileMode); + } + catch(System.Exception e) + { + if (stream != null) + stream.Dispose(); + throw e; + } + } + + public static Stream CreateStream(Stream stream, ES3Settings settings, ES3FileMode fileMode) + { + try + { + bool isWriteStream = (fileMode != ES3FileMode.Read); + + #if !DISABLE_ENCRYPTION + // Encryption + if(settings.encryptionType != ES3.EncryptionType.None && stream.GetType() != typeof(UnbufferedCryptoStream)) + { + EncryptionAlgorithm alg = null; + if(settings.encryptionType == ES3.EncryptionType.AES) + alg = new AESEncryptionAlgorithm(); + stream = new UnbufferedCryptoStream(stream, !isWriteStream, settings.encryptionPassword, settings.bufferSize, alg); + } + #endif + + // Compression + if (settings.compressionType != ES3.CompressionType.None && stream.GetType() != typeof(GZipStream)) + { + if (settings.compressionType == ES3.CompressionType.Gzip) + stream = isWriteStream ? new GZipStream(stream, CompressionMode.Compress) : new GZipStream(stream, CompressionMode.Decompress); + } + + return stream; + } + catch (System.Exception e) + { + if (stream != null) + stream.Dispose(); + if (e.GetType() == typeof(System.Security.Cryptography.CryptographicException)) + throw new System.Security.Cryptography.CryptographicException("Could not decrypt file. Please ensure that you are using the same password used to encrypt the file."); + else + throw e; + } + } + + public static void CopyTo(Stream source, Stream destination) + { + #if UNITY_2019_1_OR_NEWER + source.CopyTo(destination); + #else + byte[] buffer = new byte[2048]; + int bytesRead; + while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) + destination.Write(buffer, 0, bytesRead); + #endif + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3Stream.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3Stream.cs.meta new file mode 100644 index 0000000..ed9f16c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Streams/ES3Stream.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b4ec91ea5d66749aca7d5555b767728a +timeCreated: 1499764822 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types.meta new file mode 100644 index 0000000..30fc819 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: fd5185c51cb855e4da012e3a9c3aca20 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types.meta new file mode 100644 index 0000000..e9442bc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d080d5fc922ddcd4ea4a221aa898be4f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES32DArrayType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES32DArrayType.cs new file mode 100644 index 0000000..b3cff18 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES32DArrayType.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; +using System.Linq; + +namespace ES3Types +{ + public class ES32DArrayType : ES3CollectionType + { + public ES32DArrayType(Type type) : base(type){} + + public override void Write(object obj, ES3Writer writer, ES3.ReferenceMode unityObjectType) + { + var array = (System.Array)obj; + + if(elementType == null) + throw new ArgumentNullException("ES3Type argument cannot be null."); + + //writer.StartWriteCollection(); + + for(int i=0; i < array.GetLength(0); i++) + { + writer.StartWriteCollectionItem(i); + writer.StartWriteCollection(); + for(int j=0; j < array.GetLength(1); j++) + { + writer.StartWriteCollectionItem(j); + writer.Write(array.GetValue(i,j), elementType, unityObjectType); + writer.EndWriteCollectionItem(j); + } + writer.EndWriteCollection(); + writer.EndWriteCollectionItem(i); + } + + //writer.EndWriteCollection(); + } + + public override object Read(ES3Reader reader) + { + return Read(reader); + /*if(reader.StartReadCollection()) + return null; + + // Create a List to store the items as a 1D array, which we can work out the positions of by calculating the lengths of the two dimensions. + var items = new List(); + int length1 = 0; + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadCollectionItem()) + break; + + ReadICollection(reader, items, elementType); + length1++; + + if(reader.EndReadCollectionItem()) + break; + } + + int length2 = items.Count / length1; + + var array = new T[length1,length2]; + + for(int i=0; i(); + int length1 = 0; + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadCollectionItem()) + break; + + ReadICollection(reader, items, elementType); + length1++; + + if(reader.EndReadCollectionItem()) + break; + } + + int length2 = items.Count / length1; + + var array = ES3Reflection.ArrayCreateInstance(elementType.type, new int[]{length1, length2}); + + for(int i=0; i(ES3Reader reader, object obj) + { + ReadInto(reader, obj); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var array = (Array)obj; + + if(reader.StartReadCollection()) + throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + bool iHasBeenRead = false; + + for(int i=0; i < array.GetLength(0); i++) + { + bool jHasBeenRead = false; + + if(!reader.StartReadCollectionItem()) + throw new IndexOutOfRangeException("The collection we are loading is smaller than the collection provided as a parameter."); + + reader.StartReadCollection(); + for(int j=0; j < array.GetLength(1); j++) + { + if(!reader.StartReadCollectionItem()) + throw new IndexOutOfRangeException("The collection we are loading is smaller than the collection provided as a parameter."); + reader.ReadInto(array.GetValue(i,j), elementType); + jHasBeenRead = reader.EndReadCollectionItem(); + } + + if(!jHasBeenRead) + throw new IndexOutOfRangeException("The collection we are loading is larger than the collection provided as a parameter."); + + reader.EndReadCollection(); + + iHasBeenRead = reader.EndReadCollectionItem(); + } + + if(!iHasBeenRead) + throw new IndexOutOfRangeException("The collection we are loading is larger than the collection provided as a parameter."); + + reader.EndReadCollection(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES32DArrayType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES32DArrayType.cs.meta new file mode 100644 index 0000000..5d924b3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES32DArrayType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 16f7aabe86b814cc8a059954a1c78d25 +timeCreated: 1519132280 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES33DArrayType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES33DArrayType.cs new file mode 100644 index 0000000..a424e12 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES33DArrayType.cs @@ -0,0 +1,164 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types + { + public class ES33DArrayType : ES3CollectionType + { + public ES33DArrayType(Type type) : base(type){} + + public override void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode) + { + var array = (System.Array)obj; + + if(elementType == null) + throw new ArgumentNullException("ES3Type argument cannot be null."); + + //writer.StartWriteCollection(); + + for(int i=0; i < array.GetLength(0); i++) + { + writer.StartWriteCollectionItem(i); + writer.StartWriteCollection(); + + for(int j=0; j < array.GetLength(1); j++) + { + writer.StartWriteCollectionItem(j); + writer.StartWriteCollection(); + + for(int k=0; k < array.GetLength(2); k++) + { + writer.StartWriteCollectionItem(k); + writer.Write(array.GetValue(i,j,k), elementType, memberReferenceMode); + writer.EndWriteCollectionItem(k); + } + writer.EndWriteCollection(); + writer.EndWriteCollectionItem(j); + } + writer.EndWriteCollection(); + writer.EndWriteCollectionItem(i); + } + //writer.EndWriteCollection(); + } + + public override object Read(ES3Reader reader) + { + return Read(reader); + } + + public override object Read(ES3Reader reader) + { + if(reader.StartReadCollection()) + return null; + + // Create a List to store the items as a 1D array, which we can work out the positions of by calculating the lengths of the two dimensions. + var items = new List(); + int length1 = 0; + int length2 = 0; + + // Iterate through each sub-array + while(true) + { + if(!reader.StartReadCollectionItem()) + break; + reader.StartReadCollection(); + + length1++; + + while(true) + { + if(!reader.StartReadCollectionItem()) + break; + + ReadICollection(reader, items, elementType); + length2++; + + if(reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + if(reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + + length2 = length2/length1; + int length3 = items.Count / length2 / length1; + + var array = ES3Reflection.ArrayCreateInstance(elementType.type, new int[]{length1,length2,length3}); + + for(int i=0; i(ES3Reader reader, object obj) + { + ReadInto(reader, obj); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var array = (Array)obj; + + if(reader.StartReadCollection()) + throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + bool iHasBeenRead = false; + + for(int i=0; i < array.GetLength(0); i++) + { + bool jHasBeenRead = false; + + if(!reader.StartReadCollectionItem()) + throw new IndexOutOfRangeException("The collection we are loading is smaller than the collection provided as a parameter."); + + reader.StartReadCollection(); + + for(int j=0; j < array.GetLength(1); j++) + { + bool kHasBeenRead = false; + + if(!reader.StartReadCollectionItem()) + throw new IndexOutOfRangeException("The collection we are loading is smaller than the collection provided as a parameter."); + + reader.StartReadCollection(); + + for(int k=0; k < array.GetLength(2); k++) + { + if(!reader.StartReadCollectionItem()) + throw new IndexOutOfRangeException("The collection we are loading is smaller than the collection provided as a parameter."); + reader.ReadInto(array.GetValue(i,j,k), elementType); + kHasBeenRead = reader.EndReadCollectionItem(); + } + + if(!kHasBeenRead) + throw new IndexOutOfRangeException("The collection we are loading is larger than the collection provided as a parameter."); + + reader.EndReadCollection(); + + jHasBeenRead = reader.EndReadCollectionItem(); + } + + if(!jHasBeenRead) + throw new IndexOutOfRangeException("The collection we are loading is larger than the collection provided as a parameter."); + + reader.EndReadCollection(); + + iHasBeenRead = reader.EndReadCollectionItem(); + } + + if(!iHasBeenRead) + throw new IndexOutOfRangeException("The collection we are loading is larger than the collection provided as a parameter."); + + reader.EndReadCollection(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES33DArrayType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES33DArrayType.cs.meta new file mode 100644 index 0000000..f87024d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES33DArrayType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f60b75065118c4199aeaa2c3c31ecc0f +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ArrayType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ArrayType.cs new file mode 100644 index 0000000..d27c2d7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ArrayType.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3ArrayType : ES3CollectionType + { + public ES3ArrayType(Type type) : base(type){} + public ES3ArrayType(Type type, ES3Type elementType) : base(type, elementType){} + + public override void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode) + { + var array = (System.Array)obj; + + if(elementType == null) + throw new ArgumentNullException("ES3Type argument cannot be null."); + + //writer.StartWriteCollection(); + + for(int i=0; i(); + if (!ReadICollection(reader, list, elementType)) + return null; + + var array = ES3Reflection.ArrayCreateInstance(elementType.type, list.Count); + int i = 0; + foreach (var item in list) + { + array.SetValue(item, i); + i++; + } + + return array; + } + + public override object Read(ES3Reader reader) + { + return Read(reader); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + ReadICollectionInto(reader, (ICollection)obj, elementType); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var collection = (IList)obj; + + if (collection.Count == 0) + ES3Debug.LogWarning("LoadInto/ReadInto expects a collection containing instances to load data in to, but the collection is empty."); + + if(reader.StartReadCollection()) + throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + int itemsLoaded = 0; + + // Iterate through each item in the collection and try to load it. + foreach(var item in collection) + { + itemsLoaded++; + + if(!reader.StartReadCollectionItem()) + break; + + reader.ReadInto(item, elementType); + + // If we find a ']', we reached the end of the array. + if(reader.EndReadCollectionItem()) + break; + + // If there's still items to load, but we've reached the end of the collection we're loading into, throw an error. + if(itemsLoaded == collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is longer than the collection provided as a parameter."); + } + + // If we loaded fewer items than the parameter collection, throw index out of range exception. + if(itemsLoaded != collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is shorter than the collection provided as a parameter."); + + reader.EndReadCollection(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ArrayType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ArrayType.cs.meta new file mode 100644 index 0000000..bcdc911 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ArrayType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 80139e4c0efc5414caff6bb50527d63d +timeCreated: 1519132289 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3CollectionType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3CollectionType.cs new file mode 100644 index 0000000..ecaa2e5 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3CollectionType.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public abstract class ES3CollectionType : ES3Type + { + public ES3Type elementType; + + /*protected ES3Reflection.ES3ReflectedMethod readMethod = null; + protected ES3Reflection.ES3ReflectedMethod readIntoMethod = null;*/ + + public abstract object Read(ES3Reader reader); + public abstract void ReadInto(ES3Reader reader, object obj); + public abstract void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode); + + public ES3CollectionType(Type type) : base(type) + { + elementType = ES3TypeMgr.GetOrCreateES3Type(ES3Reflection.GetElementTypes(type)[0], false); + isCollection = true; + + // If the element type is null (i.e. unsupported), make this ES3Type null. + if(elementType == null) + isUnsupported = true; + } + + public ES3CollectionType(Type type, ES3Type elementType) : base(type) + { + this.elementType = elementType; + isCollection = true; + } + + [UnityEngine.Scripting.Preserve] + public override void Write(object obj, ES3Writer writer) + { + Write(obj, writer, ES3.ReferenceMode.ByRefAndValue); + } + + protected virtual bool ReadICollection(ES3Reader reader, ICollection collection, ES3Type elementType) + { + if(reader.StartReadCollection()) + return false; + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadCollectionItem()) + break; + collection.Add(reader.Read(elementType)); + + if(reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + + return true; + } + + protected virtual void ReadICollectionInto(ES3Reader reader, ICollection collection, ES3Type elementType) + { + ReadICollectionInto(reader, collection, elementType); + } + + [UnityEngine.Scripting.Preserve] + protected virtual void ReadICollectionInto(ES3Reader reader, ICollection collection, ES3Type elementType) + { + if(reader.StartReadCollection()) + throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + int itemsLoaded = 0; + + // Iterate through each item in the collection and try to load it. + foreach(var item in collection) + { + itemsLoaded++; + + if(!reader.StartReadCollectionItem()) + break; + + reader.ReadInto(item, elementType); + + // If we find a ']', we reached the end of the array. + if(reader.EndReadCollectionItem()) + break; + + // If there's still items to load, but we've reached the end of the collection we're loading into, throw an error. + if(itemsLoaded == collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is longer than the collection provided as a parameter."); + } + + // If we loaded fewer items than the parameter collection, throw index out of range exception. + if(itemsLoaded != collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is shorter than the collection provided as a parameter."); + + reader.EndReadCollection(); + } + + /* + * Calls the Read method using reflection so we don't need to provide a generic parameter. + */ + /*public virtual object Read(ES3Reader reader) + { + if(readMethod == null) + readMethod = ES3Reflection.GetMethod(this.GetType(), "Read", new Type[]{elementType.type}, new Type[]{typeof(ES3Reader)}); + return readMethod.Invoke(this, new object[]{reader}); + } + + public virtual void ReadInto(ES3Reader reader, object obj) + { + if(readIntoMethod == null) + readIntoMethod = ES3Reflection.GetMethod(this.GetType(), "ReadInto", new Type[]{elementType.type}, new Type[]{typeof(ES3Reader), typeof(object)}); + readIntoMethod.Invoke(this, new object[]{reader, obj}); + }*/ + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3CollectionType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3CollectionType.cs.meta new file mode 100644 index 0000000..d02b40d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3CollectionType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 4758f55361e6f4485afe7dfdd3a3a372 +timeCreated: 1519132284 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ConcurrentDictionaryType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ConcurrentDictionaryType.cs new file mode 100644 index 0000000..e7966bd --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ConcurrentDictionaryType.cs @@ -0,0 +1,142 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3ConcurrentDictionaryType : ES3Type + { + public ES3Type keyType; + public ES3Type valueType; + + protected ES3Reflection.ES3ReflectedMethod readMethod = null; + protected ES3Reflection.ES3ReflectedMethod readIntoMethod = null; + + public ES3ConcurrentDictionaryType(Type type) : base(type) + { + var types = ES3Reflection.GetElementTypes(type); + keyType = ES3TypeMgr.GetOrCreateES3Type(types[0], false); + valueType = ES3TypeMgr.GetOrCreateES3Type(types[1], false); + + // If either the key or value type is unsupported, make this type NULL. + if(keyType == null || valueType == null) + isUnsupported = true;; + + isDictionary = true; + } + + public ES3ConcurrentDictionaryType(Type type, ES3Type keyType, ES3Type valueType) : base(type) + { + this.keyType = keyType; + this.valueType = valueType; + + // If either the key or value type is unsupported, make this type NULL. + if (keyType == null || valueType == null) + isUnsupported = true; ; + + isDictionary = true; + } + + public override void Write(object obj, ES3Writer writer) + { + Write(obj, writer, writer.settings.memberReferenceMode); + } + + public void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode) + { + var dict = (IDictionary)obj; + + //writer.StartWriteDictionary(dict.Count); + + int i=0; + foreach(System.Collections.DictionaryEntry kvp in dict) + { + writer.StartWriteDictionaryKey(i); + writer.Write(kvp.Key, keyType, memberReferenceMode); + writer.EndWriteDictionaryKey(i); + writer.StartWriteDictionaryValue(i); + writer.Write(kvp.Value, valueType, memberReferenceMode); + writer.EndWriteDictionaryValue(i); + i++; + } + + //writer.EndWriteDictionary(); + } + + public override object Read(ES3Reader reader) + { + return Read(reader); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + ReadInto(reader, obj); + } + + /* + * Allows us to call the generic Read method using Reflection so we can define the generic parameter at runtime. + * It also caches the method to improve performance in later calls. + */ + public object Read(ES3Reader reader) + { + if(reader.StartReadDictionary()) + return null; + + var dict = (IDictionary)ES3Reflection.CreateInstance(type); + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadDictionaryKey()) + return dict; + var key = reader.Read(keyType); + reader.EndReadDictionaryKey(); + + reader.StartReadDictionaryValue(); + var value = reader.Read(valueType); + + dict.Add(key,value); + + if(reader.EndReadDictionaryValue()) + break; + } + + reader.EndReadDictionary(); + + return dict; + } + + public void ReadInto(ES3Reader reader, object obj) + { + if(reader.StartReadDictionary()) + throw new NullReferenceException("The Dictionary we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + var dict = (IDictionary)obj; + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadDictionaryKey()) + return; + var key = reader.Read(keyType); + + if(!dict.Contains(key)) + throw new KeyNotFoundException("The key \"" + key + "\" in the Dictionary we are loading does not exist in the Dictionary we are loading into"); + var value = dict[key]; + reader.EndReadDictionaryKey(); + + reader.StartReadDictionaryValue(); + + reader.ReadInto(value, valueType); + + if(reader.EndReadDictionaryValue()) + break; + } + + reader.EndReadDictionary(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ConcurrentDictionaryType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ConcurrentDictionaryType.cs.meta new file mode 100644 index 0000000..02b70a3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ConcurrentDictionaryType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 57aa1763324cfbd4ea9782b0ea036900 +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3DictionaryType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3DictionaryType.cs new file mode 100644 index 0000000..104755b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3DictionaryType.cs @@ -0,0 +1,142 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3DictionaryType : ES3Type + { + public ES3Type keyType; + public ES3Type valueType; + + protected ES3Reflection.ES3ReflectedMethod readMethod = null; + protected ES3Reflection.ES3ReflectedMethod readIntoMethod = null; + + public ES3DictionaryType(Type type) : base(type) + { + var types = ES3Reflection.GetElementTypes(type); + keyType = ES3TypeMgr.GetOrCreateES3Type(types[0], false); + valueType = ES3TypeMgr.GetOrCreateES3Type(types[1], false); + + // If either the key or value type is unsupported, make this type NULL. + if(keyType == null || valueType == null) + isUnsupported = true;; + + isDictionary = true; + } + + public ES3DictionaryType(Type type, ES3Type keyType, ES3Type valueType) : base(type) + { + this.keyType = keyType; + this.valueType = valueType; + + // If either the key or value type is unsupported, make this type NULL. + if (keyType == null || valueType == null) + isUnsupported = true; ; + + isDictionary = true; + } + + public override void Write(object obj, ES3Writer writer) + { + Write(obj, writer, writer.settings.memberReferenceMode); + } + + public void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode) + { + var dict = (IDictionary)obj; + + //writer.StartWriteDictionary(dict.Count); + + int i=0; + foreach(System.Collections.DictionaryEntry kvp in dict) + { + writer.StartWriteDictionaryKey(i); + writer.Write(kvp.Key, keyType, memberReferenceMode); + writer.EndWriteDictionaryKey(i); + writer.StartWriteDictionaryValue(i); + writer.Write(kvp.Value, valueType, memberReferenceMode); + writer.EndWriteDictionaryValue(i); + i++; + } + + //writer.EndWriteDictionary(); + } + + public override object Read(ES3Reader reader) + { + return Read(reader); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + ReadInto(reader, obj); + } + + /* + * Allows us to call the generic Read method using Reflection so we can define the generic parameter at runtime. + * It also caches the method to improve performance in later calls. + */ + public object Read(ES3Reader reader) + { + if(reader.StartReadDictionary()) + return null; + + var dict = (IDictionary)ES3Reflection.CreateInstance(type); + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadDictionaryKey()) + return dict; + var key = reader.Read(keyType); + reader.EndReadDictionaryKey(); + + reader.StartReadDictionaryValue(); + var value = reader.Read(valueType); + + dict.Add(key,value); + + if(reader.EndReadDictionaryValue()) + break; + } + + reader.EndReadDictionary(); + + return dict; + } + + public void ReadInto(ES3Reader reader, object obj) + { + if(reader.StartReadDictionary()) + throw new NullReferenceException("The Dictionary we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + var dict = (IDictionary)obj; + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadDictionaryKey()) + return; + var key = reader.Read(keyType); + + if(!dict.Contains(key)) + throw new KeyNotFoundException("The key \"" + key + "\" in the Dictionary we are loading does not exist in the Dictionary we are loading into"); + var value = dict[key]; + reader.EndReadDictionaryKey(); + + reader.StartReadDictionaryValue(); + + reader.ReadInto(value, valueType); + + if(reader.EndReadDictionaryValue()) + break; + } + + reader.EndReadDictionary(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3DictionaryType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3DictionaryType.cs.meta new file mode 100644 index 0000000..ee845c5 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3DictionaryType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2bc573810521e44bea185a4fa7c415e9 +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3HashSetType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3HashSetType.cs new file mode 100644 index 0000000..ebac2d7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3HashSetType.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; +using System.Linq; +using System.Reflection; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3HashSetType : ES3CollectionType + { + public ES3HashSetType(Type type) : base(type){} + + public override void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode) + { + if (obj == null) { writer.WriteNull(); return; }; + + var list = (IEnumerable)obj; + + if (elementType == null) + throw new ArgumentNullException("ES3Type argument cannot be null."); + + int count = 0; + foreach (var item in list) + count++; + + //writer.StartWriteCollection(count); + + int i = 0; + foreach (object item in list) + { + writer.StartWriteCollectionItem(i); + writer.Write(item, elementType, memberReferenceMode); + writer.EndWriteCollectionItem(i); + i++; + } + + //writer.EndWriteCollection(); + } + + public override object Read(ES3Reader reader) + { + var val = Read(reader); + if (val == null) + return default(T); + return (T)val; + } + + + public override object Read(ES3Reader reader) + { + /*var method = typeof(ES3CollectionType).GetMethod("ReadICollection", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(elementType.type); + if(!(bool)method.Invoke(this, new object[] { reader, list, elementType })) + return null;*/ + + var genericParam = ES3Reflection.GetGenericArguments(type)[0]; + var listType = ES3Reflection.MakeGenericType(typeof(List<>), genericParam); + var list = (IList)ES3Reflection.CreateInstance(listType); + + if (!reader.StartReadCollection()) + { + // Iterate through each character until we reach the end of the array. + while (true) + { + if (!reader.StartReadCollectionItem()) + break; + list.Add(reader.Read(elementType)); + + if (reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + } + + return ES3Reflection.CreateInstance(type, list); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + ReadInto(reader, obj); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + throw new NotImplementedException("Cannot use LoadInto/ReadInto with HashSet because HashSets do not maintain the order of elements"); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3HashSetType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3HashSetType.cs.meta new file mode 100644 index 0000000..1301c2e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3HashSetType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e2a5f03b11de242bf9f3c6766875188b +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ListType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ListType.cs new file mode 100644 index 0000000..931b02f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ListType.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3ListType : ES3CollectionType + { + public ES3ListType(Type type) : base(type){} + public ES3ListType(Type type, ES3Type elementType) : base(type, elementType){} + + public override void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode) + { + if(obj == null){ writer.WriteNull(); return; }; + + var list = (IList)obj; + + if(elementType == null) + throw new ArgumentNullException("ES3Type argument cannot be null."); + + //writer.StartWriteCollection(); + + int i = 0; + foreach(object item in list) + { + writer.StartWriteCollectionItem(i); + writer.Write(item, elementType, memberReferenceMode); + writer.EndWriteCollectionItem(i); + i++; + } + + //writer.EndWriteCollection(); + } + + public override object Read(ES3Reader reader) + { + return Read(reader); + + /*var list = new List(); + if(!ReadICollection(reader, list, elementType)) + return null; + return list;*/ + } + + public override void ReadInto(ES3Reader reader, object obj) + { + ReadICollectionInto(reader, (ICollection)obj, elementType); + } + + public override object Read(ES3Reader reader) + { + var instance = (IList)ES3Reflection.CreateInstance(type); + + if(reader.StartReadCollection()) + return null; + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadCollectionItem()) + break; + instance.Add(reader.Read(elementType)); + + if(reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var collection = (IList)obj; + + if(reader.StartReadCollection()) + throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + int itemsLoaded = 0; + + // Iterate through each item in the collection and try to load it. + foreach(var item in collection) + { + itemsLoaded++; + + if(!reader.StartReadCollectionItem()) + break; + + reader.ReadInto(item, elementType); + + // If we find a ']', we reached the end of the array. + if(reader.EndReadCollectionItem()) + break; + + // If there's still items to load, but we've reached the end of the collection we're loading into, throw an error. + if(itemsLoaded == collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is longer than the collection provided as a parameter."); + } + + // If we loaded fewer items than the parameter collection, throw index out of range exception. + if(itemsLoaded != collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is shorter than the collection provided as a parameter."); + + reader.EndReadCollection(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ListType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ListType.cs.meta new file mode 100644 index 0000000..628bd82 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3ListType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3502f1923072c49498bb91827fae42eb +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3NativeArrayType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3NativeArrayType.cs new file mode 100644 index 0000000..36b3065 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3NativeArrayType.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; +using System.Linq; +using Unity.Collections; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3NativeArrayType : ES3CollectionType + { + public ES3NativeArrayType(Type type) : base(type){} + public ES3NativeArrayType(Type type, ES3Type elementType) : base(type, elementType){} + + public override void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode) + { + if (elementType == null) + throw new ArgumentNullException("ES3Type argument cannot be null."); + + var enumerable = (IEnumerable)obj; + + int i = 0; + foreach(var item in enumerable) + { + writer.StartWriteCollectionItem(i); + writer.Write(item, elementType, memberReferenceMode); + writer.EndWriteCollectionItem(i); + i++; + } + } + + public override object Read(ES3Reader reader) + { + var array = ReadAsArray(reader); + + return ES3Reflection.CreateInstance(type, new object[] { array, Allocator.Persistent }); + } + + public override object Read(ES3Reader reader) + { + return Read(reader); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + ReadInto(reader, obj); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var array = ReadAsArray(reader); + var copyFromMethod = ES3Reflection.GetMethods(type, "CopyFrom").First(m => ES3Reflection.TypeIsArray(m.GetParameters()[0].GetType())); + copyFromMethod.Invoke(obj, new object[] { array }); + } + + private System.Array ReadAsArray(ES3Reader reader) + { + var list = new List(); + if (!ReadICollection(reader, list, elementType)) + return null; + + var array = ES3Reflection.ArrayCreateInstance(elementType.type, list.Count); + int i = 0; + foreach (var item in list) + { + array.SetValue(item, i); + i++; + } + + return array; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3NativeArrayType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3NativeArrayType.cs.meta new file mode 100644 index 0000000..fb46dc1 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3NativeArrayType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0dee780de7e2d074bb6ceff11f18d540 +timeCreated: 1519132289 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3QueueType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3QueueType.cs new file mode 100644 index 0000000..e204a53 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3QueueType.cs @@ -0,0 +1,147 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3QueueType : ES3CollectionType + { + public ES3QueueType(Type type) : base(type){} + + public override void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode) + { + var list = (ICollection)obj; + + if(elementType == null) + throw new ArgumentNullException("ES3Type argument cannot be null."); + + //writer.StartWriteCollection(); + + int i = 0; + foreach(object item in list) + { + writer.StartWriteCollectionItem(i); + writer.Write(item, elementType, memberReferenceMode); + writer.EndWriteCollectionItem(i); + i++; + } + + //writer.EndWriteCollection(); + } + + public override object Read(ES3Reader reader) + { + return Read(reader); + /*if(reader.StartReadCollection()) + return null; + + var queue = new Queue(); + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadCollectionItem()) + break; + queue.Enqueue(reader.Read(elementType)); + if(reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + return queue;*/ + } + + public override void ReadInto(ES3Reader reader, object obj) + { + if(reader.StartReadCollection()) + throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + int itemsLoaded = 0; + + var queue = (Queue)obj; + + // Iterate through each item in the collection and try to load it. + foreach(var item in queue) + { + itemsLoaded++; + + if(!reader.StartReadCollectionItem()) + break; + + reader.ReadInto(item, elementType); + + // If we find a ']', we reached the end of the array. + if(reader.EndReadCollectionItem()) + break; + // If there's still items to load, but we've reached the end of the collection we're loading into, throw an error. + if(itemsLoaded == queue.Count) + throw new IndexOutOfRangeException("The collection we are loading is longer than the collection provided as a parameter."); + } + + // If we loaded fewer items than the parameter collection, throw index out of range exception. + if(itemsLoaded != queue.Count) + throw new IndexOutOfRangeException("The collection we are loading is shorter than the collection provided as a parameter."); + + reader.EndReadCollection(); + } + + public override object Read(ES3Reader reader) + { + var instance = (IList)ES3Reflection.CreateInstance(ES3Reflection.MakeGenericType(typeof(List<>), elementType.type)); + + if(reader.StartReadCollection()) + return null; + + // Iterate through each character until we reach the end of the array. + while(true) + { + if (!reader.StartReadCollectionItem()) + break; + instance.Add(reader.Read(elementType)); + + if (reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + + return ES3Reflection.CreateInstance(type, instance); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + if(reader.StartReadCollection()) + throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + int itemsLoaded = 0; + + var collection = (ICollection)obj; + + // Iterate through each item in the collection and try to load it. + foreach(var item in collection) + { + itemsLoaded++; + + if(!reader.StartReadCollectionItem()) + break; + + reader.ReadInto(item, elementType); + + // If we find a ']', we reached the end of the array. + if(reader.EndReadCollectionItem()) + break; + // If there's still items to load, but we've reached the end of the collection we're loading into, throw an error. + if(itemsLoaded == collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is longer than the collection provided as a parameter."); + } + + // If we loaded fewer items than the parameter collection, throw index out of range exception. + if(itemsLoaded != collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is shorter than the collection provided as a parameter."); + + reader.EndReadCollection(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3QueueType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3QueueType.cs.meta new file mode 100644 index 0000000..98238b8 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3QueueType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0832bfdeae2dc410db8d4963332335c7 +timeCreated: 1519132279 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3StackType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3StackType.cs new file mode 100644 index 0000000..2b20dbf --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3StackType.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; +using System.Reflection; +using System.Linq; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3StackType : ES3CollectionType + { + public ES3StackType(Type type) : base(type){} + + public override void Write(object obj, ES3Writer writer, ES3.ReferenceMode memberReferenceMode) + { + var list = (ICollection)obj; + + if(elementType == null) + throw new ArgumentNullException("ES3Type argument cannot be null."); + + //writer.StartWriteCollection(); + + int i = 0; + foreach(object item in list) + { + writer.StartWriteCollectionItem(i); + writer.Write(item, elementType, memberReferenceMode); + writer.EndWriteCollectionItem(i); + i++; + } + + //writer.EndWriteCollection(); + } + + public override object Read(ES3Reader reader) + { + return Read(reader); + /*if(reader.StartReadCollection()) + return null; + + var stack = new Stack(); + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadCollectionItem()) + break; + stack.Push(reader.Read(elementType)); + if(reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + return stack;*/ + } + + public override void ReadInto(ES3Reader reader, object obj) + { + if(reader.StartReadCollection()) + throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + int itemsLoaded = 0; + + var stack = (Stack)obj; + + // Iterate through each item in the collection and try to load it. + foreach(var item in stack) + { + itemsLoaded++; + + if(!reader.StartReadCollectionItem()) + break; + + reader.ReadInto(item, elementType); + + // If we find a ']', we reached the end of the array. + if(reader.EndReadCollectionItem()) + break; + // If there's still items to load, but we've reached the end of the collection we're loading into, throw an error. + if(itemsLoaded == stack.Count) + throw new IndexOutOfRangeException("The collection we are loading is longer than the collection provided as a parameter."); + } + + // If we loaded fewer items than the parameter collection, throw index out of range exception. + if(itemsLoaded != stack.Count) + throw new IndexOutOfRangeException("The collection we are loading is shorter than the collection provided as a parameter."); + + reader.EndReadCollection(); + } + + public override object Read(ES3Reader reader) + { + var instance = (IList)ES3Reflection.CreateInstance(ES3Reflection.MakeGenericType(typeof(List<>), elementType.type)); + + if(reader.StartReadCollection()) + return null; + + // Iterate through each character until we reach the end of the array. + while(true) + { + if(!reader.StartReadCollectionItem()) + break; + instance.Add(reader.Read(elementType)); + + if(reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + + ES3Reflection.GetMethods(instance.GetType(), "Reverse").FirstOrDefault(t => !t.IsStatic).Invoke(instance, new object[]{}); + return ES3Reflection.CreateInstance(type, instance); + + } + + public override void ReadInto(ES3Reader reader, object obj) + { + if(reader.StartReadCollection()) + throw new NullReferenceException("The Collection we are trying to load is stored as null, which is not allowed when using ReadInto methods."); + + int itemsLoaded = 0; + + var collection = (ICollection)obj; + + // Iterate through each item in the collection and try to load it. + foreach(var item in collection) + { + itemsLoaded++; + + if(!reader.StartReadCollectionItem()) + break; + + reader.ReadInto(item, elementType); + + // If we find a ']', we reached the end of the array. + if(reader.EndReadCollectionItem()) + break; + // If there's still items to load, but we've reached the end of the collection we're loading into, throw an error. + if(itemsLoaded == collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is longer than the collection provided as a parameter."); + } + + // If we loaded fewer items than the parameter collection, throw index out of range exception. + if(itemsLoaded != collection.Count) + throw new IndexOutOfRangeException("The collection we are loading is shorter than the collection provided as a parameter."); + + reader.EndReadCollection(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3StackType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3StackType.cs.meta new file mode 100644 index 0000000..549bb64 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3StackType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 45a74cb7ab3d648208c9f89b7be930a7 +timeCreated: 1519132284 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3TupleType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3TupleType.cs new file mode 100644 index 0000000..cf53b5a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3TupleType.cs @@ -0,0 +1,78 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3TupleType : ES3Type + { + public ES3Type[] es3Types; + public Type[] types; + + protected ES3Reflection.ES3ReflectedMethod readMethod = null; + protected ES3Reflection.ES3ReflectedMethod readIntoMethod = null; + + public ES3TupleType(Type type) : base(type) + { + types = ES3Reflection.GetElementTypes(type); + es3Types = new ES3Type[types.Length]; + + for(int i=0; i(ES3Reader reader) + { + var objects = new object[types.Length]; + + if (reader.StartReadCollection()) + return null; + + for(int i=0; i(es3Types[i]); + reader.EndReadCollectionItem(); + } + + reader.EndReadCollection(); + + var constructor = type.GetConstructor(types); + var instance = constructor.Invoke(objects); + + return instance; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3TupleType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3TupleType.cs.meta new file mode 100644 index 0000000..eb7440c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3TupleType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8d2309c133bf4514784522dda2afb0fc +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3Type_ArrayList.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3Type_ArrayList.cs new file mode 100644 index 0000000..fa97fdb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3Type_ArrayList.cs @@ -0,0 +1,66 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("_items", "_size", "_version")] + public class ES3Type_ArrayList : ES3ObjectType + { + public static ES3Type Instance = null; + + public ES3Type_ArrayList() : base(typeof(System.Collections.ArrayList)) { Instance = this; } + + + protected override void WriteObject(object obj, ES3Writer writer) + { + var instance = (System.Collections.ArrayList)obj; + + writer.WritePrivateField("_items", instance); + writer.WritePrivateField("_size", instance); + writer.WritePrivateField("_version", instance); + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var instance = (System.Collections.ArrayList)obj; + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + + case "_items": + instance = (System.Collections.ArrayList)reader.SetPrivateField("_items", reader.Read(), instance); + break; + case "_size": + instance = (System.Collections.ArrayList)reader.SetPrivateField("_size", reader.Read(), instance); + break; + case "_version": + instance = (System.Collections.ArrayList)reader.SetPrivateField("_version", reader.Read(), instance); + break; + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadObject(ES3Reader reader) + { + var instance = new System.Collections.ArrayList(); + ReadObject(reader, instance); + return instance; + } + } + + + public class ES3UserType_ArrayListArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3UserType_ArrayListArray() : base(typeof(System.Collections.ArrayList[]), ES3Type_ArrayList.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3Type_ArrayList.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3Type_ArrayList.cs.meta new file mode 100644 index 0000000..fe44bb4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Collection Types/ES3Type_ArrayList.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 49ea5f9a0f640d440a9bd514cd7a7ad0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ComponentType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ComponentType.cs new file mode 100644 index 0000000..b63a593 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ComponentType.cs @@ -0,0 +1,145 @@ +using System; +using UnityEngine; +using System.Collections; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public abstract class ES3ComponentType : ES3UnityObjectType + { + public ES3ComponentType(Type type) : base(type) { } + + protected abstract void WriteComponent(object obj, ES3Writer writer); + protected abstract void ReadComponent(ES3Reader reader, object obj); + + protected const string gameObjectPropertyName = "goID"; + + protected override void WriteUnityObject(object obj, ES3Writer writer) + { + var instance = obj as Component; + if (obj != null && instance == null) + throw new ArgumentException("Only types of UnityEngine.Component can be written with this method, but argument given is type of " + obj.GetType()); + + var refMgr = ES3ReferenceMgrBase.GetManagerFromScene(instance.gameObject.scene); + + if (refMgr != null) + { + // Write the reference of the GameObject so we know what one to attach it to. + writer.WriteProperty(gameObjectPropertyName, refMgr.Add(instance.gameObject).ToString(), ES3Type_string.Instance); + } + WriteComponent(instance, writer); + } + + protected override void ReadUnityObject(ES3Reader reader, object obj) + { + ReadComponent(reader, obj); + } + + protected override object ReadUnityObject(ES3Reader reader) + { + throw new NotImplementedException(); + } + + /* + * It's IMPORTANT that we override ReadObject in ES3UnityObjectType rather than use ReadUnityObject because otherwise the first IF statement will never be called, + * and we will never get the reference ID for the Component we're loading, so if we create a new Component we cannot assign it's correct reference ID. + */ + protected override object ReadObject(ES3Reader reader) + { + var refMgr = ES3ReferenceMgrBase.Current; + long id = -1; + UnityEngine.Object instance = null; + + foreach (string propertyName in reader.Properties) + { + if (propertyName == ES3ReferenceMgrBase.referencePropertyName) + { + id = reader.Read_ref(); + instance = refMgr.Get(id, true); + + /*if (instance != null) + break;*/ + } + else if (propertyName == gameObjectPropertyName) + { + long goID = reader.Read_ref(); + + // If we already have an instance for this Component, don't attempt to create a new GameObject for it. + if (instance != null) + break; + + var go = (GameObject)refMgr.Get(goID, type); + + if (go == null) + { + go = new GameObject("Easy Save 3 Loaded GameObject"); +#if UNITY_EDITOR + go.AddComponent().SetMessage("This GameObject was created because Easy Save could not find a GameObject in the scene with the same instance ID as the GameObject the Component we are loading is attached to.\nTo prevent this from being created, use the LoadInto methods to tell Easy Save what Component the data should be loaded in to."); +#endif + refMgr.Add(go, goID); + } + instance = GetOrAddComponent(go, type); + refMgr.Add(instance, id); + break; + } + else + { + reader.overridePropertiesName = propertyName; + if (instance == null) + { + var go = new GameObject("Easy Save 3 Loaded GameObject"); +#if UNITY_EDITOR + go.AddComponent().SetMessage("This GameObject was created because Easy Save could not find a GameObject in the scene with the same instance ID as the GameObject the Component we are loading is attached to.\nTo prevent this from being created, use the LoadInto methods to tell Easy Save what Component the data should be loaded in to."); +#endif + instance = GetOrAddComponent(go, type); + refMgr.Add(instance, id); + refMgr.Add(go); + } + break; + } + } + + if(instance != null) + ReadComponent(reader, instance); + + return instance; + } + + private static Component GetOrAddComponent(GameObject go, Type type) + { + var c = go.GetComponent(type); + if (c != null) + return c; + return go.AddComponent(type); + + /*if (type == typeof(Transform)) + return go.GetComponent(type); + // Manage types which can only have a single Component attached. + else if (type == typeof(MeshFilter) || type.Name.ToString().Contains("Renderer") || ES3Reflection.AttributeIsDefined(type, typeof(DisallowMultipleComponent))) + return GetOrCreateComponentIfNotExists(go, type); + return go.AddComponent(type);*/ + } + + public static Component CreateComponent(Type type) + { + GameObject go = new GameObject("Easy Save 3 Loaded Component"); +#if UNITY_EDITOR + // If we're running in the Editor, add a description explaining why this object was created. + go.AddComponent().SetMessage("This GameObject was created because Easy Save tried to load a Component with an instance ID which does not exist in this scene.\nTo prevent this from being created, use the LoadInto methods to tell Easy Save what Component the data should be loaded in to.\nThis can also happen if you load a class which references another object, but that object has not yet been loaded. In this case, you should load the object the class references before loading the class."); +#endif + if (type == typeof(Transform)) + return go.GetComponent(type); + return GetOrAddComponent(go, type); + } + + // Creates a Component if one doesn't exist, or returns the existing instance. + /*public static Component GetOrCreateComponentIfNotExists(GameObject go, Type type) + { + Component mf; + if ((mf = go.GetComponent(type)) != null) + return mf; + return go.AddComponent(type); + }*/ + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ComponentType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ComponentType.cs.meta new file mode 100644 index 0000000..c7ba402 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ComponentType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6d82e3d10b49c4028bca528611e53210 +timeCreated: 1499764822 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ObjectType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ObjectType.cs new file mode 100644 index 0000000..093caad --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ObjectType.cs @@ -0,0 +1,80 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public abstract class ES3ObjectType : ES3Type + { + public ES3ObjectType(Type type) : base(type) {} + + protected abstract void WriteObject(object obj, ES3Writer writer); + protected abstract object ReadObject(ES3Reader reader); + + protected virtual void ReadObject(ES3Reader reader, object obj) + { + throw new NotSupportedException("ReadInto is not supported for type "+type); + } + + public override void Write(object obj, ES3Writer writer) + { + if (!WriteUsingDerivedType(obj, writer)) + { + var baseType = ES3Reflection.BaseType(obj.GetType()); + if (baseType != typeof(object)) + { + var es3Type = ES3TypeMgr.GetOrCreateES3Type(baseType, false); + // If it's a Dictionary or Collection, we need to write it as a field with a property name. + if (es3Type != null && (es3Type.isDictionary || es3Type.isCollection)) + writer.WriteProperty("_Values", obj, es3Type); + } + + WriteObject(obj, writer); + } + } + + public override object Read(ES3Reader reader) + { + string propertyName; + while(true) + { + propertyName = ReadPropertyName(reader); + + if(propertyName == ES3Type.typeFieldName) + return ES3TypeMgr.GetOrCreateES3Type(reader.ReadType()).Read(reader); + else + { + reader.overridePropertiesName = propertyName; + + return ReadObject(reader); + } + } + } + + public override void ReadInto(ES3Reader reader, object obj) + { + string propertyName; + while(true) + { + propertyName = ReadPropertyName(reader); + + if(propertyName == ES3Type.typeFieldName) + { + ES3TypeMgr.GetOrCreateES3Type(reader.ReadType()).ReadInto(reader, obj); + return; + } + // This is important we return if the enumerator returns null, otherwise we will encounter an endless cycle. + else if (propertyName == null) + return; + else + { + reader.overridePropertiesName = propertyName; + ReadObject(reader, obj); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ObjectType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ObjectType.cs.meta new file mode 100644 index 0000000..fd73df3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ObjectType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2becffd8c9d4e4e0db6031d9680eae48 +timeCreated: 1499764821 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3Property.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3Property.cs new file mode 100644 index 0000000..26e6369 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3Property.cs @@ -0,0 +1,30 @@ +using System; +using System.ComponentModel; + +namespace ES3Internal +{ + public class ES3Member + { + public string name; + public Type type; + public bool isProperty; + public ES3Reflection.ES3ReflectedMember reflectedMember; + public bool useReflection = false; + + public ES3Member(string name, Type type, bool isProperty) + { + this.name = name; + this.type = type; + this.isProperty = isProperty; + } + + public ES3Member(ES3Reflection.ES3ReflectedMember reflectedMember) + { + this.reflectedMember = reflectedMember; + this.name = reflectedMember.Name; + this.type = reflectedMember.MemberType; + this.isProperty = reflectedMember.isProperty; + this.useReflection = true; + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3Property.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3Property.cs.meta new file mode 100644 index 0000000..f3f82e0 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3Property.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b987e63c8e10f448c8364eaceddd96e5 +timeCreated: 1519132295 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ScriptableObjectType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ScriptableObjectType.cs new file mode 100644 index 0000000..d388055 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ScriptableObjectType.cs @@ -0,0 +1,75 @@ +using System; +using UnityEngine; +using System.Collections; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public abstract class ES3ScriptableObjectType : ES3UnityObjectType + { + public ES3ScriptableObjectType(Type type) : base(type) {} + + protected abstract void WriteScriptableObject(object obj, ES3Writer writer); + protected abstract void ReadScriptableObject(ES3Reader reader, object obj); + + protected override void WriteUnityObject(object obj, ES3Writer writer) + { + var instance = obj as ScriptableObject; + if(obj != null && instance == null) + throw new ArgumentException("Only types of UnityEngine.ScriptableObject can be written with this method, but argument given is type of "+obj.GetType()); + + // If this object is in the instance manager, store it's instance ID with it. + /*var refMgr = ES3ReferenceMgrBase.Current; + if(refMgr != null) + writer.WriteRef(instance);*/ + WriteScriptableObject(instance, writer); + } + + protected override void ReadUnityObject(ES3Reader reader, object obj) + { + ReadScriptableObject(reader, obj); + } + + protected override object ReadUnityObject(ES3Reader reader) + { + throw new NotImplementedException(); + } + + + protected override object ReadObject(ES3Reader reader) + { + var refMgr = ES3ReferenceMgrBase.Current; + long id = -1; + UnityEngine.Object instance = null; + + foreach(string propertyName in reader.Properties) + { + if(propertyName == ES3ReferenceMgrBase.referencePropertyName && refMgr != null) + { + id = reader.Read_ref(); + instance = refMgr.Get(id, type); + + if (instance != null) + break; + } + else + { + reader.overridePropertiesName = propertyName; + + if (instance == null) + { + instance = ScriptableObject.CreateInstance(type); + if (refMgr != null) + refMgr.Add(instance, id); + } + + break; + } + } + + ReadScriptableObject(reader, instance); + return instance; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ScriptableObjectType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ScriptableObjectType.cs.meta new file mode 100644 index 0000000..f3d9c7b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3ScriptableObjectType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a26529496f04146959460074ab1a9b3f +timeCreated: 1519132293 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3Type.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3Type.cs new file mode 100644 index 0000000..c2d5a3a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3Type.cs @@ -0,0 +1,194 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; +using System.Linq; + +namespace ES3Types +{ + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + [UnityEngine.Scripting.Preserve] + public abstract class ES3Type + { + public const string typeFieldName = "__type"; + + public ES3Member[] members; + public Type type; + public bool isPrimitive = false; + public bool isValueType = false; + public bool isCollection = false; + public bool isDictionary = false; + public bool isTuple = false; + public bool isEnum = false; + public bool isES3TypeUnityObject = false; + public bool isReflectedType = false; + public bool isUnsupported = false; + public int priority = 0; + + protected ES3Type(Type type) + { + // It's important the type is added here, otherwise it may cause a StackOverflow if the class has a field of the same type as itself (or collection). + ES3TypeMgr.Add(type, this); + this.type = type; + this.isValueType = ES3Reflection.IsValueType(type); + } + + public abstract void Write(object obj, ES3Writer writer); + public abstract object Read(ES3Reader reader); + + public virtual void ReadInto(ES3Reader reader, object obj) + { + throw new NotImplementedException("Self-assigning Read is not implemented or supported on this type."); + } + + protected bool WriteUsingDerivedType(object obj, ES3Writer writer) + { + var objType = obj.GetType(); + + if(objType != this.type) + { + writer.WriteType(objType); + ES3TypeMgr.GetOrCreateES3Type(objType).Write(obj, writer); + return true; + } + return false; + } + + protected void ReadUsingDerivedType(ES3Reader reader, object obj) + { + ES3TypeMgr.GetOrCreateES3Type(reader.ReadType()).ReadInto(reader, obj); + } + + internal string ReadPropertyName(ES3Reader reader) + { + if(reader.overridePropertiesName != null) + { + string propertyName = reader.overridePropertiesName; + reader.overridePropertiesName = null; + return propertyName; + } + return reader.ReadPropertyName(); + } + + #region Reflection Methods + + protected void WriteProperties(object obj, ES3Writer writer) + { + if(members == null) + GetMembers(writer.settings.safeReflection); + + for(int i=0; i(reader); + foreach (DictionaryEntry kvp in loaded) + dict[kvp.Key] = kvp.Value; + } + else if(baseType.isCollection) + { + var loaded = (IEnumerable)baseType.Read(reader); + + var type = baseType.GetType(); + + if (type == typeof(ES3ListType)) + foreach (var item in loaded) + ((IList)obj).Add(item); + else if (type == typeof(ES3QueueType)) + { + var method = baseType.type.GetMethod("Enqueue"); + foreach (var item in loaded) + method.Invoke(obj, new object[] { item }); + } + else if (type == typeof(ES3StackType)) + { + var method = baseType.type.GetMethod("Push"); + foreach (var item in loaded) + method.Invoke(obj, new object[] { item }); + } + else if (type == typeof(ES3HashSetType)) + { + var method = baseType.type.GetMethod("Add"); + foreach (var item in loaded) + method.Invoke(obj, new object[] { item }); + } + } + } + + if (property == null) + reader.Skip(); + else + { + var type = ES3TypeMgr.GetOrCreateES3Type(property.type); + + if(ES3Reflection.IsAssignableFrom(typeof(ES3DictionaryType), type.GetType())) + property.reflectedMember.SetValue(obj, ((ES3DictionaryType)type).Read(reader)); + else if(ES3Reflection.IsAssignableFrom(typeof(ES3CollectionType), type.GetType())) + property.reflectedMember.SetValue(obj, ((ES3CollectionType)type).Read(reader)); + else + { + object readObj = reader.Read(type); + property.reflectedMember.SetValue(obj, readObj); + } + } + } + return obj; + } + + protected void GetMembers(bool safe) + { + GetMembers(safe, null); + } + + protected void GetMembers(bool safe, string[] memberNames) + { + var serializedMembers = ES3Reflection.GetSerializableMembers(type, safe, memberNames); + + members = new ES3Member[serializedMembers.Length]; + for(int i=0; i types = null; + + // We cache the last accessed type as we quite often use the same type multiple times, + // so this improves performance as another lookup is not required. + private static ES3Type lastAccessedType = null; + + public static ES3Type GetOrCreateES3Type(Type type, bool throwException = true) + { + if(types == null) + Init(); + + if (type != typeof(object) && lastAccessedType != null && lastAccessedType.type == type) + return lastAccessedType; + + // If type doesn't exist, create one. + if(types.TryGetValue(type, out lastAccessedType)) + return lastAccessedType; + return (lastAccessedType = CreateES3Type(type, throwException)); + } + + public static ES3Type GetES3Type(Type type) + { + if(types == null) + Init(); + + if(types.TryGetValue(type, out lastAccessedType)) + return lastAccessedType; + return null; + } + + internal static void Add(Type type, ES3Type es3Type) + { + if(types == null) + Init(); + + var existingType = GetES3Type(type); + if (existingType != null && existingType.priority > es3Type.priority) + return; + + lock (_lock) + { + types[type] = es3Type; + } + } + + internal static ES3Type CreateES3Type(Type type, bool throwException = true) + { + ES3Type es3Type; + + if(ES3Reflection.IsEnum(type)) + return new ES3Type_enum(type); + else if(ES3Reflection.TypeIsArray(type)) + { + int rank = ES3Reflection.GetArrayRank(type); + if(rank == 1) + es3Type = new ES3ArrayType(type); + else if(rank == 2) + es3Type = new ES32DArrayType(type); + else if(rank == 3) + es3Type = new ES33DArrayType(type); + else if(throwException) + throw new NotSupportedException("Only arrays with up to three dimensions are supported by Easy Save."); + else + return null; + } + else if(ES3Reflection.IsGenericType(type) && ES3Reflection.ImplementsInterface(type, typeof(IEnumerable))) + { + Type genericType = ES3Reflection.GetGenericTypeDefinition(type); + if (typeof(List<>).IsAssignableFrom(genericType)) + es3Type = new ES3ListType(type); + else if (typeof(Dictionary<,>).IsAssignableFrom(genericType)) + es3Type = new ES3DictionaryType(type); + else if (genericType == typeof(Queue<>)) + es3Type = new ES3QueueType(type); + else if (genericType == typeof(Stack<>)) + es3Type = new ES3StackType(type); + else if (genericType == typeof(HashSet<>)) + es3Type = new ES3HashSetType(type); + else if (genericType == typeof(Unity.Collections.NativeArray<>)) + es3Type = new ES3NativeArrayType(type); + // Else see if there is an ES3Type with the generic type definition. + else if((es3Type = GetES3Type(genericType)) != null) + { + + } + else if (throwException) + throw new NotSupportedException("Generic type \"" + type.ToString() + "\" is not supported by Easy Save."); + else + return null; + } + else if(ES3Reflection.IsPrimitive(type)) // ERROR: We should not have to create an ES3Type for a primitive. + { + if(types == null || types.Count == 0) // If the type list is not initialised, it is most likely an initialisation error. + throw new TypeLoadException("ES3Type for primitive could not be found, and the type list is empty. Please contact Easy Save developers at http://www.moodkie.com/contact"); + else // Else it's a different error, possibly an error in the specific ES3Type for that type. + throw new TypeLoadException("ES3Type for primitive could not be found, but the type list has been initialised and is not empty. Please contact Easy Save developers on mail@moodkie.com"); + } + else + { + if (ES3Reflection.IsAssignableFrom(typeof(Component), type)) + es3Type = new ES3ReflectedComponentType(type); + else if (ES3Reflection.IsValueType(type)) + es3Type = new ES3ReflectedValueType(type); + else if (ES3Reflection.IsAssignableFrom(typeof(ScriptableObject), type)) + es3Type = new ES3ReflectedScriptableObjectType(type); + else if (ES3Reflection.IsAssignableFrom(typeof(UnityEngine.Object), type)) + es3Type = new ES3ReflectedUnityObjectType(type); + /*else if (ES3Reflection.HasParameterlessConstructor(type) || ES3Reflection.IsAbstract(type) || ES3Reflection.IsInterface(type)) + es3Type = new ES3ReflectedObjectType(type);*/ + else if (type.Name.StartsWith("Tuple`")) + es3Type = new ES3TupleType(type); + /*else if (throwException) + throw new NotSupportedException("Type of " + type + " is not supported as it does not have a parameterless constructor. Only value types, Components or ScriptableObjects are supportable without a parameterless constructor. However, you may be able to create an ES3Type script to add support for it.");*/ + else + es3Type = new ES3ReflectedObjectType(type); + } + + if(es3Type.type == null || es3Type.isUnsupported) + { + if(throwException) + throw new NotSupportedException(string.Format("ES3Type.type is null when trying to create an ES3Type for {0}, possibly because the element type is not supported.", type)); + return null; + } + + Add(type, es3Type); + return es3Type; + } + + internal static void Init() + { + lock (_lock) + { + types = new Dictionary(); + + var instances = ES3Reflection.GetInstances(); // ES3Types add themselves to the manager when instantiated to ensure they don't cause cyclic references if they contain a field which is the same type as themselves. + + /*foreach(var instance in instances) + ES3TypeMgr.Add(instance.type, instance);*/ + + // Check that the type list was initialised correctly. + if (types == null || types.Count == 0) + throw new TypeLoadException("Type list could not be initialised. Please contact Easy Save developers on mail@moodkie.com."); + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3TypeMgr.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3TypeMgr.cs.meta new file mode 100644 index 0000000..3b697d6 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3TypeMgr.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ed6202a98cbc545a0842c63cf8894b99 +timeCreated: 1499764823 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3UnityObjectType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3UnityObjectType.cs new file mode 100644 index 0000000..03e61bc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3UnityObjectType.cs @@ -0,0 +1,123 @@ +using System; +using UnityEngine; +using System.Collections; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public abstract class ES3UnityObjectType : ES3ObjectType + { + public ES3UnityObjectType(Type type) : base(type) + { + this.isValueType = false; + isES3TypeUnityObject = true; + } + + protected abstract void WriteUnityObject(object obj, ES3Writer writer); + protected abstract void ReadUnityObject(ES3Reader reader, object obj); + protected abstract object ReadUnityObject(ES3Reader reader); + + protected override void WriteObject(object obj, ES3Writer writer) + { + WriteObject(obj, writer, ES3.ReferenceMode.ByRefAndValue); + } + + public virtual void WriteObject(object obj, ES3Writer writer, ES3.ReferenceMode mode) + { + if(WriteUsingDerivedType(obj, writer, mode)) + return; + var instance = obj as UnityEngine.Object; + if(obj != null && instance == null) + throw new ArgumentException("Only types of UnityEngine.Object can be written with this method, but argument given is type of "+obj.GetType()); + + // If this object is in the instance manager, store it's instance ID with it. + if(mode != ES3.ReferenceMode.ByValue) + { + var refMgr = ES3ReferenceMgrBase.Current; + if (refMgr == null) + throw new InvalidOperationException($"An Easy Save 3 Manager is required to save references. To add one to your scene, exit playmode and go to Tools > Easy Save 3 > Add Manager to Scene. Object being saved by reference is {instance.GetType()} with name {instance.name}."); + writer.WriteRef(instance); + if(mode == ES3.ReferenceMode.ByRef) + return; + } + WriteUnityObject(instance, writer); + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var refMgr = ES3ReferenceMgrBase.Current; + if (refMgr != null) + { + foreach (string propertyName in reader.Properties) + { + if (propertyName == ES3ReferenceMgrBase.referencePropertyName) + // If the object we're loading into isn't registered with the reference manager, register it. + refMgr.Add((UnityEngine.Object)obj, reader.Read_ref()); + else + { + reader.overridePropertiesName = propertyName; + break; + } + } + } + ReadUnityObject(reader, obj); + } + + protected override object ReadObject(ES3Reader reader) + { + var refMgr = ES3ReferenceMgrBase.Current; + if(refMgr == null) + return ReadUnityObject(reader); + + long id = -1; + UnityEngine.Object instance = null; + + foreach(string propertyName in reader.Properties) + { + if(propertyName == ES3ReferenceMgrBase.referencePropertyName) + { + if(refMgr == null) + throw new InvalidOperationException($"An Easy Save 3 Manager is required to save references. To add one to your scene, exit playmode and go to Tools > Easy Save 3 > Add Manager to Scene. Object being saved by reference is {instance.GetType()} with name {instance.name}."); + id = reader.Read_ref(); + instance = refMgr.Get(id, type); + + if(instance != null) + break; + } + else + { + reader.overridePropertiesName = propertyName; + if (instance == null) + { + instance = (UnityEngine.Object)ReadUnityObject(reader); + refMgr.Add(instance, id); + } + break; + } + } + + ReadUnityObject(reader, instance); + return instance; + } + + protected bool WriteUsingDerivedType(object obj, ES3Writer writer, ES3.ReferenceMode mode) + { + var objType = obj.GetType(); + + if (objType != this.type) + { + writer.WriteType(objType); + + var es3Type = ES3TypeMgr.GetOrCreateES3Type(objType); + if (es3Type is ES3UnityObjectType) + ((ES3UnityObjectType)es3Type).WriteObject(obj, writer, mode); + else + es3Type.Write(obj, writer); + + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3UnityObjectType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3UnityObjectType.cs.meta new file mode 100644 index 0000000..ac4d029 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/ES3UnityObjectType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6206e73d6e9414301b5475296e1103a2 +timeCreated: 1519132286 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types.meta new file mode 100644 index 0000000..f90e319 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 60a49d37763187541924d866f78fd6de +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_BigInteger.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_BigInteger.cs new file mode 100644 index 0000000..f9fae40 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_BigInteger.cs @@ -0,0 +1,38 @@ +using System.Numerics; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3Properties("bytes")] + public class ES3Type_BigInteger : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_BigInteger() : base(typeof(BigInteger)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + BigInteger casted = (BigInteger)obj; + writer.WriteProperty("bytes", casted.ToByteArray(), ES3Type_byteArray.Instance); + } + + public override object Read(ES3Reader reader) + { + return new BigInteger(reader.ReadProperty(ES3Type_byteArray.Instance)); + } + } + + public class ES3Type_BigIntegerArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_BigIntegerArray() : base(typeof(BigInteger[]), ES3Type_BigInteger.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_BigInteger.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_BigInteger.cs.meta new file mode 100644 index 0000000..70524b5 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_BigInteger.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b3375f14105a7074b92a27519e7a9bb4 +timeCreated: 1538210707 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Random.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Random.cs new file mode 100644 index 0000000..1a51b47 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Random.cs @@ -0,0 +1,71 @@ +/* + * System.Random is no longer serializable at runtime due to Unity changing the implementation away from .NET. + */ + +using System; +using UnityEngine; + +namespace ES3Types +{ +#if !UNITY_2021_2_OR_NEWER + + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("inext", "inextp", "SeedArray")] + public class ES3Type_Random : ES3ObjectType + { + public static ES3Type Instance = null; + + public ES3Type_Random() : base(typeof(System.Random)){ Instance = this; } + + protected override void WriteObject(object obj, ES3Writer writer) + { + var instance = (System.Random)obj; + + writer.WritePrivateField("inext", instance); + writer.WritePrivateField("inextp", instance); + writer.WritePrivateField("SeedArray", instance); + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var instance = (System.Random)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "inext": + reader.SetPrivateField("inext", reader.Read(), instance); + break; + case "inextp": + reader.SetPrivateField("inextp", reader.Read(), instance); + break; + case "SeedArray": + reader.SetPrivateField("SeedArray", reader.Read(), instance); + break; + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadObject(ES3Reader reader) + { + var instance = new System.Random(); + ReadObject(reader, instance); + return instance; + } + } + + public class ES3Type_RandomArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_RandomArray() : base(typeof(System.Random[]), ES3Type_Random.Instance) + { + Instance = this; + } + } +#endif +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Random.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Random.cs.meta new file mode 100644 index 0000000..a207ee3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Random.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 84232cc4cb5a646249f6ebe5eeee1e97 +timeCreated: 1538210707 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Type.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Type.cs new file mode 100644 index 0000000..1a3cf7e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Type.cs @@ -0,0 +1,27 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3Properties()] + public class ES3Type_Type : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Type() : base(typeof(System.Type)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Type type = (Type)obj; + writer.WriteProperty("assemblyQualifiedName", type.AssemblyQualifiedName); + } + + public override object Read(ES3Reader reader) + { + return Type.GetType(reader.ReadProperty()); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Type.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Type.cs.meta new file mode 100644 index 0000000..6e403dc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/NET Types/ES3Type_Type.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 1fe3873c075a7c2409980f2e5e400017 +timeCreated: 1538210707 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types.meta new file mode 100644 index 0000000..5b75b66 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 178eaa3e3d545104da9b4aaa74f7318f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_DateTime.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_DateTime.cs new file mode 100644 index 0000000..0dbd8eb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_DateTime.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_DateTime : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_DateTime() : base(typeof(DateTime)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WriteProperty("ticks", ((DateTime)obj).Ticks, ES3Type_long.Instance); + } + + public override object Read(ES3Reader reader) + { + reader.ReadPropertyName(); + return new DateTime(reader.Read(ES3Type_long.Instance)); + } + } + + public class ES3Type_DateTimeArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_DateTimeArray() : base(typeof(DateTime[]), ES3Type_DateTime.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_DateTime.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_DateTime.cs.meta new file mode 100644 index 0000000..ed6ed0a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_DateTime.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9c9737ff78c714548af339e220b90303 +timeCreated: 1519132292 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ES3Ref.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ES3Ref.cs new file mode 100644 index 0000000..9fffa4c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ES3Ref.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_ES3Ref : ES3Type + { + public static ES3Type Instance = new ES3Type_ES3Ref(); + + public ES3Type_ES3Ref() : base(typeof(long)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive(((long)obj).ToString()); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)new ES3Ref(reader.Read_ref()); + } + } + + public class ES3Type_ES3RefArray : ES3ArrayType + { + public static ES3Type Instance = new ES3Type_ES3RefArray(); + + public ES3Type_ES3RefArray() : base(typeof(ES3Ref[]), ES3Type_ES3Ref.Instance) + { + Instance = this; + } + } + + public class ES3Type_ES3RefDictionary : ES3DictionaryType + { + public static ES3Type Instance = new ES3Type_ES3RefDictionary(); + + public ES3Type_ES3RefDictionary() : base(typeof(Dictionary), ES3Type_ES3Ref.Instance, ES3Type_ES3Ref.Instance) + { + Instance = this; + } + } +} + +public class ES3Ref +{ + public long id; + public ES3Ref(long id) + { + this.id = id; + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ES3Ref.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ES3Ref.cs.meta new file mode 100644 index 0000000..a88c0e0 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ES3Ref.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ab1dd0b4209f2c144ad424236e639426 +timeCreated: 1519132294 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_UIntPtr.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_UIntPtr.cs new file mode 100644 index 0000000..05e8b49 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_UIntPtr.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_UIntPtr : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_UIntPtr() : base(typeof(UIntPtr)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((ulong)obj); + } + + public override object Read(ES3Reader reader) + { + return (object)reader.Read_ulong(); + } + } + + public class ES3Type_UIntPtrArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_UIntPtrArray() : base(typeof(UIntPtr[]), ES3Type_UIntPtr.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_UIntPtr.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_UIntPtr.cs.meta new file mode 100644 index 0000000..e1a3ccb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_UIntPtr.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6fe9eb4dc6fa54989a516115e34602df +timeCreated: 1519132288 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_bool.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_bool.cs new file mode 100644 index 0000000..3a4dd53 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_bool.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_bool : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_bool() : base(typeof(bool)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((bool)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_bool(); + } + } + + public class ES3Type_boolArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_boolArray() : base(typeof(bool[]), ES3Type_bool.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_bool.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_bool.cs.meta new file mode 100644 index 0000000..81ea5f7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_bool.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6fa779d8184f649f897074ba540ab1f9 +timeCreated: 1519132288 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byte.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byte.cs new file mode 100644 index 0000000..00504ff --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byte.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_byte : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_byte() : base(typeof(byte)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((byte)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_byte(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byte.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byte.cs.meta new file mode 100644 index 0000000..d72b280 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byte.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0c6f8718240d84f40a9d4b3ac41b3398 +timeCreated: 1519132280 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byteArray.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byteArray.cs new file mode 100644 index 0000000..6ea34b3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byteArray.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_byteArray : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_byteArray() : base(typeof(byte[])) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((byte[])obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_byteArray(); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byteArray.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byteArray.cs.meta new file mode 100644 index 0000000..614f5dc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_byteArray.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 59bd4a4624c4a4082bb3b8333a399ee2 +timeCreated: 1519132286 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_char.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_char.cs new file mode 100644 index 0000000..47c7466 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_char.cs @@ -0,0 +1,33 @@ +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_char : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_char() : base(typeof(char)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((char)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_char(); + } + } + public class ES3Type_charArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_charArray() : base(typeof(char[]), ES3Type_char.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_char.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_char.cs.meta new file mode 100644 index 0000000..4e5cc82 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_char.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fdc3981e5018244468c97a2bbcbb610a +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_decimal.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_decimal.cs new file mode 100644 index 0000000..50e9428 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_decimal.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_decimal : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_decimal() : base(typeof(decimal)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((decimal)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_decimal(); + } + } + + public class ES3Type_decimalArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_decimalArray() : base(typeof(decimal[]), ES3Type_decimal.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_decimal.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_decimal.cs.meta new file mode 100644 index 0000000..78ea5c7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_decimal.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 030f062403dc345f78476442992e3c9c +timeCreated: 1519132279 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_double.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_double.cs new file mode 100644 index 0000000..6ca2dd3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_double.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_double : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_double() : base(typeof(double)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((double)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_double(); + } + } + + public class ES3Type_doubleArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_doubleArray() : base(typeof(double[]), ES3Type_double.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_double.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_double.cs.meta new file mode 100644 index 0000000..5ccb756 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_double.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c445261bbbfc24045863aa3c2c097a73 +timeCreated: 1519132296 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_enum.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_enum.cs new file mode 100644 index 0000000..311101a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_enum.cs @@ -0,0 +1,59 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_enum : ES3Type + { + public static ES3Type Instance = null; + private Type underlyingType = null; + + public ES3Type_enum(Type type) : base(type) + { + isPrimitive = true; + isEnum = true; + Instance = this; + underlyingType = Enum.GetUnderlyingType(type); + } + + public override void Write(object obj, ES3Writer writer) + { + if(underlyingType == typeof(int)) writer.WritePrimitive((int)obj); + else if(underlyingType == typeof(bool)) writer.WritePrimitive((bool)obj); + else if(underlyingType == typeof(byte)) writer.WritePrimitive((byte)obj); + else if(underlyingType == typeof(char)) writer.WritePrimitive((char)obj); + else if(underlyingType == typeof(decimal)) writer.WritePrimitive((decimal)obj); + else if(underlyingType == typeof(double)) writer.WritePrimitive((double)obj); + else if(underlyingType == typeof(float)) writer.WritePrimitive((float)obj); + else if(underlyingType == typeof(long)) writer.WritePrimitive((long)obj); + else if(underlyingType == typeof(sbyte)) writer.WritePrimitive((sbyte)obj); + else if(underlyingType == typeof(short)) writer.WritePrimitive((short)obj); + else if(underlyingType == typeof(uint)) writer.WritePrimitive((uint)obj); + else if(underlyingType == typeof(ulong)) writer.WritePrimitive((ulong)obj); + else if(underlyingType == typeof(ushort)) writer.WritePrimitive((ushort)obj); + else + throw new System.InvalidCastException("The underlying type " + underlyingType + " of Enum "+type+" is not supported"); + + } + + public override object Read(ES3Reader reader) + { + if(underlyingType == typeof(int)) return Enum.ToObject (type, reader.Read_int()); + else if(underlyingType == typeof(bool)) return Enum.ToObject (type, reader.Read_bool()); + else if(underlyingType == typeof(byte)) return Enum.ToObject (type, reader.Read_byte()); + else if(underlyingType == typeof(char)) return Enum.ToObject (type, reader.Read_char()); + else if(underlyingType == typeof(decimal)) return Enum.ToObject (type, reader.Read_decimal()); + else if(underlyingType == typeof(double)) return Enum.ToObject (type, reader.Read_double()); + else if(underlyingType == typeof(float)) return Enum.ToObject (type, reader.Read_float()); + else if(underlyingType == typeof(long)) return Enum.ToObject (type, reader.Read_long()); + else if(underlyingType == typeof(sbyte)) return Enum.ToObject (type, reader.Read_sbyte()); + else if(underlyingType == typeof(short)) return Enum.ToObject (type, reader.Read_short()); + else if(underlyingType == typeof(uint)) return Enum.ToObject (type, reader.Read_uint()); + else if(underlyingType == typeof(ulong)) return Enum.ToObject (type, reader.Read_ulong()); + else if(underlyingType == typeof(ushort)) return Enum.ToObject (type, reader.Read_ushort()); + else + throw new System.InvalidCastException("The underlying type " + underlyingType + " of Enum "+type+" is not supported"); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_enum.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_enum.cs.meta new file mode 100644 index 0000000..822eee4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_enum.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0bc176cf7e9c84850b4ead41131e66af +timeCreated: 1519132280 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_float.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_float.cs new file mode 100644 index 0000000..220485d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_float.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_float : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_float() : base(typeof(float)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((float)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_float(); + } + } + + public class ES3Type_floatArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_floatArray() : base(typeof(float[]), ES3Type_float.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_float.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_float.cs.meta new file mode 100644 index 0000000..a27a1f6 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_float.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f40643b43129b41ff9143c8a23741391 +timeCreated: 1519132300 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_int.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_int.cs new file mode 100644 index 0000000..6061fac --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_int.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_int : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_int() : base(typeof(int)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((int)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_int(); + } + } + + public class ES3Type_intArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_intArray() : base(typeof(int[]), ES3Type_int.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_int.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_int.cs.meta new file mode 100644 index 0000000..53a2beb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_int.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 13efdffd9de75437f8eb6d09e595e70d +timeCreated: 1519132280 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_intptr.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_intptr.cs new file mode 100644 index 0000000..f2bd8dc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_intptr.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_IntPtr : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_IntPtr() : base(typeof(IntPtr)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((long)(IntPtr)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)(IntPtr)reader.Read_long(); + } + } + + public class ES3Type_IntPtrArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_IntPtrArray() : base(typeof(IntPtr[]), ES3Type_IntPtr.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_intptr.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_intptr.cs.meta new file mode 100644 index 0000000..09cb3a1 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_intptr.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8fe212a329d2d46a482270d9a93d704f +timeCreated: 1519132291 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_long.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_long.cs new file mode 100644 index 0000000..df2271a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_long.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_long : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_long() : base(typeof(long)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((long)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_long(); + } + } + + public class ES3Type_longArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_longArray() : base(typeof(long[]), ES3Type_long.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_long.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_long.cs.meta new file mode 100644 index 0000000..792ad5e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_long.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b534e98b9d5dc4219978a5aada0d11b0 +timeCreated: 1519132294 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_sbyte.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_sbyte.cs new file mode 100644 index 0000000..3e8f210 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_sbyte.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_sbyte : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_sbyte() : base(typeof(sbyte)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((sbyte)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_sbyte(); + } + } + + public class ES3Type_sbyteArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_sbyteArray() : base(typeof(sbyte[]), ES3Type_sbyte.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_sbyte.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_sbyte.cs.meta new file mode 100644 index 0000000..383ec75 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_sbyte.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5aaea33736cb64165b06b21ccffb4dde +timeCreated: 1519132286 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_short.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_short.cs new file mode 100644 index 0000000..391c72a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_short.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_short : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_short() : base(typeof(short)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((short)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_short(); + } + } + + public class ES3Type_shortArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_shortArray() : base(typeof(short[]), ES3Type_short.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_short.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_short.cs.meta new file mode 100644 index 0000000..8088746 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_short.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 62ef5aa170d8444eb9613f6733dace9c +timeCreated: 1519132286 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_string.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_string.cs new file mode 100644 index 0000000..ef8d159 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_string.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_string : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_string() : base(typeof(string)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((string)obj); + } + + public override object Read(ES3Reader reader) + { + return reader.Read_string(); + } + } + + public class ES3Type_StringArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_StringArray() : base(typeof(string[]), ES3Type_string.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_string.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_string.cs.meta new file mode 100644 index 0000000..5c50346 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_string.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 138987e042d4e4283a967a0958ab0a52 +timeCreated: 1519132280 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_uint.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_uint.cs new file mode 100644 index 0000000..854f5c8 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_uint.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_uint : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_uint() : base(typeof(uint)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((uint)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_uint(); + } + } + + public class ES3Type_uintArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_uintArray() : base(typeof(uint[]), ES3Type_uint.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_uint.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_uint.cs.meta new file mode 100644 index 0000000..4c9fcc2 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_uint.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2c39c4f1168884e94b9e7e6087affd2d +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ulong.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ulong.cs new file mode 100644 index 0000000..d18b692 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ulong.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_ulong : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_ulong() : base(typeof(ulong)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((ulong)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_ulong(); + } + } + + public class ES3Type_ulongArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_ulongArray() : base(typeof(ulong[]), ES3Type_ulong.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ulong.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ulong.cs.meta new file mode 100644 index 0000000..2e8f548 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ulong.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f25dca3f336094cababceb772c7e390b +timeCreated: 1519132300 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ushort.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ushort.cs new file mode 100644 index 0000000..11c9e8e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ushort.cs @@ -0,0 +1,37 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_ushort : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_ushort() : base(typeof(ushort)) + { + isPrimitive = true; + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + writer.WritePrimitive((ushort)obj); + } + + public override object Read(ES3Reader reader) + { + return (T)(object)reader.Read_ushort(); + } + } + + public class ES3Type_ushortArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_ushortArray() : base(typeof(ushort[]), ES3Type_ushort.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ushort.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ushort.cs.meta new file mode 100644 index 0000000..37c6b4e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Primitive Types/ES3Type_ushort.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 33d86db06b1954996a48d38a75c76dd9 +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types.meta new file mode 100644 index 0000000..9bb1c59 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6a87015345821154d88fe49466310b9d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedComponentType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedComponentType.cs new file mode 100644 index 0000000..a1d1ca0 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedComponentType.cs @@ -0,0 +1,24 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + internal class ES3ReflectedComponentType : ES3ComponentType + { + public ES3ReflectedComponentType(Type type) : base(type) + { + isReflectedType = true; + GetMembers(true); + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + WriteProperties(obj, writer); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + ReadProperties(reader, obj); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedComponentType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedComponentType.cs.meta new file mode 100644 index 0000000..9a62402 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedComponentType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2b125647af96a4b5494ca82d1da9a9e6 +timeCreated: 1499764821 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedObjectType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedObjectType.cs new file mode 100644 index 0000000..2c57caa --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedObjectType.cs @@ -0,0 +1,35 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + internal class ES3ReflectedObjectType : ES3ObjectType + { + public ES3ReflectedObjectType(Type type) : base(type) + { + isReflectedType = true; + GetMembers(true); + } + + protected override void WriteObject(object obj, ES3Writer writer) + { + WriteProperties(obj, writer); + } + + protected override object ReadObject(ES3Reader reader) + { + var obj = ES3Reflection.CreateInstance(this.type); + ReadProperties(reader, obj); + return obj; + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + ReadProperties(reader, obj); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedObjectType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedObjectType.cs.meta new file mode 100644 index 0000000..99d776e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedObjectType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d239970ac781b4079bda34e2999dc775 +timeCreated: 1519132297 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedScriptableObjectType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedScriptableObjectType.cs new file mode 100644 index 0000000..b53b487 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedScriptableObjectType.cs @@ -0,0 +1,27 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + internal class ES3ReflectedScriptableObjectType : ES3ScriptableObjectType + { + public ES3ReflectedScriptableObjectType(Type type) : base(type) + { + isReflectedType = true; + GetMembers(true); + } + + protected override void WriteScriptableObject(object obj, ES3Writer writer) + { + WriteProperties(obj, writer); + } + + protected override void ReadScriptableObject(ES3Reader reader, object obj) + { + ReadProperties(reader, obj); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedScriptableObjectType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedScriptableObjectType.cs.meta new file mode 100644 index 0000000..45d7433 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedScriptableObjectType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: dd9e88c6e3735412ab2033c284212528 +timeCreated: 1519132298 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedType.cs new file mode 100644 index 0000000..b195113 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedType.cs @@ -0,0 +1,119 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + internal class ES3ReflectedType : ES3Type + { + public ES3ReflectedType(Type type) : base(type) + { + isReflectedType = true; + } + + // Constructs a reflected ES3Type, only serializing members which are in the provided members array. + public ES3ReflectedType(Type type, string[] members) : this(type) + { + GetMembers(false, members); + } + + public override void Write(object obj, ES3Writer writer) + { + // Manage NULL values. + if(obj == null){writer.WriteNull(); return;}; + + UnityEngine.Object unityObj = obj as UnityEngine.Object; + bool isUnityEngineObject = (unityObj != null); + + // If this is a derived type, write the type as a property and use it's specific ES3Type. + var objType = obj.GetType(); + if(objType != this.type) + { + writer.WriteType(objType); + ES3TypeMgr.GetOrCreateES3Type(objType).Write(obj, writer); + return; + } + + if(isUnityEngineObject) + writer.WriteRef(unityObj); + + if(members == null) + GetMembers(writer.settings.safeReflection); + for(int i=0; i(ES3Reader reader) + { + if(members == null) + GetMembers(reader.settings.safeReflection); + + object obj; + string propertyName = reader.ReadPropertyName(); + + // If we're loading a derived type, use it's specific ES3Type. + if(propertyName == ES3Type.typeFieldName) + return ES3TypeMgr.GetOrCreateES3Type(reader.ReadType()).Read(reader); + + // If we're loading a reference, load it. Else, create an instance. + if(propertyName == ES3ReferenceMgrBase.referencePropertyName) + { + long id = reader.Read_ref(); + obj = ES3ReferenceMgrBase.Current.Get(id, type); + if(obj == null) + { + // If an instance isn't already registered for this object, create an instance and register the reference. + obj = ES3Reflection.CreateInstance(this.type); + ES3ReferenceMgrBase.Current.Add((UnityEngine.Object)obj, id); + } + } + else + { + reader.overridePropertiesName = propertyName; + obj = ES3Reflection.CreateInstance(this.type); + } + + // Iterate through each property in the file and try to load it using the appropriate + // ES3Property in the members array. + ReadProperties(reader, obj); + + return obj; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + if(members == null) + GetMembers(reader.settings.safeReflection); + + string propertyName = reader.ReadPropertyName(); + + // If we're loading a derived type, use it's specific ES3Type. + if(propertyName == ES3Type.typeFieldName) + { + ES3TypeMgr.GetOrCreateES3Type(reader.ReadType()).ReadInto(reader, obj); + return; + } + else + reader.overridePropertiesName = propertyName; + + // Iterate through each property in the file and try to load it using the appropriate + // ES3Property in the members array. + ReadProperties(reader, obj); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedType.cs.meta new file mode 100644 index 0000000..3a91f09 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d859cda1b74634568a53487bd1651001 +timeCreated: 1499764823 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedUnityObjectType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedUnityObjectType.cs new file mode 100644 index 0000000..946a2f1 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedUnityObjectType.cs @@ -0,0 +1,35 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + internal class ES3ReflectedUnityObjectType : ES3UnityObjectType + { + public ES3ReflectedUnityObjectType(Type type) : base(type) + { + isReflectedType = true; + GetMembers(true); + } + + protected override void WriteUnityObject(object obj, ES3Writer writer) + { + WriteProperties(obj, writer); + } + + protected override object ReadUnityObject(ES3Reader reader) + { + var obj = ES3Reflection.CreateInstance(this.type); + ReadProperties(reader, obj); + return obj; + } + + protected override void ReadUnityObject(ES3Reader reader, object obj) + { + ReadProperties(reader, obj); + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedUnityObjectType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedUnityObjectType.cs.meta new file mode 100644 index 0000000..c9d5889 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedUnityObjectType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f8c48527c8cb247f1be391e0ca112968 +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedValueType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedValueType.cs new file mode 100644 index 0000000..0af9af9 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedValueType.cs @@ -0,0 +1,38 @@ +using System; +using UnityEngine; +using System.Collections; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + internal class ES3ReflectedValueType : ES3Type + { + public ES3ReflectedValueType(Type type) : base(type) + { + isReflectedType = true; + GetMembers(true); + } + + public override void Write(object obj, ES3Writer writer) + { + WriteProperties(obj, writer); + } + + public override object Read(ES3Reader reader) + { + var obj = ES3Reflection.CreateInstance(this.type); + + if(obj == null) + throw new NotSupportedException("Cannot create an instance of "+this.type+". However, you may be able to add support for it using a custom ES3Type file. For more information see: http://docs.moodkie.com/easy-save-3/es3-guides/controlling-serialization-using-es3types/"); + // Make sure we return the result of ReadProperties as properties aren't assigned by reference. + return ReadProperties(reader, obj); + } + + public override void ReadInto(ES3Reader reader, object obj) + { + throw new NotSupportedException("Cannot perform self-assigning load on a value type."); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedValueType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedValueType.cs.meta new file mode 100644 index 0000000..2099910 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Reflected Types/ES3ReflectedValueType.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f8bc4124377914b60b46b243480f0eb5 +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types.meta new file mode 100644 index 0000000..4958a37 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 38fe64536e69de8428a69298d6cf8a5f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types.meta new file mode 100644 index 0000000..c84c866 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: df068f9511cede84e8434fc81abcab75 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider.cs new file mode 100644 index 0000000..51801af --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider.cs @@ -0,0 +1,66 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("center", "size", "enabled", "isTrigger", "contactOffset", "sharedMaterial")] + public class ES3Type_BoxCollider : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_BoxCollider() : base(typeof(UnityEngine.BoxCollider)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.BoxCollider)obj; + + writer.WriteProperty("center", instance.center); + writer.WriteProperty("size", instance.size); + writer.WriteProperty("enabled", instance.enabled); + writer.WriteProperty("isTrigger", instance.isTrigger); + writer.WriteProperty("contactOffset", instance.contactOffset); + writer.WritePropertyByRef("material", instance.sharedMaterial); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.BoxCollider)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "center": + instance.center = reader.Read(); + break; + case "size": + instance.size = reader.Read(); + break; + case "enabled": + instance.enabled = reader.Read(); + break; + case "isTrigger": + instance.isTrigger = reader.Read(); + break; + case "contactOffset": + instance.contactOffset = reader.Read(); + break; + case "material": +#if UNITY_6000_0_OR_NEWER + + instance.sharedMaterial = reader.Read(); +#else + instance.sharedMaterial = reader.Read(); +#endif + break; + default: + reader.Skip(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider.cs.meta new file mode 100644 index 0000000..a45de66 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d36ea4342de4546b198eea1405516979 +timeCreated: 1519132297 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider2D.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider2D.cs new file mode 100644 index 0000000..2d42dc4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider2D.cs @@ -0,0 +1,66 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("size", "density", "isTrigger", "usedByEffector", "offset", "sharedMaterial", "enabled")] + public class ES3Type_BoxCollider2D : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_BoxCollider2D() : base(typeof(UnityEngine.BoxCollider2D)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.BoxCollider2D)obj; + + writer.WriteProperty("size", instance.size); + if(instance.attachedRigidbody != null && instance.attachedRigidbody.useAutoMass) + writer.WriteProperty("density", instance.density); + writer.WriteProperty("isTrigger", instance.isTrigger); + writer.WriteProperty("usedByEffector", instance.usedByEffector); + writer.WriteProperty("offset", instance.offset); + writer.WritePropertyByRef("sharedMaterial", instance.sharedMaterial); + writer.WriteProperty("enabled", instance.enabled); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.BoxCollider2D)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "size": + instance.size = reader.Read(); + break; + case "density": + instance.density = reader.Read(); + break; + case "isTrigger": + instance.isTrigger = reader.Read(); + break; + case "usedByEffector": + instance.usedByEffector = reader.Read(); + break; + case "offset": + instance.offset = reader.Read(); + break; + case "sharedMaterial": + instance.sharedMaterial = reader.Read(); + break; + case "enabled": + instance.enabled = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider2D.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider2D.cs.meta new file mode 100644 index 0000000..0795afc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_BoxCollider2D.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 8ae32677f95cd4f2ba1c34db2a065c9c +timeCreated: 1519132290 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Camera.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Camera.cs new file mode 100644 index 0000000..3db142b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Camera.cs @@ -0,0 +1,165 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("fieldOfView", "nearClipPlane", "farClipPlane", "renderingPath", "allowHDR", "orthographicSize", "orthographic", "opaqueSortMode", "transparencySortMode", "depth", "aspect", "cullingMask", "eventMask", "backgroundColor", "rect", "pixelRect", "worldToCameraMatrix", "projectionMatrix", "nonJitteredProjectionMatrix", "useJitteredProjectionMatrixForTransparentRendering", "clearFlags", "stereoSeparation", "stereoConvergence", "cameraType", "stereoTargetEye", "targetDisplay", "useOcclusionCulling", "cullingMatrix", "layerCullSpherical", "depthTextureMode", "clearStencilAfterLightingPass", "enabled", "hideFlags")] + public class ES3Type_Camera : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_Camera() : base(typeof(UnityEngine.Camera)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Camera)obj; + + writer.WriteProperty("fieldOfView", instance.fieldOfView); + writer.WriteProperty("nearClipPlane", instance.nearClipPlane); + writer.WriteProperty("farClipPlane", instance.farClipPlane); + writer.WriteProperty("renderingPath", instance.renderingPath); + #if UNITY_5_6_OR_NEWER + writer.WriteProperty("allowHDR", instance.allowHDR); + #endif + writer.WriteProperty("orthographicSize", instance.orthographicSize); + writer.WriteProperty("orthographic", instance.orthographic); + writer.WriteProperty("opaqueSortMode", instance.opaqueSortMode); + writer.WriteProperty("transparencySortMode", instance.transparencySortMode); + writer.WriteProperty("depth", instance.depth); + writer.WriteProperty("aspect", instance.aspect); + writer.WriteProperty("cullingMask", instance.cullingMask); + writer.WriteProperty("eventMask", instance.eventMask); + writer.WriteProperty("backgroundColor", instance.backgroundColor); + writer.WriteProperty("rect", instance.rect); + writer.WriteProperty("pixelRect", instance.pixelRect); + writer.WriteProperty("projectionMatrix", instance.projectionMatrix); + writer.WriteProperty("nonJitteredProjectionMatrix", instance.nonJitteredProjectionMatrix); + writer.WriteProperty("useJitteredProjectionMatrixForTransparentRendering", instance.useJitteredProjectionMatrixForTransparentRendering); + writer.WriteProperty("clearFlags", instance.clearFlags); + writer.WriteProperty("stereoSeparation", instance.stereoSeparation); + writer.WriteProperty("stereoConvergence", instance.stereoConvergence); + writer.WriteProperty("cameraType", instance.cameraType); + writer.WriteProperty("stereoTargetEye", instance.stereoTargetEye); + writer.WriteProperty("targetDisplay", instance.targetDisplay); + writer.WriteProperty("useOcclusionCulling", instance.useOcclusionCulling); + writer.WriteProperty("layerCullSpherical", instance.layerCullSpherical); + writer.WriteProperty("depthTextureMode", instance.depthTextureMode); + writer.WriteProperty("clearStencilAfterLightingPass", instance.clearStencilAfterLightingPass); + writer.WriteProperty("enabled", instance.enabled); + writer.WriteProperty("hideFlags", instance.hideFlags); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.Camera)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "fieldOfView": + instance.fieldOfView = reader.Read(); + break; + case "nearClipPlane": + instance.nearClipPlane = reader.Read(); + break; + case "farClipPlane": + instance.farClipPlane = reader.Read(); + break; + case "renderingPath": + instance.renderingPath = reader.Read(); + break; + #if UNITY_5_6_OR_NEWER + case "allowHDR": + instance.allowHDR = reader.Read(); + break; + #endif + case "orthographicSize": + instance.orthographicSize = reader.Read(); + break; + case "orthographic": + instance.orthographic = reader.Read(); + break; + case "opaqueSortMode": + instance.opaqueSortMode = reader.Read(); + break; + case "transparencySortMode": + instance.transparencySortMode = reader.Read(); + break; + case "depth": + instance.depth = reader.Read(); + break; + case "aspect": + instance.aspect = reader.Read(); + break; + case "cullingMask": + instance.cullingMask = reader.Read(); + break; + case "eventMask": + instance.eventMask = reader.Read(); + break; + case "backgroundColor": + instance.backgroundColor = reader.Read(); + break; + case "rect": + instance.rect = reader.Read(); + break; + case "pixelRect": + instance.pixelRect = reader.Read(); + break; + case "projectionMatrix": + instance.projectionMatrix = reader.Read(); + break; + case "nonJitteredProjectionMatrix": + instance.nonJitteredProjectionMatrix = reader.Read(); + break; + case "useJitteredProjectionMatrixForTransparentRendering": + instance.useJitteredProjectionMatrixForTransparentRendering = reader.Read(); + break; + case "clearFlags": + instance.clearFlags = reader.Read(); + break; + case "stereoSeparation": + instance.stereoSeparation = reader.Read(); + break; + case "stereoConvergence": + instance.stereoConvergence = reader.Read(); + break; + case "cameraType": + instance.cameraType = reader.Read(); + break; + case "stereoTargetEye": + instance.stereoTargetEye = reader.Read(); + break; + case "targetDisplay": + instance.targetDisplay = reader.Read(); + break; + case "useOcclusionCulling": + instance.useOcclusionCulling = reader.Read(); + break; + case "layerCullSpherical": + instance.layerCullSpherical = reader.Read(); + break; + case "depthTextureMode": + instance.depthTextureMode = reader.Read(); + break; + case "clearStencilAfterLightingPass": + instance.clearStencilAfterLightingPass = reader.Read(); + break; + case "enabled": + instance.enabled = reader.Read(); + break; + case "hideFlags": + instance.hideFlags = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Camera.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Camera.cs.meta new file mode 100644 index 0000000..2d367aa --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Camera.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c88c1ce73e1f3462ea1aff5df7935e22 +timeCreated: 1499764822 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_CapsuleCollider.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_CapsuleCollider.cs new file mode 100644 index 0000000..2451507 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_CapsuleCollider.cs @@ -0,0 +1,73 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("center", "radius", "height", "direction", "enabled", "isTrigger", "contactOffset", "sharedMaterial")] + public class ES3Type_CapsuleCollider : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_CapsuleCollider() : base(typeof(UnityEngine.CapsuleCollider)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.CapsuleCollider)obj; + + writer.WriteProperty("center", instance.center, ES3Type_Vector3.Instance); + writer.WriteProperty("radius", instance.radius, ES3Type_float.Instance); + writer.WriteProperty("height", instance.height, ES3Type_float.Instance); + writer.WriteProperty("direction", instance.direction, ES3Type_int.Instance); + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("isTrigger", instance.isTrigger, ES3Type_bool.Instance); + writer.WriteProperty("contactOffset", instance.contactOffset, ES3Type_float.Instance); + writer.WritePropertyByRef("material", instance.sharedMaterial); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.CapsuleCollider)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + case "center": + instance.center = reader.Read(ES3Type_Vector3.Instance); + break; + case "radius": + instance.radius = reader.Read(ES3Type_float.Instance); + break; + case "height": + instance.height = reader.Read(ES3Type_float.Instance); + break; + case "direction": + instance.direction = reader.Read(ES3Type_int.Instance); + break; + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "isTrigger": + instance.isTrigger = reader.Read(ES3Type_bool.Instance); + break; + case "contactOffset": + instance.contactOffset = reader.Read(ES3Type_float.Instance); + break; + case "material": +#if UNITY_6000_0_OR_NEWER + instance.sharedMaterial = reader.Read(); +#else + instance.sharedMaterial = reader.Read(); +#endif + break; + default: + reader.Skip(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_CapsuleCollider.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_CapsuleCollider.cs.meta new file mode 100644 index 0000000..f4c88e0 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_CapsuleCollider.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c523bafd506f04c85b160320b0b6d9dd +timeCreated: 1519132296 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_EventSystem.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_EventSystem.cs new file mode 100644 index 0000000..6c7f8e3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_EventSystem.cs @@ -0,0 +1,31 @@ +#if ES3_UGUI + +using System; +using UnityEngine; +using UnityEngine.EventSystems; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + public class ES3Type_EventSystem : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_EventSystem() : base(typeof(EventSystem)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + foreach(string propertyName in reader.Properties) + reader.Skip(); + } + } +} + +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_EventSystem.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_EventSystem.cs.meta new file mode 100644 index 0000000..d901720 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_EventSystem.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 02df167b6b77741308bfc8110dae71dd +timeCreated: 1519132279 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Image.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Image.cs new file mode 100644 index 0000000..4827953 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Image.cs @@ -0,0 +1,137 @@ +#if ES3_UGUI + +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("sprite", "overrideSprite", "type", "preserveAspect", "fillCenter", "fillMethod", "fillAmount", "fillClockwise", "fillOrigin", "alphaHitTestMinimumThreshold", "useSpriteMesh", "pixelsPerUnitMultiplier", "material", "onCullStateChanged", "maskable", "color", "raycastTarget", "useLegacyMeshGeneration", "useGUILayout", "enabled", "hideFlags")] + public class ES3Type_Image : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_Image() : base(typeof(UnityEngine.UI.Image)){ Instance = this; } + + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.UI.Image)obj; + + writer.WritePropertyByRef("sprite", instance.sprite); + writer.WriteProperty("type", instance.type); + writer.WriteProperty("preserveAspect", instance.preserveAspect, ES3Type_bool.Instance); + writer.WriteProperty("fillCenter", instance.fillCenter, ES3Type_bool.Instance); + writer.WriteProperty("fillMethod", instance.fillMethod); + writer.WriteProperty("fillAmount", instance.fillAmount, ES3Type_float.Instance); + writer.WriteProperty("fillClockwise", instance.fillClockwise, ES3Type_bool.Instance); + writer.WriteProperty("fillOrigin", instance.fillOrigin, ES3Type_int.Instance); + //alphaHitTestMinimumThreshold is disabled as Unity provides no way to check for crunch compression which is required to set this variable. + //writer.WriteProperty("alphaHitTestMinimumThreshold", instance.alphaHitTestMinimumThreshold, ES3Type_float.Instance); +#if UNITY_2019_1_OR_NEWER + writer.WriteProperty("useSpriteMesh", instance.useSpriteMesh, ES3Type_bool.Instance); +#endif + // Unity automatically sets the default material if it's set to null. + // This prevents missing reference warnings. + if (instance.material.name.Contains("Default")) + writer.WriteProperty("material", null); + else + writer.WriteProperty("material", instance.material); + writer.WriteProperty("onCullStateChanged", instance.onCullStateChanged); + writer.WriteProperty("maskable", instance.maskable, ES3Type_bool.Instance); + writer.WriteProperty("color", instance.color, ES3Type_Color.Instance); + writer.WriteProperty("raycastTarget", instance.raycastTarget, ES3Type_bool.Instance); + writer.WritePrivateProperty("useLegacyMeshGeneration", instance); + writer.WriteProperty("useGUILayout", instance.useGUILayout, ES3Type_bool.Instance); + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("hideFlags", instance.hideFlags, ES3Type_enum.Instance); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.UI.Image)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "sprite": + instance.sprite = reader.Read(ES3Type_Sprite.Instance); + break; + case "type": + instance.type = reader.Read(); + break; + case "preserveAspect": + instance.preserveAspect = reader.Read(ES3Type_bool.Instance); + break; + case "fillCenter": + instance.fillCenter = reader.Read(ES3Type_bool.Instance); + break; + case "fillMethod": + instance.fillMethod = reader.Read(); + break; + case "fillAmount": + instance.fillAmount = reader.Read(ES3Type_float.Instance); + break; + case "fillClockwise": + instance.fillClockwise = reader.Read(ES3Type_bool.Instance); + break; + case "fillOrigin": + instance.fillOrigin = reader.Read(ES3Type_int.Instance); + break; + /*case "alphaHitTestMinimumThreshold": + instance.alphaHitTestMinimumThreshold = reader.Read(ES3Type_float.Instance); + break;*/ +#if UNITY_2019_1_OR_NEWER + case "useSpriteMesh": + instance.useSpriteMesh = reader.Read(ES3Type_bool.Instance); + break; +#endif + case "material": + instance.material = reader.Read(ES3Type_Material.Instance); + break; + case "onCullStateChanged": + instance.onCullStateChanged = reader.Read(); + break; + case "maskable": + instance.maskable = reader.Read(ES3Type_bool.Instance); + break; + case "color": + instance.color = reader.Read(ES3Type_Color.Instance); + break; + case "raycastTarget": + instance.raycastTarget = reader.Read(ES3Type_bool.Instance); + break; + case "useLegacyMeshGeneration": + reader.SetPrivateProperty("useLegacyMeshGeneration", reader.Read(), instance); + break; + case "useGUILayout": + instance.useGUILayout = reader.Read(ES3Type_bool.Instance); + break; + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "hideFlags": + instance.hideFlags = reader.Read(ES3Type_enum.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } + + + public class ES3Type_ImageArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_ImageArray() : base(typeof(UnityEngine.UI.Image[]), ES3Type_Image.Instance) + { + Instance = this; + } + } +} + +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Image.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Image.cs.meta new file mode 100644 index 0000000..0b13178 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Image.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 044e538602955694c90bc8b86d487ac5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshCollider.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshCollider.cs new file mode 100644 index 0000000..7247493 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshCollider.cs @@ -0,0 +1,84 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("sharedMesh", "convex", "inflateMesh", "skinWidth", "enabled", "isTrigger", "contactOffset", "sharedMaterial")] + public class ES3Type_MeshCollider : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_MeshCollider() : base(typeof(UnityEngine.MeshCollider)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.MeshCollider)obj; + + writer.WritePropertyByRef("sharedMesh", instance.sharedMesh); + writer.WriteProperty("convex", instance.convex, ES3Type_bool.Instance); + /*writer.WriteProperty("inflateMesh", instance.inflateMesh, ES3Type_bool.Instance); + writer.WriteProperty("skinWidth", instance.skinWidth, ES3Type_float.Instance);*/ + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("isTrigger", instance.isTrigger, ES3Type_bool.Instance); + writer.WriteProperty("contactOffset", instance.contactOffset, ES3Type_float.Instance); + writer.WriteProperty("material", instance.sharedMaterial); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.MeshCollider)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "sharedMesh": + instance.sharedMesh = reader.Read(ES3Type_Mesh.Instance); + break; + case "convex": + instance.convex = reader.Read(ES3Type_bool.Instance); + break; + /*case "inflateMesh": + instance.inflateMesh = reader.Read(ES3Type_bool.Instance); + break; + case "skinWidth": + instance.skinWidth = reader.Read(ES3Type_float.Instance); + break;*/ + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "isTrigger": + instance.isTrigger = reader.Read(ES3Type_bool.Instance); + break; + case "contactOffset": + instance.contactOffset = reader.Read(ES3Type_float.Instance); + break; + case "material": +#if UNITY_6000_0_OR_NEWER + instance.sharedMaterial = reader.Read(); +#else + instance.sharedMaterial = reader.Read(); +#endif + break; + default: + reader.Skip(); + break; + } + } + } + } + + public class ES3Type_MeshColliderArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_MeshColliderArray() : base(typeof(UnityEngine.MeshCollider[]), ES3Type_MeshCollider.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshCollider.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshCollider.cs.meta new file mode 100644 index 0000000..dfb148f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshCollider.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b7825b483b5804bcb95a1a47cb287500 +timeCreated: 1519132294 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshFilter.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshFilter.cs new file mode 100644 index 0000000..b7a28a2 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshFilter.cs @@ -0,0 +1,51 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("sharedMesh")] + public class ES3Type_MeshFilter : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_MeshFilter() : base(typeof(UnityEngine.MeshFilter)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.MeshFilter)obj; + writer.WritePropertyByRef("sharedMesh", instance.sharedMesh); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.MeshFilter)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "sharedMesh": + instance.sharedMesh = reader.Read(ES3Type_Mesh.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } + + public class ES3Type_MeshFilterArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_MeshFilterArray() : base(typeof(UnityEngine.MeshFilter[]), ES3Type_MeshFilter.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshFilter.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshFilter.cs.meta new file mode 100644 index 0000000..9a22df1 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshFilter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 00364532a712841328836c36da833503 +timeCreated: 1519132279 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshRenderer.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshRenderer.cs new file mode 100644 index 0000000..d8b87a9 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshRenderer.cs @@ -0,0 +1,116 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("additionalVertexStreams", "enabled", "shadowCastingMode", "receiveShadows", "sharedMaterials", "lightmapIndex", "realtimeLightmapIndex", "lightmapScaleOffset", "motionVectorGenerationMode", "realtimeLightmapScaleOffset", "lightProbeUsage", "lightProbeProxyVolumeOverride", "probeAnchor", "reflectionProbeUsage", "sortingLayerName", "sortingLayerID", "sortingOrder")] + public class ES3Type_MeshRenderer : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_MeshRenderer() : base(typeof(UnityEngine.MeshRenderer)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.MeshRenderer)obj; + + writer.WriteProperty("additionalVertexStreams", instance.additionalVertexStreams, ES3Type_Mesh.Instance); + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("shadowCastingMode", instance.shadowCastingMode); + writer.WriteProperty("receiveShadows", instance.receiveShadows, ES3Type_bool.Instance); + writer.WriteProperty("sharedMaterials", instance.sharedMaterials, ES3Type_MaterialArray.Instance); + writer.WriteProperty("lightmapIndex", instance.lightmapIndex, ES3Type_int.Instance); + writer.WriteProperty("realtimeLightmapIndex", instance.realtimeLightmapIndex, ES3Type_int.Instance); + writer.WriteProperty("lightmapScaleOffset", instance.lightmapScaleOffset, ES3Type_Vector4.Instance); + writer.WriteProperty("motionVectorGenerationMode", instance.motionVectorGenerationMode); + writer.WriteProperty("realtimeLightmapScaleOffset", instance.realtimeLightmapScaleOffset, ES3Type_Vector4.Instance); + writer.WriteProperty("lightProbeUsage", instance.lightProbeUsage); + writer.WriteProperty("lightProbeProxyVolumeOverride", instance.lightProbeProxyVolumeOverride); + writer.WriteProperty("probeAnchor", instance.probeAnchor, ES3Type_Transform.Instance); + writer.WriteProperty("reflectionProbeUsage", instance.reflectionProbeUsage); + writer.WriteProperty("sortingLayerName", instance.sortingLayerName, ES3Type_string.Instance); + writer.WriteProperty("sortingLayerID", instance.sortingLayerID, ES3Type_int.Instance); + writer.WriteProperty("sortingOrder", instance.sortingOrder, ES3Type_int.Instance); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.MeshRenderer)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "additionalVertexStreams": + instance.additionalVertexStreams = reader.Read(ES3Type_Mesh.Instance); + break; + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "shadowCastingMode": + instance.shadowCastingMode = reader.Read(); + break; + case "receiveShadows": + instance.receiveShadows = reader.Read(ES3Type_bool.Instance); + break; + case "sharedMaterials": + instance.sharedMaterials = reader.Read(); + break; + case "lightmapIndex": + instance.lightmapIndex = reader.Read(ES3Type_int.Instance); + break; + case "realtimeLightmapIndex": + instance.realtimeLightmapIndex = reader.Read(ES3Type_int.Instance); + break; + case "lightmapScaleOffset": + instance.lightmapScaleOffset = reader.Read(ES3Type_Vector4.Instance); + break; + case "motionVectorGenerationMode": + instance.motionVectorGenerationMode = reader.Read(); + break; + case "realtimeLightmapScaleOffset": + instance.realtimeLightmapScaleOffset = reader.Read(ES3Type_Vector4.Instance); + break; + case "lightProbeUsage": + instance.lightProbeUsage = reader.Read(); + break; + case "lightProbeProxyVolumeOverride": + instance.lightProbeProxyVolumeOverride = reader.Read(ES3Type_GameObject.Instance); + break; + case "probeAnchor": + instance.probeAnchor = reader.Read(ES3Type_Transform.Instance); + break; + case "reflectionProbeUsage": + instance.reflectionProbeUsage = reader.Read(); + break; + case "sortingLayerName": + instance.sortingLayerName = reader.Read(ES3Type_string.Instance); + break; + case "sortingLayerID": + instance.sortingLayerID = reader.Read(ES3Type_int.Instance); + break; + case "sortingOrder": + instance.sortingOrder = reader.Read(ES3Type_int.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } + + public class ES3Type_MeshRendererArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_MeshRendererArray() : base(typeof(UnityEngine.MeshRenderer[]), ES3Type_MeshRenderer.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshRenderer.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshRenderer.cs.meta new file mode 100644 index 0000000..7277162 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_MeshRenderer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d33e88a8388cf4cf1b47495afc6722a7 +timeCreated: 1519132297 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_ParticleSystem.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_ParticleSystem.cs new file mode 100644 index 0000000..8295f33 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_ParticleSystem.cs @@ -0,0 +1,149 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("time", "hideFlags", "collision", "colorBySpeed", "colorOverLifetime", "emission", "externalForces", "forceOverLifetime", "inheritVelocity", + "lights", "limitVelocityOverLifetime", "main", "noise", "rotatonBySpeed", "rotationOverLifetime", "shape", "sizeBySpeed", "sizeOverLifetime", + "subEmitters", "textureSheetAnimation", "trails", "trigger", "useAutoRandomSeed", "velocityOverLifetime", "isPaused", "isPlaying", "isStopped")] + public class ES3Type_ParticleSystem : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_ParticleSystem() : base(typeof(UnityEngine.ParticleSystem)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem)obj; + + writer.WriteProperty("time", instance.time); + writer.WriteProperty("hideFlags", instance.hideFlags); + writer.WriteProperty("collision", instance.collision); + writer.WriteProperty("colorBySpeed", instance.colorBySpeed); + writer.WriteProperty("colorOverLifetime", instance.colorOverLifetime); + writer.WriteProperty("emission", instance.emission); + writer.WriteProperty("externalForces", instance.externalForces); + writer.WriteProperty("forceOverLifetime", instance.forceOverLifetime); + writer.WriteProperty("inheritVelocity", instance.inheritVelocity); + writer.WriteProperty("lights", instance.lights); + writer.WriteProperty("limitVelocityOverLifetime", instance.limitVelocityOverLifetime); + writer.WriteProperty("main", instance.main); + writer.WriteProperty("noise", instance.noise); + writer.WriteProperty("rotationBySpeed", instance.rotationBySpeed); + writer.WriteProperty("rotationOverLifetime", instance.rotationOverLifetime); + writer.WriteProperty("shape", instance.shape); + writer.WriteProperty("sizeBySpeed", instance.sizeBySpeed); + writer.WriteProperty("sizeOverLifetime", instance.sizeOverLifetime); + writer.WriteProperty("subEmitters", instance.subEmitters); + writer.WriteProperty("textureSheetAnimation", instance.textureSheetAnimation); + writer.WriteProperty("trails", instance.trails); + writer.WriteProperty("trigger", instance.trigger); + writer.WriteProperty("useAutoRandomSeed", instance.useAutoRandomSeed); + writer.WriteProperty("velocityOverLifetime", instance.velocityOverLifetime); + writer.WriteProperty("isPaused", instance.isPaused); + writer.WriteProperty("isPlaying", instance.isPlaying); + writer.WriteProperty("isStopped", instance.isStopped); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem)obj; + // Stop particle system as some properties require it to not be playing to be set. + instance.Stop(); + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + case "time": + instance.time = reader.Read(); + break; + case "hideFlags": + instance.hideFlags = reader.Read(); + break; + case "collision": + reader.ReadInto(instance.collision, ES3Type_CollisionModule.Instance); + break; + case "colorBySpeed": + reader.ReadInto(instance.colorBySpeed, ES3Type_ColorBySpeedModule.Instance); + break; + case "colorOverLifetime": + reader.ReadInto(instance.colorOverLifetime, ES3Type_ColorOverLifetimeModule.Instance); + break; + case "sizeOverLifetime": + reader.ReadInto(instance.sizeOverLifetime, ES3Type_SizeOverLifetimeModule.Instance); + break; + case "shape": + reader.ReadInto(instance.shape, ES3Type_ShapeModule.Instance); + break; + case "emission": + reader.ReadInto(instance.emission, ES3Type_EmissionModule.Instance); + break; + case "externalForces": + reader.ReadInto(instance.externalForces, ES3Type_ExternalForcesModule.Instance); + break; + case "forceOverLifetime": + reader.ReadInto(instance.forceOverLifetime, ES3Type_ForceOverLifetimeModule.Instance); + break; + case "inheritVelocity": + reader.ReadInto(instance.inheritVelocity, ES3Type_InheritVelocityModule.Instance); + break; + case "lights": + reader.ReadInto(instance.lights, ES3Type_LightsModule.Instance); + break; + case "limitVelocityOverLifetime": + reader.ReadInto(instance.limitVelocityOverLifetime, ES3Type_LimitVelocityOverLifetimeModule.Instance); + break; + case "main": + reader.ReadInto(instance.main, ES3Type_MainModule.Instance); + break; + case "noise": + reader.ReadInto(instance.noise, ES3Type_NoiseModule.Instance); + break; + case "sizeBySpeed": + reader.ReadInto(instance.sizeBySpeed, ES3Type_SizeBySpeedModule.Instance); + break; + case "rotationBySpeed": + reader.ReadInto(instance.rotationBySpeed, ES3Type_RotationBySpeedModule.Instance); + break; + case "rotationOverLifetime": + reader.ReadInto(instance.rotationOverLifetime, ES3Type_RotationOverLifetimeModule.Instance); + break; + case "subEmitters": + reader.ReadInto(instance.subEmitters, ES3Type_SubEmittersModule.Instance); + break; + case "textureSheetAnimation": + reader.ReadInto(instance.textureSheetAnimation, ES3Type_TextureSheetAnimationModule.Instance); + break; + case "trails": + reader.ReadInto(instance.trails, ES3Type_TrailModule.Instance); + break; + case "trigger": + reader.ReadInto(instance.trigger, ES3Type_TriggerModule.Instance); + break; + case "useAutoRandomSeed": + instance.useAutoRandomSeed = reader.Read(ES3Type_bool.Instance); + break; + case "velocityOverLifetime": + reader.ReadInto(instance.velocityOverLifetime, ES3Type_VelocityOverLifetimeModule.Instance); + break; + case "isPaused": + if (reader.Read(ES3Type_bool.Instance)) instance.Pause(); + break; + case "isPlaying": + if (reader.Read(ES3Type_bool.Instance)) instance.Play(); + break; + case "isStopped": + if (reader.Read(ES3Type_bool.Instance)) instance.Stop(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_ParticleSystem.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_ParticleSystem.cs.meta new file mode 100644 index 0000000..62abfe5 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_ParticleSystem.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9484f3e3b46ec4871977550c93381f25 +timeCreated: 1519132291 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_PolygonCollider2D.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_PolygonCollider2D.cs new file mode 100644 index 0000000..fdc765c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_PolygonCollider2D.cs @@ -0,0 +1,87 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("points", "pathCount", "paths", "density", "isTrigger", "usedByEffector", "offset", "sharedMaterial", "enabled")] + public class ES3Type_PolygonCollider2D : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_PolygonCollider2D() : base(typeof(UnityEngine.PolygonCollider2D)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.PolygonCollider2D)obj; + + writer.WriteProperty("points", instance.points, ES3Type_Vector2Array.Instance); + writer.WriteProperty("pathCount", instance.pathCount, ES3Type_int.Instance); + + for(int i=0; i(ES3Reader reader, object obj) + { + var instance = (UnityEngine.PolygonCollider2D)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "points": + instance.points = reader.Read(ES3Type_Vector2Array.Instance); + break; + case "pathCount": + int pathCount = reader.Read(ES3Type_int.Instance); + for(int i=0; i(ES3Type_Vector2Array.Instance)); + break; + case "density": + instance.density = reader.Read(ES3Type_float.Instance); + break; + case "isTrigger": + instance.isTrigger = reader.Read(ES3Type_bool.Instance); + break; + case "usedByEffector": + instance.usedByEffector = reader.Read(ES3Type_bool.Instance); + break; + case "offset": + instance.offset = reader.Read(ES3Type_Vector2.Instance); + break; + case "sharedMaterial": + instance.sharedMaterial = reader.Read(ES3Type_PhysicsMaterial2D.Instance); + break; + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } + + public class ES3Type_PolygonCollider2DArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_PolygonCollider2DArray() : base(typeof(UnityEngine.PolygonCollider2D[]), ES3Type_PolygonCollider2D.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_PolygonCollider2D.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_PolygonCollider2D.cs.meta new file mode 100644 index 0000000..21a8143 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_PolygonCollider2D.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ec8749737dd724d6a91ac3a9c241ba17 +timeCreated: 1519132300 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_RawImage.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_RawImage.cs new file mode 100644 index 0000000..36c6605 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_RawImage.cs @@ -0,0 +1,100 @@ +#if ES3_UGUI + +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("texture", "uvRect", "onCullStateChanged", "maskable", "color", "raycastTarget", "useLegacyMeshGeneration", "material", "useGUILayout", "enabled", "hideFlags")] + public class ES3Type_RawImage : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_RawImage() : base(typeof(UnityEngine.UI.RawImage)){ Instance = this;} + + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.UI.RawImage)obj; + + writer.WritePropertyByRef("texture", instance.texture); + writer.WriteProperty("uvRect", instance.uvRect, ES3Type_Rect.Instance); + writer.WriteProperty("onCullStateChanged", instance.onCullStateChanged); + writer.WriteProperty("maskable", instance.maskable, ES3Type_bool.Instance); + writer.WriteProperty("color", instance.color, ES3Type_Color.Instance); + writer.WriteProperty("raycastTarget", instance.raycastTarget, ES3Type_bool.Instance); + writer.WritePrivateProperty("useLegacyMeshGeneration", instance); + // Unity automatically sets the default material if it's set to null. + // This prevents missing reference warnings. + if (instance.material.name.Contains("Default")) + writer.WriteProperty("material", null); + else + writer.WriteProperty("material", instance.material); + writer.WriteProperty("useGUILayout", instance.useGUILayout, ES3Type_bool.Instance); + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("hideFlags", instance.hideFlags); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.UI.RawImage)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "texture": + instance.texture = reader.Read(ES3Type_Texture.Instance); + break; + case "uvRect": + instance.uvRect = reader.Read(ES3Type_Rect.Instance); + break; + case "onCullStateChanged": + instance.onCullStateChanged = reader.Read(); + break; + case "maskable": + instance.maskable = reader.Read(ES3Type_bool.Instance); + break; + case "color": + instance.color = reader.Read(ES3Type_Color.Instance); + break; + case "raycastTarget": + instance.raycastTarget = reader.Read(ES3Type_bool.Instance); + break; + case "useLegacyMeshGeneration": + reader.SetPrivateProperty("useLegacyMeshGeneration", reader.Read(), instance); + break; + case "material": + instance.material = reader.Read(ES3Type_Material.Instance); + break; + case "useGUILayout": + instance.useGUILayout = reader.Read(ES3Type_bool.Instance); + break; + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "hideFlags": + instance.hideFlags = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } + + + public class ES3Type_RawImageArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_RawImageArray() : base(typeof(UnityEngine.UI.RawImage[]), ES3Type_RawImage.Instance) + { + Instance = this; + } + } +} + +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_RawImage.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_RawImage.cs.meta new file mode 100644 index 0000000..3d4e161 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_RawImage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d8b1e267b6439604a9854f1876a085b7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Rigidbody.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Rigidbody.cs new file mode 100644 index 0000000..a412c2c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Rigidbody.cs @@ -0,0 +1,153 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("velocity", "angularVelocity", "drag", "angularDrag", "mass", "useGravity", "maxDepenetrationVelocity", "isKinematic", "freezeRotation", "constraints", "collisionDetectionMode", "centerOfMass", "inertiaTensorRotation", "inertiaTensor", "detectCollisions", "position", "rotation", "interpolation", "solverIterations", "sleepThreshold", "maxAngularVelocity", "solverVelocityIterations")] + public class ES3Type_Rigidbody : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_Rigidbody() : base(typeof(UnityEngine.Rigidbody)) { Instance = this; } + + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Rigidbody)obj; + +#if UNITY_6000_0_OR_NEWER + writer.WriteProperty("velocity", instance.linearVelocity, ES3Type_Vector3.Instance); + writer.WriteProperty("drag", instance.linearDamping, ES3Type_float.Instance); + writer.WriteProperty("angularDrag", instance.angularDamping, ES3Type_float.Instance); +#else + writer.WriteProperty("velocity", instance.velocity, ES3Type_Vector3.Instance); + writer.WriteProperty("drag", instance.drag, ES3Type_float.Instance); + writer.WriteProperty("angularDrag", instance.angularDrag, ES3Type_float.Instance); +#endif + writer.WriteProperty("angularVelocity", instance.angularVelocity, ES3Type_Vector3.Instance); + writer.WriteProperty("mass", instance.mass, ES3Type_float.Instance); + writer.WriteProperty("useGravity", instance.useGravity, ES3Type_bool.Instance); + writer.WriteProperty("maxDepenetrationVelocity", instance.maxDepenetrationVelocity, ES3Type_float.Instance); + writer.WriteProperty("isKinematic", instance.isKinematic, ES3Type_bool.Instance); + writer.WriteProperty("freezeRotation", instance.freezeRotation, ES3Type_bool.Instance); + writer.WriteProperty("constraints", instance.constraints); + writer.WriteProperty("collisionDetectionMode", instance.collisionDetectionMode); + writer.WriteProperty("centerOfMass", instance.centerOfMass, ES3Type_Vector3.Instance); + writer.WriteProperty("detectCollisions", instance.detectCollisions, ES3Type_bool.Instance); + writer.WriteProperty("position", instance.position, ES3Type_Vector3.Instance); + writer.WriteProperty("rotation", instance.rotation, ES3Type_Quaternion.Instance); + writer.WriteProperty("interpolation", instance.interpolation); + writer.WriteProperty("solverIterations", instance.solverIterations, ES3Type_int.Instance); + writer.WriteProperty("sleepThreshold", instance.sleepThreshold, ES3Type_float.Instance); + writer.WriteProperty("maxAngularVelocity", instance.maxAngularVelocity, ES3Type_float.Instance); + writer.WriteProperty("solverVelocityIterations", instance.solverVelocityIterations, ES3Type_int.Instance); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.Rigidbody)obj; + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { +#if UNITY_6000_0_OR_NEWER + case "velocity": + instance.linearVelocity = reader.Read(ES3Type_Vector3.Instance); + break; + case "drag": + instance.linearDamping = reader.Read(ES3Type_float.Instance); + break; + case "angularDrag": + instance.angularDamping = reader.Read(ES3Type_float.Instance); + break; +#else + case "velocity": + instance.velocity = reader.Read(ES3Type_Vector3.Instance); + break; + case "drag": + instance.drag = reader.Read(ES3Type_float.Instance); + break; + case "angularDrag": + instance.angularDrag = reader.Read(ES3Type_float.Instance); + break; +#endif + case "angularVelocity": + instance.angularVelocity = reader.Read(ES3Type_Vector3.Instance); + break; + case "mass": + instance.mass = reader.Read(ES3Type_float.Instance); + break; + case "useGravity": + instance.useGravity = reader.Read(ES3Type_bool.Instance); + break; + case "maxDepenetrationVelocity": + instance.maxDepenetrationVelocity = reader.Read(ES3Type_float.Instance); + break; + case "isKinematic": + instance.isKinematic = reader.Read(ES3Type_bool.Instance); + break; + case "freezeRotation": + instance.freezeRotation = reader.Read(ES3Type_bool.Instance); + break; + case "constraints": + instance.constraints = reader.Read(); + break; + case "collisionDetectionMode": + instance.collisionDetectionMode = reader.Read(); + break; + case "centerOfMass": + instance.centerOfMass = reader.Read(ES3Type_Vector3.Instance); + break; + case "inertiaTensorRotation": + instance.inertiaTensorRotation = reader.Read(ES3Type_Quaternion.Instance); + break; + case "inertiaTensor": + var inertiaTensor = reader.Read(ES3Type_Vector3.Instance); + // Check that the inertia tensor isn't zero, as it will throw an error if we try to set it. + if (inertiaTensor != Vector3.zero) + instance.inertiaTensor = inertiaTensor; + break; + case "detectCollisions": + instance.detectCollisions = reader.Read(ES3Type_bool.Instance); + break; + case "position": + instance.position = reader.Read(ES3Type_Vector3.Instance); + break; + case "rotation": + instance.rotation = reader.Read(ES3Type_Quaternion.Instance); + break; + case "interpolation": + instance.interpolation = reader.Read(); + break; + case "solverIterations": + instance.solverIterations = reader.Read(ES3Type_int.Instance); + break; + case "sleepThreshold": + instance.sleepThreshold = reader.Read(ES3Type_float.Instance); + break; + case "maxAngularVelocity": + instance.maxAngularVelocity = reader.Read(ES3Type_float.Instance); + break; + case "solverVelocityIterations": + instance.solverVelocityIterations = reader.Read(ES3Type_int.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } + + + public class ES3UserType_RigidbodyArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3UserType_RigidbodyArray() : base(typeof(UnityEngine.Rigidbody[]), ES3Type_Rigidbody.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Rigidbody.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Rigidbody.cs.meta new file mode 100644 index 0000000..471e990 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Rigidbody.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8154830c992ded745b9784a07116b1b6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_SphereCollider.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_SphereCollider.cs new file mode 100644 index 0000000..4f437e5 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_SphereCollider.cs @@ -0,0 +1,64 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("center", "radius", "enabled", "isTrigger", "contactOffset", "sharedMaterial")] + public class ES3Type_SphereCollider : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_SphereCollider() : base(typeof(UnityEngine.SphereCollider)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.SphereCollider)obj; + + writer.WriteProperty("center", instance.center, ES3Type_Vector3.Instance); + writer.WriteProperty("radius", instance.radius, ES3Type_float.Instance); + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("isTrigger", instance.isTrigger, ES3Type_bool.Instance); + writer.WriteProperty("contactOffset", instance.contactOffset, ES3Type_float.Instance); + writer.WritePropertyByRef("material", instance.sharedMaterial); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.SphereCollider)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + case "center": + instance.center = reader.Read(ES3Type_Vector3.Instance); + break; + case "radius": + instance.radius = reader.Read(ES3Type_float.Instance); + break; + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "isTrigger": + instance.isTrigger = reader.Read(ES3Type_bool.Instance); + break; + case "contactOffset": + instance.contactOffset = reader.Read(ES3Type_float.Instance); + break; + case "material": +#if UNITY_6000_0_OR_NEWER + instance.sharedMaterial = reader.Read(); +#else + instance.sharedMaterial = reader.Read(); +#endif + break; + default: + reader.Skip(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_SphereCollider.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_SphereCollider.cs.meta new file mode 100644 index 0000000..c388053 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_SphereCollider.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: bb19da8937a274e63ada528bb6215c6d +timeCreated: 1519132295 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Text.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Text.cs new file mode 100644 index 0000000..4e636ed --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Text.cs @@ -0,0 +1,148 @@ +#if ES3_UGUI + +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("font", "text", "supportRichText", "resizeTextForBestFit", "resizeTextMinSize", "resizeTextMaxSize", "alignment", "alignByGeometry", "fontSize", "horizontalOverflow", "verticalOverflow", "lineSpacing", "fontStyle", "onCullStateChanged", "maskable", "color", "raycastTarget", "material", "useGUILayout", "enabled", "tag", "name", "hideFlags")] + public class ES3Type_Text : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_Text() : base(typeof(UnityEngine.UI.Text)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.UI.Text)obj; + + //writer.WriteProperty("font", instance.font); + writer.WriteProperty("text", instance.text); + writer.WriteProperty("supportRichText", instance.supportRichText); + writer.WriteProperty("resizeTextForBestFit", instance.resizeTextForBestFit); + writer.WriteProperty("resizeTextMinSize", instance.resizeTextMinSize); + writer.WriteProperty("resizeTextMaxSize", instance.resizeTextMaxSize); + writer.WriteProperty("alignment", instance.alignment); + writer.WriteProperty("alignByGeometry", instance.alignByGeometry); + writer.WriteProperty("fontSize", instance.fontSize); + writer.WriteProperty("horizontalOverflow", instance.horizontalOverflow); + writer.WriteProperty("verticalOverflow", instance.verticalOverflow); + writer.WriteProperty("lineSpacing", instance.lineSpacing); + writer.WriteProperty("fontStyle", instance.fontStyle); + writer.WriteProperty("onCullStateChanged", instance.onCullStateChanged); + writer.WriteProperty("maskable", instance.maskable); + writer.WriteProperty("color", instance.color); + writer.WriteProperty("raycastTarget", instance.raycastTarget); + // Unity automatically sets the default material if it's set to null. + // This prevents missing reference warnings. + if (instance.material.name.Contains("Default")) + writer.WriteProperty("material", null); + else + writer.WriteProperty("material", instance.material); + writer.WriteProperty("useGUILayout", instance.useGUILayout); + writer.WriteProperty("enabled", instance.enabled); + writer.WriteProperty("hideFlags", instance.hideFlags); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.UI.Text)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "m_FontData": + reader.SetPrivateField("m_FontData", reader.Read(), instance); + break; + case "m_LastTrackedFont": + reader.SetPrivateField("m_LastTrackedFont", reader.Read(), instance); + break; + case "m_Text": + reader.SetPrivateField("m_Text", reader.Read(), instance); + break; + case "m_TextCache": + reader.SetPrivateField("m_TextCache", reader.Read(), instance); + break; + case "m_TextCacheForLayout": + reader.SetPrivateField("m_TextCacheForLayout", reader.Read(), instance); + break; + case "m_Material": + reader.SetPrivateField("m_Material", reader.Read(), instance); + break; + case "font": + instance.font = reader.Read(); + break; + case "text": + instance.text = reader.Read(); + break; + case "supportRichText": + instance.supportRichText = reader.Read(); + break; + case "resizeTextForBestFit": + instance.resizeTextForBestFit = reader.Read(); + break; + case "resizeTextMinSize": + instance.resizeTextMinSize = reader.Read(); + break; + case "resizeTextMaxSize": + instance.resizeTextMaxSize = reader.Read(); + break; + case "alignment": + instance.alignment = reader.Read(); + break; + case "alignByGeometry": + instance.alignByGeometry = reader.Read(); + break; + case "fontSize": + instance.fontSize = reader.Read(); + break; + case "horizontalOverflow": + instance.horizontalOverflow = reader.Read(); + break; + case "verticalOverflow": + instance.verticalOverflow = reader.Read(); + break; + case "lineSpacing": + instance.lineSpacing = reader.Read(); + break; + case "fontStyle": + instance.fontStyle = reader.Read(); + break; + case "onCullStateChanged": + instance.onCullStateChanged = reader.Read(); + break; + case "maskable": + instance.maskable = reader.Read(); + break; + case "color": + instance.color = reader.Read(); + break; + case "raycastTarget": + instance.raycastTarget = reader.Read(); + break; + case "material": + instance.material = reader.Read(); + break; + case "useGUILayout": + instance.useGUILayout = reader.Read(); + break; + case "enabled": + instance.enabled = reader.Read(); + break; + case "hideFlags": + instance.hideFlags = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} + +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Text.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Text.cs.meta new file mode 100644 index 0000000..83aa4f4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Text.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 69268592921476a42b9819cd66b6ea4a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Transform.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Transform.cs new file mode 100644 index 0000000..e1b04ea --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Transform.cs @@ -0,0 +1,70 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("localPosition","localRotation","localScale","parent","siblingIndex")] + public class ES3Type_Transform : ES3ComponentType + { + public static int countRead = 0; + public static ES3Type Instance = null; + + public ES3Type_Transform() : base(typeof(UnityEngine.Transform)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Transform)obj; + writer.WritePropertyByRef("parent", instance.parent); + writer.WriteProperty("localPosition", instance.localPosition); + writer.WriteProperty("localRotation", instance.localRotation); + writer.WriteProperty("localScale", instance.localScale); + writer.WriteProperty("siblingIndex", instance.GetSiblingIndex()); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (Transform)obj; + + var characterController = instance.gameObject.GetComponent(); + var characterControllerState = false; + + if (characterController != null) + { + characterControllerState = characterController.enabled; + characterController.enabled = false; + } + + foreach(string propertyName in reader.Properties) + { + switch (propertyName) + { + case "parent": + instance.SetParent(reader.Read()); + break; + case "localPosition": + instance.localPosition = reader.Read(); + break; + case "localRotation": + instance.localRotation = reader.Read(); + break; + case "localScale": + instance.localScale = reader.Read(); + break; + case "siblingIndex": + instance.SetSiblingIndex(reader.Read()); + break; + default: + reader.Skip(); + break; + } + } + + if (characterController != null) + characterController.enabled = characterControllerState; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Transform.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Transform.cs.meta new file mode 100644 index 0000000..92c5277 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/Component Types/ES3Type_Transform.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 91cb5bec8da6744608c92304a04462fd +timeCreated: 1519132291 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AnimationCurve.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AnimationCurve.cs new file mode 100644 index 0000000..853028d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AnimationCurve.cs @@ -0,0 +1,58 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("keys", "preWrapMode", "postWrapMode")] + public class ES3Type_AnimationCurve : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_AnimationCurve() : base(typeof(UnityEngine.AnimationCurve)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.AnimationCurve)obj; + + writer.WriteProperty("keys", instance.keys, ES3Type_KeyframeArray.Instance); + writer.WriteProperty("preWrapMode", instance.preWrapMode); + writer.WriteProperty("postWrapMode", instance.postWrapMode); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.AnimationCurve(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.AnimationCurve)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "keys": + instance.keys = reader.Read(); + break; + case "preWrapMode": + instance.preWrapMode = reader.Read(); + break; + case "postWrapMode": + instance.postWrapMode = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AnimationCurve.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AnimationCurve.cs.meta new file mode 100644 index 0000000..4744a26 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AnimationCurve.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5939fcd6cf1ac4167b4320111cb9930e +timeCreated: 1519132286 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AudioClip.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AudioClip.cs new file mode 100644 index 0000000..f2971ae --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AudioClip.cs @@ -0,0 +1,90 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("name", "samples", "channels", "frequency", "sampleData")] + public class ES3Type_AudioClip : ES3UnityObjectType + { + public static ES3Type Instance = null; + + public ES3Type_AudioClip() : base(typeof(UnityEngine.AudioClip)){ Instance = this; } + + protected override void WriteUnityObject(object obj, ES3Writer writer) + { + var param = (UnityEngine.AudioClip)obj; + float[] samples = new float[param.samples * param.channels]; + param.GetData(samples, 0); + writer.WriteProperty("name", param.name); + writer.WriteProperty("samples", param.samples); + writer.WriteProperty("channels", param.channels); + writer.WriteProperty("frequency", param.frequency); + writer.WriteProperty("sampleData", samples); + } + + protected override void ReadUnityObject(ES3Reader reader, object obj) + { + var clip = (AudioClip)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + case "sampleData": + clip.SetData(reader.Read(ES3Type_floatArray.Instance), 0); + break; + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadUnityObject(ES3Reader reader) + { + string name = ""; + int samples = 0; + int channels = 0; + int frequency = 0; + AudioClip clip = null; + + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + case "name": + name = reader.Read(ES3Type_string.Instance); + break; + case "samples": + samples = reader.Read(ES3Type_int.Instance); + break; + case "channels": + channels = reader.Read(ES3Type_int.Instance); + break; + case "frequency": + frequency = reader.Read(ES3Type_int.Instance); + break; + case "sampleData": + clip = AudioClip.Create(name, samples, channels, frequency, false); + clip.SetData(reader.Read(ES3Type_floatArray.Instance), 0); + break; + default: + reader.Skip(); + break; + } + } + + return clip; + } + } + + public class ES3Type_AudioClipArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_AudioClipArray() : base(typeof(UnityEngine.AudioClip[]), ES3Type_AudioClip.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AudioClip.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AudioClip.cs.meta new file mode 100644 index 0000000..77d148d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_AudioClip.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9b8f97ab775644e1782f7775c54f891a +timeCreated: 1519132292 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_BoneWeight.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_BoneWeight.cs new file mode 100644 index 0000000..ab8b845 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_BoneWeight.cs @@ -0,0 +1,61 @@ +using System; +using UnityEngine; +using System.Collections.Generic; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("boneIndex0", "boneIndex1", "boneIndex2", "boneIndex3", "weight0", "weight1", "weight2", "weight3")] + public class ES3Type_BoneWeight : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_BoneWeight() : base(typeof(BoneWeight)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + BoneWeight casted = (BoneWeight)obj; + + writer.WriteProperty("boneIndex0", casted.boneIndex0, ES3Type_int.Instance); + writer.WriteProperty("boneIndex1", casted.boneIndex1, ES3Type_int.Instance); + writer.WriteProperty("boneIndex2", casted.boneIndex2, ES3Type_int.Instance); + writer.WriteProperty("boneIndex3", casted.boneIndex3, ES3Type_int.Instance); + + writer.WriteProperty("weight0", casted.weight0, ES3Type_float.Instance); + writer.WriteProperty("weight1", casted.weight1, ES3Type_float.Instance); + writer.WriteProperty("weight2", casted.weight2, ES3Type_float.Instance); + writer.WriteProperty("weight3", casted.weight3, ES3Type_float.Instance); + + } + + public override object Read(ES3Reader reader) + { + var obj = new BoneWeight(); + + obj.boneIndex0 = reader.ReadProperty(ES3Type_int.Instance); + obj.boneIndex1 = reader.ReadProperty(ES3Type_int.Instance); + obj.boneIndex2 = reader.ReadProperty(ES3Type_int.Instance); + obj.boneIndex3 = reader.ReadProperty(ES3Type_int.Instance); + + obj.weight0 = reader.ReadProperty(ES3Type_float.Instance); + obj.weight1 = reader.ReadProperty(ES3Type_float.Instance); + obj.weight2 = reader.ReadProperty(ES3Type_float.Instance); + obj.weight3 = reader.ReadProperty(ES3Type_float.Instance); + + return obj; + } + } + + public class ES3Type_BoneWeightArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_BoneWeightArray() : base(typeof(BoneWeight[]), ES3Type_BoneWeight.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_BoneWeight.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_BoneWeight.cs.meta new file mode 100644 index 0000000..66448fd --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_BoneWeight.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 570ee00d71c7c43a5a7e6a68e2c9d96f +timeCreated: 1519132285 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Bounds.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Bounds.cs new file mode 100644 index 0000000..6cfba1f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Bounds.cs @@ -0,0 +1,42 @@ +using System; +using UnityEngine; +using System.Collections.Generic; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("center", "size")] + public class ES3Type_Bounds : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Bounds() : base(typeof(Bounds)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Bounds casted = (Bounds)obj; + + writer.WriteProperty("center", casted.center, ES3Type_Vector3.Instance); + writer.WriteProperty("size", casted.size, ES3Type_Vector3.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Bounds( reader.ReadProperty(ES3Type_Vector3.Instance), + reader.ReadProperty(ES3Type_Vector3.Instance)); + } + } + + public class ES3Type_BoundsArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_BoundsArray() : base(typeof(Bounds[]), ES3Type_Bounds.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Bounds.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Bounds.cs.meta new file mode 100644 index 0000000..c85d95d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Bounds.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3a9d8a8b9b10b466786d6d39807aa8e0 +timeCreated: 1519132283 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Burst.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Burst.cs new file mode 100644 index 0000000..ce7d171 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Burst.cs @@ -0,0 +1,77 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("time", "count", "minCount", "maxCount", "cycleCount", "repeatInterval", "probability")] + public class ES3Type_Burst : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Burst() : base(typeof(UnityEngine.ParticleSystem.Burst)){ Instance = this; } + + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.Burst)obj; + + writer.WriteProperty("time", instance.time, ES3Type_float.Instance); + writer.WriteProperty("count", instance.count, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("minCount", instance.minCount, ES3Type_short.Instance); + writer.WriteProperty("maxCount", instance.maxCount, ES3Type_short.Instance); + writer.WriteProperty("cycleCount", instance.cycleCount, ES3Type_int.Instance); + writer.WriteProperty("repeatInterval", instance.repeatInterval, ES3Type_float.Instance); + writer.WriteProperty("probability", instance.probability, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.Burst(); + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "time": + instance.time = reader.Read(ES3Type_float.Instance); + break; + case "count": + instance.count = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "minCount": + instance.minCount = reader.Read(ES3Type_short.Instance); + break; + case "maxCount": + instance.maxCount = reader.Read(ES3Type_short.Instance); + break; + case "cycleCount": + instance.cycleCount = reader.Read(ES3Type_int.Instance); + break; + case "repeatInterval": + instance.repeatInterval = reader.Read(ES3Type_float.Instance); + break; + case "probability": + instance.probability = reader.Read(ES3Type_float.Instance); + break; + default: + reader.Skip(); + break; + } + } + return instance; + } + } + + + public class ES3Type_BurstArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_BurstArray() : base(typeof(UnityEngine.ParticleSystem.Burst[]), ES3Type_Burst.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Burst.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Burst.cs.meta new file mode 100644 index 0000000..b08fb3a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Burst.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f15f94055e5ae9346969078ad65f3786 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_CollisionModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_CollisionModule.cs new file mode 100644 index 0000000..5555945 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_CollisionModule.cs @@ -0,0 +1,117 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "type", "mode", "dampen", "dampenMultiplier", "bounce", "bounceMultiplier", "lifetimeLoss", "lifetimeLossMultiplier", "minKillSpeed", "maxKillSpeed", "collidesWith", "enableDynamicColliders", "maxCollisionShapes", "quality", "voxelSize", "radiusScale", "sendCollisionMessages")] + public class ES3Type_CollisionModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_CollisionModule() : base(typeof(UnityEngine.ParticleSystem.CollisionModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.CollisionModule)obj; + + writer.WriteProperty("enabled", instance.enabled); + writer.WriteProperty("type", instance.type); + writer.WriteProperty("mode", instance.mode); + writer.WriteProperty("dampen", instance.dampen); + writer.WriteProperty("dampenMultiplier", instance.dampenMultiplier); + writer.WriteProperty("bounce", instance.bounce); + writer.WriteProperty("bounceMultiplier", instance.bounceMultiplier); + writer.WriteProperty("lifetimeLoss", instance.lifetimeLoss); + writer.WriteProperty("lifetimeLossMultiplier", instance.lifetimeLossMultiplier); + writer.WriteProperty("minKillSpeed", instance.minKillSpeed); + writer.WriteProperty("maxKillSpeed", instance.maxKillSpeed); + writer.WriteProperty("collidesWith", instance.collidesWith); + writer.WriteProperty("enableDynamicColliders", instance.enableDynamicColliders); + writer.WriteProperty("maxCollisionShapes", instance.maxCollisionShapes); + writer.WriteProperty("quality", instance.quality); + writer.WriteProperty("voxelSize", instance.voxelSize); + writer.WriteProperty("radiusScale", instance.radiusScale); + writer.WriteProperty("sendCollisionMessages", instance.sendCollisionMessages); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.CollisionModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.CollisionModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + case "enabled": + instance.enabled = reader.Read(); + break; + case "type": + instance.type = reader.Read(); + break; + case "mode": + instance.mode = reader.Read(); + break; + case "dampen": + instance.dampen = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "dampenMultiplier": + instance.dampenMultiplier = reader.Read(); + break; + case "bounce": + instance.bounce = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "bounceMultiplier": + instance.bounceMultiplier = reader.Read(); + break; + case "lifetimeLoss": + instance.lifetimeLoss = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "lifetimeLossMultiplier": + instance.lifetimeLossMultiplier = reader.Read(); + break; + case "minKillSpeed": + instance.minKillSpeed = reader.Read(); + break; + case "maxKillSpeed": + instance.maxKillSpeed = reader.Read(); + break; + case "collidesWith": + instance.collidesWith = reader.Read(); + break; + case "enableDynamicColliders": + instance.enableDynamicColliders = reader.Read(); + break; + case "maxCollisionShapes": + instance.maxCollisionShapes = reader.Read(); + break; + case "quality": + instance.quality = reader.Read(); + break; + case "voxelSize": + instance.voxelSize = reader.Read(); + break; + case "radiusScale": + instance.radiusScale = reader.Read(); + break; + case "sendCollisionMessages": + instance.sendCollisionMessages = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_CollisionModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_CollisionModule.cs.meta new file mode 100644 index 0000000..8474ea0 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_CollisionModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 45f02f0eb77fe4209a290c5928c9ade5 +timeCreated: 1519132284 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color.cs new file mode 100644 index 0000000..e35b0d9 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color.cs @@ -0,0 +1,44 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("r", "g", "b", "a")] + public class ES3Type_Color : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Color() : base(typeof(Color)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Color casted = (Color)obj; + writer.WriteProperty("r", casted.r, ES3Type_float.Instance); + writer.WriteProperty("g", casted.g, ES3Type_float.Instance); + writer.WriteProperty("b", casted.b, ES3Type_float.Instance); + writer.WriteProperty("a", casted.a, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Color( reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance)); + } + } + + public class ES3Type_ColorArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_ColorArray() : base(typeof(Color[]), ES3Type_Color.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color.cs.meta new file mode 100644 index 0000000..1d0dc8b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b97411847937943ab859b0ab7acfb872 +timeCreated: 1519132295 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color32.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color32.cs new file mode 100644 index 0000000..a5ddd20 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color32.cs @@ -0,0 +1,51 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("r", "g", "b", "a")] + public class ES3Type_Color32 : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Color32() : base(typeof(Color32)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Color32 casted = (Color32)obj; + writer.WriteProperty("r", casted.r, ES3Type_byte.Instance); + writer.WriteProperty("g", casted.g, ES3Type_byte.Instance); + writer.WriteProperty("b", casted.b, ES3Type_byte.Instance); + writer.WriteProperty("a", casted.a, ES3Type_byte.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Color32( reader.ReadProperty(ES3Type_byte.Instance), + reader.ReadProperty(ES3Type_byte.Instance), + reader.ReadProperty(ES3Type_byte.Instance), + reader.ReadProperty(ES3Type_byte.Instance)); + } + + public static bool Equals(Color32 a, Color32 b) + { + if(a.r != b.r || a.g != b.g || a.b != b.b || a.a != b.a) + return false; + return true; + } + } + + public class ES3Type_Color32Array : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_Color32Array() : base(typeof(Color32[]), ES3Type_Color32.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color32.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color32.cs.meta new file mode 100644 index 0000000..93d9bfc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Color32.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 3b1b3a09c48c14072a133f5ba4c651e7 +timeCreated: 1519132283 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorBySpeedModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorBySpeedModule.cs new file mode 100644 index 0000000..d65b3a0 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorBySpeedModule.cs @@ -0,0 +1,58 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "color", "range")] + public class ES3Type_ColorBySpeedModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_ColorBySpeedModule() : base(typeof(UnityEngine.ParticleSystem.ColorBySpeedModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.ColorBySpeedModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("color", instance.color, ES3Type_MinMaxGradient.Instance); + writer.WriteProperty("range", instance.range, ES3Type_Vector2.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.ColorBySpeedModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.ColorBySpeedModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "color": + instance.color = reader.Read(ES3Type_MinMaxGradient.Instance); + break; + case "range": + instance.range = reader.Read(ES3Type_Vector2.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorBySpeedModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorBySpeedModule.cs.meta new file mode 100644 index 0000000..38e5107 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorBySpeedModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fb109d087368d4849b6e1222c912ec72 +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorOverLifetimeModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorOverLifetimeModule.cs new file mode 100644 index 0000000..9266d62 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorOverLifetimeModule.cs @@ -0,0 +1,54 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "color")] + public class ES3Type_ColorOverLifetimeModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_ColorOverLifetimeModule() : base(typeof(UnityEngine.ParticleSystem.ColorOverLifetimeModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.ColorOverLifetimeModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("color", instance.color, ES3Type_MinMaxGradient.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.ColorOverLifetimeModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.ColorOverLifetimeModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "color": + instance.color = reader.Read(ES3Type_MinMaxGradient.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorOverLifetimeModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorOverLifetimeModule.cs.meta new file mode 100644 index 0000000..39921c1 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ColorOverLifetimeModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 744909a4693a34ff99f9886d8bddc408 +timeCreated: 1519132288 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_EmissionModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_EmissionModule.cs new file mode 100644 index 0000000..39a0244 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_EmissionModule.cs @@ -0,0 +1,74 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "rateOverTime", "rateOverTimeMultiplier", "rateOverDistance", "rateOverDistanceMultiplier")] + public class ES3Type_EmissionModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_EmissionModule() : base(typeof(UnityEngine.ParticleSystem.EmissionModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.EmissionModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("rateOverTime", instance.rateOverTime, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("rateOverTimeMultiplier", instance.rateOverTimeMultiplier, ES3Type_float.Instance); + writer.WriteProperty("rateOverDistance", instance.rateOverDistance, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("rateOverDistanceMultiplier", instance.rateOverDistanceMultiplier, ES3Type_float.Instance); + + var bursts = new ParticleSystem.Burst[instance.burstCount]; + instance.GetBursts(bursts); + writer.WriteProperty("bursts", bursts, ES3Type_BurstArray.Instance); + } + + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.EmissionModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.EmissionModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "rateOverTime": + instance.rateOverTime = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "rateOverTimeMultiplier": + instance.rateOverTimeMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "rateOverDistance": + instance.rateOverDistance = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "rateOverDistanceMultiplier": + instance.rateOverDistanceMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "bursts": + instance.SetBursts(reader.Read(ES3Type_BurstArray.Instance)); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_EmissionModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_EmissionModule.cs.meta new file mode 100644 index 0000000..99fcbec --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_EmissionModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0601343d0f8fb45d591c1f16dde23330 +timeCreated: 1519132279 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ExternalForcesModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ExternalForcesModule.cs new file mode 100644 index 0000000..06b774e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ExternalForcesModule.cs @@ -0,0 +1,54 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "multiplier")] + public class ES3Type_ExternalForcesModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_ExternalForcesModule() : base(typeof(UnityEngine.ParticleSystem.ExternalForcesModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.ExternalForcesModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("multiplier", instance.multiplier, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.ExternalForcesModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.ExternalForcesModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "multiplier": + instance.multiplier = reader.Read(ES3Type_float.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ExternalForcesModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ExternalForcesModule.cs.meta new file mode 100644 index 0000000..6c9f789 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ExternalForcesModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 73b0b581a64c54420b1931059384200c +timeCreated: 1519132288 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Flare.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Flare.cs new file mode 100644 index 0000000..3cdb7c4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Flare.cs @@ -0,0 +1,60 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("hideFlags")] + public class ES3Type_Flare : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Flare() : base(typeof(UnityEngine.Flare)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Flare)obj; + + writer.WriteProperty("hideFlags", instance.hideFlags); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.Flare(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.Flare)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "hideFlags": + instance.hideFlags = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } + + public class ES3Type_FlareArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_FlareArray() : base(typeof(UnityEngine.Flare[]), ES3Type_Flare.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Flare.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Flare.cs.meta new file mode 100644 index 0000000..daf3587 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Flare.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 32592ed571b254a1ebc1cda3cc03f861 +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Font.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Font.cs new file mode 100644 index 0000000..4fc08ec --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Font.cs @@ -0,0 +1,57 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("material", "name")] + public class ES3Type_Font : ES3UnityObjectType + { + public static ES3Type Instance = null; + + public ES3Type_Font() : base(typeof(UnityEngine.Font)){ Instance = this; } + + protected override void WriteUnityObject(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Font)obj; + + writer.WriteProperty("name", instance.name, ES3Type_string.Instance); + writer.WriteProperty("material", instance.material); + } + + protected override void ReadUnityObject(ES3Reader reader, object obj) + { + var instance = (UnityEngine.Font)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + case "material": + instance.material = reader.Read(ES3Type_Material.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadUnityObject(ES3Reader reader) + { + var instance = new UnityEngine.Font(reader.ReadProperty(ES3Type_string.Instance)); + ReadObject(reader, instance); + return instance; + } + } + + public class ES3Type_FontArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_FontArray() : base(typeof(UnityEngine.Font[]), ES3Type_Font.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Font.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Font.cs.meta new file mode 100644 index 0000000..e82c7b7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Font.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b779410f33269447a8410aa5c60a3366 +timeCreated: 1519132294 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ForceOverLifetimeModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ForceOverLifetimeModule.cs new file mode 100644 index 0000000..6215392 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ForceOverLifetimeModule.cs @@ -0,0 +1,82 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "x", "y", "z", "xMultiplier", "yMultiplier", "zMultiplier", "space", "randomized")] + public class ES3Type_ForceOverLifetimeModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_ForceOverLifetimeModule() : base(typeof(UnityEngine.ParticleSystem.ForceOverLifetimeModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.ForceOverLifetimeModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("x", instance.x, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("y", instance.y, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("z", instance.z, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("xMultiplier", instance.xMultiplier, ES3Type_float.Instance); + writer.WriteProperty("yMultiplier", instance.yMultiplier, ES3Type_float.Instance); + writer.WriteProperty("zMultiplier", instance.zMultiplier, ES3Type_float.Instance); + writer.WriteProperty("space", instance.space); + writer.WriteProperty("randomized", instance.randomized, ES3Type_bool.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.ForceOverLifetimeModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.ForceOverLifetimeModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "x": + instance.x = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "y": + instance.y = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "z": + instance.z = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "xMultiplier": + instance.xMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "yMultiplier": + instance.yMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "zMultiplier": + instance.zMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "space": + instance.space = reader.Read(); + break; + case "randomized": + instance.randomized = reader.Read(ES3Type_bool.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ForceOverLifetimeModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ForceOverLifetimeModule.cs.meta new file mode 100644 index 0000000..537835b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ForceOverLifetimeModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: fd5844fc025754c5399be113ca40fc39 +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GameObject.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GameObject.cs new file mode 100644 index 0000000..84186a8 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GameObject.cs @@ -0,0 +1,320 @@ +using System; +using UnityEngine; +using System.Collections.Generic; +using ES3Internal; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("layer", "isStatic", "tag", "name", "hideFlags", "children", "components")] + public class ES3Type_GameObject : ES3UnityObjectType + { + private const string prefabPropertyName = "es3Prefab"; + private const string transformPropertyName = "transformID"; + public static ES3Type Instance = null; + public bool saveChildren = false; + + public ES3Type_GameObject() : base(typeof(UnityEngine.GameObject)) { Instance = this; } + + public override void WriteObject(object obj, ES3Writer writer, ES3.ReferenceMode mode) + { + if (WriteUsingDerivedType(obj, writer)) + return; + var instance = (UnityEngine.GameObject)obj; + + var mgr = ES3ReferenceMgrBase.GetManagerFromScene(instance.scene); + + if (mode != ES3.ReferenceMode.ByValue) + { + writer.WriteRef(instance, ES3ReferenceMgrBase.referencePropertyName, mgr); + + if (mode == ES3.ReferenceMode.ByRef) + return; + + var es3Prefab = instance.GetComponent(); + if (es3Prefab != null) + writer.WriteProperty(prefabPropertyName, es3Prefab, ES3Type_ES3PrefabInternal.Instance); + + // Write the ID of this Transform so we can assign it's ID when we load. + writer.WriteRef(instance.transform, transformPropertyName, mgr); + } + + var es3AutoSave = instance.GetComponent(); + + if(es3AutoSave == null || es3AutoSave.saveLayer) + writer.WriteProperty("layer", instance.layer, ES3Type_int.Instance); + if (es3AutoSave == null || es3AutoSave.saveTag) + writer.WriteProperty("tag", instance.tag, ES3Type_string.Instance); + if (es3AutoSave == null || es3AutoSave.saveName) + writer.WriteProperty("name", instance.name, ES3Type_string.Instance); + if (es3AutoSave == null || es3AutoSave.saveHideFlags) + writer.WriteProperty("hideFlags", instance.hideFlags); + if (es3AutoSave == null || es3AutoSave.saveActive) + writer.WriteProperty("active", instance.activeSelf); + + if ((es3AutoSave == null && saveChildren) || (es3AutoSave != null && es3AutoSave.saveChildren)) + writer.WriteProperty("children", GetChildren(instance), ES3.ReferenceMode.ByRefAndValue); + + List components; + + var es3GameObject = instance.GetComponent(); + + // If there's an ES3AutoSave attached and Components are marked to be saved, save these. + if (es3AutoSave != null) + { + es3AutoSave.componentsToSave.RemoveAll(c => c == null); + components = es3AutoSave.componentsToSave; + } + // If there's an ES3GameObject attached, save these. + else if (es3GameObject != null) + { + es3GameObject.components.RemoveAll(c => c == null); + components = es3GameObject.components; + } + // Otherwise, only save explicitly-supported Components, /*or those explicitly marked as Serializable*/. + else + { + components = new List(); + foreach (var component in instance.GetComponents()) + if (component != null && ES3TypeMgr.GetES3Type(component.GetType()) != null) + components.Add(component); + } + + if(components != null & components.Count > 0) + writer.WriteProperty("components", components, ES3.ReferenceMode.ByRefAndValue); + } + + protected override object ReadObject(ES3Reader reader) + { + UnityEngine.Object obj = null; + var refMgr = ES3ReferenceMgrBase.Current; + long id = 0; + + // Read the intial properties regarding the instance we're loading. + while (true) + { + if (refMgr == null) + throw new InvalidOperationException($"An Easy Save 3 Manager is required to save references. To add one to your scene, exit playmode and go to Tools > Easy Save 3 > Add Manager to Scene. Object being saved by reference is {obj.GetType()} with name {obj.name}."); + + var propertyName = ReadPropertyName(reader); + + if (propertyName == ES3Type.typeFieldName) + return ES3TypeMgr.GetOrCreateES3Type(reader.ReadType()).Read(reader); + else if (propertyName == ES3ReferenceMgrBase.referencePropertyName) + { + id = reader.Read_ref(); + obj = refMgr.Get(id, true); + } + else if (propertyName == transformPropertyName) + { + // Now load the Transform's ID and assign it to the Transform of our object. + long transformID = reader.Read_ref(); + if (obj == null) + obj = CreateNewGameObject(refMgr, id); + refMgr.Add(((GameObject)obj).transform, transformID); + } + else if (propertyName == prefabPropertyName) + { + if (obj != null || ES3ReferenceMgrBase.Current == null) + { + reader.ReadInto(obj); // ReadInto to apply the prefab references. + } + else + { + obj = reader.Read(ES3Type_ES3PrefabInternal.Instance); + ES3ReferenceMgrBase.Current.Add(obj, id); + } + } + else if (propertyName == null) + { + /*if (obj == null) + obj = CreateNewGameObject(refMgr, id);*/ + return obj; + } + else + { + reader.overridePropertiesName = propertyName; + break; + } + } + + if (obj == null) + obj = CreateNewGameObject(refMgr, id); + + ReadInto(reader, obj); + return obj; + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var instance = (UnityEngine.GameObject)obj; + + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + case ES3ReferenceMgrBase.referencePropertyName: + ES3ReferenceMgr.Current.Add(instance, reader.Read_ref()); + break; + case "prefab": + break; + case "layer": + instance.layer = reader.Read(ES3Type_int.Instance); + break; + case "tag": + instance.tag = reader.Read(ES3Type_string.Instance); + break; + case "name": + instance.name = reader.Read(ES3Type_string.Instance); + break; + case "hideFlags": + instance.hideFlags = reader.Read(); + break; + case "active": + instance.SetActive(reader.Read(ES3Type_bool.Instance)); + break; + case "children": + var children = reader.Read(); + var parent = instance.transform; + // Set the parent of each child to this Transform in case the reference ID of the parent has changed. + foreach (var child in children) + child.transform.SetParent(parent); + break; + case "components": + ReadComponents(reader, instance); + break; + default: + reader.Skip(); + break; + } + } + } + + private void ReadComponents(ES3Reader reader, GameObject go) + { + if (reader.StartReadCollection()) + return; + + var components = new List(go.GetComponents()); + + // Read each Component in Components array + while (true) + { + if (!reader.StartReadCollectionItem()) + break; + + if (reader.StartReadObject()) + // We're reading null, so skip this Component. + continue; + + string typeName = null; + Type type = null; + + string propertyName; + while (true) + { + propertyName = ReadPropertyName(reader); + + if (propertyName == ES3Type.typeFieldName) + { + typeName = reader.Read(ES3Type_string.Instance); + type = ES3Reflection.GetType(typeName); + } + else if (propertyName == ES3ReferenceMgrBase.referencePropertyName) + { + if (type == null) + { + if (string.IsNullOrEmpty(typeName)) + throw new InvalidOperationException("Cannot load Component because no type data has been stored with it, so it's not possible to determine it's type"); + else + Debug.LogWarning($"Cannot load Component of type {typeName} because this type no longer exists in your project. Note that this issue will create an empty GameObject named 'New Game Object' in your scene due to the way in which this Component needs to be skipped."); + + // Read past the Component. + reader.overridePropertiesName = propertyName; + ReadObject(reader); + break; + } + + var componentRef = reader.Read_ref(); + + // Rather than loading by reference, load using the Components list. + var c = components.Find(x => x.GetType() == type); + // If the Component exists in the Component list, load into it and remove it from the list. + if (c != null) + { + if (ES3ReferenceMgrBase.Current != null) + ES3ReferenceMgrBase.Current.Add(c, componentRef); + + ES3TypeMgr.GetOrCreateES3Type(type).ReadInto(reader, c); + components.Remove(c); + } + // Else, create a new Component. + else + { + var component = go.AddComponent(type); + ES3TypeMgr.GetOrCreateES3Type(type).ReadInto(reader, component); + ES3ReferenceMgrBase.Current.Add(component, componentRef); + } + break; + } + else if (propertyName == null) + break; + else + { + reader.overridePropertiesName = propertyName; + ReadObject(reader); + break; + } + } + + reader.EndReadObject(); + + if (reader.EndReadCollectionItem()) + break; + } + + reader.EndReadCollection(); + } + + private GameObject CreateNewGameObject(ES3ReferenceMgrBase refMgr, long id) + { + GameObject go = new GameObject(); + if (id != 0) + refMgr.Add(go, id); + else + refMgr.Add(go); + return go; + } + + /* + * Gets the direct children of this GameObject. + */ + public static List GetChildren(GameObject go) + { + var goTransform = go.transform; + var children = new List(); + + foreach (Transform child in goTransform) + // If a child has an Auto Save component, let it save itself. + //if(child.GetComponent() == null) + children.Add(child.gameObject); + + return children; + } + + // These are not used as we've overridden the ReadObject methods instead. + protected override void WriteUnityObject(object obj, ES3Writer writer) { } + protected override void ReadUnityObject(ES3Reader reader, object obj) { } + protected override object ReadUnityObject(ES3Reader reader) { return null; } + } + + public class ES3Type_GameObjectArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_GameObjectArray() : base(typeof(UnityEngine.GameObject[]), ES3Type_GameObject.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GameObject.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GameObject.cs.meta new file mode 100644 index 0000000..0f59d3b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GameObject.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 1ca7947fbcbec457f89b984a9647a9d7 +timeCreated: 1519132281 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Gradient.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Gradient.cs new file mode 100644 index 0000000..5107de7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Gradient.cs @@ -0,0 +1,55 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("colorKeys", "alphaKeys", "mode")] + public class ES3Type_Gradient : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Gradient() : base(typeof(UnityEngine.Gradient)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Gradient)obj; + writer.WriteProperty("colorKeys", instance.colorKeys, ES3Type_GradientColorKeyArray.Instance); + writer.WriteProperty("alphaKeys", instance.alphaKeys, ES3Type_GradientAlphaKeyArray.Instance); + writer.WriteProperty("mode", instance.mode); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.Gradient(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.Gradient)obj; + instance.SetKeys( + reader.ReadProperty(ES3Type_GradientColorKeyArray.Instance), + reader.ReadProperty(ES3Type_GradientAlphaKeyArray.Instance) + ); + + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + case "mode": + instance.mode = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Gradient.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Gradient.cs.meta new file mode 100644 index 0000000..e400a6e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Gradient.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a509023afeeee4a49965009b6ba4bc44 +timeCreated: 1519132293 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientAlphaKey.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientAlphaKey.cs new file mode 100644 index 0000000..24ce934 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientAlphaKey.cs @@ -0,0 +1,41 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("alpha", "time")] + public class ES3Type_GradientAlphaKey : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_GradientAlphaKey() : base(typeof(UnityEngine.GradientAlphaKey)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.GradientAlphaKey)obj; + + writer.WriteProperty("alpha", instance.alpha, ES3Type_float.Instance); + writer.WriteProperty("time", instance.time, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + return new UnityEngine.GradientAlphaKey(reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance)); + } + } + + public class ES3Type_GradientAlphaKeyArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_GradientAlphaKeyArray() : base(typeof(GradientAlphaKey[]), ES3Type_GradientAlphaKey.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientAlphaKey.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientAlphaKey.cs.meta new file mode 100644 index 0000000..8b69cd8 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientAlphaKey.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 934a57ef826284a56bb97406bcf373fd +timeCreated: 1519132291 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientColorKey.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientColorKey.cs new file mode 100644 index 0000000..7317e47 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientColorKey.cs @@ -0,0 +1,41 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("color", "time")] + public class ES3Type_GradientColorKey : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_GradientColorKey() : base(typeof(UnityEngine.GradientColorKey)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.GradientColorKey)obj; + + writer.WriteProperty("color", instance.color, ES3Type_Color.Instance); + writer.WriteProperty("time", instance.time, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + return new UnityEngine.GradientColorKey(reader.ReadProperty(ES3Type_Color.Instance), + reader.ReadProperty(ES3Type_float.Instance)); + } + } + + public class ES3Type_GradientColorKeyArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_GradientColorKeyArray() : base(typeof(GradientColorKey[]), ES3Type_GradientColorKey.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientColorKey.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientColorKey.cs.meta new file mode 100644 index 0000000..b154e9a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_GradientColorKey.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9dcbf4e7ca28b4bd5a6eb0a9d256c082 +timeCreated: 1519132292 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Guid.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Guid.cs new file mode 100644 index 0000000..d56e433 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Guid.cs @@ -0,0 +1,37 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("value")] + public class ES3Type_Guid : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Guid() : base(typeof(Guid)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Guid casted = (Guid)obj; + writer.WriteProperty("value", casted.ToString(), ES3Type_string.Instance); + } + + public override object Read(ES3Reader reader) + { + return Guid.Parse(reader.ReadProperty(ES3Type_string.Instance)); + } + } + + public class ES3Type_GuidArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_GuidArray() : base(typeof(Guid[]), ES3Type_Guid.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Guid.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Guid.cs.meta new file mode 100644 index 0000000..873d71f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Guid.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7e9441d85c177084db4be38cf2cb2aca +timeCreated: 1519132295 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_InheritVelocityModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_InheritVelocityModule.cs new file mode 100644 index 0000000..07bb743 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_InheritVelocityModule.cs @@ -0,0 +1,62 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "mode", "curve", "curveMultiplier")] + public class ES3Type_InheritVelocityModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_InheritVelocityModule() : base(typeof(UnityEngine.ParticleSystem.InheritVelocityModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.InheritVelocityModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("mode", instance.mode); + writer.WriteProperty("curve", instance.curve, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("curveMultiplier", instance.curveMultiplier, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.InheritVelocityModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.InheritVelocityModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "mode": + instance.mode = reader.Read(); + break; + case "curve": + instance.curve = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "curveMultiplier": + instance.curveMultiplier = reader.Read(ES3Type_float.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_InheritVelocityModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_InheritVelocityModule.cs.meta new file mode 100644 index 0000000..35f3ffd --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_InheritVelocityModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c652805edba024e5c885fa799b3a5775 +timeCreated: 1519132296 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Keyframe.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Keyframe.cs new file mode 100644 index 0000000..af39e94 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Keyframe.cs @@ -0,0 +1,45 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("time", "value", "inTangent", "outTangent")] + public class ES3Type_Keyframe : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Keyframe() : base(typeof(UnityEngine.Keyframe)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Keyframe)obj; + + writer.WriteProperty("time", instance.time, ES3Type_float.Instance); + writer.WriteProperty("value", instance.value, ES3Type_float.Instance); + writer.WriteProperty("inTangent", instance.inTangent, ES3Type_float.Instance); + writer.WriteProperty("outTangent", instance.outTangent, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + return new UnityEngine.Keyframe(reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance)); + } + } + + public class ES3Type_KeyframeArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_KeyframeArray() : base(typeof(Keyframe[]), ES3Type_Keyframe.Instance) + { + Instance = this; + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Keyframe.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Keyframe.cs.meta new file mode 100644 index 0000000..81154b3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Keyframe.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 63eb0700074954e23aa09edcc4b81016 +timeCreated: 1519132287 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LayerMask.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LayerMask.cs new file mode 100644 index 0000000..e829a20 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LayerMask.cs @@ -0,0 +1,43 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("colorKeys", "alphaKeys", "mode")] + public class ES3Type_LayerMask : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_LayerMask() : base(typeof(UnityEngine.LayerMask)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.LayerMask)obj; + + writer.WriteProperty("value", instance.value, ES3Type_int.Instance); + } + + public override object Read(ES3Reader reader) + { + LayerMask instance = new LayerMask(); + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + case "value": + instance = reader.Read(ES3Type_int.Instance); + break; + default: + reader.Skip(); + break; + } + } + return instance; + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LayerMask.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LayerMask.cs.meta new file mode 100644 index 0000000..45f770c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LayerMask.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ad28544641a3c495b8ebbf10c51bf359 +timeCreated: 1519132293 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Light.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Light.cs new file mode 100644 index 0000000..b8501fd --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Light.cs @@ -0,0 +1,117 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("type", "color", "intensity", "bounceIntensity", "shadows", "shadowStrength", "shadowResolution", "shadowCustomResolution", "shadowBias", "shadowNormalBias", "shadowNearPlane", "range", "spotAngle", "cookieSize", "cookie", "flare", "renderMode", "cullingMask", "areaSize", "lightmappingMode", "enabled", "hideFlags")] + public class ES3Type_Light : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_Light() : base(typeof(UnityEngine.Light)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Light)obj; + + writer.WriteProperty("type", instance.type); + writer.WriteProperty("color", instance.color, ES3Type_Color.Instance); + writer.WriteProperty("intensity", instance.intensity, ES3Type_float.Instance); + writer.WriteProperty("bounceIntensity", instance.bounceIntensity, ES3Type_float.Instance); + writer.WriteProperty("shadows", instance.shadows); + writer.WriteProperty("shadowStrength", instance.shadowStrength, ES3Type_float.Instance); + writer.WriteProperty("shadowResolution", instance.shadowResolution); + writer.WriteProperty("shadowCustomResolution", instance.shadowCustomResolution, ES3Type_int.Instance); + writer.WriteProperty("shadowBias", instance.shadowBias, ES3Type_float.Instance); + writer.WriteProperty("shadowNormalBias", instance.shadowNormalBias, ES3Type_float.Instance); + writer.WriteProperty("shadowNearPlane", instance.shadowNearPlane, ES3Type_float.Instance); + writer.WriteProperty("range", instance.range, ES3Type_float.Instance); + writer.WriteProperty("spotAngle", instance.spotAngle, ES3Type_float.Instance); + writer.WriteProperty("cookieSize", instance.cookieSize, ES3Type_float.Instance); + writer.WriteProperty("cookie", instance.cookie, ES3Type_Texture2D.Instance); + writer.WriteProperty("flare", instance.flare, ES3Type_Texture2D.Instance); + writer.WriteProperty("renderMode", instance.renderMode); + writer.WriteProperty("cullingMask", instance.cullingMask, ES3Type_int.Instance); + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("hideFlags", instance.hideFlags); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.Light)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "type": + instance.type = reader.Read(); + break; + case "color": + instance.color = reader.Read(ES3Type_Color.Instance); + break; + case "intensity": + instance.intensity = reader.Read(ES3Type_float.Instance); + break; + case "bounceIntensity": + instance.bounceIntensity = reader.Read(ES3Type_float.Instance); + break; + case "shadows": + instance.shadows = reader.Read(); + break; + case "shadowStrength": + instance.shadowStrength = reader.Read(ES3Type_float.Instance); + break; + case "shadowResolution": + instance.shadowResolution = reader.Read(); + break; + case "shadowCustomResolution": + instance.shadowCustomResolution = reader.Read(ES3Type_int.Instance); + break; + case "shadowBias": + instance.shadowBias = reader.Read(ES3Type_float.Instance); + break; + case "shadowNormalBias": + instance.shadowNormalBias = reader.Read(ES3Type_float.Instance); + break; + case "shadowNearPlane": + instance.shadowNearPlane = reader.Read(ES3Type_float.Instance); + break; + case "range": + instance.range = reader.Read(ES3Type_float.Instance); + break; + case "spotAngle": + instance.spotAngle = reader.Read(ES3Type_float.Instance); + break; + case "cookieSize": + instance.cookieSize = reader.Read(ES3Type_float.Instance); + break; + case "cookie": + instance.cookie = reader.Read(); + break; + case "flare": + instance.flare = reader.Read(); + break; + case "renderMode": + instance.renderMode = reader.Read(); + break; + case "cullingMask": + instance.cullingMask = reader.Read(ES3Type_int.Instance); + break; + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "hideFlags": + instance.hideFlags = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Light.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Light.cs.meta new file mode 100644 index 0000000..54c6c1b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Light.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ed020448eba3f489fafcf36e1bf3b7e0 +timeCreated: 1519132300 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LightsModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LightsModule.cs new file mode 100644 index 0000000..4af8af8 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LightsModule.cs @@ -0,0 +1,94 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "ratio", "useRandomDistribution", "light", "useParticleColor", "sizeAffectsRange", "alphaAffectsIntensity", "range", "rangeMultiplier", "intensity", "intensityMultiplier", "maxLights")] + public class ES3Type_LightsModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_LightsModule() : base(typeof(UnityEngine.ParticleSystem.LightsModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.LightsModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("ratio", instance.ratio, ES3Type_float.Instance); + writer.WriteProperty("useRandomDistribution", instance.useRandomDistribution, ES3Type_bool.Instance); + writer.WritePropertyByRef("light", instance.light); + writer.WriteProperty("useParticleColor", instance.useParticleColor, ES3Type_bool.Instance); + writer.WriteProperty("sizeAffectsRange", instance.sizeAffectsRange, ES3Type_bool.Instance); + writer.WriteProperty("alphaAffectsIntensity", instance.alphaAffectsIntensity, ES3Type_bool.Instance); + writer.WriteProperty("range", instance.range, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("rangeMultiplier", instance.rangeMultiplier, ES3Type_float.Instance); + writer.WriteProperty("intensity", instance.intensity, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("intensityMultiplier", instance.intensityMultiplier, ES3Type_float.Instance); + writer.WriteProperty("maxLights", instance.maxLights, ES3Type_int.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.LightsModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.LightsModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "ratio": + instance.ratio = reader.Read(ES3Type_float.Instance); + break; + case "useRandomDistribution": + instance.useRandomDistribution = reader.Read(ES3Type_bool.Instance); + break; + case "light": + instance.light = reader.Read(ES3Type_Light.Instance); + break; + case "useParticleColor": + instance.useParticleColor = reader.Read(ES3Type_bool.Instance); + break; + case "sizeAffectsRange": + instance.sizeAffectsRange = reader.Read(ES3Type_bool.Instance); + break; + case "alphaAffectsIntensity": + instance.alphaAffectsIntensity = reader.Read(ES3Type_bool.Instance); + break; + case "range": + instance.range = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "rangeMultiplier": + instance.rangeMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "intensity": + instance.intensity = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "intensityMultiplier": + instance.intensityMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "maxLights": + instance.maxLights = reader.Read(ES3Type_int.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LightsModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LightsModule.cs.meta new file mode 100644 index 0000000..c27d822 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LightsModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: ca49590603e164a87a49d3c66013bede +timeCreated: 1519132296 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LimitVelocityOverLifetimeModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LimitVelocityOverLifetimeModule.cs new file mode 100644 index 0000000..059a9f6 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LimitVelocityOverLifetimeModule.cs @@ -0,0 +1,94 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "limitX", "limitXMultiplier", "limitY", "limitYMultiplier", "limitZ", "limitZMultiplier", "limit", "limitMultiplier", "dampen", "separateAxes", "space")] + public class ES3Type_LimitVelocityOverLifetimeModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_LimitVelocityOverLifetimeModule() : base(typeof(UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("limitX", instance.limitX, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("limitXMultiplier", instance.limitXMultiplier, ES3Type_float.Instance); + writer.WriteProperty("limitY", instance.limitY, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("limitYMultiplier", instance.limitYMultiplier, ES3Type_float.Instance); + writer.WriteProperty("limitZ", instance.limitZ, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("limitZMultiplier", instance.limitZMultiplier, ES3Type_float.Instance); + writer.WriteProperty("limit", instance.limit, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("limitMultiplier", instance.limitMultiplier, ES3Type_float.Instance); + writer.WriteProperty("dampen", instance.dampen, ES3Type_float.Instance); + writer.WriteProperty("separateAxes", instance.separateAxes, ES3Type_bool.Instance); + writer.WriteProperty("space", instance.space); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.LimitVelocityOverLifetimeModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "limitX": + instance.limitX = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "limitXMultiplier": + instance.limitXMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "limitY": + instance.limitY = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "limitYMultiplier": + instance.limitYMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "limitZ": + instance.limitZ = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "limitZMultiplier": + instance.limitZMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "limit": + instance.limit = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "limitMultiplier": + instance.limitMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "dampen": + instance.dampen = reader.Read(ES3Type_float.Instance); + break; + case "separateAxes": + instance.separateAxes = reader.Read(ES3Type_bool.Instance); + break; + case "space": + instance.space = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LimitVelocityOverLifetimeModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LimitVelocityOverLifetimeModule.cs.meta new file mode 100644 index 0000000..7dbe48e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_LimitVelocityOverLifetimeModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 1b26d58c373b9474591275b8c3b33514 +timeCreated: 1519132281 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MainModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MainModule.cs new file mode 100644 index 0000000..54cfae8 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MainModule.cs @@ -0,0 +1,206 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("duration", "loop", "prewarm", "startDelay", "startDelayMultiplier", "startLifetime", "startLifetimeMultiplier", "startSpeed", "startSpeedMultiplier", "startSize3D", "startSize", "startSizeMultiplier", "startSizeX", "startSizeXMultiplier", "startSizeY", "startSizeYMultiplier", "startSizeZ", "startSizeZMultiplier", "startRotation3D", "startRotation", "startRotationMultiplier", "startRotationX", "startRotationXMultiplier", "startRotationY", "startRotationYMultiplier", "startRotationZ", "startRotationZMultiplier", "randomizeRotationDirection", "startColor", "gravityModifier", "gravityModifierMultiplier", "simulationSpace", "customSimulationSpace", "simulationSpeed", "scalingMode", "playOnAwake", "maxParticles")] + public class ES3Type_MainModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_MainModule() : base(typeof(UnityEngine.ParticleSystem.MainModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.MainModule)obj; + + writer.WriteProperty("duration", instance.duration, ES3Type_float.Instance); + writer.WriteProperty("loop", instance.loop, ES3Type_bool.Instance); + writer.WriteProperty("prewarm", instance.prewarm, ES3Type_bool.Instance); + writer.WriteProperty("startDelay", instance.startDelay, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startDelayMultiplier", instance.startDelayMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startLifetime", instance.startLifetime, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startLifetimeMultiplier", instance.startLifetimeMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startSpeed", instance.startSpeed, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startSpeedMultiplier", instance.startSpeedMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startSize3D", instance.startSize3D, ES3Type_bool.Instance); + writer.WriteProperty("startSize", instance.startSize, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startSizeMultiplier", instance.startSizeMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startSizeX", instance.startSizeX, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startSizeXMultiplier", instance.startSizeXMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startSizeY", instance.startSizeY, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startSizeYMultiplier", instance.startSizeYMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startSizeZ", instance.startSizeZ, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startSizeZMultiplier", instance.startSizeZMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startRotation3D", instance.startRotation3D, ES3Type_bool.Instance); + writer.WriteProperty("startRotation", instance.startRotation, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startRotationMultiplier", instance.startRotationMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startRotationX", instance.startRotationX, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startRotationXMultiplier", instance.startRotationXMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startRotationY", instance.startRotationY, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startRotationYMultiplier", instance.startRotationYMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startRotationZ", instance.startRotationZ, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startRotationZMultiplier", instance.startRotationZMultiplier, ES3Type_float.Instance); + #if UNITY_2018_1_OR_NEWER + writer.WriteProperty("flipRotation", instance.flipRotation, ES3Type_float.Instance); + #else + writer.WriteProperty("randomizeRotationDirection", instance.randomizeRotationDirection, ES3Type_float.Instance); + #endif + writer.WriteProperty("startColor", instance.startColor, ES3Type_MinMaxGradient.Instance); + writer.WriteProperty("gravityModifier", instance.gravityModifier, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("gravityModifierMultiplier", instance.gravityModifierMultiplier, ES3Type_float.Instance); + writer.WriteProperty("simulationSpace", instance.simulationSpace); + writer.WritePropertyByRef("customSimulationSpace", instance.customSimulationSpace); + writer.WriteProperty("simulationSpeed", instance.simulationSpeed, ES3Type_float.Instance); + writer.WriteProperty("scalingMode", instance.scalingMode); + writer.WriteProperty("playOnAwake", instance.playOnAwake, ES3Type_bool.Instance); + writer.WriteProperty("maxParticles", instance.maxParticles, ES3Type_int.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.MainModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.MainModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + case "duration": + instance.duration = reader.Read(ES3Type_float.Instance); + break; + case "loop": + instance.loop = reader.Read(ES3Type_bool.Instance); + break; + case "prewarm": + instance.prewarm = reader.Read(ES3Type_bool.Instance); + break; + case "startDelay": + instance.startDelay = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startDelayMultiplier": + instance.startDelayMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startLifetime": + instance.startLifetime = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startLifetimeMultiplier": + instance.startLifetimeMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startSpeed": + instance.startSpeed = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startSpeedMultiplier": + instance.startSpeedMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startSize3D": + instance.startSize3D = reader.Read(ES3Type_bool.Instance); + break; + case "startSize": + instance.startSize = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startSizeMultiplier": + instance.startSizeMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startSizeX": + instance.startSizeX = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startSizeXMultiplier": + instance.startSizeXMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startSizeY": + instance.startSizeY = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startSizeYMultiplier": + instance.startSizeYMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startSizeZ": + instance.startSizeZ = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startSizeZMultiplier": + instance.startSizeZMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startRotation3D": + instance.startRotation3D = reader.Read(ES3Type_bool.Instance); + break; + case "startRotation": + instance.startRotation = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startRotationMultiplier": + instance.startRotationMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startRotationX": + instance.startRotationX = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startRotationXMultiplier": + instance.startRotationXMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startRotationY": + instance.startRotationY = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startRotationYMultiplier": + instance.startRotationYMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startRotationZ": + instance.startRotationZ = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startRotationZMultiplier": + instance.startRotationZMultiplier = reader.Read(ES3Type_float.Instance); + break; + #if UNITY_2018_1_OR_NEWER + case "flipRotation": + instance.flipRotation = reader.Read(ES3Type_float.Instance); + break; + case "randomizeRotationDirection": + instance.flipRotation = reader.Read(ES3Type_float.Instance); + break; + #else + case "randomizeRotationDirection": + instance.randomizeRotationDirection = reader.Read(ES3Type_float.Instance); + break; + #endif + case "startColor": + instance.startColor = reader.Read(ES3Type_MinMaxGradient.Instance); + break; + case "gravityModifier": + instance.gravityModifier = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "gravityModifierMultiplier": + instance.gravityModifierMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "simulationSpace": + instance.simulationSpace = reader.Read(); + break; + case "customSimulationSpace": + instance.customSimulationSpace = reader.Read(ES3Type_Transform.Instance); + break; + case "simulationSpeed": + instance.simulationSpeed = reader.Read(ES3Type_float.Instance); + break; + case "scalingMode": + instance.scalingMode = reader.Read(); + break; + case "playOnAwake": + instance.playOnAwake = reader.Read(ES3Type_bool.Instance); + break; + case "maxParticles": + instance.maxParticles = reader.Read(ES3Type_int.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MainModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MainModule.cs.meta new file mode 100644 index 0000000..945d296 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MainModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 55fa2d96d06d64809ad226f1874be169 +timeCreated: 1519132285 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Material.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Material.cs new file mode 100644 index 0000000..e31c703 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Material.cs @@ -0,0 +1,1304 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("shader", "renderQueue", "shaderKeywords", "globalIlluminationFlags", "properties")] + public class ES3Type_Material : ES3UnityObjectType + { + public static ES3Type Instance = null; + + public ES3Type_Material() : base(typeof(UnityEngine.Material)){ Instance = this; } + + protected override void WriteUnityObject(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Material)obj; + + // Uncomment if you want "instance" to be removed from the name. + //instance.name = instance.name.Replace(" (Instance)", ""); + + writer.WriteProperty("name", instance.name); + writer.WriteProperty("shader", instance.shader); + writer.WriteProperty("renderQueue", instance.renderQueue, ES3Type_int.Instance); + writer.WriteProperty("shaderKeywords", instance.shaderKeywords); + writer.WriteProperty("globalIlluminationFlags", instance.globalIlluminationFlags); + + var shader = instance.shader; + + if (shader != null) + { +#if UNITY_2019_3_OR_NEWER + for (int i = 0; i < shader.GetPropertyCount(); i++) + { + var name = shader.GetPropertyName(i); + + switch (shader.GetPropertyType(i)) + { + case UnityEngine.Rendering.ShaderPropertyType.Color: + writer.WriteProperty(name, instance.GetColor(name)); + break; + case UnityEngine.Rendering.ShaderPropertyType.Float: + case UnityEngine.Rendering.ShaderPropertyType.Range: + writer.WriteProperty(name, instance.GetFloat(name)); + break; + case UnityEngine.Rendering.ShaderPropertyType.Texture: + var texture = instance.GetTexture(name); + + if (texture != null && texture.GetType() != typeof(Texture2D)) + { + ES3Internal.ES3Debug.LogWarning($"The texture '{name}' of Material '{instance.name}' will not be saved as only Textures of type Texture2D can be saved at runtime, whereas '{name}' is of type '{texture.GetType()}'."); + break; + } + writer.WriteProperty(name, texture); + writer.WriteProperty(name + "_TextureOffset", instance.GetTextureOffset(name)); + writer.WriteProperty(name + "_TextureScale", instance.GetTextureScale(name)); + break; + case UnityEngine.Rendering.ShaderPropertyType.Vector: + writer.WriteProperty(name, instance.GetVector(name)); + break; + } + } + +#else + + if(instance.HasProperty("_Color")) + writer.WriteProperty("_Color", instance.GetColor("_Color")); + if(instance.HasProperty("_SpecColor")) + writer.WriteProperty("_SpecColor", instance.GetColor("_SpecColor")); + if(instance.HasProperty("_Shininess")) + writer.WriteProperty("_Shininess", instance.GetFloat("_Shininess")); + if(instance.HasProperty("_MainTex")) + { + writer.WriteProperty("_MainTex", instance.GetTexture("_MainTex")); + writer.WriteProperty("_MainTex_Scale", instance.GetTextureScale("_MainTex")); + } + if(instance.HasProperty("_MainTex_TextureOffset")) + writer.WriteProperty("_MainTex_TextureOffset", instance.GetTextureOffset("_MainTex_TextureOffset")); + if(instance.HasProperty("_MainTex_TextureScale")) + writer.WriteProperty("_MainTex_TextureScale", instance.GetTextureScale("_MainTex_TextureScale")); + if(instance.HasProperty("_Illum")) + writer.WriteProperty("_Illum", instance.GetTexture("_Illum")); + if(instance.HasProperty("_Illum_TextureOffset")) + writer.WriteProperty("_Illum_TextureOffset", instance.GetTextureOffset("_Illum_TextureOffset")); + if(instance.HasProperty("_Illum_TextureScale")) + writer.WriteProperty("_Illum_TextureScale", instance.GetTextureScale("_Illum_TextureScale")); + if(instance.HasProperty("_BumpMap")) + writer.WriteProperty("_BumpMap", instance.GetTexture("_BumpMap")); + if(instance.HasProperty("_BumpMap_TextureOffset")) + writer.WriteProperty("_BumpMap_TextureOffset", instance.GetTextureOffset("_BumpMap_TextureOffset")); + if(instance.HasProperty("_BumpMap_TextureScale")) + writer.WriteProperty("_BumpMap_TextureScale", instance.GetTextureScale("_BumpMap_TextureScale")); + if(instance.HasProperty("_Emission")) + writer.WriteProperty("_Emission", instance.GetFloat("_Emission")); + if(instance.HasProperty("_Specular")) + writer.WriteProperty("_Specular", instance.GetColor("_Specular")); + if(instance.HasProperty("_MainBump")) + writer.WriteProperty("_MainBump", instance.GetTexture("_MainBump")); + if(instance.HasProperty("_MainBump_TextureOffset")) + writer.WriteProperty("_MainBump_TextureOffset", instance.GetTextureOffset("_MainBump_TextureOffset")); + if(instance.HasProperty("_MainBump_TextureScale")) + writer.WriteProperty("_MainBump_TextureScale", instance.GetTextureScale("_MainBump_TextureScale")); + if(instance.HasProperty("_Mask")) + writer.WriteProperty("_Mask", instance.GetTexture("_Mask")); + if(instance.HasProperty("_Mask_TextureOffset")) + writer.WriteProperty("_Mask_TextureOffset", instance.GetTextureOffset("_Mask_TextureOffset")); + if(instance.HasProperty("_Mask_TextureScale")) + writer.WriteProperty("_Mask_TextureScale", instance.GetTextureScale("_Mask_TextureScale")); + if(instance.HasProperty("_Focus")) + writer.WriteProperty("_Focus", instance.GetFloat("_Focus")); + if(instance.HasProperty("_StencilComp")) + writer.WriteProperty("_StencilComp", instance.GetFloat("_StencilComp")); + if(instance.HasProperty("_Stencil")) + writer.WriteProperty("_Stencil", instance.GetFloat("_Stencil")); + if(instance.HasProperty("_StencilOp")) + writer.WriteProperty("_StencilOp", instance.GetFloat("_StencilOp")); + if(instance.HasProperty("_StencilWriteMask")) + writer.WriteProperty("_StencilWriteMask", instance.GetFloat("_StencilWriteMask")); + if(instance.HasProperty("_StencilReadMask")) + writer.WriteProperty("_StencilReadMask", instance.GetFloat("_StencilReadMask")); + if(instance.HasProperty("_ColorMask")) + writer.WriteProperty("_ColorMask", instance.GetFloat("_ColorMask")); + if(instance.HasProperty("_UseUIAlphaClip")) + writer.WriteProperty("_UseUIAlphaClip", instance.GetFloat("_UseUIAlphaClip")); + if(instance.HasProperty("_SrcBlend")) + writer.WriteProperty("_SrcBlend", instance.GetFloat("_SrcBlend")); + if(instance.HasProperty("_DstBlend")) + writer.WriteProperty("_DstBlend", instance.GetFloat("_DstBlend")); + if(instance.HasProperty("_ReflectColor")) + writer.WriteProperty("_ReflectColor", instance.GetColor("_ReflectColor")); + if(instance.HasProperty("_Cube")) + writer.WriteProperty("_Cube", instance.GetTexture("_Cube")); + if(instance.HasProperty("_Cube_TextureOffset")) + writer.WriteProperty("_Cube_TextureOffset", instance.GetTextureOffset("_Cube_TextureOffset")); + if(instance.HasProperty("_Cube_TextureScale")) + writer.WriteProperty("_Cube_TextureScale", instance.GetTextureScale("_Cube_TextureScale")); + if(instance.HasProperty("_Tint")) + writer.WriteProperty("_Tint", instance.GetColor("_Tint")); + if(instance.HasProperty("_Exposure")) + writer.WriteProperty("_Exposure", instance.GetFloat("_Exposure")); + if(instance.HasProperty("_Rotation")) + writer.WriteProperty("_Rotation", instance.GetFloat("_Rotation")); + if(instance.HasProperty("_Tex")) + writer.WriteProperty("_Tex", instance.GetTexture("_Tex")); + if(instance.HasProperty("_Tex_TextureOffset")) + writer.WriteProperty("_Tex_TextureOffset", instance.GetTextureOffset("_Tex_TextureOffset")); + if(instance.HasProperty("_Tex_TextureScale")) + writer.WriteProperty("_Tex_TextureScale", instance.GetTextureScale("_Tex_TextureScale")); + if(instance.HasProperty("_Control")) + writer.WriteProperty("_Control", instance.GetTexture("_Control")); + if(instance.HasProperty("_Control_TextureOffset")) + writer.WriteProperty("_Control_TextureOffset", instance.GetTextureOffset("_Control_TextureOffset")); + if(instance.HasProperty("_Control_TextureScale")) + writer.WriteProperty("_Control_TextureScale", instance.GetTextureScale("_Control_TextureScale")); + if(instance.HasProperty("_Splat3")) + writer.WriteProperty("_Splat3", instance.GetTexture("_Splat3")); + if(instance.HasProperty("_Splat3_TextureOffset")) + writer.WriteProperty("_Splat3_TextureOffset", instance.GetTextureOffset("_Splat3_TextureOffset")); + if(instance.HasProperty("_Splat3_TextureScale")) + writer.WriteProperty("_Splat3_TextureScale", instance.GetTextureScale("_Splat3_TextureScale")); + if(instance.HasProperty("_Splat2")) + writer.WriteProperty("_Splat2", instance.GetTexture("_Splat2")); + if(instance.HasProperty("_Splat2_TextureOffset")) + writer.WriteProperty("_Splat2_TextureOffset", instance.GetTextureOffset("_Splat2_TextureOffset")); + if(instance.HasProperty("_Splat2_TextureScale")) + writer.WriteProperty("_Splat2_TextureScale", instance.GetTextureScale("_Splat2_TextureScale")); + if(instance.HasProperty("_Splat1")) + writer.WriteProperty("_Splat1", instance.GetTexture("_Splat1")); + if(instance.HasProperty("_Splat1_TextureOffset")) + writer.WriteProperty("_Splat1_TextureOffset", instance.GetTextureOffset("_Splat1_TextureOffset")); + if(instance.HasProperty("_Splat1_TextureScale")) + writer.WriteProperty("_Splat1_TextureScale", instance.GetTextureScale("_Splat1_TextureScale")); + if(instance.HasProperty("_Splat0")) + writer.WriteProperty("_Splat0", instance.GetTexture("_Splat0")); + if(instance.HasProperty("_Splat0_TextureOffset")) + writer.WriteProperty("_Splat0_TextureOffset", instance.GetTextureOffset("_Splat0_TextureOffset")); + if(instance.HasProperty("_Splat0_TextureScale")) + writer.WriteProperty("_Splat0_TextureScale", instance.GetTextureScale("_Splat0_TextureScale")); + if(instance.HasProperty("_Normal3")) + writer.WriteProperty("_Normal3", instance.GetTexture("_Normal3")); + if(instance.HasProperty("_Normal3_TextureOffset")) + writer.WriteProperty("_Normal3_TextureOffset", instance.GetTextureOffset("_Normal3_TextureOffset")); + if(instance.HasProperty("_Normal3_TextureScale")) + writer.WriteProperty("_Normal3_TextureScale", instance.GetTextureScale("_Normal3_TextureScale")); + if(instance.HasProperty("_Normal2")) + writer.WriteProperty("_Normal2", instance.GetTexture("_Normal2")); + if(instance.HasProperty("_Normal2_TextureOffset")) + writer.WriteProperty("_Normal2_TextureOffset", instance.GetTextureOffset("_Normal2_TextureOffset")); + if(instance.HasProperty("_Normal2_TextureScale")) + writer.WriteProperty("_Normal2_TextureScale", instance.GetTextureScale("_Normal2_TextureScale")); + if(instance.HasProperty("_Normal1")) + writer.WriteProperty("_Normal1", instance.GetTexture("_Normal1")); + if(instance.HasProperty("_Normal1_TextureOffset")) + writer.WriteProperty("_Normal1_TextureOffset", instance.GetTextureOffset("_Normal1_TextureOffset")); + if(instance.HasProperty("_Normal1_TextureScale")) + writer.WriteProperty("_Normal1_TextureScale", instance.GetTextureScale("_Normal1_TextureScale")); + if(instance.HasProperty("_Normal0")) + writer.WriteProperty("_Normal0", instance.GetTexture("_Normal0")); + if(instance.HasProperty("_Normal0_TextureOffset")) + writer.WriteProperty("_Normal0_TextureOffset", instance.GetTextureOffset("_Normal0_TextureOffset")); + if(instance.HasProperty("_Normal0_TextureScale")) + writer.WriteProperty("_Normal0_TextureScale", instance.GetTextureScale("_Normal0_TextureScale")); + if(instance.HasProperty("_Cutoff")) + writer.WriteProperty("_Cutoff", instance.GetFloat("_Cutoff")); + if(instance.HasProperty("_BaseLight")) + writer.WriteProperty("_BaseLight", instance.GetFloat("_BaseLight")); + if(instance.HasProperty("_AO")) + writer.WriteProperty("_AO", instance.GetFloat("_AO")); + if(instance.HasProperty("_Occlusion")) + writer.WriteProperty("_Occlusion", instance.GetFloat("_Occlusion")); + if(instance.HasProperty("_TreeInstanceColor")) + writer.WriteProperty("_TreeInstanceColor", instance.GetVector("_TreeInstanceColor")); + if(instance.HasProperty("_TreeInstanceScale")) + writer.WriteProperty("_TreeInstanceScale", instance.GetVector("_TreeInstanceScale")); + if(instance.HasProperty("_SquashAmount")) + writer.WriteProperty("_SquashAmount", instance.GetFloat("_SquashAmount")); + if(instance.HasProperty("_TranslucencyColor")) + writer.WriteProperty("_TranslucencyColor", instance.GetColor("_TranslucencyColor")); + if(instance.HasProperty("_TranslucencyViewDependency")) + writer.WriteProperty("_TranslucencyViewDependency", instance.GetFloat("_TranslucencyViewDependency")); + if(instance.HasProperty("_ShadowStrength")) + writer.WriteProperty("_ShadowStrength", instance.GetFloat("_ShadowStrength")); + if(instance.HasProperty("_ShadowOffsetScale")) + writer.WriteProperty("_ShadowOffsetScale", instance.GetFloat("_ShadowOffsetScale")); + if(instance.HasProperty("_ShadowTex")) + writer.WriteProperty("_ShadowTex", instance.GetTexture("_ShadowTex")); + if(instance.HasProperty("_ShadowTex_TextureOffset")) + writer.WriteProperty("_ShadowTex_TextureOffset", instance.GetTextureOffset("_ShadowTex_TextureOffset")); + if(instance.HasProperty("_ShadowTex_TextureScale")) + writer.WriteProperty("_ShadowTex_TextureScale", instance.GetTextureScale("_ShadowTex_TextureScale")); + if(instance.HasProperty("_BumpSpecMap")) + writer.WriteProperty("_BumpSpecMap", instance.GetTexture("_BumpSpecMap")); + if(instance.HasProperty("_BumpSpecMap_TextureOffset")) + writer.WriteProperty("_BumpSpecMap_TextureOffset", instance.GetTextureOffset("_BumpSpecMap_TextureOffset")); + if(instance.HasProperty("_BumpSpecMap_TextureScale")) + writer.WriteProperty("_BumpSpecMap_TextureScale", instance.GetTextureScale("_BumpSpecMap_TextureScale")); + if(instance.HasProperty("_TranslucencyMap")) + writer.WriteProperty("_TranslucencyMap", instance.GetTexture("_TranslucencyMap")); + if(instance.HasProperty("_TranslucencyMap_TextureOffset")) + writer.WriteProperty("_TranslucencyMap_TextureOffset", instance.GetTextureOffset("_TranslucencyMap_TextureOffset")); + if(instance.HasProperty("_TranslucencyMap_TextureScale")) + writer.WriteProperty("_TranslucencyMap_TextureScale", instance.GetTextureScale("_TranslucencyMap_TextureScale")); + if(instance.HasProperty("_LightMap")) + writer.WriteProperty("_LightMap", instance.GetTexture("_LightMap")); + if(instance.HasProperty("_LightMap_TextureOffset")) + writer.WriteProperty("_LightMap_TextureOffset", instance.GetTextureOffset("_LightMap_TextureOffset")); + if(instance.HasProperty("_LightMap_TextureScale")) + writer.WriteProperty("_LightMap_TextureScale", instance.GetTextureScale("_LightMap_TextureScale")); + if(instance.HasProperty("_DetailTex")) + writer.WriteProperty("_DetailTex", instance.GetTexture("_DetailTex")); + if(instance.HasProperty("_DetailTex_TextureOffset")) + writer.WriteProperty("_DetailTex_TextureOffset", instance.GetTextureOffset("_DetailTex_TextureOffset")); + if(instance.HasProperty("_DetailTex_TextureScale")) + writer.WriteProperty("_DetailTex_TextureScale", instance.GetTextureScale("_DetailTex_TextureScale")); + if(instance.HasProperty("_DetailBump")) + writer.WriteProperty("_DetailBump", instance.GetTexture("_DetailBump")); + if(instance.HasProperty("_DetailBump_TextureOffset")) + writer.WriteProperty("_DetailBump_TextureOffset", instance.GetTextureOffset("_DetailBump_TextureOffset")); + if(instance.HasProperty("_DetailBump_TextureScale")) + writer.WriteProperty("_DetailBump_TextureScale", instance.GetTextureScale("_DetailBump_TextureScale")); + if(instance.HasProperty("_Strength")) + writer.WriteProperty("_Strength", instance.GetFloat("_Strength")); + if(instance.HasProperty("_InvFade")) + writer.WriteProperty("_InvFade", instance.GetFloat("_InvFade")); + if(instance.HasProperty("_EmisColor")) + writer.WriteProperty("_EmisColor", instance.GetColor("_EmisColor")); + if(instance.HasProperty("_Parallax")) + writer.WriteProperty("_Parallax", instance.GetFloat("_Parallax")); + if(instance.HasProperty("_ParallaxMap")) + writer.WriteProperty("_ParallaxMap", instance.GetTexture("_ParallaxMap")); + if(instance.HasProperty("_ParallaxMap_TextureOffset")) + writer.WriteProperty("_ParallaxMap_TextureOffset", instance.GetTextureOffset("_ParallaxMap_TextureOffset")); + if(instance.HasProperty("_ParallaxMap_TextureScale")) + writer.WriteProperty("_ParallaxMap_TextureScale", instance.GetTextureScale("_ParallaxMap_TextureScale")); + if(instance.HasProperty("_DecalTex")) + writer.WriteProperty("_DecalTex", instance.GetTexture("_DecalTex")); + if(instance.HasProperty("_DecalTex_TextureOffset")) + writer.WriteProperty("_DecalTex_TextureOffset", instance.GetTextureOffset("_DecalTex_TextureOffset")); + if(instance.HasProperty("_DecalTex_TextureScale")) + writer.WriteProperty("_DecalTex_TextureScale", instance.GetTextureScale("_DecalTex_TextureScale")); + if(instance.HasProperty("_GlossMap")) + writer.WriteProperty("_GlossMap", instance.GetTexture("_GlossMap")); + if(instance.HasProperty("_GlossMap_TextureOffset")) + writer.WriteProperty("_GlossMap_TextureOffset", instance.GetTextureOffset("_GlossMap_TextureOffset")); + if(instance.HasProperty("_GlossMap_TextureScale")) + writer.WriteProperty("_GlossMap_TextureScale", instance.GetTextureScale("_GlossMap_TextureScale")); + if(instance.HasProperty("_ShadowOffset")) + writer.WriteProperty("_ShadowOffset", instance.GetTexture("_ShadowOffset")); + if(instance.HasProperty("_ShadowOffset_TextureOffset")) + writer.WriteProperty("_ShadowOffset_TextureOffset", instance.GetTextureOffset("_ShadowOffset_TextureOffset")); + if(instance.HasProperty("_ShadowOffset_TextureScale")) + writer.WriteProperty("_ShadowOffset_TextureScale", instance.GetTextureScale("_ShadowOffset_TextureScale")); + if(instance.HasProperty("_SunDisk")) + writer.WriteProperty("_SunDisk", instance.GetFloat("_SunDisk")); + if(instance.HasProperty("_SunSize")) + writer.WriteProperty("_SunSize", instance.GetFloat("_SunSize")); + if(instance.HasProperty("_AtmosphereThickness")) + writer.WriteProperty("_AtmosphereThickness", instance.GetFloat("_AtmosphereThickness")); + if(instance.HasProperty("_SkyTint")) + writer.WriteProperty("_SkyTint", instance.GetColor("_SkyTint")); + if(instance.HasProperty("_GroundColor")) + writer.WriteProperty("_GroundColor", instance.GetColor("_GroundColor")); + if(instance.HasProperty("_WireThickness")) + writer.WriteProperty("_WireThickness", instance.GetFloat("_WireThickness")); + if(instance.HasProperty("_ZWrite")) + writer.WriteProperty("_ZWrite", instance.GetFloat("_ZWrite")); + if(instance.HasProperty("_ZTest")) + writer.WriteProperty("_ZTest", instance.GetFloat("_ZTest")); + if(instance.HasProperty("_Cull")) + writer.WriteProperty("_Cull", instance.GetFloat("_Cull")); + if(instance.HasProperty("_ZBias")) + writer.WriteProperty("_ZBias", instance.GetFloat("_ZBias")); + if(instance.HasProperty("_HueVariation")) + writer.WriteProperty("_HueVariation", instance.GetColor("_HueVariation")); + if(instance.HasProperty("_WindQuality")) + writer.WriteProperty("_WindQuality", instance.GetFloat("_WindQuality")); + if(instance.HasProperty("_DetailMask")) + writer.WriteProperty("_DetailMask", instance.GetTexture("_DetailMask")); + if(instance.HasProperty("_DetailMask_TextureOffset")) + writer.WriteProperty("_DetailMask_TextureOffset", instance.GetTextureOffset("_DetailMask_TextureOffset")); + if(instance.HasProperty("_DetailMask_TextureScale")) + writer.WriteProperty("_DetailMask_TextureScale", instance.GetTextureScale("_DetailMask_TextureScale")); + if(instance.HasProperty("_MetallicTex")) + writer.WriteProperty("_MetallicTex", instance.GetTexture("_MetallicTex")); + if(instance.HasProperty("_MetallicTex_TextureOffset")) + writer.WriteProperty("_MetallicTex_TextureOffset", instance.GetTextureOffset("_MetallicTex_TextureOffset")); + if(instance.HasProperty("_MetallicTex_TextureScale")) + writer.WriteProperty("_MetallicTex_TextureScale", instance.GetTextureScale("_MetallicTex_TextureScale")); + if(instance.HasProperty("_Glossiness")) + writer.WriteProperty("_Glossiness", instance.GetFloat("_Glossiness")); + if(instance.HasProperty("_GlossMapScale")) + writer.WriteProperty("_GlossMapScale", instance.GetFloat("_GlossMapScale")); + if(instance.HasProperty("_SmoothnessTextureChannel")) + writer.WriteProperty("_SmoothnessTextureChannel", instance.GetFloat("_SmoothnessTextureChannel")); + if(instance.HasProperty("_Metallic")) + writer.WriteProperty("_Metallic", instance.GetFloat("_Metallic")); + if(instance.HasProperty("_MetallicGlossMap")) + writer.WriteProperty("_MetallicGlossMap", instance.GetTexture("_MetallicGlossMap")); + if(instance.HasProperty("_MetallicGlossMap_TextureOffset")) + writer.WriteProperty("_MetallicGlossMap_TextureOffset", instance.GetTextureOffset("_MetallicGlossMap_TextureOffset")); + if(instance.HasProperty("_MetallicGlossMap_TextureScale")) + writer.WriteProperty("_MetallicGlossMap_TextureScale", instance.GetTextureScale("_MetallicGlossMap_TextureScale")); + if(instance.HasProperty("_SpecularHighlights")) + writer.WriteProperty("_SpecularHighlights", instance.GetFloat("_SpecularHighlights")); + if(instance.HasProperty("_GlossyReflections")) + writer.WriteProperty("_GlossyReflections", instance.GetFloat("_GlossyReflections")); + if(instance.HasProperty("_BumpScale")) + writer.WriteProperty("_BumpScale", instance.GetFloat("_BumpScale")); + if(instance.HasProperty("_OcclusionStrength")) + writer.WriteProperty("_OcclusionStrength", instance.GetFloat("_OcclusionStrength")); + if(instance.HasProperty("_OcclusionMap")) + writer.WriteProperty("_OcclusionMap", instance.GetTexture("_OcclusionMap")); + if(instance.HasProperty("_OcclusionMap_TextureOffset")) + writer.WriteProperty("_OcclusionMap_TextureOffset", instance.GetTextureOffset("_OcclusionMap_TextureOffset")); + if(instance.HasProperty("_OcclusionMap_TextureScale")) + writer.WriteProperty("_OcclusionMap_TextureScale", instance.GetTextureScale("_OcclusionMap_TextureScale")); + if(instance.HasProperty("_EmissionColor")) + writer.WriteProperty("_EmissionColor", instance.GetColor("_EmissionColor")); + if(instance.HasProperty("_EmissionMap")) + writer.WriteProperty("_EmissionMap", instance.GetTexture("_EmissionMap")); + if(instance.HasProperty("_EmissionMap_TextureOffset")) + writer.WriteProperty("_EmissionMap_TextureOffset", instance.GetTextureOffset("_EmissionMap_TextureOffset")); + if(instance.HasProperty("_EmissionMap_TextureScale")) + writer.WriteProperty("_EmissionMap_TextureScale", instance.GetTextureScale("_EmissionMap_TextureScale")); + if(instance.HasProperty("_DetailAlbedoMap")) + writer.WriteProperty("_DetailAlbedoMap", instance.GetTexture("_DetailAlbedoMap")); + if(instance.HasProperty("_DetailAlbedoMap_TextureOffset")) + writer.WriteProperty("_DetailAlbedoMap_TextureOffset", instance.GetTextureOffset("_DetailAlbedoMap_TextureOffset")); + if(instance.HasProperty("_DetailAlbedoMap_TextureScale")) + writer.WriteProperty("_DetailAlbedoMap_TextureScale", instance.GetTextureScale("_DetailAlbedoMap_TextureScale")); + if(instance.HasProperty("_DetailNormalMapScale")) + writer.WriteProperty("_DetailNormalMapScale", instance.GetFloat("_DetailNormalMapScale")); + if(instance.HasProperty("_DetailNormalMap")) + writer.WriteProperty("_DetailNormalMap", instance.GetTexture("_DetailNormalMap")); + if(instance.HasProperty("_DetailNormalMap_TextureOffset")) + writer.WriteProperty("_DetailNormalMap_TextureOffset", instance.GetTextureOffset("_DetailNormalMap_TextureOffset")); + if(instance.HasProperty("_DetailNormalMap_TextureScale")) + writer.WriteProperty("_DetailNormalMap_TextureScale", instance.GetTextureScale("_DetailNormalMap_TextureScale")); + if(instance.HasProperty("_UVSec")) + writer.WriteProperty("_UVSec", instance.GetFloat("_UVSec")); + if(instance.HasProperty("_Mode")) + writer.WriteProperty("_Mode", instance.GetFloat("_Mode")); + if(instance.HasProperty("_TintColor")) + writer.WriteProperty("_TintColor", instance.GetColor("_TintColor")); + if(instance.HasProperty("_WavingTint")) + writer.WriteProperty("_WavingTint", instance.GetColor("_WavingTint")); + if(instance.HasProperty("_WaveAndDistance")) + writer.WriteProperty("_WaveAndDistance", instance.GetVector("_WaveAndDistance")); + if(instance.HasProperty("_LightTexture0")) + writer.WriteProperty("_LightTexture0", instance.GetTexture("_LightTexture0")); + if(instance.HasProperty("_LightTexture0_TextureOffset")) + writer.WriteProperty("_LightTexture0_TextureOffset", instance.GetTextureOffset("_LightTexture0_TextureOffset")); + if(instance.HasProperty("_LightTexture0_TextureScale")) + writer.WriteProperty("_LightTexture0_TextureScale", instance.GetTextureScale("_LightTexture0_TextureScale")); + if(instance.HasProperty("_LightTextureB0")) + writer.WriteProperty("_LightTextureB0", instance.GetTexture("_LightTextureB0")); + if(instance.HasProperty("_LightTextureB0_TextureOffset")) + writer.WriteProperty("_LightTextureB0_TextureOffset", instance.GetTextureOffset("_LightTextureB0_TextureOffset")); + if(instance.HasProperty("_LightTextureB0_TextureScale")) + writer.WriteProperty("_LightTextureB0_TextureScale", instance.GetTextureScale("_LightTextureB0_TextureScale")); + if(instance.HasProperty("_ShadowMapTexture")) + writer.WriteProperty("_ShadowMapTexture", instance.GetTexture("_ShadowMapTexture")); + if(instance.HasProperty("_ShadowMapTexture_TextureOffset")) + writer.WriteProperty("_ShadowMapTexture_TextureOffset", instance.GetTextureOffset("_ShadowMapTexture_TextureOffset")); + if(instance.HasProperty("_ShadowMapTexture_TextureScale")) + writer.WriteProperty("_ShadowMapTexture_TextureScale", instance.GetTextureScale("_ShadowMapTexture_TextureScale")); + if(instance.HasProperty("_SecondTex")) + writer.WriteProperty("_SecondTex", instance.GetTexture("_SecondTex")); + if(instance.HasProperty("_SecondTex_TextureOffset")) + writer.WriteProperty("_SecondTex_TextureOffset", instance.GetTextureOffset("_SecondTex_TextureOffset")); + if(instance.HasProperty("_SecondTex_TextureScale")) + writer.WriteProperty("_SecondTex_TextureScale", instance.GetTextureScale("_SecondTex_TextureScale")); + if(instance.HasProperty("_ThirdTex")) + writer.WriteProperty("_ThirdTex", instance.GetTexture("_ThirdTex")); + if(instance.HasProperty("_ThirdTex_TextureOffset")) + writer.WriteProperty("_ThirdTex_TextureOffset", instance.GetTextureOffset("_ThirdTex_TextureOffset")); + if(instance.HasProperty("_ThirdTex_TextureScale")) + writer.WriteProperty("_ThirdTex_TextureScale", instance.GetTextureScale("_ThirdTex_TextureScale")); + if(instance.HasProperty("PixelSnap")) + writer.WriteProperty("PixelSnap", instance.GetFloat("PixelSnap")); + if(instance.HasProperty("_RendererColor")) + writer.WriteProperty("_RendererColor", instance.GetColor("_RendererColor")); + if(instance.HasProperty("_Flip")) + writer.WriteProperty("_Flip", instance.GetVector("_Flip")); + if(instance.HasProperty("_AlphaTex")) + writer.WriteProperty("_AlphaTex", instance.GetTexture("_AlphaTex")); + if(instance.HasProperty("_AlphaTex_TextureOffset")) + writer.WriteProperty("_AlphaTex_TextureOffset", instance.GetTextureOffset("_AlphaTex_TextureOffset")); + if(instance.HasProperty("_AlphaTex_TextureScale")) + writer.WriteProperty("_AlphaTex_TextureScale", instance.GetTextureScale("_AlphaTex_TextureScale")); + if(instance.HasProperty("_EnableExternalAlpha")) + writer.WriteProperty("_EnableExternalAlpha", instance.GetFloat("_EnableExternalAlpha")); + if(instance.HasProperty("_Level")) + writer.WriteProperty("_Level", instance.GetFloat("_Level")); + if(instance.HasProperty("_SpecGlossMap")) + writer.WriteProperty("_SpecGlossMap", instance.GetTexture("_SpecGlossMap")); + if(instance.HasProperty("_SpecGlossMap_TextureOffset")) + writer.WriteProperty("_SpecGlossMap_TextureOffset", instance.GetTextureOffset("_SpecGlossMap_TextureOffset")); + if(instance.HasProperty("_SpecGlossMap_TextureScale")) + writer.WriteProperty("_SpecGlossMap_TextureScale", instance.GetTextureScale("_SpecGlossMap_TextureScale")); + if(instance.HasProperty("_FrontTex")) + writer.WriteProperty("_FrontTex", instance.GetTexture("_FrontTex")); + if(instance.HasProperty("_FrontTex_TextureOffset")) + writer.WriteProperty("_FrontTex_TextureOffset", instance.GetTextureOffset("_FrontTex_TextureOffset")); + if(instance.HasProperty("_FrontTex_TextureScale")) + writer.WriteProperty("_FrontTex_TextureScale", instance.GetTextureScale("_FrontTex_TextureScale")); + if(instance.HasProperty("_BackTex")) + writer.WriteProperty("_BackTex", instance.GetTexture("_BackTex")); + if(instance.HasProperty("_BackTex_TextureOffset")) + writer.WriteProperty("_BackTex_TextureOffset", instance.GetTextureOffset("_BackTex_TextureOffset")); + if(instance.HasProperty("_BackTex_TextureScale")) + writer.WriteProperty("_BackTex_TextureScale", instance.GetTextureScale("_BackTex_TextureScale")); + if(instance.HasProperty("_LeftTex")) + writer.WriteProperty("_LeftTex", instance.GetTexture("_LeftTex")); + if(instance.HasProperty("_LeftTex_TextureOffset")) + writer.WriteProperty("_LeftTex_TextureOffset", instance.GetTextureOffset("_LeftTex_TextureOffset")); + if(instance.HasProperty("_LeftTex_TextureScale")) + writer.WriteProperty("_LeftTex_TextureScale", instance.GetTextureScale("_LeftTex_TextureScale")); + if(instance.HasProperty("_RightTex")) + writer.WriteProperty("_RightTex", instance.GetTexture("_RightTex")); + if(instance.HasProperty("_RightTex_TextureOffset")) + writer.WriteProperty("_RightTex_TextureOffset", instance.GetTextureOffset("_RightTex_TextureOffset")); + if(instance.HasProperty("_RightTex_TextureScale")) + writer.WriteProperty("_RightTex_TextureScale", instance.GetTextureScale("_RightTex_TextureScale")); + if(instance.HasProperty("_UpTex")) + writer.WriteProperty("_UpTex", instance.GetTexture("_UpTex")); + if(instance.HasProperty("_UpTex_TextureOffset")) + writer.WriteProperty("_UpTex_TextureOffset", instance.GetTextureOffset("_UpTex_TextureOffset")); + if(instance.HasProperty("_UpTex_TextureScale")) + writer.WriteProperty("_UpTex_TextureScale", instance.GetTextureScale("_UpTex_TextureScale")); + if(instance.HasProperty("_DownTex")) + writer.WriteProperty("_DownTex", instance.GetTexture("_DownTex")); + if(instance.HasProperty("_DownTex_TextureOffset")) + writer.WriteProperty("_DownTex_TextureOffset", instance.GetTextureOffset("_DownTex_TextureOffset")); + if(instance.HasProperty("_DownTex_TextureScale")) + writer.WriteProperty("_DownTex_TextureScale", instance.GetTextureScale("_DownTex_TextureScale")); + if(instance.HasProperty("_Metallic0")) + writer.WriteProperty("_Metallic0", instance.GetFloat("_Metallic0")); + if(instance.HasProperty("_Metallic1")) + writer.WriteProperty("_Metallic1", instance.GetFloat("_Metallic1")); + if(instance.HasProperty("_Metallic2")) + writer.WriteProperty("_Metallic2", instance.GetFloat("_Metallic2")); + if(instance.HasProperty("_Metallic3")) + writer.WriteProperty("_Metallic3", instance.GetFloat("_Metallic3")); + if(instance.HasProperty("_Smoothness0")) + writer.WriteProperty("_Smoothness0", instance.GetFloat("_Smoothness0")); + if(instance.HasProperty("_Smoothness1")) + writer.WriteProperty("_Smoothness1", instance.GetFloat("_Smoothness1")); + if(instance.HasProperty("_Smoothness2")) + writer.WriteProperty("_Smoothness2", instance.GetFloat("_Smoothness2")); + if(instance.HasProperty("_Smoothness3")) + writer.WriteProperty("_Smoothness3", instance.GetFloat("_Smoothness3")); + if(instance.HasProperty("_TexA")) + writer.WriteProperty("_TexA", instance.GetTexture("_TexA")); + if(instance.HasProperty("_TexA_TextureOffset")) + writer.WriteProperty("_TexA_TextureOffset", instance.GetTextureOffset("_TexA_TextureOffset")); + if(instance.HasProperty("_TexA_TextureScale")) + writer.WriteProperty("_TexA_TextureScale", instance.GetTextureScale("_TexA_TextureScale")); + if(instance.HasProperty("_TexB")) + writer.WriteProperty("_TexB", instance.GetTexture("_TexB")); + if(instance.HasProperty("_TexB_TextureOffset")) + writer.WriteProperty("_TexB_TextureOffset", instance.GetTextureOffset("_TexB_TextureOffset")); + if(instance.HasProperty("_TexB_TextureScale")) + writer.WriteProperty("_TexB_TextureScale", instance.GetTextureScale("_TexB_TextureScale")); + if(instance.HasProperty("_value")) + writer.WriteProperty("_value", instance.GetFloat("_value")); + if(instance.HasProperty("_Texel")) + writer.WriteProperty("_Texel", instance.GetFloat("_Texel")); + if(instance.HasProperty("_Detail")) + writer.WriteProperty("_Detail", instance.GetTexture("_Detail")); + if(instance.HasProperty("_Detail_TextureOffset")) + writer.WriteProperty("_Detail_TextureOffset", instance.GetTextureOffset("_Detail_TextureOffset")); + if(instance.HasProperty("_Detail_TextureScale")) + writer.WriteProperty("_Detail_TextureScale", instance.GetTextureScale("_Detail_TextureScale")); + if(instance.HasProperty("_HalfOverCutoff")) + writer.WriteProperty("_HalfOverCutoff", instance.GetFloat("_HalfOverCutoff")); + #endif + } + } + + protected override object ReadUnityObject(ES3Reader reader) + { + var obj = new Material(Shader.Find("Diffuse")); + ReadUnityObject(reader, obj); + return obj; + } + + protected override void ReadUnityObject(ES3Reader reader, object obj) + { + var instance = (UnityEngine.Material)obj; + +#if UNITY_2019_3_OR_NEWER + + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + case "name": + instance.name = reader.Read(ES3Type_string.Instance); + break; + case "shader": + instance.shader = reader.Read(ES3Type_Shader.Instance); + break; + case "renderQueue": + instance.renderQueue = reader.Read(ES3Type_int.Instance); + break; + case "shaderKeywords": + var keywords = reader.Read(); + foreach (var keyword in keywords) + instance.EnableKeyword(keyword); + break; + case "globalIlluminationFlags": + instance.globalIlluminationFlags = reader.Read(); + break; + case "_MainTex_Scale": + instance.SetTextureScale("_MainTex", reader.Read()); + break; + default: + var propertyIndex = -1; + if (instance.shader != null && instance.HasProperty(propertyName) && (propertyIndex = instance.shader.FindPropertyIndex(propertyName)) != -1) + { + var propertyType = instance.shader.GetPropertyType(propertyIndex); + + switch (propertyType) + { + case UnityEngine.Rendering.ShaderPropertyType.Color: + instance.SetColor(propertyName, reader.Read()); + break; + case UnityEngine.Rendering.ShaderPropertyType.Float: + case UnityEngine.Rendering.ShaderPropertyType.Range: + instance.SetFloat(propertyName, reader.Read()); + break; + case UnityEngine.Rendering.ShaderPropertyType.Texture: + instance.SetTexture(propertyName, reader.Read()); + break; + case UnityEngine.Rendering.ShaderPropertyType.Vector: + instance.SetColor(propertyName, reader.Read()); + break; + } + } + else if (propertyName.EndsWith("_TextureScale")) + instance.SetTextureScale(propertyName.Split(new string[] { "_TextureScale" }, StringSplitOptions.None)[0], reader.Read()); + else if (propertyName.EndsWith("_TextureOffset")) + instance.SetTextureOffset(propertyName.Split(new string[] { "_TextureOffset" }, StringSplitOptions.None)[0], reader.Read()); + + reader.Skip(); + break; + } + } +#else + + foreach (string propertyName in reader.Properties) + { + switch(propertyName) + { + case "name": + instance.name = reader.Read(ES3Type_string.Instance); + break; + case "shader": + instance.shader = reader.Read(ES3Type_Shader.Instance); + break; + case "renderQueue": + instance.renderQueue = reader.Read(ES3Type_int.Instance); + break; + case "shaderKeywords": + instance.shaderKeywords = reader.Read(); + break; + case "globalIlluminationFlags": + instance.globalIlluminationFlags = reader.Read(); + break; + case "_Color": + instance.SetColor("_Color", reader.Read()); + break; + case "_SpecColor": + instance.SetColor("_SpecColor", reader.Read()); + break; + case "_Shininess": + instance.SetFloat("_Shininess", reader.Read()); + break; + case "_MainTex": + instance.SetTexture("_MainTex", reader.Read()); + break; + case "_MainTex_TextureOffset": + instance.SetTextureOffset("_MainTex_TextureOffset", reader.Read()); + break; + case "_MainTex_TextureScale": + instance.SetTextureScale("_MainTex_TextureScale", reader.Read()); + break; + case "_Illum": + instance.SetTexture("_Illum", reader.Read()); + break; + case "_Illum_TextureOffset": + instance.SetTextureOffset("_Illum_TextureOffset", reader.Read()); + break; + case "_Illum_TextureScale": + instance.SetTextureScale("_Illum_TextureScale", reader.Read()); + break; + case "_BumpMap": + instance.SetTexture("_BumpMap", reader.Read()); + break; + case "_BumpMap_TextureOffset": + instance.SetTextureOffset("_BumpMap_TextureOffset", reader.Read()); + break; + case "_BumpMap_TextureScale": + instance.SetTextureScale("_BumpMap_TextureScale", reader.Read()); + break; + case "_Emission": + instance.SetFloat("_Emission", reader.Read()); + break; + case "_Specular": + instance.SetColor("_Specular", reader.Read()); + break; + case "_MainBump": + instance.SetTexture("_MainBump", reader.Read()); + break; + case "_MainBump_TextureOffset": + instance.SetTextureOffset("_MainBump_TextureOffset", reader.Read()); + break; + case "_MainBump_TextureScale": + instance.SetTextureScale("_MainBump_TextureScale", reader.Read()); + break; + case "_Mask": + instance.SetTexture("_Mask", reader.Read()); + break; + case "_Mask_TextureOffset": + instance.SetTextureOffset("_Mask_TextureOffset", reader.Read()); + break; + case "_Mask_TextureScale": + instance.SetTextureScale("_Mask_TextureScale", reader.Read()); + break; + case "_Focus": + instance.SetFloat("_Focus", reader.Read()); + break; + case "_StencilComp": + instance.SetFloat("_StencilComp", reader.Read()); + break; + case "_Stencil": + instance.SetFloat("_Stencil", reader.Read()); + break; + case "_StencilOp": + instance.SetFloat("_StencilOp", reader.Read()); + break; + case "_StencilWriteMask": + instance.SetFloat("_StencilWriteMask", reader.Read()); + break; + case "_StencilReadMask": + instance.SetFloat("_StencilReadMask", reader.Read()); + break; + case "_ColorMask": + instance.SetFloat("_ColorMask", reader.Read()); + break; + case "_UseUIAlphaClip": + instance.SetFloat("_UseUIAlphaClip", reader.Read()); + break; + case "_SrcBlend": + instance.SetFloat("_SrcBlend", reader.Read()); + break; + case "_DstBlend": + instance.SetFloat("_DstBlend", reader.Read()); + break; + case "_ReflectColor": + instance.SetColor("_ReflectColor", reader.Read()); + break; + case "_Cube": + instance.SetTexture("_Cube", reader.Read()); + break; + case "_Cube_TextureOffset": + instance.SetTextureOffset("_Cube_TextureOffset", reader.Read()); + break; + case "_Cube_TextureScale": + instance.SetTextureScale("_Cube_TextureScale", reader.Read()); + break; + case "_Tint": + instance.SetColor("_Tint", reader.Read()); + break; + case "_Exposure": + instance.SetFloat("_Exposure", reader.Read()); + break; + case "_Rotation": + instance.SetFloat("_Rotation", reader.Read()); + break; + case "_Tex": + instance.SetTexture("_Tex", reader.Read()); + break; + case "_Tex_TextureOffset": + instance.SetTextureOffset("_Tex_TextureOffset", reader.Read()); + break; + case "_Tex_TextureScale": + instance.SetTextureScale("_Tex_TextureScale", reader.Read()); + break; + case "_MainTex_Scale": + instance.SetTextureScale("_MainTex", reader.Read()); + break; + case "_Control": + instance.SetTexture("_Control", reader.Read()); + break; + case "_Control_TextureOffset": + instance.SetTextureOffset("_Control_TextureOffset", reader.Read()); + break; + case "_Control_TextureScale": + instance.SetTextureScale("_Control_TextureScale", reader.Read()); + break; + case "_Splat3": + instance.SetTexture("_Splat3", reader.Read()); + break; + case "_Splat3_TextureOffset": + instance.SetTextureOffset("_Splat3_TextureOffset", reader.Read()); + break; + case "_Splat3_TextureScale": + instance.SetTextureScale("_Splat3_TextureScale", reader.Read()); + break; + case "_Splat2": + instance.SetTexture("_Splat2", reader.Read()); + break; + case "_Splat2_TextureOffset": + instance.SetTextureOffset("_Splat2_TextureOffset", reader.Read()); + break; + case "_Splat2_TextureScale": + instance.SetTextureScale("_Splat2_TextureScale", reader.Read()); + break; + case "_Splat1": + instance.SetTexture("_Splat1", reader.Read()); + break; + case "_Splat1_TextureOffset": + instance.SetTextureOffset("_Splat1_TextureOffset", reader.Read()); + break; + case "_Splat1_TextureScale": + instance.SetTextureScale("_Splat1_TextureScale", reader.Read()); + break; + case "_Splat0": + instance.SetTexture("_Splat0", reader.Read()); + break; + case "_Splat0_TextureOffset": + instance.SetTextureOffset("_Splat0_TextureOffset", reader.Read()); + break; + case "_Splat0_TextureScale": + instance.SetTextureScale("_Splat0_TextureScale", reader.Read()); + break; + case "_Normal3": + instance.SetTexture("_Normal3", reader.Read()); + break; + case "_Normal3_TextureOffset": + instance.SetTextureOffset("_Normal3_TextureOffset", reader.Read()); + break; + case "_Normal3_TextureScale": + instance.SetTextureScale("_Normal3_TextureScale", reader.Read()); + break; + case "_Normal2": + instance.SetTexture("_Normal2", reader.Read()); + break; + case "_Normal2_TextureOffset": + instance.SetTextureOffset("_Normal2_TextureOffset", reader.Read()); + break; + case "_Normal2_TextureScale": + instance.SetTextureScale("_Normal2_TextureScale", reader.Read()); + break; + case "_Normal1": + instance.SetTexture("_Normal1", reader.Read()); + break; + case "_Normal1_TextureOffset": + instance.SetTextureOffset("_Normal1_TextureOffset", reader.Read()); + break; + case "_Normal1_TextureScale": + instance.SetTextureScale("_Normal1_TextureScale", reader.Read()); + break; + case "_Normal0": + instance.SetTexture("_Normal0", reader.Read()); + break; + case "_Normal0_TextureOffset": + instance.SetTextureOffset("_Normal0_TextureOffset", reader.Read()); + break; + case "_Normal0_TextureScale": + instance.SetTextureScale("_Normal0_TextureScale", reader.Read()); + break; + case "_Cutoff": + instance.SetFloat("_Cutoff", reader.Read()); + break; + case "_BaseLight": + instance.SetFloat("_BaseLight", reader.Read()); + break; + case "_AO": + instance.SetFloat("_AO", reader.Read()); + break; + case "_Occlusion": + instance.SetFloat("_Occlusion", reader.Read()); + break; + case "_TreeInstanceColor": + instance.SetVector("_TreeInstanceColor", reader.Read()); + break; + case "_TreeInstanceScale": + instance.SetVector("_TreeInstanceScale", reader.Read()); + break; + case "_SquashAmount": + instance.SetFloat("_SquashAmount", reader.Read()); + break; + case "_TranslucencyColor": + instance.SetColor("_TranslucencyColor", reader.Read()); + break; + case "_TranslucencyViewDependency": + instance.SetFloat("_TranslucencyViewDependency", reader.Read()); + break; + case "_ShadowStrength": + instance.SetFloat("_ShadowStrength", reader.Read()); + break; + case "_ShadowOffsetScale": + instance.SetFloat("_ShadowOffsetScale", reader.Read()); + break; + case "_ShadowTex": + instance.SetTexture("_ShadowTex", reader.Read()); + break; + case "_ShadowTex_TextureOffset": + instance.SetTextureOffset("_ShadowTex_TextureOffset", reader.Read()); + break; + case "_ShadowTex_TextureScale": + instance.SetTextureScale("_ShadowTex_TextureScale", reader.Read()); + break; + case "_BumpSpecMap": + instance.SetTexture("_BumpSpecMap", reader.Read()); + break; + case "_BumpSpecMap_TextureOffset": + instance.SetTextureOffset("_BumpSpecMap_TextureOffset", reader.Read()); + break; + case "_BumpSpecMap_TextureScale": + instance.SetTextureScale("_BumpSpecMap_TextureScale", reader.Read()); + break; + case "_TranslucencyMap": + instance.SetTexture("_TranslucencyMap", reader.Read()); + break; + case "_TranslucencyMap_TextureOffset": + instance.SetTextureOffset("_TranslucencyMap_TextureOffset", reader.Read()); + break; + case "_TranslucencyMap_TextureScale": + instance.SetTextureScale("_TranslucencyMap_TextureScale", reader.Read()); + break; + case "_LightMap": + instance.SetTexture("_LightMap", reader.Read()); + break; + case "_LightMap_TextureOffset": + instance.SetTextureOffset("_LightMap_TextureOffset", reader.Read()); + break; + case "_LightMap_TextureScale": + instance.SetTextureScale("_LightMap_TextureScale", reader.Read()); + break; + case "_DetailTex": + instance.SetTexture("_DetailTex", reader.Read()); + break; + case "_DetailTex_TextureOffset": + instance.SetTextureOffset("_DetailTex_TextureOffset", reader.Read()); + break; + case "_DetailTex_TextureScale": + instance.SetTextureScale("_DetailTex_TextureScale", reader.Read()); + break; + case "_DetailBump": + instance.SetTexture("_DetailBump", reader.Read()); + break; + case "_DetailBump_TextureOffset": + instance.SetTextureOffset("_DetailBump_TextureOffset", reader.Read()); + break; + case "_DetailBump_TextureScale": + instance.SetTextureScale("_DetailBump_TextureScale", reader.Read()); + break; + case "_Strength": + instance.SetFloat("_Strength", reader.Read()); + break; + case "_InvFade": + instance.SetFloat("_InvFade", reader.Read()); + break; + case "_EmisColor": + instance.SetColor("_EmisColor", reader.Read()); + break; + case "_Parallax": + instance.SetFloat("_Parallax", reader.Read()); + break; + case "_ParallaxMap": + instance.SetTexture("_ParallaxMap", reader.Read()); + break; + case "_ParallaxMap_TextureOffset": + instance.SetTextureOffset("_ParallaxMap_TextureOffset", reader.Read()); + break; + case "_ParallaxMap_TextureScale": + instance.SetTextureScale("_ParallaxMap_TextureScale", reader.Read()); + break; + case "_DecalTex": + instance.SetTexture("_DecalTex", reader.Read()); + break; + case "_DecalTex_TextureOffset": + instance.SetTextureOffset("_DecalTex_TextureOffset", reader.Read()); + break; + case "_DecalTex_TextureScale": + instance.SetTextureScale("_DecalTex_TextureScale", reader.Read()); + break; + case "_GlossMap": + instance.SetTexture("_GlossMap", reader.Read()); + break; + case "_GlossMap_TextureOffset": + instance.SetTextureOffset("_GlossMap_TextureOffset", reader.Read()); + break; + case "_GlossMap_TextureScale": + instance.SetTextureScale("_GlossMap_TextureScale", reader.Read()); + break; + case "_ShadowOffset": + instance.SetTexture("_ShadowOffset", reader.Read()); + break; + case "_ShadowOffset_TextureOffset": + instance.SetTextureOffset("_ShadowOffset_TextureOffset", reader.Read()); + break; + case "_ShadowOffset_TextureScale": + instance.SetTextureScale("_ShadowOffset_TextureScale", reader.Read()); + break; + case "_SunDisk": + instance.SetFloat("_SunDisk", reader.Read()); + break; + case "_SunSize": + instance.SetFloat("_SunSize", reader.Read()); + break; + case "_AtmosphereThickness": + instance.SetFloat("_AtmosphereThickness", reader.Read()); + break; + case "_SkyTint": + instance.SetColor("_SkyTint", reader.Read()); + break; + case "_GroundColor": + instance.SetColor("_GroundColor", reader.Read()); + break; + case "_WireThickness": + instance.SetFloat("_WireThickness", reader.Read()); + break; + case "_ZWrite": + instance.SetFloat("_ZWrite", reader.Read()); + break; + case "_ZTest": + instance.SetFloat("_ZTest", reader.Read()); + break; + case "_Cull": + instance.SetFloat("_Cull", reader.Read()); + break; + case "_ZBias": + instance.SetFloat("_ZBias", reader.Read()); + break; + case "_HueVariation": + instance.SetColor("_HueVariation", reader.Read()); + break; + case "_WindQuality": + instance.SetFloat("_WindQuality", reader.Read()); + break; + case "_DetailMask": + instance.SetTexture("_DetailMask", reader.Read()); + break; + case "_DetailMask_TextureOffset": + instance.SetTextureOffset("_DetailMask_TextureOffset", reader.Read()); + break; + case "_DetailMask_TextureScale": + instance.SetTextureScale("_DetailMask_TextureScale", reader.Read()); + break; + case "_MetallicTex": + instance.SetTexture("_MetallicTex", reader.Read()); + break; + case "_MetallicTex_TextureOffset": + instance.SetTextureOffset("_MetallicTex_TextureOffset", reader.Read()); + break; + case "_MetallicTex_TextureScale": + instance.SetTextureScale("_MetallicTex_TextureScale", reader.Read()); + break; + case "_Glossiness": + instance.SetFloat("_Glossiness", reader.Read()); + break; + case "_GlossMapScale": + instance.SetFloat("_GlossMapScale", reader.Read()); + break; + case "_SmoothnessTextureChannel": + instance.SetFloat("_SmoothnessTextureChannel", reader.Read()); + break; + case "_Metallic": + instance.SetFloat("_Metallic", reader.Read()); + break; + case "_MetallicGlossMap": + instance.SetTexture("_MetallicGlossMap", reader.Read()); + break; + case "_MetallicGlossMap_TextureOffset": + instance.SetTextureOffset("_MetallicGlossMap_TextureOffset", reader.Read()); + break; + case "_MetallicGlossMap_TextureScale": + instance.SetTextureScale("_MetallicGlossMap_TextureScale", reader.Read()); + break; + case "_SpecularHighlights": + instance.SetFloat("_SpecularHighlights", reader.Read()); + break; + case "_GlossyReflections": + instance.SetFloat("_GlossyReflections", reader.Read()); + break; + case "_BumpScale": + instance.SetFloat("_BumpScale", reader.Read()); + break; + case "_OcclusionStrength": + instance.SetFloat("_OcclusionStrength", reader.Read()); + break; + case "_OcclusionMap": + instance.SetTexture("_OcclusionMap", reader.Read()); + break; + case "_OcclusionMap_TextureOffset": + instance.SetTextureOffset("_OcclusionMap_TextureOffset", reader.Read()); + break; + case "_OcclusionMap_TextureScale": + instance.SetTextureScale("_OcclusionMap_TextureScale", reader.Read()); + break; + case "_EmissionColor": + instance.SetColor("_EmissionColor", reader.Read()); + break; + case "_EmissionMap": + instance.SetTexture("_EmissionMap", reader.Read()); + break; + case "_EmissionMap_TextureOffset": + instance.SetTextureOffset("_EmissionMap_TextureOffset", reader.Read()); + break; + case "_EmissionMap_TextureScale": + instance.SetTextureScale("_EmissionMap_TextureScale", reader.Read()); + break; + case "_DetailAlbedoMap": + instance.SetTexture("_DetailAlbedoMap", reader.Read()); + break; + case "_DetailAlbedoMap_TextureOffset": + instance.SetTextureOffset("_DetailAlbedoMap_TextureOffset", reader.Read()); + break; + case "_DetailAlbedoMap_TextureScale": + instance.SetTextureScale("_DetailAlbedoMap_TextureScale", reader.Read()); + break; + case "_DetailNormalMapScale": + instance.SetFloat("_DetailNormalMapScale", reader.Read()); + break; + case "_DetailNormalMap": + instance.SetTexture("_DetailNormalMap", reader.Read()); + break; + case "_DetailNormalMap_TextureOffset": + instance.SetTextureOffset("_DetailNormalMap_TextureOffset", reader.Read()); + break; + case "_DetailNormalMap_TextureScale": + instance.SetTextureScale("_DetailNormalMap_TextureScale", reader.Read()); + break; + case "_UVSec": + instance.SetFloat("_UVSec", reader.Read()); + break; + case "_Mode": + instance.SetFloat("_Mode", reader.Read()); + break; + case "_TintColor": + instance.SetColor("_TintColor", reader.Read()); + break; + case "_WavingTint": + instance.SetColor("_WavingTint", reader.Read()); + break; + case "_WaveAndDistance": + instance.SetVector("_WaveAndDistance", reader.Read()); + break; + case "_LightTexture0": + instance.SetTexture("_LightTexture0", reader.Read()); + break; + case "_LightTexture0_TextureOffset": + instance.SetTextureOffset("_LightTexture0_TextureOffset", reader.Read()); + break; + case "_LightTexture0_TextureScale": + instance.SetTextureScale("_LightTexture0_TextureScale", reader.Read()); + break; + case "_LightTextureB0": + instance.SetTexture("_LightTextureB0", reader.Read()); + break; + case "_LightTextureB0_TextureOffset": + instance.SetTextureOffset("_LightTextureB0_TextureOffset", reader.Read()); + break; + case "_LightTextureB0_TextureScale": + instance.SetTextureScale("_LightTextureB0_TextureScale", reader.Read()); + break; + case "_ShadowMapTexture": + instance.SetTexture("_ShadowMapTexture", reader.Read()); + break; + case "_ShadowMapTexture_TextureOffset": + instance.SetTextureOffset("_ShadowMapTexture_TextureOffset", reader.Read()); + break; + case "_ShadowMapTexture_TextureScale": + instance.SetTextureScale("_ShadowMapTexture_TextureScale", reader.Read()); + break; + case "_SecondTex": + instance.SetTexture("_SecondTex", reader.Read()); + break; + case "_SecondTex_TextureOffset": + instance.SetTextureOffset("_SecondTex_TextureOffset", reader.Read()); + break; + case "_SecondTex_TextureScale": + instance.SetTextureScale("_SecondTex_TextureScale", reader.Read()); + break; + case "_ThirdTex": + instance.SetTexture("_ThirdTex", reader.Read()); + break; + case "_ThirdTex_TextureOffset": + instance.SetTextureOffset("_ThirdTex_TextureOffset", reader.Read()); + break; + case "_ThirdTex_TextureScale": + instance.SetTextureScale("_ThirdTex_TextureScale", reader.Read()); + break; + case "PixelSnap": + instance.SetFloat("PixelSnap", reader.Read()); + break; + case "_RendererColor": + instance.SetColor("_RendererColor", reader.Read()); + break; + case "_Flip": + instance.SetVector("_Flip", reader.Read()); + break; + case "_AlphaTex": + instance.SetTexture("_AlphaTex", reader.Read()); + break; + case "_AlphaTex_TextureOffset": + instance.SetTextureOffset("_AlphaTex_TextureOffset", reader.Read()); + break; + case "_AlphaTex_TextureScale": + instance.SetTextureScale("_AlphaTex_TextureScale", reader.Read()); + break; + case "_EnableExternalAlpha": + instance.SetFloat("_EnableExternalAlpha", reader.Read()); + break; + case "_Level": + instance.SetFloat("_Level", reader.Read()); + break; + case "_SpecGlossMap": + instance.SetTexture("_SpecGlossMap", reader.Read()); + break; + case "_SpecGlossMap_TextureOffset": + instance.SetTextureOffset("_SpecGlossMap_TextureOffset", reader.Read()); + break; + case "_SpecGlossMap_TextureScale": + instance.SetTextureScale("_SpecGlossMap_TextureScale", reader.Read()); + break; + case "_FrontTex": + instance.SetTexture("_FrontTex", reader.Read()); + break; + case "_FrontTex_TextureOffset": + instance.SetTextureOffset("_FrontTex_TextureOffset", reader.Read()); + break; + case "_FrontTex_TextureScale": + instance.SetTextureScale("_FrontTex_TextureScale", reader.Read()); + break; + case "_BackTex": + instance.SetTexture("_BackTex", reader.Read()); + break; + case "_BackTex_TextureOffset": + instance.SetTextureOffset("_BackTex_TextureOffset", reader.Read()); + break; + case "_BackTex_TextureScale": + instance.SetTextureScale("_BackTex_TextureScale", reader.Read()); + break; + case "_LeftTex": + instance.SetTexture("_LeftTex", reader.Read()); + break; + case "_LeftTex_TextureOffset": + instance.SetTextureOffset("_LeftTex_TextureOffset", reader.Read()); + break; + case "_LeftTex_TextureScale": + instance.SetTextureScale("_LeftTex_TextureScale", reader.Read()); + break; + case "_RightTex": + instance.SetTexture("_RightTex", reader.Read()); + break; + case "_RightTex_TextureOffset": + instance.SetTextureOffset("_RightTex_TextureOffset", reader.Read()); + break; + case "_RightTex_TextureScale": + instance.SetTextureScale("_RightTex_TextureScale", reader.Read()); + break; + case "_UpTex": + instance.SetTexture("_UpTex", reader.Read()); + break; + case "_UpTex_TextureOffset": + instance.SetTextureOffset("_UpTex_TextureOffset", reader.Read()); + break; + case "_UpTex_TextureScale": + instance.SetTextureScale("_UpTex_TextureScale", reader.Read()); + break; + case "_DownTex": + instance.SetTexture("_DownTex", reader.Read()); + break; + case "_DownTex_TextureOffset": + instance.SetTextureOffset("_DownTex_TextureOffset", reader.Read()); + break; + case "_DownTex_TextureScale": + instance.SetTextureScale("_DownTex_TextureScale", reader.Read()); + break; + case "_Metallic0": + instance.SetFloat("_Metallic0", reader.Read()); + break; + case "_Metallic1": + instance.SetFloat("_Metallic1", reader.Read()); + break; + case "_Metallic2": + instance.SetFloat("_Metallic2", reader.Read()); + break; + case "_Metallic3": + instance.SetFloat("_Metallic3", reader.Read()); + break; + case "_Smoothness0": + instance.SetFloat("_Smoothness0", reader.Read()); + break; + case "_Smoothness1": + instance.SetFloat("_Smoothness1", reader.Read()); + break; + case "_Smoothness2": + instance.SetFloat("_Smoothness2", reader.Read()); + break; + case "_Smoothness3": + instance.SetFloat("_Smoothness3", reader.Read()); + break; + case "_TexA": + instance.SetTexture("_TexA", reader.Read()); + break; + case "_TexA_TextureOffset": + instance.SetTextureOffset("_TexA_TextureOffset", reader.Read()); + break; + case "_TexA_TextureScale": + instance.SetTextureScale("_TexA_TextureScale", reader.Read()); + break; + case "_TexB": + instance.SetTexture("_TexB", reader.Read()); + break; + case "_TexB_TextureOffset": + instance.SetTextureOffset("_TexB_TextureOffset", reader.Read()); + break; + case "_TexB_TextureScale": + instance.SetTextureScale("_TexB_TextureScale", reader.Read()); + break; + case "_value": + instance.SetFloat("_value", reader.Read()); + break; + case "_Texel": + instance.SetFloat("_Texel", reader.Read()); + break; + case "_Detail": + instance.SetTexture("_Detail", reader.Read()); + break; + case "_Detail_TextureOffset": + instance.SetTextureOffset("_Detail_TextureOffset", reader.Read()); + break; + case "_Detail_TextureScale": + instance.SetTextureScale("_Detail_TextureScale", reader.Read()); + break; + case "_HalfOverCutoff": + instance.SetFloat("_HalfOverCutoff", reader.Read()); + break; + + default: + reader.Skip(); + break; + } + } +#endif + } + } + + public class ES3Type_MaterialArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_MaterialArray() : base(typeof(Material[]), ES3Type_Material.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Material.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Material.cs.meta new file mode 100644 index 0000000..0240dd4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Material.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e2fe9704b49ad41cbb997e2b68befc6e +timeCreated: 1519132298 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Matrix4x4.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Matrix4x4.cs new file mode 100644 index 0000000..6cef1fc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Matrix4x4.cs @@ -0,0 +1,47 @@ +using System; +using UnityEngine; +using System.Collections.Generic; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("col0", "col1", "col2", "col3")] + public class ES3Type_Matrix4x4 : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Matrix4x4() : base(typeof(Matrix4x4)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Matrix4x4 casted = (Matrix4x4)obj; + writer.WriteProperty("col0", casted.GetColumn(0), ES3Type_Vector4.Instance); + writer.WriteProperty("col1", casted.GetColumn(1), ES3Type_Vector4.Instance); + writer.WriteProperty("col2", casted.GetColumn(2), ES3Type_Vector4.Instance); + writer.WriteProperty("col3", casted.GetColumn(3), ES3Type_Vector4.Instance); + } + + public override object Read(ES3Reader reader) + { + var matrix = new Matrix4x4(); + matrix.SetColumn(0, reader.ReadProperty(ES3Type_Vector4.Instance)); + matrix.SetColumn(1, reader.ReadProperty(ES3Type_Vector4.Instance)); + matrix.SetColumn(2, reader.ReadProperty(ES3Type_Vector4.Instance)); + matrix.SetColumn(3, reader.ReadProperty(ES3Type_Vector4.Instance)); + return matrix; + } + } + + public class ES3Type_Matrix4x4Array : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_Matrix4x4Array() : base(typeof(Matrix4x4[]), ES3Type_Matrix4x4.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Matrix4x4.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Matrix4x4.cs.meta new file mode 100644 index 0000000..ee057a4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Matrix4x4.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b08ac351ee185470bb1ccb5150c4082f +timeCreated: 1519132294 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Mesh.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Mesh.cs new file mode 100644 index 0000000..b07a7b7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Mesh.cs @@ -0,0 +1,169 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("bounds", "subMeshCount", "boneWeights", "bindposes", "vertices", "normals", "tangents", "uv", "uv2", "uv3", "uv4", "colors32", "triangles", "subMeshes")] + public class ES3Type_Mesh : ES3UnityObjectType + { + public static ES3Type Instance = null; + + public ES3Type_Mesh() : base(typeof(UnityEngine.Mesh)) + { + Instance = this; + } + + protected override void WriteUnityObject(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Mesh)obj; + + if(!instance.isReadable) + { + ES3Internal.ES3Debug.LogWarning("Easy Save cannot save the vertices for this Mesh because it is not marked as readable, so it will be stored by reference. To save the vertex data for this Mesh, check the 'Read/Write Enabled' checkbox in its Import Settings.", instance); + return; + } + + writer.WriteProperty("indexFormat", instance.indexFormat); + writer.WriteProperty("name", instance.name); + writer.WriteProperty("vertices", instance.vertices, ES3Type_Vector3Array.Instance); + writer.WriteProperty("triangles", instance.triangles, ES3Type_intArray.Instance); + writer.WriteProperty("bounds", instance.bounds, ES3Type_Bounds.Instance); + writer.WriteProperty("boneWeights", instance.boneWeights, ES3Type_BoneWeightArray.Instance); + writer.WriteProperty("bindposes", instance.bindposes, ES3Type_Matrix4x4Array.Instance); + writer.WriteProperty("normals", instance.normals, ES3Type_Vector3Array.Instance); + writer.WriteProperty("tangents", instance.tangents, ES3Type_Vector4Array.Instance); + writer.WriteProperty("uv", instance.uv, ES3Type_Vector2Array.Instance); + writer.WriteProperty("uv2", instance.uv2, ES3Type_Vector2Array.Instance); + writer.WriteProperty("uv3", instance.uv3, ES3Type_Vector2Array.Instance); + writer.WriteProperty("uv4", instance.uv4, ES3Type_Vector2Array.Instance); + writer.WriteProperty("colors32", instance.colors32, ES3Type_Color32Array.Instance); + writer.WriteProperty("subMeshCount", instance.subMeshCount, ES3Type_int.Instance); + for(int i=0; i(ES3Reader reader) + { + var obj = new Mesh(); + ReadUnityObject(reader, obj); + return obj; + } + + protected override void ReadUnityObject(ES3Reader reader, object obj) + { + var instance = (UnityEngine.Mesh)obj; + if (instance == null) + return; + + if (!instance.isReadable) + ES3Internal.ES3Debug.LogWarning("Easy Save cannot load the vertices for this Mesh because it is not marked as readable, so it will be loaded by reference. To load the vertex data for this Mesh, check the 'Read/Write Enabled' checkbox in its Import Settings.", instance); + + foreach (string propertyName in reader.Properties) + { + // If this Mesh isn't readable, we should skip past all of its properties. + if (!instance.isReadable) + { + reader.Skip(); + continue; + } + + switch (propertyName) + { + case "indexFormat": + instance.indexFormat = reader.Read(); + break; + case "name": + instance.name = reader.Read(ES3Type_string.Instance); + break; + case "bounds": + instance.bounds = reader.Read(ES3Type_Bounds.Instance); + break; + case "boneWeights": + instance.boneWeights = reader.Read(ES3Type_BoneWeightArray.Instance); + break; + case "bindposes": + instance.bindposes = reader.Read(ES3Type_Matrix4x4Array.Instance); + break; + case "vertices": + instance.vertices = reader.Read(ES3Type_Vector3Array.Instance); + break; + case "normals": + instance.normals = reader.Read(ES3Type_Vector3Array.Instance); + break; + case "tangents": + instance.tangents = reader.Read(ES3Type_Vector4Array.Instance); + break; + case "uv": + instance.uv = reader.Read(ES3Type_Vector2Array.Instance); + break; + case "uv2": + instance.uv2 = reader.Read(ES3Type_Vector2Array.Instance); + break; + case "uv3": + instance.uv3 = reader.Read(ES3Type_Vector2Array.Instance); + break; + case "uv4": + instance.uv4 = reader.Read(ES3Type_Vector2Array.Instance); + break; + case "colors32": + instance.colors32 = reader.Read(ES3Type_Color32Array.Instance); + break; + case "triangles": + instance.triangles = reader.Read(ES3Type_intArray.Instance); + break; + case "subMeshCount": + instance.subMeshCount = reader.Read(ES3Type_int.Instance); + for(int i=0; i(ES3Type_intArray.Instance), i); + break; + case "blendShapeCount": + instance.ClearBlendShapes(); + var blendShapeCount = reader.Read(ES3Type_int.Instance); + for (int blendShapeIndex = 0; blendShapeIndex < blendShapeCount; blendShapeIndex++) + { + var shapeName = reader.ReadProperty(); + var frameCount = reader.ReadProperty(); + + for (int frameIndex = 0; frameIndex < frameCount; frameIndex++) + { + var deltaVertices = reader.ReadProperty(); + var deltaNormals = reader.ReadProperty(); + var deltaTangents = reader.ReadProperty(); + var frameWeight = reader.ReadProperty(); + + instance.AddBlendShapeFrame(shapeName, frameWeight, deltaVertices, deltaNormals, deltaTangents); + } + } + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Mesh.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Mesh.cs.meta new file mode 100644 index 0000000..d4f2333 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Mesh.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e39bdb3d7bcae4f1aa682cbc9ff72ce7 +timeCreated: 1519132298 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxCurve.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxCurve.cs new file mode 100644 index 0000000..fdfa780 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxCurve.cs @@ -0,0 +1,114 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("mode", "curveMultiplier", "curveMax", "curveMin", "constantMax", "constantMin", "constant", "curve")] + public class ES3Type_MinMaxCurve : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_MinMaxCurve() : base(typeof(UnityEngine.ParticleSystem.MinMaxCurve)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.MinMaxCurve)obj; + + writer.WriteProperty("mode", instance.mode); + writer.WriteProperty("curveMultiplier", instance.curveMultiplier, ES3Type_float.Instance); + writer.WriteProperty("curveMax", instance.curveMax, ES3Type_AnimationCurve.Instance); + writer.WriteProperty("curveMin", instance.curveMin, ES3Type_AnimationCurve.Instance); + writer.WriteProperty("constantMax", instance.constantMax, ES3Type_float.Instance); + writer.WriteProperty("constantMin", instance.constantMin, ES3Type_float.Instance); + writer.WriteProperty("constant", instance.constant, ES3Type_float.Instance); + writer.WriteProperty("curve", instance.curve, ES3Type_AnimationCurve.Instance); + } + + [UnityEngine.Scripting.Preserve] + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.MinMaxCurve(); + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "mode": + instance.mode = reader.Read(); + break; + case "curveMultiplier": + instance.curveMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "curveMax": + instance.curveMax = reader.Read(ES3Type_AnimationCurve.Instance); + break; + case "curveMin": + instance.curveMin = reader.Read(ES3Type_AnimationCurve.Instance); + break; + case "constantMax": + instance.constantMax = reader.Read(ES3Type_float.Instance); + break; + case "constantMin": + instance.constantMin = reader.Read(ES3Type_float.Instance); + break; + case "constant": + instance.constant = reader.Read(ES3Type_float.Instance); + break; + case "curve": + instance.curve = reader.Read(ES3Type_AnimationCurve.Instance); + break; + default: + reader.Skip(); + break; + } + } + return instance; + } + + [UnityEngine.Scripting.Preserve] + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.MinMaxCurve)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "mode": + instance.mode = reader.Read(); + break; + case "curveMultiplier": + instance.curveMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "curveMax": + instance.curveMax = reader.Read(ES3Type_AnimationCurve.Instance); + break; + case "curveMin": + instance.curveMin = reader.Read(ES3Type_AnimationCurve.Instance); + break; + case "constantMax": + instance.constantMax = reader.Read(ES3Type_float.Instance); + break; + case "constantMin": + instance.constantMin = reader.Read(ES3Type_float.Instance); + break; + case "constant": + instance.constant = reader.Read(ES3Type_float.Instance); + break; + case "curve": + instance.curve = reader.Read(ES3Type_AnimationCurve.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxCurve.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxCurve.cs.meta new file mode 100644 index 0000000..6c43b9e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxCurve.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: b63607ddb964c4897880a99d41c70efd +timeCreated: 1519132294 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxGradient.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxGradient.cs new file mode 100644 index 0000000..120f006 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxGradient.cs @@ -0,0 +1,68 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("mode", "gradientMax", "gradientMin", "colorMax", "colorMin", "color", "gradient")] + public class ES3Type_MinMaxGradient : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_MinMaxGradient() : base(typeof(UnityEngine.ParticleSystem.MinMaxGradient)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.MinMaxGradient)obj; + + writer.WriteProperty("mode", instance.mode); + writer.WriteProperty("gradientMax", instance.gradientMax, ES3Type_Gradient.Instance); + writer.WriteProperty("gradientMin", instance.gradientMin, ES3Type_Gradient.Instance); + writer.WriteProperty("colorMax", instance.colorMax, ES3Type_Color.Instance); + writer.WriteProperty("colorMin", instance.colorMin, ES3Type_Color.Instance); + writer.WriteProperty("color", instance.color, ES3Type_Color.Instance); + writer.WriteProperty("gradient", instance.gradient, ES3Type_Gradient.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.MinMaxGradient(); + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "mode": + instance.mode = reader.Read(); + break; + case "gradientMax": + instance.gradientMax = reader.Read(ES3Type_Gradient.Instance); + break; + case "gradientMin": + instance.gradientMin = reader.Read(ES3Type_Gradient.Instance); + break; + case "colorMax": + instance.colorMax = reader.Read(ES3Type_Color.Instance); + break; + case "colorMin": + instance.colorMin = reader.Read(ES3Type_Color.Instance); + break; + case "color": + instance.color = reader.Read(ES3Type_Color.Instance); + break; + case "gradient": + instance.gradient = reader.Read(ES3Type_Gradient.Instance); + break; + default: + reader.Skip(); + break; + } + } + return instance; + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxGradient.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxGradient.cs.meta new file mode 100644 index 0000000..72fe496 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_MinMaxGradient.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c5b12866f2f984f6a822a127d5be1f9c +timeCreated: 1519132296 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_NoiseModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_NoiseModule.cs new file mode 100644 index 0000000..d4e5ca4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_NoiseModule.cs @@ -0,0 +1,154 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "separateAxes", "strength", "strengthMultiplier", "strengthX", "strengthXMultiplier", "strengthY", "strengthYMultiplier", "strengthZ", "strengthZMultiplier", "frequency", "damping", "octaveCount", "octaveMultiplier", "octaveScale", "quality", "scrollSpeed", "scrollSpeedMultiplier", "remapEnabled", "remap", "remapMultiplier", "remapX", "remapXMultiplier", "remapY", "remapYMultiplier", "remapZ", "remapZMultiplier")] + public class ES3Type_NoiseModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_NoiseModule() : base(typeof(UnityEngine.ParticleSystem.NoiseModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.NoiseModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("separateAxes", instance.separateAxes, ES3Type_bool.Instance); + writer.WriteProperty("strength", instance.strength, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("strengthMultiplier", instance.strengthMultiplier, ES3Type_float.Instance); + writer.WriteProperty("strengthX", instance.strengthX, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("strengthXMultiplier", instance.strengthXMultiplier, ES3Type_float.Instance); + writer.WriteProperty("strengthY", instance.strengthY, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("strengthYMultiplier", instance.strengthYMultiplier, ES3Type_float.Instance); + writer.WriteProperty("strengthZ", instance.strengthZ, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("strengthZMultiplier", instance.strengthZMultiplier, ES3Type_float.Instance); + writer.WriteProperty("frequency", instance.frequency, ES3Type_float.Instance); + writer.WriteProperty("damping", instance.damping, ES3Type_bool.Instance); + writer.WriteProperty("octaveCount", instance.octaveCount, ES3Type_int.Instance); + writer.WriteProperty("octaveMultiplier", instance.octaveMultiplier, ES3Type_float.Instance); + writer.WriteProperty("octaveScale", instance.octaveScale, ES3Type_float.Instance); + writer.WriteProperty("quality", instance.quality); + writer.WriteProperty("scrollSpeed", instance.scrollSpeed, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("scrollSpeedMultiplier", instance.scrollSpeedMultiplier, ES3Type_float.Instance); + writer.WriteProperty("remapEnabled", instance.remapEnabled, ES3Type_bool.Instance); + writer.WriteProperty("remap", instance.remap, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("remapMultiplier", instance.remapMultiplier, ES3Type_float.Instance); + writer.WriteProperty("remapX", instance.remapX, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("remapXMultiplier", instance.remapXMultiplier, ES3Type_float.Instance); + writer.WriteProperty("remapY", instance.remapY, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("remapYMultiplier", instance.remapYMultiplier, ES3Type_float.Instance); + writer.WriteProperty("remapZ", instance.remapZ, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("remapZMultiplier", instance.remapZMultiplier, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.NoiseModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.NoiseModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "separateAxes": + instance.separateAxes = reader.Read(ES3Type_bool.Instance); + break; + case "strength": + instance.strength = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "strengthMultiplier": + instance.strengthMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "strengthX": + instance.strengthX = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "strengthXMultiplier": + instance.strengthXMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "strengthY": + instance.strengthY = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "strengthYMultiplier": + instance.strengthYMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "strengthZ": + instance.strengthZ = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "strengthZMultiplier": + instance.strengthZMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "frequency": + instance.frequency = reader.Read(ES3Type_float.Instance); + break; + case "damping": + instance.damping = reader.Read(ES3Type_bool.Instance); + break; + case "octaveCount": + instance.octaveCount = reader.Read(ES3Type_int.Instance); + break; + case "octaveMultiplier": + instance.octaveMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "octaveScale": + instance.octaveScale = reader.Read(ES3Type_float.Instance); + break; + case "quality": + instance.quality = reader.Read(); + break; + case "scrollSpeed": + instance.scrollSpeed = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "scrollSpeedMultiplier": + instance.scrollSpeedMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "remapEnabled": + instance.remapEnabled = reader.Read(ES3Type_bool.Instance); + break; + case "remap": + instance.remap = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "remapMultiplier": + instance.remapMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "remapX": + instance.remapX = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "remapXMultiplier": + instance.remapXMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "remapY": + instance.remapY = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "remapYMultiplier": + instance.remapYMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "remapZ": + instance.remapZ = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "remapZMultiplier": + instance.remapZMultiplier = reader.Read(ES3Type_float.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_NoiseModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_NoiseModule.cs.meta new file mode 100644 index 0000000..8c93046 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_NoiseModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 95fd95820c7c942ef96f463a52c3d4ae +timeCreated: 1519132291 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicMaterial.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicMaterial.cs new file mode 100644 index 0000000..5151333 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicMaterial.cs @@ -0,0 +1,140 @@ +using System; + +namespace ES3Types +{ +#if UNITY_6000_0_OR_NEWER + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("dynamicFriction", "staticFriction", "bounciness", "frictionCombine", "bounceCombine")] + public class ES3Type_PhysicsMaterial : ES3ObjectType + { + public static ES3Type Instance = null; + + public ES3Type_PhysicsMaterial() : base(typeof(UnityEngine.PhysicsMaterial)) { Instance = this; } + + protected override void WriteObject(object obj, ES3Writer writer) + { + var instance = (UnityEngine.PhysicsMaterial)obj; + + writer.WriteProperty("dynamicFriction", instance.dynamicFriction, ES3Type_float.Instance); + writer.WriteProperty("staticFriction", instance.staticFriction, ES3Type_float.Instance); + writer.WriteProperty("bounciness", instance.bounciness, ES3Type_float.Instance); + writer.WriteProperty("frictionCombine", instance.frictionCombine); + writer.WriteProperty("bounceCombine", instance.bounceCombine); + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var instance = (UnityEngine.PhysicsMaterial)obj; + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + + case "dynamicFriction": + instance.dynamicFriction = reader.Read(ES3Type_float.Instance); + break; + case "staticFriction": + instance.staticFriction = reader.Read(ES3Type_float.Instance); + break; + case "bounciness": + instance.bounciness = reader.Read(ES3Type_float.Instance); + break; + case "frictionCombine": + instance.frictionCombine = reader.Read(); + break; + case "bounceCombine": + instance.bounceCombine = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadObject(ES3Reader reader) + { + var instance = new UnityEngine.PhysicsMaterial(); + ReadObject(reader, instance); + return instance; + } + } + + public class ES3Type_PhysicsMaterialArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_PhysicsMaterialArray() : base(typeof(UnityEngine.PhysicsMaterial[]), ES3Type_PhysicsMaterial.Instance) + { + Instance = this; + } + } +#else + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("dynamicFriction", "staticFriction", "bounciness", "frictionCombine", "bounceCombine")] + public class ES3Type_PhysicMaterial : ES3ObjectType + { + public static ES3Type Instance = null; + + public ES3Type_PhysicMaterial() : base(typeof(UnityEngine.PhysicMaterial)) { Instance = this; } + + protected override void WriteObject(object obj, ES3Writer writer) + { + var instance = (UnityEngine.PhysicMaterial)obj; + + writer.WriteProperty("dynamicFriction", instance.dynamicFriction, ES3Type_float.Instance); + writer.WriteProperty("staticFriction", instance.staticFriction, ES3Type_float.Instance); + writer.WriteProperty("bounciness", instance.bounciness, ES3Type_float.Instance); + writer.WriteProperty("frictionCombine", instance.frictionCombine); + writer.WriteProperty("bounceCombine", instance.bounceCombine); + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var instance = (UnityEngine.PhysicMaterial)obj; + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + + case "dynamicFriction": + instance.dynamicFriction = reader.Read(ES3Type_float.Instance); + break; + case "staticFriction": + instance.staticFriction = reader.Read(ES3Type_float.Instance); + break; + case "bounciness": + instance.bounciness = reader.Read(ES3Type_float.Instance); + break; + case "frictionCombine": + instance.frictionCombine = reader.Read(); + break; + case "bounceCombine": + instance.bounceCombine = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadObject(ES3Reader reader) + { + var instance = new UnityEngine.PhysicMaterial(); + ReadObject(reader, instance); + return instance; + } + } + + public class ES3Type_PhysicMaterialArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_PhysicMaterialArray() : base(typeof(UnityEngine.PhysicMaterial[]), ES3Type_PhysicMaterial.Instance) + { + Instance = this; + } + } +#endif +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicMaterial.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicMaterial.cs.meta new file mode 100644 index 0000000..bbc3c12 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicMaterial.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f4b8d9e47b0dc49f48c834a160b6fe55 +timeCreated: 1519132300 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicsMaterial2D.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicsMaterial2D.cs new file mode 100644 index 0000000..0dc2e43 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicsMaterial2D.cs @@ -0,0 +1,59 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("bounciness", "friction")] + public class ES3Type_PhysicsMaterial2D : ES3ObjectType + { + public static ES3Type Instance = null; + + public ES3Type_PhysicsMaterial2D() : base(typeof(UnityEngine.PhysicsMaterial2D)){ Instance = this; } + + protected override void WriteObject(object obj, ES3Writer writer) + { + var instance = (UnityEngine.PhysicsMaterial2D)obj; + + writer.WriteProperty("bounciness", instance.bounciness, ES3Type_float.Instance); + writer.WriteProperty("friction", instance.friction, ES3Type_float.Instance); + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var instance = (UnityEngine.PhysicsMaterial2D)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "bounciness": + instance.bounciness = reader.Read(ES3Type_float.Instance); + break; + case "friction": + instance.friction = reader.Read(ES3Type_float.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadObject(ES3Reader reader) + { + var instance = new UnityEngine.PhysicsMaterial2D(); + ReadObject(reader, instance); + return instance; + } + } + + public class ES3Type_PhysicsMaterial2DArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_PhysicsMaterial2DArray() : base(typeof(UnityEngine.PhysicsMaterial2D[]), ES3Type_PhysicsMaterial2D.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicsMaterial2D.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicsMaterial2D.cs.meta new file mode 100644 index 0000000..765da0f --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_PhysicsMaterial2D.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 456568556c632458bb73fffbb1be0c84 +timeCreated: 1519132284 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Quaternion.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Quaternion.cs new file mode 100644 index 0000000..f2413d0 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Quaternion.cs @@ -0,0 +1,44 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("x", "y", "z", "w")] + public class ES3Type_Quaternion : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Quaternion() : base(typeof(Quaternion)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var casted = (Quaternion)obj; + writer.WriteProperty("x", casted.x, ES3Type_float.Instance); + writer.WriteProperty("y", casted.y, ES3Type_float.Instance); + writer.WriteProperty("z", casted.z, ES3Type_float.Instance); + writer.WriteProperty("w", casted.w, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Quaternion( reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance)); + } + } + + public class ES3Type_QuaternionArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_QuaternionArray() : base(typeof(Quaternion[]), ES3Type_Quaternion.Instance) + { + Instance = this; + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Quaternion.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Quaternion.cs.meta new file mode 100644 index 0000000..bb4c22a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Quaternion.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d9975ecdd621d46a285708463dde7816 +timeCreated: 1519132297 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Rect.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Rect.cs new file mode 100644 index 0000000..1639584 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Rect.cs @@ -0,0 +1,35 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("x", "y", "width", "height")] + public class ES3Type_Rect : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Rect() : base(typeof(UnityEngine.Rect)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Rect)obj; + + writer.WriteProperty("x", instance.x, ES3Type_float.Instance); + writer.WriteProperty("y", instance.y, ES3Type_float.Instance); + writer.WriteProperty("width", instance.width, ES3Type_float.Instance); + writer.WriteProperty("height", instance.height, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Rect(reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance)); + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Rect.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Rect.cs.meta new file mode 100644 index 0000000..1874834 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Rect.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d9b9aa6e5759a4a3e857f90a2de74e5f +timeCreated: 1519132297 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RectTransform.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RectTransform.cs new file mode 100644 index 0000000..24696f4 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RectTransform.cs @@ -0,0 +1,96 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("anchorMin", "anchorMax", "anchoredPosition", "sizeDelta", "pivot", "offsetMin", "offsetMax", "localPosition", "localRotation", "localScale", "parent", "hideFlags")] + public class ES3Type_RectTransform : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_RectTransform() : base(typeof(UnityEngine.RectTransform)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.RectTransform)obj; + + writer.WritePropertyByRef("parent", instance.parent); + writer.WriteProperty("anchorMin", instance.anchorMin, ES3Type_Vector2.Instance); + writer.WriteProperty("anchorMax", instance.anchorMax, ES3Type_Vector2.Instance); + writer.WriteProperty("anchoredPosition", instance.anchoredPosition, ES3Type_Vector2.Instance); + writer.WriteProperty("sizeDelta", instance.sizeDelta, ES3Type_Vector2.Instance); + writer.WriteProperty("pivot", instance.pivot, ES3Type_Vector2.Instance); + writer.WriteProperty("offsetMin", instance.offsetMin, ES3Type_Vector2.Instance); + writer.WriteProperty("offsetMax", instance.offsetMax, ES3Type_Vector2.Instance); + writer.WriteProperty("localPosition", instance.localPosition, ES3Type_Vector3.Instance); + writer.WriteProperty("localRotation", instance.localRotation, ES3Type_Quaternion.Instance); + writer.WriteProperty("localScale", instance.localScale, ES3Type_Vector3.Instance); + writer.WriteProperty("hideFlags", instance.hideFlags); + writer.WriteProperty("siblingIndex", instance.GetSiblingIndex()); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + if (obj.GetType() == typeof(UnityEngine.Transform)) + obj = ((Transform)obj).gameObject.AddComponent(); + + var instance = (UnityEngine.RectTransform)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "anchorMin": + instance.anchorMin = reader.Read(ES3Type_Vector2.Instance); + break; + case "anchorMax": + instance.anchorMax = reader.Read(ES3Type_Vector2.Instance); + break; + case "anchoredPosition": + instance.anchoredPosition = reader.Read(ES3Type_Vector2.Instance); + break; + case "sizeDelta": + instance.sizeDelta = reader.Read(ES3Type_Vector2.Instance); + break; + case "pivot": + instance.pivot = reader.Read(ES3Type_Vector2.Instance); + break; + case "offsetMin": + instance.offsetMin = reader.Read(ES3Type_Vector2.Instance); + break; + case "offsetMax": + instance.offsetMax = reader.Read(ES3Type_Vector2.Instance); + break; + case "localPosition": + instance.localPosition = reader.Read(ES3Type_Vector3.Instance); + break; + case "localRotation": + instance.localRotation = reader.Read(ES3Type_Quaternion.Instance); + break; + case "localScale": + instance.localScale = reader.Read(ES3Type_Vector3.Instance); + break; + case "parent": + instance.SetParent(reader.Read(ES3Type_Transform.Instance)); + break; + case "hierarchyCapacity": + instance.hierarchyCapacity = reader.Read(ES3Type_int.Instance); + break; + case "hideFlags": + instance.hideFlags = reader.Read(); + break; + case "siblingIndex": + instance.SetSiblingIndex(reader.Read()); + break; + default: + reader.Skip(); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RectTransform.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RectTransform.cs.meta new file mode 100644 index 0000000..2386dc3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RectTransform.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 2f7556a7c1bb04cf5979c7e6e65c5e51 +timeCreated: 1519132282 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RenderTexture.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RenderTexture.cs new file mode 100644 index 0000000..5959e92 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RenderTexture.cs @@ -0,0 +1,165 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("width", "height", "dimension", "graphicsFormat", "useMipMap", "vrUsage", "memorylessMode", "format", "stencilFormat", "autoGenerateMips", "volumeDepth", "antiAliasing", "bindTextureMS", "enableRandomWrite", "useDynamicScale", "isPowerOfTwo", "depth", "descriptor", "masterTextureLimit", "anisotropicFiltering", "wrapMode", "wrapModeU", "wrapModeV", "wrapModeW", "filterMode", "anisoLevel", "mipMapBias", "imageContentsHash", "streamingTextureForceLoadAll", "streamingTextureDiscardUnusedMips", "allowThreadedTextureCreation", "name")] + public class ES3Type_RenderTexture : ES3ObjectType + { + public static ES3Type Instance = null; + + public ES3Type_RenderTexture() : base(typeof(UnityEngine.RenderTexture)) { Instance = this; } + + + protected override void WriteObject(object obj, ES3Writer writer) + { + var instance = (UnityEngine.RenderTexture)obj; + + writer.WriteProperty("descriptor", instance.descriptor); + writer.WriteProperty("antiAliasing", instance.antiAliasing, ES3Type_int.Instance); + writer.WriteProperty("isPowerOfTwo", instance.isPowerOfTwo, ES3Type_bool.Instance); + writer.WriteProperty("anisotropicFiltering", UnityEngine.RenderTexture.anisotropicFiltering); + writer.WriteProperty("wrapMode", instance.wrapMode); + writer.WriteProperty("wrapModeU", instance.wrapModeU); + writer.WriteProperty("wrapModeV", instance.wrapModeV); + writer.WriteProperty("wrapModeW", instance.wrapModeW); + writer.WriteProperty("filterMode", instance.filterMode); + writer.WriteProperty("anisoLevel", instance.anisoLevel, ES3Type_int.Instance); + writer.WriteProperty("mipMapBias", instance.mipMapBias, ES3Type_float.Instance); + +#if UNITY_2020_1_OR_NEWER + writer.WriteProperty("streamingTextureForceLoadAll", UnityEngine.RenderTexture.streamingTextureForceLoadAll, ES3Type_bool.Instance); + writer.WriteProperty("streamingTextureDiscardUnusedMips", UnityEngine.RenderTexture.streamingTextureDiscardUnusedMips, ES3Type_bool.Instance); + writer.WriteProperty("allowThreadedTextureCreation", UnityEngine.RenderTexture.allowThreadedTextureCreation, ES3Type_bool.Instance); +#endif + } + + protected override void ReadObject(ES3Reader reader, object obj) + { + var instance = (UnityEngine.RenderTexture)obj; + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + case "width": + instance.width = reader.Read(ES3Type_int.Instance); + break; + case "height": + instance.height = reader.Read(ES3Type_int.Instance); + break; + case "dimension": + instance.dimension = reader.Read(); + break; + case "useMipMap": + instance.useMipMap = reader.Read(ES3Type_bool.Instance); + break; + case "memorylessMode": + instance.memorylessMode = reader.Read(); + break; + case "format": + instance.format = reader.Read(); + break; + case "autoGenerateMips": + instance.autoGenerateMips = reader.Read(ES3Type_bool.Instance); + break; + case "volumeDepth": + instance.volumeDepth = reader.Read(ES3Type_int.Instance); + break; + case "antiAliasing": + instance.antiAliasing = reader.Read(ES3Type_int.Instance); + break; + case "enableRandomWrite": + instance.enableRandomWrite = reader.Read(ES3Type_bool.Instance); + break; + case "isPowerOfTwo": + instance.isPowerOfTwo = reader.Read(ES3Type_bool.Instance); + break; + case "depth": + instance.depth = reader.Read(ES3Type_int.Instance); + break; + case "descriptor": + instance.descriptor = reader.Read(); + break; + case "anisotropicFiltering": + UnityEngine.RenderTexture.anisotropicFiltering = reader.Read(); + break; + case "wrapMode": + instance.wrapMode = reader.Read(); + break; + case "wrapModeU": + instance.wrapModeU = reader.Read(); + break; + case "wrapModeV": + instance.wrapModeV = reader.Read(); + break; + case "wrapModeW": + instance.wrapModeW = reader.Read(); + break; + case "filterMode": + instance.filterMode = reader.Read(); + break; + case "anisoLevel": + instance.anisoLevel = reader.Read(ES3Type_int.Instance); + break; + case "mipMapBias": + instance.mipMapBias = reader.Read(ES3Type_float.Instance); + break; + case "name": + instance.name = reader.Read(ES3Type_string.Instance); + break; + +#if UNITY_2020_1_OR_NEWER + case "vrUsage": + instance.vrUsage = reader.Read(); + break; + case "graphicsFormat": + instance.graphicsFormat = reader.Read(); + break; + case "stencilFormat": + instance.stencilFormat = reader.Read(); + break; + case "bindTextureMS": + instance.bindTextureMS = reader.Read(ES3Type_bool.Instance); + break; + case "useDynamicScale": + instance.useDynamicScale = reader.Read(ES3Type_bool.Instance); + break; + case "streamingTextureForceLoadAll": + UnityEngine.RenderTexture.streamingTextureForceLoadAll = reader.Read(ES3Type_bool.Instance); + break; + case "streamingTextureDiscardUnusedMips": + UnityEngine.RenderTexture.streamingTextureDiscardUnusedMips = reader.Read(ES3Type_bool.Instance); + break; + case "allowThreadedTextureCreation": + UnityEngine.RenderTexture.allowThreadedTextureCreation = reader.Read(ES3Type_bool.Instance); + break; +#endif + + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadObject(ES3Reader reader) + { + var descriptor = reader.ReadProperty(); + var instance = new UnityEngine.RenderTexture(descriptor); + ReadObject(reader, instance); + return instance; + } + } + + + public class ES3Type_RenderTextureArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_RenderTextureArray() : base(typeof(UnityEngine.RenderTexture[]), ES3Type_RenderTexture.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RenderTexture.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RenderTexture.cs.meta new file mode 100644 index 0000000..a0082df --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RenderTexture.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 589b7cd3ec938964197a399aa93bff00 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationBySpeedModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationBySpeedModule.cs new file mode 100644 index 0000000..80a9768 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationBySpeedModule.cs @@ -0,0 +1,82 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "x", "xMultiplier", "y", "yMultiplier", "z", "zMultiplier", "separateAxes", "range")] + public class ES3Type_RotationBySpeedModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_RotationBySpeedModule() : base(typeof(UnityEngine.ParticleSystem.RotationBySpeedModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.RotationBySpeedModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("x", instance.x, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("xMultiplier", instance.xMultiplier, ES3Type_float.Instance); + writer.WriteProperty("y", instance.y, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("yMultiplier", instance.yMultiplier, ES3Type_float.Instance); + writer.WriteProperty("z", instance.z, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("zMultiplier", instance.zMultiplier, ES3Type_float.Instance); + writer.WriteProperty("separateAxes", instance.separateAxes, ES3Type_bool.Instance); + writer.WriteProperty("range", instance.range, ES3Type_Vector2.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.RotationBySpeedModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.RotationBySpeedModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "x": + instance.x = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "xMultiplier": + instance.xMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "y": + instance.y = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "yMultiplier": + instance.yMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "z": + instance.z = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "zMultiplier": + instance.zMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "separateAxes": + instance.separateAxes = reader.Read(ES3Type_bool.Instance); + break; + case "range": + instance.range = reader.Read(ES3Type_Vector2.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationBySpeedModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationBySpeedModule.cs.meta new file mode 100644 index 0000000..1f0bd64 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationBySpeedModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 0a7279e70f63d4a2787489257b5e3ea9 +timeCreated: 1519132280 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationOverLifetimeModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationOverLifetimeModule.cs new file mode 100644 index 0000000..11c3648 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationOverLifetimeModule.cs @@ -0,0 +1,78 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "x", "xMultiplier", "y", "yMultiplier", "z", "zMultiplier", "separateAxes")] + public class ES3Type_RotationOverLifetimeModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_RotationOverLifetimeModule() : base(typeof(UnityEngine.ParticleSystem.RotationOverLifetimeModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.RotationOverLifetimeModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("x", instance.x, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("xMultiplier", instance.xMultiplier, ES3Type_float.Instance); + writer.WriteProperty("y", instance.y, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("yMultiplier", instance.yMultiplier, ES3Type_float.Instance); + writer.WriteProperty("z", instance.z, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("zMultiplier", instance.zMultiplier, ES3Type_float.Instance); + writer.WriteProperty("separateAxes", instance.separateAxes, ES3Type_bool.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.RotationOverLifetimeModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.RotationOverLifetimeModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "x": + instance.x = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "xMultiplier": + instance.xMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "y": + instance.y = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "yMultiplier": + instance.yMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "z": + instance.z = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "zMultiplier": + instance.zMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "separateAxes": + instance.separateAxes = reader.Read(ES3Type_bool.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationOverLifetimeModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationOverLifetimeModule.cs.meta new file mode 100644 index 0000000..6eeaf0a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_RotationOverLifetimeModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e54d1e36b07864bc2b7f33a6182d124b +timeCreated: 1519132299 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Shader.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Shader.cs new file mode 100644 index 0000000..fe02907 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Shader.cs @@ -0,0 +1,61 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("name","maximumLOD")] + public class ES3Type_Shader : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Shader() : base(typeof(UnityEngine.Shader)){ Instance = this; } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Shader)obj; + + writer.WriteProperty("name", instance.name, ES3Type_string.Instance); + writer.WriteProperty("maximumLOD", instance.maximumLOD, ES3Type_int.Instance); + } + + public override object Read(ES3Reader reader) + { + Shader obj = Shader.Find(reader.ReadProperty(ES3Type_string.Instance)); + if(obj == null) + obj = Shader.Find("Diffuse"); + ReadInto(reader, obj); + return obj; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.Shader)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + case "name": + instance.name = reader.Read(ES3Type_string.Instance); + break; + case "maximumLOD": + instance.maximumLOD = reader.Read(ES3Type_int.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } + + public class ES3Type_ShaderArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_ShaderArray() : base(typeof(UnityEngine.Shader[]), ES3Type_Shader.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Shader.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Shader.cs.meta new file mode 100644 index 0000000..c980dbf --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Shader.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 9d42e849fe2364f1b92d805b3fa7f874 +timeCreated: 1519132292 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ShapeModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ShapeModule.cs new file mode 100644 index 0000000..d498cbd --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ShapeModule.cs @@ -0,0 +1,132 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "shapeType", "randomDirectionAmount", "sphericalDirectionAmount", "alignToDirection", "radius", "angle", "length", "box", "meshShapeType", "mesh", "meshRenderer", "skinnedMeshRenderer", "useMeshMaterialIndex", "meshMaterialIndex", "useMeshColors", "normalOffset", "meshScale", "arc")] + public class ES3Type_ShapeModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_ShapeModule() : base(typeof(UnityEngine.ParticleSystem.ShapeModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.ShapeModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("shapeType", instance.shapeType); + writer.WriteProperty("randomDirectionAmount", instance.randomDirectionAmount, ES3Type_float.Instance); + writer.WriteProperty("sphericalDirectionAmount", instance.sphericalDirectionAmount, ES3Type_float.Instance); + writer.WriteProperty("alignToDirection", instance.alignToDirection, ES3Type_bool.Instance); + writer.WriteProperty("radius", instance.radius, ES3Type_float.Instance); + writer.WriteProperty("angle", instance.angle, ES3Type_float.Instance); + writer.WriteProperty("length", instance.length, ES3Type_float.Instance); + #if UNITY_5 + writer.WriteProperty("box", instance.box, ES3Type_Vector3.Instance); + writer.WriteProperty("meshScale", instance.meshScale, ES3Type_float.Instance); + #else + writer.WriteProperty("scale", instance.scale, ES3Type_Vector3.Instance); + #endif + writer.WriteProperty("meshShapeType", instance.meshShapeType); + writer.WritePropertyByRef("mesh", instance.mesh); + writer.WritePropertyByRef("meshRenderer", instance.meshRenderer); + writer.WritePropertyByRef("skinnedMeshRenderer", instance.skinnedMeshRenderer); + writer.WriteProperty("useMeshMaterialIndex", instance.useMeshMaterialIndex, ES3Type_bool.Instance); + writer.WriteProperty("meshMaterialIndex", instance.meshMaterialIndex, ES3Type_int.Instance); + writer.WriteProperty("useMeshColors", instance.useMeshColors, ES3Type_bool.Instance); + writer.WriteProperty("normalOffset", instance.normalOffset, ES3Type_float.Instance); + writer.WriteProperty("arc", instance.arc, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.ShapeModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.ShapeModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "shapeType": + instance.shapeType = reader.Read(); + break; + case "randomDirectionAmount": + instance.randomDirectionAmount = reader.Read(ES3Type_float.Instance); + break; + case "sphericalDirectionAmount": + instance.sphericalDirectionAmount = reader.Read(ES3Type_float.Instance); + break; + case "alignToDirection": + instance.alignToDirection = reader.Read(ES3Type_bool.Instance); + break; + case "radius": + instance.radius = reader.Read(ES3Type_float.Instance); + break; + case "angle": + instance.angle = reader.Read(ES3Type_float.Instance); + break; + case "length": + instance.length = reader.Read(ES3Type_float.Instance); + break; + #if UNITY_5 + case "box": + instance.box = reader.Read(ES3Type_Vector3.Instance); + break; + case "meshScale": + instance.meshScale = reader.Read(ES3Type_float.Instance); + break; + #else + case "scale": + instance.scale = reader.Read(ES3Type_Vector3.Instance); + break; + #endif + case "meshShapeType": + instance.meshShapeType = reader.Read(); + break; + case "mesh": + instance.mesh = reader.Read(); + break; + case "meshRenderer": + instance.meshRenderer = reader.Read(); + break; + case "skinnedMeshRenderer": + instance.skinnedMeshRenderer = reader.Read(); + break; + case "useMeshMaterialIndex": + instance.useMeshMaterialIndex = reader.Read(ES3Type_bool.Instance); + break; + case "meshMaterialIndex": + instance.meshMaterialIndex = reader.Read(ES3Type_int.Instance); + break; + case "useMeshColors": + instance.useMeshColors = reader.Read(ES3Type_bool.Instance); + break; + case "normalOffset": + instance.normalOffset = reader.Read(ES3Type_float.Instance); + break; + case "arc": + instance.arc = reader.Read(ES3Type_float.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ShapeModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ShapeModule.cs.meta new file mode 100644 index 0000000..a9a4b21 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_ShapeModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 238b82f3d73ce4b4ebeb3a5c22eff5e9 +timeCreated: 1519132281 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeBySpeedModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeBySpeedModule.cs new file mode 100644 index 0000000..a37aefc --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeBySpeedModule.cs @@ -0,0 +1,90 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "size", "sizeMultiplier", "x", "xMultiplier", "y", "yMultiplier", "z", "zMultiplier", "separateAxes", "range")] + public class ES3Type_SizeBySpeedModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_SizeBySpeedModule() : base(typeof(UnityEngine.ParticleSystem.SizeBySpeedModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.SizeBySpeedModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("size", instance.size, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("sizeMultiplier", instance.sizeMultiplier, ES3Type_float.Instance); + writer.WriteProperty("x", instance.x, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("xMultiplier", instance.xMultiplier, ES3Type_float.Instance); + writer.WriteProperty("y", instance.y, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("yMultiplier", instance.yMultiplier, ES3Type_float.Instance); + writer.WriteProperty("z", instance.z, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("zMultiplier", instance.zMultiplier, ES3Type_float.Instance); + writer.WriteProperty("separateAxes", instance.separateAxes, ES3Type_bool.Instance); + writer.WriteProperty("range", instance.range, ES3Type_Vector2.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.SizeBySpeedModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.SizeBySpeedModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "size": + instance.size = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "sizeMultiplier": + instance.sizeMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "x": + instance.x = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "xMultiplier": + instance.xMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "y": + instance.y = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "yMultiplier": + instance.yMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "z": + instance.z = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "zMultiplier": + instance.zMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "separateAxes": + instance.separateAxes = reader.Read(ES3Type_bool.Instance); + break; + case "range": + instance.range = reader.Read(ES3Type_Vector2.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeBySpeedModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeBySpeedModule.cs.meta new file mode 100644 index 0000000..9a3e3e9 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeBySpeedModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 553dbccc70c984444a8e1e4fb140acaa +timeCreated: 1519132285 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeOverLifetimeModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeOverLifetimeModule.cs new file mode 100644 index 0000000..9fa4e3c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeOverLifetimeModule.cs @@ -0,0 +1,86 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "size", "sizeMultiplier", "x", "xMultiplier", "y", "yMultiplier", "z", "zMultiplier", "separateAxes")] + public class ES3Type_SizeOverLifetimeModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_SizeOverLifetimeModule() : base(typeof(UnityEngine.ParticleSystem.SizeOverLifetimeModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.SizeOverLifetimeModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("size", instance.size, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("sizeMultiplier", instance.sizeMultiplier, ES3Type_float.Instance); + writer.WriteProperty("x", instance.x, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("xMultiplier", instance.xMultiplier, ES3Type_float.Instance); + writer.WriteProperty("y", instance.y, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("yMultiplier", instance.yMultiplier, ES3Type_float.Instance); + writer.WriteProperty("z", instance.z, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("zMultiplier", instance.zMultiplier, ES3Type_float.Instance); + writer.WriteProperty("separateAxes", instance.separateAxes, ES3Type_bool.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.SizeOverLifetimeModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.SizeOverLifetimeModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "size": + instance.size = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "sizeMultiplier": + instance.sizeMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "x": + instance.x = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "xMultiplier": + instance.xMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "y": + instance.y = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "yMultiplier": + instance.yMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "z": + instance.z = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "zMultiplier": + instance.zMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "separateAxes": + instance.separateAxes = reader.Read(ES3Type_bool.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeOverLifetimeModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeOverLifetimeModule.cs.meta new file mode 100644 index 0000000..a1511c2 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SizeOverLifetimeModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 414f41e320e5f4be0a7aa4b39344c5e4 +timeCreated: 1519132284 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SkinnedMeshRenderer.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SkinnedMeshRenderer.cs new file mode 100644 index 0000000..6c6d3ca --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SkinnedMeshRenderer.cs @@ -0,0 +1,157 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("bones", "rootBone", "quality", "sharedMesh", "updateWhenOffscreen", "skinnedMotionVectors", "localBounds", "enabled", "shadowCastingMode", "receiveShadows", "sharedMaterials", "lightmapIndex", "realtimeLightmapIndex", "lightmapScaleOffset", "motionVectorGenerationMode", "realtimeLightmapScaleOffset", "lightProbeUsage", "lightProbeProxyVolumeOverride", "probeAnchor", "reflectionProbeUsage", "sortingLayerName", "sortingLayerID", "sortingOrder")] + public class ES3Type_SkinnedMeshRenderer : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_SkinnedMeshRenderer() : base(typeof(UnityEngine.SkinnedMeshRenderer)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.SkinnedMeshRenderer)obj; + + writer.WriteProperty("bones", instance.bones); + writer.WriteProperty("rootBone", instance.rootBone); + writer.WriteProperty("quality", instance.quality); + writer.WriteProperty("sharedMesh", instance.sharedMesh); + writer.WriteProperty("updateWhenOffscreen", instance.updateWhenOffscreen, ES3Type_bool.Instance); + writer.WriteProperty("skinnedMotionVectors", instance.skinnedMotionVectors, ES3Type_bool.Instance); + writer.WriteProperty("localBounds", instance.localBounds, ES3Type_Bounds.Instance); + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("shadowCastingMode", instance.shadowCastingMode); + writer.WriteProperty("receiveShadows", instance.receiveShadows, ES3Type_bool.Instance); + writer.WriteProperty("sharedMaterials", instance.sharedMaterials); + writer.WriteProperty("lightmapIndex", instance.lightmapIndex, ES3Type_int.Instance); + writer.WriteProperty("realtimeLightmapIndex", instance.realtimeLightmapIndex, ES3Type_int.Instance); + writer.WriteProperty("lightmapScaleOffset", instance.lightmapScaleOffset, ES3Type_Vector4.Instance); + writer.WriteProperty("motionVectorGenerationMode", instance.motionVectorGenerationMode); + writer.WriteProperty("realtimeLightmapScaleOffset", instance.realtimeLightmapScaleOffset, ES3Type_Vector4.Instance); + writer.WriteProperty("lightProbeUsage", instance.lightProbeUsage); + writer.WriteProperty("lightProbeProxyVolumeOverride", instance.lightProbeProxyVolumeOverride); + writer.WriteProperty("probeAnchor", instance.probeAnchor); + writer.WriteProperty("reflectionProbeUsage", instance.reflectionProbeUsage); + writer.WriteProperty("sortingLayerName", instance.sortingLayerName, ES3Type_string.Instance); + writer.WriteProperty("sortingLayerID", instance.sortingLayerID, ES3Type_int.Instance); + writer.WriteProperty("sortingOrder", instance.sortingOrder, ES3Type_int.Instance); + + // Get BlendShapeWeights + if (instance.sharedMesh != null) + { + var blendShapeWeights = new float[instance.sharedMesh.blendShapeCount]; + for (int i = 0; i < blendShapeWeights.Length; i++) + blendShapeWeights[i] = instance.GetBlendShapeWeight(i); + writer.WriteProperty("blendShapeWeights", blendShapeWeights, ES3Type_floatArray.Instance); + } + + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.SkinnedMeshRenderer)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + + case "bones": + instance.bones = reader.Read(); + break; + case "rootBone": + instance.rootBone = reader.Read(ES3Type_Transform.Instance); + break; + case "quality": + instance.quality = reader.Read(); + break; + case "sharedMesh": + instance.sharedMesh = reader.Read(ES3Type_Mesh.Instance); + break; + case "updateWhenOffscreen": + instance.updateWhenOffscreen = reader.Read(ES3Type_bool.Instance); + break; + case "skinnedMotionVectors": + instance.skinnedMotionVectors = reader.Read(ES3Type_bool.Instance); + break; + case "localBounds": + instance.localBounds = reader.Read(ES3Type_Bounds.Instance); + break; + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "shadowCastingMode": + instance.shadowCastingMode = reader.Read(); + break; + case "receiveShadows": + instance.receiveShadows = reader.Read(ES3Type_bool.Instance); + break; + case "sharedMaterials": + instance.sharedMaterials = reader.Read(); + break; + case "lightmapIndex": + instance.lightmapIndex = reader.Read(ES3Type_int.Instance); + break; + case "realtimeLightmapIndex": + instance.realtimeLightmapIndex = reader.Read(ES3Type_int.Instance); + break; + case "lightmapScaleOffset": + instance.lightmapScaleOffset = reader.Read(ES3Type_Vector4.Instance); + break; + case "motionVectorGenerationMode": + instance.motionVectorGenerationMode = reader.Read(); + break; + case "realtimeLightmapScaleOffset": + instance.realtimeLightmapScaleOffset = reader.Read(ES3Type_Vector4.Instance); + break; + case "lightProbeUsage": + instance.lightProbeUsage = reader.Read(); + break; + case "lightProbeProxyVolumeOverride": + instance.lightProbeProxyVolumeOverride = reader.Read(ES3Type_GameObject.Instance); + break; + case "probeAnchor": + instance.probeAnchor = reader.Read(ES3Type_Transform.Instance); + break; + case "reflectionProbeUsage": + instance.reflectionProbeUsage = reader.Read(); + break; + case "sortingLayerName": + instance.sortingLayerName = reader.Read(ES3Type_string.Instance); + break; + case "sortingLayerID": + instance.sortingLayerID = reader.Read(ES3Type_int.Instance); + break; + case "sortingOrder": + instance.sortingOrder = reader.Read(ES3Type_int.Instance); + break; + case "blendShapeWeights": + var blendShapeWeights = reader.Read(ES3Type_floatArray.Instance); + if (instance.sharedMesh == null) break; + if (blendShapeWeights.Length != instance.sharedMesh.blendShapeCount) + ES3Internal.ES3Debug.LogError("The number of blend shape weights we are loading does not match the number of blend shapes in this SkinnedMeshRenderer's Mesh"); + for (int i = 0; i < blendShapeWeights.Length; i++) + instance.SetBlendShapeWeight(i, blendShapeWeights[i]); + break; + default: + reader.Skip(); + break; + } + } + } + } + + public class ES3Type_SkinnedMeshRendererArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_SkinnedMeshRendererArray() : base(typeof(UnityEngine.SkinnedMeshRenderer[]), ES3Type_SkinnedMeshRenderer.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SkinnedMeshRenderer.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SkinnedMeshRenderer.cs.meta new file mode 100644 index 0000000..be24b9c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SkinnedMeshRenderer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: c60a9d4280a1740059c9784d75d00ad9 +timeCreated: 1519132296 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Sprite.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Sprite.cs new file mode 100644 index 0000000..3f8c1d2 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Sprite.cs @@ -0,0 +1,69 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("texture", "rect", "pivot", "pixelsPerUnit", "border")] + public class ES3Type_Sprite : ES3UnityObjectType + { + public static ES3Type Instance = null; + + public ES3Type_Sprite() : base(typeof(UnityEngine.Sprite)) { Instance = this; } + + protected override void WriteUnityObject(object obj, ES3Writer writer) + { + var instance = (UnityEngine.Sprite)obj; + + writer.WriteProperty("texture", instance.texture, ES3Type_Texture2D.Instance); + writer.WriteProperty("rect", instance.rect, ES3Type_Rect.Instance); + // Pivot value is in pixels, but we require a normalised pivot when using Sprite.Create during loading, so we normalise it here. + writer.WriteProperty("pivot", new Vector2(instance.pivot.x / instance.texture.width, instance.pivot.y / instance.texture.height), ES3Type_Vector2.Instance); + writer.WriteProperty("pixelsPerUnit", instance.pixelsPerUnit, ES3Type_float.Instance); + writer.WriteProperty("border", instance.border, ES3Type_Vector4.Instance); + } + + protected override void ReadUnityObject(ES3Reader reader, object obj) + { + foreach (string propertyName in reader.Properties) + reader.Skip(); + } + + protected override object ReadUnityObject(ES3Reader reader) + { + Texture2D texture = null; + Rect rect = Rect.zero; + Vector2 pivot = Vector2.zero; + float pixelsPerUnit = 0; + Vector4 border = Vector4.zero; + + foreach (string propertyName in reader.Properties) + { + switch (propertyName) + { + case "texture": + texture = reader.Read(ES3Type_Texture2D.Instance); + break; + case "textureRect": + case "rect": + rect = reader.Read(ES3Type_Rect.Instance); + break; + case "pivot": + pivot = reader.Read(ES3Type_Vector2.Instance); + break; + case "pixelsPerUnit": + pixelsPerUnit = reader.Read(ES3Type_float.Instance); + break; + case "border": + border = reader.Read(ES3Type_Vector4.Instance); + break; + default: + reader.Skip(); + break; + } + } + + return Sprite.Create(texture, rect, pivot, pixelsPerUnit, 0, SpriteMeshType.Tight, border); + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Sprite.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Sprite.cs.meta new file mode 100644 index 0000000..24da62d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Sprite.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: dd9947bd586c04b26ae52e608a032be9 +timeCreated: 1519132298 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SpriteRenderer.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SpriteRenderer.cs new file mode 100644 index 0000000..5b53084 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SpriteRenderer.cs @@ -0,0 +1,126 @@ +using System; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("sprite", "color", "flipX", "flipY", "enabled", "shadowCastingMode", "receiveShadows", "sharedMaterials", "lightmapIndex", "realtimeLightmapIndex", "lightmapScaleOffset", "motionVectorGenerationMode", "realtimeLightmapScaleOffset", "lightProbeUsage", "lightProbeProxyVolumeOverride", "probeAnchor", "reflectionProbeUsage", "sortingLayerName", "sortingLayerID", "sortingOrder")] + public class ES3Type_SpriteRenderer : ES3ComponentType + { + public static ES3Type Instance = null; + + public ES3Type_SpriteRenderer() : base(typeof(UnityEngine.SpriteRenderer)) + { + Instance = this; + } + + protected override void WriteComponent(object obj, ES3Writer writer) + { + var instance = (UnityEngine.SpriteRenderer)obj; + + writer.WriteProperty("sprite", instance.sprite); + writer.WriteProperty("color", instance.color, ES3Type_Color.Instance); + writer.WriteProperty("flipX", instance.flipX, ES3Type_bool.Instance); + writer.WriteProperty("flipY", instance.flipY, ES3Type_bool.Instance); + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("shadowCastingMode", instance.shadowCastingMode); + writer.WriteProperty("receiveShadows", instance.receiveShadows, ES3Type_bool.Instance); + writer.WriteProperty("sharedMaterials", instance.sharedMaterials); + writer.WriteProperty("lightmapIndex", instance.lightmapIndex, ES3Type_int.Instance); + writer.WriteProperty("realtimeLightmapIndex", instance.realtimeLightmapIndex, ES3Type_int.Instance); + writer.WriteProperty("lightmapScaleOffset", instance.lightmapScaleOffset, ES3Type_Vector4.Instance); + writer.WriteProperty("motionVectorGenerationMode", instance.motionVectorGenerationMode); + writer.WriteProperty("realtimeLightmapScaleOffset", instance.realtimeLightmapScaleOffset, ES3Type_Vector4.Instance); + writer.WriteProperty("lightProbeUsage", instance.lightProbeUsage); + writer.WriteProperty("lightProbeProxyVolumeOverride", instance.lightProbeProxyVolumeOverride, ES3Type_GameObject.Instance); + writer.WriteProperty("probeAnchor", instance.probeAnchor, ES3Type_Transform.Instance); + writer.WriteProperty("reflectionProbeUsage", instance.reflectionProbeUsage); + writer.WriteProperty("sortingLayerName", instance.sortingLayerName, ES3Type_string.Instance); + writer.WriteProperty("sortingLayerID", instance.sortingLayerID, ES3Type_int.Instance); + writer.WriteProperty("sortingOrder", instance.sortingOrder, ES3Type_int.Instance); + } + + protected override void ReadComponent(ES3Reader reader, object obj) + { + var instance = (UnityEngine.SpriteRenderer)obj; + foreach(string propertyName in reader.Properties) + { + switch(propertyName) + { + case "sprite": + instance.sprite = reader.Read(ES3Type_Sprite.Instance); + break; + case "color": + instance.color = reader.Read(ES3Type_Color.Instance); + break; + case "flipX": + instance.flipX = reader.Read(ES3Type_bool.Instance); + break; + case "flipY": + instance.flipY = reader.Read(ES3Type_bool.Instance); + break; + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "shadowCastingMode": + instance.shadowCastingMode = reader.Read(); + break; + case "receiveShadows": + instance.receiveShadows = reader.Read(ES3Type_bool.Instance); + break; + case "sharedMaterials": + instance.sharedMaterials = reader.Read(); + break; + case "lightmapIndex": + instance.lightmapIndex = reader.Read(ES3Type_int.Instance); + break; + case "realtimeLightmapIndex": + instance.realtimeLightmapIndex = reader.Read(ES3Type_int.Instance); + break; + case "lightmapScaleOffset": + instance.lightmapScaleOffset = reader.Read(ES3Type_Vector4.Instance); + break; + case "motionVectorGenerationMode": + instance.motionVectorGenerationMode = reader.Read(); + break; + case "realtimeLightmapScaleOffset": + instance.realtimeLightmapScaleOffset = reader.Read(ES3Type_Vector4.Instance); + break; + case "lightProbeUsage": + instance.lightProbeUsage = reader.Read(); + break; + case "lightProbeProxyVolumeOverride": + instance.lightProbeProxyVolumeOverride = reader.Read(ES3Type_GameObject.Instance); + break; + case "probeAnchor": + instance.probeAnchor = reader.Read(ES3Type_Transform.Instance); + break; + case "reflectionProbeUsage": + instance.reflectionProbeUsage = reader.Read(); + break; + case "sortingLayerName": + instance.sortingLayerName = reader.Read(ES3Type_string.Instance); + break; + case "sortingLayerID": + instance.sortingLayerID = reader.Read(ES3Type_int.Instance); + break; + case "sortingOrder": + instance.sortingOrder = reader.Read(ES3Type_int.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } + + public class ES3Type_SpriteRendererArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_SpriteRendererArray() : base(typeof(UnityEngine.SpriteRenderer[]), ES3Type_SpriteRenderer.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SpriteRenderer.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SpriteRenderer.cs.meta new file mode 100644 index 0000000..f5cf21b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SpriteRenderer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: f9f81f5e14f124e78877586f0b733864 +timeCreated: 1519132301 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SubEmittersModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SubEmittersModule.cs new file mode 100644 index 0000000..5b5a085 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_SubEmittersModule.cs @@ -0,0 +1,86 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("properties", "systems", "types")] + public class ES3Type_SubEmittersModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_SubEmittersModule() : base(typeof(UnityEngine.ParticleSystem.SubEmittersModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.SubEmittersModule)obj; + + var seProperties = new ParticleSystemSubEmitterProperties[instance.subEmittersCount]; + var seSystems = new ParticleSystem[instance.subEmittersCount]; + var seTypes = new ParticleSystemSubEmitterType[instance.subEmittersCount]; + + for(int i=0; i(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.SubEmittersModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.SubEmittersModule)obj; + + ParticleSystemSubEmitterProperties[] seProperties = null; + ParticleSystem[] seSystems = null; + ParticleSystemSubEmitterType[] seTypes = null; + + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "properties": + seProperties = reader.Read(new ES3ArrayType(typeof(ParticleSystemSubEmitterProperties[]))); + break; + case "systems": + seSystems = reader.Read(); + break; + case "types": + seTypes = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + + if(seProperties != null) + { + for(int i=0; i(ES3Reader reader, object obj) + { + if (obj.GetType () == typeof(Texture2D)) + ES3Type_Texture2D.Instance.ReadInto(reader, obj); + else + throw new NotSupportedException ("Textures of type "+obj.GetType()+" are not currently supported."); + } + + public override object Read(ES3Reader reader) + { + return ES3Type_Texture2D.Instance.Read(reader); + } + } + + public class ES3Type_TextureArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_TextureArray() : base(typeof(UnityEngine.Texture[]), ES3Type_Texture.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Texture.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Texture.cs.meta new file mode 100644 index 0000000..7429668 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Texture.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 615cb2cf345144f858b56b5ff6690a9f +timeCreated: 1536306115 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Texture2D.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Texture2D.cs new file mode 100644 index 0000000..1a06a8c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Texture2D.cs @@ -0,0 +1,132 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("filterMode", "anisoLevel", "wrapMode", "mipMapBias", "rawTextureData")] + public class ES3Type_Texture2D : ES3UnityObjectType + { + public static ES3Type Instance = null; + + public ES3Type_Texture2D() : base(typeof(Texture2D)){ Instance = this; } + + protected override void WriteUnityObject(object obj, ES3Writer writer) + { + var instance = (Texture2D)obj; + + if (!IsReadable(instance)) + { + ES3Internal.ES3Debug.LogWarning("Easy Save cannot save the pixels or properties of this Texture because it is not read/write enabled, so Easy Save will store it by reference instead. To save the pixel data, check the 'Read/Write Enabled' checkbox in the Texture's import settings. Clicking this warning will take you to the Texture, assuming it is not generated at runtime.", instance); + return; + } + + writer.WriteProperty("width", instance.width, ES3Type_int.Instance); + writer.WriteProperty("height", instance.height, ES3Type_int.Instance); + writer.WriteProperty("format", instance.format); + writer.WriteProperty("mipmapCount", instance.mipmapCount, ES3Type_int.Instance); + writer.WriteProperty("filterMode", instance.filterMode); + writer.WriteProperty("anisoLevel", instance.anisoLevel, ES3Type_int.Instance); + writer.WriteProperty("wrapMode", instance.wrapMode); + writer.WriteProperty("mipMapBias", instance.mipMapBias, ES3Type_float.Instance); + writer.WriteProperty("rawTextureData", instance.GetRawTextureData(), ES3Type_byteArray.Instance); + } + + protected override void ReadUnityObject(ES3Reader reader, object obj) + { + if (obj == null) + return; + + if (obj.GetType() == typeof(RenderTexture)) + { + ES3Type_RenderTexture.Instance.ReadInto(reader, obj); + return; + } + + var instance = (Texture2D)obj; + + if (!IsReadable(instance)) + ES3Internal.ES3Debug.LogWarning($"Easy Save cannot load the properties or pixels for this Texture {instance.name} because it is not read/write enabled, so it will be loaded by reference. To load the properties and pixels for this Texture, check the 'Read/Write Enabled' checkbox in its Import Settings.", instance); + + foreach (string propertyName in reader.Properties) + { + // If this Texture isn't readable, we should skip past all of its properties. + if (!IsReadable(instance)) + { + reader.Skip(); + continue; + } + + switch (propertyName) + { + case "filterMode": + instance.filterMode = reader.Read(); + break; + case "anisoLevel": + instance.anisoLevel = reader.Read(ES3Type_int.Instance); + break; + case "wrapMode": + instance.wrapMode = reader.Read(); + break; + case "mipMapBias": + instance.mipMapBias = reader.Read(ES3Type_float.Instance); + break; + case "rawTextureData": + // LoadRawTextureData requires that the correct width, height, TextureFormat and mipMaps are set before being called. + // If an error occurs here, it's likely that we're using LoadInto to load into a Texture which differs in these values. + // In this case, LoadInto should be avoided and Load should be used instead. + if (!IsReadable(instance)) + { + ES3Internal.ES3Debug.LogWarning("Easy Save cannot load the pixels of this Texture because it is not read/write enabled, so Easy Save will ignore the pixel data. To load the pixel data, check the 'Read/Write Enabled' checkbox in the Texture's import settings. Clicking this warning will take you to the Texture, assuming it is not generated at runtime.", instance); + reader.Skip(); + } + else + { + try + { + instance.LoadRawTextureData(reader.Read(ES3Type_byteArray.Instance)); + instance.Apply(); + } + catch(Exception e) + { + ES3Internal.ES3Debug.LogError("Easy Save encountered an error when trying to load this Texture, please see the end of this messasge for the error. This is most likely because the Texture format of the instance we are loading into is different to the Texture we saved.\n"+e.ToString(), instance); + } + } + break; + default: + reader.Skip(); + break; + } + } + } + + protected override object ReadUnityObject(ES3Reader reader) + { + var instance = new Texture2D( reader.Read(ES3Type_int.Instance), // Property name has already been read in ES3UnityObjectType, so we only need to read the value. + reader.ReadProperty(ES3Type_int.Instance), + reader.ReadProperty(), + (reader.ReadProperty(ES3Type_int.Instance) > 1)); + ReadObject(reader, instance); + return instance; + } + + protected bool IsReadable(Texture2D instance) + { + #if UNITY_2018_3_OR_NEWER + return instance != null && instance.isReadable; + #else + return true; + #endif + } + } + + public class ES3Type_Texture2DArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_Texture2DArray() : base(typeof(Texture2D[]), ES3Type_Texture2D.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Texture2D.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Texture2D.cs.meta new file mode 100644 index 0000000..03717ba --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Texture2D.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 86d4ce7d016c24d0489778178716fa3d +timeCreated: 1519132290 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TextureSheetAnimationModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TextureSheetAnimationModule.cs new file mode 100644 index 0000000..2a4608d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TextureSheetAnimationModule.cs @@ -0,0 +1,112 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "numTilesX", "numTilesY", "animation", "useRandomRow", "frameOverTime", "frameOverTimeMultiplier", "startFrame", "startFrameMultiplier", "cycleCount", "rowIndex", "uvChannelMask", "flipU", "flipV")] + public class ES3Type_TextureSheetAnimationModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_TextureSheetAnimationModule() : base(typeof(UnityEngine.ParticleSystem.TextureSheetAnimationModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.TextureSheetAnimationModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("numTilesX", instance.numTilesX, ES3Type_int.Instance); + writer.WriteProperty("numTilesY", instance.numTilesY, ES3Type_int.Instance); + writer.WriteProperty("animation", instance.animation); +#if UNITY_2019_1_OR_NEWER + writer.WriteProperty("useRandomRow", instance.rowMode); +#else + writer.WriteProperty("useRandomRow", instance.useRandomRow, ES3Type_bool.Instance); +#endif + writer.WriteProperty("frameOverTime", instance.frameOverTime, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("frameOverTimeMultiplier", instance.frameOverTimeMultiplier, ES3Type_float.Instance); + writer.WriteProperty("startFrame", instance.startFrame, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("startFrameMultiplier", instance.startFrameMultiplier, ES3Type_float.Instance); + writer.WriteProperty("cycleCount", instance.cycleCount, ES3Type_int.Instance); + writer.WriteProperty("rowIndex", instance.rowIndex, ES3Type_int.Instance); + writer.WriteProperty("uvChannelMask", instance.uvChannelMask); + //writer.WriteProperty("flipU", instance.flipU, ES3Type_float.Instance); + //writer.WriteProperty("flipV", instance.flipV, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.TextureSheetAnimationModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.TextureSheetAnimationModule)obj; + string propertyName; + while ((propertyName = reader.ReadPropertyName()) != null) + { + switch (propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "numTilesX": + instance.numTilesX = reader.Read(ES3Type_int.Instance); + break; + case "numTilesY": + instance.numTilesY = reader.Read(ES3Type_int.Instance); + break; + case "animation": + instance.animation = reader.Read(); + break; +#if UNITY_2019_1_OR_NEWER + case "rowMode": + instance.rowMode = reader.Read(); + break; +#else + case "useRandomRow": + instance.useRandomRow = reader.Read(ES3Type_bool.Instance); + break; +#endif + case "frameOverTime": + instance.frameOverTime = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "frameOverTimeMultiplier": + instance.frameOverTimeMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "startFrame": + instance.startFrame = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "startFrameMultiplier": + instance.startFrameMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "cycleCount": + instance.cycleCount = reader.Read(ES3Type_int.Instance); + break; + case "rowIndex": + instance.rowIndex = reader.Read(ES3Type_int.Instance); + break; + case "uvChannelMask": + instance.uvChannelMask = reader.Read(); + break; + /*case "flipU": + instance.flipU = reader.Read(ES3Type_float.Instance); + break; + case "flipV": + instance.flipV = reader.Read(ES3Type_float.Instance); + break;*/ + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TextureSheetAnimationModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TextureSheetAnimationModule.cs.meta new file mode 100644 index 0000000..9f58775 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TextureSheetAnimationModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 059be233c84494c01be9f48a8be8e89e +timeCreated: 1519132279 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TrailModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TrailModule.cs new file mode 100644 index 0000000..4009e68 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TrailModule.cs @@ -0,0 +1,106 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "ratio", "lifetime", "lifetimeMultiplier", "minVertexDistance", "textureMode", "worldSpace", "dieWithParticles", "sizeAffectsWidth", "sizeAffectsLifetime", "inheritParticleColor", "colorOverLifetime", "widthOverTrail", "widthOverTrailMultiplier", "colorOverTrail")] + public class ES3Type_TrailModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_TrailModule() : base(typeof(UnityEngine.ParticleSystem.TrailModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.TrailModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("ratio", instance.ratio, ES3Type_float.Instance); + writer.WriteProperty("lifetime", instance.lifetime, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("lifetimeMultiplier", instance.lifetimeMultiplier, ES3Type_float.Instance); + writer.WriteProperty("minVertexDistance", instance.minVertexDistance, ES3Type_float.Instance); + writer.WriteProperty("textureMode", instance.textureMode); + writer.WriteProperty("worldSpace", instance.worldSpace, ES3Type_bool.Instance); + writer.WriteProperty("dieWithParticles", instance.dieWithParticles, ES3Type_bool.Instance); + writer.WriteProperty("sizeAffectsWidth", instance.sizeAffectsWidth, ES3Type_bool.Instance); + writer.WriteProperty("sizeAffectsLifetime", instance.sizeAffectsLifetime, ES3Type_bool.Instance); + writer.WriteProperty("inheritParticleColor", instance.inheritParticleColor, ES3Type_bool.Instance); + writer.WriteProperty("colorOverLifetime", instance.colorOverLifetime, ES3Type_MinMaxGradient.Instance); + writer.WriteProperty("widthOverTrail", instance.widthOverTrail, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("widthOverTrailMultiplier", instance.widthOverTrailMultiplier, ES3Type_float.Instance); + writer.WriteProperty("colorOverTrail", instance.colorOverTrail, ES3Type_MinMaxGradient.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.TrailModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.TrailModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "ratio": + instance.ratio = reader.Read(ES3Type_float.Instance); + break; + case "lifetime": + instance.lifetime = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "lifetimeMultiplier": + instance.lifetimeMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "minVertexDistance": + instance.minVertexDistance = reader.Read(ES3Type_float.Instance); + break; + case "textureMode": + instance.textureMode = reader.Read(); + break; + case "worldSpace": + instance.worldSpace = reader.Read(ES3Type_bool.Instance); + break; + case "dieWithParticles": + instance.dieWithParticles = reader.Read(ES3Type_bool.Instance); + break; + case "sizeAffectsWidth": + instance.sizeAffectsWidth = reader.Read(ES3Type_bool.Instance); + break; + case "sizeAffectsLifetime": + instance.sizeAffectsLifetime = reader.Read(ES3Type_bool.Instance); + break; + case "inheritParticleColor": + instance.inheritParticleColor = reader.Read(ES3Type_bool.Instance); + break; + case "colorOverLifetime": + instance.colorOverLifetime = reader.Read(ES3Type_MinMaxGradient.Instance); + break; + case "widthOverTrail": + instance.widthOverTrail = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "widthOverTrailMultiplier": + instance.widthOverTrailMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "colorOverTrail": + instance.colorOverTrail = reader.Read(ES3Type_MinMaxGradient.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TrailModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TrailModule.cs.meta new file mode 100644 index 0000000..bdb0464 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TrailModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 56ad47761f46a452b84d1efde61de80c +timeCreated: 1519132285 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TriggerModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TriggerModule.cs new file mode 100644 index 0000000..20a4a5b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TriggerModule.cs @@ -0,0 +1,70 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "inside", "outside", "enter", "exit", "radiusScale")] + public class ES3Type_TriggerModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_TriggerModule() : base(typeof(UnityEngine.ParticleSystem.TriggerModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.TriggerModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("inside", instance.inside); + writer.WriteProperty("outside", instance.outside); + writer.WriteProperty("enter", instance.enter); + writer.WriteProperty("exit", instance.exit); + writer.WriteProperty("radiusScale", instance.radiusScale, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.TriggerModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.TriggerModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "inside": + instance.inside = reader.Read(); + break; + case "outside": + instance.outside = reader.Read(); + break; + case "enter": + instance.enter = reader.Read(); + break; + case "exit": + instance.exit = reader.Read(); + break; + case "radiusScale": + instance.radiusScale = reader.Read(ES3Type_float.Instance); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TriggerModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TriggerModule.cs.meta new file mode 100644 index 0000000..9aed376 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_TriggerModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7cf3d6f533d04498fb0601796570f998 +timeCreated: 1519132289 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2.cs new file mode 100644 index 0000000..3ba779d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2.cs @@ -0,0 +1,40 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("x", "y")] + public class ES3Type_Vector2 : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Vector2() : base(typeof(Vector2)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Vector2 casted = (Vector2)obj; + writer.WriteProperty("x", casted.x, ES3Type_float.Instance); + writer.WriteProperty("y", casted.y, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Vector2( reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance)); + } + } + + public class ES3Type_Vector2Array : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_Vector2Array() : base(typeof(Vector2[]), ES3Type_Vector2.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2.cs.meta new file mode 100644 index 0000000..6d94ec3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 6cdccaf6dcab94e45931bf15d2a90640 +timeCreated: 1519132287 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2Int.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2Int.cs new file mode 100644 index 0000000..79f8e03 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2Int.cs @@ -0,0 +1,42 @@ +#if UNITY_2017_2_OR_NEWER +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("x", "y")] + public class ES3Type_Vector2Int : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Vector2Int() : base(typeof(Vector2Int)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Vector2Int casted = (Vector2Int)obj; + writer.WriteProperty("x", casted.x, ES3Type_int.Instance); + writer.WriteProperty("y", casted.y, ES3Type_int.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Vector2Int( reader.ReadProperty(ES3Type_int.Instance), + reader.ReadProperty(ES3Type_int.Instance)); + } + } + + public class ES3Type_Vector2IntArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_Vector2IntArray() : base(typeof(Vector2Int[]), ES3Type_Vector2Int.Instance) + { + Instance = this; + } + } +} +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2Int.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2Int.cs.meta new file mode 100644 index 0000000..a8cc143 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector2Int.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: d4ce5526a479a4cdab37fa9c10dc3964 +timeCreated: 1519132287 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3.cs new file mode 100644 index 0000000..dd4da36 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3.cs @@ -0,0 +1,42 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3Properties("x", "y", "z")] + public class ES3Type_Vector3 : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Vector3() : base(typeof(Vector3)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Vector3 casted = (Vector3)obj; + writer.WriteProperty("x", casted.x, ES3Type_float.Instance); + writer.WriteProperty("y", casted.y, ES3Type_float.Instance); + writer.WriteProperty("z", casted.z, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Vector3( reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance)); + } + } + + public class ES3Type_Vector3Array : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_Vector3Array() : base(typeof(Vector3[]), ES3Type_Vector3.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3.cs.meta new file mode 100644 index 0000000..80e53bb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 65ba0614942de49678702985ca4ca357 +timeCreated: 1519132287 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3Int.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3Int.cs new file mode 100644 index 0000000..552a817 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3Int.cs @@ -0,0 +1,44 @@ +#if UNITY_2017_2_OR_NEWER +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("x", "y", "z")] + public class ES3Type_Vector3Int : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Vector3Int() : base(typeof(Vector3Int)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Vector3Int casted = (Vector3Int)obj; + writer.WriteProperty("x", casted.x, ES3Type_int.Instance); + writer.WriteProperty("y", casted.y, ES3Type_int.Instance); + writer.WriteProperty("z", casted.z, ES3Type_int.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Vector3Int( reader.ReadProperty(ES3Type_int.Instance), + reader.ReadProperty(ES3Type_int.Instance), + reader.ReadProperty(ES3Type_int.Instance)); + } + } + + public class ES3Type_Vector3IntArray : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_Vector3IntArray() : base(typeof(Vector3Int[]), ES3Type_Vector3Int.Instance) + { + Instance = this; + } + } +} +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3Int.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3Int.cs.meta new file mode 100644 index 0000000..cf4d455 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector3Int.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 7e3a1d8e6e8144f71a61562fc86b2b2c +timeCreated: 1519132287 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector4.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector4.cs new file mode 100644 index 0000000..5782c43 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector4.cs @@ -0,0 +1,50 @@ +using System; +using UnityEngine; +using System.Collections.Generic; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("x", "y", "z", "w")] + public class ES3Type_Vector4 : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_Vector4() : base(typeof(Vector4)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + Vector4 casted = (Vector4)obj; + writer.WriteProperty("x", casted.x, ES3Type_float.Instance); + writer.WriteProperty("y", casted.y, ES3Type_float.Instance); + writer.WriteProperty("z", casted.z, ES3Type_float.Instance); + writer.WriteProperty("w", casted.w, ES3Type_float.Instance); + } + + public override object Read(ES3Reader reader) + { + return new Vector4( reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance), + reader.ReadProperty(ES3Type_float.Instance)); + } + + public static bool Equals(Vector4 a, Vector4 b) + { + return (Mathf.Approximately(a.x,b.x) && Mathf.Approximately(a.y,b.y) && Mathf.Approximately(a.z,b.z) && Mathf.Approximately(a.w,b.w)); + } + } + + public class ES3Type_Vector4Array : ES3ArrayType + { + public static ES3Type Instance; + + public ES3Type_Vector4Array() : base(typeof(Vector4[]), ES3Type_Vector4.Instance) + { + Instance = this; + } + } +} \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector4.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector4.cs.meta new file mode 100644 index 0000000..8b99b5c --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_Vector4.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 970684b89a8e24102a42f02a5ed59a66 +timeCreated: 1519132292 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_VelocityOverLifetimeModule.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_VelocityOverLifetimeModule.cs new file mode 100644 index 0000000..c72cd72 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_VelocityOverLifetimeModule.cs @@ -0,0 +1,77 @@ +using System; +using UnityEngine; + +namespace ES3Types +{ + [UnityEngine.Scripting.Preserve] + [ES3PropertiesAttribute("enabled", "x", "y", "z", "xMultiplier", "yMultiplier", "zMultiplier", "space")] + public class ES3Type_VelocityOverLifetimeModule : ES3Type + { + public static ES3Type Instance = null; + + public ES3Type_VelocityOverLifetimeModule() : base(typeof(UnityEngine.ParticleSystem.VelocityOverLifetimeModule)) + { + Instance = this; + } + + public override void Write(object obj, ES3Writer writer) + { + var instance = (UnityEngine.ParticleSystem.VelocityOverLifetimeModule)obj; + + writer.WriteProperty("enabled", instance.enabled, ES3Type_bool.Instance); + writer.WriteProperty("x", instance.x, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("y", instance.y, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("z", instance.z, ES3Type_MinMaxCurve.Instance); + writer.WriteProperty("xMultiplier", instance.xMultiplier, ES3Type_float.Instance); + writer.WriteProperty("yMultiplier", instance.yMultiplier, ES3Type_float.Instance); + writer.WriteProperty("zMultiplier", instance.zMultiplier, ES3Type_float.Instance); + writer.WriteProperty("space", instance.space); + } + + public override object Read(ES3Reader reader) + { + var instance = new UnityEngine.ParticleSystem.VelocityOverLifetimeModule(); + ReadInto(reader, instance); + return instance; + } + + public override void ReadInto(ES3Reader reader, object obj) + { + var instance = (UnityEngine.ParticleSystem.VelocityOverLifetimeModule)obj; + string propertyName; + while((propertyName = reader.ReadPropertyName()) != null) + { + switch(propertyName) + { + case "enabled": + instance.enabled = reader.Read(ES3Type_bool.Instance); + break; + case "x": + instance.x = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "y": + instance.y = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "z": + instance.z = reader.Read(ES3Type_MinMaxCurve.Instance); + break; + case "xMultiplier": + instance.xMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "yMultiplier": + instance.yMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "zMultiplier": + instance.zMultiplier = reader.Read(ES3Type_float.Instance); + break; + case "space": + instance.space = reader.Read(); + break; + default: + reader.Skip(); + break; + } + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_VelocityOverLifetimeModule.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_VelocityOverLifetimeModule.cs.meta new file mode 100644 index 0000000..a344c8b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/ES3Type_VelocityOverLifetimeModule.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: a4884364ae36a4916a8bc2bd6e5e9683 +timeCreated: 1519132293 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/UnityObjectType.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/UnityObjectType.cs new file mode 100644 index 0000000..976750e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/UnityObjectType.cs @@ -0,0 +1,18 @@ +using UnityEngine; +using System.Collections.Generic; + +public class UnityObjectType : MonoBehaviour +{ + public List objs; // Assign to this in the Editor + + void Start() + { + if(!ES3.KeyExists("this")) + ES3.Save("this", this); + else + ES3.LoadInto("this", this); + + foreach(var obj in objs) + Debug.Log(obj); + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/UnityObjectType.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/UnityObjectType.cs.meta new file mode 100644 index 0000000..412fb55 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Types/Unity Types/UnityObjectType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 871617aa2d4bcfe428d9625de50b8f65 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web.meta new file mode 100644 index 0000000..0cd695b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9418fe16c22ebe14ba6e2c5796dfd8b4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3Cloud.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3Cloud.cs new file mode 100644 index 0000000..7f7fac2 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3Cloud.cs @@ -0,0 +1,757 @@ +#if !DISABLE_WEB +using System.Collections; +using System.Collections.Generic; +using System.Text; +using UnityEngine; +using UnityEngine.Networking; +using System; +using ES3Internal; + +#if UNITY_VISUAL_SCRIPTING +[Unity.VisualScripting.IncludeInSettings(true)] +#elif BOLT_VISUAL_SCRIPTING +[Ludiq.IncludeInSettings(true)] +#endif +public class ES3Cloud : ES3WebClass +{ + int timeout = 20; + + /// Constructs an new ES3Cloud object with the given URL to an ES3.php file. + /// The URL of the ES3.php file on your server you want to use. + public ES3Cloud(string url, string apiKey) : base(url, apiKey) + { + } + + public ES3Cloud(string url, string apiKey, int timeout) : base(url, apiKey) + { + this.timeout = timeout; + } + + #region Downloaded Data Handling + + /// The encoding to use when encoding and decoding data as strings. + public System.Text.Encoding encoding = System.Text.Encoding.UTF8; + + + private byte[] _data = null; + /// Any downloaded data, if applicable. This may also contain an error message, so you should check the 'ifError' variable before reading data. + public byte[] data + { + get{ return _data; } + } + + /// The downloaded data as text, decoded using the encoding specified by the 'encoding' variable. + public string text + { + get + { + if(data == null) + return null; + return encoding.GetString(data); + } + } + + /// An array of filenames downloaded from the server. This must only be accessed after calling the 'DownloadFilenames' routine. + public string[] filenames + { + get + { + if(data == null || data.Length == 0) + return new string[0]; + return text.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries); + } + + } + + /// A UTC DateTime object representing the date and time a file on the server was last updated. This should only be called after calling the 'DownloadTimestamp' routine. + public DateTime timestamp + { + get + { + if(data == null || data.Length == 0) + return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + + double timestamp; + if(!double.TryParse(text, out timestamp)) + throw new FormatException("Could not convert downloaded data to a timestamp. Data downloaded was: " + text); + + return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp); + } + } + + #endregion + + #region Sync + + /// Synchronises the default file with a file on the server. If the file on the server is newer than the local copy, the local file will be overwritten by the file on the server. Otherwise, the file on the server will be overwritten. + public IEnumerator Sync() + { + return Sync(new ES3Settings(), "", ""); + } + + /// Synchronises a local file with a file on the server. If the file on the server is newer than the local copy, the local file will be overwritten by the file on the server. Otherwise, the file on the server will be overwritten. + /// The relative or absolute path of the local file we want to synchronise. + public IEnumerator Sync(string filePath) + { + return Sync(new ES3Settings(filePath), "", ""); + } + + /// Synchronises a local file with a file on the server. If the file on the server is newer than the local copy, the local file will be overwritten by the file on the server. Otherwise, the file on the server will be overwritten. + /// The relative or absolute path of the local file we want to synchronise. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + public IEnumerator Sync(string filePath, string user) + { + return Sync(new ES3Settings(filePath), user, ""); + } + + /// Synchronises a local file with a file on the server. If the file on the server is newer than the local copy, the local file will be overwritten by the file on the server. Otherwise, the file on the server will be overwritten. + /// The relative or absolute path of the local file we want to synchronise. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + public IEnumerator Sync(string filePath, string user, string password) + { + return Sync(new ES3Settings(filePath), user, password); + } + + /// Synchronises a local file with a file on the server. If the file on the server is newer than the local copy, the local file will be overwritten by the file on the server. Otherwise, the file on the server will be overwritten. + /// The relative or absolute path of the local file we want to synchronise. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + /// The settings we want to use to override the default settings. + public IEnumerator Sync(string filePath, ES3Settings settings) + { + return Sync(new ES3Settings(filePath, settings), "", ""); + } + + /// Synchronises a local file with a file on the server. If the file on the server is newer than the local copy, the local file will be overwritten by the file on the server. Otherwise, the file on the server will be overwritten. + /// The relative or absolute path of the file we want to use. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The settings we want to use to override the default settings. + public IEnumerator Sync(string filePath, string user, ES3Settings settings) + { + return Sync(new ES3Settings(filePath, settings), user, ""); + } + + /// Synchronises a local file with a file on the server. If the file on the server is newer than the local copy, the local file will be overwritten by the file on the server. Otherwise, the file on the server will be overwritten. + /// The relative or absolute path of the local file we want to synchronise. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + /// The settings we want to use to override the default settings. + public IEnumerator Sync(string filePath, string user, string password, ES3Settings settings) + { + return Sync(new ES3Settings(filePath, settings), user, password); + } + + /// Synchronises a local file with a file on the server. If the file on the server is newer than the local copy, the local file will be overwritten by the file on the server. Otherwise, the file on the server will be overwritten. + /// The settings we want to use to override the default settings. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + private IEnumerator Sync(ES3Settings settings, string user, string password) + { + Reset(); + + yield return DownloadFile(settings, user, password, GetFileTimestamp(settings)); + + if(errorCode == 3) + { + // Clear the error. + Reset(); + + // File does not exist on server, or is older than locally stored data, so upload the local file to the server if it exists. + if(ES3.FileExists(settings)) + yield return UploadFile(settings, user, password); + } + + isDone = true; + } + + #endregion + + #region UploadFile + + /// Uploads the default file to the server, overwriting any existing file. + public IEnumerator UploadFile() + { + return UploadFile(new ES3Settings(), "", ""); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// The relative or absolute path of the file we want to use. + public IEnumerator UploadFile(string filePath) + { + return UploadFile(new ES3Settings(filePath), "", ""); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// The relative or absolute path of the file we want to use. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + public IEnumerator UploadFile(string filePath, string user) + { + return UploadFile(new ES3Settings(filePath), user, ""); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// The relative or absolute path of the file we want to use. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + public IEnumerator UploadFile(string filePath, string user, string password) + { + return UploadFile(new ES3Settings(filePath), user, password); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// The relative or absolute path of the file we want to use. + /// The settings we want to use to override the default settings. + public IEnumerator UploadFile(string filePath, ES3Settings settings) + { + return UploadFile(new ES3Settings(filePath, settings), "", ""); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// The relative or absolute path of the file we want to use. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The settings we want to use to override the default settings. + public IEnumerator UploadFile(string filePath, string user, ES3Settings settings) + { + return UploadFile(new ES3Settings(filePath, settings), user, ""); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// The relative or absolute path of the file we want to use. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + /// The settings we want to use to override the default settings. + public IEnumerator UploadFile(string filePath, string user, string password, ES3Settings settings) + { + return UploadFile(new ES3Settings(filePath, settings), user, password); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// An ES3File containing the data we want to upload. + public IEnumerator UploadFile(ES3File es3File) + { + return UploadFile(es3File.GetBytes(), es3File.settings, "", "", DateTimeToUnixTimestamp(DateTime.Now)); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// An ES3File containing the data we want to upload. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + public IEnumerator UploadFile(ES3File es3File, string user) + { + return UploadFile(es3File.GetBytes(), es3File.settings, user, "", DateTimeToUnixTimestamp(DateTime.Now)); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// An ES3File containing the data we want to upload. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + public IEnumerator UploadFile(ES3File es3File, string user, string password) + { + return UploadFile(es3File.GetBytes(), es3File.settings, user, password, DateTimeToUnixTimestamp(DateTime.Now)); + } + + /// Uploads a local file to the server, overwriting any existing file. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + public IEnumerator UploadFile(ES3Settings settings, string user, string password) + { + return UploadFile(ES3.LoadRawBytes(settings), settings, user, password); + } + + public IEnumerator UploadFile(byte[] bytes, ES3Settings settings, string user, string password) + { + return UploadFile(bytes, settings, user, password, DateTimeToUnixTimestamp(ES3.GetTimestamp(settings))); + } + + private IEnumerator UploadFile(byte[] bytes, ES3Settings settings, string user, string password, long fileTimestamp) + { + Reset(); + + var form = CreateWWWForm(); + form.AddField("apiKey", apiKey); + form.AddField("putFile", settings.path); + form.AddField("timestamp", fileTimestamp.ToString()); + form.AddField("user", GetUser(user, password)); + form.AddBinaryData("data", bytes, "data.dat", "multipart/form-data"); + + using(var webRequest = UnityWebRequest.Post(url, form)) + { + webRequest.timeout = timeout; + yield return SendWebRequest(webRequest); + HandleError(webRequest, true); + } + + isDone = true; + } + + #endregion + + #region DownloadFile + + /// Downloads the default file from the server and saves it locally, overwriting the existing local default file. An error is returned if the file does not exist. + public IEnumerator DownloadFile() + { + return DownloadFile(new ES3Settings(), "", "", 0); + } + + /// Downloads a file from the server and saves it locally, overwriting any existing local file. An error is returned if the file does not exist. + /// The relative or absolute path of the file we want to download. + public IEnumerator DownloadFile(string filePath) + { + return DownloadFile(new ES3Settings(filePath), "", "", 0); + } + + /// Downloads a file from the server and saves it locally, overwriting any existing local file. An error is returned if the file does not exist. + /// The relative or absolute path of the file we want to download. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + public IEnumerator DownloadFile(string filePath, string user) + { + return DownloadFile(new ES3Settings(filePath), user, "", 0); + } + + /// Downloads a file from the server and saves it locally, overwriting any existing local file. An error is returned if the file does not exist. + /// The relative or absolute path of the file we want to download. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + public IEnumerator DownloadFile(string filePath, string user, string password) + { + return DownloadFile(new ES3Settings(filePath), user, password, 0); + } + + /// Downloads a file from the server and saves it locally, overwriting any existing local file. An error is returned if the file does not exist. + /// The relative or absolute path of the file we want to download. + /// The settings we want to use to override the default settings. + public IEnumerator DownloadFile(string filePath, ES3Settings settings) + { + return DownloadFile(new ES3Settings(filePath, settings), "", "", 0); + } + + /// Downloads a file from the server and saves it locally, overwriting any existing local file. An error is returned if the file does not exist. + /// The relative or absolute path of the file we want to download. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The settings we want to use to override the default settings. + public IEnumerator DownloadFile(string filePath, string user, ES3Settings settings) + { + return DownloadFile(new ES3Settings(filePath, settings), user, "", 0); + } + + /// Downloads a file from the server and saves it locally, overwriting any existing local file. An error is returned if the file does not exist. + /// The relative or absolute path of the file we want to download. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + /// The settings we want to use to override the default settings. + public IEnumerator DownloadFile(string filePath, string user, string password, ES3Settings settings) + { + return DownloadFile(new ES3Settings(filePath, settings), user, password, 0); + } + + /// Downloads a file from the server and saves it locally, overwriting any existing local file. An error is returned if the file does not exist. + /// The ES3File we want to load our data into. The filename in the settings of the ES3File will be used when downloading. + public IEnumerator DownloadFile(ES3File es3File) + { + return DownloadFile(es3File, "", "", 0); + } + + /// Downloads a file from the server and saves it locally, overwriting any existing local file. An error is returned if the file does not exist. + /// The ES3File we want to load our data into. The filename in the settings of the ES3File will be used when downloading. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + public IEnumerator DownloadFile(ES3File es3File, string user) + { + return DownloadFile(es3File, user, "", 0); + } + + /// Downloads a file from the server and saves it locally, overwriting any existing local file. An error is returned if the file does not exist. + /// The ES3File we want to load our data into. The filename in the settings of the ES3File will be used when downloading. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + public IEnumerator DownloadFile(ES3File es3File, string user, string password) + { + return DownloadFile(es3File, user, password, 0); + } + + private IEnumerator DownloadFile(ES3File es3File, string user, string password, long timestamp) + { + Reset(); + + var form = CreateWWWForm(); + form.AddField("apiKey", apiKey); + form.AddField("getFile", es3File.settings.path); + form.AddField("user", GetUser(user, password)); + if(timestamp > 0) + form.AddField("timestamp", timestamp.ToString()); + + using(var webRequest = UnityWebRequest.Post(url, form)) + { + webRequest.timeout = timeout; + + yield return SendWebRequest(webRequest); + + if(!HandleError(webRequest, false)) + { + if(webRequest.downloadedBytes > 0) + { + es3File.Clear(); + es3File.SaveRaw(webRequest.downloadHandler.data); + } + else + { + error = string.Format("File {0} was not found on the server.", es3File.settings.path); + errorCode = 3; + } + } + } + + isDone = true; + } + + private IEnumerator DownloadFile(ES3Settings settings, string user, string password, long timestamp) + { + Reset(); + + var form = CreateWWWForm(); + form.AddField("apiKey", apiKey); + form.AddField("getFile", settings.path); + form.AddField("user", GetUser(user, password)); + if(timestamp > 0) + form.AddField("timestamp", timestamp.ToString()); + + using(var webRequest = UnityWebRequest.Post(url, form)) + { + webRequest.timeout = timeout; + + yield return SendWebRequest(webRequest); + if(!HandleError(webRequest, false)) + { + if(webRequest.downloadedBytes > 0) + { + ES3.SaveRaw(webRequest.downloadHandler.data, settings); + } + else + { + error = string.Format("File {0} was not found on the server.", settings.path); + errorCode = 3; + } + } + } + + isDone = true; + } + + #endregion + + #region DeleteFile + + /// Deletes the default file from the server. An error is *not* returned if the file does not exist. + public IEnumerator DeleteFile() + { + return DeleteFile(new ES3Settings(), "", ""); + } + + /// Deletes a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + public IEnumerator DeleteFile(string filePath) + { + return DeleteFile(new ES3Settings(filePath), "", ""); + } + + /// Deletes a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + public IEnumerator DeleteFile(string filePath, string user) + { + return DeleteFile(new ES3Settings(filePath), user, ""); + } + + /// Deletes a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + public IEnumerator DeleteFile(string filePath, string user, string password) + { + return DeleteFile(new ES3Settings(filePath), user, password); + } + + /// Deletes a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The settings we want to use to override the default settings. + public IEnumerator DeleteFile(string filePath, ES3Settings settings) + { + return DeleteFile(new ES3Settings(filePath, settings), "", ""); + } + + /// Deletes a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The settings we want to use to override the default settings. + public IEnumerator DeleteFile(string filePath, string user, ES3Settings settings) + { + return DeleteFile(new ES3Settings(filePath, settings), user, ""); + } + + /// Deletes a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + /// The settings we want to use to override the default settings. + public IEnumerator DeleteFile(string filePath, string user, string password, ES3Settings settings) + { + return DeleteFile(new ES3Settings(filePath, settings), user, password); + } + + private IEnumerator DeleteFile(ES3Settings settings, string user, string password) + { + Reset(); + + var form = CreateWWWForm(); + form.AddField("apiKey", apiKey); + form.AddField("deleteFile", settings.path); + form.AddField("user", GetUser(user, password)); + + using(var webRequest = UnityWebRequest.Post(url, form)) + { + webRequest.timeout = timeout; + + yield return SendWebRequest(webRequest); + HandleError(webRequest, true); + } + + isDone = true; + } + + #endregion + + #region RenameFile + + /// Renames a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + public IEnumerator RenameFile(string filePath, string newFilePath) + { + return RenameFile(new ES3Settings(filePath), new ES3Settings(newFilePath), "", ""); + } + + /// Renames a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + public IEnumerator RenameFile(string filePath, string newFilePath, string user) + { + return RenameFile(new ES3Settings(filePath), new ES3Settings(newFilePath), user, ""); + } + + /// Renames a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + public IEnumerator RenameFile(string filePath, string newFilePath, string user, string password) + { + return RenameFile(new ES3Settings(filePath), new ES3Settings(newFilePath), user, password); + } + + /// Renames a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The settings we want to use to override the default settings. + public IEnumerator RenameFile(string filePath, string newFilePath, ES3Settings settings) + { + return RenameFile(new ES3Settings(filePath, settings), new ES3Settings(newFilePath, settings), "", ""); + } + + /// Renames a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The settings we want to use to override the default settings. + public IEnumerator RenameFile(string filePath, string newFilePath, string user, ES3Settings settings) + { + return RenameFile(new ES3Settings(filePath, settings), new ES3Settings(newFilePath, settings), user, ""); + } + + /// Renames a file from the server. An error is *not* returned if the file does not exist. + /// The relative or absolute path of the file we want to delete. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + /// The settings we want to use to override the default settings. + public IEnumerator RenameFile(string filePath, string newFilePath, string user, string password, ES3Settings settings) + { + return RenameFile(new ES3Settings(filePath, settings), new ES3Settings(newFilePath, settings), user, password); + } + + private IEnumerator RenameFile(ES3Settings settings, ES3Settings newSettings, string user, string password) + { + Reset(); + + var form = CreateWWWForm(); + form.AddField("apiKey", apiKey); + form.AddField("renameFile", settings.path); + form.AddField("newFilename", newSettings.path); + form.AddField("user", GetUser(user, password)); + + using(var webRequest = UnityWebRequest.Post(url, form)) + { + webRequest.timeout = timeout; + + yield return SendWebRequest(webRequest); + HandleError(webRequest, true); + } + + isDone = true; + } + + #endregion + + #region DownloadFilenames + + /// Downloads the names of all of the files on the server. Downloaded filenames are stored in the 'filenames' variable of the ES3Cloud object. + /// The unique name of the user we want to find the filenames of. + /// The password of the user we want to find the filenames of. + public IEnumerator DownloadFilenames(string user="", string password="") + { + Reset(); + + var form = CreateWWWForm(); + form.AddField("apiKey", apiKey); + form.AddField("getFilenames", ""); + form.AddField("user", GetUser(user, password)); + + using(var webRequest = UnityWebRequest.Post(url, form)) + { + webRequest.timeout = timeout; + + yield return SendWebRequest(webRequest); + if(!HandleError(webRequest, false)) + _data = webRequest.downloadHandler.data; + } + + isDone = true; + } + + /// Downloads the names of all of the files on the server. Downloaded filenames are stored in the 'filenames' variable of the ES3Cloud object. + /// The unique name of the user we want to find the filenames of. + /// The password of the user we want to find the filenames of. + /// A search pattern containing '%' or '_' wildcards where '%' represents zero, one, or multiple characters, and '_' represents a single character. + public IEnumerator SearchFilenames(string searchPattern, string user="", string password="") + { + Reset(); + + var form = CreateWWWForm(); + form.AddField("apiKey", apiKey); + form.AddField("getFilenames", ""); + form.AddField("user", GetUser(user, password)); + if (!string.IsNullOrEmpty(searchPattern)) + form.AddField("pattern", searchPattern); + + using (var webRequest = UnityWebRequest.Post(url, form)) + { + webRequest.timeout = timeout; + + yield return SendWebRequest(webRequest); + if (!HandleError(webRequest, false)) + _data = webRequest.downloadHandler.data; + } + + isDone = true; + } + + #endregion + + #region DownloadTimestamp + + /// Downloads the timestamp representing when the server file was last updated. The downloaded timestamp is stored in the 'timestamp' variable of the ES3Cloud object. + public IEnumerator DownloadTimestamp() + { + return DownloadTimestamp(new ES3Settings(), "", ""); + } + + /// Downloads the timestamp representing when the server file was last updated. The downloaded timestamp is stored in the 'timestamp' variable of the ES3Cloud object. + /// The relative or absolute path of the file we want to get the timestamp of. + public IEnumerator DownloadTimestamp(string filePath) + { + return DownloadTimestamp(new ES3Settings(filePath), "", ""); + } + + /// Downloads the timestamp representing when the server file was last updated. The downloaded timestamp is stored in the 'timestamp' variable of the ES3Cloud object. + /// The relative or absolute path of the file we want to get the timestamp of. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + public IEnumerator DownloadTimestamp(string filePath, string user) + { + return DownloadTimestamp(new ES3Settings(filePath), user, ""); + } + + /// Downloads the timestamp representing when the server file was last updated. The downloaded timestamp is stored in the 'timestamp' variable of the ES3Cloud object. + /// The relative or absolute path of the file we want to get the timestamp of. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + public IEnumerator DownloadTimestamp(string filePath, string user, string password) + { + return DownloadTimestamp(new ES3Settings(filePath), user, password); + } + + /// Downloads the timestamp representing when the server file was last updated. The downloaded timestamp is stored in the 'timestamp' variable of the ES3Cloud object. + /// The relative or absolute path of the file we want to get the timestamp of. + /// The settings we want to use to override the default settings. + public IEnumerator DownloadTimestamp(string filePath, ES3Settings settings) + { + return DownloadTimestamp(new ES3Settings(filePath, settings), "", ""); + } + + /// Downloads the timestamp representing when the server file was last updated. The downloaded timestamp is stored in the 'timestamp' variable of the ES3Cloud object. + /// The relative or absolute path of the file we want to get the timestamp of. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The settings we want to use to override the default settings. + public IEnumerator DownloadTimestamp(string filePath, string user, ES3Settings settings) + { + return DownloadTimestamp(new ES3Settings(filePath, settings), user, ""); + } + + /// Downloads the timestamp representing when the server file was last updated. The downloaded timestamp is stored in the 'timestamp' variable of the ES3Cloud object. + /// The relative or absolute path of the file we want to get the timestamp of. + /// The unique name of the user this file belongs to, if the file isn't globally accessible. + /// The password of the user this file belongs to. + /// The settings we want to use to override the default settings. + public IEnumerator DownloadTimestamp(string filePath, string user, string password, ES3Settings settings) + { + return DownloadTimestamp(new ES3Settings(filePath, settings), user, password); + } + + private IEnumerator DownloadTimestamp(ES3Settings settings, string user, string password) + { + Reset(); + + var form = CreateWWWForm(); + form.AddField("apiKey", apiKey); + form.AddField("getTimestamp", settings.path); + form.AddField("user", GetUser(user, password)); + + using(var webRequest = UnityWebRequest.Post(url, form)) + { + webRequest.timeout = timeout; + + yield return SendWebRequest(webRequest); + if(!HandleError(webRequest, false)) + _data = webRequest.downloadHandler.data; + } + + isDone = true; + } + + #endregion + + #region Internal Methods + + private long DateTimeToUnixTimestamp(DateTime dt) + { + return Convert.ToInt64((dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds); + } + + private long GetFileTimestamp(ES3Settings settings) + { + return DateTimeToUnixTimestamp(ES3.GetTimestamp(settings)); + } + + protected override void Reset() + { + _data = null; + base.Reset(); + } + + #endregion +} + +#endif \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3Cloud.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3Cloud.cs.meta new file mode 100644 index 0000000..02e505e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3Cloud.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: e639a3698613946f0951d104a492f138 +timeCreated: 1500448165 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3WebClass.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3WebClass.cs new file mode 100644 index 0000000..b9d8465 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3WebClass.cs @@ -0,0 +1,148 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Networking; + +namespace ES3Internal +{ + public class ES3WebClass + { + protected string url; + protected string apiKey; + + protected List> formData = new List>(); + protected UnityWebRequest _webRequest = null; + + + public bool isDone = false; + public float uploadProgress + { + get + { + if(_webRequest == null) + return 0; + else + return _webRequest.uploadProgress; + } + } + + public float downloadProgress + { + get + { + if(_webRequest == null) + return 0; + else + return _webRequest.downloadProgress; + } + } + + #region Error Handling + + /// An error message, if an error occurred. + public string error = null; + /// This is set to true if an error occurred while performing an operation. + public bool isError{ get{ return !string.IsNullOrEmpty(error) || errorCode > 0; } } + /// The error code relating to the error, if one occurred. If it's a server error, this will return the HTTP error code. + public long errorCode = 0; + + public static bool IsNetworkError(UnityWebRequest www) + { +#if UNITY_2020_1_OR_NEWER + return www.result == UnityWebRequest.Result.ConnectionError; +#else + return www.isNetworkError; +#endif + } + +#endregion + + protected ES3WebClass(string url, string apiKey) + { + this.url = url; + this.apiKey = apiKey; + } + +#region Other Methods + + /// Adds POST data to any requests sent by this ES3Cloud object. Use this if you are sending data to a custom script on your server. + /// The name of the POST field we want to add. + /// The string value of the POST field we want to add. + public void AddPOSTField(string fieldName, string value) + { + formData.Add(new KeyValuePair(fieldName, value)); + } + +#endregion + +#region Internal Methods + + protected string GetUser(string user, string password) + { + if(string.IsNullOrEmpty(user)) + return ""; + // Final user string is a combination of the username and password, and hashed if encryption is enabled. + if(!string.IsNullOrEmpty(password)) + user += password; + +#if !DISABLE_ENCRYPTION && !DISABLE_HASHING + user = ES3Internal.ES3Hash.SHA1Hash(user); +#endif + return user; + } + + protected WWWForm CreateWWWForm() + { + var form = new WWWForm(); + foreach(var kvp in formData) + form.AddField(kvp.Key, kvp.Value); + return form; + } + + /* Checks if an error occurred and sets relevant details, and returns true if an error did occur */ + protected bool HandleError(UnityWebRequest webRequest, bool errorIfDataIsDownloaded) + { + if(IsNetworkError(webRequest)) + { + errorCode = 1; + error = "Error: " + webRequest.error; + } + else if(webRequest.responseCode >= 400) + { + errorCode = webRequest.responseCode; + if(string.IsNullOrEmpty(webRequest.downloadHandler.text)) + error = string.Format("Server returned {0} error with no message", webRequest.responseCode); + else + error = webRequest.downloadHandler.text; + } + else if(errorIfDataIsDownloaded && webRequest.downloadedBytes > 0) + { + errorCode = 2; + error = "Server error: '" + webRequest.downloadHandler.text + "'"; + } + else + return false; + return true; + } + + protected IEnumerator SendWebRequest(UnityWebRequest webRequest) + { + _webRequest = webRequest; +#if !UNITY_2017_2_OR_NEWER + yield return webRequest.Send(); +#else + yield return webRequest.SendWebRequest(); +#endif + } + + protected virtual void Reset() + { + error = null; + errorCode = 0; + isDone = false; + } + + +#endregion + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3WebClass.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3WebClass.cs.meta new file mode 100644 index 0000000..c290041 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Web/ES3WebClass.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 338b6919533e14c37afa52e7b0a91a6d +timeCreated: 1502349814 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers.meta new file mode 100644 index 0000000..2f166ef --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c81b45ff1c5b81346b683246219d5357 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3Binary.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3Binary.cs new file mode 100644 index 0000000..cadd1e7 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3Binary.cs @@ -0,0 +1,121 @@ +using System.Collections; +using System.Collections.Generic; +using System; + +namespace ES3Internal +{ + internal enum ES3SpecialByte : byte + { + Null = 0, + Bool = 1, + Byte = 2, + Sbyte = 3, + Char = 4, + Decimal = 5, + Double = 6, + Float = 7, + Int = 8, + Uint = 9, + Long = 10, + Ulong = 11, + Short = 12, + Ushort = 13, + String = 14, + ByteArray = 15, + Collection = 128, + Dictionary = 129, + CollectionItem = 130, + Object = 254, + Terminator = 255 + } + + internal static class ES3Binary + { + internal const string ObjectTerminator = "."; + + internal static readonly Dictionary IdToType = new Dictionary() + { + { ES3SpecialByte.Null, null }, + { ES3SpecialByte.Bool, typeof(bool)}, + { ES3SpecialByte.Byte, typeof(byte)}, + { ES3SpecialByte.Sbyte, typeof(sbyte)}, + { ES3SpecialByte.Char, typeof(char)}, + { ES3SpecialByte.Decimal, typeof(decimal)}, + { ES3SpecialByte.Double, typeof(double)}, + { ES3SpecialByte.Float, typeof(float)}, + { ES3SpecialByte.Int, typeof(int)}, + { ES3SpecialByte.Uint, typeof(uint)}, + { ES3SpecialByte.Long, typeof(long)}, + { ES3SpecialByte.Ulong, typeof(ulong)}, + { ES3SpecialByte.Short, typeof(short)}, + { ES3SpecialByte.Ushort, typeof(ushort)}, + { ES3SpecialByte.String, typeof(string)}, + { ES3SpecialByte.ByteArray, typeof(byte[])} + }; + + internal static readonly Dictionary TypeToId = new Dictionary() + { + { typeof(bool), ES3SpecialByte.Bool}, + { typeof(byte), ES3SpecialByte.Byte}, + { typeof(sbyte), ES3SpecialByte.Sbyte}, + { typeof(char), ES3SpecialByte.Char}, + { typeof(decimal), ES3SpecialByte.Decimal}, + { typeof(double), ES3SpecialByte.Double}, + { typeof(float), ES3SpecialByte.Float}, + { typeof(int), ES3SpecialByte.Int}, + { typeof(uint), ES3SpecialByte.Uint}, + { typeof(long), ES3SpecialByte.Long}, + { typeof(ulong), ES3SpecialByte.Ulong}, + { typeof(short), ES3SpecialByte.Short}, + { typeof(ushort), ES3SpecialByte.Ushort}, + { typeof(string), ES3SpecialByte.String}, + { typeof(byte[]), ES3SpecialByte.ByteArray} + }; + + internal static ES3SpecialByte TypeToByte(Type type) + { + ES3SpecialByte b; + if (TypeToId.TryGetValue(type, out b)) + return b; + return ES3SpecialByte.Object; + } + + internal static Type ByteToType(ES3SpecialByte b) + { + return ByteToType((byte)b); + } + + internal static Type ByteToType(byte b) + { + Type type; + if (IdToType.TryGetValue((ES3SpecialByte)b, out type)) + return type; + return typeof(object); + } + + internal static bool IsPrimitive(ES3SpecialByte b) + { + switch(b) + { + case ES3SpecialByte.Bool: + case ES3SpecialByte.Byte: + case ES3SpecialByte.Sbyte: + case ES3SpecialByte.Char: + case ES3SpecialByte.Decimal: + case ES3SpecialByte.Double: + case ES3SpecialByte.Float: + case ES3SpecialByte.Int: + case ES3SpecialByte.Uint: + case ES3SpecialByte.Long: + case ES3SpecialByte.Ulong: + case ES3SpecialByte.Short: + case ES3SpecialByte.Ushort: + case ES3SpecialByte.String: + case ES3SpecialByte.ByteArray: + return true; + default: + return false; + } + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3Binary.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3Binary.cs.meta new file mode 100644 index 0000000..9019d8b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3Binary.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9398c7a61f9679e41af5e48cac61f763 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3BinaryWriter.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3BinaryWriter.cs new file mode 100644 index 0000000..3850d28 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3BinaryWriter.cs @@ -0,0 +1,4 @@ +/* + * BinaryWriter is not implemented. + * See this post for more info: https://moodkie.com/forum/viewtopic.php?p=7478#p7478 + */ diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3BinaryWriter.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3BinaryWriter.cs.meta new file mode 100644 index 0000000..4b787bf --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3BinaryWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 890d1774e6bacdc43bf99692dfc5360a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3CacheWriter.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3CacheWriter.cs new file mode 100644 index 0000000..537480a --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3CacheWriter.cs @@ -0,0 +1,157 @@ +using System.Collections.Generic; +using System.Collections; +using System.IO; +using System; +using UnityEngine; +using System.Text; +using System.Globalization; + +namespace ES3Internal +{ + internal class ES3CacheWriter : ES3Writer + { + ES3File es3File; + + internal ES3CacheWriter(ES3Settings settings, bool writeHeaderAndFooter, bool mergeKeys) : base(settings, writeHeaderAndFooter, mergeKeys) + { + es3File = new ES3File(settings); + } + + /* User-facing methods used when writing randomly-accessible Key-Value pairs. */ + #region Write(key, value) Methods + + /// Writes a value to the writer with the given key. + /// The key which uniquely identifies this value. + /// The value we want to write. + public override void Write(string key, object value) + { + es3File.Save(key, (T)value); + } + + internal override void Write(string key, Type type, byte[] value) + { + ES3Debug.LogError("Not implemented"); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public override void Write(Type type, string key, object value) + { + es3File.Save(key, value); + } + + #endregion + + + #region WritePrimitive(value) methods. + + internal override void WritePrimitive(int value) { } + internal override void WritePrimitive(float value) { } + internal override void WritePrimitive(bool value) { } + internal override void WritePrimitive(decimal value) { } + internal override void WritePrimitive(double value) { } + internal override void WritePrimitive(long value) { } + internal override void WritePrimitive(ulong value) { } + internal override void WritePrimitive(uint value) { } + internal override void WritePrimitive(byte value) { } + internal override void WritePrimitive(sbyte value) { } + internal override void WritePrimitive(short value) { } + internal override void WritePrimitive(ushort value) { } + internal override void WritePrimitive(char value) { } + internal override void WritePrimitive(byte[] value) { } + + + internal override void WritePrimitive(string value) + { + } + + internal override void WriteNull() + { + } + + #endregion + + #region Format-specific methods + + private static bool CharacterRequiresEscaping(char c) + { + return false; + } + + private void WriteCommaIfRequired() + { + } + + internal override void WriteRawProperty(string name, byte[] value) + { + } + + internal override void StartWriteFile() + { + } + + internal override void EndWriteFile() + { + } + + internal override void StartWriteProperty(string name) + { + base.StartWriteProperty(name); + } + + internal override void EndWriteProperty(string name) + { + } + + internal override void StartWriteObject(string name) + { + } + + internal override void EndWriteObject(string name) + { + } + + internal override void StartWriteCollection() + { + } + + internal override void EndWriteCollection() + { + } + + internal override void StartWriteCollectionItem(int index) + { + } + + internal override void EndWriteCollectionItem(int index) + { + } + + internal override void StartWriteDictionary() + { + } + + internal override void EndWriteDictionary() + { + } + + internal override void StartWriteDictionaryKey(int index) + { + } + + internal override void EndWriteDictionaryKey(int index) + { + } + + internal override void StartWriteDictionaryValue(int index) + { + } + + internal override void EndWriteDictionaryValue(int index) + { + } + + #endregion + + public override void Dispose(){} + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3CacheWriter.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3CacheWriter.cs.meta new file mode 100644 index 0000000..fe20eeb --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3CacheWriter.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 52e4ba456dd1422409a95cdc6bf43f6b +timeCreated: 1499764822 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3JSONWriter.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3JSONWriter.cs new file mode 100644 index 0000000..9e2fc2b --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3JSONWriter.cs @@ -0,0 +1,233 @@ +using System.Collections.Generic; +using System.Collections; +using System.IO; +using System; +using UnityEngine; +using System.Text; +using System.Globalization; + +namespace ES3Internal +{ + internal class ES3JSONWriter : ES3Writer + { + internal StreamWriter baseWriter; + + private bool isFirstProperty = true; + + public ES3JSONWriter(Stream stream, ES3Settings settings) : this(stream, settings, true, true){} + + internal ES3JSONWriter(Stream stream, ES3Settings settings, bool writeHeaderAndFooter, bool mergeKeys) : base(settings, writeHeaderAndFooter, mergeKeys) + { + baseWriter = new StreamWriter(stream); + StartWriteFile(); + } + + #region WritePrimitive(value) methods. + + internal override void WritePrimitive(int value) { baseWriter.Write(value); } + internal override void WritePrimitive(float value) { baseWriter.Write(value.ToString("R", CultureInfo.InvariantCulture)); } + internal override void WritePrimitive(bool value) { baseWriter.Write(value ? "true" : "false"); } + internal override void WritePrimitive(decimal value) { baseWriter.Write(value.ToString(CultureInfo.InvariantCulture)); } + internal override void WritePrimitive(double value) { baseWriter.Write(value.ToString("R", CultureInfo.InvariantCulture)); } + internal override void WritePrimitive(long value) { baseWriter.Write(value); } + internal override void WritePrimitive(ulong value) { baseWriter.Write(value); } + internal override void WritePrimitive(uint value) { baseWriter.Write(value); } + internal override void WritePrimitive(byte value) { baseWriter.Write(System.Convert.ToInt32(value)); } + internal override void WritePrimitive(sbyte value) { baseWriter.Write(System.Convert.ToInt32(value)); } + internal override void WritePrimitive(short value) { baseWriter.Write(System.Convert.ToInt32(value)); } + internal override void WritePrimitive(ushort value) { baseWriter.Write(System.Convert.ToInt32(value)); } + internal override void WritePrimitive(char value) { WritePrimitive( value.ToString() ); } + internal override void WritePrimitive(byte[] value) { WritePrimitive( System.Convert.ToBase64String(value) ); } + + + internal override void WritePrimitive(string value) + { + baseWriter.Write("\""); + + // Escape any quotation marks within the string. + for(int i = 0; i keysToDelete = new HashSet(); + + internal bool writeHeaderAndFooter = true; + internal bool overwriteKeys = true; + + protected int serializationDepth = 0; + + #region ES3Writer Abstract Methods + + internal abstract void WriteNull(); + + internal virtual void StartWriteFile() + { + serializationDepth++; + } + + internal virtual void EndWriteFile() + { + serializationDepth--; + } + + internal virtual void StartWriteObject(string name) + { + serializationDepth++; + } + + internal virtual void EndWriteObject(string name) + { + serializationDepth--; + } + + internal virtual void StartWriteProperty(string name) + { + if (name == null) + throw new ArgumentNullException("Key or field name cannot be NULL when saving data."); + ES3Debug.Log(""+name +" (writing property)", null, serializationDepth); + } + + internal virtual void EndWriteProperty(string name) + { + } + + internal virtual void StartWriteCollection() + { + serializationDepth++; + } + + internal virtual void EndWriteCollection() + { + serializationDepth--; + } + + internal abstract void StartWriteCollectionItem(int index); + internal abstract void EndWriteCollectionItem(int index); + + internal abstract void StartWriteDictionary(); + internal abstract void EndWriteDictionary(); + internal abstract void StartWriteDictionaryKey(int index); + internal abstract void EndWriteDictionaryKey(int index); + internal abstract void StartWriteDictionaryValue(int index); + internal abstract void EndWriteDictionaryValue(int index); + + public abstract void Dispose(); + + #endregion + + #region ES3Writer Interface abstract methods + + internal abstract void WriteRawProperty(string name, byte[] bytes); + + internal abstract void WritePrimitive(int value); + internal abstract void WritePrimitive(float value); + internal abstract void WritePrimitive(bool value); + internal abstract void WritePrimitive(decimal value); + internal abstract void WritePrimitive(double value); + internal abstract void WritePrimitive(long value); + internal abstract void WritePrimitive(ulong value); + internal abstract void WritePrimitive(uint value); + internal abstract void WritePrimitive(byte value); + internal abstract void WritePrimitive(sbyte value); + internal abstract void WritePrimitive(short value); + internal abstract void WritePrimitive(ushort value); + internal abstract void WritePrimitive(char value); + internal abstract void WritePrimitive(string value); + internal abstract void WritePrimitive(byte[] value); + + #endregion + + protected ES3Writer(ES3Settings settings, bool writeHeaderAndFooter, bool overwriteKeys) + { + this.settings = settings; + this.writeHeaderAndFooter = writeHeaderAndFooter; + this.overwriteKeys = overwriteKeys; + } + + /* User-facing methods used when writing randomly-accessible Key-Value pairs. */ + #region Write(key, value) Methods + + internal virtual void Write(string key, Type type, byte[] value) + { + StartWriteProperty(key); + StartWriteObject(key); + WriteType(type); + WriteRawProperty("value", value); + EndWriteObject(key); + EndWriteProperty(key); + MarkKeyForDeletion(key); + } + + /// Writes a value to the writer with the given key. + /// The key which uniquely identifies this value. + /// The value we want to write. + public virtual void Write(string key, object value) + { + if (typeof(T) == typeof(object)) + { + if (value == null) + Write(typeof(System.Object), key, null); + else + Write(value.GetType(), key, value); + } + else + Write(typeof(T), key, value); + } + + /// Writes a value to the writer with the given key, using the given type rather than the generic parameter. + /// The key which uniquely identifies this value. + /// The value we want to write. + /// The type we want to use for the header, and to retrieve an ES3Type. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual void Write(Type type, string key, object value) + { + StartWriteProperty(key); + StartWriteObject(key); + WriteType(type); + WriteProperty("value", value, ES3TypeMgr.GetOrCreateES3Type(type), settings.referenceMode); + EndWriteObject(key); + EndWriteProperty(key); + MarkKeyForDeletion(key); + } + + #endregion + + #region Write(value) & Write(value, ES3Type) Methods + + /// Writes a value to the writer. Note that this should only be called within an ES3Type. + /// The value we want to write. + /// Whether we want to write UnityEngine.Object fields and properties by reference, by value, or both. + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual void Write(object value, ES3.ReferenceMode memberReferenceMode = ES3.ReferenceMode.ByRef) + { + if(value == null){ WriteNull(); return; } + + var type = ES3TypeMgr.GetOrCreateES3Type(value.GetType()); + Write(value, type, memberReferenceMode); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual void Write(object value, ES3Type type, ES3.ReferenceMode memberReferenceMode = ES3.ReferenceMode.ByRef) + { + // Note that we have to check UnityEngine.Object types for null by casting it first, otherwise + // it will always return false. + if (value == null || (ES3Reflection.IsAssignableFrom(typeof(UnityEngine.Object), value.GetType()) && value as UnityEngine.Object == null)) + { + WriteNull(); + return; + } + + // Deal with System.Objects + if (type == null || type.type == typeof(object)) + { + var valueType = value.GetType(); + type = ES3TypeMgr.GetOrCreateES3Type(valueType); + + if(type == null) + throw new NotSupportedException("Types of " + valueType + " are not supported. Please see the Supported Types guide for more information: https://docs.moodkie.com/easy-save-3/es3-supported-types/"); + + if (!type.isCollection && !type.isDictionary) + { + StartWriteObject(null); + WriteType(valueType); + + type.Write(value, this); + + EndWriteObject(null); + return; + } + } + + if(type == null) + throw new ArgumentNullException("ES3Type argument cannot be null."); + if (type.isUnsupported) + { + if(type.isCollection || type.isDictionary) + throw new NotSupportedException(type.type + " is not supported because it's element type is not supported. Please see the Supported Types guide for more information: https://docs.moodkie.com/easy-save-3/es3-supported-types/"); + else + throw new NotSupportedException("Types of " + type.type + " are not supported. Please see the Supported Types guide for more information: https://docs.moodkie.com/easy-save-3/es3-supported-types/"); + } + + if (type.isPrimitive || type.isEnum) + type.Write(value, this); + else if (type.isCollection) + { + StartWriteCollection(); + ((ES3CollectionType)type).Write(value, this, memberReferenceMode); + EndWriteCollection(); + } + else if (type.isDictionary) + { + StartWriteDictionary(); + ((ES3DictionaryType)type).Write(value, this, memberReferenceMode); + EndWriteDictionary(); + } + else + { + if (type.type == typeof(GameObject)) + ((ES3Type_GameObject)type).saveChildren = settings.saveChildren; + + StartWriteObject(null); + + if (type.isES3TypeUnityObject) + ((ES3UnityObjectType)type).WriteObject(value, this, memberReferenceMode); + else + type.Write(value, this); + EndWriteObject(null); + } + } + + internal virtual void WriteRef(UnityEngine.Object obj) + { + WriteRef(obj, ES3ReferenceMgrBase.referencePropertyName); + } + + internal virtual void WriteRef(UnityEngine.Object obj, string propertyName) + { + WriteRef(obj, ES3ReferenceMgrBase.referencePropertyName, ES3ReferenceMgrBase.Current); + } + + internal virtual void WriteRef(UnityEngine.Object obj, string propertyName, ES3ReferenceMgrBase refMgr) + { + if (refMgr == null) + throw new InvalidOperationException($"An Easy Save 3 Manager is required to save references. To add one to your scene, exit playmode and go to Tools > Easy Save 3 > Add Manager to Scene. Object being saved by reference is {obj.GetType()} with name {obj.name}."); + + // Get the reference ID, if it exists, and store it. + long id = refMgr.Get(obj); + // If reference ID doesn't exist, create reference. + if (id == -1) + id = refMgr.Add(obj); + WriteProperty(propertyName, id.ToString()); + } + + #endregion + + /* Writes a property as a name value pair. */ + #region WriteProperty(name, value) methods + + /// Writes a field or property to the writer. Note that this should only be called within an ES3Type. + /// The name of the field or property. + /// The value we want to write. + public virtual void WriteProperty(string name, object value) + { + WriteProperty(name, value, settings.memberReferenceMode); + } + + /// Writes a field or property to the writer. Note that this should only be called within an ES3Type. + /// The name of the field or property. + /// The value we want to write. + /// Whether we want to write the property by reference, by value, or both. + public virtual void WriteProperty(string name, object value, ES3.ReferenceMode memberReferenceMode) + { + if (SerializationDepthLimitExceeded()) + return; + + StartWriteProperty(name); + Write(value, memberReferenceMode); + EndWriteProperty(name); + } + + /// Writes a field or property to the writer. Note that this should only be called within an ES3Type. + /// The name of the field or property. + /// The value we want to write. + public virtual void WriteProperty(string name, object value) + { + WriteProperty(name, value, ES3TypeMgr.GetOrCreateES3Type(typeof(T)), settings.memberReferenceMode); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual void WriteProperty(string name, object value, ES3Type type) + { + WriteProperty(name, value, type, settings.memberReferenceMode); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual void WriteProperty(string name, object value, ES3Type type, ES3.ReferenceMode memberReferenceMode) + { + if (SerializationDepthLimitExceeded()) + return; + + StartWriteProperty(name); + Write(value, type, memberReferenceMode); + EndWriteProperty(name); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual void WritePropertyByRef(string name, UnityEngine.Object value) + { + if (SerializationDepthLimitExceeded()) + return; + + StartWriteProperty(name); + if(value == null) + { + WriteNull(); + return; }; + StartWriteObject(name); + WriteRef(value); + EndWriteObject(name); + EndWriteProperty(name); + } + + /// Writes a private property to the writer. Note that this should only be called within an ES3Type. + /// The name of the property. + /// The object containing the property we want to write. + public void WritePrivateProperty(string name, object objectContainingProperty) + { + var property = ES3Reflection.GetES3ReflectedProperty(objectContainingProperty.GetType(), name); + if(property.IsNull) + throw new MissingMemberException("A private property named "+ name + " does not exist in the type "+objectContainingProperty.GetType()); + WriteProperty(name, property.GetValue(objectContainingProperty), ES3TypeMgr.GetOrCreateES3Type(property.MemberType)); + } + + /// Writes a private field to the writer. Note that this should only be called within an ES3Type. + /// The name of the field. + /// The object containing the property we want to write. + public void WritePrivateField(string name, object objectContainingField) + { + var field = ES3Reflection.GetES3ReflectedMember(objectContainingField.GetType(), name); + if(field.IsNull) + throw new MissingMemberException("A private field named "+ name + " does not exist in the type "+objectContainingField.GetType()); + WriteProperty(name,field.GetValue(objectContainingField), ES3TypeMgr.GetOrCreateES3Type(field.MemberType)); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void WritePrivateProperty(string name, object objectContainingProperty, ES3Type type) + { + var property = ES3Reflection.GetES3ReflectedProperty(objectContainingProperty.GetType(), name); + if(property.IsNull) + throw new MissingMemberException("A private property named "+ name + " does not exist in the type "+objectContainingProperty.GetType()); + WriteProperty(name, property.GetValue(objectContainingProperty), type); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void WritePrivateField(string name, object objectContainingField, ES3Type type) + { + var field = ES3Reflection.GetES3ReflectedMember(objectContainingField.GetType(), name); + if(field.IsNull) + throw new MissingMemberException("A private field named "+ name + " does not exist in the type "+objectContainingField.GetType()); + WriteProperty(name,field.GetValue(objectContainingField), type); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void WritePrivatePropertyByRef(string name, object objectContainingProperty) + { + var property = ES3Reflection.GetES3ReflectedProperty(objectContainingProperty.GetType(), name); + if(property.IsNull) + throw new MissingMemberException("A private property named "+ name + " does not exist in the type "+objectContainingProperty.GetType()); + WritePropertyByRef(name, (UnityEngine.Object)property.GetValue(objectContainingProperty)); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void WritePrivateFieldByRef(string name, object objectContainingField) + { + var field = ES3Reflection.GetES3ReflectedMember(objectContainingField.GetType(), name); + if(field.IsNull) + throw new MissingMemberException("A private field named "+ name + " does not exist in the type "+objectContainingField.GetType()); + WritePropertyByRef(name, (UnityEngine.Object)field.GetValue(objectContainingField)); + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public void WriteType(Type type) + { + WriteProperty(ES3Type.typeFieldName, ES3Reflection.GetTypeString(type)); + } + + #endregion + + #region Create methods + + /// Creates a new ES3Writer. + /// The relative or absolute path of the file we want to write to. + /// The settings we want to use to override the default settings. + public static ES3Writer Create(string filePath, ES3Settings settings) + { + return Create(new ES3Settings(filePath, settings)); + } + + /// Creates a new ES3Writer. + /// The settings we want to use to override the default settings. + public static ES3Writer Create(ES3Settings settings) + { + return Create(settings, true, true, false); + } + + // Implicit Stream Methods. + internal static ES3Writer Create(ES3Settings settings, bool writeHeaderAndFooter, bool overwriteKeys, bool append) + { + var stream = ES3Stream.CreateStream(settings, (append ? ES3FileMode.Append : ES3FileMode.Write)); + if(stream == null) + return null; + return Create(stream, settings, writeHeaderAndFooter, overwriteKeys); + } + + // Explicit Stream Methods. + + internal static ES3Writer Create(Stream stream, ES3Settings settings, bool writeHeaderAndFooter, bool overwriteKeys) + { + if(stream.GetType() == typeof(MemoryStream)) + { + settings = (ES3Settings)settings.Clone(); + settings.location = ES3.Location.InternalMS; + } + + // Get the baseWriter using the given Stream. + if(settings.format == ES3.Format.JSON) + return new ES3JSONWriter(stream, settings, writeHeaderAndFooter, overwriteKeys); + else + return null; + } + + #endregion + + /* + * Checks whether serialization depth limit has been exceeded + */ + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + protected bool SerializationDepthLimitExceeded() + { + if (serializationDepth > settings.serializationDepthLimit) + { + ES3Debug.LogWarning("Serialization depth limit of " + settings.serializationDepthLimit + " has been exceeded, indicating that there may be a circular reference.\nIf this is not a circular reference, you can increase the depth by going to Window > Easy Save 3 > Settings > Advanced Settings > Serialization Depth Limit"); + return true; + } + return false; + } + + /* + * Marks a key for deletion. + * When merging files, keys marked for deletion will not be included. + */ + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public virtual void MarkKeyForDeletion(string key) + { + keysToDelete.Add(key); + } + + /* + * Merges the contents of the non-temporary file with this ES3Writer, + * ignoring any keys which are marked for deletion. + */ + protected void Merge() + { + using(var reader = ES3Reader.Create(settings)) + { + if(reader == null) + return; + Merge(reader); + } + } + + /* + * Merges the contents of the ES3Reader with this ES3Writer, + * ignoring any keys which are marked for deletion. + */ + protected void Merge(ES3Reader reader) + { + foreach(KeyValuePair kvp in reader.RawEnumerator) + if(!keysToDelete.Contains(kvp.Key) || kvp.Value.type == null) // Don't add keys whose data is of a type which no longer exists in the project. + Write(kvp.Key, kvp.Value.type.type, kvp.Value.bytes); + } + + /// Stores the contents of the writer and overwrites any existing keys if overwriting is enabled. + public virtual void Save() + { + Save(overwriteKeys); + } + + /// Stores the contents of the writer and overwrites any existing keys if overwriting is enabled. + /// Whether we should overwrite existing keys. + public virtual void Save(bool overwriteKeys) + { + if(overwriteKeys) + Merge(); + EndWriteFile(); + Dispose(); + + // If we're writing to a location which can become corrupted, rename the backup file to the file we want. + // This prevents corrupt data. + if(settings.location == ES3.Location.File || settings.location == ES3.Location.PlayerPrefs) + ES3IO.CommitBackup(settings); + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3Writer.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3Writer.cs.meta new file mode 100644 index 0000000..e0973a9 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3Writer.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 09319508912db4c13bd924c6dc89f661 +timeCreated: 1499764821 +licenseType: Store +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3XMLWriter.cs b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3XMLWriter.cs new file mode 100644 index 0000000..1556134 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3XMLWriter.cs @@ -0,0 +1,4 @@ +public class ES3XMLWriter +{ + // Not implemented +} diff --git a/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3XMLWriter.cs.meta b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3XMLWriter.cs.meta new file mode 100644 index 0000000..6831603 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Plugins/Easy Save 3/Scripts/Writers/ES3XMLWriter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3bac03a64f52fa94ea3bdcafecad8788 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Scripts.meta b/Assets/SGModule/DataStorage/SGModule/Scripts.meta new file mode 100644 index 0000000..0b656e1 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2c6058521ada9f3418c6e5618c4b3e22 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage.meta b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage.meta new file mode 100644 index 0000000..d83be3e --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3d2e02948d7940b1a968b9d46be0fc4a +timeCreated: 1749436768 \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataKey.cs b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataKey.cs new file mode 100644 index 0000000..5396ebe --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataKey.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; + +namespace SGModule.DataStorage { + /// + /// 数据键的抽象类,提供键名的统一管理。 + /// + public class DataKeyInfo { + public DataKeyInfo(Type type, bool cloudSave = true) { + Type = type; + CloudSave = cloudSave; + } + + /// + /// 数据类型 + /// + public Type Type { + get; + } + + /// + /// 是否需要云端保存 + /// + public bool CloudSave { + get; + } + } + + public static class DataKeyDic { + private static readonly Dictionary _keyDic = new(); + + public static bool Register(string key, bool cloudSave = true) { + if (_keyDic.ContainsKey(key)) { + return false; + } + + _keyDic.Add(key, new DataKeyInfo(typeof(T), cloudSave)); + return true; + } + + public static DataKeyInfo Get(string keyName) { + return _keyDic.GetValueOrDefault(keyName); + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataKey.cs.meta b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataKey.cs.meta new file mode 100644 index 0000000..48b8202 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataKey.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 67e790243cf14564981fd065e9f6ee86 +timeCreated: 1732529768 \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataManager.cs b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataManager.cs new file mode 100644 index 0000000..2929de8 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataManager.cs @@ -0,0 +1,381 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using Newtonsoft.Json; +using SGModule.Common.Base; +using SGModule.Common.Extensions; +using SGModule.Common.Helper; +using UnityEngine; + +namespace SGModule.DataStorage { + /// + /// 数据管理类,基于 Easy Save 实现,提供 JSON 导出功能。 + /// + public class DataManager : SingletonMonoBehaviour { + private const float InitialAutoSaveInterval = 15f; // 初始自动保存间隔 + private const int SaveThreshold = 20; // 自动保存调用计数阈值 + + private static readonly DataStorage _dataVersion = new("DataVersion", 1L); + + private readonly Dictionary _cache = new(); // 数据缓存 + + private readonly HashSet _modifiedKeys = new(); // 记录最近修改的键 + + private Dictionary _cloudData = new(); //云存储数据 + private bool _hasUnsavedChanges; // 是否有未保存的修改 + + private Action _saveCallback; + private int _saveCallCount; // 保存调用计数 + private float _timer; // 自动保存计时器 + + private void Start() { + // ClearAllData(); + StartCoroutine(AutoSaveRoutine()); + } + + + /// + /// Unity 应用暂停或失去焦点时触发保存。 + /// + private void OnApplicationFocus(bool hasFocus) { + if (!hasFocus) { + SaveChange(true); + } + } + + /// + /// Unity 游戏退出时 + /// + private void OnApplicationQuit() { + SaveChange(true); + } + + private IEnumerator AutoSaveRoutine() { + var lastTime = Time.time; + + var wait = new WaitForSeconds(3f); // 每3秒检查一次 + while (true) { + yield return wait; + + var currentTime = Time.time; + _timer += currentTime - lastTime; + lastTime = currentTime; + if (_timer >= InitialAutoSaveInterval || _saveCallCount >= SaveThreshold) { + _timer = 0f; + _saveCallCount = 0; + SaveChange(false); + } + } + } + + + public void Init() { + GMTool.Instance.AddItem(new GMToolItem(GUIType.Separator, () => "数据模块")); + GMTool.Instance.AddItem(new GMToolItem(GUIType.Button, () => "清空数据", s => { + ClearAllData(); + })); + } + + /// + /// 如果有未保存的修改,则执行保存。 + /// + private void SaveChange(bool onQuit) { + Log.DataStorage.Info($"SaveChange trigger. hasUnsavedChanges:{_hasUnsavedChanges}, onQuit:{onQuit}"); + if (!_hasUnsavedChanges) { + return; + } + + _dataVersion.Value++; + _hasUnsavedChanges = false; // 重置修改标记 + + FlushAutoSave(); + + // 控制保存回调频率 + if (onQuit || _dataVersion.Value % 2 == 0) { + Log.DataStorage.Info("SaveChange Callback trigger."); + _saveCallback?.Invoke(ExportToJson(), _dataVersion.Value, onQuit); + } + } + + /// + /// 同步缓存中的所有修改到磁盘。 + /// + private void FlushAutoSave() { + foreach (var key in _modifiedKeys) { + if (_cache.TryGetValue(key, out var value)) { + ES3.Save(key, value); + } + } + + _modifiedKeys.Clear(); // 清空自动保存的修改记录 + } + + + /// + /// 保存数据到指定键,并更新缓存。 + /// + /// 数据类型 + /// 存储键 + /// 要保存的数据 + public void SaveData(string key, T data) { + // 直接更新缓存 + _cache[key] = data; + + // 记录修改的键(避免重复添加) + if (_modifiedKeys.Add(key)) { + _hasUnsavedChanges = true; + } + + _saveCallCount++; // 记录保存调用次数 + } + + /// + /// 加载指定键的数据,优先从缓存中获取。 + /// + /// 数据类型 + /// 存储键 + /// 默认值 + /// 加载的数据 + public T LoadData(string key, T defaultValue = default) { + // 1. 缓存读取 + if (_cache.TryGetValue(key, out var cached)) { + return cached is T t ? t : cached.As() ?? defaultValue; + } + + + // 2. 云端数据读取 + if (_cloudData != null && _cloudData.TryGetValue(key, out var value)) { + var val = value.As(); + if (val != null) { + _cache[key] = val; + return val; + } + + Log.DataStorage.Error($"云端数据类型不匹配: key={key}, value={value}, 目标类型={typeof(T)}, 实际类型={value?.GetType()}"); + } + + + // 3. 从本地 ES3 读取 + if (ES3.KeyExists(key)) { + try { + var result = ES3.Load(key).As(); + if (result != null) { + _cache[key] = result; + return result; + } + } + catch (Exception e) { + Log.DataStorage.Error($"{key} 加载失败: {e.Message}"); + } + } + + _cache[key] = defaultValue; + return defaultValue; + } + + + /// + /// 检查指定键是否存在(优先检查缓存)。 + /// + /// 存储键 + /// 是否存在 + public bool KeyExists(string key) { + return _cache.ContainsKey(key) || ES3.KeyExists(key); + } + + /// + /// 删除指定键的数据,并更新缓存。 + /// + /// 存储键 + public void DeleteKey(string key) { + _cache.Remove(key); + _modifiedKeys.Remove(key); // 删除自动保存记录 + + if (ES3.KeyExists(key)) { + ES3.DeleteKey(key); + } + } + + /// + /// 清空存储文件。 + /// + public void ClearAllData() { + if (!ES3.FileExists()) { + return; + } + + ES3.DeleteFile(); + _cache.Clear(); + _modifiedKeys.Clear(); // 清空自动保存记录 + } + + + /// + /// 将存储文件中的所有键值对导出为 JSON 字符串 + /// + private static string ExportToJson() { + if (!ES3.FileExists()) { + Log.DataStorage.Warning("ES3 Save file does not exist."); + return null; + } + + var allKeys = ES3.GetKeys(); + var dataDict = new Dictionary(); + + foreach (var key in allKeys) { + // 添加空值检查 + if (key == null) { + Log.DataStorage.Warning("Found null key in ES3 storage, skipping..."); + continue; + } + + // 验证键的格式 + if (string.IsNullOrEmpty(key.Trim())) { + Log.DataStorage.Warning($"Found empty or whitespace key in ES3 storage, skipping..."); + continue; + } + + if (DataKeyDic.Get(key)?.CloudSave != true) { + continue; + } + + try { + var value = ES3.Load(key); + if (value != null) { + dataDict[key] = value; + } else { + Log.DataStorage.Warning($"Loaded null value for key: {key}, skipping..."); + } + } + catch (Exception e) { + Log.DataStorage.Error($"Failed to load key {key}: {e.Message}"); + // 不重新抛出异常,继续处理其他键 + continue; + } + } + + // 使用 Newtonsoft.Json 序列化为 JSON 字符串 + return JsonConvert.SerializeObject(dataDict); + } + + + + /// + /// 从 JSON 字符串导入数据 + /// + public void ImportFromJson(string json, long version) { + Log.DataStorage.Info($"云端数据版本: {version},本地数据版本: {_dataVersion.Value} ,数据: {json}"); + _cloudData.Clear(); + + if (string.IsNullOrEmpty(json) || version < 0) { + Log.DataStorage.Warning("Invalid json or version for import"); + return; + } + + if (version >= _dataVersion.Value) { + _cloudData = JsonConvert.DeserializeObject>(json); + + // 验证并过滤空键 + if (_cloudData != null) { + var validCloudData = new Dictionary(); + foreach (var kv in _cloudData) { + if (kv.Key != null) { + validCloudData[kv.Key] = kv.Value; + } else { + Log.DataStorage.Warning("Found null key in imported JSON, skipping..."); + } + } + _cloudData = validCloudData; + } + + // 本地数据比云端的版低, 将云端数据保存到本地 + if (version > _dataVersion.Value) { + RestoreCloudDataToES3(); + _dataVersion.Value = version; + } + + return; + } + + // 本地数据比云端的版本高, 触发保存回调上传本地数据到云端 + _saveCallback?.Invoke(ExportToJson(), _dataVersion.Value, false); + } + + private void RestoreCloudDataToES3() { + if (_cloudData == null) { + Log.DataStorage.Warning("Cloud data is null, skipping restore"); + return; + } + + foreach (var kv in _cloudData) { + // 确保键不为空 + if (kv.Key == null) { + Log.DataStorage.Warning("Found null key in cloud data, skipping..."); + continue; + } + + var type = DataKeyDic.Get(kv.Key)?.Type; + if (type == null) { + Log.DataStorage.Warning($"云端数据 key={kv.Key} 未注册类型,跳过保存"); + continue; + } + + try { + ES3.Save(kv.Key, kv.Value.As(targetType: type)); + } + catch (Exception e) { + Log.DataStorage.Error($"Failed to save cloud data key {kv.Key}: {e.Message}"); + } + } + } + + + /// + /// 添加保存时回调 + /// + /// + public void AddSaveCallback(Action saveCallback) { + _saveCallback += saveCallback; + } + + /// + /// 清空保存时回调 + /// + public void ClearSaveCallback() { + _saveCallback = null; + } + + /// + /// 移除保存回调 + /// + /// + public void RemoveSaveCallback(Action saveCallback) { + _saveCallback -= saveCallback; + } + + + /// + /// 打印存储文件的所有键值(调试用)。 + /// + public void DebugAllKeys() { + Log.DataStorage.Info("DebugAllKeys Start"); + foreach (var key in ES3.GetKeys()) { + Log.DataStorage.Info($"Key: {key}, Value: {ES3.Load(key)}"); + } + + Log.DataStorage.Info("DebugAllKeys End"); + } + + /// + /// 调试用:打印缓存中的所有数据。 + /// + public void DebugCache() { + Log.DataStorage.Info("DebugCache Start"); + foreach (var kvp in _cache) { + Log.DataStorage.Info($"Cache Key: {kvp.Key}, Value: {kvp.Value}"); + } + + Log.DataStorage.Info("DebugCache End"); + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataManager.cs.meta b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataManager.cs.meta new file mode 100644 index 0000000..a6df658 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 8bba5cfb80ce444a83615209cce62c41 +timeCreated: 1732247748 \ No newline at end of file diff --git a/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataStorage.cs b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataStorage.cs new file mode 100644 index 0000000..42446d3 --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataStorage.cs @@ -0,0 +1,50 @@ +using System; +using SGModule.Common.Helper; + +namespace SGModule.DataStorage { + public class DataStorage { + private readonly T _defaultValue; + private readonly string _key; + private readonly Action _onChange; + + public DataStorage(string key, T defaultValue = default, Action onChange = null, bool cloudSave = true) { + if (!DataKeyDic.Register(key, cloudSave)) { + throw new Exception($"Key {key} already exists."); + } + + _key = key; + _defaultValue = defaultValue; + _onChange = onChange; + } + + public T Value { + get => DataManager.Instance.LoadData(_key, _defaultValue); + set => SaveAndDispatch(value); + } + + /// + /// 手动触发保存(即使数据本身未变更) + /// + public void Save() { + SaveAndDispatch(Value, true); + } + + /// + /// 更新值并创建变更追踪,分发并保存 + /// + private void SaveAndDispatch(T newValue, bool forceSave = false) { + var oldValue = Value; + + // 如果不强制保存且值没有变动,直接返回 + if (!forceSave && CommonUtils.DeepEquals(oldValue, newValue)) { + return; + } + + // 分发变更通知(old -> new) + _onChange?.Invoke(oldValue, newValue); + + // 保存新值 + DataManager.Instance.SaveData(_key, newValue); + } + } +} diff --git a/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataStorage.cs.meta b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataStorage.cs.meta new file mode 100644 index 0000000..bf6376d --- /dev/null +++ b/Assets/SGModule/DataStorage/SGModule/Scripts/DataStorage/DataStorage.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6ae1c9cdc59347df87f98bb709968090 +timeCreated: 1749437333 \ No newline at end of file diff --git a/Assets/SGModule/MarkdownKit.meta b/Assets/SGModule/MarkdownKit.meta new file mode 100644 index 0000000..5445234 --- /dev/null +++ b/Assets/SGModule/MarkdownKit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f724f31e8502ac94ca98afaaa2cb0d4e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/MarkdownKit/README.md b/Assets/SGModule/MarkdownKit/README.md new file mode 100644 index 0000000..f7d27b6 --- /dev/null +++ b/Assets/SGModule/MarkdownKit/README.md @@ -0,0 +1,153 @@ +# 📘 MarkdownDisplayToolkit Md转换模块 + +**核心功能**: + +- 🌐 支持从网络下载 Markdown 文本数据 +- 🧱 自动按标题分割 Markdown 文本 +- 🔄 将 Markdown 转换为 FairyGUI 支持的 UBB 富文本格式 +- 🎨 支持标准富文本格式转换 +- 🪄 直接在指定 FairyGUI 节点下创建并展示富文本内容 + +------ + +## 🚀 快速开始 + +### 1️⃣ 引用说明 + +本模块依赖通用模块中的单例基类,使用前需引入通用模块。 + +### 2️⃣ 基础使用流程 + +```c# +// 1. 加载 Markdown 内容(尽可能早的拉取) +MarkdownKit.Instance.LoadText("privacy", "https://www.moggyfuzz.com/privacy.md"); +MarkdownKit.Instance.LoadText("user", "https://www.moggyfuzz.com/user.md"); + + +// 2. 在 FairyGUI 上展示内容 +var color = new Color(159 / 255f, 120 / 255f, 102 / 255f, 1f); +MarkdownKit.Instance.ShowAsRichText(oneFGUIComponent, BisTerm ? "user" : "privacy", color, (success, state) => { + if (success) { + Debug.Log("✅ 内容加载成功!当前状态:" + state); + } + else { + Debug.LogError("❌ 内容加载失败!当前状态:" + state); + } +}, 44); + +``` + +------ + +## 🛠️ 详细功能说明 + +### 📥 加载功能 + +- 使用 `LoadText(string key, string url, int textSize = 40)` 进行加载 +- 自动下载,状态可查询(见下方 API) + +------ + +### 📤 内容展示 + +**参数说明**: + +| 参数名 | 说明 | +| ---------- | -------------------------------------------------- | +| `parent` | 父节点容器(FairyGUI) | +| `key` | 唯一键名,与 `LoadText` 保持一致 | +| `color` | 文本颜色 | +| `callback` | 状态回调 `(bool success, MarkdownTextState state)` | +| `textSize` | (可选)自定义字体大小(默认 40) | + +**回调状态说明**: + +| 状态 | 说明 | +| ------------- | -------------------------- | +| `Complete` | ✅ 内容已加载并展示完成 | +| `Downloading` | 🔄 正在下载中 | +| `Exception` | ⚠️ 下载失败,将自动重试一次 | + +------ + +## 📚 API 参考 + +### 📑 获取富文本内容 + +```csharp +List GetText(string key, Action> onComplete, int textSize = 40) +``` + +------ + +### 🧐 查询当前状态 + +```csharp +MarkdownTextState GetState(string key) +``` + +------ + +### 📦 获取完整数据 + +```csharp +MarkdownData GetData(string key) +``` + +**返回字段说明**: + +- 📎 URL 地址 +- 🔁 当前状态 +- 📄 原始 Markdown 文本 +- ✂️ 分割后的段落列表 +- 🎨 转换后的富文本列表 +- 🖋️ 文字大小等配置信息 + +------ + +## 💡 最佳实践 + +### ✅ 1. 容器选择 + +- 推荐使用可滚动的 FairyGUI 容器 +- 确保容器有足够的展示空间 + +------ + +### ⚠️ 2. 错误处理建议 + +```csharp +MarkdownKit.Instance.ShowAsRichText( + parent, + "tutorial", + Color.black, + (success, state) => { + if (!success && state == MarkdownTextState.Exception) { + // 显示重试按钮或错误提示 + } + } +); +``` + +------ + +### 🧑‍🎨 3. 样式定制 + +```csharp +MarkdownKit.Instance.ShowAsRichText( + scrollPane, + "tutorial", + new Color(0.1f, 0.1f, 0.1f), // 深灰色文字 + null, + 36 // 更小的文字 +); +``` + +------ + +## 📌 注意事项 + +- ⏱ 网络错误会自动重试一次 +- 🧹 所有 FairyGUI 元素会正确释放 +- 🧠 内部管理已加载内容的内存占用 + diff --git a/Assets/SGModule/MarkdownKit/README.md.meta b/Assets/SGModule/MarkdownKit/README.md.meta new file mode 100644 index 0000000..9c0bf50 --- /dev/null +++ b/Assets/SGModule/MarkdownKit/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5ac0c3ec5384654458c45a41b840d4b2 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/MarkdownKit/SGModule.meta b/Assets/SGModule/MarkdownKit/SGModule.meta new file mode 100644 index 0000000..19e3a2e --- /dev/null +++ b/Assets/SGModule/MarkdownKit/SGModule.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6c3e7d7920b316840a92d866eaa9969e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/MarkdownKit/SGModule/Scripts.meta b/Assets/SGModule/MarkdownKit/SGModule/Scripts.meta new file mode 100644 index 0000000..7454951 --- /dev/null +++ b/Assets/SGModule/MarkdownKit/SGModule/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 23df540381cb5ee4c978714ae3117b82 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/MarkdownKit/SGModule/Scripts/MakdownData.cs b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MakdownData.cs new file mode 100644 index 0000000..e23b0d0 --- /dev/null +++ b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MakdownData.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; + +namespace SGModule.MarkdownKit { + public class MarkdownData { + public int BaseSize; + public List MarkdownTextList; + public Action> OnComplete; + public List RichTextList; + public MarkdownTextState State; + public string Text; + public string Url; + } + + public enum MarkdownTextState { + None, + Downloading, + Complete, + Exception + } + + public static class MarkdownDataMgr { + private static readonly Dictionary _markdownData = new(); + + /// + /// 获取完整数据 + /// + /// + /// + public static MarkdownData GetData(string key) { + return _markdownData.GetValueOrDefault(key); + } + + /// + /// 获取当前状态 + /// + /// 自定义的键名 + /// + public static MarkdownTextState GetState(string key) { + var data = GetData(key); + if (data != null) { + return data.State; + } + + return MarkdownTextState.None; + } + + /// + /// 获取当前状态 + /// + /// 自定义的键名 + /// 数据 + /// + public static bool TryAdd(string key, MarkdownData data) { + return _markdownData.TryAdd(key, data); + } + + /// + /// 获取当前状态 + /// + /// 自定义的键名 + /// 数据 + /// + public static bool TryGetValue(string key, out MarkdownData data) { + return _markdownData.TryGetValue(key, out data); + } + } +} diff --git a/Assets/SGModule/MarkdownKit/SGModule/Scripts/MakdownData.cs.meta b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MakdownData.cs.meta new file mode 100644 index 0000000..42e13e6 --- /dev/null +++ b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MakdownData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: bac5b35d952c6aa40bb88c625ad5651f +timeCreated: 1750064740 \ No newline at end of file diff --git a/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownConvert.cs b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownConvert.cs new file mode 100644 index 0000000..60c675c --- /dev/null +++ b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownConvert.cs @@ -0,0 +1,124 @@ +using System.Text.RegularExpressions; + +namespace SGModule.MarkdownKit { + public static class MarkdownConvert { + /// + /// 将md转换为富文本标签 + /// + /// + /// + public static string ToRichText(string markdown) { + // 移除每一行行尾的多余空格和制表符 + markdown = Regex.Replace(markdown, @"[ \t]+$", ""); + + // 标题替换 (支持 "#### " 等不同级别的标题) + markdown = Regex.Replace(markdown, @"^(#{1,6})\s*(.+)$", match => { + var level = match.Groups[1].Value.Length; // 获取标题级别 + var content = match.Groups[2].Value.Trim(); // 去除标题内容的多余空格 + + + // 标题大小规则:越小的标题级别,字体越大 + var baseSize = 40; // 默认正文字体大小 + var size = baseSize + (6 - level) * 5; // 一级标题最大,六级标题最小 + var str = $"{content}\n"; + if (level <= 2) { + str = $"{str}"; + } + + return str; // 设置标题大小 + }, RegexOptions.Multiline); + + // 粗体替换 ( **加粗** ) + markdown = Regex.Replace(markdown, @"\*\*(.+?)\*\*", "$1"); + + // 斜体替换 ( *斜体* ) + markdown = Regex.Replace(markdown, @"\*(.+?)\*", "$1"); + + // 下划线替换 ( __下划线__ ) + markdown = Regex.Replace(markdown, @"__(.+?)__", "$1"); + + // 删除线替换 ( ~~删除线~~ ) + markdown = Regex.Replace(markdown, @"~~(.+?)~~", "$1"); + + // 超链接替换 ( [文字](链接) ) + markdown = Regex.Replace(markdown, @"\[(.+?)\]\((.+?)\)", "$1"); + + // 无序列表替换 ( - 或 * 开头) + markdown = Regex.Replace(markdown, @"^\s*[-*]\s+(.+)$", match => { + var content = match.Groups[1].Value.Trim(); + return $"• {content}"; // 使用 • 作为无序列表的符号 + }, RegexOptions.Multiline); + + // 有序列表替换 ( 1. 或 2. 开头) + markdown = Regex.Replace(markdown, @"^\s*\d+\.\s+(.+)$", match => { + var content = match.Groups[1].Value.Trim(); + return $"{content}"; // 有序列表使用加粗标记 + }, RegexOptions.Multiline); + + // 移除多余的连续空行 (将多个空行压缩为一个空行) + markdown = Regex.Replace(markdown, @"(\r?\n){2,}", "\n"); + + return markdown; + } + + /// + /// 将md文本转换为UBB语法的富文本 + /// + /// + /// + /// + public static string ToUBB(string markdown, int textBaseSize) { + // 移除每一行行尾的多余空格和制表符 + markdown = Regex.Replace(markdown, @"[ \t]+$", ""); + + // 标题替换 (支持 "#### " 等不同级别的标题) + markdown = Regex.Replace(markdown, @"^(#{1,6})\s*(.+)$", match => { + var level = match.Groups[1].Value.Length; // 获取标题级别 + var content = match.Groups[2].Value.Trim(); // 去除标题内容的多余空格 + + // 标题大小规则:越小的标题级别,字体越大 + var baseSize = textBaseSize; // 默认正文字体大小 + var size = baseSize + (6 - level) * 3; // 一级标题最大,六级标题最小 + + var str = $"[b][size={size}]{content}[/size][/b]\n"; + if (level <= 2) { + str = $"[u]{str}[/u]"; + } + + return str; // 设置标题大小 + }, RegexOptions.Multiline); + + // 粗体替换 ( **加粗** -> [b]加粗[/b]) + markdown = Regex.Replace(markdown, @"\*\*(.+?)\*\*", "[b]$1[/b]"); + + // 斜体替换 ( *斜体* -> [i]斜体[/i]) + markdown = Regex.Replace(markdown, @"\*(.+?)\*", "[i]$1[/i]"); + + // 下划线替换 ( __下划线__ -> [u]下划线[/u]) + markdown = Regex.Replace(markdown, @"__(.+?)__", "[u]$1[/u]"); + + // 删除线替换 ( ~~删除线~~ -> [s]删除线[/s]) + markdown = Regex.Replace(markdown, @"~~(.+?)~~", "[s]$1[/s]"); + + // 超链接替换 ( [文字](链接) -> [url=链接]文字[/url]) + markdown = Regex.Replace(markdown, @"\[(.+?)\]\((.+?)\)", "[url=$2]$1[/url]"); + + // 无序列表替换 ( - 或 * 开头 -> • 项目内容) + markdown = Regex.Replace(markdown, @"^\s*[-*]\s+(.+)$", match => { + var content = match.Groups[1].Value.Trim(); + return $"• {content}"; // 使用 • 作为无序列表的符号 + }, RegexOptions.Multiline); + + // 有序列表替换 ( 1. 或 2. 开头 -> 加粗项目内容) + markdown = Regex.Replace(markdown, @"^\s*\d+\.\s+(.+)$", match => { + var content = match.Groups[1].Value.Trim(); + return $"[b]{content}[/b]"; // 有序列表使用加粗标记 + }, RegexOptions.Multiline); + + // 移除多余的连续空行 (将多个空行压缩为一个空行) + markdown = Regex.Replace(markdown, @"(\r?\n){2,}", "\n"); + + return markdown; + } + } +} diff --git a/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownConvert.cs.meta b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownConvert.cs.meta new file mode 100644 index 0000000..54ef317 --- /dev/null +++ b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownConvert.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 47ec1e22bc98a8e4a9404d009c4e2b90 +timeCreated: 1750065981 \ No newline at end of file diff --git a/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownKit.cs b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownKit.cs new file mode 100644 index 0000000..01cd053 --- /dev/null +++ b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownKit.cs @@ -0,0 +1,227 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Text; +using FairyGUI; +using SGModule.Common.Base; +using SGModule.Common.Helper; +using UnityEngine; +using UnityEngine.Networking; + +namespace SGModule.MarkdownKit { + public class MarkdownKit : SingletonMonoBehaviour { + /// + /// 加载文本,直接去网络下载 + /// + /// 自己为Md相关数据起的名字,后续都是通过这个来操作 + /// 文字默认大小 + /// md下载地址 + public void LoadText(string key, string url, int textSize = 40) { + var data = new MarkdownData { Url = url, BaseSize = textSize }; + if (!MarkdownDataMgr.TryAdd(key, data)) { + Log.MarkdownKit.Warning($"{key} 已加载,请勿重复加载!!!"); + return; + } + + StartCoroutine(Download(data)); + } + + /// + /// 获取指定的文本数据 + /// + /// 自定义键名 + /// 获取回调 + /// 文本大小 + public void GetText(string key, Action> onComplete, int textSize = 40) { + if (!MarkdownDataMgr.TryGetValue(key, out var data)) { + Log.MarkdownKit.Warning($"{key} 未初始化,请加载后重试"); + return; + } + + SetMarkdownTextSize(data, textSize); + + switch (data.State) { + case MarkdownTextState.Complete: + onComplete?.Invoke(true, data.RichTextList); + return; + case MarkdownTextState.Downloading: + data.OnComplete += onComplete; + return; + case MarkdownTextState.Exception: + data.OnComplete += onComplete; + StartCoroutine(Download(data)); + break; + } + } + + /// + /// 下载md + /// + /// + /// + private IEnumerator Download(MarkdownData data) { + data.State = MarkdownTextState.Downloading; + + var unityWebRequest = new UnityWebRequest(data.Url) { + downloadHandler = new DownloadHandlerBuffer() + }; + + unityWebRequest.SetRequestHeader("Content-Type", "application/json;charset=utf-8"); + + yield return unityWebRequest.SendWebRequest(); //发送请求 + + if (unityWebRequest.result is not UnityWebRequest.Result.Success) { + data.State = MarkdownTextState.Exception; + data.OnComplete?.Invoke(false, null); + Log.MarkdownKit.Error($"失败 {unityWebRequest.result} {unityWebRequest.error}"); + } + else { + var receiveContent = unityWebRequest.downloadHandler.text; + + data.Text = receiveContent; + data.MarkdownTextList = SplitMarkdownByHeaders(receiveContent); + UpdateMarkdownTextList(data); + data.State = MarkdownTextState.Complete; + + data.OnComplete?.Invoke(true, data.RichTextList); + } + + data.OnComplete = null; + } + + /// + /// 根据md标题切割md文本 + /// + /// + /// + private List SplitMarkdownByHeaders(string markdownText) { + var sections = new List(); + var currentSection = new StringBuilder(); + + using (var reader = new StringReader(markdownText)) { + string line; + while ((line = reader.ReadLine()) != null) { + if (line.StartsWith("#")) // 如果是标题行 + { + if (currentSection.Length > 0) { + sections.Add(currentSection.ToString()); + currentSection.Clear(); + } + } + + currentSection.AppendLine(line); + } + + if (currentSection.Length > 0) // 添加最后一段 + { + sections.Add(currentSection.ToString()); + } + } + + return sections; + } + + /// + /// 设置富文本默认文字大小 + /// + /// + /// + private void SetMarkdownTextSize(MarkdownData data, int textSize) { + if (textSize > 0 && data.BaseSize != textSize) { + data.BaseSize = textSize; + + UpdateMarkdownTextList(data); + } + } + + /// + /// 更新富文本数据 + /// + /// + private void UpdateMarkdownTextList(MarkdownData data) { + if (data.MarkdownTextList == null) { + return; + } + + var richTextList = new List(); + foreach (var section in data.MarkdownTextList) { + var richText = MarkdownConvert.ToUBB(section, data.BaseSize); + + richTextList.Add(richText); + } + + data.RichTextList = richTextList; + } + + /// + /// 添加富文本到指定节点下 + /// + /// 指定节点 + /// 数据键名 + /// 颜色 + /// 回调,参数分是代表了结果与当前状态 + /// 字体大小,如果与当前不一致将更新富文本数据 + public void ShowAsRichText(GComponent parent, string key, Color color, Action callback, int textSize = -1) { + //处理对象为空或者相关对象已经被销毁的情况,如界面在等待过程中已经被关闭 + if (parent == null || parent.isDisposed) { + Log.MarkdownKit.Warning("parent 是无效的"); + return; + } + + if (!MarkdownDataMgr.TryGetValue(key, out var data)) { + Log.MarkdownKit.Error($"未加载 {key}的数据"); + callback?.Invoke(false, MarkdownTextState.None); + return; + } + + Action> show = list => { + //处理对象为空或者相关对象已经被销毁的情况,如界面在等待过程中已经被关闭 + if (parent == null || parent.isDisposed) { + Log.MarkdownKit.Warning("parent 是无效的"); + return; + } + + SetMarkdownTextSize(data, textSize); + foreach (var richText in list) { + // 创建 GRichTextField + var aRichTextField = new GRichTextField(); + + aRichTextField.UBBEnabled = true; + aRichTextField.SetSize(parent.size.x, 0); + aRichTextField.color = color; + aRichTextField.textFormat.size = data.BaseSize; + aRichTextField.autoSize = AutoSizeType.Height; + aRichTextField.AddRelation(GRoot.inst, RelationType.Width); + aRichTextField.text = richText; + parent.AddChild(aRichTextField); + } + }; + + Action> downloadingCallback = (result, list) => { + callback?.Invoke(result, data.State); + if (result) { + show.Invoke(list); + } + }; + + switch (data.State) { + case MarkdownTextState.Downloading: + callback?.Invoke(true, data.State); + data.OnComplete += downloadingCallback; + break; + case MarkdownTextState.Complete: + callback?.Invoke(true, data.State); + show.Invoke(data.RichTextList); + break; + case MarkdownTextState.Exception: + callback?.Invoke(true, data.State); + data.OnComplete += downloadingCallback; + StartCoroutine(Download(data)); + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + } +} diff --git a/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownKit.cs.meta b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownKit.cs.meta new file mode 100644 index 0000000..b2cb7f0 --- /dev/null +++ b/Assets/SGModule/MarkdownKit/SGModule/Scripts/MarkdownKit.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b1caa4712eda60b45bff71a47741756c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net.meta b/Assets/SGModule/Net.meta new file mode 100644 index 0000000..33b2217 --- /dev/null +++ b/Assets/SGModule/Net.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 863ea601ea8dfc144b7dc71a47153fb7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/README.md b/Assets/SGModule/Net/README.md new file mode 100644 index 0000000..18c6dca --- /dev/null +++ b/Assets/SGModule/Net/README.md @@ -0,0 +1,67 @@ +# 🌐 Net 网络模块 + +适用于 Unity 的网络模块,包含网络检测、接口请求、Token 鉴权、服务器时间同步等功能。模块职责清晰、易扩展,使用前需引入通用模块。 + +------ + +## 📦 模块概览 + +| 模块 | 功能描述 | +| ---------------- | --------------------------------------------------- | +| `NetChecker` | 📶 检测网络是否可用,支持 Ping / HTTP 检查 | +| `NetCore` | 📡 网络请求基类,支持加密和 Token 自动处理(需继承) | +| `TokenManager` | 🔐 Token 缓存 / 自动刷新 / 登录回退处理 | +| `ServerClock` | 🕒 同步服务器时间,避免设备本地误差 | +| `WebSocket 模块` | 依赖 nativewebsocket 插件 | + +------ + +## ✅ 使用示例 + +### 1. 网络检测 + +```c# +StartCoroutine(NetChecker.Instance.WaitUntilNetworkConnected(10, 1f, success => { + if (success) Debug.Log("✅ 网络可用"); +})); +``` + +------ + +### 2. 实现你的请求类(必须继承 NetCore) + +```c# +public class NetKit : NetCore { + // 详情参考此类 +} +``` + +------ + +### 3. 发起接口请求(在子类中) + +```c# +NetKit.Instance.Post("/event/incrN", trackData, + response => { + callback?.Invoke(response.IsSuccess, response.Data); + }); +``` + +------ + +### 4. Token 获取(自动缓存) + +```c# +yield return TokenManager.Instance.GetToken(token => { + Debug.Log("当前 Token:" + token); +}); +``` + +------ + +### 5. 服务器时间同步 + +```c# +ServerClock.Init(serverUnixTime); +var now = ServerClock.GetCurrentServerTime(); +``` \ No newline at end of file diff --git a/Assets/SGModule/Net/README.md.meta b/Assets/SGModule/Net/README.md.meta new file mode 100644 index 0000000..e2b3f9e --- /dev/null +++ b/Assets/SGModule/Net/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: c97138411a25ced4f9dfa8842cb4f0da +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule.meta b/Assets/SGModule/Net/SGModule.meta new file mode 100644 index 0000000..34bdc6c --- /dev/null +++ b/Assets/SGModule/Net/SGModule.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3196117d57be50e409688a93df57f045 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/Scripts.meta b/Assets/SGModule/Net/SGModule/Scripts.meta new file mode 100644 index 0000000..8d5f694 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0915769f0cd1ba541832197a5a79b69b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core.meta b/Assets/SGModule/Net/SGModule/Scripts/Core.meta new file mode 100644 index 0000000..48bee12 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Core.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ac3aa62a90e10c34486be40387fbd2b9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs b/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs new file mode 100644 index 0000000..1c2eeba --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs @@ -0,0 +1,284 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using SGModule.Common.Base; +using SGModule.Common.Helper; +using UnityEngine; +using UnityEngine.Networking; + +namespace SGModule.Net { + public enum ConnectionStatus { + Uninitialized, // 未初始化 + Connected, // 已连接 + Disconnected // 未连接 + } + + // 网络检测类 + public class NetChecker : SingletonMonoBehaviour { + private const float WebRequestInterval = 5f; + private const float PingInterval = 2; + + // 可配置多个检测 URL + [SerializeField] private List checkUrls = new() { + "https://www.baidu.com", // 国内 URL + "https://www.google.com" // 国外 URL + }; + + // 是否启用 Ping 检测 + [SerializeField] private bool usePingCheck; + + // 配置可用的 Ping 地址列表 + private readonly List _pingAddresses = new() { + "8.8.8.8", // Google DNS(适合全球) + "223.5.5.5", // 阿里云 + "1.1.1.1" // Cloudflare DNS(全球可用) + }; + + + private Coroutine _checkInternetCoroutine; + private float _checkInterval = WebRequestInterval; + private bool _isChecking; + private bool _lastConnected; + private string _preferredUrl; // 当前优先检测的 URL + + /// + /// null = 未检测;true = 联网;false = 未联网 + /// + private bool? IsConnected { + get; + set; + } + + private void OnEnable() { + StartCheckingInternet(); + } + + private void OnDisable() { + StopCheckingInternet(); + } + + /// + /// 等待网络连通,自动处理初始化和总超时时间 + /// + /// 最多等待的总时间(秒) + /// 每次重试间隔 + /// 检测结果回调 + public IEnumerator WaitUntilNetworkConnected(float timeout, float checkInterval, Action callback) { + var elapsed = 0f; + + // 阶段 1: 等待初始化完成 + while (!IsConnected.HasValue && elapsed < timeout) { + yield return new WaitForSeconds(checkInterval); + elapsed += checkInterval; + } + + if (!IsConnected.HasValue) { + Log.Net.Warning("网络检测初始化超时!"); + callback(false); + yield break; + } + + // 阶段 2: 等待网络恢复 + while (IsConnected == false && elapsed < timeout) { + Log.Net.Warning($"网络异常,等待中... 已耗时: {elapsed:F1}s"); + yield return new WaitForSeconds(checkInterval); + elapsed += checkInterval; + } + + var success = IsConnected == true; + if (!success) { + Log.Net.Warning("网络连接等待超时!"); + } + + callback(success); + } + + public ConnectionStatus GetConnectionStatus() { + return IsConnected switch { + null => ConnectionStatus.Uninitialized, + true => ConnectionStatus.Connected, + false => ConnectionStatus.Disconnected + }; + } + + public void Init() { + StartCheckingInternet(); + } + + private void StartCheckingInternet() { + _checkInterval = usePingCheck ? PingInterval : WebRequestInterval; + _checkInternetCoroutine ??= StartCoroutine(CheckInternetRoutine()); + } + + private void StopCheckingInternet() { + if (_checkInternetCoroutine != null) { + StopCoroutine(_checkInternetCoroutine); + _checkInternetCoroutine = null; + } + } + + private IEnumerator CheckInternetRoutine() { + while (true) { + if (_isChecking) { + yield break; // 避免并发冲突 + } + + _isChecking = true; + + if (QuickNetDeviceCheck()) { + // if (usePingCheck) { + yield return CheckWithPing(); + // } + // else { + // yield return CheckWithUnityWebRequest(); + // } + } + else { + IsConnected = false; + } + + if (IsConnected.HasValue && _lastConnected != IsConnected.Value) { + Log.Net.Info($"网络状态变化: {IsConnected}"); + _lastConnected = IsConnected.Value; + } + + _isChecking = false; + yield return new WaitForSecondsRealtime(_checkInterval); + } + } + + /// + /// 使用 Ping 检测网络连通性 + /// + private IEnumerator CheckWithPing() { + var pings = _pingAddresses.Select(ip => new Ping(ip)).ToList(); + + var startTime = Time.realtimeSinceStartup; + var success = false; + + // 等待所有 Ping 返回结果或超时 + while (Time.realtimeSinceStartup - startTime < _checkInterval) { + foreach (var ping in pings) { + if (ping.isDone && ping.time >= 0) { + success = true; + break; + } + } + + if (success) { + break; + } + + yield return new WaitForSecondsRealtime(0.1f); + } + + // 如果有任意一个 Ping 成功,网络即为可用 + IsConnected = success; + } + + /// + /// 使用 UnityWebRequest 检测网络连通性 + /// + private IEnumerator CheckWithUnityWebRequest() { + if (!string.IsNullOrEmpty(_preferredUrl)) { + var request = UnityWebRequest.Get(_preferredUrl); + request.timeout = (int) _checkInterval; + yield return request.SendWebRequest(); + + if (request.result == UnityWebRequest.Result.Success) { + IsConnected = true; + request.Dispose(); + yield break; + } + + Log.Net.Warning($"CheckNet 首选URL请求失败: {_preferredUrl}, 错误: {request.error}"); + + _preferredUrl = null; // 失败则清除 + request.Dispose(); + } + + // fallback:尝试所有 URL + var ops = new List(); + var requests = new List(); + + foreach (var url in checkUrls) { + var req = UnityWebRequest.Get(url); + req.timeout = (int) _checkInterval; + ops.Add(req.SendWebRequest()); + requests.Add(req); + } + + yield return StartCoroutine(WaitForAnyRequest(ops)); + + foreach (var req in requests) { + req.Dispose(); + } + } + + + // 等待任意一个请求完成并返回 + private IEnumerator WaitForAnyRequest(List ops) { + while (ops.Any(op => !op.isDone)) { + if (ops.Any(op => op.isDone && op.webRequest.result == UnityWebRequest.Result.Success)) { + break; + } + + yield return null; + } + + var successOp = ops.FirstOrDefault(op => op.webRequest.result == UnityWebRequest.Result.Success); + + if (successOp == null) { + foreach (var op in ops.Where(op => op.isDone)) { + Log.Net.Warning($"请求失败: {op.webRequest.url}, 错误: {op.webRequest.error}"); + } + } + + IsConnected = successOp != null; + _preferredUrl = successOp?.webRequest.url; + } + + // 添加或删除检查 URL + public void AddCheckUrl(string url) { + if (!checkUrls.Contains(url)) { + checkUrls.Add(url); + } + } + + public void RemoveCheckUrl(string url) { + if (checkUrls.Contains(url)) { + checkUrls.Remove(url); + } + } + + public void AddPingTarget(string ip) { + if (!_pingAddresses.Contains(ip)) { + _pingAddresses.Add(ip); + } + } + + public void RemovePingTarget(string ip) { + if (_pingAddresses.Contains(ip)) { + _pingAddresses.Remove(ip); + } + } + + // 切换是否使用 Ping 检测 + public void SetUsePingCheck(bool enablePing) { + usePingCheck = enablePing; +#if UNITY_WEBGL +usePingCheck = false; +#endif + _checkInterval = usePingCheck ? PingInterval : WebRequestInterval; + } + + private bool QuickNetDeviceCheck() { + if (Application.isEditor) { + return true; + } + + return Application.internetReachability != NetworkReachability.NotReachable; + } + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs.meta new file mode 100644 index 0000000..fbc0661 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Core/NetChecker.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 410b1547c3cc4b6496884bc02a4b8498 +timeCreated: 1731574865 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core/NetCore.cs b/Assets/SGModule/Net/SGModule/Scripts/Core/NetCore.cs new file mode 100644 index 0000000..1c87078 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Core/NetCore.cs @@ -0,0 +1,272 @@ +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using Newtonsoft.Json; +using SGModule.Common.Base; +using SGModule.Common.Extensions; +using SGModule.Common.Helper; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.Networking; + +namespace SGModule.Net { + // 网络请求核心类 + public abstract class NetCore : SingletonMonoBehaviour where TC : MonoBehaviour { + private const int Timeout = 15; + private NetCoreModel _config; + private bool _isInit; + private int _requestCounter; + private string _requestHost; + + private new void Awake() { + InternalInit(); + } + + protected abstract string Encrypt(string text, string key); + protected abstract string Decrypt(string text, string key); + protected abstract TokenManager.RefreshTokenDelegate RefreshTokenHandler(); + protected abstract TokenManager.ReauthenticateDelegate ReauthenticateHandler(); + + protected abstract NetCoreModel ProvideConfig(); + + private void InternalInit() { + NetChecker.Instance.Init(); + TokenManager.Instance.InitHandlers(RefreshTokenHandler(), ReauthenticateHandler()); + + _config = ProvideConfig(); + if (_config == null) { + Log.Net.Error("网络配置为空,请检查!!!!"); + return; + } + + _isInit = true; + _requestHost = _config.RequestHost; + + Log.Net.Info($"Host is: {_config.RequestHost}"); + + if (_config.ConnMode == ConnectionMode.WebSocket) { + WebSocketService.Instance.Init(GetWsUrl()); + } + } + + + private string GetApiUrl() { + return $"https://{_requestHost}/api/"; + } + + private string GetWsUrl() { + return $"wss://{_requestHost}/ws/"; + } + + /// + /// Post请求(异步) + /// + /// 请求路径 + /// 请求参数 + /// 请求回调 + /// 是否带Token + /// 额外的请求头 + protected IEnumerator PostAsync(string path, object requestData = null, UnityAction> onCompleted = null, bool withToken = true, Dictionary headers = null) { + var done = false; + + Post(path, requestData, response => { + onCompleted?.Invoke(response); + done = true; + }, withToken, true, headers); + + yield return new WaitUntil(() => done); + } + + /// + /// Post请求(泛型) + /// + /// 请求路径 + /// 请求参数 + /// 请求回调 + /// 是否带Token + /// 是否使用协程 + /// 额外的请求头 + /// 返回数据中Data的类型 + protected void Post(string path, object requestData = null, UnityAction> onCompleted = null, bool withToken = true, bool useCoroutine = true, Dictionary headers = null) { + if (useCoroutine) { + StartCoroutine(PostInternal(path, requestData, onCompleted, withToken, headers)); + } + else { + SendWebRequest(path, requestData, withToken, headers); + } + } + + + /// + /// 发出请求 所有的请求最终都会从这里发出 + /// + /// 请求路径 + /// 请求参数 + /// 请求回调 + /// 是否带Token + /// 额外的请求头 + /// 返回数据中Data的类型 + /// + private IEnumerator PostInternal(string path, object requestData, UnityAction> onCompleted, bool withToken = true, Dictionary headers = null) { + var response = new ResponseData(); + + if (!_isInit) { + Log.Net.Error("NetworkKit模块未完成初始化 请检查!!! "); + response.Code = -1; + response.Msg = "NetworkKit module has not been initialized yet"; + onCompleted?.Invoke(response); + yield break; + } + + // 1. 网络检查 + var isNetworkOk = true; + // yield return NetChecker.Instance.WaitUntilNetworkConnected(15, 1f, result => isNetworkOk = result); + if (!isNetworkOk) { + response.Code = -1; + response.Msg = "Network status abnormal."; + onCompleted?.Invoke(response); + yield break; + } + + // 2. Token 处理(根据 withToken 参数) + if (withToken) { + string token = null; + yield return TokenManager.Instance.GetToken(result => token = result); + + if (string.IsNullOrEmpty(token)) { + response.Code = -1; + response.Msg = "Token acquisition failed."; + onCompleted?.Invoke(response); + yield break; + } + + // 合并原有 header + headers ??= new Dictionary(); + + headers["x-token"] = token; + } + + + yield return SendRequest(path, requestData, onCompleted, headers); + } + + private IEnumerator SendRequest( + string path, + object requestData, + UnityAction> onCompleted = null, + Dictionary headers = null) { + var requestId = GetNextRequestId(); + + var requestJson = SerializeHelper.ToJsonIndented(requestData ?? new object()); + + var unityWebRequest = CreatePostRequest(path, requestJson, headers); + + Log.Net.Info($"[Req:{requestId}] | Path: {path} | Body: {requestJson}"); + + yield return unityWebRequest.SendWebRequest(); //发送请求 + + var response = new ResponseData(); + + if (unityWebRequest.result is not UnityWebRequest.Result.Success) { + Log.Net.Error($"[Resp:{requestId}] | Path: {path} | Error: {unityWebRequest.error}"); + response.Code = -1; + response.Msg = unityWebRequest.error; + } + else { + var receiveContent = unityWebRequest.downloadHandler.text; + + if (!receiveContent.IsNullOrWhiteSpace()) { + receiveContent = Decrypt(UnquoteString(receiveContent), _requestHost); + } + + + var raw = SerializeHelper.ToObject>(receiveContent); + + if (raw?.Code == 0) { + Log.Net.Info($"[Resp:{requestId}] | Path: {path} | Result: {receiveContent}"); + + // 处理字符串类型的情况 + if (typeof(T) == typeof(string)) { + response.Data = (T) (object) (raw.Data?.ToString() ?? ""); + } + else { + response.Data = SerializeHelper.ToObject(JsonConvert.SerializeObject(raw.Data)); + } + } + else { + Log.Net.Warning($"[Resp:{requestId}] | Path: {path} | Result: {receiveContent}"); + + response.Code = raw?.Code ?? -2; + response.Msg = raw?.Msg ?? "未知错误"; + } + } + + onCompleted?.Invoke(response); + + unityWebRequest.Dispose(); + } + + private UnityWebRequest CreatePostRequest(string path, string requestJson, Dictionary headers = null) { + path = Encrypt(path, _requestHost); + requestJson = Encrypt(requestJson, _requestHost); + + var fullUrl = GetApiUrl() + path; + + var request = new UnityWebRequest(fullUrl, UnityWebRequest.kHttpVerbPOST) { + uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(requestJson)), + downloadHandler = new DownloadHandlerBuffer(), + timeout = Timeout + }; + + SetRequestHeaders(request, headers); + + return request; + } + + private void SetRequestHeaders(UnityWebRequest request, Dictionary headers) { + request.SetRequestHeader("Content-Type", "application/json;charset=utf-8"); + if (headers == null) { + return; + } + + foreach (var kvp in headers.Where(kvp => kvp.Value != null)) { + request.SetRequestHeader(kvp.Key, kvp.Value); + } + } + + private int GetNextRequestId() { + return Interlocked.Increment(ref _requestCounter); + } + + // 去除双引号(如果存在) + private static string UnquoteString(string input) { + if (!string.IsNullOrEmpty(input) && input.Length >= 2 && + input[0] == '"' && input[input.Length - 1] == '"') { + return input.Substring(1, input.Length - 2); + } + + return input; + } + + + private void SendWebRequest(string url, object requestData = null, bool withToken = false, Dictionary header = null) { + if (withToken) { + // 合并原有 header + header ??= new Dictionary(); + header["x-token"] = TokenManager.Instance.CachedToken; + } + + var requestId = GetNextRequestId(); + + var requestJson = SerializeHelper.ToJsonIndented(requestData ?? new object()); + + var unityWebRequest = CreatePostRequest(url, requestJson, header); + + Log.Net.Info($"[Req:{requestId}] | Path: {url} | Body: {requestJson}"); + + unityWebRequest.SendWebRequest(); //发送请求 + } + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core/NetCore.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/Core/NetCore.cs.meta new file mode 100644 index 0000000..a3671bb --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Core/NetCore.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 4495c7a990814f9e977dc6853d262a5f +timeCreated: 1731305623 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core/ServerClock.cs b/Assets/SGModule/Net/SGModule/Scripts/Core/ServerClock.cs new file mode 100644 index 0000000..e8b9d77 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Core/ServerClock.cs @@ -0,0 +1,20 @@ +using System; + +namespace SGModule.Net { + // 服务器时钟管理类 + public static class ServerClock { + private static long _timeDifference; // 本地与服务器的时间偏差 + + public static void Init(long serverTime) { + _timeDifference = serverTime - Now(); + } + + public static long GetCurrentServerTime() { + return Now() + _timeDifference; + } + + private static long Now() { + return DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + } + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core/ServerClock.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/Core/ServerClock.cs.meta new file mode 100644 index 0000000..c4eea9d --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Core/ServerClock.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 59a4eda105634775a948f64a9f6631d7 +timeCreated: 1750225342 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core/TokenManager.cs b/Assets/SGModule/Net/SGModule/Scripts/Core/TokenManager.cs new file mode 100644 index 0000000..d6b93da --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Core/TokenManager.cs @@ -0,0 +1,204 @@ +using System.Collections; +using System.Collections.Generic; +using SGModule.Common.Base; +using SGModule.Common.Extensions; +using SGModule.Common.Helper; +using UnityEngine; +using UnityEngine.Events; + +namespace SGModule.Net { + // Token管理类 + public class TokenManager : SingletonMonoBehaviour { + public delegate IEnumerator ReauthenticateDelegate(UnityAction onCompleted); + + public delegate IEnumerator RefreshTokenDelegate(UnityAction onCompleted); + + private const string JarvisTokenKey = "JarvisToken"; + private const string JarvisTokenExpiresAtKey = "JarvisTokenExpiresAt"; + private const float MinRefreshInterval = 10f; // 刷新间隔秒数限制 + private const int MaxTokenRecordCount = 10; // 最多记录最近token数 + + private readonly List _tokenRecord = new(); + + private long _cachedExpiresAt; + private string _cachedToken; + + private bool _isReauthenticating; + private bool _isRefreshing; + private float _lastRefreshTime; + private ReauthenticateDelegate _reauthenticateHandler; + + private RefreshTokenDelegate _refreshTokenHandler; + + public string CachedToken { + get { + if (string.IsNullOrEmpty(_cachedToken)) { + _cachedToken = PlayerPrefs.GetString(JarvisTokenKey, null); + } + + return _cachedToken; + } + set { + _cachedToken = value; + if (!string.IsNullOrEmpty(value)) { + PlayerPrefs.SetString(JarvisTokenKey, value); + } + else { + PlayerPrefs.DeleteKey(JarvisTokenKey); + } + } + } + + public long CachedExpiresAt { + get { + if (_cachedExpiresAt == 0) { + var expiresStr = PlayerPrefs.GetString(JarvisTokenExpiresAtKey, "0"); + if (!long.TryParse(expiresStr, out _cachedExpiresAt)) { + _cachedExpiresAt = 0; + } + } + + return _cachedExpiresAt; + } + set { + _cachedExpiresAt = value; + PlayerPrefs.SetString(JarvisTokenExpiresAtKey, value.ToString()); + } + } + + + private long RemainingTokenSeconds => CachedExpiresAt - ServerClock.GetCurrentServerTime(); + + public void InitHandlers(RefreshTokenDelegate refreshTokenHandler, ReauthenticateDelegate reauthenticateHandler) { + _refreshTokenHandler = refreshTokenHandler; + _reauthenticateHandler = reauthenticateHandler; + } + + /// + /// 获取有效Token,自动处理刷新和重新登录 + /// + public IEnumerator GetToken(UnityAction callback) { + // 若正在重新登录,则等待其完成,避免刷新或登录并发 + yield return WaitForReauthenticationComplete(); + if (_isReauthenticating) { + callback?.Invoke(null); + yield break; + } + + + if (IsTokenValid()) { + callback?.Invoke(CachedToken); // 优先返回现有有效 Token + + // 如果快过期,则后台触发刷新,不等待 + if (IsTokenExpiringSoon() && ShouldStartRefresh()) { + _lastRefreshTime = Time.realtimeSinceStartup; + StartCoroutine(RefreshTokenRoutine()); // 不阻塞当前流程 + } + } + else { + // token 已过期,必须重新登录 + yield return ReauthenticateRoutine(success => { + callback?.Invoke(success ? CachedToken : null); + }); + } + } + + private IEnumerator WaitForReauthenticationComplete() { + var waitCount = 0; + while (_isReauthenticating && waitCount < 6) { + yield return new WaitForSeconds(0.5f); + waitCount++; + } + } + + + private IEnumerator RefreshTokenRoutine() { + if (_isRefreshing || _refreshTokenHandler == null) { + if (_refreshTokenHandler == null) { + Log.Net.Error("未设置 RefreshTokenHandler 委托,请先调用 InitHandlers 进行注入!"); + } + + yield break; + } + + _isRefreshing = true; + var retryCount = 0; + var refreshSuccess = false; + + while (!refreshSuccess && retryCount < 3) { + retryCount++; + Log.Net.Info($"Token快过期了, 尝试刷新Token, 次数: {retryCount}"); + yield return _refreshTokenHandler((token, expiresAt) => { + refreshSuccess = !token.IsNullOrWhiteSpace(); + if (refreshSuccess) { + UpdateTokenCache(token, expiresAt); + } + }); + + if (!refreshSuccess) { + yield return new WaitForSeconds(1f); + } + } + + if (!refreshSuccess) { + Log.Net.Error("Token刷新失败"); + } + + _isRefreshing = false; + } + + private IEnumerator ReauthenticateRoutine(UnityAction onCompleted) { + if (_isReauthenticating || _reauthenticateHandler == null) { + if (_reauthenticateHandler == null) { + Log.Net.Error("未设置 ReauthenticateHandler 委托,请先调用 InitHandlers 进行注入!"); + } + + onCompleted?.Invoke(false); + yield break; + } + + _isReauthenticating = true; + Log.Net.Error("Token过期,开始重新登录流程"); + yield return _reauthenticateHandler((token, expiresAt) => { + var success = !token.IsNullOrWhiteSpace(); + if (success) { + UpdateTokenCache(token, expiresAt); + } + + onCompleted?.Invoke(success); + }); + _isReauthenticating = false; + } + + private bool IsTokenValid() { + return !string.IsNullOrEmpty(CachedToken) && RemainingTokenSeconds > 0; + } + + // 小于1小时(3600秒)有效期,认为快过期需要刷新 + private bool IsTokenExpiringSoon() { + return RemainingTokenSeconds < 3600; + } + + public void UpdateTokenCache(string token, long expiresAt) { + CachedToken = token; + CachedExpiresAt = expiresAt; + + + _tokenRecord.Add(token); + if (_tokenRecord.Count > MaxTokenRecordCount) { + _tokenRecord.RemoveAt(0); + } + } + + private bool ShouldStartRefresh() { + return !_isRefreshing && Time.realtimeSinceStartup - _lastRefreshTime > MinRefreshInterval; + } + + /// + /// 获取Token记录(测试功能用) + /// + public List GetTokenRecord() { + return _tokenRecord; + } + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/Core/TokenManager.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/Core/TokenManager.cs.meta new file mode 100644 index 0000000..5908d8d --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Core/TokenManager.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 9f7c53b24f0542499942172b93150c4b +timeCreated: 1750153672 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/Models.meta b/Assets/SGModule/Net/SGModule/Scripts/Models.meta new file mode 100644 index 0000000..ca6ca4b --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Models.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 92442bedfec46f64e99ebfad2afc096c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/Scripts/Models/NetCoreModel.cs b/Assets/SGModule/Net/SGModule/Scripts/Models/NetCoreModel.cs new file mode 100644 index 0000000..9f3275e --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Models/NetCoreModel.cs @@ -0,0 +1,6 @@ +namespace SGModule.Net { + public class NetCoreModel { + public ConnectionMode ConnMode; + public string RequestHost; + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/Models/NetCoreModel.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/Models/NetCoreModel.cs.meta new file mode 100644 index 0000000..ebbdf40 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Models/NetCoreModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f1af59db74324485a1ad287fae41f4a7 +timeCreated: 1750301716 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/Models/ResponseData.cs b/Assets/SGModule/Net/SGModule/Scripts/Models/ResponseData.cs new file mode 100644 index 0000000..b08432d --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Models/ResponseData.cs @@ -0,0 +1,21 @@ +using Newtonsoft.Json; + +namespace SGModule.Net { + public class ResponseData { + [JsonProperty("code")] public int Code; + [JsonProperty("data")] public T Data; + [JsonProperty("msg")] public string Msg; + + public bool IsSuccess => Code == 0; + + public void Deconstruct(out bool isSuccess, out T data) { + isSuccess = IsSuccess; + data = Data; + } + } + + public class RequestTokenData { + [JsonProperty("expires_at")] public long ExpiresAt; + [JsonProperty("token")] public string Token; + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/Models/ResponseData.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/Models/ResponseData.cs.meta new file mode 100644 index 0000000..0079629 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/Models/ResponseData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 367023343f32423a945b22cd9e10954d +timeCreated: 1731310905 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket.meta b/Assets/SGModule/Net/SGModule/Scripts/WebSocket.meta new file mode 100644 index 0000000..df19551 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1927ccee3f8f484eb4cb2c12246b1021 +timeCreated: 1736219769 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/ResponseData.cs b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/ResponseData.cs new file mode 100644 index 0000000..8793101 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/ResponseData.cs @@ -0,0 +1,36 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +public class ResponseData { + [JsonProperty("cmd")] + public int Cmd { + get; + set; + } + + [JsonProperty("body")] + public Body Body { + get; + set; + } +} + +public class Body { + [JsonProperty("code")] + public int Code { + get; + set; + } + + [JsonProperty("data")] + public JToken Data { + get; + set; + } // 使用 JToken 来处理不同的 data 结构 + + [JsonProperty("msg")] + public string Msg { + get; + set; + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/ResponseData.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/ResponseData.cs.meta new file mode 100644 index 0000000..bebbfec --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/ResponseData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d2969c12b6014b5c935b92b050e7f19a +timeCreated: 1736158044 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketData.cs b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketData.cs new file mode 100644 index 0000000..97ad480 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketData.cs @@ -0,0 +1,4 @@ +internal class WebSocketData { + public int cmd; + public string token; +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketData.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketData.cs.meta new file mode 100644 index 0000000..a6b286f --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c7cbb19f802743be9768ee60d9eaf110 +timeCreated: 1736221524 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketEvent.cs b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketEvent.cs new file mode 100644 index 0000000..86c0aff --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketEvent.cs @@ -0,0 +1,6 @@ +namespace SGModule.Net { + public enum WebSocketEvent { + BindToken = 4097, + SendHeartbeat = 4098 + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketEvent.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketEvent.cs.meta new file mode 100644 index 0000000..d0c0bdd --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketEvent.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 6ab1b29ab34f456b8398d41adcb955c3 +timeCreated: 1736221044 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketService.cs b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketService.cs new file mode 100644 index 0000000..4bf3f24 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketService.cs @@ -0,0 +1,221 @@ +using System; +using System.Text; +using System.Threading.Tasks; +using NativeWebSocket; +using Newtonsoft.Json; +using SGModule.Common.Base; +using SGModule.Common.Helper; +using UnityEngine; + +namespace SGModule.Net { + public class WebSocketService : SingletonMonoBehaviour { + private const float OffLineDecisionTime = 5f; + private bool _bindToken; + + private float _offlineDuration; + private string _url; + private WebSocket _webSocket; + + private void Update() { +#if !UNITY_WEBGL || UNITY_EDITOR + if (_webSocket != null) { + _webSocket.DispatchMessageQueue(); + } +#endif + if (IsInitComplete) { + // 网络状态检测 + if (NetChecker.Instance.GetConnectionStatus() == ConnectionStatus.Connected) { + _offlineDuration = 0; + if (_webSocket == null || _webSocket.State == WebSocketState.Closed) { + Log.Net.Warning("网络恢复 重连"); + TryReconnect(); + } + } + else { + _offlineDuration += Time.deltaTime; + if (_offlineDuration > OffLineDecisionTime && _webSocket != null && _webSocket.State == WebSocketState.Open) { + Log.Net.Warning("断网 主动结束连接"); + _ = Disconnect(); + } + } + } + } + + private async void OnApplicationQuit() { + await Disconnect(); + } + + private void InitGmTool() { + } + + /// + /// 初始化 + /// + /// + public async void Init(string url) { + InitGmTool(); + + NetChecker.Instance.SetUsePingCheck(true); + + Log.Net.Info($"Initializing WebSocket service. Url: {url}"); + _url = url; + + OnOpenAction += OnOpen; + OnMessageAction += OnMessage; + OnErrorAction += OnError; + OnCloseAction += OnClose; + + await Connect(); + } + + private void Send(object data) { + if (_webSocket == null) { + Log.Net.Warning("webSocket is null"); + return; + } + + if (_webSocket.State != WebSocketState.Open) { + Log.Net.Warning("webSocket.State != Open"); + return; + } + + var jsonString = JsonConvert.SerializeObject(data); + var byteArray = Encoding.UTF8.GetBytes(jsonString); + _webSocket.Send(byteArray); + } + + /// + /// 断开连接 + /// + public async Task Disconnect() { + if (_webSocket != null) { + var webSocket = _webSocket; + _webSocket = null; + await webSocket.Close(); + } + } + + #region 连接管理 + + // 事件回调 + public event Action OnOpenAction; + public event Action OnMessageAction; + public event Action OnCloseAction; + public event Action OnErrorAction; + + /// + /// 初始化并尝试连接 + /// + private async Task Connect() { + if (_webSocket != null && (_webSocket.State == WebSocketState.Open || _webSocket.State == WebSocketState.Connecting)) { + Log.Net.Warning("WebSocket is already connected or connecting."); + return; + } + + _webSocket = new WebSocket(_url); + + // 绑定事件 + _webSocket.OnOpen += () => { + Log.Net.Info("WebSocket connected."); + OnOpenAction?.Invoke(); + }; + + _webSocket.OnMessage += bytes => { + var message = Encoding.UTF8.GetString(bytes); + Log.Net.Info($"Message received: {message}"); + OnMessageAction?.Invoke(message); + }; + + _webSocket.OnClose += code => { + Log.Net.Info($"WebSocket disconnected with code: {code}"); + OnCloseAction?.Invoke(code); + }; + + _webSocket.OnError += error => { + Log.Net.Error($"WebSocket error: {error}"); + OnErrorAction?.Invoke(error); + }; + + // 开始连接 + try { + await _webSocket.Connect(); + } + catch (Exception ex) { + Log.Net.Error($"WebSocket connection failed: {ex.Message}"); + TryReconnect(); + } + } + + + private void OnOpen() { + IsInitComplete = true; + // 重连成功后绑定 Token + if (_bindToken) { + BindToken(TokenManager.Instance.CachedToken); + } + } + + private void OnClose(WebSocketCloseCode closeCode) { + } + + private void OnMessage(string message) { + var responseData = WebSocketTools.DeserializeResponse(message); + WebSocketTools.ProcessResponseData(responseData); + } + + private void OnError(string errorMsg) { + } + + /// + /// 尝试重连 + /// + private async void TryReconnect() { + var maxRetries = 5; // 最大重连次数 + var attempt = 0; + while (attempt < maxRetries) { + attempt++; + Log.Net.Info($"Attempting to reconnect... (Attempt {attempt}/{maxRetries})"); + try { + await Connect(); + + //以下或许不会执行 这个 + Log.Net.Info("Reconnected successfully."); + return; // 重连成功 + } + catch (Exception ex) { + Log.Net.Error($"Reconnection attempt {attempt} failed: {ex.Message}"); + await Task.Delay(2000); // 等待一段时间再尝试 + } + } + + Log.Net.Error("Max reconnection attempts reached. Connection failed."); + } + + #endregion + + #region 请求 + + /// + /// 绑定Token + /// + public void BindToken(string token) { + Send(new WebSocketData { + cmd = (int) WebSocketEvent.BindToken, + token = token + }); + + _bindToken = true; + } + + /// + /// 发送心跳 + /// + public void SendHeartbeat() { + Send(new WebSocketData { + cmd = (int) WebSocketEvent.SendHeartbeat + }); + } + + #endregion + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketService.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketService.cs.meta new file mode 100644 index 0000000..0df60c4 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketService.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: cdcb270d0b1e4b3fbc8983b5d1088660 +timeCreated: 1736219848 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketTools.cs b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketTools.cs new file mode 100644 index 0000000..c2cecbd --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketTools.cs @@ -0,0 +1,70 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using SGModule.Common.Helper; + +public class WebSocketTools { + // 反序列化函数,返回 ResponseData 对象 + public static ResponseData DeserializeResponse(string jsonMessage) { + try { + return JsonConvert.DeserializeObject(jsonMessage); + } + catch (JsonException ex) { + Log.Net.Error($"Failed to deserialize response: {ex.Message}"); + return null; + } + } + + // 处理数据函数 + public static void ProcessResponseData(ResponseData responseData) { + // 处理请求成功的情况 + if (responseData.Body.Code == 0) { + Log.Net.Info("Request succeeded"); + HandleData(responseData.Body.Data); // 不传入类型时,先默认不解析 + } + else { + Log.Net.Error($"Request failed: {responseData.Body.Msg}"); + } + } + + // 泛型版本的 HandleData,允许外部传入一个类型 + public static void HandleData(JToken data) { + // 检查 data 是否为空对象 + if (data.Type == JTokenType.Object && !data.HasValues) { + Log.Net.Info("Data is empty"); + // 可根据需要进一步处理空数据的情况 + } + else { + // 如果 data 包含有效数据,打印或进一步处理 + Log.Net.Info("Received data: " + data); + ProcessValidData(data); + } + } + + // 泛型版本的 HandleData,传入类型进行解析 + public static void HandleData(JToken data) { + if (data != null) { + try { + var parsedData = data.ToObject(); // 将 data 解析为指定类型 + Log.Net.Info("Parsed data: " + JsonConvert.SerializeObject(parsedData)); + ProcessValidData(parsedData); // 进一步处理解析后的数据 + } + catch (JsonException ex) { + Log.Net.Error($"Failed to parse data to type {typeof(T)}: {ex.Message}"); + } + } + else { + Log.Net.Warning("Data is null, cannot parse."); + } + } + + // 处理解析后的 data 类型 + public static void ProcessValidData(T parsedData) { + if (parsedData != null) { + // 在这里可以对解析后的 data 进行具体处理 + Log.Net.Info("Successfully processed data: " + parsedData); + } + else { + Log.Net.Warning("Parsed data is null, cannot process."); + } + } +} diff --git a/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketTools.cs.meta b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketTools.cs.meta new file mode 100644 index 0000000..aadba3b --- /dev/null +++ b/Assets/SGModule/Net/SGModule/Scripts/WebSocket/WebSocketTools.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 69c922dca7314799ade451fd4f2fb6fd +timeCreated: 1736159321 \ No newline at end of file diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket.meta b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket.meta new file mode 100644 index 0000000..26cd77c --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c7f0b7a09c76e4c419c7aee3dd9bfefd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket.meta b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket.meta new file mode 100644 index 0000000..72e9efa --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6183796adc7be374c86975de4519da5c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.cs b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.cs new file mode 100644 index 0000000..503cf43 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.cs @@ -0,0 +1,848 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.WebSockets; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +using AOT; +using System.Runtime.InteropServices; +using UnityEngine; +using System.Collections; + +public class MainThreadUtil : MonoBehaviour +{ + public static MainThreadUtil Instance { get; private set; } + public static SynchronizationContext synchronizationContext { get; private set; } + + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] + public static void Setup() + { + Instance = new GameObject("MainThreadUtil") + .AddComponent(); + synchronizationContext = SynchronizationContext.Current; + } + + public static void Run(IEnumerator waitForUpdate) + { + synchronizationContext.Post(_ => Instance.StartCoroutine( + waitForUpdate), null); + } + + void Awake() + { + gameObject.hideFlags = HideFlags.HideAndDontSave; + DontDestroyOnLoad(gameObject); + } +} + +public class WaitForUpdate : CustomYieldInstruction +{ + public override bool keepWaiting + { + get { return false; } + } + + public MainThreadAwaiter GetAwaiter() + { + var awaiter = new MainThreadAwaiter(); + MainThreadUtil.Run(CoroutineWrapper(this, awaiter)); + return awaiter; + } + + public class MainThreadAwaiter : INotifyCompletion + { + Action continuation; + + public bool IsCompleted { get; set; } + + public void GetResult() { } + + public void Complete() + { + IsCompleted = true; + continuation?.Invoke(); + } + + void INotifyCompletion.OnCompleted(Action continuation) + { + this.continuation = continuation; + } + } + + public static IEnumerator CoroutineWrapper(IEnumerator theWorker, MainThreadAwaiter awaiter) + { + yield return theWorker; + awaiter.Complete(); + } +} + +namespace NativeWebSocket +{ + public delegate void WebSocketOpenEventHandler(); + public delegate void WebSocketMessageEventHandler(byte[] data); + public delegate void WebSocketErrorEventHandler(string errorMsg); + public delegate void WebSocketCloseEventHandler(WebSocketCloseCode closeCode); + + public enum WebSocketCloseCode + { + /* Do NOT use NotSet - it's only purpose is to indicate that the close code cannot be parsed. */ + NotSet = 0, + Normal = 1000, + Away = 1001, + ProtocolError = 1002, + UnsupportedData = 1003, + Undefined = 1004, + NoStatus = 1005, + Abnormal = 1006, + InvalidData = 1007, + PolicyViolation = 1008, + TooBig = 1009, + MandatoryExtension = 1010, + ServerError = 1011, + TlsHandshakeFailure = 1015 + } + + public enum WebSocketState + { + Connecting, + Open, + Closing, + Closed + } + + public interface IWebSocket + { + event WebSocketOpenEventHandler OnOpen; + event WebSocketMessageEventHandler OnMessage; + event WebSocketErrorEventHandler OnError; + event WebSocketCloseEventHandler OnClose; + + WebSocketState State { get; } + } + + public static class WebSocketHelpers + { + public static WebSocketCloseCode ParseCloseCodeEnum(int closeCode) + { + + if (WebSocketCloseCode.IsDefined(typeof(WebSocketCloseCode), closeCode)) + { + return (WebSocketCloseCode)closeCode; + } + else + { + return WebSocketCloseCode.Undefined; + } + + } + + public static WebSocketException GetErrorMessageFromCode(int errorCode, Exception inner) + { + switch (errorCode) + { + case -1: + return new WebSocketUnexpectedException("WebSocket instance not found.", inner); + case -2: + return new WebSocketInvalidStateException("WebSocket is already connected or in connecting state.", inner); + case -3: + return new WebSocketInvalidStateException("WebSocket is not connected.", inner); + case -4: + return new WebSocketInvalidStateException("WebSocket is already closing.", inner); + case -5: + return new WebSocketInvalidStateException("WebSocket is already closed.", inner); + case -6: + return new WebSocketInvalidStateException("WebSocket is not in open state.", inner); + case -7: + return new WebSocketInvalidArgumentException("Cannot close WebSocket. An invalid code was specified or reason is too long.", inner); + default: + return new WebSocketUnexpectedException("Unknown error.", inner); + } + } + } + + public class WebSocketException : Exception + { + public WebSocketException() { } + public WebSocketException(string message) : base(message) { } + public WebSocketException(string message, Exception inner) : base(message, inner) { } + } + + public class WebSocketUnexpectedException : WebSocketException + { + public WebSocketUnexpectedException() { } + public WebSocketUnexpectedException(string message) : base(message) { } + public WebSocketUnexpectedException(string message, Exception inner) : base(message, inner) { } + } + + public class WebSocketInvalidArgumentException : WebSocketException + { + public WebSocketInvalidArgumentException() { } + public WebSocketInvalidArgumentException(string message) : base(message) { } + public WebSocketInvalidArgumentException(string message, Exception inner) : base(message, inner) { } + } + + public class WebSocketInvalidStateException : WebSocketException + { + public WebSocketInvalidStateException() { } + public WebSocketInvalidStateException(string message) : base(message) { } + public WebSocketInvalidStateException(string message, Exception inner) : base(message, inner) { } + } + + public class WaitForBackgroundThread + { + public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() + { + return Task.Run(() => { }).ConfigureAwait(false).GetAwaiter(); + } + } + +#if UNITY_WEBGL && !UNITY_EDITOR + + /// + /// WebSocket class bound to JSLIB. + /// + public class WebSocket : IWebSocket { + + /* WebSocket JSLIB functions */ + [DllImport ("__Internal")] + public static extern int WebSocketConnect (int instanceId); + + [DllImport ("__Internal")] + public static extern int WebSocketClose (int instanceId, int code, string reason); + + [DllImport ("__Internal")] + public static extern int WebSocketSend (int instanceId, byte[] dataPtr, int dataLength); + + [DllImport ("__Internal")] + public static extern int WebSocketSendText (int instanceId, string message); + + [DllImport ("__Internal")] + public static extern int WebSocketGetState (int instanceId); + + protected int instanceId; + + public event WebSocketOpenEventHandler OnOpen; + public event WebSocketMessageEventHandler OnMessage; + public event WebSocketErrorEventHandler OnError; + public event WebSocketCloseEventHandler OnClose; + + public WebSocket (string url, Dictionary headers = null) { + if (!WebSocketFactory.isInitialized) { + WebSocketFactory.Initialize (); + } + + int instanceId = WebSocketFactory.WebSocketAllocate (url); + WebSocketFactory.instances.Add (instanceId, this); + + this.instanceId = instanceId; + } + + public WebSocket (string url, string subprotocol, Dictionary headers = null) { + if (!WebSocketFactory.isInitialized) { + WebSocketFactory.Initialize (); + } + + int instanceId = WebSocketFactory.WebSocketAllocate (url); + WebSocketFactory.instances.Add (instanceId, this); + + WebSocketFactory.WebSocketAddSubProtocol(instanceId, subprotocol); + + this.instanceId = instanceId; + } + + public WebSocket (string url, List subprotocols, Dictionary headers = null) { + if (!WebSocketFactory.isInitialized) { + WebSocketFactory.Initialize (); + } + + int instanceId = WebSocketFactory.WebSocketAllocate (url); + WebSocketFactory.instances.Add (instanceId, this); + + foreach (string subprotocol in subprotocols) { + WebSocketFactory.WebSocketAddSubProtocol(instanceId, subprotocol); + } + + this.instanceId = instanceId; + } + + ~WebSocket () { + WebSocketFactory.HandleInstanceDestroy (this.instanceId); + } + + public int GetInstanceId () { + return this.instanceId; + } + + public Task Connect () { + int ret = WebSocketConnect (this.instanceId); + + if (ret < 0) + throw WebSocketHelpers.GetErrorMessageFromCode (ret, null); + + return Task.CompletedTask; + } + + public void CancelConnection () { + if (State == WebSocketState.Open) + Close (WebSocketCloseCode.Abnormal); + } + + public Task Close (WebSocketCloseCode code = WebSocketCloseCode.Normal, string reason = null) { + int ret = WebSocketClose (this.instanceId, (int) code, reason); + + if (ret < 0) + throw WebSocketHelpers.GetErrorMessageFromCode (ret, null); + + return Task.CompletedTask; + } + + public Task Send (byte[] data) { + int ret = WebSocketSend (this.instanceId, data, data.Length); + + if (ret < 0) + throw WebSocketHelpers.GetErrorMessageFromCode (ret, null); + + return Task.CompletedTask; + } + + public Task SendText (string message) { + int ret = WebSocketSendText (this.instanceId, message); + + if (ret < 0) + throw WebSocketHelpers.GetErrorMessageFromCode (ret, null); + + return Task.CompletedTask; + } + + public WebSocketState State { + get { + int state = WebSocketGetState (this.instanceId); + + if (state < 0) + throw WebSocketHelpers.GetErrorMessageFromCode (state, null); + + switch (state) { + case 0: + return WebSocketState.Connecting; + + case 1: + return WebSocketState.Open; + + case 2: + return WebSocketState.Closing; + + case 3: + return WebSocketState.Closed; + + default: + return WebSocketState.Closed; + } + } + } + + public void DelegateOnOpenEvent () { + this.OnOpen?.Invoke (); + } + + public void DelegateOnMessageEvent (byte[] data) { + this.OnMessage?.Invoke (data); + } + + public void DelegateOnErrorEvent (string errorMsg) { + this.OnError?.Invoke (errorMsg); + } + + public void DelegateOnCloseEvent (int closeCode) { + this.OnClose?.Invoke (WebSocketHelpers.ParseCloseCodeEnum (closeCode)); + } + + } + +#else + + public class WebSocket : IWebSocket + { + public event WebSocketOpenEventHandler OnOpen; + public event WebSocketMessageEventHandler OnMessage; + public event WebSocketErrorEventHandler OnError; + public event WebSocketCloseEventHandler OnClose; + + private Uri uri; + private Dictionary headers; + private List subprotocols; + private ClientWebSocket m_Socket = new ClientWebSocket(); + + private CancellationTokenSource m_TokenSource; + private CancellationToken m_CancellationToken; + + private readonly object OutgoingMessageLock = new object(); + private readonly object IncomingMessageLock = new object(); + + private bool isSending = false; + private List> sendBytesQueue = new List>(); + private List> sendTextQueue = new List>(); + + public WebSocket(string url, Dictionary headers = null) + { + uri = new Uri(url); + + if (headers == null) + { + this.headers = new Dictionary(); + } + else + { + this.headers = headers; + } + + subprotocols = new List(); + + string protocol = uri.Scheme; + if (!protocol.Equals("ws") && !protocol.Equals("wss")) + throw new ArgumentException("Unsupported protocol: " + protocol); + } + + public WebSocket(string url, string subprotocol, Dictionary headers = null) + { + uri = new Uri(url); + + if (headers == null) + { + this.headers = new Dictionary(); + } + else + { + this.headers = headers; + } + + subprotocols = new List {subprotocol}; + + string protocol = uri.Scheme; + if (!protocol.Equals("ws") && !protocol.Equals("wss")) + throw new ArgumentException("Unsupported protocol: " + protocol); + } + + public WebSocket(string url, List subprotocols, Dictionary headers = null) + { + uri = new Uri(url); + + if (headers == null) + { + this.headers = new Dictionary(); + } + else + { + this.headers = headers; + } + + this.subprotocols = subprotocols; + + string protocol = uri.Scheme; + if (!protocol.Equals("ws") && !protocol.Equals("wss")) + throw new ArgumentException("Unsupported protocol: " + protocol); + } + + public void CancelConnection() + { + m_TokenSource?.Cancel(); + } + + public async Task Connect() + { + try + { + m_TokenSource = new CancellationTokenSource(); + m_CancellationToken = m_TokenSource.Token; + + m_Socket = new ClientWebSocket(); + + foreach (var header in headers) + { + m_Socket.Options.SetRequestHeader(header.Key, header.Value); + } + + foreach (string subprotocol in subprotocols) { + m_Socket.Options.AddSubProtocol(subprotocol); + } + + await m_Socket.ConnectAsync(uri, m_CancellationToken); + OnOpen?.Invoke(); + + await Receive(); + } + catch (Exception ex) + { + OnError?.Invoke(ex.Message); + OnClose?.Invoke(WebSocketCloseCode.Abnormal); + } + finally + { + if (m_Socket != null) + { + m_TokenSource.Cancel(); + m_Socket.Dispose(); + } + } + } + + public WebSocketState State + { + get + { + switch (m_Socket.State) + { + case System.Net.WebSockets.WebSocketState.Connecting: + return WebSocketState.Connecting; + + case System.Net.WebSockets.WebSocketState.Open: + return WebSocketState.Open; + + case System.Net.WebSockets.WebSocketState.CloseSent: + case System.Net.WebSockets.WebSocketState.CloseReceived: + return WebSocketState.Closing; + + case System.Net.WebSockets.WebSocketState.Closed: + return WebSocketState.Closed; + + default: + return WebSocketState.Closed; + } + } + } + + public Task Send(byte[] bytes) + { + // return m_Socket.SendAsync(buffer, WebSocketMessageType.Binary, true, CancellationToken.None); + return SendMessage(sendBytesQueue, WebSocketMessageType.Binary, new ArraySegment(bytes)); + } + + public Task SendText(string message) + { + var encoded = Encoding.UTF8.GetBytes(message); + + // m_Socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); + return SendMessage(sendTextQueue, WebSocketMessageType.Text, new ArraySegment(encoded, 0, encoded.Length)); + } + + private async Task SendMessage(List> queue, WebSocketMessageType messageType, ArraySegment buffer) + { + // Return control to the calling method immediately. + // await Task.Yield (); + + // Make sure we have data. + if (buffer.Count == 0) + { + return; + } + + // The state of the connection is contained in the context Items dictionary. + bool sending; + + lock (OutgoingMessageLock) + { + sending = isSending; + + // If not, we are now. + if (!isSending) + { + isSending = true; + } + } + + if (!sending) + { + // Lock with a timeout, just in case. + if (!Monitor.TryEnter(m_Socket, 1000)) + { + // If we couldn't obtain exclusive access to the socket in one second, something is wrong. + await m_Socket.CloseAsync(WebSocketCloseStatus.InternalServerError, string.Empty, m_CancellationToken); + return; + } + + try + { + // Send the message synchronously. + var t = m_Socket.SendAsync(buffer, messageType, true, m_CancellationToken); + t.Wait(m_CancellationToken); + } + finally + { + Monitor.Exit(m_Socket); + } + + // Note that we've finished sending. + lock (OutgoingMessageLock) + { + isSending = false; + } + + // Handle any queued messages. + await HandleQueue(queue, messageType); + } + else + { + // Add the message to the queue. + lock (OutgoingMessageLock) + { + queue.Add(buffer); + } + } + } + + private async Task HandleQueue(List> queue, WebSocketMessageType messageType) + { + var buffer = new ArraySegment(); + lock (OutgoingMessageLock) + { + // Check for an item in the queue. + if (queue.Count > 0) + { + // Pull it off the top. + buffer = queue[0]; + queue.RemoveAt(0); + } + } + + // Send that message. + if (buffer.Count > 0) + { + await SendMessage(queue, messageType, buffer); + } + } + + private List m_MessageList = new List(); + + // simple dispatcher for queued messages. + public void DispatchMessageQueue() + { + if (m_MessageList.Count == 0) + { + return; + } + + List messageListCopy; + + lock (IncomingMessageLock) + { + messageListCopy = new List(m_MessageList); + m_MessageList.Clear(); + } + + var len = messageListCopy.Count; + for (int i = 0; i < len; i++) + { + OnMessage?.Invoke(messageListCopy[i]); + } + } + + public async Task Receive() + { + WebSocketCloseCode closeCode = WebSocketCloseCode.Abnormal; + await new WaitForBackgroundThread(); + + ArraySegment buffer = new ArraySegment(new byte[8192]); + try + { + while (m_Socket.State == System.Net.WebSockets.WebSocketState.Open) + { + WebSocketReceiveResult result = null; + + using (var ms = new MemoryStream()) + { + do + { + result = await m_Socket.ReceiveAsync(buffer, m_CancellationToken); + ms.Write(buffer.Array, buffer.Offset, result.Count); + } + while (!result.EndOfMessage); + + ms.Seek(0, SeekOrigin.Begin); + + if (result.MessageType == WebSocketMessageType.Text) + { + lock (IncomingMessageLock) + { + m_MessageList.Add(ms.ToArray()); + } + + //using (var reader = new StreamReader(ms, Encoding.UTF8)) + //{ + // string message = reader.ReadToEnd(); + // OnMessage?.Invoke(this, new MessageEventArgs(message)); + //} + } + else if (result.MessageType == WebSocketMessageType.Binary) + { + lock (IncomingMessageLock) + { + m_MessageList.Add(ms.ToArray()); + } + } + else if (result.MessageType == WebSocketMessageType.Close) + { + await Close(); + closeCode = WebSocketHelpers.ParseCloseCodeEnum((int)result.CloseStatus); + break; + } + } + } + } + catch (Exception) + { + m_TokenSource.Cancel(); + } + finally + { + await new WaitForUpdate(); + OnClose?.Invoke(closeCode); + } + } + + public async Task Close() + { + if (State == WebSocketState.Open) + { + await m_Socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, m_CancellationToken); + } + } + } +#endif + + /// + /// Factory + /// + + /// + /// Class providing static access methods to work with JSLIB WebSocket or WebSocketSharp interface + /// + public static class WebSocketFactory + { + +#if UNITY_WEBGL && !UNITY_EDITOR + /* Map of websocket instances */ + public static Dictionary instances = new Dictionary (); + + /* Delegates */ + public delegate void OnOpenCallback (int instanceId); + public delegate void OnMessageCallback (int instanceId, System.IntPtr msgPtr, int msgSize); + public delegate void OnErrorCallback (int instanceId, System.IntPtr errorPtr); + public delegate void OnCloseCallback (int instanceId, int closeCode); + + /* WebSocket JSLIB callback setters and other functions */ + [DllImport ("__Internal")] + public static extern int WebSocketAllocate (string url); + + [DllImport ("__Internal")] + public static extern int WebSocketAddSubProtocol (int instanceId, string subprotocol); + + [DllImport ("__Internal")] + public static extern void WebSocketFree (int instanceId); + + [DllImport ("__Internal")] + public static extern void WebSocketSetOnOpen (OnOpenCallback callback); + + [DllImport ("__Internal")] + public static extern void WebSocketSetOnMessage (OnMessageCallback callback); + + [DllImport ("__Internal")] + public static extern void WebSocketSetOnError (OnErrorCallback callback); + + [DllImport ("__Internal")] + public static extern void WebSocketSetOnClose (OnCloseCallback callback); + + /* If callbacks was initialized and set */ + public static bool isInitialized = false; + + /* + * Initialize WebSocket callbacks to JSLIB + */ + public static void Initialize () { + + WebSocketSetOnOpen (DelegateOnOpenEvent); + WebSocketSetOnMessage (DelegateOnMessageEvent); + WebSocketSetOnError (DelegateOnErrorEvent); + WebSocketSetOnClose (DelegateOnCloseEvent); + + isInitialized = true; + + } + + /// + /// Called when instance is destroyed (by destructor) + /// Method removes instance from map and free it in JSLIB implementation + /// + /// Instance identifier. + public static void HandleInstanceDestroy (int instanceId) { + + instances.Remove (instanceId); + WebSocketFree (instanceId); + + } + + [MonoPInvokeCallback (typeof (OnOpenCallback))] + public static void DelegateOnOpenEvent (int instanceId) { + + WebSocket instanceRef; + + if (instances.TryGetValue (instanceId, out instanceRef)) { + instanceRef.DelegateOnOpenEvent (); + } + + } + + [MonoPInvokeCallback (typeof (OnMessageCallback))] + public static void DelegateOnMessageEvent (int instanceId, System.IntPtr msgPtr, int msgSize) { + + WebSocket instanceRef; + + if (instances.TryGetValue (instanceId, out instanceRef)) { + byte[] msg = new byte[msgSize]; + Marshal.Copy (msgPtr, msg, 0, msgSize); + + instanceRef.DelegateOnMessageEvent (msg); + } + + } + + [MonoPInvokeCallback (typeof (OnErrorCallback))] + public static void DelegateOnErrorEvent (int instanceId, System.IntPtr errorPtr) { + + WebSocket instanceRef; + + if (instances.TryGetValue (instanceId, out instanceRef)) { + + string errorMsg = Marshal.PtrToStringAuto (errorPtr); + instanceRef.DelegateOnErrorEvent (errorMsg); + + } + + } + + [MonoPInvokeCallback (typeof (OnCloseCallback))] + public static void DelegateOnCloseEvent (int instanceId, int closeCode) { + + WebSocket instanceRef; + + if (instances.TryGetValue (instanceId, out instanceRef)) { + instanceRef.DelegateOnCloseEvent (closeCode); + } + + } +#endif + + /// + /// Create WebSocket client instance + /// + /// The WebSocket instance. + /// WebSocket valid URL. + public static WebSocket CreateInstance(string url) + { + return new WebSocket(url); + } + + } + +} diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.cs.meta b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.cs.meta new file mode 100644 index 0000000..919c067 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b775e14fc5a58124e8dbe558d81b5824 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.jslib b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.jslib new file mode 100644 index 0000000..052f213 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.jslib @@ -0,0 +1,333 @@ + +var LibraryWebSocket = { + $webSocketState: { + /* + * Map of instances + * + * Instance structure: + * { + * url: string, + * ws: WebSocket + * } + */ + instances: {}, + + /* Last instance ID */ + lastId: 0, + + /* Event listeners */ + onOpen: null, + onMesssage: null, + onError: null, + onClose: null, + + /* Debug mode */ + debug: false + }, + + /** + * Set onOpen callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnOpen: function(callback) { + + webSocketState.onOpen = callback; + + }, + + /** + * Set onMessage callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnMessage: function(callback) { + + webSocketState.onMessage = callback; + + }, + + /** + * Set onError callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnError: function(callback) { + + webSocketState.onError = callback; + + }, + + /** + * Set onClose callback + * + * @param callback Reference to C# static function + */ + WebSocketSetOnClose: function(callback) { + + webSocketState.onClose = callback; + + }, + + /** + * Allocate new WebSocket instance struct + * + * @param url Server URL + */ + WebSocketAllocate: function(url) { + + var urlStr = UTF8ToString(url); + var id = webSocketState.lastId++; + + webSocketState.instances[id] = { + subprotocols: [], + url: urlStr, + ws: null + }; + + return id; + + }, + + /** + * Add subprotocol to instance + * + * @param instanceId Instance ID + * @param subprotocol Subprotocol name to add to instance + */ + WebSocketAddSubProtocol: function(instanceId, subprotocol) { + + var subprotocolStr = UTF8ToString(subprotocol); + webSocketState.instances[instanceId].subprotocols.push(subprotocolStr); + + }, + + /** + * Remove reference to WebSocket instance + * + * If socket is not closed function will close it but onClose event will not be emitted because + * this function should be invoked by C# WebSocket destructor. + * + * @param instanceId Instance ID + */ + WebSocketFree: function(instanceId) { + + var instance = webSocketState.instances[instanceId]; + + if (!instance) return 0; + + // Close if not closed + if (instance.ws && instance.ws.readyState < 2) + instance.ws.close(); + + // Remove reference + delete webSocketState.instances[instanceId]; + + return 0; + + }, + + /** + * Connect WebSocket to the server + * + * @param instanceId Instance ID + */ + WebSocketConnect: function(instanceId) { + + var instance = webSocketState.instances[instanceId]; + if (!instance) return -1; + + if (instance.ws !== null) + return -2; + + instance.ws = new WebSocket(instance.url, instance.subprotocols); + + instance.ws.binaryType = 'arraybuffer'; + + instance.ws.onopen = function() { + + if (webSocketState.debug) + console.log("[JSLIB WebSocket] Connected."); + + if (webSocketState.onOpen) + Module.dynCall_vi(webSocketState.onOpen, instanceId); + + }; + + instance.ws.onmessage = function(ev) { + + if (webSocketState.debug) + console.log("[JSLIB WebSocket] Received message:", ev.data); + + if (webSocketState.onMessage === null) + return; + + if (ev.data instanceof ArrayBuffer) { + + var dataBuffer = new Uint8Array(ev.data); + + var buffer = _malloc(dataBuffer.length); + HEAPU8.set(dataBuffer, buffer); + + try { + Module.dynCall_viii(webSocketState.onMessage, instanceId, buffer, dataBuffer.length); + } finally { + _free(buffer); + } + + } else { + var dataBuffer = (new TextEncoder()).encode(ev.data); + + var buffer = _malloc(dataBuffer.length); + HEAPU8.set(dataBuffer, buffer); + + try { + Module.dynCall_viii(webSocketState.onMessage, instanceId, buffer, dataBuffer.length); + } finally { + _free(buffer); + } + + } + + }; + + instance.ws.onerror = function(ev) { + + if (webSocketState.debug) + console.log("[JSLIB WebSocket] Error occured."); + + if (webSocketState.onError) { + + var msg = "WebSocket error."; + var length = lengthBytesUTF8(msg) + 1; + var buffer = _malloc(length); + stringToUTF8(msg, buffer, length); + + try { + Module.dynCall_vii(webSocketState.onError, instanceId, buffer); + } finally { + _free(buffer); + } + + } + + }; + + instance.ws.onclose = function(ev) { + + if (webSocketState.debug) + console.log("[JSLIB WebSocket] Closed."); + + if (webSocketState.onClose) + Module.dynCall_vii(webSocketState.onClose, instanceId, ev.code); + + delete instance.ws; + + }; + + return 0; + + }, + + /** + * Close WebSocket connection + * + * @param instanceId Instance ID + * @param code Close status code + * @param reasonPtr Pointer to reason string + */ + WebSocketClose: function(instanceId, code, reasonPtr) { + + var instance = webSocketState.instances[instanceId]; + if (!instance) return -1; + + if (!instance.ws) + return -3; + + if (instance.ws.readyState === 2) + return -4; + + if (instance.ws.readyState === 3) + return -5; + + var reason = ( reasonPtr ? UTF8ToString(reasonPtr) : undefined ); + + try { + instance.ws.close(code, reason); + } catch(err) { + return -7; + } + + return 0; + + }, + + /** + * Send message over WebSocket + * + * @param instanceId Instance ID + * @param bufferPtr Pointer to the message buffer + * @param length Length of the message in the buffer + */ + WebSocketSend: function(instanceId, bufferPtr, length) { + + var instance = webSocketState.instances[instanceId]; + if (!instance) return -1; + + if (!instance.ws) + return -3; + + if (instance.ws.readyState !== 1) + return -6; + + instance.ws.send(HEAPU8.buffer.slice(bufferPtr, bufferPtr + length)); + + return 0; + + }, + + /** + * Send text message over WebSocket + * + * @param instanceId Instance ID + * @param bufferPtr Pointer to the message buffer + * @param length Length of the message in the buffer + */ + WebSocketSendText: function(instanceId, message) { + + var instance = webSocketState.instances[instanceId]; + if (!instance) return -1; + + if (!instance.ws) + return -3; + + if (instance.ws.readyState !== 1) + return -6; + + instance.ws.send(UTF8ToString(message)); + + return 0; + + }, + + /** + * Return WebSocket readyState + * + * @param instanceId Instance ID + */ + WebSocketGetState: function(instanceId) { + + var instance = webSocketState.instances[instanceId]; + if (!instance) return -1; + + if (instance.ws) + return instance.ws.readyState; + else + return 3; + + } + +}; + +autoAddDeps(LibraryWebSocket, '$webSocketState'); +mergeInto(LibraryManager.library, LibraryWebSocket); diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.jslib.meta b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.jslib.meta new file mode 100644 index 0000000..6e7dc52 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/WebSocket.jslib.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: d4e1195d1a5508b419c5fc7120cba0ed +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + WebGL: WebGL + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/endel.nativewebsocket.asmdef b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/endel.nativewebsocket.asmdef new file mode 100644 index 0000000..871f704 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/endel.nativewebsocket.asmdef @@ -0,0 +1,3 @@ +{ + "name": "endel.nativewebsocket" +} diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/endel.nativewebsocket.asmdef.meta b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/endel.nativewebsocket.asmdef.meta new file mode 100644 index 0000000..78dd45f --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocket/endel.nativewebsocket.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: f3cf245a6f30d9740a037cf5cd3dfb43 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocketExample.meta b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocketExample.meta new file mode 100644 index 0000000..1d64930 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/WebSocketExample.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c66c722e6468770478c807f30bd55575 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/package.json b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/package.json new file mode 100644 index 0000000..fe13be4 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/package.json @@ -0,0 +1,32 @@ +{ + "name": "com.endel.nativewebsocket", + "version": "1.1.4", + "description": "WebSocket client for Unity - with no external dependencies (WebGL, Native, Android, iOS, UWP).", + "license": "Apache 2.0", + "repository": { + "type": "git", + "url": "https://github.com/endel/NativeWebSocket.git" + }, + "author": { + "name": "Endel Dreyer", + "email": "endel.dreyer@gmail.com", + "url": "https://github.com/endel/NativeWebSocket" + }, + "keywords": [ + "websocket", + "websockets", + "native websocket", + "native websockets" + ], + "displayName": "Native WebSockets", + "unity": "2019.1", + "dependencies": {}, + "samples": [ + { + "displayName": "Example", + "description": "WebSocket Example", + "path": "Samples~/WebSocketExample" + } + ], + "_fingerprint": "c5101c07762251edc82caad9e8a39d51b1229c31" +} diff --git a/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/package.json.meta b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/package.json.meta new file mode 100644 index 0000000..f45a8b7 --- /dev/null +++ b/Assets/SGModule/Net/SGModule/com.endel.nativewebsocket/package.json.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: de5c97ce7ae5a4a4b9da45566ae46222 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/NetKit.meta b/Assets/SGModule/NetKit.meta new file mode 100644 index 0000000..7cc1431 --- /dev/null +++ b/Assets/SGModule/NetKit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9bdcc53638bbc5b4dac6ed497f066341 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/NetKit/README.md b/Assets/SGModule/NetKit/README.md new file mode 100644 index 0000000..a443a86 --- /dev/null +++ b/Assets/SGModule/NetKit/README.md @@ -0,0 +1,62 @@ +# 🧰 NetKit 模块说明 + +`NetKit` 是一个网络接口相关工具模块,涵盖心跳、登录、网络核心、数据打点及数据结构等功能。 + +------ + +## 🚀 快速开始 + +1. **初始化网络组件** + + ```csharp + NetKit.Instance.Init(); + ``` + +2. **执行登录请求** + + ```csharp + LoginKit.Instance.LoginRequest(channel, haveSimCard, (success, loginModel) => { + if (success) { + // 登录成功逻辑 + } else { + // 登录失败逻辑 + } + }); + ``` + +3. **发送事件打点** + + ```csharp + TrackKit.SendEvent(ADEventTrack.Event, ADEventTrack.Property.fail_click); + ``` + +4. **开启心跳** + + ```csharp + HeartbeatKit.Instance.StartHeartbeat(); + ``` + +------ + +## 📦 模块介绍 + +| 模块名 | 功能描述 | +| -------------- | ------------------------------------- | +| `Model` | 📄 请求与响应数据模型定义 | +| `Core/NetKit` | ⚙️ 网络请求核心,管理请求与 Token | +| `Track` | 📊 事件与属性注册及数据打点 | +| `ErrorLogKit` | 🛠️ 异常日志收集及去重上报 | +| `HeartbeatKit` | ❤️ 心跳管理,确保连接持续活跃 | +| `LoginKit` | 🔐 登录请求、认证及状态管理 | +| `NetGmTool` | 🛠️ 本地调试辅助,支持 Token 和状态测试 | + +------ + +## 📖 说明 + +- **NetKit** 负责所有网络通信,自动处理数据加解密和 Token 刷新。 +- **TrackKit** 提供强大的事件打点功能,支持静态及动态事件注册。 +- **ErrorLogKit** 实现错误日志的收集、去重与上传,方便问题排查。 +- **HeartbeatKit** 管理心跳发送,支持应用前后台切换时的状态保存与恢复。 +- **LoginKit** 负责用户登录流程与自动重新认证逻辑。 +- **NetGmTool** 为游戏调试提供实用工具,方便状态和 Token 测试。 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/README.md.meta b/Assets/SGModule/NetKit/README.md.meta new file mode 100644 index 0000000..1fb77d1 --- /dev/null +++ b/Assets/SGModule/NetKit/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 461e8e64590ffe249b3f7c1451512685 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/NetKit/SGModule.meta b/Assets/SGModule/NetKit/SGModule.meta new file mode 100644 index 0000000..90574d7 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 377616a3c9914ce282defb0ea95df273 +timeCreated: 1750131791 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model.meta b/Assets/SGModule/NetKit/SGModule/Model.meta new file mode 100644 index 0000000..9ae490d --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c5faf4e0266639349b4b5bf725766915 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/NetKit/SGModule/Model/H5Model.cs b/Assets/SGModule/NetKit/SGModule/Model/H5Model.cs new file mode 100644 index 0000000..6b87037 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/H5Model.cs @@ -0,0 +1,13 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class H5RefreshTimes { + [JsonProperty("link")] public string Link; + [JsonProperty("times")] public int Times; + } + + public class H5SendClass { + [JsonProperty("link")] public string Link; + [JsonProperty("type")] public string Type; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/H5Model.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/H5Model.cs.meta new file mode 100644 index 0000000..0cdf8cc --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/H5Model.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f1b181d7aace436781161651452781e4 +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model/LoginModel.cs b/Assets/SGModule/NetKit/SGModule/Model/LoginModel.cs new file mode 100644 index 0000000..54cfc01 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/LoginModel.cs @@ -0,0 +1,22 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class LoginModel { + [JsonProperty("cdn_url")] public string CdnURL; + [JsonProperty("country")] public string Country; + [JsonProperty("debug_log")] public bool DebugLog = true; + [JsonProperty("enwp")] public int Enwp; + [JsonProperty("expires_at")] public long ExpiresAt; + [JsonProperty("invite_code")] public string InviteCode; + [JsonProperty("is_magic")] public bool IsMagic; + [JsonProperty("last_login_time")] public long LastLoginTime; + [JsonProperty("login_time")] public long LoginTime; + [JsonProperty("new_player")] public bool NewPlayer; + [JsonProperty("play_data")] public string PlayData; + [JsonProperty("play_data_ver")] public long PlayDataVer; + [JsonProperty("reg_time")] public long RegTime; + [JsonProperty("setting")] public string Setting; + [JsonProperty("token")] public string Token; + [JsonProperty("uid")] public long Uid; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/LoginModel.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/LoginModel.cs.meta new file mode 100644 index 0000000..20f6463 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/LoginModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: eb0f97d9dd47436985c16d162e2685f3 +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model/OrderModel.cs b/Assets/SGModule/NetKit/SGModule/Model/OrderModel.cs new file mode 100644 index 0000000..4e137e2 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/OrderModel.cs @@ -0,0 +1,30 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class OrderModel { + } + + public class PayOutUserInfoData { + [JsonProperty("email")] public string Email; + [JsonProperty("first_name")] public string FirstName; + [JsonProperty("last_name")] public string LastName; + } + + public class PayerData { + [JsonProperty("amount")] public int Amount; + [JsonProperty("email")] public string Email; + [JsonProperty("name")] public string Name; + [JsonProperty("tel")] public string Tel; + } + + public class OrderData { + [JsonProperty("code")] public int Code; + [JsonProperty("order_id")] public string OrderID; + [JsonProperty("pay_url")] public string PayURL; + } + + public class OrderState { + [JsonProperty("order_id")] public string OrderID; + [JsonProperty("status")] public int Status; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/OrderModel.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/OrderModel.cs.meta new file mode 100644 index 0000000..379a4ea --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/OrderModel.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 46a43334a3ce46a19994cde06807db90 +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model/RequestLoginData.cs b/Assets/SGModule/NetKit/SGModule/Model/RequestLoginData.cs new file mode 100644 index 0000000..a9e03be --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RequestLoginData.cs @@ -0,0 +1,16 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class RequestLoginData { + [JsonProperty("app_version")] public string AppVersion; + [JsonProperty("channel")] public string Channel; + [JsonProperty("device_id")] public string DeviceID; + [JsonProperty("pack_name")] public string PackName; + [JsonProperty("sim")] public bool Sim; + } + + public class RequestTokenData { + [JsonProperty("expires_at")] public long ExpiresAt; + [JsonProperty("token")] public string Token; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/RequestLoginData.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/RequestLoginData.cs.meta new file mode 100644 index 0000000..50182ac --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RequestLoginData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 1fbee719fd2e44ef80b7316d0dbf86bc +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model/RequestResultData.cs b/Assets/SGModule/NetKit/SGModule/Model/RequestResultData.cs new file mode 100644 index 0000000..1b1cd62 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RequestResultData.cs @@ -0,0 +1,8 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class RequestResultData { + [JsonProperty("result")] public string Result; + [JsonProperty("type")] public int Type; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/RequestResultData.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/RequestResultData.cs.meta new file mode 100644 index 0000000..7bf1a9f --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RequestResultData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 47baead934174984ba39556242043834 +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model/RequestSavePlayData.cs b/Assets/SGModule/NetKit/SGModule/Model/RequestSavePlayData.cs new file mode 100644 index 0000000..123c873 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RequestSavePlayData.cs @@ -0,0 +1,8 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class RequestSavePlayData { + [JsonProperty("data")] public string Data; + [JsonProperty("version")] public long Version; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/RequestSavePlayData.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/RequestSavePlayData.cs.meta new file mode 100644 index 0000000..867a6fe --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RequestSavePlayData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0be72479fa3145a08ea156a655a15439 +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model/RequestStageData.cs b/Assets/SGModule/NetKit/SGModule/Model/RequestStageData.cs new file mode 100644 index 0000000..e2569aa --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RequestStageData.cs @@ -0,0 +1,15 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class RequestStageData { + [JsonProperty("begin_time")] public int BeginTime; + [JsonProperty("end_time")] public int EndTime; + [JsonProperty("item_costs")] public int[] ItemCosts; + [JsonProperty("item_type")] public int ItemType; + [JsonProperty("layer")] public int Layer; + [JsonProperty("level")] public int Level; + [JsonProperty("pass")] public bool Pass; + [JsonProperty("remove_item")] public int RemoveItem; + [JsonProperty("total_item")] public int TotalItem; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/RequestStageData.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/RequestStageData.cs.meta new file mode 100644 index 0000000..b01bab0 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RequestStageData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 74a78e3c4c5342d58c8b7c7f8fa1ebac +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model/RespDebugData.cs b/Assets/SGModule/NetKit/SGModule/Model/RespDebugData.cs new file mode 100644 index 0000000..c3917d3 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RespDebugData.cs @@ -0,0 +1,17 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class RespDebugData { + [JsonProperty("channel")] public string Channel; + [JsonProperty("device")] public string Device; + [JsonProperty("device_id")] public string DeviceID; + [JsonProperty("level")] public string Level; + [JsonProperty("message")] public string Message; + [JsonProperty("network")] public string Network; + [JsonProperty("os_ver")] public string OSVer; + [JsonProperty("pack_name")] public string PackName; + [JsonProperty("stacktrace")] public string Stacktrace; + [JsonProperty("uid")] public long Uid; + [JsonProperty("version")] public string Version; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/RespDebugData.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/RespDebugData.cs.meta new file mode 100644 index 0000000..60e4b38 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RespDebugData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: d6e06882fc534baeb5b28e1c969c9f3b +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model/RespLoginFunnelData.cs b/Assets/SGModule/NetKit/SGModule/Model/RespLoginFunnelData.cs new file mode 100644 index 0000000..138e39e --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RespLoginFunnelData.cs @@ -0,0 +1,14 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class RespLoginFunnelData { + [JsonProperty("channel")] public string Channel; + [JsonProperty("device_id")] public string DeviceID; + [JsonProperty("pack_name")] public string PackName; + [JsonProperty("payload")] public string Payload; + [JsonProperty("trace_id")] public string TraceID; + [JsonProperty("type")] public string Type; + [JsonProperty("uid")] public long Uid; + [JsonProperty("version")] public string Version; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/RespLoginFunnelData.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/RespLoginFunnelData.cs.meta new file mode 100644 index 0000000..0997223 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/RespLoginFunnelData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 74c68fa36c4649c283f499dbc71204cb +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Model/TrackData.cs b/Assets/SGModule/NetKit/SGModule/Model/TrackData.cs new file mode 100644 index 0000000..f9dd9bb --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/TrackData.cs @@ -0,0 +1,9 @@ +using Newtonsoft.Json; + +namespace SGModule.NetKit { + public class TrackData { + [JsonProperty("event")] public string Event; + [JsonProperty("n")] public int N; + [JsonProperty("property")] public string Property; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Model/TrackData.cs.meta b/Assets/SGModule/NetKit/SGModule/Model/TrackData.cs.meta new file mode 100644 index 0000000..391abf6 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Model/TrackData.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 07578d2c40f54591b67a1897fea057f7 +timeCreated: 1750149344 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts.meta b/Assets/SGModule/NetKit/SGModule/Scripts.meta new file mode 100644 index 0000000..42a4ca7 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a4e6e38198f91e545ae7b37e06c9a7de +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Core.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Core.meta new file mode 100644 index 0000000..600cf6c --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Core.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 817656c157454e70a7bf6677e6f2eb34 +timeCreated: 1750318367 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Core/NetKit.cs b/Assets/SGModule/NetKit/SGModule/Scripts/Core/NetKit.cs new file mode 100644 index 0000000..cad4b0d --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Core/NetKit.cs @@ -0,0 +1,96 @@ +using System.Collections; +using System.Collections.Generic; +using SGModule.Common; +using SGModule.Common.Helper; +using SGModule.Net; +using UnityEngine.Events; + +namespace SGModule.NetKit { + public class NetKit : NetCore { + public void Init() { + Log.NetKit.Info("NetworkKit Init!!!!!"); + } + + protected override string Encrypt(string text, string key) { + return ConfigManager.GameConfig.isRelease ? Cryptor.Encrypt(text, key) : text; + } + + protected override string Decrypt(string text, string key) { + return ConfigManager.GameConfig.isRelease ? Cryptor.Decrypt(text, key) : text; + } + + protected override TokenManager.RefreshTokenDelegate RefreshTokenHandler() { + return onCompleted => PostAsync( + "tokenRefresh", + onCompleted: response => { + if (response.IsSuccess) { + var token = response.Data.Token; + var expiresAt = response.Data.ExpiresAt; + onCompleted?.Invoke(token, expiresAt); + } + else { + onCompleted?.Invoke(null, 0); + } + }); + } + + protected override TokenManager.ReauthenticateDelegate ReauthenticateHandler() { + return onCompleted => LoginKit.Instance.ReauthenticateOnExpiration(success => { + if (success) { + var model = LoginKit.Instance.LoginModel; + onCompleted?.Invoke(model.Token, model.ExpiresAt); + } + else { + onCompleted?.Invoke(null, 0); + } + }); + } + + protected override NetCoreModel ProvideConfig() { + var netConf = ConfigManager.NetworkConfig; + return new NetCoreModel { + RequestHost = ConfigManager.GameConfig.isRelease ? netConf.releaseHost : netConf.debugHost, + ConnMode = netConf.connectionMode + }; + } + + /// + /// Post请求(异步) + /// + /// 请求路径 + /// 请求参数 + /// 请求回调 + /// 是否带Token + /// 额外的请求头 + public new IEnumerator PostAsync(string path, object requestData = null, UnityAction> onCompleted = null, bool withToken = true, Dictionary headers = null) { + return base.PostAsync(path, requestData, onCompleted, withToken, headers); + } + + /// + /// Post请求 + /// + /// 请求路径 + /// 请求参数 + /// 请求回调 + /// 是否带Token + /// 是否使用协程 + /// 额外的请求头 + public void Post(string path, object requestData = null, UnityAction> onCompleted = null, bool withToken = true, bool useCoroutine = true, Dictionary headers = null) { + base.Post(path, requestData, onCompleted, withToken, useCoroutine, headers); + } + + /// + /// Post请求(泛型) + /// + /// 请求路径 + /// 请求参数 + /// 请求回调 + /// 是否带Token + /// 是否使用协程 + /// 额外的请求头 + /// 返回数据中Data的类型 + public new void Post(string path, object requestData = null, UnityAction> onCompleted = null, bool withToken = true, bool useCoroutine = true, Dictionary headers = null) { + base.Post(path, requestData, onCompleted, withToken, useCoroutine, headers); + } + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Core/NetKit.cs.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Core/NetKit.cs.meta new file mode 100644 index 0000000..b6fbd8d --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Core/NetKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 2f42dbabd49047c1af47fd8e5b5e32c7 +timeCreated: 1750148161 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Kits.meta new file mode 100644 index 0000000..77173d3 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 701ea16802aa4ad5b5655d0f7e785345 +timeCreated: 1750318405 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/ErrorLogKit.cs b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/ErrorLogKit.cs new file mode 100644 index 0000000..a879e80 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/ErrorLogKit.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using SGModule.Common.Helper; +using UnityEngine; +using UnityEngine.Events; + +namespace SGModule.NetKit { + public static class ErrorLogKit { + private static readonly Dictionary> _statusDic = new(); + private static bool _isErrorLoggingEnabled = true; + + /// + /// 初始化方法 + /// + /// 是否开启错误日志上报 + public static void Init(bool isErrorLoggingEnabled) { + _isErrorLoggingEnabled = isErrorLoggingEnabled; + } + + /// + /// 发送错误日志 + /// + /// + /// + /// + /// + public static void Send(string level, string message, string stackTrace, string attribution = "organic") { + if (!_isErrorLoggingEnabled) { + return; + } + + // 如果只需要日期部分,可以使用ToShortDateString()或ToString("yyyy-MM-dd")等进行格式化 + var currentDate = DateTime.Now; + var formattedDate = currentDate.ToString("yyyy_MM_dd_HH_mm"); + + var md5Str = MD5Helper.GetStringMD5(message + stackTrace); + + if (!_statusDic.ContainsKey(formattedDate)) { + _statusDic.Add(formattedDate, new Dictionary()); + } + + if (_statusDic[formattedDate].ContainsKey(md5Str)) { + return; + } + + _statusDic[formattedDate].Add(md5Str, true); + + SendLogToServer(level, message, stackTrace, attribution); + } + + public static void SendDebugToServer(string error, string stackTrace = "") + { + Send("debug", error, stackTrace); + } + + + private static void SendLogToServer(string level, string message, string stackTrace, string attribution, UnityAction callback = null) { + var requestData = new RespDebugData { + Channel = attribution, + Uid = LoginKit.Instance.LoginModel?.Uid ?? -1, + Device = SystemInfo.deviceModel, + OSVer = SystemInfo.operatingSystem, + Network = GetNetworkType(), + DeviceID = DeviceHelper.GetDeviceID(), + PackName = Application.identifier, + Version = Application.version, + Level = level, + Message = message, + Stacktrace = stackTrace + }; + + NetKit.Instance.Post("event/cliDebugLog", requestData, response => { + callback?.Invoke(response.IsSuccess); + }, false); + } + + private static string GetNetworkType() { + return Application.internetReachability switch { + NetworkReachability.ReachableViaCarrierDataNetwork => "Mobile Data", + NetworkReachability.ReachableViaLocalAreaNetwork => "Wi-Fi", + _ => "Not Connected" + }; + } + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/ErrorLogKit.cs.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/ErrorLogKit.cs.meta new file mode 100644 index 0000000..5109db7 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/ErrorLogKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 7a44a0584561409fbbe702a3b9f563f4 +timeCreated: 1731321384 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/HeartbeatKit.cs b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/HeartbeatKit.cs new file mode 100644 index 0000000..213d451 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/HeartbeatKit.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections; +using SGModule.Common; +using SGModule.Common.Base; +using SGModule.Common.Helper; +using SGModule.Net; +using UnityEngine; + +namespace SGModule.NetKit { + public class HeartbeatKit : SingletonMonoBehaviour { + private Coroutine _heartbeatCoroutine; + private static int HeartbeatInterval => 60; + private const string HeartbeatForegroundTime = "HeartbeatForegroundTime"; + + /// + /// 后台时逻辑 + /// + /// + private void OnApplicationPause(bool pauseStatus) { + Log.NetKit.Warning($"OnApplication Pause :{pauseStatus}"); + // 应用程序失去焦点 + if (pauseStatus) { + SaveRemainingHeartbeatTime(); + } + else { + RestoreNextHeartbeatTime(); + } + } + + // 应用程序退出 + private void OnApplicationQuit() { + Log.NetKit.Warning("OnApplication Quit"); + + SaveRemainingHeartbeatTime(); + } + + public void StartHeartbeat() { + _heartbeatCoroutine??= StartCoroutine(HeartbeatRequestCoroutine()); + } + + private IEnumerator HeartbeatRequestCoroutine() { + RestoreNextHeartbeatTime(); // 恢复之前剩余时间或默认值 + + while (true) { + if (Now() >= NextHeartbeatTime) { + NextHeartbeatTime += HeartbeatInterval; + RequestHeart(); + } + + yield return new WaitForSeconds(1); + } + } + + // 应用程序失去焦点, 保存心跳剩余时间 + private void SaveRemainingHeartbeatTime() { + var remain = Math.Max((int) (NextHeartbeatTime - Now()), 0); + LastRemainingInterval = remain % HeartbeatInterval; + } + + + // 应用程序获得焦点, 恢复下次心跳时间 + private void RestoreNextHeartbeatTime() { + var now = Now(); + if (LastRemainingInterval < 0) { + NextHeartbeatTime = now; + return; + } + + var remain = LastRemainingInterval % HeartbeatInterval; + if (remain <= 0) { + remain = HeartbeatInterval; + } + + NextHeartbeatTime = now + remain; + } + + private long _nextHeartbeatTime; + + private long NextHeartbeatTime { + get { + if (_nextHeartbeatTime <= 0) { + _nextHeartbeatTime = Now() + HeartbeatInterval; + } + + return _nextHeartbeatTime; + } + set { + var now = Now(); + if (value <= now) { + value = now + HeartbeatInterval; + } + + _nextHeartbeatTime = value; + } + } + + private int? _lastRemainingInterval; + + private int LastRemainingInterval { + get { + if (_lastRemainingInterval != null) { + return _lastRemainingInterval.Value; + } + + _lastRemainingInterval = PlayerPrefs.GetInt(HeartbeatForegroundTime, -1); + + return _lastRemainingInterval.Value; + } + set { + _lastRemainingInterval = value; + PlayerPrefs.SetInt(HeartbeatForegroundTime, value); + } + } + + + private void RequestHeart() { + if (ConfigManager.NetworkConfig.connectionMode == ConnectionMode.WebSocket) { + WebSocketService.Instance.SendHeartbeat(); + } + else { + NetKit.Instance.Post("user/health"); + } + } + + private static long Now() { + return DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + } + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/HeartbeatKit.cs.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/HeartbeatKit.cs.meta new file mode 100644 index 0000000..0c8d840 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/HeartbeatKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: efd2140efaf44544a7879ad411a0cf84 +timeCreated: 1750147028 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/LoginKit.cs b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/LoginKit.cs new file mode 100644 index 0000000..4f6a3b6 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/LoginKit.cs @@ -0,0 +1,127 @@ +using System.Collections; +using SGModule.Common; +using SGModule.Common.Base; +using SGModule.Common.Helper; +using SGModule.Net; +using UnityEngine; +using UnityEngine.Events; + +namespace SGModule.NetKit +{ + public class LoginKit : SingletonMonoBehaviour + { + private string _channel; + private bool _sim; + private bool _loginSuccess; + private LoginModel _loginModel; + private bool _isFirstLoginSuccess = true; + private RequestLoginData _requestLoginData; + private string _packName; + + + public string Channel => _channel; + + public void LoginRequest(string channel, bool haveSimCard, UnityAction onCompleted) + { + _packName = ConfigManager.GameConfig.packageName; + _channel = string.IsNullOrEmpty(channel) ? "organic" : channel; + _sim = haveSimCard; + + _requestLoginData = new RequestLoginData + { + DeviceID = DeviceHelper.GetDeviceID(), + AppVersion = Application.version, + PackName = _packName, + Channel = _channel, + Sim = _sim + }; + StartCoroutine(LoginCoroutine(_requestLoginData, (isSuccess, loginModel) => + { + if (isSuccess) + { + OnLoginSuccess(); + } + + onCompleted?.Invoke(isSuccess, loginModel); + })); + } + + public IEnumerator ReauthenticateOnExpiration(UnityAction onCompleted) + { + if (_requestLoginData == null) + { + Log.NetKit.Error("登录数据为空,重新登录失败"); + onCompleted?.Invoke(false); + yield break; + } + + yield return LoginCoroutine(_requestLoginData, (isSuccess, _) => + { + onCompleted?.Invoke(isSuccess); + }); + } + + private IEnumerator LoginCoroutine(RequestLoginData reqData, UnityAction onCompleted) + { + const int maxRetry = 5; + for (var attempt = 0; attempt < maxRetry; attempt++) + { + if (attempt > 0) + { + Log.NetKit.Warning($"登录失败,重试第 {attempt} 次..."); + yield return new WaitForSeconds(5f); + } + + yield return DoLoginRequest(reqData); + + if (_loginSuccess) + { + onCompleted?.Invoke(true, _loginModel); + yield break; + } + } + +// Log.NetKit.Error("登录最终失败"); + onCompleted?.Invoke(false, null); + } + + private IEnumerator DoLoginRequest(RequestLoginData reqData) + { + yield return NetKit.Instance.PostAsync( + "login", + reqData, + response => + { + _loginSuccess = response.IsSuccess; + _loginModel = response.Data; + }, + withToken: false + ); + } + + private void OnLoginSuccess() + { + Log.NetKit.Info("登录成功,处理登录后逻辑"); + + ServerClock.Init(_loginModel.LoginTime); + + Net.TokenManager.Instance.UpdateTokenCache(_loginModel.Token, _loginModel.ExpiresAt); + + ErrorLogKit.Init(_loginModel.DebugLog); + + + // 开始心跳 + HeartbeatKit.Instance.StartHeartbeat(); + + + StartCoroutine(TrackKit.NoSentTrackProcessing()); // 处理堆积的打点数据 + } + + + public LoginModel LoginModel => _loginModel ??= new LoginModel(); + + + + public bool LoginSuccess => _loginSuccess; + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/LoginKit.cs.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/LoginKit.cs.meta new file mode 100644 index 0000000..348391b --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/LoginKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: c4397a02039f4461bd27548285617aa2 +timeCreated: 1731380564 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/NetGmTool.cs b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/NetGmTool.cs new file mode 100644 index 0000000..ca4d6e0 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/NetGmTool.cs @@ -0,0 +1,51 @@ +using SGModule.Common.Base; +using SGModule.Common.Helper; +using SGModule.Net; + +namespace SGModule.NetKit { + public class NetGmTool : SingletonMonoBehaviour { + public void Init() { + GMTool.Instance.AddItem(new GMToolItem(GUIType.Separator, () => "网络模块")); + GMTool.Instance.AddItem( + new GMToolItem(GUIType.Label, () => $"当前网络状态:{NetChecker.Instance.GetConnectionStatus()}")); + GMTool.Instance.AddItem(new GMToolItem(GUIType.Label, + () => $"loginModel uid:{(LoginKit.Instance.LoginModel == null ? "null" : LoginKit.Instance.LoginModel.Uid)}")); + GMTool.Instance.AddItem(new GMToolItem(GUIType.Label, + () => + $"Token过期时间:{TimeHelper.ConvertToLocalTime(TokenManager.Instance.CachedExpiresAt)}")); + + GMTool.Instance.AddItem(new GMToolItem(GUIType.Label, + () => { + var str = ""; + foreach (var record in Net.TokenManager.Instance.GetTokenRecord()) { + str += $"Token: {record} " + "\n"; + } + + return str; + }) + ); + GMTool.Instance.AddItem(new GMToolItem(GUIType.Button, () => "Token刷新测试", + s => { + VerifyTokenExpiryImminent(); + })); + GMTool.Instance.AddItem(new GMToolItem(GUIType.Button, () => "Token过期测试", + s => { + VerifyTokenExpirationBehavior(); + })); + } + + /// + /// Token即将过期(测试功能用) + /// + public void VerifyTokenExpiryImminent() { + TokenManager.Instance.CachedExpiresAt -= 85400; + } + + /// + /// token过期(测试功能用) + /// + public void VerifyTokenExpirationBehavior() { + TokenManager.Instance.CachedExpiresAt -= 86400; + } + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/NetGmTool.cs.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/NetGmTool.cs.meta new file mode 100644 index 0000000..158c0eb --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/NetGmTool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4fc2222765694fea9075b15bca3cb0ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track.meta new file mode 100644 index 0000000..0a8195c --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: fd3b50565e714d6f8e3ce3b99665ba08 +timeCreated: 1750318517 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackEvent.cs b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackEvent.cs new file mode 100644 index 0000000..7030021 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackEvent.cs @@ -0,0 +1,46 @@ +using System.Collections.Generic; +using System.Linq; +using SGModule.Common.Helper; + +namespace SGModule.NetKit { + public static class TrackEvent { + private static readonly HashSet _registeredStaticEvents = new(); + private static readonly HashSet _registeredDynamicEventPrefixes = new(); + + + public static string Register(string eventKey, bool isDynamic = false) { + var targetSet = isDynamic ? _registeredDynamicEventPrefixes : _registeredStaticEvents; + + if (!targetSet.Add(eventKey)) + { + var type = isDynamic ? "动态" : "静态"; + Log.NetKit.Error($"[Track] 重复的{type} Event 注册: {eventKey}"); + } + + return eventKey; + + } + + + /// + /// 是否为注册的静态 property(完全匹配) + /// + private static bool ContainsExact(string eventKey) { + return _registeredStaticEvents.Contains(eventKey); + } + + /// + /// 是否匹配任何已注册的动态前缀 + /// + private static bool ContainsDynamic(string eventKey) { + return _registeredDynamicEventPrefixes.Any(eventKey.StartsWith); + } + + /// + /// 检查是否存在(静态或动态) + /// + public static bool Contains(string eventKey) { + return ContainsExact(eventKey) || ContainsDynamic(eventKey); + } + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackEvent.cs.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackEvent.cs.meta new file mode 100644 index 0000000..598ef07 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackEvent.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: b125ff11596c4c639f9b69eedf446e6b +timeCreated: 1750319472 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackKit.cs b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackKit.cs new file mode 100644 index 0000000..28054a8 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackKit.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using SGModule.Common; +using SGModule.Common.Helper; +using UnityEngine; +using UnityEngine.Events; + +namespace SGModule.NetKit { + public static class TrackKit { + private static string _traceID; + private static readonly Dictionary _statusDic = new(); + + //登录前的打点数据,没有token无法正确发送,登录成功后重新发一遍 + private static readonly Queue _waitLoginSuccessTrackQueue = new(); + + private static void PostTrack(TrackData trackData, UnityAction callback = null) { + if (!LoginKit.Instance.LoginSuccess) { + _waitLoginSuccessTrackQueue.Enqueue(trackData); + return; + } + + NetKit.Instance.Post("/event/incrN", trackData, + response => { + callback?.Invoke(response.IsSuccess, response.Data); + }); + } + + /// + /// 发送未发送的打点数据 + /// + /// + public static IEnumerator NoSentTrackProcessing() { + //处理未发送的打点数据 + while (_waitLoginSuccessTrackQueue.Count > 0) { + var trackData = _waitLoginSuccessTrackQueue.Dequeue(); + PostTrack(trackData); + + yield return new WaitForSeconds(1f); + } + + _waitLoginSuccessTrackQueue.Clear(); + } + + + public static void SendEvent(string @event, string property = "", int n = 1) { + // 检查Key是否注册 + if (!TrackEvent.Contains(@event)) { + Log.NetKit.Warning($"Not found event key: {@event}"); + return; + } + + if (!TrackProperty.Contains(property)) { + Log.NetKit.Warning($"Not found property key: {property}"); + return; + } + + var data = new TrackData { Event = @event, Property = property, N = n }; + + Log.NetKit.Info($"Sending track {data.Event} | {data.Property} | {data.N}"); + + PostTrack(data); + } + + + #region 登录漏斗 + + private static readonly Dictionary _loginFunnelEventMap = new() { + { LoginFunnelEventType.Bootstrap, "bootstrap" }, + { LoginFunnelEventType.AfSend, "afSend" }, + { LoginFunnelEventType.AfRecv, "afRecv" }, + { LoginFunnelEventType.LoginSend, "loginSend" }, + { LoginFunnelEventType.LoginRecv, "loginRecv" }, + { LoginFunnelEventType.LoadBegin, "loadBegin" }, + { LoginFunnelEventType.LoadFinish, "loadFinish" }, + { LoginFunnelEventType.EnterButtonShow, "enterButtonShow" }, + { LoginFunnelEventType.EnterButtonClick, "enterButtonClick" }, + { LoginFunnelEventType.EnterHall, "enterHall" }, + }; + + /// + /// 登录漏斗打点 + /// + /// + /// + /// + public static void TrackLoginFunnel(LoginFunnelEventType loginFunnelEventType, string message = "") { + if (!_loginFunnelEventMap.TryGetValue(loginFunnelEventType, out var trackName)) { + throw new ArgumentOutOfRangeException(nameof(loginFunnelEventType), loginFunnelEventType, null); + } + + if (_statusDic.TryGetValue(trackName, out var status)) { + if (status) { + return; + } + } + + _statusDic.Add(trackName, true); + + PostFunnelLogin(trackName, message); + } + + + private static void PostFunnelLogin(string type, string payload) { + if (type == "bootstrap") { + var timestamp = DateTime.Now.ToUniversalTime().Ticks - 621355968000000000; + _traceID = timestamp.ToString(); + } + + var requestData = new RespLoginFunnelData { + Uid = LoginKit.Instance.LoginModel?.Uid ?? -1, + TraceID = _traceID, + DeviceID = DeviceHelper.GetDeviceID(), + PackName = ConfigManager.GameConfig.packageName, + Version = Application.version, + Channel = LoginKit.Instance.Channel, + Type = type, + Payload = payload + }; + + NetKit.Instance.Post("event/funnelLogin", requestData, withToken: false); + } + + #endregion + } + + public enum LoginFunnelEventType { + Bootstrap, + AfSend, + AfRecv, + LoginSend, + LoginRecv, + LoadBegin, + LoadFinish, + EnterButtonShow, + EnterButtonClick, + EnterHall + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackKit.cs.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackKit.cs.meta new file mode 100644 index 0000000..fb356d8 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackKit.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 26c30475fb634d57b705e283a0f5b943 +timeCreated: 1731395165 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackProperty.cs b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackProperty.cs new file mode 100644 index 0000000..56ebd54 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackProperty.cs @@ -0,0 +1,43 @@ +using System.Collections.Generic; +using System.Linq; +using SGModule.Common.Helper; + +namespace SGModule.NetKit { + public static class TrackProperty { + private static readonly HashSet _registeredStaticProperties = new(); + private static readonly HashSet _registeredDynamicPropertyPrefixes = new(); + + public static string Register(string propertyKey, bool isDynamic = false) { + var targetSet = isDynamic ? _registeredDynamicPropertyPrefixes : _registeredStaticProperties; + + if (!targetSet.Add(propertyKey)) { + var type = isDynamic ? "动态" : "静态"; + Log.NetKit.Error($"[Track] 重复的{type} Property 注册: {propertyKey}"); + } + + return propertyKey; + } + + + /// + /// 是否为注册的静态 property(完全匹配) + /// + private static bool ContainsExact(string propertyKey) { + return _registeredStaticProperties.Contains(propertyKey); + } + + /// + /// 是否匹配任何已注册的动态前缀 + /// + private static bool ContainsDynamic(string propertyKey) { + return _registeredDynamicPropertyPrefixes.Any(propertyKey.StartsWith); + } + + /// + /// 检查是否存在(静态或动态) + /// + public static bool Contains(string propertyKey) { + return ContainsExact(propertyKey) || ContainsDynamic(propertyKey); + } + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackProperty.cs.meta b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackProperty.cs.meta new file mode 100644 index 0000000..ed69174 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/Kits/Track/TrackProperty.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 3265ffa2bf4b44cfbb3ee93a91692c59 +timeCreated: 1750319513 \ No newline at end of file diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/NetApi.cs b/Assets/SGModule/NetKit/SGModule/Scripts/NetApi.cs new file mode 100644 index 0000000..1168c58 --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/NetApi.cs @@ -0,0 +1,136 @@ +using SGModule.Common.Helper; +using UnityEngine.Events; + +namespace SGModule.NetKit { + public static class NetApi { + #region 玩家数据 + + public static void RequestPlayerData(UnityAction onCompleted) { + NetKit.Instance.Post("user/userData", onCompleted: response => { + onCompleted?.Invoke(response.IsSuccess, response.Data); + }); + } + + /// + /// 立即发送请求更新用户数据 + /// + /// + /// + public static void UploadPlayerDataUpdate(long version, string data) { + var requestSavePlayData = new RequestSavePlayData { + Version = version, + Data = data + }; + NetKit.Instance.Post("user/updateData", requestSavePlayData, useCoroutine: false); + } + + + /// + /// 启动协程更新用户数据 + /// + /// + /// + /// + public static void UploadPlayerDataUpdate(long version, string data, UnityAction onCompleted) { + var requestSavePlayData = new RequestSavePlayData { + Version = version, + Data = data + }; + NetKit.Instance.Post("user/updateData", requestSavePlayData, + response => { + onCompleted?.Invoke(response.IsSuccess); + }); + } + + public static void DeltaUpdateData(long version, string data, UnityAction onCompleted) { + var requestSavePlayData = new RequestSavePlayData { + Version = version, + Data = data + }; + NetKit.Instance.Post("user/deltaUpdateData", requestSavePlayData, + response => { + onCompleted?.Invoke(response.IsSuccess); + }); + } + + #endregion + + + #region Pay + + public static void PixPayIn(string account, string phone, string email, int amount, + UnityAction onCompleted = null) { + var data = new PayerData { + Name = account, + Tel = phone, + Email = email, + Amount = amount + }; + + NetKit.Instance.Post("shop/pixPayIn", data, + response => { + onCompleted?.Invoke(response.IsSuccess, response.Data); + }); + } + + public static void PixPayOrderQuery(string orderID, UnityAction onCompleted = null) { + var data = new OrderData { + OrderID = orderID + }; + + NetKit.Instance.Post("shop/pixPayOrderQuery", data, + response => { + onCompleted?.Invoke(response.IsSuccess, response.Data); + }); + } + + public static void PayOutUserInfo(string email, string firstName, string lastName, + UnityAction onCompleted = null) { + var data = new PayOutUserInfoData { + Email = email, + FirstName = firstName, + LastName = lastName + }; + + NetKit.Instance.Post("shop/payOutUserInfo", data, + response => { + onCompleted?.Invoke(response.IsSuccess, response.Data); + }); + } + + #endregion + + + #region H5 + + public static void H5RefreshTimes(string link, string type, UnityAction onCompleted = null) { + var info = new H5SendClass { + Link = link, + Type = type + }; + NetKit.Instance.Post("event/h5Impressions", info, + response => { + onCompleted?.Invoke(response.IsSuccess, response.Data); + }); + } + + #endregion + + + #region 结算上传 + + public static void SettleUp(int gameType, RequestStageData stageData, UnityAction onCompleted = null) { + var requestJson = SerializeHelper.ToJsonIndented(stageData); + var reqData = new RequestResultData { + Type = gameType, + Result = requestJson + }; + + NetKit.Instance.Post("game/settleUp", reqData, response => { + onCompleted?.Invoke(response.IsSuccess); + }); + } + + #endregion + } +} diff --git a/Assets/SGModule/NetKit/SGModule/Scripts/NetApi.cs.meta b/Assets/SGModule/NetKit/SGModule/Scripts/NetApi.cs.meta new file mode 100644 index 0000000..12b425f --- /dev/null +++ b/Assets/SGModule/NetKit/SGModule/Scripts/NetApi.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 518e3aed166f4dce98dbaed4a0dca443 +timeCreated: 1750316780 \ No newline at end of file diff --git a/ProjectSettings/ProjectSettings.asset b/ProjectSettings/ProjectSettings.asset index 18a3c2a..70d16fc 100644 --- a/ProjectSettings/ProjectSettings.asset +++ b/ProjectSettings/ProjectSettings.asset @@ -141,7 +141,7 @@ PlayerSettings: loadStoreDebugModeEnabled: 0 visionOSBundleVersion: 1.0 tvOSBundleVersion: 1.0 - bundleVersion: 1.0.0 + bundleVersion: 1.0.1 preloadedAssets: [] metroInputSource: 0 wsaTransparentSwapchain: 0