using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Networking; using UnityEngine.Tilemaps; using Object = UnityEngine.Object; [assembly: System.Reflection.AssemblyMetadata("Notice", "Copyright (c) casualexpie. Source available at https://opensource.smellypawz.com under the casualexpie Source-Available License. You may read and build it for yourself; don't redistribute, sell or reuse the code without permission.")] namespace SaveAnywhere { [BepInPlugin("saveanywhere", "Save Anywhere", Plugin.Version)] public class Plugin : BaseUnityPlugin { public const string Version = "1.8.1"; public const string BugsUrl = "https://www.nexusmods.com/scavprototype/mods/885?tab=bugs"; internal static ManualLogSource Log; internal static ConfigEntry SaveKey; internal static ConfigEntry EnemyRadius; internal static Harmony HarmonyInstance; internal static ConfigEntry AutoSave; internal static ConfigEntry AutoSaveMinutes; internal static ConfigEntry AutoSaveOnNewLayer; internal static ConfigEntry SlotCount; internal static ConfigEntry CloudEnabled; internal static ConfigEntry CloudAsked; internal static ConfigEntry ShowCheatFlag; private void Awake() { Log = Logger; SaveKey = Config.Bind("Hotkeys", "SaveKey", new KeyboardShortcut(KeyCode.F5), "Saves the game where you stand."); EnemyRadius = Config.Bind("Safety", "EnemyRadius", 15f, "Saving is blocked while a living enemy is closer than this (meters)."); AutoSave = Config.Bind("AutoSave", "Enabled", true, "Save automatically during a run. Can also be toggled from the pause menu."); AutoSaveMinutes = Config.Bind("AutoSave", "IntervalMinutes", 5f, "Minutes of play between auto-saves (minimum 1). Paused time doesn't count."); AutoSaveOnNewLayer = Config.Bind("AutoSave", "SaveOnNewLayer", true, "Also auto-save about 10 seconds after you arrive on a new layer."); SlotCount = Config.Bind("Slots", "SlotCount", 5, "How many manual save slots to show (1-10). Auto-save always has its own extra slot."); CloudEnabled = Config.Bind("Cloud", "Enabled", false, "Very experimental: upload your save slots to the Save Anywhere cloud so you can continue on another PC or Steam Deck. Turn it on or off with the Cloud saves button under SAVE SLOTS on the main menu."); CloudAsked = Config.Bind("Cloud", "Asked", false, "Whether you have already answered the cloud saves question. Set to false to see it again."); ShowCheatFlag = Config.Bind("Debug", "ShowCheatedFlag", true, "Debug: show on the SAVE SLOTS screen whether the game marked each save as cheated (Cheated: TRUE or FALSE)."); if (DemoGuard.IsDemo()) { Log.LogWarning("Casualties: Unknown demo detected (game version " + Application.version + "). Save Anywhere only works with the full game, so it has turned itself off."); DemoGuard.ShowPopup(); return; } Boot(); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private void Boot() { HarmonyInstance = new Harmony("saveanywhere"); HarmonyInstance.PatchAll(); Runner.Ensure(); Log.LogInfo("Save Anywhere " + Version + " loaded. " + SaveKey.Value + " or the pause menu to save. Game version " + Application.version + "."); } } internal static class DemoGuard { public const string StoreUrl = "https://store.steampowered.com/app/4576490/"; private static readonly string[] FullGameOnly = { "EndLabScript", "BlueHeart", "WWMRLight" }; public static bool IsDemo() { int missing = 0; foreach (string n in FullGameOnly) if (Type.GetType(n + ", Assembly-CSharp", false) == null) missing++; return missing == FullGameOnly.Length; } public static void ShowPopup() { GameObject go = new GameObject("SaveAnywhereDemoNotice"); go.hideFlags = HideFlags.HideAndDontSave; Object.DontDestroyOnLoad(go); go.AddComponent(); } } internal class DemoPopup : MonoBehaviour { private bool open = true; private GameObject blocker; private GUIStyle title, body, btn; private void Update() { if (open && blocker == null) { blocker = new GameObject("SaveAnywhereDemoBlocker"); DontDestroyOnLoad(blocker); Canvas c = blocker.AddComponent(); c.renderMode = RenderMode.ScreenSpaceOverlay; c.sortingOrder = 32766; blocker.AddComponent(); GameObject p = new GameObject("Blocker"); p.transform.SetParent(blocker.transform, false); UnityEngine.UI.Image img = p.AddComponent(); img.color = new Color(0f, 0f, 0f, 0f); RectTransform rt = img.rectTransform; rt.anchorMin = Vector2.zero; rt.anchorMax = Vector2.one; rt.offsetMin = Vector2.zero; rt.offsetMax = Vector2.zero; } else if (!open && blocker != null) { Destroy(blocker); blocker = null; } } private void OnGUI() { if (!open) return; if (title == null) { title = new GUIStyle(GUI.skin.label) { fontSize = 22, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter, wordWrap = true }; title.normal.textColor = new Color(1f, 0.75f, 0.2f); body = new GUIStyle(GUI.skin.label) { fontSize = 16, alignment = TextAnchor.UpperCenter, wordWrap = true, richText = true }; body.normal.textColor = Color.white; btn = new GUIStyle(GUI.skin.button) { fontSize = 16, fontStyle = FontStyle.Bold }; } float s = Mathf.Max(0.75f, Screen.height / 1080f); Matrix4x4 old = GUI.matrix; GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(s, s, 1f)); float vw = Screen.width / s, vh = Screen.height / s; GUI.color = new Color(0f, 0f, 0f, 0.75f); GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture); GUI.color = Color.white; float w = 620f; GUILayout.Window(0x5A5E03, new Rect((vw - w) * 0.5f, vh * 0.5f - 180f, w, 0f), Draw, "Save Anywhere " + Plugin.Version); GUI.FocusWindow(0x5A5E03); GUI.matrix = old; } private void Draw(int id) { GUILayout.Space(8f); GUILayout.Label("DEMO VERSION DETECTED", title); GUILayout.Space(8f); GUILayout.Label("Save Anywhere only works with the full game of Casualties: Unknown. The demo is an older build with different game code, so the mod has turned itself off.\n\nYour game and saves aren't affected. Saving works the normal way.\n\nBuy the full game on Steam to use Save Anywhere.", body); GUILayout.Space(12f); GUILayout.BeginHorizontal(); if (GUILayout.Button("Open the Steam store page", btn, GUILayout.Height(36f))) Application.OpenURL(DemoGuard.StoreUrl); if (GUILayout.Button("OK", btn, GUILayout.Height(36f))) open = false; GUILayout.EndHorizontal(); GUILayout.Space(4f); } } internal static class MultiplayerGuard { internal static bool Detected; internal static readonly List Found = new List(); private static readonly string[] PluginKeywords = { "krokmp", "krokosha", "casualtiestogether", "casualtiesmp", "multiplayer", "coop", "netplay", "netcode", "lobby", "latejoin" }; private static readonly string[] NetLibraries = { "mirror", "unity.netcode", "fishnet", "photon", "litenetlib", "riptide", "kcp2k", "telepathy", "lidgren", "facepunch.steamworks", "unity.networking.transport", "unity.services.lobby", "unity.services.relay" }; private static string Normalize(string s) { if (s == null) return ""; return s.ToLowerInvariant().Replace(" ", "").Replace("-", "").Replace("_", "").Replace(".", ""); } private static bool HasKeyword(string hay) { for (int i = 0; i < PluginKeywords.Length; i++) if (hay.Contains(PluginKeywords[i])) return true; return false; } private static bool offLogged; private static bool libLogged; private static Assembly AssemblyOf(PluginInfo p) { try { if (!ReferenceEquals(p.Instance, null)) return p.Instance.GetType().Assembly; } catch (Exception) { } if (string.IsNullOrEmpty(p.Location)) return null; foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) { try { if (!a.IsDynamic && string.Equals(a.Location, p.Location, StringComparison.OrdinalIgnoreCase)) return a; } catch (Exception) { } } return null; } private static readonly Dictionary offCache = new Dictionary(); private static bool SwitchedOff(PluginInfo p) { string key = p.Metadata.GUID; bool v; if (offCache.TryGetValue(key, out v)) return v; v = SwitchedOffNow(p); if (!ReferenceEquals(p.Instance, null)) offCache[key] = v; return v; } private static bool SwitchedOffNow(PluginInfo p) { Assembly a = AssemblyOf(p); if (a == null) return false; Type[] types; try { types = a.GetTypes(); } catch (ReflectionTypeLoadException e) { types = e.Types; } catch (Exception) { return false; } foreach (Type t in types) { if (t == null) continue; try { PropertyInfo pi = t.GetProperty("FORCE_DISABLE_MP_MOD", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (pi != null && pi.PropertyType == typeof(bool) && (bool)pi.GetValue(null, null)) return true; FieldInfo fi = t.GetField("FORCE_DISABLE_MP_MOD", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (fi != null && fi.FieldType == typeof(bool) && (bool)fi.GetValue(null)) return true; } catch (Exception) { } } return false; } private static bool OwnedByOff(Assembly lib, List off) { string dir = null; try { if (!lib.IsDynamic && !string.IsNullOrEmpty(lib.Location)) dir = Path.GetDirectoryName(lib.Location); } catch (Exception) { } string name = lib.GetName().Name; foreach (PluginInfo p in off) { try { if (dir != null && !string.IsNullOrEmpty(p.Location) && string.Equals(Path.GetDirectoryName(p.Location), dir, StringComparison.OrdinalIgnoreCase)) return true; Assembly a = AssemblyOf(p); if (a == null) continue; foreach (AssemblyName r in a.GetReferencedAssemblies()) if (string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)) return true; } catch (Exception) { } } return false; } internal static bool Check() { if (Detected) return true; List found = new List(); HashSet flagged = new HashSet(); Dictionary plugins = BepInEx.Bootstrap.Chainloader.PluginInfos; HashSet offGuids = new HashSet(); List offPlugins = new List(); List offNames = new List(); foreach (KeyValuePair kv in plugins) { PluginInfo p = kv.Value; if (p == null || p.Metadata == null || p.Metadata.GUID == "saveanywhere") continue; string file = ""; try { file = Path.GetFileNameWithoutExtension(p.Location); } catch (Exception) { } string hay = Normalize(p.Metadata.GUID) + "|" + Normalize(p.Metadata.Name) + "|" + Normalize(file); if (SwitchedOff(p)) { offGuids.Add(p.Metadata.GUID); offPlugins.Add(p); offNames.Add(p.Metadata.Name); } } if (offGuids.Count > 0) { foreach (KeyValuePair kv in plugins) { PluginInfo p = kv.Value; if (p == null || p.Metadata == null || offGuids.Contains(p.Metadata.GUID) || p.Dependencies == null) continue; foreach (BepInDependency dep in p.Dependencies) { if (dep != null && offGuids.Contains(dep.DependencyGUID)) { offGuids.Add(p.Metadata.GUID); offPlugins.Add(p); offNames.Add(p.Metadata.Name + " (add-on)"); break; } } } if (!offLogged) { offLogged = true; Plugin.Log.LogInfo("Multiplayer mod found but switched off: " + string.Join(", ", offNames.ToArray()) + ". Save Anywhere stays on."); } } foreach (KeyValuePair kv in plugins) { PluginInfo p = kv.Value; if (p == null || p.Metadata == null || p.Metadata.GUID == "saveanywhere") continue; if (offGuids.Contains(p.Metadata.GUID)) continue; string file = ""; try { file = Path.GetFileNameWithoutExtension(p.Location); } catch (Exception) { } string hay = Normalize(p.Metadata.GUID) + "|" + Normalize(p.Metadata.Name) + "|" + Normalize(file); if (HasKeyword(hay)) { flagged.Add(p.Metadata.GUID); found.Add(p.Metadata.Name); } } foreach (KeyValuePair kv in plugins) { PluginInfo p = kv.Value; if (p == null || p.Metadata == null || flagged.Contains(p.Metadata.GUID) || offGuids.Contains(p.Metadata.GUID) || p.Dependencies == null) continue; foreach (BepInDependency dep in p.Dependencies) { if (dep != null && flagged.Contains(dep.DependencyGUID)) { found.Add(p.Metadata.Name + " (multiplayer add-on)"); break; } } } List libs = new List(); Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < asms.Length; i++) { string name; try { name = asms[i].GetName().Name; } catch (Exception) { continue; } if (name == null) continue; string low = name.ToLowerInvariant(); for (int j = 0; j < NetLibraries.Length; j++) { if (low.StartsWith(NetLibraries[j])) { if (offPlugins.Count > 0 && OwnedByOff(asms[i], offPlugins)) break; libs.Add(name + " (network library)"); break; } } } if (found.Count == 0) { if (libs.Count > 0 && !libLogged) { libLogged = true; Plugin.Log.LogInfo("Network library loaded by another mod (" + string.Join(", ", libs.ToArray()) + "), but no multiplayer mod found. Save Anywhere stays on."); } return false; } found.AddRange(libs); Detected = true; Found.AddRange(found); Loader.Pending = null; try { if (Plugin.HarmonyInstance != null) Plugin.HarmonyInstance.UnpatchSelf(); } catch (Exception e) { Plugin.Log.LogWarning("Unpatch failed: " + e.Message); } Plugin.Log.LogWarning("Multiplayer detected (" + string.Join(", ", found.ToArray()) + "). Save Anywhere is now fully disabled."); return true; } } internal static class Merc { private static readonly FieldInfo BallField = AccessTools.Field(typeof(WorldGeneration), "spawnedMercBall"); private static readonly FieldInfo ChipField = AccessTools.Field(typeof(WorldGeneration), "chip"); private static string ChipId(int depth) { switch (depth) { case 1: return "regenerationchip"; case 2: return "capacitorchip"; case 3: return "swapchip"; case 4: return "rejuvenationchip"; case 6: return "aichip"; case 8: return "kineticchip"; } return null; } internal static void Capture(WorldGeneration w, JObject m) { m["canmerc"] = w.canStartMercRun; if (BallField != null) m["mercball"] = (bool)BallField.GetValue(w); Vector2? ch = PlayerCamera.main.chipHeight; if (ch.HasValue) { m["chipx"] = ch.Value.x; m["chipy"] = ch.Value.y; } } internal static void Apply(WorldGeneration w, Snapshot s) { bool fresh = s.Meta["canmerc"] != null; if (fresh) w.canStartMercRun = (bool)s.Meta["canmerc"]; else if (w.isMercRun) w.canStartMercRun = false; if (BallField != null) { bool ball; if (s.Meta["mercball"] != null) ball = (bool)s.Meta["mercball"]; else ball = w.isMercRun || Item.allItems.Any(x => x != null && x.id == "nanotechscanner") || Object.FindObjectsOfType().Any(t => t.parent == null && t.name.StartsWith("techball")); if (ball) BallField.SetValue(w, true); } Vector2? mark = null; if (s.Meta["chipx"] != null) mark = new Vector2((float)s.Meta["chipx"], (float)s.Meta["chipy"]); string id = ChipId(w.biomeDepth); Item chip = null; if (id != null && (mark.HasValue || (!fresh && w.isMercRun))) { float best = float.MaxValue; foreach (Item it in Item.allItems) { if (it == null || it.id != id || it.transform.parent != null) continue; float d = mark.HasValue ? Vector2.Distance(it.transform.position, mark.Value) : 0f; if (d < best) { best = d; chip = it; } } } if (chip != null) { if (ChipField != null) ChipField.SetValue(w, chip.transform); if (!mark.HasValue) mark = chip.transform.position; } if (mark.HasValue) { PlayerCamera.main.SetChipIndicatorPos(mark); Plugin.Log.LogInfo("Restored the nano-tech scanner chip marker."); } } } internal static class Lights { private static readonly string[] Ids = { "flashlight", "emergencylight" }; private static CustomItemBehaviour Of(Item it) { if (it == null || Array.IndexOf(Ids, it.id) < 0) return null; return it.GetComponent(); } internal static int State(Item it) { CustomItemBehaviour c = Of(it); return c == null ? 0 : c.state; } internal static void Set(Item it, int state) { CustomItemBehaviour c = Of(it); if (c != null) c.state = state; } private static string Key(Item it) { Transform p = it.transform.parent; return it.id + "|" + (p == null ? "" : p.name.Replace("(Clone)", "").Trim()); } internal static void CaptureBody(Body b, JObject m) { JArray arr = new JArray(); foreach (Item it in b.GetComponentsInChildren(true)) { int st = State(it); if (st == 0) continue; JObject o = new JObject(); o["id"] = it.id; o["key"] = Key(it); o["st"] = st; arr.Add(o); } if (arr.Count > 0) m["lights"] = arr; } internal static void ApplyBody(Body b, Snapshot s) { JArray arr = s.Meta["lights"] as JArray; if (arr == null) return; List free = new List(); foreach (Item it in b.GetComponentsInChildren(true)) if (Of(it) != null) free.Add(it); List left = new List(); int n = 0; foreach (JToken t in arr) { JObject o = (JObject)t; string key = (string)o["key"]; Item hit = free.Find(x => Key(x) == key); if (hit == null) { left.Add(o); continue; } Set(hit, (int)o["st"]); free.Remove(hit); n++; } foreach (JObject o in left) { string id = (string)o["id"]; Item hit = free.Find(x => x.id == id); if (hit == null) continue; Set(hit, (int)o["st"]); free.Remove(hit); n++; } if (n > 0) Plugin.Log.LogInfo("Turned " + n + " carried light(s) back on."); } } internal static class Paths { public static string Dir { get { return Application.persistentDataPath; } } public static string Save { get { return Dir + "\\save.sv"; } } public static string Snap { get { return Dir + "\\saveanywhere.sav"; } } public static string Shown { get { string d = Dir.Replace('/', '\\'); int i = d.IndexOf("\\AppData\\", StringComparison.OrdinalIgnoreCase); return i >= 0 ? d.Substring(i + 1) : d; } } } internal static class CheatFlag { private static readonly Dictionary cache = new Dictionary(); private static GUIStyle style; public static string OfBytes(byte[] save) { try { string j = SaveSystem.Unzip(save); if (j.Contains("\"cheatedSave\":true")) return "TRUE"; if (j.Contains("\"cheatedSave\":false")) return "FALSE"; } catch (Exception) { } return "?"; } public static string OfGame() { try { return File.Exists(Paths.Save) ? OfBytes(File.ReadAllBytes(Paths.Save)) : null; } catch (Exception) { return "?"; } } public static string OfSlot(SlotInfo s) { if (s == null) return null; string key = s.Slot + ":" + s.Hash; string v; if (cache.TryGetValue(key, out v)) return v; v = "?"; try { byte[] b = Snapshot.ReadSaveBytes(Slots.PathOf(s.Slot)); if (b != null) v = OfBytes(b); } catch (Exception) { } cache[key] = v; return v; } public static string Colored(string v) { if (v == "TRUE") return "TRUE"; if (v == "FALSE") return "FALSE"; return "?"; } public static void DrawTag(Rect r, string v) { if (style == null) { style = new GUIStyle(GUI.skin.label) { fontSize = 11, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter, richText = true }; style.normal.textColor = Color.white; } Color old = GUI.color; GUI.color = new Color(0f, 0f, 0f, 0.65f); GUI.DrawTexture(r, Texture2D.whiteTexture); GUI.color = old; GUI.Label(r, "Cheated: " + Colored(v), style); } } internal class SlotInfo { public int Slot; public string Run; public DateTime SavedAt; public bool Auto; public int Layer; public float RunTime; public string Hash; public int Character; public string RunType; public int Art = -1; } internal static class RunType { private static bool Same(object a, object b) { if (a == null || b == null) return a == b; string sa = Convert.ToString(a, System.Globalization.CultureInfo.InvariantCulture); string sb = Convert.ToString(b, System.Globalization.CultureInfo.InvariantCulture); if (string.Equals(sa, sb, StringComparison.OrdinalIgnoreCase)) return true; double da, db; if (double.TryParse(sa, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out da) && double.TryParse(sb, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out db)) return Math.Abs(da - db) < 0.0001; return false; } public static string Current() { try { Dictionary cur = WorldGeneration.runSettings; if (cur == null) return ""; Dictionary normal = RunSettings.GetPreset("normal").presetValues; foreach (RunSettingsPreset p in RunSettings.presets) { Dictionary want = new Dictionary(normal); foreach (KeyValuePair kv in p.presetValues) want[kv.Key] = kv.Value; bool match = true; foreach (KeyValuePair kv in want) { object v; if (!cur.TryGetValue(kv.Key, out v)) continue; if (!Same(v, kv.Value)) { match = false; break; } } if (match) return Label(p.presetName); } return "Custom"; } catch (Exception e) { Plugin.Log.LogWarning("Couldn't work out the run type: " + e.Message); return ""; } } private static string Label(string preset) { try { string n = Locale.GetOther("preset" + preset); if (!string.IsNullOrEmpty(n) && n != "preset" + preset) return n; } catch (Exception) { } return char.ToUpper(preset[0]) + preset.Substring(1); } } internal static class LayerArt { private static string Dir { get { return Paths.Dir + "\\SaveAnywhere\\art"; } } private static readonly Dictionary loaded = new Dictionary(); private static readonly HashSet missing = new HashSet(); private static bool captured; public static int CurrentIndex(WorldGeneration w) { if (w == null) return -1; return w.biomeOverride != WorldGeneration.OverrideSceneType.None ? 11 : w.biomeDepth; } public static void Tick() { if (captured) return; WorldGeneration w = WorldGeneration.world; if (w == null || w.generatingWorld || !w.worldExists) return; captured = true; Sprite[] imgs = w.layerGenerationImages; if (imgs == null) return; try { Directory.CreateDirectory(Dir); } catch (Exception e) { Plugin.Log.LogWarning("Couldn't make the layer art folder: " + e.Message); return; } int saved = 0; for (int i = 0; i < imgs.Length; i++) { string path = Dir + "\\layer" + i + ".png"; if (imgs[i] == null || File.Exists(path)) continue; try { Texture2D t = Grab(imgs[i], 480); File.WriteAllBytes(path, t.EncodeToPNG()); Object.Destroy(t); missing.Remove(i); saved++; } catch (Exception e) { Plugin.Log.LogWarning("Couldn't save the art for layer image " + i + ": " + e.Message); } } if (saved > 0) Plugin.Log.LogInfo("Saved " + saved + " layer pictures for the save slot cards."); } private static Texture2D Grab(Sprite sp, int maxW) { Texture src = sp.texture; Rect tr = sp.textureRect; float k = Mathf.Min(1f, maxW / tr.width); int ow = Mathf.Max(1, Mathf.RoundToInt(tr.width * k)); int oh = Mathf.Max(1, Mathf.RoundToInt(tr.height * k)); RenderTexture rt = RenderTexture.GetTemporary(ow, oh, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); Graphics.Blit(src, rt, new Vector2(tr.width / src.width, tr.height / src.height), new Vector2(tr.x / src.width, tr.y / src.height)); RenderTexture prev = RenderTexture.active; RenderTexture.active = rt; Texture2D t = new Texture2D(ow, oh, TextureFormat.RGB24, false); t.ReadPixels(new Rect(0, 0, ow, oh), 0, 0); t.Apply(); RenderTexture.active = prev; RenderTexture.ReleaseTemporary(rt); return t; } public static Texture2D Get(int index) { if (index < 0) return null; Texture2D t; if (loaded.TryGetValue(index, out t) && t != null) return t; if (missing.Contains(index)) return null; string path = Dir + "\\layer" + index + ".png"; try { if (!File.Exists(path)) { missing.Add(index); return null; } t = new Texture2D(2, 2, TextureFormat.RGB24, false); if (!ImageConversion.LoadImage(t, File.ReadAllBytes(path))) { missing.Add(index); return null; } t.wrapMode = TextureWrapMode.Clamp; loaded[index] = t; return t; } catch (Exception) { missing.Add(index); return null; } } public static void ForgetMissing() { missing.Clear(); } } internal static class Slots { private static string Dir { get { return Paths.Dir + "\\SaveAnywhere"; } } private static string IndexPath { get { return Dir + "\\slots.json"; } } public static string CurrentRun { get { return PlayerPrefs.GetString("saveanywhere_run", ""); } set { PlayerPrefs.SetString("saveanywhere_run", value ?? ""); PlayerPrefs.Save(); } } public static string PathOf(int slot) { return Dir + "\\slot" + slot + ".sav"; } public const int AutoSlot = 11; public static int Count { get { return Mathf.Clamp(Plugin.SlotCount.Value, 1, 10); } } public static string Name(int slot) { return slot == AutoSlot ? "the auto-save slot" : "slot " + slot; } public static int ManualFor(int slot, string run) { if (slot != AutoSlot) return slot; SlotInfo s = LoadIndex().Where(x => x.Slot != AutoSlot && x.Run == run && !string.IsNullOrEmpty(run)).OrderByDescending(x => x.SavedAt).FirstOrDefault(); return s != null ? s.Slot : 0; } public static List LoadIndex() { List list = new List(); try { if (!File.Exists(IndexPath)) return list; foreach (JToken t in JArray.Parse(File.ReadAllText(IndexPath))) { SlotInfo s = new SlotInfo(); s.Slot = (int)t["slot"]; s.Run = (string)t["run"]; s.SavedAt = new DateTime((long)t["at"]); s.Auto = (bool)t["auto"]; s.Layer = (int)t["layer"]; s.RunTime = (float)t["time"]; s.Hash = (string)t["hash"]; s.Character = (int)t["char"]; s.RunType = t["type"] != null ? (string)t["type"] : null; s.Art = t["art"] != null ? (int)t["art"] : s.Layer - 1; if (File.Exists(PathOf(s.Slot))) list.Add(s); } } catch (Exception e) { Plugin.Log.LogWarning("Couldn't read the save slot list: " + e.Message); } return list; } private static void SaveIndex(List list) { JArray a = new JArray(); foreach (SlotInfo s in list) { JObject o = new JObject(); o["slot"] = s.Slot; o["run"] = s.Run; o["at"] = s.SavedAt.Ticks; o["auto"] = s.Auto; o["layer"] = s.Layer; o["time"] = s.RunTime; o["hash"] = s.Hash; o["char"] = s.Character; if (s.RunType != null) o["type"] = s.RunType; o["art"] = s.Art; a.Add(o); } Directory.CreateDirectory(Dir); File.WriteAllText(IndexPath, a.ToString(Formatting.None)); } public static int CurrentSlot { get { return PlayerPrefs.GetInt("saveanywhere_slot", 0); } set { PlayerPrefs.SetInt("saveanywhere_slot", value); PlayerPrefs.Save(); } } public static int PickManualSlot() { int cur = CurrentSlot; if (cur > 0 && cur != AutoSlot) return cur; List list = LoadIndex(); for (int i = 1; i <= Count; i++) if (!list.Any(x => x.Slot == i)) return i; return 0; } public static int FindByHash(string hash) { SlotInfo s = LoadIndex().FirstOrDefault(x => x.Hash == hash); return s != null ? s.Slot : 0; } public static void Store(Snapshot snap, int slot, bool auto, int layer, float runTime, int character, string runType, int art) { Directory.CreateDirectory(Dir); string run = CurrentRun; List list = LoadIndex(); list.RemoveAll(x => x.Slot == slot); snap.Write(PathOf(slot)); SlotInfo n = new SlotInfo(); n.Slot = slot; n.Run = run; n.SavedAt = DateTime.Now; n.Auto = auto; n.Layer = layer; n.RunTime = runTime; n.Hash = snap.Hash; n.Character = character; n.RunType = runType; n.Art = art; list.Add(n); SaveIndex(list); Plugin.Log.LogInfo("Saved into " + Name(slot) + ". Marked as cheated by the game: " + CheatFlag.OfBytes(snap.SaveBytes)); } public static bool Import(int slot, byte[] data, string metaJson) { Directory.CreateDirectory(Dir); string tmp = PathOf(slot) + ".cloud"; Snapshot snap = null; try { File.WriteAllBytes(tmp, data); snap = Snapshot.Read(tmp); } catch (Exception e) { Plugin.Log.LogWarning("Downloaded save couldn't be read: " + e.Message); } if (snap == null) { TryDelete(tmp); return false; } JObject m; try { m = string.IsNullOrEmpty(metaJson) ? new JObject() : Cloud.Json(metaJson); } catch (Exception) { m = new JObject(); } SlotInfo n = new SlotInfo(); n.Slot = slot; n.Run = (string)m["runId"]; if (string.IsNullOrEmpty(n.Run) && snap.Meta["run"] != null) n.Run = (string)snap.Meta["run"]; DateTime at; n.SavedAt = m["savedAt"] != null && DateTime.TryParse((string)m["savedAt"], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out at) ? at.ToLocalTime() : DateTime.Now; n.SavedAt = new DateTime(n.SavedAt.Ticks); n.Auto = slot == AutoSlot; int v; n.Layer = m["layer"] != null && int.TryParse(m["layer"].ToString(), out v) ? v : snap.Depth + 1; n.RunTime = m["runTime"] != null && int.TryParse(m["runTime"].ToString(), out v) ? v : 0; n.Character = m["character"] != null && int.TryParse(m["character"].ToString(), out v) ? v : 0; n.RunType = (string)m["runType"]; n.Hash = snap.Hash; n.Art = n.Layer - 1; List list = LoadIndex(); list.RemoveAll(x => x.Slot == slot); TryDelete(PathOf(slot)); File.Move(tmp, PathOf(slot)); list.Add(n); SaveIndex(list); return true; } public static void DeleteRun(string run) { Cloud.DeleteForRun(run, 0); List list = LoadIndex(); foreach (SlotInfo s in list.Where(x => x.Run == run).ToList()) { TryDelete(PathOf(s.Slot)); list.Remove(s); } SaveIndex(list); CurrentSlot = 0; } public static void Delete(int slot) { SlotInfo old = LoadIndex().FirstOrDefault(x => x.Slot == slot); if (old != null) Cloud.DeleteForRun(old.Run, slot); if (CurrentSlot == slot) CurrentSlot = 0; List list = LoadIndex(); TryDelete(PathOf(slot)); list.RemoveAll(x => x.Slot == slot); SaveIndex(list); } public static bool Use(SlotInfo s) { try { Snapshot snap = Snapshot.Read(PathOf(s.Slot)); if (snap == null) return false; File.WriteAllBytes(Paths.Save, snap.SaveBytes); File.Copy(PathOf(s.Slot), Paths.Snap, true); CurrentRun = s.Run; CurrentSlot = ManualFor(s.Slot, s.Run); return true; } catch (Exception e) { Plugin.Log.LogError("Couldn't use save slot " + s.Slot + ": " + e); return false; } } private static void TryDelete(string p) { try { if (File.Exists(p)) File.Delete(p); } catch (Exception) { } } } internal class Snapshot { private const string Magic = "SAVEANYWHERE1"; public string Hash; public byte[] SaveBytes; public JObject Meta; public int W; public int H; public ushort[,] Blocks; public byte[,] Fluid; public int Depth { get { return (int)Meta["depth"]; } } public static string HashOf(byte[] data) { using (SHA1 sha = SHA1.Create()) { byte[] h = sha.ComputeHash(data); StringBuilder sb = new StringBuilder(); for (int i = 0; i < h.Length; i++) sb.Append(h[i].ToString("x2")); return sb.ToString(); } } public void Write(string path) { string tmp = path + ".tmp"; using (FileStream fs = File.Create(tmp)) using (GZipStream gz = new GZipStream(fs, CompressionMode.Compress)) using (BinaryWriter w = new BinaryWriter(gz)) { w.Write(Magic); w.Write(Hash); w.Write(SaveBytes.Length); w.Write(SaveBytes); w.Write(Meta.ToString(Formatting.None)); w.Write(W); w.Write(H); byte[] b = new byte[W * H * 2]; Buffer.BlockCopy(Blocks, 0, b, 0, b.Length); w.Write(b); byte[] f = new byte[W * H]; Buffer.BlockCopy(Fluid, 0, f, 0, f.Length); w.Write(f); } if (File.Exists(path)) File.Delete(path); File.Move(tmp, path); } public static byte[] ReadSaveBytes(string path) { using (FileStream fs = File.OpenRead(path)) using (GZipStream gz = new GZipStream(fs, CompressionMode.Decompress)) using (BinaryReader r = new BinaryReader(gz)) { if (r.ReadString() != Magic) return null; r.ReadString(); return r.ReadBytes(r.ReadInt32()); } } public static Snapshot Read(string path) { using (FileStream fs = File.OpenRead(path)) using (GZipStream gz = new GZipStream(fs, CompressionMode.Decompress)) using (BinaryReader r = new BinaryReader(gz)) { if (r.ReadString() != Magic) return null; Snapshot s = new Snapshot(); s.Hash = r.ReadString(); s.SaveBytes = r.ReadBytes(r.ReadInt32()); s.Meta = JObject.Parse(r.ReadString()); s.W = r.ReadInt32(); s.H = r.ReadInt32(); byte[] b = r.ReadBytes(s.W * s.H * 2); s.Blocks = new ushort[s.W, s.H]; Buffer.BlockCopy(b, 0, s.Blocks, 0, b.Length); byte[] f = r.ReadBytes(s.W * s.H); s.Fluid = new byte[s.W, s.H]; Buffer.BlockCopy(f, 0, s.Fluid, 0, f.Length); return s; } } } internal static class Prefabs { private static readonly string[] Folders = { "Structures", "Special" }; private static readonly string[] ExtraRoots = { "Lifepod", "BioContainer", "LifepodStart" }; private static readonly Dictionary cache = new Dictionary(); private static List> roots; private static Dictionary assetsByName; public static string BaseName(string name) { string n = name; while (n.EndsWith("(Clone)")) n = n.Substring(0, n.Length - 7).TrimEnd(); return n.Trim(); } private static List> Roots() { if (roots != null) return roots; roots = new List>(); foreach (string folder in Folders) { GameObject[] all = Resources.LoadAll(folder); foreach (GameObject g in all) roots.Add(new KeyValuePair(folder + "/" + g.name, g)); } foreach (string p in ExtraRoots) { GameObject g = Resources.Load(p); if (g != null) roots.Add(new KeyValuePair(p, g)); } return roots; } private static bool FindChild(Transform t, Func match, List path) { for (int i = 0; i < t.childCount; i++) { Transform c = t.GetChild(i); path.Add(i); if (match(c)) return true; if (FindChild(c, match, path)) return true; path.RemoveAt(path.Count - 1); } return false; } private static string SearchRoots(Func match) { foreach (KeyValuePair kv in Roots()) { List path = new List(); if (FindChild(kv.Value.transform, match, path)) return "C:" + kv.Key + "|" + string.Join("/", path.Select(x => x.ToString()).ToArray()); } return null; } private static void CollectNames(Transform t, int depth, List into) { if (depth <= 0) return; for (int i = 0; i < t.childCount; i++) { Transform c = t.GetChild(i); into.Add(BaseName(c.name)); CollectNames(c, depth - 1, into); } } private static float Similarity(List inst, Transform cand) { List cn = new List(); CollectNames(cand, 3, cn); List left = new List(inst); int common = 0, candOnly = 0; foreach (string s in cn) { int i = left.IndexOf(s); if (i >= 0) { common++; left.RemoveAt(i); } else candOnly++; } return common * 2f - candOnly - left.Count * 0.5f; } private static void FindAll(Transform t, Func match, List path, string rootKey, List> into) { for (int i = 0; i < t.childCount; i++) { Transform c = t.GetChild(i); path.Add(i); if (match(c)) into.Add(new KeyValuePair("C:" + rootKey + "|" + string.Join("/", path.Select(x => x.ToString()).ToArray()), c)); FindAll(c, match, path, rootKey, into); path.RemoveAt(path.Count - 1); } } public static string ForBuilding(GameObject go) { string n = BaseName(go.name); BuildingEntity self = go.GetComponent(); string beId = self != null ? self.id : null; List inst = new List(); CollectNames(go.transform, 3, inst); string key = n + "|" + beId + "|" + string.Join(",", inst.OrderBy(x => x).ToArray()); string res; if (cache.TryGetValue(key, out res)) return res; Func match = c => { if (c.name != n) return false; BuildingEntity be = c.GetComponent(); return be != null && (beId == null || be.id == beId); }; List> cands = new List>(); string[] tries = { n, "Special/" + n, "Structures/" + n }; foreach (string t in tries) { GameObject g = Resources.Load(t); if (g != null && match(g.transform)) { cands.Add(new KeyValuePair("R:" + t, g.transform)); break; } } foreach (KeyValuePair kv in Roots()) FindAll(kv.Value.transform, match, new List(), kv.Key, cands); res = null; float best = float.MinValue; foreach (KeyValuePair c in cands) { float sc = Similarity(inst, c.Value); if (sc > best) { best = sc; res = c.Key; } } if (res == null) res = "N:" + n; cache[key] = res; return res; } public static string ForSpawn(GameObject go) { Transform src = go.transform; return SearchRoots(c => { if (!c.name.StartsWith("DOSPAWN") || c.childCount != src.childCount) return false; for (int i = 0; i < c.childCount; i++) if (BaseName(src.GetChild(i).name) != c.GetChild(i).name) return false; return true; }); } public static GameObject Load(string res) { if (string.IsNullOrEmpty(res) || res.Length < 3) return null; string body = res.Substring(2); if (res.StartsWith("R:")) return Resources.Load(body); if (res.StartsWith("C:")) { int bar = body.IndexOf('|'); GameObject root = Resources.Load(body.Substring(0, bar)); if (root == null) return null; Transform t = root.transform; string idx = body.Substring(bar + 1); if (idx.Length > 0) { foreach (string s in idx.Split('/')) { int i = int.Parse(s); if (i >= t.childCount) return null; t = t.GetChild(i); } } return t.gameObject; } if (res.StartsWith("N:")) { if (assetsByName == null) { assetsByName = new Dictionary(); foreach (GameObject g in Resources.FindObjectsOfTypeAll()) { if (g.scene.IsValid()) continue; if (g.GetComponent() == null) continue; if (!assetsByName.ContainsKey(g.name)) assetsByName[g.name] = g; } } GameObject found; if (assetsByName.TryGetValue(body, out found)) return found; GameObject[] all = Resources.LoadAll(""); foreach (GameObject g in all) { if (g.name == body && g.GetComponent() != null) { assetsByName[body] = g; return g; } } } return null; } } internal static class Comps { private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; public static string Capture(GameObject go) { Dictionary d = new Dictionary(); foreach (Component c in go.GetComponents()) { if (c == null) continue; Type t = c.GetType(); if (Attribute.IsDefined(t, typeof(Saveable)) && !d.ContainsKey(t)) d.Add(t, c); } if (d.Count == 0) return null; return JsonConvert.SerializeObject(d, Formatting.None, Settings); } public static void Apply(GameObject go, string json) { if (string.IsNullOrEmpty(json)) return; JObject j = JObject.Parse(json); foreach (JProperty p in j.Properties()) { try { Type t = AccessTools.TypeByName(p.Name); if (t == null) continue; Component c = go.GetComponent(t); if (c == null) c = go.AddComponent(t); JObject fields = p.Value as JObject; if (fields == null) continue; foreach (JProperty f in fields.Properties()) { FieldInfo fi = t.GetField(f.Name); if (fi == null) continue; try { fi.SetValue(c, f.Value.ToObject(fi.FieldType)); } catch (Exception e) { Plugin.Log.LogWarning("Field " + t.Name + "." + f.Name + ": " + e.Message); } } } catch (Exception e) { Plugin.Log.LogWarning("Component " + p.Name + ": " + e.Message); } } } } internal static class Veins { private static bool IsVein(GameObject g) { return g != null && g.name.StartsWith("vein"); } private static bool IsClimbRope(GameObject g) { return g != null && g.name.StartsWith("climbingrope"); } private static bool IsCaveRope(GameObject g) { return g != null && (g.name.StartsWith("sandvinerope") || g.name.StartsWith("mushroomrope")); } private static void Register(Climbable cl) { if (Climbable.allClimbables == null) Climbable.allClimbables = new List(); if (!Climbable.allClimbables.Contains(cl)) Climbable.allClimbables.Add(cl); } public static void Capture(GameObject g, JObject o) { if (IsVein(g) || IsCaveRope(g)) { SpriteRenderer sr = g.GetComponent(); if (sr != null) { Color c = sr.color; o["vc"] = new JArray(c.r, c.g, c.b, c.a); if (sr.drawMode != SpriteDrawMode.Simple) o["vs"] = new JArray(sr.size.x, sr.size.y); } } Climbable cl = g.GetComponent(); if (cl != null && cl.points != null && cl.points.Count >= 2) { JArray p = new JArray(); foreach (Vector2 v in cl.points) { p.Add(v.x); p.Add(v.y); } o["vp"] = p; o["vd"] = cl.downwardsVelocity; } } public static void Apply(GameObject g, JObject o) { if (IsVein(g) || IsCaveRope(g)) { SpriteRenderer sr = g.GetComponent(); JArray c = o["vc"] as JArray; if (sr != null && c != null && c.Count == 4) sr.color = new Color((float)c[0], (float)c[1], (float)c[2], (float)c[3]); JArray s = o["vs"] as JArray; if (sr != null && s != null && s.Count == 2) sr.size = new Vector2((float)s[0], (float)s[1]); } Climbable cl = g.GetComponent(); JArray p = o["vp"] as JArray; if (cl != null && p != null && p.Count >= 4) { List pts = new List(); for (int i = 0; i + 1 < p.Count; i += 2) pts.Add(new Vector2((float)p[i], (float)p[i + 1])); cl.points = pts; if (o["vd"] != null) cl.downwardsVelocity = (float)o["vd"]; cl.CalculateTotalLength(); if (IsClimbRope(g) && g.transform.childCount > 0) g.transform.GetChild(0).localScale = new Vector2(1f, Vector2.Distance(pts[pts.Count - 1], pts[0]) / 25f); } } public static void Repair() { Physics2D.SyncTransforms(); int mask = LayerMask.GetMask("Ground"); int n = 0; foreach (Climbable cl in Object.FindObjectsOfType()) { if (cl == null) continue; if (cl.points != null && cl.points.Count >= 2) continue; if (IsVein(cl.gameObject)) { Vector2 from = cl.transform.position; RaycastHit2D up = Physics2D.Raycast(from, Vector2.up, WorldGeneration.CHUNKSIZE * 4, mask); RaycastHit2D down = Physics2D.Raycast(from, Vector2.down, WorldGeneration.CHUNKSIZE * 4, mask); if (!up || !down) continue; cl.transform.position = new Vector3(cl.transform.position.x, (up.point.y + down.point.y) * 0.5f, cl.transform.position.z); SpriteRenderer sr = cl.GetComponent(); if (sr != null) sr.size = new Vector2(2f, Mathf.Max(0.5f, Mathf.Abs(up.point.y - down.point.y) - 1f)); cl.points = new List { new Vector2(from.x, down.point.y), new Vector2(from.x, up.point.y) }; cl.downwardsVelocity = (1f - Mathf.Clamp(cl.transform.localScale.x, 0.5f, 1f)) * 10f; cl.CalculateTotalLength(); Register(cl); n++; } else if (IsClimbRope(cl.gameObject)) { Vector2 top = cl.transform.position; RaycastHit2D down = Physics2D.Raycast(top, Vector2.down, 25f, mask); Vector2 bottom = down ? down.point : top + Vector2.down * 25f; cl.points = new List { bottom, top }; cl.CalculateTotalLength(); if (cl.transform.childCount > 0) cl.transform.GetChild(0).localScale = new Vector2(1f, Vector2.Distance(top, bottom) / 25f); Register(cl); n++; } else if (IsCaveRope(cl.gameObject)) { Vector2 mid = cl.transform.position; RaycastHit2D up = Physics2D.Raycast(mid, Vector2.up, WorldGeneration.CHUNKSIZE * 4, mask); if (!up) continue; Vector2 top = new Vector2(mid.x, up.point.y); Vector2 bottom = new Vector2(mid.x, 2f * mid.y - up.point.y); if (top.y - bottom.y < 0.5f) continue; SpriteRenderer sr = cl.GetComponent(); if (sr != null && sr.drawMode != SpriteDrawMode.Simple) sr.size = new Vector2(2.5f, top.y - bottom.y); cl.points = new List { bottom, top }; cl.downwardsVelocity = (1f - Mathf.Clamp(cl.transform.localScale.x, 0.15f, 1f)) * 16f; cl.CalculateTotalLength(); Register(cl); n++; } } if (n > 0) Plugin.Log.LogInfo("Rebuilt " + n + " climbables (veins/ropes) from an older save."); } } internal static class Crystals { private static readonly FieldInfo EffectsField = AccessTools.Field(typeof(CrystalBehaviour), "effects"); private static readonly FieldInfo ExaminedField = AccessTools.Field(typeof(CrystalBehaviour), "hasBeenExamined"); private static JArray Col(Color c) { return new JArray(c.r, c.g, c.b, c.a); } private static Color Col(JToken t) { JArray a = (JArray)t; return new Color((float)a[0], (float)a[1], (float)a[2], (float)a[3]); } public static JObject Capture(BuildingEntity be, string res) { GameObject g = be.gameObject; GameObject pf = res != null ? Prefabs.Load(res) : null; CrystalBehaviour cb = g.GetComponent(); if (cb == null && (pf == null || pf.GetComponent() == null)) return null; JObject c = new JObject(); SpriteRenderer sr = g.GetComponent(); if (sr != null) c["sc"] = Col(sr.color); UnityEngine.Rendering.Universal.Light2D l = g.GetComponent(); if (l != null) { c["lc"] = Col(l.color); c["li"] = l.intensity; c["lf"] = l.falloffIntensity; c["lv"] = l.volumeIntensityEnabled; c["lvi"] = l.volumeIntensity; c["lr"] = l.pointLightOuterRadius; c["le"] = l.enabled; } c["alive"] = cb != null; c["usable"] = g.GetComponent() != null; c["desc"] = be.description; JArray fx = new JArray(); if (cb != null) { List list = EffectsField != null ? EffectsField.GetValue(cb) as List : null; if (list != null) foreach (CrystalEffect e in list) if (e != null) fx.Add(e.GetType().FullName); c["ex"] = ExaminedField != null && (bool)ExaminedField.GetValue(cb); } c["fx"] = fx; return c; } public static void Apply(GameObject g, JObject c) { CrystalBehaviour cb = g.GetComponent(); if (c == null) { if (cb == null) return; cb.SetColor(UnityEngine.Random.value < 0.5f ? Color.magenta : Color.cyan); UsableObject u0 = g.GetComponent(); if (u0 != null) Object.Destroy(u0); Object.Destroy(cb); return; } if (cb != null) { List list = new List(); if (EffectsField != null) EffectsField.SetValue(cb, list); if ((bool)c["alive"] && c["fx"] is JArray) { foreach (JToken t in (JArray)c["fx"]) { Type ty = AccessTools.TypeByName((string)t); if (ty == null || !typeof(CrystalEffect).IsAssignableFrom(ty)) continue; try { CrystalEffect e = (CrystalEffect)Activator.CreateInstance(ty, true); e.crystal = cb; list.Add(e); e.Start(); } catch (Exception ex) { Plugin.Log.LogWarning("Crystal effect " + ty.Name + " failed: " + ex.Message); } } } if (list.Count == 0) Object.Destroy(cb); else { if (list.Count > 1) { GameObject d = Utils.Create("Special/CrystalDistort", g.transform); d.transform.localPosition = Vector3.zero; d.transform.localScale = Vector3.one; d.transform.rotation = Quaternion.identity; d.GetComponent().material.SetFloat("_DistortStrength", list.Count * 0.015f); } if (ExaminedField != null && c["ex"] != null) ExaminedField.SetValue(cb, (bool)c["ex"]); cb.CheckCurrentChunk(WorldGeneration.world.GetClosestChunkScript(g.transform.position)); } } if (c["usable"] != null && !(bool)c["usable"]) { UsableObject u = g.GetComponent(); if (u != null) Object.Destroy(u); } SpriteRenderer sr = g.GetComponent(); if (sr != null && c["sc"] != null) sr.color = Col(c["sc"]); UnityEngine.Rendering.Universal.Light2D l = g.GetComponent(); if (l != null && c["lc"] != null) { l.color = Col(c["lc"]); l.intensity = (float)c["li"]; l.falloffIntensity = (float)c["lf"]; l.volumeIntensityEnabled = (bool)c["lv"]; l.volumeIntensity = (float)c["lvi"]; l.pointLightOuterRadius = (float)c["lr"]; l.enabled = (bool)c["le"]; } BuildingEntity be = g.GetComponent(); if (be != null && c["desc"] != null) be.description = (string)c["desc"]; } } internal static class Safety { private static readonly string[] EnemyNames = { "GuardScript", "TurretScript", "CeilingTurret", "LaserDroneScript", "CrystalEnemy", "SpiderHandler", "ElderThornbackBehaviour", "ScrapEaterScript", "BloodSuckerScript" }; private static List enemyTypes; public static string Check() { WorldGeneration w = WorldGeneration.world; if (w == null || PlayerCamera.main == null || PlayerCamera.main.body == null) return "you're not in a run"; if (RunEnd.Ended) return "the run is over"; Body b = PlayerCamera.main.body; if (w.generatingWorld || Loader.Restoring) return "the layer is still loading"; if (w.biomeOverride != WorldGeneration.OverrideSceneType.None) return "you can't save here"; if (w.biomeDepth >= 9) return "you can't save on the final layers"; if (!b.alive) return "you're dead"; if (PlayerCamera.main.selfDestructActive) return "you gave up on this run"; if (b.isDying || b.isCriticallyDying) return "you're in critical condition, treat your wounds first"; if (b.sleeping) return "you're asleep"; if (b.consciousness < 50f) return "you're unconscious"; if (!b.standing) return "you're knocked down"; if (b.currentClimbable != null) return "you're climbing"; bool moving = b.rb != null && Mathf.Abs(b.rb.velocity.y) > 2.5f; if (!b.grounded || moving) return "you're falling"; string danger = Danger(w, b); if (danger != null) return danger; float r = Plugin.EnemyRadius.Value; if (r > 0f) { if (enemyTypes == null) { enemyTypes = new List(); foreach (string n in EnemyNames) { Type t = AccessTools.TypeByName(n); if (t != null) enemyTypes.Add(t); } } Vector2 me = b.transform.position; foreach (Type t in enemyTypes) { foreach (Object o in Object.FindObjectsOfType(t)) { Component c = o as Component; if (c == null) continue; BuildingEntity be = c.GetComponent(); if (be != null && be.health < 0.5f) continue; if (Vector2.Distance(me, c.transform.position) < r) return "an enemy is nearby"; } } foreach (TraderScript t in Object.FindObjectsOfType()) if (t != null && t.hostile && Vector2.Distance(me, t.transform.position) < r) return "a hostile survivor is nearby"; } return null; } private const float BlastRadius = 20f; private static readonly FieldInfo GrabBody = AccessTools.Field(typeof(GrabberPlant), "grabBody"); private static readonly FieldInfo SuckLimb = AccessTools.Field(typeof(BloodSuckerScript), "limb"); private static readonly FieldInfo MinePressed = AccessTools.Field(typeof(MineScript), "pressed"); private static readonly FieldInfo MineExploded = AccessTools.Field(typeof(MineScript), "exploded"); private static readonly FieldInfo CrystalEffects = AccessTools.Field(typeof(CrystalBehaviour), "effects"); private static readonly Type UnstableType = AccessTools.TypeByName("CrystalUnstable"); private static readonly FieldInfo UnstableTimer = UnstableType != null ? AccessTools.Field(UnstableType, "timerStarted") : null; private static string Danger(WorldGeneration w, Body b) { if (w.earthquakeTime > 0f || w.earthquakeIntensity > 0.02f) return "an earthquake is happening"; RadiationLine line = RadiationLine.line; if (line != null && line.active && b.transform.position.y > line.transform.position.y - 30f) return "the radiation line is too close"; if (w.fungusRainIntensity > 0.15f) return "fungal rain is falling"; EndLabScript lab = Object.FindObjectOfType(); if (lab != null && lab.doTimer) return "the escape countdown is running"; if (b.bloodOxygen < 80f) return "you can't breathe properly"; if (b.temperature < 34f) return "you're freezing"; if (b.temperature > 40f) return "you're overheating"; if (b.limbs != null) foreach (Limb l in b.limbs) if (l != null && !l.dismembered && l.totalBleedAmount > 25f) return "you're bleeding badly, treat your wounds first"; Vector2 me = b.transform.position; foreach (BearTrap t in Object.FindObjectsOfType()) if (t != null && t.caughtLimb != null && t.caughtLimb.body == b) return "you're caught in a bear trap"; if (GrabBody != null) foreach (GrabberPlant g in Object.FindObjectsOfType()) { Rigidbody2D gb = g != null ? GrabBody.GetValue(g) as Rigidbody2D : null; if (gb != null && gb.GetComponentInParent() == b) return "a grabber plant has you"; } if (SuckLimb != null) foreach (BloodSuckerScript s in Object.FindObjectsOfType()) { Limb l = s != null ? SuckLimb.GetValue(s) as Limb : null; if (l != null && l.body == b) return "a bloodsucker is attached to you"; } if (MinePressed != null && MineExploded != null) foreach (MineScript m in Object.FindObjectsOfType()) if (m != null && (bool)MinePressed.GetValue(m) && !(bool)MineExploded.GetValue(m) && Vector2.Distance(me, m.transform.position) < BlastRadius) return "a mine is about to go off"; foreach (CustomItemBehaviour c in Object.FindObjectsOfType()) if (c != null && c.IsInvoking("DynamiteExplode") && Vector2.Distance(me, c.transform.position) < BlastRadius) return "lit dynamite is nearby"; if (CrystalEffects != null && UnstableTimer != null) foreach (CrystalBehaviour cb in Object.FindObjectsOfType()) { if (cb == null || Vector2.Distance(me, cb.transform.position) >= BlastRadius) continue; System.Collections.IList fx = CrystalEffects.GetValue(cb) as System.Collections.IList; if (fx == null) continue; foreach (object e in fx) if (e != null && e.GetType() == UnstableType && (bool)UnstableTimer.GetValue(e)) return "a crystal is about to explode"; } return null; } } internal static class Saver { private static readonly FieldInfo BlocksField = AccessTools.Field(typeof(WorldGeneration), "worldBlocks"); private static readonly FieldInfo CorpseComment = AccessTools.Field(typeof(CorpseScript), "didComment"); private static bool warnedNoSlot; public static int Precheck(bool auto, int slot) { if (MultiplayerGuard.Check()) return 0; string why = Safety.Check(); if (why != null) { if (!auto) Runner.Toast("Can't save: " + why + ".", true); return 0; } int target = auto ? Slots.AutoSlot : (slot > 0 ? slot : Slots.PickManualSlot()); if (target <= 0) { if (!auto || !warnedNoSlot) Runner.Toast("All save slots are full. Pause and click Save to pick a slot.", true); if (auto) warnedNoSlot = true; return 0; } warnedNoSlot = false; return target; } public static bool Write(bool auto, int target) { try { WorldGeneration w = WorldGeneration.world; SaveSystem.SaveGame(); JObject j = JObject.Parse(SaveSystem.Unzip(File.ReadAllBytes(Paths.Save))); j["biome"] = w.biomeDepth; byte[] bytes = SaveSystem.Zip(j.ToString(Formatting.None)); File.WriteAllBytes(Paths.Save, bytes); Snapshot s = new Snapshot(); s.SaveBytes = bytes; s.Hash = Snapshot.HashOf(bytes); ushort[,] blocks = (ushort[,])BlocksField.GetValue(w); s.W = blocks.GetLength(0); s.H = blocks.GetLength(1); s.Blocks = (ushort[,])blocks.Clone(); byte[,] fl = FluidManager.main.fluid; s.Fluid = (fl != null && fl.GetLength(0) == s.W && fl.GetLength(1) == s.H) ? (byte[,])fl.Clone() : new byte[s.W, s.H]; s.Meta = CaptureMeta(w); if (string.IsNullOrEmpty(Slots.CurrentRun)) Slots.CurrentRun = Guid.NewGuid().ToString("N"); s.Meta["run"] = Slots.CurrentRun; s.Write(Paths.Snap); try { float rt = j["runTime"] != null ? (float)j["runTime"] : 0f; Slots.Store(s, target, auto, w.biomeDepth + 1, rt, PlayerCamera.main.body.charType, RunType.Current(), LayerArt.CurrentIndex(w)); if (target != Slots.AutoSlot) Slots.CurrentSlot = target; } catch (Exception e) { Plugin.Log.LogError("Couldn't write the save slot: " + e); } Plugin.Log.LogInfo((auto ? "Auto-saved" : "Saved") + " layer " + (w.biomeDepth + 1) + " to " + Slots.Name(target) + " with " + ((JArray)s.Meta["objs"]).Count + " world objects."); Runner.ResetAuto(); return true; } catch (Exception e) { Plugin.Log.LogError("Save failed: " + e); Runner.Toast("Save failed, see BepInEx\\LogOutput.log.", true); return false; } } private static JObject CaptureMeta(WorldGeneration w) { Body b = PlayerCamera.main.body; JObject m = new JObject(); m["ver"] = Plugin.Version; m["depth"] = w.biomeDepth; m["px"] = b.transform.position.x; m["py"] = b.transform.position.y; m["right"] = b.isRight; m["layerTime"] = w.layerTimeSpent; m["fog"] = w.fogAmount; m["rain"] = w.skyMaterial != null ? w.skyMaterial.GetFloat("_RainIntensity") : 0f; int mod = -1; foreach (LayerModifier lm in LayerModifier.availableModifiers) if (lm.active) { mod = lm.modifierIndex; break; } m["mod"] = mod; Merc.Capture(w, m); Lights.CaptureBody(b, m); JArray objs = new JArray(); Transform bodyT = b.transform; foreach (BuildingEntity be in Object.FindObjectsOfType()) { try { if (be == null || Under(be.transform, bodyT) || HasOwner(be.transform)) continue; if (be.health < 0.5f) continue; objs.Add(CaptureBuilding(be)); } catch (Exception e) { Plugin.Log.LogWarning("Skipped " + be.name + ": " + e.Message); } } foreach (Item it in Item.allItems.ToArray()) { try { if (it == null || string.IsNullOrEmpty(it.id)) continue; Transform p = it.transform.parent; if (p != null && !p.name.StartsWith("DOSPAWN")) continue; if (Under(it.transform, bodyT)) continue; objs.Add(CaptureItem(it)); } catch (Exception e) { Plugin.Log.LogWarning("Skipped " + it.name + ": " + e.Message); } } List spawns = new List(); foreach (GameObject g in SceneManager.GetActiveScene().GetRootGameObjects()) if (g.name.StartsWith("DOSPAWN")) spawns.Add(g); if (w.worldGrid != null) foreach (Transform t in w.worldGrid.transform) if (t.name.StartsWith("DOSPAWN")) spawns.Add(t.gameObject); foreach (GameObject g in spawns) { try { string res = Prefabs.ForSpawn(g); if (res == null) continue; JObject o = Pose(g.transform); o["k"] = "spawn"; o["res"] = res; o["tm"] = g.GetComponent() != null; objs.Add(o); } catch (Exception e) { Plugin.Log.LogWarning("Skipped " + g.name + ": " + e.Message); } } m["objs"] = objs; return m; } private static bool Under(Transform t, Transform root) { for (Transform c = t; c != null; c = c.parent) if (c == root) return true; return false; } private static bool HasOwner(Transform t) { for (Transform c = t.parent; c != null; c = c.parent) if (c.GetComponent() != null || c.GetComponent() != null) return true; return false; } private static JObject Pose(Transform t) { JObject o = new JObject(); o["x"] = t.position.x; o["y"] = t.position.y; o["rz"] = t.eulerAngles.z; o["sx"] = t.localScale.x; o["sy"] = t.localScale.y; return o; } private static JObject CaptureItem(Item it) { JObject o = Pose(it.transform); o["k"] = "item"; o["res"] = it.id; o["cond"] = it.condition; o["fav"] = it.favourited; o["label"] = it.label; o["sw"] = it.colorSwatch; string c = Comps.Capture(it.gameObject); if (c != null) o["comps"] = c; if (it.transform.parent == null && it.GetComponent() != null) o["lock"] = true; int ls = Lights.State(it); if (ls != 0) o["light"] = ls; if (it.GetComponent() != null) { JArray kids = new JArray(); foreach (Transform t in it.transform) { Item k = t.GetComponent(); if (k != null && !string.IsNullOrEmpty(k.id)) kids.Add(CaptureItem(k)); } o["kids"] = kids; } return o; } private static JObject CaptureBuilding(BuildingEntity be) { JObject o = Pose(be.transform); o["k"] = "build"; o["res"] = Prefabs.ForBuilding(be.gameObject); o["hp"] = be.health; o["bx"] = be.blockPlacedOn.x; o["by"] = be.blockPlacedOn.y; o["rg"] = be.requireGround; string c = Comps.Capture(be.gameObject); if (c != null) o["comps"] = c; JObject cry = Crystals.Capture(be, (string)o["res"]); if (cry != null) o["cry"] = cry; Veins.Capture(be.gameObject, o); TraderScript tr = be.GetComponent(); if (tr != null) { JObject t = new JObject(); t["char"] = tr.character; t["vg"] = tr.valueGiven; t["tvg"] = tr.totalValueGiven; t["rep"] = tr.reputation; t["host"] = tr.hostility; t["conv"] = tr.startedConvo; JArray items = new JArray(); if (tr.items != null) { foreach (TraderItem ti in tr.items) { JObject x = new JObject(); x["id"] = ti.id; x["b"] = ti.bought; x["v"] = ti.value; x["p"] = Convert.ToInt32(ti.preference); items.Add(x); } } t["items"] = items; o["trader"] = t; } CorpseScript cs = be.GetComponent(); if (cs != null && CorpseComment != null) o["seen"] = (bool)CorpseComment.GetValue(cs); return o; } } internal class Spawned { public GameObject Go; public JObject Data; } internal static class Loader { public static Snapshot Pending; public static bool Restoring; public static bool InStart; public static float QuietUntil; private static readonly FieldInfo BlocksField = AccessTools.Field(typeof(WorldGeneration), "worldBlocks"); private static readonly FieldInfo HealthField = AccessTools.Field(typeof(BuildingEntity), "_health"); private static readonly FieldInfo CorpseComment = AccessTools.Field(typeof(CorpseScript), "didComment"); private static readonly HashSet allowed = new HashSet(); public static bool Quiet { get { return Restoring || Time.realtimeSinceStartup < QuietUntil; } } public static void CheckSave() { Pending = null; if (MultiplayerGuard.Check()) return; try { if (!SaveSystem.loadedRun || !File.Exists(Paths.Save) || !File.Exists(Paths.Snap)) return; string h = Snapshot.HashOf(File.ReadAllBytes(Paths.Save)); Snapshot s = Snapshot.Read(Paths.Snap); if (s != null && s.Hash == h) { Pending = s; if (s.Meta["run"] != null) Slots.CurrentRun = (string)s.Meta["run"]; Slots.CurrentSlot = Slots.ManualFor(Slots.FindByHash(s.Hash), Slots.CurrentRun); Plugin.Log.LogInfo("Save Anywhere save found for layer " + (s.Depth + 1) + ", restoring it."); } } catch (Exception e) { Pending = null; Plugin.Log.LogError("Couldn't read the Save Anywhere save: " + e); } } public static void KeepSave() { try { if (Pending != null && !File.Exists(Paths.Save)) File.WriteAllBytes(Paths.Save, Pending.SaveBytes); } catch (Exception e) { Plugin.Log.LogError("Couldn't keep the save: " + e); } } public static bool Matches(WorldGeneration w) { ushort[,] blocks = (ushort[,])BlocksField.GetValue(w); if (blocks == null || blocks.GetLength(0) != Pending.W || blocks.GetLength(1) != Pending.H) return false; return Pending.Depth == w.biomeDepth; } private static IEnumerator Call(WorldGeneration w, string name) { return (IEnumerator)AccessTools.Method(typeof(WorldGeneration), name).Invoke(w, null); } private static void Try(string what, Action a) { try { a(); } catch (Exception e) { Plugin.Log.LogError("Restore step '" + what + "' failed: " + e); } } public static IEnumerator Restore(WorldGeneration w) { Snapshot s = Pending; Restoring = true; allowed.Clear(); w.loadingObject.SetActive(true); w.generatingWorld = true; yield return Call(w, "WorldPreprocess"); yield return Call(w, "WorldCreateBackground"); w.SetLoadingText("gencreatingcolliders"); yield return null; Try("terrain", () => ApplyTerrain(w, s, true)); Try("player", () => PlacePlayer(s)); yield return null; List spawned = new List(); Try("objects", () => SpawnAll(w, s, spawned)); yield return null; yield return null; Try("object state", () => PostStart(spawned)); Try("cleanup", () => Cleanup()); Body b = PlayerCamera.main.body; float hap = b.happiness, caf = b.caffeinated, hear = b.hearingLoss, hun = b.hunger, thi = b.thirst; yield return Call(w, "FinishWorldGeneration"); Try("cleanup", () => Cleanup()); Try("pod effects", () => RemovePodEffects()); Try("terrain", () => ApplyTerrain(w, s, false)); Try("fluid", () => ApplyFluid(s)); Try("stats", () => { b.happiness = hap; b.caffeinated = caf; b.hearingLoss = hear; b.hunger = hun; b.thirst = thi; w.layerTimeSpent = (float)s.Meta["layerTime"]; w.SetFog((float)s.Meta["fog"]); if (w.skyMaterial != null) w.skyMaterial.SetFloat("_RainIntensity", (float)s.Meta["rain"]); }); Try("veins", () => Veins.Repair()); Try("merc run", () => Merc.Apply(w, s)); Try("lights", () => Lights.ApplyBody(b, s)); Try("player", () => PlacePlayer(s)); Restoring = false; QuietUntil = Time.realtimeSinceStartup + 3f; Pending = null; allowed.Clear(); Plugin.Log.LogInfo("Restored layer " + (s.Depth + 1) + " (" + spawned.Count + " objects)."); Runner.Toast("Save loaded.", false); Runner.JustRestored = true; Runner.ResetAuto(); } private static void ApplyTerrain(WorldGeneration w, Snapshot s, bool force) { ushort[,] blocks = (ushort[,])BlocksField.GetValue(w); if (!force) { bool same = true; for (int x = 0; x < s.W && same; x++) for (int y = 0; y < s.H; y++) if (blocks[x, y] != s.Blocks[x, y]) { same = false; break; } if (same) return; } Buffer.BlockCopy(s.Blocks, 0, blocks, 0, s.W * s.H * 2); w.UpdateWorld(); } private static void ApplyFluid(Snapshot s) { byte[,] fl = FluidManager.main.fluid; if (fl == null || fl.GetLength(0) != s.W || fl.GetLength(1) != s.H) return; Buffer.BlockCopy(s.Fluid, 0, fl, 0, s.W * s.H); } private static void PlacePlayer(Snapshot s) { Body b = PlayerCamera.main.body; Vector3 pos = new Vector3((float)s.Meta["px"], (float)s.Meta["py"], b.transform.position.z); b.transform.position = pos; if (b.rb != null) b.rb.velocity = Vector2.zero; Transform cam = PlayerCamera.main.transform; cam.position = new Vector3(pos.x, pos.y, cam.position.z); } private static Vector3 Pos(JObject o) { return new Vector3((float)o["x"], (float)o["y"], 0f); } private static Quaternion Rot(JObject o) { return Quaternion.Euler(0f, 0f, (float)o["rz"]); } private static void SetPose(GameObject g, JObject o) { Vector3 sc = g.transform.localScale; g.transform.localScale = new Vector3((float)o["sx"], (float)o["sy"], sc.z); } private static void SpawnAll(WorldGeneration w, Snapshot s, List spawned) { JArray objs = (JArray)s.Meta["objs"]; int failed = 0; foreach (JToken tok in objs) { JObject o = (JObject)tok; try { string k = (string)o["k"]; GameObject g = null; if (k == "item") g = SpawnItem(o); else if (k == "build") g = SpawnBuilding(w, o); else if (k == "spawn") g = SpawnSpawn(w, o); if (g == null) { failed++; continue; } allowed.Add(g.GetInstanceID()); Spawned sp = new Spawned(); sp.Go = g; sp.Data = o; spawned.Add(sp); } catch (Exception e) { failed++; Plugin.Log.LogWarning("Couldn't restore " + (string)o["res"] + ": " + e.Message); } } if (failed > 0) Plugin.Log.LogWarning(failed + " saved objects couldn't be restored."); } private static GameObject SpawnItem(JObject o) { Object pf = Resources.Load((string)o["res"]); if (pf == null) return null; GameObject g = Object.Instantiate(pf, Pos(o), Rot(o)) as GameObject; if (g == null) return null; SetPose(g, o); ApplyItem(g, o); return g; } private static void ApplyItem(GameObject g, JObject o) { Item it = g.GetComponent(); if (it == null) return; it.condition = (float)o["cond"]; it.favourited = (bool)o["fav"]; it.label = (string)o["label"]; it.colorSwatch = (int)o["sw"]; Comps.Apply(g, (string)o["comps"]); if (o["lock"] != null && (bool)o["lock"] && g.GetComponent() == null) g.AddComponent(); if (o["light"] != null) Lights.Set(it, (int)o["light"]); } private static void FillContainer(GameObject g, JObject o) { JArray kids = o["kids"] as JArray; if (kids == null) return; Container c = g.GetComponent(); if (c == null) return; List old = new List(); foreach (Transform t in g.transform) if (t.GetComponent() != null) old.Add(t.gameObject); foreach (GameObject x in old) Object.Destroy(x); foreach (JToken tok in kids) { JObject ko = (JObject)tok; try { Object pf = Resources.Load((string)ko["res"]); if (pf == null) continue; GameObject kg = Object.Instantiate(pf, g.transform.position, Quaternion.identity) as GameObject; if (kg == null) continue; ApplyItem(kg, ko); c.LoadItem(kg.GetComponent()); FillContainer(kg, ko); } catch (Exception e) { Plugin.Log.LogWarning("Couldn't restore container item " + (string)ko["res"] + ": " + e.Message); } } } private static GameObject SpawnBuilding(WorldGeneration w, JObject o) { GameObject pf = Prefabs.Load((string)o["res"]); if (pf == null) return null; GameObject g = Object.Instantiate(pf, Pos(o), Rot(o)); if (g.GetComponent() != null && w.worldGrid != null) g.transform.SetParent(w.worldGrid.transform, true); SetPose(g, o); BuildingEntity be = g.GetComponent(); if (be != null) { be.blockPlacedOn = new Vector2Int((int)o["bx"], (int)o["by"]); if (HealthField != null) HealthField.SetValue(be, (float)o["hp"]); if (be.requireGround && w.ChunkUpdated != null) { int cx = be.blockPlacedOn.x / WorldGeneration.CHUNKSIZE, cy = be.blockPlacedOn.y / WorldGeneration.CHUNKSIZE; if (cx >= 0 && cy >= 0 && cx < w.ChunkUpdated.GetLength(0) && cy < w.ChunkUpdated.GetLength(1)) w.ChunkUpdated[cx, cy].AddListener(be.CheckSeating); } } ApplyTrader(g, o); try { Crystals.Apply(g, o["cry"] as JObject); if (be != null && HealthField != null) HealthField.SetValue(be, (float)o["hp"]); } catch (Exception e) { Plugin.Log.LogWarning("Crystal restore failed for " + g.name + ": " + e.Message); } try { Veins.Apply(g, o); } catch (Exception e) { Plugin.Log.LogWarning("Vein restore failed for " + g.name + ": " + e.Message); } return g; } private static GameObject SpawnSpawn(WorldGeneration w, JObject o) { GameObject pf = Prefabs.Load((string)o["res"]); if (pf == null) return null; GameObject g = Object.Instantiate(pf, Pos(o), Rot(o)); SetPose(g, o); if ((bool)o["tm"] && w.worldGrid != null) g.transform.SetParent(w.worldGrid.transform, true); List strip = new List(); foreach (Item it in g.GetComponentsInChildren(true)) strip.Add(it.gameObject); foreach (BuildingEntity be in g.GetComponentsInChildren(true)) strip.Add(be.gameObject); foreach (GameObject x in strip) if (x != g) Object.Destroy(x); return g; } private static void ApplyTrader(GameObject g, JObject o) { JObject t = o["trader"] as JObject; if (t == null) return; TraderScript tr = g.GetComponent(); if (tr == null) return; tr.character = (int)t["char"]; tr.valueGiven = (int)t["vg"]; tr.totalValueGiven = (int)t["tvg"]; tr.reputation = (float)t["rep"]; tr.hostility = (float)t["host"]; tr.startedConvo = (bool)t["conv"]; List list = new List(); foreach (JToken tok in (JArray)t["items"]) { TraderItem ti = new TraderItem(); ti.id = (string)tok["id"]; ti.bought = (bool)tok["b"]; ti.value = (int)tok["v"]; ti.preference = (TraderScript.TraderItemPreference)Enum.ToObject(typeof(TraderScript.TraderItemPreference), (int)tok["p"]); list.Add(ti); } tr.items = list; } private static void PostStart(List spawned) { foreach (Spawned sp in spawned) { if (sp.Go == null) continue; try { string k = (string)sp.Data["k"]; if (k == "item") { FillContainer(sp.Go, sp.Data); Rigidbody2D rb = sp.Go.GetComponent(); if (rb != null && rb.bodyType != RigidbodyType2D.Static) rb.velocity = Vector2.zero; } else if (k == "build") { BuildingEntity be = sp.Go.GetComponent(); if (be != null && HealthField != null) HealthField.SetValue(be, (float)sp.Data["hp"]); Comps.Apply(sp.Go, (string)sp.Data["comps"]); ApplyTrader(sp.Go, sp.Data); CorpseScript cs = sp.Go.GetComponent(); if (cs != null && CorpseComment != null && sp.Data["seen"] != null) CorpseComment.SetValue(cs, (bool)sp.Data["seen"]); } } catch (Exception e) { Plugin.Log.LogWarning("Couldn't finish restoring " + sp.Go.name + ": " + e.Message); } } } private static bool IsAllowed(Transform t) { for (Transform c = t; c != null; c = c.parent) if (allowed.Contains(c.gameObject.GetInstanceID())) return true; return false; } private static void Cleanup() { Transform bodyT = PlayerCamera.main.body.transform; int n = 0; foreach (BuildingEntity be in Object.FindObjectsOfType()) { if (be == null) continue; if (IsUnder(be.transform, bodyT) || IsAllowed(be.transform)) continue; Object.Destroy(be.gameObject); n++; } foreach (Item it in Item.allItems.ToArray()) { if (it == null) continue; Transform p = it.transform.parent; if (p != null && !p.name.StartsWith("DOSPAWN")) continue; if (IsUnder(it.transform, bodyT) || IsAllowed(it.transform)) continue; Object.Destroy(it.gameObject); n++; } if (n > 0) Plugin.Log.LogInfo("Removed " + n + " objects that weren't in the save."); } private static bool IsUnder(Transform t, Transform root) { for (Transform c = t; c != null; c = c.parent) if (c == root) return true; return false; } private static void RemovePodEffects() { foreach (GameObject g in SceneManager.GetActiveScene().GetRootGameObjects()) if (g.name.StartsWith("ExplosionParticle") && !allowed.Contains(g.GetInstanceID())) Object.Destroy(g); } } [HarmonyPatch(typeof(SaveSystem), "TryLoadGame")] internal static class TryLoadPatch { private static void Prefix() { Loader.CheckSave(); } private static void Postfix() { Loader.KeepSave(); } } internal static class RunEnd { public static bool Ended; public static void DeleteSaves(string why) { Ended = true; try { if (!string.IsNullOrEmpty(Slots.CurrentRun)) Slots.DeleteRun(Slots.CurrentRun); } catch (Exception e) { Plugin.Log.LogError("Couldn't delete the save slots: " + e.Message); } try { bool any = false; if (File.Exists(Paths.Save)) { File.Delete(Paths.Save); any = true; } if (File.Exists(Paths.Snap)) { File.Delete(Paths.Snap); any = true; } if (any) Plugin.Log.LogInfo("Run ended (" + why + "), save deleted."); } catch (Exception e) { Plugin.Log.LogError("Couldn't delete the save: " + e.Message); } } } [HarmonyPatch(typeof(PlayerCamera), "EndSequence")] internal static class EndSequencePatch { private static void Prefix(int type) { if (type == 0) { RunEnd.Ended = true; Plugin.Log.LogInfo("Died. Your last save was kept, Continue to try again."); return; } RunEnd.DeleteSaves("ending"); } } [HarmonyPatch(typeof(PauseHandler), "TryQuit")] internal static class GiveUpPatch { private static void Postfix(PauseHandler __instance) { if (WorldGeneration.world != null && WorldGeneration.world.biomeOverride != WorldGeneration.OverrideSceneType.None) return; if (Traverse.Create(__instance).Field("timesQuitPressed").GetValue() >= 4) RunEnd.DeleteSaves("gave up"); } } [HarmonyPatch(typeof(WorldGeneration), "Start")] internal static class WorldStartPatch { private static void Prefix() { Loader.InStart = true; RunEnd.Ended = false; if (!SaveSystem.loadedRun) { Slots.CurrentRun = Guid.NewGuid().ToString("N"); Slots.CurrentSlot = 0; } else if (Loader.Pending == null) Slots.CurrentSlot = 0; Runner.ResetAuto(); } private static Exception Finalizer(Exception __exception) { Loader.InStart = false; return __exception; } } [HarmonyPatch(typeof(WorldGeneration), "GetRunSettingBool")] internal static class StartBonusPatch { private static readonly string[] Keys = { "permanentaddiction", "mindwiped", "zeroskills", "blind", "amputee" }; private static bool Prefix(string name, ref bool __result) { if (Loader.InStart && Loader.Pending != null && Array.IndexOf(Keys, name) >= 0) { __result = false; return false; } return true; } } [HarmonyPatch(typeof(WorldGeneration), "GenerateWorld")] internal static class GenerateWorldPatch { private static bool Prefix(WorldGeneration __instance, ref IEnumerator __result) { if (Loader.Pending == null) return true; bool ok = false; try { ok = Loader.Matches(__instance); } catch (Exception e) { Plugin.Log.LogError("Save check failed: " + e); } if (!ok) { Plugin.Log.LogWarning("The Save Anywhere save doesn't match this layer, generating normally."); Loader.Pending = null; return true; } __result = Loader.Restore(__instance); return false; } } [HarmonyPatch(typeof(WorldGeneration), "DistributeMiniBarrels")] internal static class MiniBarrelPatch { private static bool Prefix() { return !Loader.Restoring; } } [HarmonyPatch(typeof(WorldGeneration), "ApplyLayerModifiers")] internal static class LayerModifierPatch { private static bool Prefix(WorldGeneration __instance) { if (!Loader.Restoring || Loader.Pending == null) return true; int idx = (int)Loader.Pending.Meta["mod"]; if (idx >= 0) { LayerModifier m = LayerModifier.availableModifiers.FirstOrDefault(x => x.modifierIndex == idx); if (m != null) { m.Initialize(__instance); m.active = true; Traverse t = Traverse.Create(__instance); t.Field("layerPrefix").SetValue(Locale.GetOther("layermodifier" + idx)); t.Field("layerDescription").SetValue(Locale.GetOther("layermodifier" + idx + "dsc")); } } return false; } } [HarmonyPatch] internal static class TalkPatch { private static IEnumerable TargetMethods() { return AccessTools.GetDeclaredMethods(typeof(Talker)).Where(m => m.Name == "Talk").Cast(); } private static bool Prefix() { return !Loader.Quiet; } } [HarmonyPatch(typeof(Sound), "Play", new Type[] { typeof(string), typeof(Vector2), typeof(bool), typeof(bool), typeof(Transform), typeof(float), typeof(float), typeof(bool), typeof(bool) })] internal static class PodSoundPatch { private static bool Prefix(string clip) { return !(Loader.Restoring && clip == "lifePodHit"); } } [HarmonyPatch(typeof(PlayerCamera), "LifePodShake")] internal static class LifePodShakePatch { private static bool Prefix() { return !Loader.Quiet; } } [HarmonyPatch(typeof(AdaptiveButton), "overlayActive", MethodType.Getter)] internal static class MenuButtonPatch { private static void Postfix(ref bool __result) { if (Runner.UiBlocking) __result = true; } } [HarmonyPatch(typeof(PauseHandler), "Start")] internal static class PauseStartPatch { private static void Postfix(PauseHandler __instance) { try { PauseRing.Build(__instance); } catch (Exception e) { Plugin.Log.LogWarning("Couldn't add the pause menu buttons, using the fallback buttons instead: " + e); } } } internal static class PauseRing { private static readonly FieldInfo PosField = AccessTools.Field(typeof(PauseHandler), "buttonPos"); private static readonly List made = new List(); private static Sprite saveSpr, quitSpr, autoOnSpr, autoOffSpr; private static UnityEngine.UI.Image autoImg; private static UITooltip autoTip; private static bool lastAuto; private static bool lastShown = true; private static bool first = true; internal static bool Built { get { for (int i = 0; i < made.Count; i++) if (made[i] != null) return !MultiplayerGuard.Detected; return false; } } internal static void Build(PauseHandler ph) { made.Clear(); autoImg = null; autoTip = null; first = true; lastShown = true; List pos = PosField == null ? null : PosField.GetValue(ph) as List; if (ph.buttons == null || ph.buttons.Count == 0 || pos == null || pos.Count != ph.buttons.Count) { Plugin.Log.LogWarning("The pause menu layout wasn't what Save Anywhere expected, using the fallback buttons."); return; } RectTransform tpl = ph.buttons[0]; int baseCount = pos.Count; List shown = new List(); for (int i = 0; i < baseCount; i++) shown.Add(Scale(pos[i], i)); Vector2 left = shown[0], top = shown[0], right = shown[0]; foreach (Vector2 p in shown) { if (p.x < left.x) left = p; if (p.x > right.x) right = p; if (Mathf.Abs(p.x) < Mathf.Abs(top.x) || (Mathf.Abs(p.x) == Mathf.Abs(top.x) && p.y < top.y)) top = p; } Vector2 aL = new Vector2(left.x, -left.y), aT = new Vector2(top.x, -top.y), aR = new Vector2(right.x, -right.y); if (left.y > 0f || right.y > 0f || top.y > 0f) { float r = 0f; foreach (Vector2 p in shown) r = Mathf.Max(r, p.magnitude); if (r < 50f) r = 421f; aL = Spot(r, 125f); aT = Spot(r, 90f); aR = Spot(r, 55f); } if (saveSpr == null) { saveSpr = Icons.Make(0, false); quitSpr = Icons.Make(1, false); autoOnSpr = Icons.Make(2, false); autoOffSpr = Icons.Make(2, true); } Add(ph, pos, tpl, "SaveAnywhereAutoSave", Unscale(aL, pos.Count), autoOnSpr, "Auto-save", "", Runner.ClickAuto); Add(ph, pos, tpl, "SaveAnywhereSave", Unscale(aT, pos.Count), saveSpr, "Save", "Save your game right here, to a slot you pick.", Runner.ClickSave); Add(ph, pos, tpl, "SaveAnywhereSaveQuit", Unscale(aR, pos.Count), quitSpr, "Save & Quit", "Save to your current slot and go back to the main menu.", Runner.ClickSaveQuit); if (made.Count > 0) { autoImg = made[0].GetComponent(); autoTip = made[0].GetComponent(); Refresh(); } Plugin.Log.LogInfo("Added " + made.Count + " Save Anywhere buttons to the pause menu."); } private static Vector2 Factor(int index) { float t = 1f + index * 0.1f; return new Vector2(0.5f + Utils.OutCubic(t) * 0.5f, 0.5f + Utils.InOutCubic(t) * 0.5f); } private static Vector2 Scale(Vector2 p, int index) { Vector2 f = Factor(index); return new Vector2(p.x * f.x, p.y * f.y); } private static Vector2 Unscale(Vector2 p, int index) { Vector2 f = Factor(index); return new Vector2(Mathf.Approximately(f.x, 0f) ? p.x : p.x / f.x, Mathf.Approximately(f.y, 0f) ? p.y : p.y / f.y); } private static Vector2 Spot(float r, float deg) { float a = deg * Mathf.Deg2Rad; return new Vector2(Mathf.Round(Mathf.Cos(a) * r), Mathf.Round(Mathf.Sin(a) * r)); } private static void Add(PauseHandler ph, List pos, RectTransform tpl, string name, Vector2 at, Sprite spr, string title, string desc, UnityEngine.Events.UnityAction click) { GameObject g = Object.Instantiate(tpl.gameObject, tpl.parent, false); g.name = name; UITooltip tip = g.GetComponent(); if (tip != null) { tip.skipLocale = true; tip.localeName = ""; tip.localeDesc = ""; tip.tipName = title; tip.tipDesc = desc; } UnityEngine.UI.Image img = g.GetComponent(); if (img != null) { img.sprite = spr; img.color = Color.white; } UnityEngine.UI.Button btn = g.GetComponent(); if (btn != null) { btn.onClick = new UnityEngine.UI.Button.ButtonClickedEvent(); btn.onClick.AddListener(click); } RectTransform rt = (RectTransform)g.transform; rt.localPosition = new Vector3(at.x, at.y, tpl.localPosition.z); rt.localScale = Vector3.one; ph.buttons.Add(rt); pos.Add(at); made.Add(g); } internal static void Refresh() { if (made.Count == 0) return; bool show = !MultiplayerGuard.Detected; if (show != lastShown) { lastShown = show; foreach (GameObject g in made) if (g != null) g.SetActive(show); } if (autoImg == null) return; bool on = Plugin.AutoSave.Value; if (!first && on == lastAuto) return; first = false; lastAuto = on; autoImg.sprite = on ? autoOnSpr : autoOffSpr; autoImg.color = on ? Color.white : new Color(0.6f, 0.6f, 0.6f, 1f); if (autoTip != null) { autoTip.tipName = Runner.AutoLabel(); autoTip.tipDesc = on ? "Click to turn auto-saving off." : "Click to turn auto-saving on."; } } } internal static class Icons { private const int N = 40; private static Color[] px; private static void Put(int x, int y, Color c) { if (x < 0 || y < 0 || x >= N || y >= N) return; px[(N - 1 - y) * N + x] = c; } private static void Floppy(int ox, int oy, int s) { int cut = Mathf.Max(2, s / 6); int shL = s / 4, shR = (int)(s * 0.7f), shB = (int)(s * 0.34f); int slL = (int)(s * 0.52f), slR = (int)(s * 0.66f); int lbL = (int)(s * 0.17f), lbR = s - lbL, lbT = s / 2; for (int y = 0; y < s; y++) for (int x = 0; x < s; x++) { if (x - (s - 1 - cut) > y) continue; Color c = Color.white; if (x >= shL && x < shR && y < shB) c = (x >= slL && x < slR && y >= 1 && y < shB - 1) ? Color.white : Color.black; if (x >= lbL && x < lbR && y >= lbT && y < s - 1) c = Color.black; Put(ox + x, oy + y, c); } } internal static Sprite Make(int kind, bool off) { px = new Color[N * N]; for (int y = 0; y < N; y++) for (int x = 0; x < N; x++) { float dx = x + 0.5f - N * 0.5f, dy = y + 0.5f - N * 0.5f; float d = Mathf.Sqrt(dx * dx + dy * dy); Color c = d > N * 0.5f ? Color.clear : (d > N * 0.5f - 1f ? Color.white : Color.black); Put(x, y, c); } if (kind == 0) Floppy(11, 11, 18); else if (kind == 1) { Floppy(6, 13, 14); for (int x = 22; x <= 28; x++) { Put(x, 19, Color.white); Put(x, 20, Color.white); } for (int x = 28; x <= 32; x++) { int h = 32 - x; for (int y = 19 - h; y <= 20 + h; y++) Put(x, y, Color.white); } } else { Floppy(9, 9, 16); for (int y = 19; y <= 36; y++) for (int x = 19; x <= 36; x++) { float dx = x + 0.5f - 27.5f, dy = y + 0.5f - 27.5f; float d = Mathf.Sqrt(dx * dx + dy * dy); if (d <= 8f) Put(x, y, Color.black); if (d <= 7f) Put(x, y, d > 6f ? Color.white : Color.black); } for (int y = 23; y <= 27; y++) Put(27, y, Color.white); for (int x = 27; x <= 30; x++) Put(x, 27, Color.white); if (off) { for (int y = 0; y < N; y++) for (int x = 0; x < N; x++) { if (x < 8 || x > 31 || y < 8 || y > 31) continue; int k = Mathf.Abs(x - (N - 1 - y)); if (k <= 1) Put(x, y, Color.white); else if (k == 2) Put(x, y, Color.black); } } } Texture2D t = new Texture2D(N, N, TextureFormat.RGBA32, false); t.hideFlags = HideFlags.HideAndDontSave; t.filterMode = FilterMode.Point; t.wrapMode = TextureWrapMode.Clamp; t.SetPixels(px); t.Apply(); Sprite sp = Sprite.Create(t, new Rect(0f, 0f, N, N), new Vector2(0.5f, 0.5f), 100f / 3f); sp.hideFlags = HideFlags.HideAndDontSave; return sp; } } internal static class Floppy { private const string IconPng = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABWZkRUNSJJPjAOWrYpkAAAHzSURBVHgB5cRjtCVn2oDh+3mravPY57RtxLYzM0kGydi2bdu2EYxi22bbPH2szap6n2/Vj7PWXr06mWimZ773x3Wxbt061q1bpwlV1b2pKs+EqmqtdevW6bp165hkAJ03bx4ATxegewPYl3nz5gEoQMLMmzcPgP+kefPmASiAAdgf5s2bB6AGYH+ZN28eBmB/MgD7kwHYnwzA/mQAnq7169fzRAD+FQMwaf369ewLwL7MmzePxLx582Rv8+bNA+BfMQCJefPmsS/z5s1TQJ8ugCdiAPYnA7C39evX8+8AsDcDUGv9+vUAUmvevHnydABSa/369QDUMgC15s2bJwCAPpsA5s2bJwC1DMDe5s2bByDPpnnz5gGwNwOwPxmAva1fvx5An03r168HYG8GYG/z5s0DkGfTvHnzANibAdifDMDe1q9fD6DPpvXr1wOwNwOwt3nz5gHIs2nevHkA7M0A7E8GYG/r168H0GfT+vXrAdibAdjbvHnzAOTZNG/ePAD2ZgD2JwOwfv16EgCJ9evXA+izaf369QAk1q9fTwLAAMybN08SAOvXr1eAefPmySRAno558+bJJID169crwLx58yQBYABqzZs3j3nz5imgz6Z58+bpvHnzAKhl1q9fD6AJgP8EQBPr16/HALJ+/Xr2B0D+D4vj8vCfnqe8AAAAAElFTkSuQmCC"; private static readonly Color[] SlotColors = { new Color32(96, 150, 235, 255), new Color32(235, 90, 90, 255), new Color32(90, 200, 120, 255), new Color32(240, 200, 70, 255), new Color32(170, 120, 230, 255), new Color32(245, 150, 70, 255), new Color32(70, 200, 210, 255), new Color32(240, 130, 190, 255), new Color32(170, 215, 80, 255), new Color32(150, 162, 182, 255) }; private static Texture2D icon; public static Texture2D Icon { get { if (icon != null) return icon; icon = new Texture2D(2, 2, TextureFormat.RGBA32, false); ImageConversion.LoadImage(icon, Convert.FromBase64String(IconPng)); icon.filterMode = FilterMode.Point; icon.wrapMode = TextureWrapMode.Clamp; icon.hideFlags = HideFlags.HideAndDontSave; return icon; } } public static Color Tint(int slot, bool empty) { if (empty) return new Color(0.45f, 0.47f, 0.5f, 0.5f); if (slot == Slots.AutoSlot) return new Color32(225, 228, 235, 255); return SlotColors[(Mathf.Max(1, slot) - 1) % SlotColors.Length]; } public static void Draw(Rect r, int slot, bool empty) { Color old = GUI.color; GUI.color = Tint(slot, empty); GUI.DrawTexture(r, Icon); GUI.color = old; } public static void DrawPlain(Rect r) { GUI.DrawTexture(r, Icon); } } internal static class SlotScreen { public static bool Open; public static bool Loading; public static bool SaveMode; private static bool quitAfter; private static List list = new List(); private static string currentHash; private static int currentSlot; private static int confirmDelete = -1; private static int confirmOverwrite = -1; private static int cloudPanel = -1; private static string shareCode, shareMsg, shareUntil; private static int shareSlot = -1; private static bool codePanel; private static string codeText = "", codeMsg; private static string cloudConfirm; private static GUIStyle cloudSmall, btnSmall, panelText; public static void OpenForSave(bool quit) { Refresh(); SaveMode = true; quitAfter = quit; Open = true; } private static Texture2D white; private static GUIStyle title, sub, cardTitle, cardBig, cardText, badge, numStyle, btn, btnDanger, menuBtn; private static readonly Dictionary biomeIcons = new Dictionary(); public static void Close() { Open = false; Loading = false; SaveMode = false; quitAfter = false; confirmDelete = -1; confirmOverwrite = -1; cloudPanel = -1; cloudConfirm = null; } private static string gameFlag; private static void Refresh() { list = Slots.LoadIndex(); LayerArt.ForgetMissing(); currentSlot = Slots.CurrentSlot; currentHash = null; try { if (File.Exists(Paths.Save)) currentHash = Snapshot.HashOf(File.ReadAllBytes(Paths.Save)); } catch (Exception) { } gameFlag = CheatFlag.OfGame(); if (Plugin.CloudEnabled.Value) Runner.Run(Cloud.RefreshList()); } private static void Styles() { if (title != null) return; white = Texture2D.whiteTexture; title = new GUIStyle(GUI.skin.label) { fontSize = 40, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft }; title.normal.textColor = new Color(1f, 0.78f, 0.3f); sub = new GUIStyle(GUI.skin.label) { fontSize = 16, alignment = TextAnchor.MiddleCenter, wordWrap = true, richText = true }; sub.normal.textColor = new Color(0.8f, 0.8f, 0.8f); cardTitle = new GUIStyle(GUI.skin.label) { fontSize = 18, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft }; cardTitle.normal.textColor = Color.white; cardBig = new GUIStyle(GUI.skin.label) { fontSize = 22, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter }; cardBig.normal.textColor = Color.white; cardText = new GUIStyle(GUI.skin.label) { fontSize = 14, alignment = TextAnchor.MiddleCenter, wordWrap = true, richText = true }; cardText.normal.textColor = new Color(0.82f, 0.82f, 0.82f); badge = new GUIStyle(GUI.skin.label) { fontSize = 12, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter }; badge.normal.textColor = Color.black; numStyle = new GUIStyle(GUI.skin.label) { fontSize = 40, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter }; numStyle.normal.textColor = new Color(0.2f, 0.2f, 0.24f); btn = new GUIStyle(GUI.skin.button) { fontSize = 16, fontStyle = FontStyle.Bold }; btnDanger = new GUIStyle(btn) { fontSize = 14, padding = new RectOffset(2, 2, 2, 2) }; btnDanger.normal.textColor = new Color(1f, 0.6f, 0.55f); btnDanger.hover.textColor = new Color(1f, 0.45f, 0.4f); menuBtn = new GUIStyle(GUI.skin.button) { fontSize = 18, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft, padding = new RectOffset(56, 10, 4, 4) }; cloudSmall = new GUIStyle(GUI.skin.label) { fontSize = 12, alignment = TextAnchor.MiddleLeft, wordWrap = true, richText = true, padding = new RectOffset(0, 0, 0, 0), margin = new RectOffset(0, 0, 0, 0) }; cloudSmall.normal.textColor = new Color(0.85f, 0.85f, 0.85f); btnSmall = new GUIStyle(GUI.skin.button) { fontSize = 13, fontStyle = FontStyle.Bold }; panelText = new GUIStyle(GUI.skin.label) { fontSize = 15, alignment = TextAnchor.MiddleLeft, wordWrap = true, richText = true }; panelText.normal.textColor = new Color(0.88f, 0.88f, 0.88f); } private static void Fill(Rect r, Color c) { Color old = GUI.color; GUI.color = c; GUI.DrawTexture(r, white); GUI.color = old; } private static void Frame(Rect r, Color c, float t) { Fill(new Rect(r.x, r.y, r.width, t), c); Fill(new Rect(r.x, r.yMax - t, r.width, t), c); Fill(new Rect(r.x, r.y, t, r.height), c); Fill(new Rect(r.xMax - t, r.y, t, r.height), c); } private static void Badge(Rect r, string text, Color bg) { Fill(r, bg); GUI.Label(r, text, badge); } private static Sprite BiomeIcon(int layer) { Sprite s; if (biomeIcons.TryGetValue(layer, out s)) return s; try { s = Resources.Load("BiomeIcon/" + layer); } catch (Exception) { s = null; } biomeIcons[layer] = s; return s; } private static string BiomeName(int layer) { try { string n = Locale.GetOther("layertitle" + layer); if (!string.IsNullOrEmpty(n) && n != "layertitle" + layer) return n; } catch (Exception) { } return ""; } private static string CharName(int c) { try { string n = Locale.GetOther("char" + c + "name"); if (!string.IsNullOrEmpty(n) && n != "char" + c + "name") return n; } catch (Exception) { } return "Character " + (c + 1); } public static void DrawMenuButton(float vw) { Styles(); Rect r = new Rect(vw - 250f, 20f, 230f, 56f); if (GUI.Button(r, "SAVE SLOTS", menuBtn)) { Refresh(); SaveMode = false; Open = true; } Floppy.DrawPlain(new Rect(r.x + 10f, r.y + 8f, 40f, 40f)); } public static void Draw(float vw, float vh) { Styles(); Event e = Event.current; if (e.type == EventType.KeyDown && e.keyCode == KeyCode.Escape) { if (codePanel) codePanel = false; else if (cloudPanel > 0) cloudPanel = -1; else Close(); e.Use(); return; } Fill(new Rect(0, 0, vw, vh), new Color(0.03f, 0.03f, 0.05f, 0.93f)); int count = Slots.Count; foreach (SlotInfo si in list) if (si.Slot > count && si.Slot != Slots.AutoSlot) count = si.Slot; if (Plugin.CloudEnabled.Value) foreach (int k in Cloud.Remote.Keys) if (k > count && k != Slots.AutoSlot && k <= 10) count = k; int total = count + 1; float cw = 220f, ch = Plugin.CloudEnabled.Value ? 424f : 386f, gap = 22f; int cols = Mathf.Clamp(Mathf.FloorToInt((vw - 40f + gap) / (cw + gap)), 1, Mathf.Min(total, 6)); int rows = (total + cols - 1) / cols; float gridW = cols * cw + (cols - 1) * gap; float gridH = rows * ch + (rows - 1) * gap; float top = Mathf.Max(150f, (vh - gridH) * 0.5f); float gx = (vw - gridW) * 0.5f; float tw = 420f; float tx = (vw - tw) * 0.5f; Floppy.DrawPlain(new Rect(tx, top - 128f, 72f, 72f)); GUI.Label(new Rect(tx + 90f, top - 128f, tw - 90f, 72f), SaveMode ? "SAVE GAME" : "SAVE SLOTS", title); string head = SaveMode ? "Pick a slot to save into. " + Plugin.SaveKey.Value + " and Save & Quit then keep saving into that slot (marked CURRENT). Auto-save only uses its own slot." : "Pick a save to load it. CONTINUE marks the save the Continue button loads."; GUI.Label(new Rect(gx, top - 50f, gridW, 36f), head, sub); if (Plugin.ShowCheatFlag.Value) GUI.Label(new Rect(gx, top - 17f, gridW, 16f), "Debug: the game's save file (save.sv) is " + (gameFlag == null ? "not there right now" : "marked as cheated: " + CheatFlag.Colored(gameFlag) + "") + "", sub); SlotInfo newest = list.OrderByDescending(x => x.SavedAt).FirstOrDefault(); bool panel = cloudPanel > 0 || codePanel; GUI.enabled = !panel; for (int idx = 0; idx < total; idx++) { int i = idx == 0 ? Slots.AutoSlot : idx; Rect card = new Rect(gx + (idx % cols) * (cw + gap), top + (idx / cols) * (ch + gap), cw, ch); SlotInfo s = list.FirstOrDefault(x => x.Slot == i); DrawCard(card, i, s, newest); } float by = top + gridH + 26f; GUI.Label(new Rect(gx, by, gridW, 44f), "Auto-save has its own slot and never overwrites your manual saves. A run's slots are deleted when the run ends.", sub); bool codes = !SaveMode && Plugin.CloudEnabled.Value; float bx = codes ? (vw - 440f) * 0.5f : (vw - 200f) * 0.5f; if (GUI.Button(new Rect(bx, by + 54f, 200f, 46f), "BACK", btn)) Close(); if (codes && GUI.Button(new Rect(bx + 240f, by + 54f, 200f, 46f), "SHARE CODE", btn)) { codePanel = true; codeMsg = null; } GUI.enabled = true; if (cloudPanel > 0) DrawCloudPanel(vw, vh); else if (codePanel) DrawCodePanel(vw, vh); } private static Cloud.CloudSlot CloudFor(int slot) { if (!Plugin.CloudEnabled.Value) return null; Cloud.CloudSlot c; return Cloud.Remote.TryGetValue(slot, out c) ? c : null; } private static string Describe(int layer, int character, float runTime, DateTime at) { return "Layer " + layer + ", " + CharName(character) + ", run time " + TimeSpan.FromSeconds(runTime).ToString().Split('.')[0] + ", saved " + at.ToString("MMM d, HH:mm"); } private static void DrawIcon(Rect area, float width) { Texture2D ic = Cloud.Icon; if (ic == null) return; float h = width * ic.height / ic.width; GUI.DrawTexture(new Rect(area.x, area.y + (area.height - h) * 0.5f, width, h), ic); } private static void OpenPanel(int slot) { cloudPanel = slot; cloudConfirm = null; if (shareSlot != slot) { shareCode = null; shareMsg = null; shareSlot = slot; } Runner.Run(Cloud.FetchVersions(slot)); } private static void DrawCloudRow(Rect r, int slot, SlotInfo s) { if (!Plugin.CloudEnabled.Value) return; Cloud.CloudSlot c = CloudFor(slot); string status; if (Cloud.ListState == "loading") status = "Checking the cloud..."; else if (Cloud.ListState == "error") status = "Cloud unavailable"; else if (c == null) { if (s == null) return; status = "Not in the cloud yet"; } else if (s == null) status = "Only in the cloud"; else if (Cloud.Same(s, c)) status = "Synced to the cloud"; else if (Cloud.SavedTime(c) > s.SavedAt) status = "Cloud has a newer save"; else status = "Cloud copy is older"; Rect row = new Rect(r.x + 10f, r.y + 346f, r.width - 20f, 28f); DrawIcon(row, 26f); float right = SaveMode ? row.xMax : row.xMax - 66f; GUI.Label(new Rect(row.x + 32f, row.y - 6f, right - row.x - 36f, row.height + 12f), status, cloudSmall); if (!SaveMode && GUI.Button(new Rect(row.xMax - 62f, row.y, 62f, 28f), "CLOUD", btnSmall)) OpenPanel(slot); } private static void DrawCloudPanel(float vw, float vh) { int slot = cloudPanel; Fill(new Rect(0, 0, vw, vh), new Color(0f, 0f, 0f, 0.55f)); float pw = Mathf.Min(680f, vw - 40f), ph = 610f; Rect p = new Rect((vw - pw) * 0.5f, Mathf.Max(20f, (vh - ph) * 0.5f), pw, ph); Fill(p, new Color(0.1f, 0.1f, 0.13f, 0.99f)); Frame(p, new Color(0.96f, 0.55f, 0.16f), 2f); DrawIcon(new Rect(p.x + 18f, p.y + 14f, 60f, 40f), 60f); GUI.Label(new Rect(p.x + 90f, p.y + 14f, pw - 110f, 40f), (slot == Slots.AutoSlot ? "AUTO-SAVE" : "SLOT " + slot) + " IN THE CLOUD", cardBig); bool locked = Cloud.Busy; bool canUpload = Cloud.State != "off" && Cloud.State != "readonly"; float y = p.y + 66f; SlotInfo local = list.FirstOrDefault(x => x.Slot == slot); GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 26f), "On this PC: " + (local != null ? Describe(local.Layer, local.Character, local.RunTime, local.SavedAt) : "nothing in this slot"), panelText); y += 32f; if (local != null) { GUI.enabled = !locked && canUpload; if (GUI.Button(new Rect(p.x + 20f, y, 260f, 32f), "UPLOAD THIS PC'S SAVE", btnSmall)) { Cloud.QueueUpload(slot); Runner.Toast("Uploading " + Slots.Name(slot) + "...", false); } GUI.enabled = !locked && canUpload; if (GUI.Button(new Rect(p.x + 290f, y, 200f, 32f), "SHARE THIS SAVE", btnSmall)) { shareCode = null; shareMsg = "Making a share code..."; int sl = slot; Runner.Run(Cloud.Share(sl, (c, until, err) => { shareSlot = sl; shareCode = c; shareUntil = until; shareMsg = err; })); } GUI.enabled = true; y += 40f; if (shareCode != null) { string shown = shareCode.Length == 8 ? shareCode.Substring(0, 4) + "-" + shareCode.Substring(4) : shareCode; GUI.Label(new Rect(p.x + 20f, y, pw - 160f, 32f), "Share code: " + shown + " works until " + shareUntil + "", panelText); if (GUI.Button(new Rect(p.xMax - 130f, y, 110f, 30f), "COPY", btnSmall)) { GUIUtility.systemCopyBuffer = shown; Runner.Toast("Share code copied.", false); } y += 40f; } else if (!string.IsNullOrEmpty(shareMsg)) { GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 32f), "" + shareMsg + "", cloudSmall); y += 40f; } } GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 24f), "Cloud copies (newest first, up to 6 kept)", panelText); y += 28f; if (Cloud.VersionsState == "loading") GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 26f), "Loading...", panelText); else if (Cloud.VersionsState == "error") GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 26f), "Couldn't load the cloud copies.", panelText); else if (Cloud.Versions.Count == 0) GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 26f), "No cloud copies of this slot yet.", panelText); else { for (int i = 0; i < Cloud.Versions.Count && i < 6; i++) { Cloud.CloudSlot v = Cloud.Versions[i]; Rect row = new Rect(p.x + 20f, y, pw - 40f, 40f); Fill(row, new Color(1f, 1f, 1f, i % 2 == 0 ? 0.05f : 0.02f)); string tag = i == 0 ? "NEWEST " : ""; if (local != null && Cloud.Same(local, v)) tag += "(same as this PC) "; GUI.Label(new Rect(row.x + 8f, row.y, row.width - 140f, row.height), tag + Describe(v.Layer, v.Character, v.RunTime, Cloud.SavedTime(v)), cloudSmall); string key = "dl" + v.Version; string label = local != null ? (cloudConfirm == key ? "SURE?" : "REPLACE") : "DOWNLOAD"; GUI.enabled = !locked; if (GUI.Button(new Rect(row.xMax - 124f, row.y + 5f, 116f, 30f), label, btnSmall)) { if (local != null && cloudConfirm != key) cloudConfirm = key; else { cloudConfirm = null; string ver = i == 0 ? null : v.Version; Runner.Run(Cloud.Download(slot, ver, ok => { Refresh(); Runner.Run(Cloud.FetchVersions(slot)); })); } } GUI.enabled = true; y += 44f; } } float by = p.yMax - 54f; if (local != null) GUI.Label(new Rect(p.x + 20f, by - 40f, pw - 40f, 36f), "REPLACE puts the cloud copy into this slot on this PC. Your current save in this slot is overwritten.", cloudSmall); GUI.enabled = !locked && Cloud.Versions.Count > 0; if (GUI.Button(new Rect(p.x + 20f, by, 220f, 38f), cloudConfirm == "del" ? "SURE? DELETE ALL" : "DELETE FROM CLOUD", btnDanger)) { if (cloudConfirm != "del") cloudConfirm = "del"; else { cloudConfirm = null; Runner.Run(Cloud.DeleteRemote(slot, () => { Refresh(); Runner.Run(Cloud.FetchVersions(slot)); })); } } GUI.enabled = true; if (locked) GUI.Label(new Rect(p.x + 250f, by, 160f, 38f), "Working...", panelText); if (GUI.Button(new Rect(p.xMax - 160f, by, 140f, 38f), "CLOSE", btn)) cloudPanel = -1; } private static void DrawCodePanel(float vw, float vh) { Fill(new Rect(0, 0, vw, vh), new Color(0f, 0f, 0f, 0.55f)); float pw = Mathf.Min(620f, vw - 40f), ph = 330f; Rect p = new Rect((vw - pw) * 0.5f, Mathf.Max(20f, (vh - ph) * 0.5f), pw, ph); Fill(p, new Color(0.1f, 0.1f, 0.13f, 0.99f)); Frame(p, new Color(0.96f, 0.55f, 0.16f), 2f); DrawIcon(new Rect(p.x + 18f, p.y + 14f, 60f, 40f), 60f); GUI.Label(new Rect(p.x + 90f, p.y + 14f, pw - 110f, 40f), "LOAD A SHARED SAVE", cardBig); bool locked = Cloud.Busy; int target = -1; for (int i = 1; i <= Slots.Count; i++) if (!list.Any(x => x.Slot == i)) { target = i; break; } float y = p.y + 66f; GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 48f), "Type the code a friend gave you (they get one with SHARE THIS SAVE in a slot's CLOUD panel). Their run goes into your first empty slot.", panelText); y += 58f; GUI.SetNextControlName("sharecode"); codeText = GUI.TextField(new Rect(p.x + 20f, y, 260f, 38f), codeText ?? "", 12); GUI.enabled = !locked && target > 0; if (GUI.Button(new Rect(p.x + 296f, y, 160f, 38f), locked ? "LOADING..." : "LOAD", btnSmall)) { codeMsg = "Getting the shared save..."; int sl = target; Runner.Run(Cloud.FetchShare(codeText, sl, (ok, msg) => { codeMsg = (ok ? "" : "") + msg + ""; if (ok) { codeText = ""; Refresh(); } })); } GUI.enabled = true; y += 50f; string info = target > 0 ? "It will go into " + Slots.Name(target) + "." : "All your slots are full. Delete a save or add slots (SlotCount in the config) first."; GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 28f), info, cloudSmall); y += 32f; if (!string.IsNullOrEmpty(codeMsg)) GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 40f), codeMsg, panelText); if (GUI.Button(new Rect(p.xMax - 160f, p.yMax - 54f, 140f, 38f), "CLOSE", btn)) codePanel = false; } private static void DrawCard(Rect r, int slot, SlotInfo s, SlotInfo newest) { bool empty = s == null; bool hover = r.Contains(Event.current.mousePosition); bool isCurrent = !empty && currentHash != null && s.Hash == currentHash; Fill(r, empty ? new Color(0.1f, 0.1f, 0.12f, 0.9f) : (hover ? new Color(0.2f, 0.2f, 0.25f, 0.97f) : new Color(0.14f, 0.14f, 0.18f, 0.97f))); if (!empty) DrawArt(r, s, hover); Frame(r, isCurrent ? new Color(0.56f, 0.89f, 0.56f) : (hover && !empty ? new Color(1f, 0.82f, 0.5f) : new Color(1f, 1f, 1f, 0.12f)), isCurrent ? 3f : 2f); bool autoCard = slot == Slots.AutoSlot; GUI.Label(new Rect(r.x + 14f, r.y + 8f, 150f, 28f), autoCard ? "AUTO-SAVE" : "SLOT " + slot, cardTitle); if (!empty) { if (Plugin.ShowCheatFlag.Value) CheatFlag.DrawTag(new Rect(r.x + 14f, r.y + 38f, 112f, 16f), CheatFlag.OfSlot(s)); Sprite icon = BiomeIcon(s.Layer); if (icon != null && icon.texture != null) { Rect tr = icon.textureRect; Rect uv = new Rect(tr.x / icon.texture.width, tr.y / icon.texture.height, tr.width / icon.texture.width, tr.height / icon.texture.height); GUI.DrawTextureWithTexCoords(new Rect(r.xMax - 46f, r.y + 6f, 36f, 36f), icon.texture, uv); } } Rect fl = new Rect(r.x + (r.width - 128f) * 0.5f, r.y + 46f, 128f, 128f); Floppy.Draw(fl, slot, empty); Cloud.CloudSlot rc = empty && !SaveMode ? CloudFor(slot) : null; if (rc != null) { GUI.Label(new Rect(r.x, r.y + 180f, r.width, 30f), "LAYER " + rc.Layer, cardBig); GUI.Label(new Rect(r.x + 8f, r.y + 208f, r.width - 16f, 22f), BiomeName(rc.Layer), cardText); Color oc = GUI.color; GUI.color = new Color(1f, 0.72f, 0.35f); GUI.Label(new Rect(r.x + 8f, r.y + 232f, r.width - 16f, 22f), CharName(rc.Character), cardText); GUI.color = oc; GUI.Label(new Rect(r.x + 8f, r.y + 254f, r.width - 16f, 20f), string.IsNullOrEmpty(rc.RunType) ? "Run type unknown" : "" + rc.RunType + " run", cardText); GUI.Label(new Rect(r.x + 8f, r.y + 276f, r.width - 16f, 20f), "Run time " + TimeSpan.FromSeconds(rc.RunTime).ToString().Split('.')[0], cardText); GUI.Label(new Rect(r.x + 8f, r.y + 296f, r.width - 16f, 20f), Cloud.SavedTime(rc).ToString("MMM d, HH:mm"), cardText); Badge(new Rect(r.x + 12f, r.y + 320f, r.width - 24f, 18f), "IN THE CLOUD", new Color(0.96f, 0.6f, 0.25f)); if (GUI.Button(new Rect(r.x + 12f, r.yMax - 42f, r.width - 24f, 32f), "DOWNLOAD", btn) && !Cloud.Busy) Runner.Run(Cloud.Download(slot, null, ok => Refresh())); DrawCloudRow(r, slot, null); return; } if (empty) { GUI.Label(new Rect(r.x, r.y + 196f, r.width, 30f), "EMPTY", cardBig); if (autoCard) GUI.Label(new Rect(r.x + 10f, r.y + 228f, r.width - 20f, 60f), Plugin.AutoSave.Value ? "Auto-save fills this slot during a run." : "Auto-save is off. Turn it on in the pause menu.", cardText); else if (SaveMode) { if (GUI.Button(new Rect(r.x + 12f, r.yMax - 42f, r.width - 24f, 32f), "SAVE HERE", btn)) SaveInto(slot); } else GUI.Label(new Rect(r.x + 10f, r.y + 228f, r.width - 20f, 40f), "Save during a run to fill this slot.", cardText); DrawCloudRow(r, slot, null); return; } GUI.Label(new Rect(r.x, r.y + 180f, r.width, 30f), "LAYER " + s.Layer, cardBig); GUI.Label(new Rect(r.x + 8f, r.y + 208f, r.width - 16f, 22f), BiomeName(s.Layer), cardText); Color oldC = GUI.color; GUI.color = new Color(1f, 0.72f, 0.35f); GUI.Label(new Rect(r.x + 8f, r.y + 232f, r.width - 16f, 22f), CharName(s.Character), cardText); GUI.color = oldC; GUI.Label(new Rect(r.x + 8f, r.y + 254f, r.width - 16f, 20f), string.IsNullOrEmpty(s.RunType) ? "Run type unknown" : "" + s.RunType + " run", cardText); GUI.Label(new Rect(r.x + 8f, r.y + 276f, r.width - 16f, 20f), "Run time " + TimeSpan.FromSeconds(s.RunTime).ToString().Split('.')[0], cardText); GUI.Label(new Rect(r.x + 8f, r.y + 296f, r.width - 16f, 20f), s.SavedAt.ToString("MMM d, HH:mm"), cardText); float bx = r.x + 12f, bw2 = (r.width - 24f - 8f) / 2f; Badge(new Rect(bx, r.y + 320f, bw2, 18f), s.Auto ? "AUTO-SAVE" : "MANUAL", s.Auto ? new Color(0.55f, 0.72f, 0.95f) : new Color(0.85f, 0.85f, 0.85f)); if (SaveMode && slot == currentSlot) Badge(new Rect(bx + bw2 + 8f, r.y + 320f, bw2, 18f), "CURRENT", new Color(1f, 0.82f, 0.5f)); else if (!SaveMode && isCurrent) Badge(new Rect(bx + bw2 + 8f, r.y + 320f, bw2, 18f), "CONTINUE", new Color(0.56f, 0.89f, 0.56f)); Rect lb = new Rect(r.x + 12f, r.yMax - 42f, r.width - 24f - 90f, 32f); Rect db = new Rect(lb.xMax + 6f, lb.y, 84f, 32f); if (SaveMode && autoCard) { GUI.Label(lb, "Auto-save only", cardText); } else if (SaveMode) { string label = slot == currentSlot ? "SAVE" : (confirmOverwrite == slot ? "SURE?" : "OVERWRITE"); if (GUI.Button(lb, label, btn)) { if (slot == currentSlot || confirmOverwrite == slot) SaveInto(slot); else { confirmOverwrite = slot; confirmDelete = -1; } } } else if (GUI.Button(lb, "LOAD", btn)) Load(s); if (GUI.Button(db, confirmDelete == s.Slot ? "SURE?" : "DELETE", btnDanger)) { if (confirmDelete == s.Slot) { Slots.Delete(s.Slot); confirmDelete = -1; Refresh(); } else confirmDelete = s.Slot; } DrawCloudRow(r, slot, s); } private static void DrawArt(Rect r, SlotInfo s, bool hover) { Texture2D t = LayerArt.Get(s.Art); if (t == null) return; float cardAspect = r.width / r.height; float texAspect = (float)t.width / t.height; Rect uv; if (texAspect > cardAspect) { float w = cardAspect / texAspect; uv = new Rect((1f - w) * 0.5f, 0f, w, 1f); } else { float h = texAspect / cardAspect; uv = new Rect(0f, (1f - h) * 0.5f, 1f, h); } Color old = GUI.color; GUI.color = new Color(1f, 1f, 1f, hover ? 0.75f : 0.6f); GUI.DrawTextureWithTexCoords(r, t, uv); GUI.color = old; Fill(new Rect(r.x, r.y, r.width, 44f), new Color(0.05f, 0.05f, 0.07f, 0.5f)); Fill(new Rect(r.x, r.y + 170f, r.width, r.height - 170f), new Color(0.05f, 0.05f, 0.07f, 0.62f)); } private static void SaveInto(int slot) { confirmOverwrite = -1; bool quit = quitAfter; Runner.SaveAsync(false, slot, ok => { if (ok) { Close(); if (quit && PlayerCamera.main != null) PlayerCamera.main.ToMainMenu(); } else Refresh(); }); } private static void Load(SlotInfo s) { if (!Slots.Use(s)) { Runner.Toast("That save slot couldn't be read.", true); Refresh(); return; } PreRunScript pr = Object.FindObjectOfType(); if (pr == null) { Runner.Toast((s.Slot == Slots.AutoSlot ? "The auto-save" : "Slot " + s.Slot) + " is ready, press Continue.", false); Close(); return; } StartLoad(pr, s); } internal static void StartLoad(PreRunScript pr, SlotInfo s) { Plugin.Log.LogInfo("Loading save slot " + s.Slot + "."); Traverse.Create(pr).Field("savedCharacter").SetValue(s.Character); Open = false; Loading = PlayerPrefs.GetInt("didbasiccourse") != 0; pr.LoadRun(); } } public static class Api { internal static SlotInfo PendingLoad; internal static float PendingAt; private static SlotInfo Newest() { if (MultiplayerGuard.Detected) return null; List list = Slots.LoadIndex(); string run = Slots.CurrentRun; SlotInfo s = list.Where(x => x.Run == run).OrderByDescending(x => x.SavedAt).FirstOrDefault(); return s; } public static bool HasCheckpoint() { try { return Newest() != null; } catch (Exception) { return false; } } public static bool LoadLastCheckpoint() { try { SlotInfo s = Newest(); if (s == null || !Slots.Use(s)) return false; PendingLoad = s; PendingAt = Time.realtimeSinceStartup; Plugin.Log.LogInfo("Loading the last checkpoint (slot " + s.Slot + ") from the death screen."); if (PlayerCamera.main != null) PlayerCamera.main.ToMainMenu(); else SceneManager.LoadScene("PreGen"); return true; } catch (Exception e) { Plugin.Log.LogError("Couldn't load the last checkpoint: " + e); return false; } } internal static void Tick(bool onMenu) { if (PendingLoad == null) return; if (Time.realtimeSinceStartup - PendingAt > 30f) { PendingLoad = null; return; } if (!onMenu || Time.timeSinceLevelLoad < 0.75f) return; PreRunScript pr = Object.FindObjectOfType(); if (pr == null) return; SlotInfo s = PendingLoad; PendingLoad = null; try { SlotScreen.StartLoad(pr, s); } catch (Exception e) { Plugin.Log.LogError("Checkpoint load failed: " + e); } } } internal static class SelfUpdate { private const string Server = "https://updates.smellypawz.com"; private const string FilesPage = "https://www.nexusmods.com/scavprototype/mods/885?tab=files"; internal static bool Checked; internal static string NewVersion = "", Notes = ""; private static bool available, dismissed; private static GUIStyle box, head, text, button; internal static IEnumerator Check() { Checked = true; UnityWebRequest req = UnityWebRequest.Get(Server + "/v1/latest?app=saveanywhere&have=" + Plugin.Version); req.timeout = 15; yield return req.SendWebRequest(); string body = req.responseCode == 200 && req.downloadHandler != null ? req.downloadHandler.text : null; req.Dispose(); if (body == null) yield break; try { JObject o = Cloud.Json(body); if (o["update"] == null || !(bool)o["update"]) yield break; NewVersion = (string)o["version"] ?? ""; Notes = ((string)o["notes"] ?? "").Replace("<", "").Replace(">", ""); available = true; Plugin.Log.LogInfo("Save Anywhere " + NewVersion + " is out on Nexus."); } catch (Exception e) { Plugin.Log.LogWarning("Couldn't read the update check: " + e.Message); } } private static void Styles() { if (box != null) return; Texture2D bg = new Texture2D(1, 1); bg.SetPixel(0, 0, new Color(0.08f, 0.08f, 0.1f, 0.94f)); bg.Apply(); box = new GUIStyle(GUI.skin.box); box.normal.background = bg; head = new GUIStyle(GUI.skin.label) { fontSize = 20, fontStyle = FontStyle.Bold, richText = true }; head.normal.textColor = new Color(1f, 0.82f, 0.5f); text = new GUIStyle(GUI.skin.label) { fontSize = 15, wordWrap = true, richText = true }; text.normal.textColor = new Color(0.85f, 0.85f, 0.88f); button = new GUIStyle(GUI.skin.button) { fontSize = 16, fontStyle = FontStyle.Bold }; } internal static void DrawBanner(float vw) { if (!available || dismissed) return; Styles(); float w = Mathf.Min(560f, vw - 560f); if (w < 360f) w = 360f; Rect r = new Rect((vw - w) * 0.5f, 20f, w, 126f); GUI.Box(r, GUIContent.none, box); GUI.Label(new Rect(r.x + 16f, r.y + 8f, w - 32f, 28f), "Save Anywhere " + NewVersion + " is out", head); GUI.Label(new Rect(r.x + 16f, r.y + 38f, w - 32f, 40f), Notes.Length > 0 ? Notes : "Get the new version from the Nexus page.", text); float by = r.yMax - 42f; if (GUI.Button(new Rect(r.x + 16f, by, 170f, 32f), "OPEN NEXUS", button)) Application.OpenURL(FilesPage); if (GUI.Button(new Rect(r.xMax - 106f, by, 90f, 32f), "LATER", button)) dismissed = true; } } internal static class Cloud { internal const string BaseUrl = "https://cloud.smellypawz.com"; internal static string State = ""; internal static string Message = ""; internal static bool Checking; internal static float LastCheck = -1000f; internal static bool NeedsCheck() { if (Checking) return false; return State == "" || (State == "error" && Time.unscaledTime - LastCheck > 60f); } internal static void Reset() { if (Checking) return; State = ""; Message = ""; } internal static string StatusLine() { switch (State) { case "checking": return "Connecting to the cloud..."; case "ok": return "Connected to the cloud."; case "readonly": return "" + (Message.Length > 0 ? Message : "Cloud saves are read-only for now.") + ""; case "off": return "" + (Message.Length > 0 ? Message : "Cloud saves have been switched off by the mod author.") + ""; case "error": return "Can't reach the cloud right now. Your saves on this PC still work."; case "update": return "" + UpdateText() + ""; default: return ""; } } private class Pending { public string Slot; public byte[] Data; public string Meta; } private static readonly List queue = new List(); private static bool uploading; private static string id; private static string token; private static string AccountPath { get { return Paths.Dir + "\\SaveAnywhere\\cloud.json"; } } private static void LoadAccount() { try { if (!File.Exists(AccountPath)) return; JObject o = JObject.Parse(File.ReadAllText(AccountPath)); id = (string)o["id"]; token = (string)o["token"]; if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(token)) { id = null; token = null; } } catch (Exception e) { id = null; token = null; Plugin.Log.LogWarning("Couldn't read the cloud account file: " + e.Message); } } private static void SaveAccount(string newId, string newToken) { id = newId; token = newToken; JObject o = new JObject(); o["id"] = newId; o["token"] = newToken; Directory.CreateDirectory(Paths.Dir + "\\SaveAnywhere"); File.WriteAllText(AccountPath, o.ToString(Formatting.None)); } private static void ClearAccount() { id = null; token = null; try { if (File.Exists(AccountPath)) File.Delete(AccountPath); } catch (Exception) { } } internal static string SlotName(int slot) { return slot == Slots.AutoSlot ? "auto" : slot.ToString(); } internal static void QueueUpload(int slot) { if (!Plugin.CloudEnabled.Value || State == "off" || State == "readonly" || State == "update") return; try { string path = Slots.PathOf(slot); if (!File.Exists(path)) return; byte[] data = File.ReadAllBytes(path); string name = SlotName(slot); queue.RemoveAll(p => p.Slot == name); Pending pending = new Pending(); pending.Slot = name; pending.Data = data; pending.Meta = MetaFor(slot); queue.Add(pending); if (!uploading) Runner.Run(UploadLoop()); } catch (Exception e) { Plugin.Log.LogWarning("Couldn't queue the cloud upload for " + Slots.Name(slot) + ": " + e.Message); } } internal static string MetaFor(int slot) { { SlotInfo s = Slots.LoadIndex().FirstOrDefault(x => x.Slot == slot); JObject m = new JObject(); if (s != null) { m["layer"] = s.Layer; m["character"] = s.Character; m["runType"] = s.RunType ?? ""; m["runTime"] = Mathf.RoundToInt(s.RunTime); m["savedAt"] = s.SavedAt.ToUniversalTime().ToString("o"); m["runId"] = s.Run ?? ""; } m["modVersion"] = Plugin.Version; m["gameVersion"] = Application.version; return m.ToString(Formatting.None); } } internal static IEnumerator Share(int slot, Action done) { Busy = true; byte[] data = null; string meta = null; try { string path = Slots.PathOf(slot); if (File.Exists(path)) { data = File.ReadAllBytes(path); meta = MetaFor(slot); } } catch (Exception e) { Plugin.Log.LogWarning("Couldn't read " + Slots.Name(slot) + " to share it: " + e.Message); } if (data == null) { Busy = false; done(null, null, "There's no save in this slot to share."); yield break; } yield return EnsureAccount(); if (id == null) { Busy = false; done(null, null, "Couldn't make a cloud account for this PC. Try again later."); yield break; } UnityWebRequest req = new UnityWebRequest(BaseUrl + "/v1/share", "POST"); req.uploadHandler = new UploadHandlerRaw(data); req.uploadHandler.contentType = "application/octet-stream"; req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("Authorization", "Bearer " + id + "." + token); req.SetRequestHeader("X-SA-Meta", meta); req.SetRequestHeader("X-SA-Version", Plugin.Version); req.timeout = 60; yield return req.SendWebRequest(); long code = req.responseCode; bool net = req.result == UnityWebRequest.Result.ConnectionError || code == 0; string body = req.downloadHandler != null ? req.downloadHandler.text : ""; req.Dispose(); Busy = false; if (code == 200) { try { JObject o = Json(body); string c = (string)o["code"]; DateTime exp; string until = DateTime.TryParse((string)o["expires"], out exp) ? exp.ToLocalTime().ToString("MMM d") : "a week"; Plugin.Log.LogInfo("Shared " + Slots.Name(slot) + " as " + c + "."); done(c, until, null); } catch (Exception) { done(null, null, "The cloud answered, but the code couldn't be read."); } yield break; } string why = "Sharing didn't work (HTTP " + code + ")."; if (net) why = "Couldn't reach the cloud. Check your internet and try again."; else if (code == 426) { NeedUpdate(body); why = UpdateText(); } else if (code == 503) why = "Cloud saves are switched off or read-only right now, so sharing is too."; else if (code == 415) why = "The cloud couldn't read this save, so it wasn't shared."; else if (code == 413) why = "This save is too big to share."; else if (code == 429) why = body.Contains("too_many_shares\"") ? "You already have 5 shared saves running. Old codes stop working after 7 days." : "Too many shares today. Try again tomorrow."; Plugin.Log.LogWarning("Share failed (HTTP " + code + "): " + body); done(null, null, why); } internal static string CleanCode(string raw) { StringBuilder sb = new StringBuilder(); foreach (char ch in (raw ?? "").ToUpperInvariant()) if ("ABCDEFGHJKMNPQRSTUVWXYZ23456789".IndexOf(ch) >= 0) sb.Append(ch); return sb.ToString(); } internal static IEnumerator FetchShare(string raw, int slot, Action done) { string code = CleanCode(raw); if (code.Length != 8) { done(false, "A share code has 8 letters and numbers, like K7QX-2M9P."); yield break; } Busy = true; yield return EnsureAccount(); if (id == null) { Busy = false; done(false, "Couldn't make a cloud account for this PC. Try again later."); yield break; } Resp r = new Resp(); yield return Call("GET", "/v1/share/" + code, null, r); Busy = false; if (r.Code == 200 && r.Bytes != null && r.Bytes.Length > 0) { bool ok = Slots.Import(slot, r.Bytes, r.Meta); if (ok) Plugin.Log.LogInfo("Loaded shared save " + code + " into " + Slots.Name(slot) + "."); done(ok, ok ? "The shared save is in " + Slots.Name(slot) + ". Pick it to play." : "That shared save couldn't be read."); yield break; } done(false, Friendly(r, "No shared save has that code. Check it and try again.")); } private static IEnumerator UploadLoop() { uploading = true; while (queue.Count > 0) { Pending p = queue[0]; queue.RemoveAt(0); if (id == null) LoadAccount(); if (id == null) { yield return Signup(); if (id == null) { queue.Clear(); break; } } for (int attempt = 0; attempt < 2; attempt++) { UnityWebRequest req = new UnityWebRequest(BaseUrl + "/v1/slots/" + p.Slot, "PUT"); req.uploadHandler = new UploadHandlerRaw(p.Data); req.uploadHandler.contentType = "application/octet-stream"; req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("Authorization", "Bearer " + id + "." + token); req.SetRequestHeader("X-SA-Meta", p.Meta); req.SetRequestHeader("X-SA-Version", Plugin.Version); req.timeout = 60; yield return req.SendWebRequest(); long code = req.responseCode; bool netFail = req.result == UnityWebRequest.Result.ConnectionError; string body = req.downloadHandler != null ? req.downloadHandler.text : ""; string err = req.error; req.Dispose(); if (code == 401 && attempt == 0) { Plugin.Log.LogInfo("The cloud didn't recognise this PC's account any more, making a new one."); ClearAccount(); yield return Signup(); if (id == null) break; continue; } Report(p, code, body, netFail, err); break; } } uploading = false; if (SlotScreen.Open) Runner.Run(RefreshList()); } private static IEnumerator Signup() { UnityWebRequest req = new UnityWebRequest(BaseUrl + "/v1/signup", "POST"); req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes("{}")); req.uploadHandler.contentType = "application/json"; req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("X-SA-Version", Plugin.Version); req.timeout = 20; yield return req.SendWebRequest(); long code = req.responseCode; bool netFail = req.result == UnityWebRequest.Result.ConnectionError; string body = req.downloadHandler != null ? req.downloadHandler.text : ""; string err = req.error; req.Dispose(); if (code == 200) { try { JObject o = JObject.Parse(body); SaveAccount((string)o["id"], (string)o["token"]); Plugin.Log.LogInfo("Made a cloud account for this PC."); } catch (Exception e) { Plugin.Log.LogWarning("Couldn't store the new cloud account: " + e.Message); } yield break; } if (netFail || code == 0) { NetError(err); yield break; } if (code == 503) { Disabled(body); yield break; } if (code == 426) { NeedUpdate(body); yield break; } Plugin.Log.LogWarning("Couldn't make a cloud account (HTTP " + code + "): " + body); Runner.CloudToast(code == 429 ? "Cloud: couldn't make your cloud account right now. It'll try again later." : "Cloud: couldn't make your cloud account. See BepInEx\\LogOutput.log.", true); } internal static string MinVersion = ""; internal static int VersionNum(string v) { try { string[] p = (v ?? "").Trim().Split('.'); if (p.Length != 3) return -1; return int.Parse(p[0]) * 1000000 + int.Parse(p[1]) * 1000 + int.Parse(p[2]); } catch (Exception) { return -1; } } internal static string UpdateText() { return "Cloud saves need Save Anywhere " + (MinVersion.Length > 0 ? MinVersion : "a newer version") + " or newer. Update the mod from Nexus. Your saves on this PC still work."; } private static void NeedUpdate(string body) { try { string v = (string)JObject.Parse(body)["minVersion"]; if (VersionNum(v) > 0) MinVersion = v; } catch (Exception) { } bool first = State != "update"; State = "update"; queue.Clear(); if (first) { Plugin.Log.LogWarning("The Save Anywhere cloud needs a newer version of the mod (" + (MinVersion.Length > 0 ? MinVersion : "?") + ", this is " + Plugin.Version + ")."); Runner.CloudToast("Cloud: update Save Anywhere to keep using cloud saves.", true); } } private static string ErrorOf(string body) { try { return (string)JObject.Parse(body)["error"] ?? ""; } catch (Exception) { return ""; } } private static void NetError(string err) { State = "error"; LastCheck = Time.unscaledTime; Plugin.Log.LogWarning("Couldn't reach the Save Anywhere cloud: " + err); Runner.CloudToast("Couldn't reach the cloud. Your save is safe on this PC.", true); } private static void Disabled(string body) { try { JObject o = JObject.Parse(body); string mode = (string)o["mode"] ?? "off"; Message = ((string)o["message"] ?? "").Replace("<", "").Replace(">", ""); State = mode == "readonly" ? "readonly" : "off"; } catch (Exception) { State = "off"; } queue.Clear(); Plugin.Log.LogInfo("The Save Anywhere cloud is " + State + (Message.Length > 0 ? ": " + Message : ".")); Runner.CloudToast(Message.Length > 0 ? Message : "Cloud saves are switched off right now. Your save is safe on this PC.", true); } private static void Report(Pending p, long code, string body, bool netFail, string err) { string what = p.Slot == "auto" ? "the auto-save" : "slot " + p.Slot; if (code == 200) { State = "ok"; Plugin.Log.LogInfo("Uploaded " + what + " to the cloud (" + (p.Data.Length / 1024) + " KB)."); Runner.CloudToast("Uploaded to the cloud", false); return; } if (netFail || code == 0) { NetError(err); return; } if (code == 503) { Disabled(body); return; } if (code == 426) { NeedUpdate(body); return; } string e = ErrorOf(body); Plugin.Log.LogWarning("Cloud upload of " + what + " failed (HTTP " + code + ", " + e + ")."); string msg; if (e == "account_full") msg = "Cloud: your cloud storage is full. Delete some cloud saves to upload more."; else if (e == "cloud_full") msg = "Cloud: the cloud server is full right now. Your save is safe on this PC."; else if (code == 429) msg = "Cloud: too many uploads right now. It'll upload again with your next save."; else if (code == 403) msg = "Cloud: this cloud account is blocked."; else msg = "Cloud: the upload didn't work. Your save is safe on this PC."; Runner.CloudToast(msg, true); } internal class Resp { public long Code; public bool Net; public string Text = ""; public byte[] Bytes; public string Meta; public string Error; } internal class CloudSlot { public int Slot; public string Version; public DateTime Uploaded; public int Layer; public int Character; public string RunType; public float RunTime; public string SavedAt; public string RunId; public int Versions = 1; } internal static readonly Dictionary Remote = new Dictionary(); internal static string ListState = ""; internal static readonly List Versions = new List(); internal static string VersionsState = ""; internal static bool Busy; private static Texture2D icon; internal static Texture2D Icon { get { if (icon != null) return icon; try { using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("SaveAnywhere.cloudflare.png")) { if (s != null) { byte[] b = new byte[s.Length]; s.Read(b, 0, b.Length); Texture2D t = new Texture2D(2, 2, TextureFormat.RGBA32, false); if (t.LoadImage(b)) { t.filterMode = FilterMode.Bilinear; icon = t; return icon; } } } } catch (Exception e) { Plugin.Log.LogWarning("Couldn't load the cloud icon: " + e.Message); } string[] rows = { ".....####.......", "....######.###..", "...###########..", ".##############.", "################", "################", "################", ".##############." }; Texture2D p = new Texture2D(16, rows.Length, TextureFormat.RGBA32, false); p.filterMode = FilterMode.Point; Color clear = new Color(0f, 0f, 0f, 0f); for (int y = 0; y < rows.Length; y++) for (int x = 0; x < 16; x++) p.SetPixel(x, rows.Length - 1 - y, rows[y][x] == '#' ? (y >= rows.Length - 2 ? new Color(0.86f, 0.42f, 0.1f) : new Color(0.96f, 0.55f, 0.16f)) : clear); p.Apply(); icon = p; return icon; } } internal static JObject Json(string text) { using (JsonTextReader reader = new JsonTextReader(new StringReader(text))) { reader.DateParseHandling = DateParseHandling.None; return JObject.Load(reader); } } internal static int SlotNum(string name) { if (name == "auto") return Slots.AutoSlot; int n; return int.TryParse(name, out n) ? n : -1; } private static int Int(JToken t) { if (t == null) return 0; int n; return int.TryParse(t.ToString(), out n) ? n : 0; } private static CloudSlot ParseSlot(JToken o) { CloudSlot c = new CloudSlot(); c.Slot = SlotNum((string)o["slot"]); c.Version = (string)o["version"]; DateTime up; c.Uploaded = DateTime.TryParse((string)o["uploaded"], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out up) ? up.ToLocalTime() : DateTime.MinValue; JToken m = o["meta"] ?? new JObject(); c.Layer = Int(m["layer"]); c.Character = Int(m["character"]); c.RunType = (string)m["runType"]; c.RunTime = Int(m["runTime"]); c.SavedAt = (string)m["savedAt"]; c.RunId = (string)m["runId"]; if (o["versions"] != null) c.Versions = Int(o["versions"]); return c; } internal static DateTime SavedTime(CloudSlot c) { DateTime d; if (c.SavedAt != null && DateTime.TryParse(c.SavedAt, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out d)) return d.ToLocalTime(); return c.Uploaded; } internal static string SavedKey(SlotInfo s) { return s.SavedAt.ToUniversalTime().ToString("o"); } internal static bool Same(SlotInfo s, CloudSlot c) { return s != null && c != null && c.SavedAt == SavedKey(s); } private static IEnumerator Call(string method, string path, byte[] body, Resp into) { UnityWebRequest req = new UnityWebRequest(BaseUrl + path, method); if (body != null) { req.uploadHandler = new UploadHandlerRaw(body); req.uploadHandler.contentType = "application/json"; } req.downloadHandler = new DownloadHandlerBuffer(); if (id != null) req.SetRequestHeader("Authorization", "Bearer " + id + "." + token); req.SetRequestHeader("X-SA-Version", Plugin.Version); req.timeout = 60; yield return req.SendWebRequest(); into.Code = req.responseCode; if (into.Code == 426) NeedUpdate(req.downloadHandler != null ? req.downloadHandler.text : ""); into.Net = req.result == UnityWebRequest.Result.ConnectionError || req.responseCode == 0; into.Error = req.error; into.Bytes = req.downloadHandler != null ? req.downloadHandler.data : null; string ct = req.GetResponseHeader("Content-Type") ?? ""; into.Text = ct.Contains("json") && into.Bytes != null ? Encoding.UTF8.GetString(into.Bytes) : ""; into.Meta = req.GetResponseHeader("X-SA-Meta"); req.Dispose(); } private static void NoteDisabled(Resp r) { try { JObject o = Cloud.Json(r.Text); string mode = (string)o["mode"] ?? "off"; Message = ((string)o["message"] ?? "").Replace("<", "").Replace(">", ""); State = mode == "readonly" ? "readonly" : "off"; } catch (Exception) { State = "off"; } } internal static IEnumerator RefreshList() { if (!Plugin.CloudEnabled.Value) { Remote.Clear(); ListState = ""; yield break; } if (id == null) LoadAccount(); if (id == null) { Remote.Clear(); ListState = "ok"; yield break; } ListState = "loading"; Resp r = new Resp(); yield return Call("GET", "/v1/slots", null, r); if (r.Code == 200) { Remote.Clear(); try { foreach (JToken o in (JArray)Cloud.Json(r.Text)["slots"]) { CloudSlot c = ParseSlot(o); if (c.Slot > 0) Remote[c.Slot] = c; } ListState = "ok"; } catch (Exception e) { ListState = "error"; Plugin.Log.LogWarning("Couldn't read the cloud slot list: " + e.Message); } yield break; } if (r.Code == 503) NoteDisabled(r); ListState = "error"; if (r.Net) { State = "error"; LastCheck = Time.unscaledTime; } Plugin.Log.LogWarning("Couldn't list cloud saves (HTTP " + r.Code + ")."); } internal static IEnumerator FetchVersions(int slot) { Versions.Clear(); if (id == null) LoadAccount(); if (id == null) { VersionsState = "ok"; yield break; } VersionsState = "loading"; Resp r = new Resp(); yield return Call("GET", "/v1/slots/" + SlotName(slot) + "/versions", null, r); if (r.Code != 200) { if (r.Code == 503) NoteDisabled(r); VersionsState = "error"; yield break; } try { foreach (JToken o in (JArray)Cloud.Json(r.Text)["versions"]) Versions.Add(ParseSlot(o)); VersionsState = "ok"; } catch (Exception) { VersionsState = "error"; } } internal static IEnumerator Download(int slot, string version, Action done) { Busy = true; if (id == null) LoadAccount(); Resp r = new Resp(); yield return Call("GET", "/v1/slots/" + SlotName(slot) + (version != null ? "/versions/" + version : ""), null, r); bool ok = false; if (r.Code == 200 && r.Bytes != null) { ok = Slots.Import(slot, r.Bytes, r.Meta); if (ok) Plugin.Log.LogInfo("Downloaded " + Slots.Name(slot) + " from the cloud (" + (r.Bytes.Length / 1024) + " KB)."); Runner.Toast(ok ? "Downloaded " + Slots.Name(slot) + " from the cloud." : "That cloud save couldn't be read.", !ok); } else { if (r.Code == 503) NoteDisabled(r); Plugin.Log.LogWarning("Cloud download failed (HTTP " + r.Code + ", " + r.Error + ")."); Runner.Toast(r.Net ? "Couldn't reach the cloud." : (r.Code == 503 && Message.Length > 0 ? Message : "The download didn't work."), true); } Busy = false; if (done != null) done(ok); } internal static IEnumerator DeleteRemote(int slot, Action done) { Busy = true; if (id == null) LoadAccount(); if (id != null) { Resp r = new Resp(); yield return Call("DELETE", "/v1/slots/" + SlotName(slot), null, r); if (r.Code == 200) Plugin.Log.LogInfo("Deleted " + Slots.Name(slot) + " from the cloud."); else Plugin.Log.LogWarning("Couldn't delete " + Slots.Name(slot) + " from the cloud (HTTP " + r.Code + ")."); } Busy = false; if (done != null) done(); } internal static void DeleteForRun(string run, int onlySlot) { if (!Plugin.CloudEnabled.Value || string.IsNullOrEmpty(run)) return; Runner.Run(DeleteForRunRoutine(run, onlySlot)); } private static IEnumerator DeleteForRunRoutine(string run, int onlySlot) { if (id == null) LoadAccount(); if (id == null) yield break; Resp r = new Resp(); yield return Call("GET", "/v1/slots", null, r); if (r.Code != 200) yield break; List hit = new List(); try { foreach (JToken o in (JArray)Cloud.Json(r.Text)["slots"]) { CloudSlot c = ParseSlot(o); if (c.Slot > 0 && c.RunId == run && (onlySlot <= 0 || c.Slot == onlySlot)) hit.Add(c.Slot); } } catch (Exception) { yield break; } foreach (int s in hit) { Resp d = new Resp(); yield return Call("DELETE", "/v1/slots/" + SlotName(s), null, d); if (d.Code == 200) { Remote.Remove(s); Plugin.Log.LogInfo("Deleted " + Slots.Name(s) + " from the cloud too."); } } } internal static bool HasAccount() { if (id == null) LoadAccount(); return id != null; } private static IEnumerator EnsureAccount() { if (id == null) LoadAccount(); if (id == null) yield return Signup(); } internal static string Friendly(Resp r, string notFound) { if (r.Net) return "Couldn't reach the cloud. Check your internet and try again."; if (r.Code == 503) { NoteDisabled(r); return Message.Length > 0 ? Message : "Cloud saves are switched off right now."; } if (r.Code == 426) return UpdateText(); if (r.Code == 429) return "Too many tries. Wait a little and try again."; if (r.Code == 404 || r.Code == 400) return notFound; if (r.Code == 410) return "That code has expired. Get a new one."; if (r.Code == 403) return "This cloud account is blocked."; if (r.Code == 401) return "This PC isn't signed in to the cloud any more. Save once to make a new cloud account."; return "Something went wrong (HTTP " + r.Code + ")."; } private static byte[] Body(JObject o) { return Encoding.UTF8.GetBytes(o.ToString(Formatting.None)); } internal static IEnumerator GetUsage(Action done) { if (!HasAccount()) { done("No cloud account yet. It's made the first time you save with cloud saves on."); yield break; } Resp r = new Resp(); yield return Call("GET", "/v1/usage", null, r); if (r.Code != 200) { done(Friendly(r, "Couldn't read your cloud usage.")); yield break; } try { JObject o = Json(r.Text); double used = (double)o["bytes"] / 1048576.0, max = (double)o["maxBytes"] / 1048576.0; done(string.Format("Using {0:0.0} MB of {1:0} MB. {2} of {3} devices linked.", used, max, (int)o["devices"], (int)o["maxDevices"])); } catch (Exception) { done("Couldn't read your cloud usage."); } } internal static IEnumerator GetLinkCode(Action done) { yield return EnsureAccount(); if (id == null) { done(null, "Couldn't make your cloud account. Try again later."); yield break; } Resp r = new Resp(); yield return Call("POST", "/v1/link-code", Body(new JObject()), r); if (r.Code != 200) { done(null, Friendly(r, "Couldn't make a link code.")); yield break; } try { done((string)Json(r.Text)["code"], null); } catch (Exception) { done(null, "Couldn't read the link code."); } } internal static IEnumerator UseLinkCode(string code, Action done) { JObject b = new JObject(); b["code"] = code ?? ""; Resp r = new Resp(); yield return Call("POST", "/v1/link", Body(b), r); if (r.Code != 200) { done(false, Friendly(r, "That code didn't work. Check it and try again.")); yield break; } Adopt(r.Text); done(true, "Linked! This PC now uses the same cloud saves as your other device."); } internal static IEnumerator MakeRecoveryKey(Action done) { yield return EnsureAccount(); if (id == null) { done(null, "Couldn't make your cloud account. Try again later."); yield break; } Resp r = new Resp(); yield return Call("POST", "/v1/recovery-key", Body(new JObject()), r); if (r.Code != 200) { done(null, Friendly(r, "Couldn't make a recovery key.")); yield break; } try { done((string)Json(r.Text)["recoveryKey"], null); } catch (Exception) { done(null, "Couldn't read the recovery key."); } } internal static IEnumerator UseRecoveryKey(string key, bool signOutOthers, Action done) { JObject b = new JObject(); b["recoveryKey"] = key ?? ""; b["signOutOthers"] = signOutOthers; Resp r = new Resp(); yield return Call("POST", "/v1/recover", Body(b), r); if (r.Code != 200) { done(false, Friendly(r, "That recovery key didn't work. Check it and try again.")); yield break; } Adopt(r.Text); done(true, signOutOthers ? "Recovered! Every other device has been signed out." : "Recovered! This PC has your cloud saves again."); } private static void Adopt(string text) { JObject o = Json(text); SaveAccount((string)o["id"], (string)o["token"]); Remote.Clear(); ListState = ""; State = ""; Plugin.Log.LogInfo("This PC is now linked to a cloud account."); } internal static IEnumerator LogoutOthers(Action done) { if (!HasAccount()) { done(false, "No cloud account yet."); yield break; } Resp r = new Resp(); yield return Call("POST", "/v1/logout-others", Body(new JObject()), r); if (r.Code != 200) { done(false, Friendly(r, "Couldn't sign out your other devices.")); yield break; } done(true, "Every other device has been signed out. Only this PC can use your cloud saves now."); } internal static IEnumerator DeleteAccount(Action done) { if (!HasAccount()) { done(true, "There's no cloud data for this PC."); yield break; } Resp r = new Resp(); yield return Call("DELETE", "/v1/account", null, r); if (r.Code != 200 && r.Code != 401) { done(false, Friendly(r, "Couldn't delete your cloud data.")); yield break; } ClearAccount(); Remote.Clear(); ListState = ""; queue.Clear(); Plugin.Log.LogInfo("Deleted this PC's cloud account and all its cloud saves."); done(true, "All your cloud saves and your cloud account have been deleted. Cloud saves are now off."); } internal static string InactiveNote = ""; private static bool accountChecked; internal static IEnumerator CheckStatus() { Checking = true; State = "checking"; using (UnityWebRequest req = UnityWebRequest.Get(BaseUrl + "/v1/health")) { req.SetRequestHeader("X-SA-Version", Plugin.Version); req.timeout = 10; yield return req.SendWebRequest(); Finish(req); } LastCheck = Time.unscaledTime; Checking = false; if (!accountChecked && (State == "ok" || State == "readonly") && HasAccount()) { accountChecked = true; yield return CheckAccount(); } } private static IEnumerator CheckAccount() { Resp r = new Resp(); yield return Call("GET", "/v1/me", null, r); if (r.Code != 200) yield break; try { JObject o = Json(r.Text); if (!(bool)o["warn"]) yield break; int idle = (int)o["idleDays"]; int del = (int)o["deleteAfterDays"]; InactiveNote = "Your cloud account hadn't been used for " + idle + " days.\n\nCloud accounts that go " + del + " days without being used are deleted automatically, together with ALL their cloud saves and old copies. Deleted accounts can't be brought back, not even with a recovery key.\n\nYour account is active again now. To keep it, play with cloud saves on at least once every " + del + " days. Your saves on this PC are never deleted."; Plugin.Log.LogInfo("The cloud account had been unused for " + idle + " days. Showed the inactivity warning."); } catch (Exception) { } } private static void Finish(UnityWebRequest req) { if (req.result != UnityWebRequest.Result.Success) { State = "error"; Plugin.Log.LogWarning("Couldn't reach the Save Anywhere cloud: " + req.error); return; } try { JObject o = JObject.Parse(req.downloadHandler.text); string mode = (string)o["cloud"] ?? "on"; Message = ((string)o["message"] ?? "").Replace("<", "").Replace(">", ""); State = mode == "readonly" ? "readonly" : mode == "off" ? "off" : "ok"; string mv = (string)o["minVersion"]; if (State != "off" && VersionNum(mv) > 0 && VersionNum(Plugin.Version) < VersionNum(mv)) { MinVersion = mv; State = "update"; Plugin.Log.LogWarning("The Save Anywhere cloud needs version " + mv + " or newer (this is " + Plugin.Version + ")."); return; } Plugin.Log.LogInfo("Save Anywhere cloud: " + mode + (Message.Length > 0 ? " (" + Message + ")" : "") + "."); } catch (Exception e) { State = "error"; Plugin.Log.LogWarning("The Save Anywhere cloud sent an answer the mod didn't understand: " + e.Message); } } } internal class Runner : MonoBehaviour { private static Runner instance; private bool cloudPromptOpen; private bool mpHandled; private bool mpPopupOpen; private float nextNetCheck; internal static bool JustRestored; private static float autoTimer; private static float layerSaveIn = -1f; private static float nextAutoTry; private static bool layerSaveDue; private static bool wasGenerating; internal static void ResetAuto() { autoTimer = 0f; layerSaveIn = -1f; layerSaveDue = false; } private void AutoTick() { if (!InRun()) { wasGenerating = false; return; } WorldGeneration w = WorldGeneration.world; bool gen = w.generatingWorld || Loader.Restoring; if (wasGenerating && !gen) { if (JustRestored) JustRestored = false; else layerSaveIn = 10f; } wasGenerating = gen; if (gen || PauseHandler.paused || !Plugin.AutoSave.Value) return; float dt = Time.deltaTime; autoTimer += dt; bool due = autoTimer >= Mathf.Max(1f, Plugin.AutoSaveMinutes.Value) * 60f; if (layerSaveIn >= 0f) { layerSaveIn -= dt; if (layerSaveIn <= 0f) { layerSaveIn = -1f; layerSaveDue = Plugin.AutoSaveOnNewLayer.Value; } } if (layerSaveDue) due = true; if (!due || Time.unscaledTime < nextAutoTry) return; nextAutoTry = Time.unscaledTime + 2f; SaveAsync(true, 0, null); } internal static bool Saving; internal static void Guard(string what, Action a) { Plugin.Log.LogInfo(what + " clicked."); try { a(); } catch (Exception e) { Plugin.Log.LogError(what + " failed (game version " + Application.version + "): " + e); Toast("Save Anywhere error, please send BepInEx\\LogOutput.log.", true); } } internal static void SaveAsync(bool auto, int slot, Action done) { if (Saving || instance == null) return; int target; try { target = Saver.Precheck(auto, slot); } catch (Exception e) { Plugin.Log.LogError("Save check failed (game version " + Application.version + "): " + e); if (!auto) Toast("Save Anywhere error, please send BepInEx\\LogOutput.log.", true); Saving = false; return; } if (target <= 0) { if (done != null) done(false); return; } instance.StartCoroutine(instance.SaveRoutine(auto, target, done)); } private IEnumerator SaveRoutine(bool auto, int target, Action done) { Saving = true; float start = Time.realtimeSinceStartup; ShowPill(auto ? "Auto-saving..." : "Saving...", PillKind.Saving, 60f, true); yield return null; yield return new WaitForEndOfFrame(); bool ok = false; string why; try { why = InRun() ? Safety.Check() : "you're not in a run"; } catch (Exception e) { Plugin.Log.LogError("Save check failed (game version " + Application.version + "): " + e); why = "an error happened, please send BepInEx\\LogOutput.log"; } if (why != null) { if (auto) pillText = null; else Toast("Can't save: " + why + ".", true); } else ok = Saver.Write(auto, target); if (ok) { while (Time.realtimeSinceStartup < start + 0.9f) yield return null; ShowPill(target == Slots.AutoSlot ? "Auto-saved" : (auto ? "Auto-saved" : "Saved") + " to slot " + target, PillKind.Saved, Mathf.Max(1f, start + 3f - Time.realtimeSinceStartup), false); Cloud.QueueUpload(target); } Saving = false; if (done != null) { try { done(ok); } catch (Exception e) { Plugin.Log.LogError("After-save step failed: " + e); } } } private enum PillKind { Info, Bad, Saving, Saved } private static string pillText; private static PillKind pillKind; private static float pillStart, pillUntil; private static Texture2D dotTex; private GUIStyle pillStyle; private static void ShowPill(string text, PillKind kind, float duration, bool fadeIn) { float now = Time.realtimeSinceStartup; bool visible = pillText != null && now < pillUntil; pillText = text; pillKind = kind; pillUntil = now + duration; if (fadeIn || !visible) pillStart = now; } private static Texture2D Dot { get { if (dotTex != null) return dotTex; const int n = 128; dotTex = new Texture2D(n, n, TextureFormat.RGBA32, false); dotTex.hideFlags = HideFlags.HideAndDontSave; dotTex.wrapMode = TextureWrapMode.Clamp; dotTex.filterMode = FilterMode.Bilinear; Color[] px = new Color[n * n]; float c = (n - 1) * 0.5f, rad = n * 0.5f - 1f; for (int y = 0; y < n; y++) for (int x = 0; x < n; x++) { float d = Mathf.Sqrt((x - c) * (x - c) + (y - c) * (y - c)); px[y * n + x] = new Color(1f, 1f, 1f, Mathf.Clamp01(rad - d + 0.5f)); } dotTex.SetPixels(px); dotTex.Apply(); return dotTex; } } private static void FillPill(Rect r, Color c) { float h = r.height, half = h * 0.5f; GUI.color = c; GUI.DrawTextureWithTexCoords(new Rect(r.x, r.y, half, h), Dot, new Rect(0f, 0f, 0.5f, 1f)); GUI.DrawTextureWithTexCoords(new Rect(r.xMax - half, r.y, half, h), Dot, new Rect(0.5f, 0f, 0.5f, 1f)); GUI.DrawTexture(new Rect(r.x + half, r.y, r.width - h, h), Texture2D.whiteTexture); } private static void DrawSpinner(Rect r, Color c, float alpha) { const int dots = 8; int head = (int)(Time.realtimeSinceStartup * 12f) % dots; Vector2 center = r.center; float ring = r.width * 0.37f, big = r.width * 0.27f; for (int i = 0; i < dots; i++) { int age = (head - i + dots) % dots; float t = age / (float)(dots - 1); float ang = -Mathf.PI * 0.5f + i * Mathf.PI * 2f / dots; float d = Mathf.Lerp(big, big * 0.5f, t); Vector2 p = center + new Vector2(Mathf.Cos(ang), Mathf.Sin(ang)) * ring; GUI.color = new Color(c.r, c.g, c.b, Mathf.Lerp(1f, 0.15f, t) * alpha); GUI.DrawTexture(new Rect(p.x - d * 0.5f, p.y - d * 0.5f, d, d), Dot); } } internal static string AutoLabel() { return Plugin.AutoSave.Value ? "Auto-save: ON (" + Mathf.Max(1f, Plugin.AutoSaveMinutes.Value).ToString("0.#") + " min)" : "Auto-save: OFF"; } internal static void ClickSave() { Guard("Save button", () => { string why = Safety.Check(); if (why != null) Toast("Can't save: " + why + ".", true); else SlotScreen.OpenForSave(false); }); } internal static void ClickSaveQuit() { Guard("Save & Quit button", () => { string why = Safety.Check(); if (why != null) Toast("Can't save: " + why + ".", true); else if (Slots.PickManualSlot() > 0) SaveAsync(false, 0, ok => { if (ok && PlayerCamera.main != null) PlayerCamera.main.ToMainMenu(); }); else SlotScreen.OpenForSave(true); }); } internal static void ClickAuto() { Guard("Auto-save button", () => { Plugin.AutoSave.Value = !Plugin.AutoSave.Value; ResetAuto(); Toast(Plugin.AutoSave.Value ? "Auto-save turned on." : "Auto-save turned off.", false); }); } private void DrawPill(float vw, bool high) { float now = Time.realtimeSinceStartup; if (pillText == null || now >= pillUntil) return; if (pillStyle == null) { pillStyle = new GUIStyle(GUI.skin.label) { fontSize = 18, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft, wordWrap = false, richText = false }; pillStyle.padding = new RectOffset(0, 0, 0, 0); } float a = Mathf.Clamp01((now - pillStart) / 0.15f) * Mathf.Clamp01((pillUntil - now) / 0.35f); bool bad = pillKind == PillKind.Bad; bool hasIcon = pillKind == PillKind.Saving || pillKind == PillKind.Saved; Color bg = bad ? new Color(0.84f, 0.26f, 0.21f) : new Color(1f, 0.58f, 0.13f); Color fg = bad ? Color.white : new Color(0.16f, 0.08f, 0.01f); Vector2 ts = pillStyle.CalcSize(new GUIContent(pillText)); float h = 46f, pad = 22f, icon = 26f, gap = 11f; float w = Mathf.Min(vw - 32f, pad * 2f + ts.x + (hasIcon ? icon + gap : 0f)); float y = (high ? 6f : 74f) - (1f - Mathf.Clamp01((now - pillStart) / 0.2f)) * 8f; Rect r = new Rect((vw - w) * 0.5f, y, w, h); Color old = GUI.color; FillPill(new Rect(r.x, r.y + 3f, r.width, r.height), new Color(0f, 0f, 0f, 0.35f * a)); FillPill(r, new Color(bg.r, bg.g, bg.b, 0.97f * a)); FillPill(new Rect(r.x + 3f, r.y + 2f, r.width - 6f, r.height * 0.45f), new Color(1f, 1f, 1f, 0.13f * a)); float x = r.x + pad; Rect ir = new Rect(x, r.center.y - icon * 0.5f, icon, icon); if (hasIcon) DrawSpinner(ir, fg, a); if (hasIcon) x += icon + gap; GUI.color = new Color(1f, 1f, 1f, a); pillStyle.normal.textColor = fg; GUI.Label(new Rect(x, r.y, r.xMax - pad - x + 2f, h), pillText, pillStyle); GUI.color = old; } private GameObject clickBlocker; private Rect cloudRect; private GUIStyle smallStyle; private GUIStyle titleStyle, bodyStyle, toastStyle, toastBadStyle, btnStyle; internal static void Ensure() { if (instance != null) return; GameObject go = new GameObject("SaveAnywhereRunner"); go.hideFlags = HideFlags.HideAndDontSave; DontDestroyOnLoad(go); instance = go.AddComponent(); } internal static void Run(IEnumerator routine) { if (instance != null) instance.StartCoroutine(routine); } internal static void CloudToast(string text, bool bad) { if (instance != null) instance.StartCoroutine(instance.CloudToastRoutine(text, bad)); } private IEnumerator CloudToastRoutine(string text, bool bad) { float until = Time.realtimeSinceStartup + 5f; while (pillText != null && Time.realtimeSinceStartup < pillUntil && Time.realtimeSinceStartup < until) yield return null; ShowPill(text, bad ? PillKind.Bad : PillKind.Info, bad ? 4f : 2.5f, true); } internal static void Toast(string text, bool bad) { ShowPill(text, bad ? PillKind.Bad : PillKind.Info, 3.5f, true); } private static bool InRun() { return PlayerCamera.main != null && PlayerCamera.main.body != null && WorldGeneration.world != null; } private static bool OnMainMenu() { return SceneManager.GetActiveScene().name == "PreGen"; } private bool cuPopup; private bool onMenu; private bool CloudVisible() { return !MultiplayerGuard.Detected && onMenu && !cuPopup && (!Plugin.CloudAsked.Value || cloudPromptOpen); } private bool MpVisible() { return MultiplayerGuard.Detected && mpPopupOpen && !cuPopup; } private bool SlotsAvailable() { return !MultiplayerGuard.Detected && onMenu && !cuPopup && !CloudVisible() && !SettingsVisible() && !InactiveVisible() && !SlotScreen.Loading; } private void Update() { try { LayerArt.Tick(); } catch (Exception e) { Plugin.Log.LogWarning("Layer art capture failed: " + e.Message); } cuPopup = GameObject.Find("CUCheatsClickBlocker") != null; bool menuNow = OnMainMenu(); if (menuNow && !onMenu) SlotScreen.Close(); onMenu = menuNow; Api.Tick(onMenu); if (!mpHandled) { bool hit = MultiplayerGuard.Detected; if (!hit && Time.unscaledTime >= nextNetCheck) { nextNetCheck = Time.unscaledTime + 3f; hit = MultiplayerGuard.Check(); } if (hit) { mpHandled = true; mpPopupOpen = true; } } if (MultiplayerGuard.Detected) { PauseRing.Refresh(); BlockGameUI(MpVisible()); return; } if (SlotScreen.Open && SlotScreen.SaveMode && (!InRun() || !PauseHandler.paused)) SlotScreen.Close(); if (InRun() && !SlotScreen.Open && Plugin.SaveKey.Value.IsDown()) { Plugin.Log.LogInfo("Save key pressed."); if (Slots.PickManualSlot() > 0) SaveAsync(false, 0, null); else Toast("Pick a slot first: pause and click Save.", true); } AutoTick(); if (onMenu && Plugin.CloudEnabled.Value && Cloud.NeedsCheck()) StartCoroutine(Cloud.CheckStatus()); PauseRing.Refresh(); if (settingsOpen && !onMenu) settingsOpen = false; BlockGameUI(CloudVisible() || SettingsVisible() || InactiveVisible() || (SlotScreen.Open && (SlotScreen.SaveMode || SlotsAvailable()))); } private static int blockFrame = -100; internal static bool UiBlocking { get { return Time.frameCount - blockFrame <= 2; } } private void BlockGameUI(bool block) { if (block) blockFrame = Time.frameCount; else blockFrame = -100; if (block && clickBlocker == null) { clickBlocker = new GameObject("SaveAnywhereClickBlocker"); DontDestroyOnLoad(clickBlocker); Canvas canvas = clickBlocker.AddComponent(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.sortingOrder = 32766; clickBlocker.AddComponent(); GameObject panel = new GameObject("Blocker"); panel.transform.SetParent(clickBlocker.transform, false); UnityEngine.UI.Image img = panel.AddComponent(); img.color = new Color(0f, 0f, 0f, 0f); img.raycastTarget = true; RectTransform rt = img.rectTransform; rt.anchorMin = Vector2.zero; rt.anchorMax = Vector2.one; rt.offsetMin = Vector2.zero; rt.offsetMax = Vector2.zero; MuteSceneInput(); } else if (!block && clickBlocker != null) { Destroy(clickBlocker); clickBlocker = null; RestoreSceneInput(); } else if (block && Time.frameCount % 30 == 0) { MuteSceneInput(); } } private readonly List mutedRaycasters = new List(); private readonly Dictionary mutedCameras = new Dictionary(); private void MuteSceneInput() { foreach (UnityEngine.EventSystems.BaseRaycaster r in FindObjectsOfType()) { if (r == null || !r.enabled) continue; if (clickBlocker != null && r.gameObject == clickBlocker) continue; if (r.gameObject.name == "CUCheatsClickBlocker") continue; r.enabled = false; mutedRaycasters.Add(r); } foreach (Camera c in Camera.allCameras) { if (c == null || mutedCameras.ContainsKey(c)) continue; mutedCameras[c] = c.eventMask; c.eventMask = 0; } } private void RestoreSceneInput() { foreach (UnityEngine.EventSystems.BaseRaycaster r in mutedRaycasters) if (r != null) r.enabled = true; mutedRaycasters.Clear(); foreach (KeyValuePair kv in mutedCameras) if (kv.Key != null) kv.Key.eventMask = kv.Value; mutedCameras.Clear(); } private void Styles() { if (titleStyle != null) return; titleStyle = new GUIStyle(GUI.skin.label) { fontSize = 22, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter, wordWrap = true }; titleStyle.normal.textColor = new Color(1f, 0.75f, 0.2f); bodyStyle = new GUIStyle(GUI.skin.label) { fontSize = 16, alignment = TextAnchor.UpperCenter, wordWrap = true, richText = true }; bodyStyle.normal.textColor = Color.white; btnStyle = new GUIStyle(GUI.skin.button) { fontSize = 16, fontStyle = FontStyle.Bold }; toastStyle = new GUIStyle(GUI.skin.box) { fontSize = 18, alignment = TextAnchor.MiddleCenter, wordWrap = true }; toastStyle.normal.textColor = new Color(0.6f, 1f, 0.6f); toastBadStyle = new GUIStyle(toastStyle); toastBadStyle.normal.textColor = new Color(1f, 0.55f, 0.5f); } private void OnGUI() { Styles(); float s = Mathf.Max(0.75f, Screen.height / 1080f); Matrix4x4 old = GUI.matrix; GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(s, s, 1f)); float vw = Screen.width / s, vh = Screen.height / s; if (MultiplayerGuard.Detected) { if (MpVisible()) { GUI.color = new Color(0f, 0f, 0f, 0.75f); GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture); GUI.color = Color.white; float mw = 640f; Rect mr = new Rect((vw - mw) * 0.5f, vh * 0.5f - 220f, mw, 0f); GUILayout.Window(0x5A5E02, mr, DrawMultiplayer, "Save Anywhere - Multiplayer detected"); GUI.FocusWindow(0x5A5E02); } GUI.matrix = old; return; } if (CloudVisible()) { GUI.color = new Color(0f, 0f, 0f, 0.6f); GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture); GUI.color = Color.white; float w = 680f; cloudRect = new Rect((vw - w) * 0.5f, vh * 0.5f - 260f, w, 0f); cloudRect = GUILayout.Window(0x5A5E01, cloudRect, DrawCloudPrompt, "Save Anywhere " + Plugin.Version); GUI.FocusWindow(0x5A5E01); } else if (SettingsVisible()) { Event ev = Event.current; if (ev.type == EventType.KeyDown && ev.keyCode == KeyCode.Escape && !settingsBusy) { settingsOpen = false; ev.Use(); } GUI.color = new Color(0f, 0f, 0f, 0.6f); GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture); GUI.color = Color.white; float sw = Mathf.Min(760f, vw - 40f); settingsRect = new Rect((vw - sw) * 0.5f, Mathf.Max(20f, vh * 0.5f - 330f), sw, 0f); settingsRect = GUILayout.Window(0x5A5E04, settingsRect, DrawCloudSettings, "Save Anywhere " + Plugin.Version); GUI.FocusWindow(0x5A5E04); } else if (InactiveVisible()) { GUI.color = new Color(0f, 0f, 0f, 0.6f); GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture); GUI.color = Color.white; float iw = Mathf.Min(620f, vw - 40f); Rect ir = new Rect((vw - iw) * 0.5f, vh * 0.5f - 200f, iw, 0f); GUILayout.Window(0x5A5E05, ir, DrawInactive, "Save Anywhere " + Plugin.Version); GUI.FocusWindow(0x5A5E05); } if (SlotScreen.Open && SlotScreen.SaveMode && InRun()) { SlotScreen.Draw(vw, vh); } else if (SlotsAvailable()) { if (SlotScreen.Open) SlotScreen.Draw(vw, vh); else { SlotScreen.DrawMenuButton(vw); DrawCloudButton(vw); if (!SelfUpdate.Checked) Runner.Run(SelfUpdate.Check()); SelfUpdate.DrawBanner(vw); } } if (InRun() && PauseHandler.paused && !WorldGeneration.world.generatingWorld && !SlotScreen.Open && !PauseRing.Built) { float bw = 200f, bh = 40f, gap = 12f; float x = (vw - (bw * 3f + gap * 2f)) * 0.5f, y = 24f; if (GUI.Button(new Rect(x, y, bw, bh), "Save", btnStyle)) ClickSave(); if (GUI.Button(new Rect(x + bw + gap, y, bw, bh), "Save & Quit", btnStyle)) ClickSaveQuit(); if (GUI.Button(new Rect(x + (bw + gap) * 2f, y, bw, bh), AutoLabel(), btnStyle)) ClickAuto(); } DrawPill(vw, InRun() && PauseHandler.paused && PauseRing.Built); GUI.matrix = old; } private void DrawMultiplayer(int id) { GUILayout.Space(8f); GUILayout.Label("MULTIPLAYER MOD DETECTED", titleStyle); GUILayout.Space(8f); GUILayout.Label("Save Anywhere has turned itself off completely, because saving and loading in multiplayer can badly break or corrupt your save. Saving with F5 and the pause menu buttons won't work this session, and Continue loads the game's normal save.", bodyStyle); GUILayout.Space(6f); GUILayout.Label("Found: " + string.Join(", ", MultiplayerGuard.Found.ToArray()) + "", bodyStyle); GUILayout.Space(6f); GUILayout.Label("To use Save Anywhere in single-player, switch Casualties Together off in its menu (Settings > General > Deactivate Multiplayer Mod), or remove the multiplayer mod.", bodyStyle); GUILayout.Space(8f); GUILayout.Label("Not using a multiplayer mod? Then this is a false alarm. Please send a bug report right away in the Bugs tab on the Save Anywhere Nexus page, with the \"Found\" line above and your BepInEx\\LogOutput.log file.", bodyStyle); GUILayout.Space(12f); if (!string.IsNullOrEmpty(Plugin.BugsUrl) && GUILayout.Button("Report a false alarm (opens the Bugs page)", btnStyle, GUILayout.Height(36f))) Application.OpenURL(Plugin.BugsUrl); if (GUILayout.Button("OK", btnStyle, GUILayout.Height(40f))) mpPopupOpen = false; GUILayout.Space(4f); } private GUIStyle leftStyle; private void CloudStyles() { if (smallStyle != null) return; smallStyle = new GUIStyle(GUI.skin.label) { fontSize = 13, alignment = TextAnchor.UpperRight, wordWrap = true, richText = true }; smallStyle.normal.textColor = new Color(0.85f, 0.85f, 0.85f); leftStyle = new GUIStyle(bodyStyle) { alignment = TextAnchor.UpperLeft }; } private void DrawCloudButton(float vw) { CloudStyles(); Rect r = new Rect(vw - 250f, 84f, 230f, 34f); if (GUI.Button(r, Plugin.CloudEnabled.Value ? "Cloud saves: ON" : "Cloud saves: OFF", btnStyle)) { if (Plugin.CloudEnabled.Value) { Plugin.CloudEnabled.Value = false; Cloud.Reset(); Plugin.Log.LogInfo("Cloud saves turned off."); } else cloudPromptOpen = true; } if (!Plugin.CloudEnabled.Value) return; if (GUI.Button(new Rect(vw - 250f, 124f, 230f, 30f), "CLOUD SETTINGS", btnStyle)) OpenSettings(); string line = Cloud.StatusLine(); if (line.Length > 0) GUI.Label(new Rect(vw - 340f, 158f, 320f, 70f), line, smallStyle); } private bool settingsOpen; private bool settingsBusy; private string settingsMsg = ""; private bool settingsMsgBad; private string usageLine = ""; private string shownCode = ""; private string shownKey = ""; private string codeInput = ""; private string keyInput = ""; private bool signOutOthers; private string settingsConfirm = ""; private Rect settingsRect; private bool SettingsVisible() { return settingsOpen && onMenu && !MultiplayerGuard.Detected && !cuPopup; } private void OpenSettings() { settingsOpen = true; settingsMsg = ""; shownCode = ""; shownKey = ""; codeInput = ""; keyInput = ""; signOutOthers = false; settingsConfirm = ""; RefreshUsage(); } private void RefreshUsage() { usageLine = "Checking..."; StartCoroutine(Cloud.GetUsage(s => usageLine = s)); } private void Busy(IEnumerator routine) { settingsBusy = true; settingsMsg = "Working..."; settingsMsgBad = false; StartCoroutine(BusyRoutine(routine)); } private IEnumerator BusyRoutine(IEnumerator routine) { yield return StartCoroutine(routine); settingsBusy = false; } private void Say(string msg, bool bad) { settingsMsg = msg ?? ""; settingsMsgBad = bad; } private void DrawCloudSettings(int wid) { CloudStyles(); GUILayout.Space(6f); GUILayout.Label("CLOUD SETTINGS", titleStyle); GUILayout.Label("" + usageLine + "", bodyStyle); GUILayout.Space(8f); bool was = GUI.enabled; GUI.enabled = !settingsBusy; GUILayout.Label("Use your cloud saves on another device", leftStyle); GUILayout.BeginHorizontal(); if (GUILayout.Button("GET A LINK CODE", btnStyle, GUILayout.Height(32f), GUILayout.Width(220f))) Busy(Cloud.GetLinkCode((code, err) => { if (code != null) { shownCode = code; Say("Type this code on your other device (Cloud settings > Use a code) within 10 minutes.", false); } else Say(err, true); })); GUILayout.Label(shownCode.Length > 0 ? "" + shownCode + "" : "Get a code here, then type it on the other device.", leftStyle); GUILayout.EndHorizontal(); GUILayout.Space(4f); GUILayout.BeginHorizontal(); GUILayout.Label("Code from another device:", leftStyle, GUILayout.Width(220f)); codeInput = GUILayout.TextField(codeInput, 7, GUILayout.Width(120f), GUILayout.Height(30f)); if (GUILayout.Button(settingsConfirm == "link" ? "SURE? LINK" : "LINK THIS PC", btnStyle, GUILayout.Height(30f))) { if (settingsConfirm != "link") { settingsConfirm = "link"; Say("Linking switches this PC to the other device's cloud saves. Saves on this PC aren't touched, but this PC's current cloud saves won't show here any more. Click again to link.", false); } else { settingsConfirm = ""; Busy(Cloud.UseLinkCode(codeInput, (ok, msg) => { Say(msg, !ok); if (ok) { codeInput = ""; RefreshUsage(); } })); } } GUILayout.EndHorizontal(); GUILayout.Space(12f); GUILayout.Label("Recovery key (gets your cloud saves back if you lose this PC or reinstall Windows)", leftStyle); GUILayout.BeginHorizontal(); if (GUILayout.Button(settingsConfirm == "key" ? "SURE? NEW KEY" : "MAKE A RECOVERY KEY", btnStyle, GUILayout.Height(32f), GUILayout.Width(220f))) { if (settingsConfirm != "key") { settingsConfirm = "key"; Say("Making a new key cancels any key you made before. Click again to make one.", false); } else { settingsConfirm = ""; Busy(Cloud.MakeRecoveryKey((key, err) => { if (key != null) { shownKey = key; Say("Write this key down or keep it somewhere safe. Anyone with it can get into your cloud saves. It's only shown now.", false); } else Say(err, true); })); } } if (shownKey.Length > 0) { GUILayout.Label("" + shownKey + "", leftStyle); if (GUILayout.Button("COPY", btnStyle, GUILayout.Height(32f), GUILayout.Width(80f))) { GUIUtility.systemCopyBuffer = shownKey; Say("Recovery key copied. Paste it somewhere safe.", false); } } GUILayout.EndHorizontal(); GUILayout.Space(4f); GUILayout.BeginHorizontal(); GUILayout.Label("Use a recovery key:", leftStyle, GUILayout.Width(220f)); keyInput = GUILayout.TextField(keyInput, 40, GUILayout.Width(280f), GUILayout.Height(30f)); if (GUILayout.Button("RECOVER", btnStyle, GUILayout.Height(30f))) Busy(Cloud.UseRecoveryKey(keyInput, signOutOthers, (ok, msg) => { Say(msg, !ok); if (ok) { keyInput = ""; RefreshUsage(); } })); GUILayout.EndHorizontal(); signOutOthers = GUILayout.Toggle(signOutOthers, " Also sign out every other device (use this if a PC was lost or stolen)"); GUILayout.Space(12f); GUILayout.BeginHorizontal(); if (GUILayout.Button(settingsConfirm == "out" ? "SURE? SIGN OUT OTHERS" : "SIGN OUT OTHER DEVICES", btnStyle, GUILayout.Height(32f))) { if (settingsConfirm != "out") { settingsConfirm = "out"; Say("Every other device linked to your cloud saves will be signed out. Click again to do it.", false); } else { settingsConfirm = ""; Busy(Cloud.LogoutOthers((ok, msg) => { Say(msg, !ok); RefreshUsage(); })); } } GUIStyle danger = new GUIStyle(btnStyle); danger.normal.textColor = new Color(1f, 0.6f, 0.55f); if (GUILayout.Button(settingsConfirm == "del" ? "SURE? DELETE EVERYTHING" : "DELETE MY CLOUD DATA", danger, GUILayout.Height(32f))) { if (settingsConfirm != "del") { settingsConfirm = "del"; Say("This deletes ALL your cloud saves, every old copy and your cloud account, for every linked device. Saves on this PC aren't touched. Click again to delete.", true); } else { settingsConfirm = ""; Busy(Cloud.DeleteAccount((ok, msg) => { Say(msg, !ok); if (ok) { Plugin.CloudEnabled.Value = false; Cloud.Reset(); usageLine = ""; } })); } } GUILayout.EndHorizontal(); GUI.enabled = was; GUILayout.Space(10f); if (settingsMsg.Length > 0) GUILayout.Label("" + settingsMsg + "", bodyStyle); GUILayout.Space(6f); if (GUILayout.Button("CLOSE", btnStyle, GUILayout.Height(36f))) settingsOpen = false; GUILayout.Space(4f); } private bool InactiveVisible() { return Cloud.InactiveNote.Length > 0 && onMenu && !MultiplayerGuard.Detected && !cuPopup && !CloudVisible() && !SettingsVisible(); } private void DrawInactive(int id) { CloudStyles(); GUILayout.Space(8f); GUILayout.Label("CLOUD ACCOUNT WAS INACTIVE", titleStyle); GUILayout.Space(6f); GUILayout.Label(Cloud.InactiveNote, bodyStyle); GUILayout.Space(10f); if (GUILayout.Button("OK, GOT IT", btnStyle, GUILayout.Height(38f))) Cloud.InactiveNote = ""; GUILayout.Space(4f); } private void DrawCloudPrompt(int id) { CloudStyles(); GUILayout.Space(8f); GUILayout.Label("CLOUD SAVES (VERY EXPERIMENTAL)", titleStyle); GUILayout.Space(8f); GUILayout.Label("Save Anywhere can upload your save slots to a server run by the mod author (casualexpie), so you can continue your run on another PC or Steam Deck.", bodyStyle); GUILayout.Space(8f); GUILayout.Label("\u2022 This is a very experimental feature. It may break, lose cloud saves, or stop working.\n\u2022 The mod author can switch cloud saving off at any time, for example if hosting costs get too high. If that happens, your saves on this PC keep working normally.\n\u2022 Keep backing up your Save Anywhere saves yourself anyway. Don't rely on the cloud as your only copy.", leftStyle); GUILayout.Space(8f); GUILayout.Label("What gets uploaded: your save slots and their details (layer, character, run type, run time, when it was saved). No name, email or password.\nYou can change your mind any time with the Cloud saves button under SAVE SLOTS on the main menu.", bodyStyle); GUILayout.Space(12f); GUILayout.BeginHorizontal(); if (GUILayout.Button("Yes, turn on cloud saves", btnStyle, GUILayout.Height(40f))) { Plugin.CloudEnabled.Value = true; Plugin.CloudAsked.Value = true; cloudPromptOpen = false; Cloud.Reset(); Plugin.Log.LogInfo("Cloud saves turned on."); } if (GUILayout.Button("No thanks", btnStyle, GUILayout.Height(40f))) { Plugin.CloudEnabled.Value = false; Plugin.CloudAsked.Value = true; cloudPromptOpen = false; Plugin.Log.LogInfo("Cloud saves left off."); } GUILayout.EndHorizontal(); GUILayout.Space(6f); GUILayout.BeginHorizontal(); if (GUILayout.Button("Open save folder (make a backup)", btnStyle, GUILayout.Height(30f))) { try { System.Diagnostics.Process.Start("explorer.exe", "\"" + Paths.Dir.Replace('/', '\\') + "\""); } catch (Exception e) { Plugin.Log.LogError("Couldn't open the save folder: " + e.Message); } } if (!string.IsNullOrEmpty(Plugin.BugsUrl) && GUILayout.Button("Report a bug", btnStyle, GUILayout.Height(30f))) Application.OpenURL(Plugin.BugsUrl); GUILayout.EndHorizontal(); GUILayout.Space(4f); } } }