casualexpie/opensource

casualexpie/save-anywherePublicSource-available

save-anywhere/SaveAnywhere.cs
5072 lines · 223.5 KBRawDownload
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.IO;
5using System.IO.Compression;
6using System.Linq;
7using System.Reflection;
8using System.Security.Cryptography;
9using System.Text;
10using BepInEx;
11using BepInEx.Configuration;
12using BepInEx.Logging;
13using HarmonyLib;
14using Newtonsoft.Json;
15using Newtonsoft.Json.Linq;
16using UnityEngine;
17using UnityEngine.SceneManagement;
18using UnityEngine.Networking;
19using UnityEngine.Tilemaps;
20using Object = UnityEngine.Object;
21
22[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.")]
23
24namespace SaveAnywhere
25{
26 [BepInPlugin("saveanywhere", "Save Anywhere", Plugin.Version)]
27 public class Plugin : BaseUnityPlugin
28 {
29 public const string Version = "1.8.1";
30 public const string BugsUrl = "https://www.nexusmods.com/scavprototype/mods/885?tab=bugs";
31 internal static ManualLogSource Log;
32 internal static ConfigEntry<KeyboardShortcut> SaveKey;
33 internal static ConfigEntry<float> EnemyRadius;
34 internal static Harmony HarmonyInstance;
35 internal static ConfigEntry<bool> AutoSave;
36 internal static ConfigEntry<float> AutoSaveMinutes;
37 internal static ConfigEntry<bool> AutoSaveOnNewLayer;
38 internal static ConfigEntry<int> SlotCount;
39 internal static ConfigEntry<bool> CloudEnabled;
40 internal static ConfigEntry<bool> CloudAsked;
41 internal static ConfigEntry<bool> ShowCheatFlag;
42
43 private void Awake()
44 {
45 Log = Logger;
46 SaveKey = Config.Bind("Hotkeys", "SaveKey", new KeyboardShortcut(KeyCode.F5), "Saves the game where you stand.");
47 EnemyRadius = Config.Bind("Safety", "EnemyRadius", 15f, "Saving is blocked while a living enemy is closer than this (meters).");
48 AutoSave = Config.Bind("AutoSave", "Enabled", true, "Save automatically during a run. Can also be toggled from the pause menu.");
49 AutoSaveMinutes = Config.Bind("AutoSave", "IntervalMinutes", 5f, "Minutes of play between auto-saves (minimum 1). Paused time doesn't count.");
50 AutoSaveOnNewLayer = Config.Bind("AutoSave", "SaveOnNewLayer", true, "Also auto-save about 10 seconds after you arrive on a new layer.");
51 SlotCount = Config.Bind("Slots", "SlotCount", 5, "How many manual save slots to show (1-10). Auto-save always has its own extra slot.");
52 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.");
53 CloudAsked = Config.Bind("Cloud", "Asked", false, "Whether you have already answered the cloud saves question. Set to false to see it again.");
54 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).");
55 if (DemoGuard.IsDemo())
56 {
57 Log.LogWarning("Casualties: Unknown demo detected (game version " + Application.version + "). Save Anywhere only works with the full game, so it has turned itself off.");
58 DemoGuard.ShowPopup();
59 return;
60 }
61 Boot();
62 }
63
64 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
65 private void Boot()
66 {
67 HarmonyInstance = new Harmony("saveanywhere");
68 HarmonyInstance.PatchAll();
69 Runner.Ensure();
70 Log.LogInfo("Save Anywhere " + Version + " loaded. " + SaveKey.Value + " or the pause menu to save. Game version " + Application.version + ".");
71 }
72 }
73
74 internal static class DemoGuard
75 {
76 public const string StoreUrl = "https://store.steampowered.com/app/4576490/";
77 private static readonly string[] FullGameOnly = { "EndLabScript", "BlueHeart", "WWMRLight" };
78
79 public static bool IsDemo()
80 {
81 int missing = 0;
82 foreach (string n in FullGameOnly)
83 if (Type.GetType(n + ", Assembly-CSharp", false) == null) missing++;
84 return missing == FullGameOnly.Length;
85 }
86
87 public static void ShowPopup()
88 {
89 GameObject go = new GameObject("SaveAnywhereDemoNotice");
90 go.hideFlags = HideFlags.HideAndDontSave;
91 Object.DontDestroyOnLoad(go);
92 go.AddComponent<DemoPopup>();
93 }
94 }
95
96 internal class DemoPopup : MonoBehaviour
97 {
98 private bool open = true;
99 private GameObject blocker;
100 private GUIStyle title, body, btn;
101
102 private void Update()
103 {
104 if (open && blocker == null)
105 {
106 blocker = new GameObject("SaveAnywhereDemoBlocker");
107 DontDestroyOnLoad(blocker);
108 Canvas c = blocker.AddComponent<Canvas>();
109 c.renderMode = RenderMode.ScreenSpaceOverlay;
110 c.sortingOrder = 32766;
111 blocker.AddComponent<UnityEngine.UI.GraphicRaycaster>();
112 GameObject p = new GameObject("Blocker");
113 p.transform.SetParent(blocker.transform, false);
114 UnityEngine.UI.Image img = p.AddComponent<UnityEngine.UI.Image>();
115 img.color = new Color(0f, 0f, 0f, 0f);
116 RectTransform rt = img.rectTransform;
117 rt.anchorMin = Vector2.zero;
118 rt.anchorMax = Vector2.one;
119 rt.offsetMin = Vector2.zero;
120 rt.offsetMax = Vector2.zero;
121 }
122 else if (!open && blocker != null)
123 {
124 Destroy(blocker);
125 blocker = null;
126 }
127 }
128
129 private void OnGUI()
130 {
131 if (!open) return;
132 if (title == null)
133 {
134 title = new GUIStyle(GUI.skin.label) { fontSize = 22, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter, wordWrap = true };
135 title.normal.textColor = new Color(1f, 0.75f, 0.2f);
136 body = new GUIStyle(GUI.skin.label) { fontSize = 16, alignment = TextAnchor.UpperCenter, wordWrap = true, richText = true };
137 body.normal.textColor = Color.white;
138 btn = new GUIStyle(GUI.skin.button) { fontSize = 16, fontStyle = FontStyle.Bold };
139 }
140 float s = Mathf.Max(0.75f, Screen.height / 1080f);
141 Matrix4x4 old = GUI.matrix;
142 GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(s, s, 1f));
143 float vw = Screen.width / s, vh = Screen.height / s;
144 GUI.color = new Color(0f, 0f, 0f, 0.75f);
145 GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture);
146 GUI.color = Color.white;
147 float w = 620f;
148 GUILayout.Window(0x5A5E03, new Rect((vw - w) * 0.5f, vh * 0.5f - 180f, w, 0f), Draw, "Save Anywhere " + Plugin.Version);
149 GUI.FocusWindow(0x5A5E03);
150 GUI.matrix = old;
151 }
152
153 private void Draw(int id)
154 {
155 GUILayout.Space(8f);
156 GUILayout.Label("DEMO VERSION DETECTED", title);
157 GUILayout.Space(8f);
158 GUILayout.Label("Save Anywhere only works with the <b>full game</b> of Casualties: Unknown. The demo is an older build with different game code, so the mod has <b>turned itself off</b>.\n\nYour game and saves aren't affected. Saving works the normal way.\n\n<color=#ffd27f>Buy the full game on Steam to use Save Anywhere.</color>", body);
159 GUILayout.Space(12f);
160 GUILayout.BeginHorizontal();
161 if (GUILayout.Button("Open the Steam store page", btn, GUILayout.Height(36f))) Application.OpenURL(DemoGuard.StoreUrl);
162 if (GUILayout.Button("OK", btn, GUILayout.Height(36f))) open = false;
163 GUILayout.EndHorizontal();
164 GUILayout.Space(4f);
165 }
166 }
167
168 internal static class MultiplayerGuard
169 {
170 internal static bool Detected;
171 internal static readonly List<string> Found = new List<string>();
172
173 private static readonly string[] PluginKeywords =
174 {
175 "krokmp", "krokosha", "casualtiestogether", "casualtiesmp", "multiplayer", "coop", "netplay", "netcode", "lobby", "latejoin"
176 };
177
178 private static readonly string[] NetLibraries =
179 {
180 "mirror", "unity.netcode", "fishnet", "photon", "litenetlib", "riptide", "kcp2k", "telepathy",
181 "lidgren", "facepunch.steamworks", "unity.networking.transport", "unity.services.lobby", "unity.services.relay"
182 };
183
184 private static string Normalize(string s)
185 {
186 if (s == null) return "";
187 return s.ToLowerInvariant().Replace(" ", "").Replace("-", "").Replace("_", "").Replace(".", "");
188 }
189
190 private static bool HasKeyword(string hay)
191 {
192 for (int i = 0; i < PluginKeywords.Length; i++)
193 if (hay.Contains(PluginKeywords[i])) return true;
194 return false;
195 }
196
197 private static bool offLogged;
198 private static bool libLogged;
199
200 private static Assembly AssemblyOf(PluginInfo p)
201 {
202 try
203 {
204 if (!ReferenceEquals(p.Instance, null)) return p.Instance.GetType().Assembly;
205 }
206 catch (Exception) { }
207 if (string.IsNullOrEmpty(p.Location)) return null;
208 foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
209 {
210 try { if (!a.IsDynamic && string.Equals(a.Location, p.Location, StringComparison.OrdinalIgnoreCase)) return a; }
211 catch (Exception) { }
212 }
213 return null;
214 }
215
216 private static readonly Dictionary<string, bool> offCache = new Dictionary<string, bool>();
217
218 private static bool SwitchedOff(PluginInfo p)
219 {
220 string key = p.Metadata.GUID;
221 bool v;
222 if (offCache.TryGetValue(key, out v)) return v;
223 v = SwitchedOffNow(p);
224 if (!ReferenceEquals(p.Instance, null)) offCache[key] = v;
225 return v;
226 }
227
228 private static bool SwitchedOffNow(PluginInfo p)
229 {
230 Assembly a = AssemblyOf(p);
231 if (a == null) return false;
232 Type[] types;
233 try { types = a.GetTypes(); }
234 catch (ReflectionTypeLoadException e) { types = e.Types; }
235 catch (Exception) { return false; }
236 foreach (Type t in types)
237 {
238 if (t == null) continue;
239 try
240 {
241 PropertyInfo pi = t.GetProperty("FORCE_DISABLE_MP_MOD", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
242 if (pi != null && pi.PropertyType == typeof(bool) && (bool)pi.GetValue(null, null)) return true;
243 FieldInfo fi = t.GetField("FORCE_DISABLE_MP_MOD", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
244 if (fi != null && fi.FieldType == typeof(bool) && (bool)fi.GetValue(null)) return true;
245 }
246 catch (Exception) { }
247 }
248 return false;
249 }
250
251 private static bool OwnedByOff(Assembly lib, List<PluginInfo> off)
252 {
253 string dir = null;
254 try { if (!lib.IsDynamic && !string.IsNullOrEmpty(lib.Location)) dir = Path.GetDirectoryName(lib.Location); }
255 catch (Exception) { }
256 string name = lib.GetName().Name;
257 foreach (PluginInfo p in off)
258 {
259 try
260 {
261 if (dir != null && !string.IsNullOrEmpty(p.Location) && string.Equals(Path.GetDirectoryName(p.Location), dir, StringComparison.OrdinalIgnoreCase)) return true;
262 Assembly a = AssemblyOf(p);
263 if (a == null) continue;
264 foreach (AssemblyName r in a.GetReferencedAssemblies())
265 if (string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)) return true;
266 }
267 catch (Exception) { }
268 }
269 return false;
270 }
271
272 internal static bool Check()
273 {
274 if (Detected) return true;
275 List<string> found = new List<string>();
276 HashSet<string> flagged = new HashSet<string>();
277 Dictionary<string, PluginInfo> plugins = BepInEx.Bootstrap.Chainloader.PluginInfos;
278 HashSet<string> offGuids = new HashSet<string>();
279 List<PluginInfo> offPlugins = new List<PluginInfo>();
280 List<string> offNames = new List<string>();
281 foreach (KeyValuePair<string, PluginInfo> kv in plugins)
282 {
283 PluginInfo p = kv.Value;
284 if (p == null || p.Metadata == null || p.Metadata.GUID == "saveanywhere") continue;
285 string file = "";
286 try { file = Path.GetFileNameWithoutExtension(p.Location); } catch (Exception) { }
287 string hay = Normalize(p.Metadata.GUID) + "|" + Normalize(p.Metadata.Name) + "|" + Normalize(file);
288 if (SwitchedOff(p))
289 {
290 offGuids.Add(p.Metadata.GUID);
291 offPlugins.Add(p);
292 offNames.Add(p.Metadata.Name);
293 }
294 }
295 if (offGuids.Count > 0)
296 {
297 foreach (KeyValuePair<string, PluginInfo> kv in plugins)
298 {
299 PluginInfo p = kv.Value;
300 if (p == null || p.Metadata == null || offGuids.Contains(p.Metadata.GUID) || p.Dependencies == null) continue;
301 foreach (BepInDependency dep in p.Dependencies)
302 {
303 if (dep != null && offGuids.Contains(dep.DependencyGUID))
304 {
305 offGuids.Add(p.Metadata.GUID);
306 offPlugins.Add(p);
307 offNames.Add(p.Metadata.Name + " (add-on)");
308 break;
309 }
310 }
311 }
312 if (!offLogged)
313 {
314 offLogged = true;
315 Plugin.Log.LogInfo("Multiplayer mod found but switched off: " + string.Join(", ", offNames.ToArray()) + ". Save Anywhere stays on.");
316 }
317 }
318 foreach (KeyValuePair<string, PluginInfo> kv in plugins)
319 {
320 PluginInfo p = kv.Value;
321 if (p == null || p.Metadata == null || p.Metadata.GUID == "saveanywhere") continue;
322 if (offGuids.Contains(p.Metadata.GUID)) continue;
323 string file = "";
324 try { file = Path.GetFileNameWithoutExtension(p.Location); } catch (Exception) { }
325 string hay = Normalize(p.Metadata.GUID) + "|" + Normalize(p.Metadata.Name) + "|" + Normalize(file);
326 if (HasKeyword(hay))
327 {
328 flagged.Add(p.Metadata.GUID);
329 found.Add(p.Metadata.Name);
330 }
331 }
332 foreach (KeyValuePair<string, PluginInfo> kv in plugins)
333 {
334 PluginInfo p = kv.Value;
335 if (p == null || p.Metadata == null || flagged.Contains(p.Metadata.GUID) || offGuids.Contains(p.Metadata.GUID) || p.Dependencies == null) continue;
336 foreach (BepInDependency dep in p.Dependencies)
337 {
338 if (dep != null && flagged.Contains(dep.DependencyGUID))
339 {
340 found.Add(p.Metadata.Name + " (multiplayer add-on)");
341 break;
342 }
343 }
344 }
345 List<string> libs = new List<string>();
346 Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies();
347 for (int i = 0; i < asms.Length; i++)
348 {
349 string name;
350 try { name = asms[i].GetName().Name; } catch (Exception) { continue; }
351 if (name == null) continue;
352 string low = name.ToLowerInvariant();
353 for (int j = 0; j < NetLibraries.Length; j++)
354 {
355 if (low.StartsWith(NetLibraries[j]))
356 {
357 if (offPlugins.Count > 0 && OwnedByOff(asms[i], offPlugins)) break;
358 libs.Add(name + " (network library)");
359 break;
360 }
361 }
362 }
363 if (found.Count == 0)
364 {
365 if (libs.Count > 0 && !libLogged)
366 {
367 libLogged = true;
368 Plugin.Log.LogInfo("Network library loaded by another mod (" + string.Join(", ", libs.ToArray()) + "), but no multiplayer mod found. Save Anywhere stays on.");
369 }
370 return false;
371 }
372 found.AddRange(libs);
373 Detected = true;
374 Found.AddRange(found);
375 Loader.Pending = null;
376 try { if (Plugin.HarmonyInstance != null) Plugin.HarmonyInstance.UnpatchSelf(); }
377 catch (Exception e) { Plugin.Log.LogWarning("Unpatch failed: " + e.Message); }
378 Plugin.Log.LogWarning("Multiplayer detected (" + string.Join(", ", found.ToArray()) + "). Save Anywhere is now fully disabled.");
379 return true;
380 }
381 }
382
383 internal static class Merc
384 {
385 private static readonly FieldInfo BallField = AccessTools.Field(typeof(WorldGeneration), "spawnedMercBall");
386 private static readonly FieldInfo ChipField = AccessTools.Field(typeof(WorldGeneration), "chip");
387
388 private static string ChipId(int depth)
389 {
390 switch (depth)
391 {
392 case 1: return "regenerationchip";
393 case 2: return "capacitorchip";
394 case 3: return "swapchip";
395 case 4: return "rejuvenationchip";
396 case 6: return "aichip";
397 case 8: return "kineticchip";
398 }
399 return null;
400 }
401
402 internal static void Capture(WorldGeneration w, JObject m)
403 {
404 m["canmerc"] = w.canStartMercRun;
405 if (BallField != null) m["mercball"] = (bool)BallField.GetValue(w);
406 Vector2? ch = PlayerCamera.main.chipHeight;
407 if (ch.HasValue)
408 {
409 m["chipx"] = ch.Value.x;
410 m["chipy"] = ch.Value.y;
411 }
412 }
413
414 internal static void Apply(WorldGeneration w, Snapshot s)
415 {
416 bool fresh = s.Meta["canmerc"] != null;
417 if (fresh) w.canStartMercRun = (bool)s.Meta["canmerc"];
418 else if (w.isMercRun) w.canStartMercRun = false;
419 if (BallField != null)
420 {
421 bool ball;
422 if (s.Meta["mercball"] != null) ball = (bool)s.Meta["mercball"];
423 else ball = w.isMercRun || Item.allItems.Any(x => x != null && x.id == "nanotechscanner") || Object.FindObjectsOfType<Transform>().Any(t => t.parent == null && t.name.StartsWith("techball"));
424 if (ball) BallField.SetValue(w, true);
425 }
426 Vector2? mark = null;
427 if (s.Meta["chipx"] != null) mark = new Vector2((float)s.Meta["chipx"], (float)s.Meta["chipy"]);
428 string id = ChipId(w.biomeDepth);
429 Item chip = null;
430 if (id != null && (mark.HasValue || (!fresh && w.isMercRun)))
431 {
432 float best = float.MaxValue;
433 foreach (Item it in Item.allItems)
434 {
435 if (it == null || it.id != id || it.transform.parent != null) continue;
436 float d = mark.HasValue ? Vector2.Distance(it.transform.position, mark.Value) : 0f;
437 if (d < best) { best = d; chip = it; }
438 }
439 }
440 if (chip != null)
441 {
442 if (ChipField != null) ChipField.SetValue(w, chip.transform);
443 if (!mark.HasValue) mark = chip.transform.position;
444 }
445 if (mark.HasValue)
446 {
447 PlayerCamera.main.SetChipIndicatorPos(mark);
448 Plugin.Log.LogInfo("Restored the nano-tech scanner chip marker.");
449 }
450 }
451 }
452
453 internal static class Lights
454 {
455 private static readonly string[] Ids = { "flashlight", "emergencylight" };
456
457 private static CustomItemBehaviour Of(Item it)
458 {
459 if (it == null || Array.IndexOf(Ids, it.id) < 0) return null;
460 return it.GetComponent<CustomItemBehaviour>();
461 }
462
463 internal static int State(Item it)
464 {
465 CustomItemBehaviour c = Of(it);
466 return c == null ? 0 : c.state;
467 }
468
469 internal static void Set(Item it, int state)
470 {
471 CustomItemBehaviour c = Of(it);
472 if (c != null) c.state = state;
473 }
474
475 private static string Key(Item it)
476 {
477 Transform p = it.transform.parent;
478 return it.id + "|" + (p == null ? "" : p.name.Replace("(Clone)", "").Trim());
479 }
480
481 internal static void CaptureBody(Body b, JObject m)
482 {
483 JArray arr = new JArray();
484 foreach (Item it in b.GetComponentsInChildren<Item>(true))
485 {
486 int st = State(it);
487 if (st == 0) continue;
488 JObject o = new JObject();
489 o["id"] = it.id;
490 o["key"] = Key(it);
491 o["st"] = st;
492 arr.Add(o);
493 }
494 if (arr.Count > 0) m["lights"] = arr;
495 }
496
497 internal static void ApplyBody(Body b, Snapshot s)
498 {
499 JArray arr = s.Meta["lights"] as JArray;
500 if (arr == null) return;
501 List<Item> free = new List<Item>();
502 foreach (Item it in b.GetComponentsInChildren<Item>(true))
503 if (Of(it) != null) free.Add(it);
504 List<JObject> left = new List<JObject>();
505 int n = 0;
506 foreach (JToken t in arr)
507 {
508 JObject o = (JObject)t;
509 string key = (string)o["key"];
510 Item hit = free.Find(x => Key(x) == key);
511 if (hit == null) { left.Add(o); continue; }
512 Set(hit, (int)o["st"]);
513 free.Remove(hit);
514 n++;
515 }
516 foreach (JObject o in left)
517 {
518 string id = (string)o["id"];
519 Item hit = free.Find(x => x.id == id);
520 if (hit == null) continue;
521 Set(hit, (int)o["st"]);
522 free.Remove(hit);
523 n++;
524 }
525 if (n > 0) Plugin.Log.LogInfo("Turned " + n + " carried light(s) back on.");
526 }
527 }
528
529 internal static class Paths
530 {
531 public static string Dir { get { return Application.persistentDataPath; } }
532 public static string Save { get { return Dir + "\\save.sv"; } }
533 public static string Snap { get { return Dir + "\\saveanywhere.sav"; } }
534 public static string Shown
535 {
536 get
537 {
538 string d = Dir.Replace('/', '\\');
539 int i = d.IndexOf("\\AppData\\", StringComparison.OrdinalIgnoreCase);
540 return i >= 0 ? d.Substring(i + 1) : d;
541 }
542 }
543 }
544
545 internal static class CheatFlag
546 {
547 private static readonly Dictionary<string, string> cache = new Dictionary<string, string>();
548 private static GUIStyle style;
549
550 public static string OfBytes(byte[] save)
551 {
552 try
553 {
554 string j = SaveSystem.Unzip(save);
555 if (j.Contains("\"cheatedSave\":true")) return "TRUE";
556 if (j.Contains("\"cheatedSave\":false")) return "FALSE";
557 }
558 catch (Exception) { }
559 return "?";
560 }
561
562 public static string OfGame()
563 {
564 try { return File.Exists(Paths.Save) ? OfBytes(File.ReadAllBytes(Paths.Save)) : null; }
565 catch (Exception) { return "?"; }
566 }
567
568 public static string OfSlot(SlotInfo s)
569 {
570 if (s == null) return null;
571 string key = s.Slot + ":" + s.Hash;
572 string v;
573 if (cache.TryGetValue(key, out v)) return v;
574 v = "?";
575 try
576 {
577 byte[] b = Snapshot.ReadSaveBytes(Slots.PathOf(s.Slot));
578 if (b != null) v = OfBytes(b);
579 }
580 catch (Exception) { }
581 cache[key] = v;
582 return v;
583 }
584
585 public static string Colored(string v)
586 {
587 if (v == "TRUE") return "<color=#ff6a8a>TRUE</color>";
588 if (v == "FALSE") return "<color=#8fe38f>FALSE</color>";
589 return "<color=#aaaaaa>?</color>";
590 }
591
592 public static void DrawTag(Rect r, string v)
593 {
594 if (style == null)
595 {
596 style = new GUIStyle(GUI.skin.label) { fontSize = 11, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter, richText = true };
597 style.normal.textColor = Color.white;
598 }
599 Color old = GUI.color;
600 GUI.color = new Color(0f, 0f, 0f, 0.65f);
601 GUI.DrawTexture(r, Texture2D.whiteTexture);
602 GUI.color = old;
603 GUI.Label(r, "Cheated: " + Colored(v), style);
604 }
605 }
606
607 internal class SlotInfo
608 {
609 public int Slot;
610 public string Run;
611 public DateTime SavedAt;
612 public bool Auto;
613 public int Layer;
614 public float RunTime;
615 public string Hash;
616 public int Character;
617 public string RunType;
618 public int Art = -1;
619 }
620
621 internal static class RunType
622 {
623 private static bool Same(object a, object b)
624 {
625 if (a == null || b == null) return a == b;
626 string sa = Convert.ToString(a, System.Globalization.CultureInfo.InvariantCulture);
627 string sb = Convert.ToString(b, System.Globalization.CultureInfo.InvariantCulture);
628 if (string.Equals(sa, sb, StringComparison.OrdinalIgnoreCase)) return true;
629 double da, db;
630 if (double.TryParse(sa, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out da)
631 && double.TryParse(sb, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out db))
632 return Math.Abs(da - db) < 0.0001;
633 return false;
634 }
635
636 public static string Current()
637 {
638 try
639 {
640 Dictionary<string, object> cur = WorldGeneration.runSettings;
641 if (cur == null) return "";
642 Dictionary<string, object> normal = RunSettings.GetPreset("normal").presetValues;
643 foreach (RunSettingsPreset p in RunSettings.presets)
644 {
645 Dictionary<string, object> want = new Dictionary<string, object>(normal);
646 foreach (KeyValuePair<string, object> kv in p.presetValues) want[kv.Key] = kv.Value;
647 bool match = true;
648 foreach (KeyValuePair<string, object> kv in want)
649 {
650 object v;
651 if (!cur.TryGetValue(kv.Key, out v)) continue;
652 if (!Same(v, kv.Value)) { match = false; break; }
653 }
654 if (match) return Label(p.presetName);
655 }
656 return "Custom";
657 }
658 catch (Exception e)
659 {
660 Plugin.Log.LogWarning("Couldn't work out the run type: " + e.Message);
661 return "";
662 }
663 }
664
665 private static string Label(string preset)
666 {
667 try
668 {
669 string n = Locale.GetOther("preset" + preset);
670 if (!string.IsNullOrEmpty(n) && n != "preset" + preset) return n;
671 }
672 catch (Exception) { }
673 return char.ToUpper(preset[0]) + preset.Substring(1);
674 }
675 }
676
677 internal static class LayerArt
678 {
679 private static string Dir { get { return Paths.Dir + "\\SaveAnywhere\\art"; } }
680 private static readonly Dictionary<int, Texture2D> loaded = new Dictionary<int, Texture2D>();
681 private static readonly HashSet<int> missing = new HashSet<int>();
682 private static bool captured;
683
684 public static int CurrentIndex(WorldGeneration w)
685 {
686 if (w == null) return -1;
687 return w.biomeOverride != WorldGeneration.OverrideSceneType.None ? 11 : w.biomeDepth;
688 }
689
690 public static void Tick()
691 {
692 if (captured) return;
693 WorldGeneration w = WorldGeneration.world;
694 if (w == null || w.generatingWorld || !w.worldExists) return;
695 captured = true;
696 Sprite[] imgs = w.layerGenerationImages;
697 if (imgs == null) return;
698 try { Directory.CreateDirectory(Dir); }
699 catch (Exception e) { Plugin.Log.LogWarning("Couldn't make the layer art folder: " + e.Message); return; }
700 int saved = 0;
701 for (int i = 0; i < imgs.Length; i++)
702 {
703 string path = Dir + "\\layer" + i + ".png";
704 if (imgs[i] == null || File.Exists(path)) continue;
705 try
706 {
707 Texture2D t = Grab(imgs[i], 480);
708 File.WriteAllBytes(path, t.EncodeToPNG());
709 Object.Destroy(t);
710 missing.Remove(i);
711 saved++;
712 }
713 catch (Exception e) { Plugin.Log.LogWarning("Couldn't save the art for layer image " + i + ": " + e.Message); }
714 }
715 if (saved > 0) Plugin.Log.LogInfo("Saved " + saved + " layer pictures for the save slot cards.");
716 }
717
718 private static Texture2D Grab(Sprite sp, int maxW)
719 {
720 Texture src = sp.texture;
721 Rect tr = sp.textureRect;
722 float k = Mathf.Min(1f, maxW / tr.width);
723 int ow = Mathf.Max(1, Mathf.RoundToInt(tr.width * k));
724 int oh = Mathf.Max(1, Mathf.RoundToInt(tr.height * k));
725 RenderTexture rt = RenderTexture.GetTemporary(ow, oh, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
726 Graphics.Blit(src, rt, new Vector2(tr.width / src.width, tr.height / src.height), new Vector2(tr.x / src.width, tr.y / src.height));
727 RenderTexture prev = RenderTexture.active;
728 RenderTexture.active = rt;
729 Texture2D t = new Texture2D(ow, oh, TextureFormat.RGB24, false);
730 t.ReadPixels(new Rect(0, 0, ow, oh), 0, 0);
731 t.Apply();
732 RenderTexture.active = prev;
733 RenderTexture.ReleaseTemporary(rt);
734 return t;
735 }
736
737 public static Texture2D Get(int index)
738 {
739 if (index < 0) return null;
740 Texture2D t;
741 if (loaded.TryGetValue(index, out t) && t != null) return t;
742 if (missing.Contains(index)) return null;
743 string path = Dir + "\\layer" + index + ".png";
744 try
745 {
746 if (!File.Exists(path)) { missing.Add(index); return null; }
747 t = new Texture2D(2, 2, TextureFormat.RGB24, false);
748 if (!ImageConversion.LoadImage(t, File.ReadAllBytes(path))) { missing.Add(index); return null; }
749 t.wrapMode = TextureWrapMode.Clamp;
750 loaded[index] = t;
751 return t;
752 }
753 catch (Exception) { missing.Add(index); return null; }
754 }
755
756 public static void ForgetMissing() { missing.Clear(); }
757 }
758
759 internal static class Slots
760 {
761 private static string Dir { get { return Paths.Dir + "\\SaveAnywhere"; } }
762 private static string IndexPath { get { return Dir + "\\slots.json"; } }
763
764 public static string CurrentRun
765 {
766 get { return PlayerPrefs.GetString("saveanywhere_run", ""); }
767 set { PlayerPrefs.SetString("saveanywhere_run", value ?? ""); PlayerPrefs.Save(); }
768 }
769
770 public static string PathOf(int slot) { return Dir + "\\slot" + slot + ".sav"; }
771
772 public const int AutoSlot = 11;
773
774 public static int Count { get { return Mathf.Clamp(Plugin.SlotCount.Value, 1, 10); } }
775
776 public static string Name(int slot) { return slot == AutoSlot ? "the auto-save slot" : "slot " + slot; }
777
778 public static int ManualFor(int slot, string run)
779 {
780 if (slot != AutoSlot) return slot;
781 SlotInfo s = LoadIndex().Where(x => x.Slot != AutoSlot && x.Run == run && !string.IsNullOrEmpty(run)).OrderByDescending(x => x.SavedAt).FirstOrDefault();
782 return s != null ? s.Slot : 0;
783 }
784
785 public static List<SlotInfo> LoadIndex()
786 {
787 List<SlotInfo> list = new List<SlotInfo>();
788 try
789 {
790 if (!File.Exists(IndexPath)) return list;
791 foreach (JToken t in JArray.Parse(File.ReadAllText(IndexPath)))
792 {
793 SlotInfo s = new SlotInfo();
794 s.Slot = (int)t["slot"];
795 s.Run = (string)t["run"];
796 s.SavedAt = new DateTime((long)t["at"]);
797 s.Auto = (bool)t["auto"];
798 s.Layer = (int)t["layer"];
799 s.RunTime = (float)t["time"];
800 s.Hash = (string)t["hash"];
801 s.Character = (int)t["char"];
802 s.RunType = t["type"] != null ? (string)t["type"] : null;
803 s.Art = t["art"] != null ? (int)t["art"] : s.Layer - 1;
804 if (File.Exists(PathOf(s.Slot))) list.Add(s);
805 }
806 }
807 catch (Exception e) { Plugin.Log.LogWarning("Couldn't read the save slot list: " + e.Message); }
808 return list;
809 }
810
811 private static void SaveIndex(List<SlotInfo> list)
812 {
813 JArray a = new JArray();
814 foreach (SlotInfo s in list)
815 {
816 JObject o = new JObject();
817 o["slot"] = s.Slot;
818 o["run"] = s.Run;
819 o["at"] = s.SavedAt.Ticks;
820 o["auto"] = s.Auto;
821 o["layer"] = s.Layer;
822 o["time"] = s.RunTime;
823 o["hash"] = s.Hash;
824 o["char"] = s.Character;
825 if (s.RunType != null) o["type"] = s.RunType;
826 o["art"] = s.Art;
827 a.Add(o);
828 }
829 Directory.CreateDirectory(Dir);
830 File.WriteAllText(IndexPath, a.ToString(Formatting.None));
831 }
832
833 public static int CurrentSlot
834 {
835 get { return PlayerPrefs.GetInt("saveanywhere_slot", 0); }
836 set { PlayerPrefs.SetInt("saveanywhere_slot", value); PlayerPrefs.Save(); }
837 }
838
839 public static int PickManualSlot()
840 {
841 int cur = CurrentSlot;
842 if (cur > 0 && cur != AutoSlot) return cur;
843 List<SlotInfo> list = LoadIndex();
844 for (int i = 1; i <= Count; i++)
845 if (!list.Any(x => x.Slot == i)) return i;
846 return 0;
847 }
848
849 public static int FindByHash(string hash)
850 {
851 SlotInfo s = LoadIndex().FirstOrDefault(x => x.Hash == hash);
852 return s != null ? s.Slot : 0;
853 }
854
855 public static void Store(Snapshot snap, int slot, bool auto, int layer, float runTime, int character, string runType, int art)
856 {
857 Directory.CreateDirectory(Dir);
858 string run = CurrentRun;
859 List<SlotInfo> list = LoadIndex();
860 list.RemoveAll(x => x.Slot == slot);
861 snap.Write(PathOf(slot));
862 SlotInfo n = new SlotInfo();
863 n.Slot = slot;
864 n.Run = run;
865 n.SavedAt = DateTime.Now;
866 n.Auto = auto;
867 n.Layer = layer;
868 n.RunTime = runTime;
869 n.Hash = snap.Hash;
870 n.Character = character;
871 n.RunType = runType;
872 n.Art = art;
873 list.Add(n);
874 SaveIndex(list);
875 Plugin.Log.LogInfo("Saved into " + Name(slot) + ". Marked as cheated by the game: " + CheatFlag.OfBytes(snap.SaveBytes));
876 }
877
878 public static bool Import(int slot, byte[] data, string metaJson)
879 {
880 Directory.CreateDirectory(Dir);
881 string tmp = PathOf(slot) + ".cloud";
882 Snapshot snap = null;
883 try
884 {
885 File.WriteAllBytes(tmp, data);
886 snap = Snapshot.Read(tmp);
887 }
888 catch (Exception e) { Plugin.Log.LogWarning("Downloaded save couldn't be read: " + e.Message); }
889 if (snap == null)
890 {
891 TryDelete(tmp);
892 return false;
893 }
894 JObject m;
895 try { m = string.IsNullOrEmpty(metaJson) ? new JObject() : Cloud.Json(metaJson); }
896 catch (Exception) { m = new JObject(); }
897 SlotInfo n = new SlotInfo();
898 n.Slot = slot;
899 n.Run = (string)m["runId"];
900 if (string.IsNullOrEmpty(n.Run) && snap.Meta["run"] != null) n.Run = (string)snap.Meta["run"];
901 DateTime at;
902 n.SavedAt = m["savedAt"] != null && DateTime.TryParse((string)m["savedAt"], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out at) ? at.ToLocalTime() : DateTime.Now;
903 n.SavedAt = new DateTime(n.SavedAt.Ticks);
904 n.Auto = slot == AutoSlot;
905 int v;
906 n.Layer = m["layer"] != null && int.TryParse(m["layer"].ToString(), out v) ? v : snap.Depth + 1;
907 n.RunTime = m["runTime"] != null && int.TryParse(m["runTime"].ToString(), out v) ? v : 0;
908 n.Character = m["character"] != null && int.TryParse(m["character"].ToString(), out v) ? v : 0;
909 n.RunType = (string)m["runType"];
910 n.Hash = snap.Hash;
911 n.Art = n.Layer - 1;
912 List<SlotInfo> list = LoadIndex();
913 list.RemoveAll(x => x.Slot == slot);
914 TryDelete(PathOf(slot));
915 File.Move(tmp, PathOf(slot));
916 list.Add(n);
917 SaveIndex(list);
918 return true;
919 }
920
921 public static void DeleteRun(string run)
922 {
923 Cloud.DeleteForRun(run, 0);
924 List<SlotInfo> list = LoadIndex();
925 foreach (SlotInfo s in list.Where(x => x.Run == run).ToList())
926 {
927 TryDelete(PathOf(s.Slot));
928 list.Remove(s);
929 }
930 SaveIndex(list);
931 CurrentSlot = 0;
932 }
933
934 public static void Delete(int slot)
935 {
936 SlotInfo old = LoadIndex().FirstOrDefault(x => x.Slot == slot);
937 if (old != null) Cloud.DeleteForRun(old.Run, slot);
938 if (CurrentSlot == slot) CurrentSlot = 0;
939 List<SlotInfo> list = LoadIndex();
940 TryDelete(PathOf(slot));
941 list.RemoveAll(x => x.Slot == slot);
942 SaveIndex(list);
943 }
944
945 public static bool Use(SlotInfo s)
946 {
947 try
948 {
949 Snapshot snap = Snapshot.Read(PathOf(s.Slot));
950 if (snap == null) return false;
951 File.WriteAllBytes(Paths.Save, snap.SaveBytes);
952 File.Copy(PathOf(s.Slot), Paths.Snap, true);
953 CurrentRun = s.Run;
954 CurrentSlot = ManualFor(s.Slot, s.Run);
955 return true;
956 }
957 catch (Exception e)
958 {
959 Plugin.Log.LogError("Couldn't use save slot " + s.Slot + ": " + e);
960 return false;
961 }
962 }
963
964 private static void TryDelete(string p)
965 {
966 try { if (File.Exists(p)) File.Delete(p); } catch (Exception) { }
967 }
968 }
969
970 internal class Snapshot
971 {
972 private const string Magic = "SAVEANYWHERE1";
973 public string Hash;
974 public byte[] SaveBytes;
975 public JObject Meta;
976 public int W;
977 public int H;
978 public ushort[,] Blocks;
979 public byte[,] Fluid;
980
981 public int Depth { get { return (int)Meta["depth"]; } }
982
983 public static string HashOf(byte[] data)
984 {
985 using (SHA1 sha = SHA1.Create())
986 {
987 byte[] h = sha.ComputeHash(data);
988 StringBuilder sb = new StringBuilder();
989 for (int i = 0; i < h.Length; i++) sb.Append(h[i].ToString("x2"));
990 return sb.ToString();
991 }
992 }
993
994 public void Write(string path)
995 {
996 string tmp = path + ".tmp";
997 using (FileStream fs = File.Create(tmp))
998 using (GZipStream gz = new GZipStream(fs, CompressionMode.Compress))
999 using (BinaryWriter w = new BinaryWriter(gz))
1000 {
1001 w.Write(Magic);
1002 w.Write(Hash);
1003 w.Write(SaveBytes.Length);
1004 w.Write(SaveBytes);
1005 w.Write(Meta.ToString(Formatting.None));
1006 w.Write(W);
1007 w.Write(H);
1008 byte[] b = new byte[W * H * 2];
1009 Buffer.BlockCopy(Blocks, 0, b, 0, b.Length);
1010 w.Write(b);
1011 byte[] f = new byte[W * H];
1012 Buffer.BlockCopy(Fluid, 0, f, 0, f.Length);
1013 w.Write(f);
1014 }
1015 if (File.Exists(path)) File.Delete(path);
1016 File.Move(tmp, path);
1017 }
1018
1019 public static byte[] ReadSaveBytes(string path)
1020 {
1021 using (FileStream fs = File.OpenRead(path))
1022 using (GZipStream gz = new GZipStream(fs, CompressionMode.Decompress))
1023 using (BinaryReader r = new BinaryReader(gz))
1024 {
1025 if (r.ReadString() != Magic) return null;
1026 r.ReadString();
1027 return r.ReadBytes(r.ReadInt32());
1028 }
1029 }
1030
1031 public static Snapshot Read(string path)
1032 {
1033 using (FileStream fs = File.OpenRead(path))
1034 using (GZipStream gz = new GZipStream(fs, CompressionMode.Decompress))
1035 using (BinaryReader r = new BinaryReader(gz))
1036 {
1037 if (r.ReadString() != Magic) return null;
1038 Snapshot s = new Snapshot();
1039 s.Hash = r.ReadString();
1040 s.SaveBytes = r.ReadBytes(r.ReadInt32());
1041 s.Meta = JObject.Parse(r.ReadString());
1042 s.W = r.ReadInt32();
1043 s.H = r.ReadInt32();
1044 byte[] b = r.ReadBytes(s.W * s.H * 2);
1045 s.Blocks = new ushort[s.W, s.H];
1046 Buffer.BlockCopy(b, 0, s.Blocks, 0, b.Length);
1047 byte[] f = r.ReadBytes(s.W * s.H);
1048 s.Fluid = new byte[s.W, s.H];
1049 Buffer.BlockCopy(f, 0, s.Fluid, 0, f.Length);
1050 return s;
1051 }
1052 }
1053 }
1054
1055 internal static class Prefabs
1056 {
1057 private static readonly string[] Folders = { "Structures", "Special" };
1058 private static readonly string[] ExtraRoots = { "Lifepod", "BioContainer", "LifepodStart" };
1059 private static readonly Dictionary<string, string> cache = new Dictionary<string, string>();
1060 private static List<KeyValuePair<string, GameObject>> roots;
1061 private static Dictionary<string, GameObject> assetsByName;
1062
1063 public static string BaseName(string name)
1064 {
1065 string n = name;
1066 while (n.EndsWith("(Clone)")) n = n.Substring(0, n.Length - 7).TrimEnd();
1067 return n.Trim();
1068 }
1069
1070 private static List<KeyValuePair<string, GameObject>> Roots()
1071 {
1072 if (roots != null) return roots;
1073 roots = new List<KeyValuePair<string, GameObject>>();
1074 foreach (string folder in Folders)
1075 {
1076 GameObject[] all = Resources.LoadAll<GameObject>(folder);
1077 foreach (GameObject g in all) roots.Add(new KeyValuePair<string, GameObject>(folder + "/" + g.name, g));
1078 }
1079 foreach (string p in ExtraRoots)
1080 {
1081 GameObject g = Resources.Load<GameObject>(p);
1082 if (g != null) roots.Add(new KeyValuePair<string, GameObject>(p, g));
1083 }
1084 return roots;
1085 }
1086
1087 private static bool FindChild(Transform t, Func<Transform, bool> match, List<int> path)
1088 {
1089 for (int i = 0; i < t.childCount; i++)
1090 {
1091 Transform c = t.GetChild(i);
1092 path.Add(i);
1093 if (match(c)) return true;
1094 if (FindChild(c, match, path)) return true;
1095 path.RemoveAt(path.Count - 1);
1096 }
1097 return false;
1098 }
1099
1100 private static string SearchRoots(Func<Transform, bool> match)
1101 {
1102 foreach (KeyValuePair<string, GameObject> kv in Roots())
1103 {
1104 List<int> path = new List<int>();
1105 if (FindChild(kv.Value.transform, match, path))
1106 return "C:" + kv.Key + "|" + string.Join("/", path.Select(x => x.ToString()).ToArray());
1107 }
1108 return null;
1109 }
1110
1111 private static void CollectNames(Transform t, int depth, List<string> into)
1112 {
1113 if (depth <= 0) return;
1114 for (int i = 0; i < t.childCount; i++)
1115 {
1116 Transform c = t.GetChild(i);
1117 into.Add(BaseName(c.name));
1118 CollectNames(c, depth - 1, into);
1119 }
1120 }
1121
1122 private static float Similarity(List<string> inst, Transform cand)
1123 {
1124 List<string> cn = new List<string>();
1125 CollectNames(cand, 3, cn);
1126 List<string> left = new List<string>(inst);
1127 int common = 0, candOnly = 0;
1128 foreach (string s in cn)
1129 {
1130 int i = left.IndexOf(s);
1131 if (i >= 0) { common++; left.RemoveAt(i); }
1132 else candOnly++;
1133 }
1134 return common * 2f - candOnly - left.Count * 0.5f;
1135 }
1136
1137 private static void FindAll(Transform t, Func<Transform, bool> match, List<int> path, string rootKey, List<KeyValuePair<string, Transform>> into)
1138 {
1139 for (int i = 0; i < t.childCount; i++)
1140 {
1141 Transform c = t.GetChild(i);
1142 path.Add(i);
1143 if (match(c)) into.Add(new KeyValuePair<string, Transform>("C:" + rootKey + "|" + string.Join("/", path.Select(x => x.ToString()).ToArray()), c));
1144 FindAll(c, match, path, rootKey, into);
1145 path.RemoveAt(path.Count - 1);
1146 }
1147 }
1148
1149 public static string ForBuilding(GameObject go)
1150 {
1151 string n = BaseName(go.name);
1152 BuildingEntity self = go.GetComponent<BuildingEntity>();
1153 string beId = self != null ? self.id : null;
1154 List<string> inst = new List<string>();
1155 CollectNames(go.transform, 3, inst);
1156 string key = n + "|" + beId + "|" + string.Join(",", inst.OrderBy(x => x).ToArray());
1157 string res;
1158 if (cache.TryGetValue(key, out res)) return res;
1159
1160 Func<Transform, bool> match = c =>
1161 {
1162 if (c.name != n) return false;
1163 BuildingEntity be = c.GetComponent<BuildingEntity>();
1164 return be != null && (beId == null || be.id == beId);
1165 };
1166 List<KeyValuePair<string, Transform>> cands = new List<KeyValuePair<string, Transform>>();
1167 string[] tries = { n, "Special/" + n, "Structures/" + n };
1168 foreach (string t in tries)
1169 {
1170 GameObject g = Resources.Load<GameObject>(t);
1171 if (g != null && match(g.transform)) { cands.Add(new KeyValuePair<string, Transform>("R:" + t, g.transform)); break; }
1172 }
1173 foreach (KeyValuePair<string, GameObject> kv in Roots())
1174 FindAll(kv.Value.transform, match, new List<int>(), kv.Key, cands);
1175
1176 res = null;
1177 float best = float.MinValue;
1178 foreach (KeyValuePair<string, Transform> c in cands)
1179 {
1180 float sc = Similarity(inst, c.Value);
1181 if (sc > best) { best = sc; res = c.Key; }
1182 }
1183 if (res == null) res = "N:" + n;
1184 cache[key] = res;
1185 return res;
1186 }
1187
1188 public static string ForSpawn(GameObject go)
1189 {
1190 Transform src = go.transform;
1191 return SearchRoots(c =>
1192 {
1193 if (!c.name.StartsWith("DOSPAWN") || c.childCount != src.childCount) return false;
1194 for (int i = 0; i < c.childCount; i++)
1195 if (BaseName(src.GetChild(i).name) != c.GetChild(i).name) return false;
1196 return true;
1197 });
1198 }
1199
1200 public static GameObject Load(string res)
1201 {
1202 if (string.IsNullOrEmpty(res) || res.Length < 3) return null;
1203 string body = res.Substring(2);
1204 if (res.StartsWith("R:")) return Resources.Load<GameObject>(body);
1205 if (res.StartsWith("C:"))
1206 {
1207 int bar = body.IndexOf('|');
1208 GameObject root = Resources.Load<GameObject>(body.Substring(0, bar));
1209 if (root == null) return null;
1210 Transform t = root.transform;
1211 string idx = body.Substring(bar + 1);
1212 if (idx.Length > 0)
1213 {
1214 foreach (string s in idx.Split('/'))
1215 {
1216 int i = int.Parse(s);
1217 if (i >= t.childCount) return null;
1218 t = t.GetChild(i);
1219 }
1220 }
1221 return t.gameObject;
1222 }
1223 if (res.StartsWith("N:"))
1224 {
1225 if (assetsByName == null)
1226 {
1227 assetsByName = new Dictionary<string, GameObject>();
1228 foreach (GameObject g in Resources.FindObjectsOfTypeAll<GameObject>())
1229 {
1230 if (g.scene.IsValid()) continue;
1231 if (g.GetComponent<BuildingEntity>() == null) continue;
1232 if (!assetsByName.ContainsKey(g.name)) assetsByName[g.name] = g;
1233 }
1234 }
1235 GameObject found;
1236 if (assetsByName.TryGetValue(body, out found)) return found;
1237 GameObject[] all = Resources.LoadAll<GameObject>("");
1238 foreach (GameObject g in all)
1239 {
1240 if (g.name == body && g.GetComponent<BuildingEntity>() != null) { assetsByName[body] = g; return g; }
1241 }
1242 }
1243 return null;
1244 }
1245 }
1246
1247 internal static class Comps
1248 {
1249 private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
1250
1251 public static string Capture(GameObject go)
1252 {
1253 Dictionary<Type, Component> d = new Dictionary<Type, Component>();
1254 foreach (Component c in go.GetComponents<Component>())
1255 {
1256 if (c == null) continue;
1257 Type t = c.GetType();
1258 if (Attribute.IsDefined(t, typeof(Saveable)) && !d.ContainsKey(t)) d.Add(t, c);
1259 }
1260 if (d.Count == 0) return null;
1261 return JsonConvert.SerializeObject(d, Formatting.None, Settings);
1262 }
1263
1264 public static void Apply(GameObject go, string json)
1265 {
1266 if (string.IsNullOrEmpty(json)) return;
1267 JObject j = JObject.Parse(json);
1268 foreach (JProperty p in j.Properties())
1269 {
1270 try
1271 {
1272 Type t = AccessTools.TypeByName(p.Name);
1273 if (t == null) continue;
1274 Component c = go.GetComponent(t);
1275 if (c == null) c = go.AddComponent(t);
1276 JObject fields = p.Value as JObject;
1277 if (fields == null) continue;
1278 foreach (JProperty f in fields.Properties())
1279 {
1280 FieldInfo fi = t.GetField(f.Name);
1281 if (fi == null) continue;
1282 try { fi.SetValue(c, f.Value.ToObject(fi.FieldType)); }
1283 catch (Exception e) { Plugin.Log.LogWarning("Field " + t.Name + "." + f.Name + ": " + e.Message); }
1284 }
1285 }
1286 catch (Exception e) { Plugin.Log.LogWarning("Component " + p.Name + ": " + e.Message); }
1287 }
1288 }
1289 }
1290
1291 internal static class Veins
1292 {
1293 private static bool IsVein(GameObject g)
1294 {
1295 return g != null && g.name.StartsWith("vein");
1296 }
1297
1298 private static bool IsClimbRope(GameObject g)
1299 {
1300 return g != null && g.name.StartsWith("climbingrope");
1301 }
1302
1303 private static bool IsCaveRope(GameObject g)
1304 {
1305 return g != null && (g.name.StartsWith("sandvinerope") || g.name.StartsWith("mushroomrope"));
1306 }
1307
1308 private static void Register(Climbable cl)
1309 {
1310 if (Climbable.allClimbables == null) Climbable.allClimbables = new List<Climbable>();
1311 if (!Climbable.allClimbables.Contains(cl)) Climbable.allClimbables.Add(cl);
1312 }
1313
1314 public static void Capture(GameObject g, JObject o)
1315 {
1316 if (IsVein(g) || IsCaveRope(g))
1317 {
1318 SpriteRenderer sr = g.GetComponent<SpriteRenderer>();
1319 if (sr != null)
1320 {
1321 Color c = sr.color;
1322 o["vc"] = new JArray(c.r, c.g, c.b, c.a);
1323 if (sr.drawMode != SpriteDrawMode.Simple) o["vs"] = new JArray(sr.size.x, sr.size.y);
1324 }
1325 }
1326 Climbable cl = g.GetComponent<Climbable>();
1327 if (cl != null && cl.points != null && cl.points.Count >= 2)
1328 {
1329 JArray p = new JArray();
1330 foreach (Vector2 v in cl.points) { p.Add(v.x); p.Add(v.y); }
1331 o["vp"] = p;
1332 o["vd"] = cl.downwardsVelocity;
1333 }
1334 }
1335
1336 public static void Apply(GameObject g, JObject o)
1337 {
1338 if (IsVein(g) || IsCaveRope(g))
1339 {
1340 SpriteRenderer sr = g.GetComponent<SpriteRenderer>();
1341 JArray c = o["vc"] as JArray;
1342 if (sr != null && c != null && c.Count == 4) sr.color = new Color((float)c[0], (float)c[1], (float)c[2], (float)c[3]);
1343 JArray s = o["vs"] as JArray;
1344 if (sr != null && s != null && s.Count == 2) sr.size = new Vector2((float)s[0], (float)s[1]);
1345 }
1346 Climbable cl = g.GetComponent<Climbable>();
1347 JArray p = o["vp"] as JArray;
1348 if (cl != null && p != null && p.Count >= 4)
1349 {
1350 List<Vector2> pts = new List<Vector2>();
1351 for (int i = 0; i + 1 < p.Count; i += 2) pts.Add(new Vector2((float)p[i], (float)p[i + 1]));
1352 cl.points = pts;
1353 if (o["vd"] != null) cl.downwardsVelocity = (float)o["vd"];
1354 cl.CalculateTotalLength();
1355 if (IsClimbRope(g) && g.transform.childCount > 0)
1356 g.transform.GetChild(0).localScale = new Vector2(1f, Vector2.Distance(pts[pts.Count - 1], pts[0]) / 25f);
1357 }
1358 }
1359
1360 public static void Repair()
1361 {
1362 Physics2D.SyncTransforms();
1363 int mask = LayerMask.GetMask("Ground");
1364 int n = 0;
1365 foreach (Climbable cl in Object.FindObjectsOfType<Climbable>())
1366 {
1367 if (cl == null) continue;
1368 if (cl.points != null && cl.points.Count >= 2) continue;
1369 if (IsVein(cl.gameObject))
1370 {
1371 Vector2 from = cl.transform.position;
1372 RaycastHit2D up = Physics2D.Raycast(from, Vector2.up, WorldGeneration.CHUNKSIZE * 4, mask);
1373 RaycastHit2D down = Physics2D.Raycast(from, Vector2.down, WorldGeneration.CHUNKSIZE * 4, mask);
1374 if (!up || !down) continue;
1375 cl.transform.position = new Vector3(cl.transform.position.x, (up.point.y + down.point.y) * 0.5f, cl.transform.position.z);
1376 SpriteRenderer sr = cl.GetComponent<SpriteRenderer>();
1377 if (sr != null) sr.size = new Vector2(2f, Mathf.Max(0.5f, Mathf.Abs(up.point.y - down.point.y) - 1f));
1378 cl.points = new List<Vector2> { new Vector2(from.x, down.point.y), new Vector2(from.x, up.point.y) };
1379 cl.downwardsVelocity = (1f - Mathf.Clamp(cl.transform.localScale.x, 0.5f, 1f)) * 10f;
1380 cl.CalculateTotalLength();
1381 Register(cl);
1382 n++;
1383 }
1384 else if (IsClimbRope(cl.gameObject))
1385 {
1386 Vector2 top = cl.transform.position;
1387 RaycastHit2D down = Physics2D.Raycast(top, Vector2.down, 25f, mask);
1388 Vector2 bottom = down ? down.point : top + Vector2.down * 25f;
1389 cl.points = new List<Vector2> { bottom, top };
1390 cl.CalculateTotalLength();
1391 if (cl.transform.childCount > 0)
1392 cl.transform.GetChild(0).localScale = new Vector2(1f, Vector2.Distance(top, bottom) / 25f);
1393 Register(cl);
1394 n++;
1395 }
1396 else if (IsCaveRope(cl.gameObject))
1397 {
1398 Vector2 mid = cl.transform.position;
1399 RaycastHit2D up = Physics2D.Raycast(mid, Vector2.up, WorldGeneration.CHUNKSIZE * 4, mask);
1400 if (!up) continue;
1401 Vector2 top = new Vector2(mid.x, up.point.y);
1402 Vector2 bottom = new Vector2(mid.x, 2f * mid.y - up.point.y);
1403 if (top.y - bottom.y < 0.5f) continue;
1404 SpriteRenderer sr = cl.GetComponent<SpriteRenderer>();
1405 if (sr != null && sr.drawMode != SpriteDrawMode.Simple) sr.size = new Vector2(2.5f, top.y - bottom.y);
1406 cl.points = new List<Vector2> { bottom, top };
1407 cl.downwardsVelocity = (1f - Mathf.Clamp(cl.transform.localScale.x, 0.15f, 1f)) * 16f;
1408 cl.CalculateTotalLength();
1409 Register(cl);
1410 n++;
1411 }
1412 }
1413 if (n > 0) Plugin.Log.LogInfo("Rebuilt " + n + " climbables (veins/ropes) from an older save.");
1414 }
1415 }
1416
1417 internal static class Crystals
1418 {
1419 private static readonly FieldInfo EffectsField = AccessTools.Field(typeof(CrystalBehaviour), "effects");
1420 private static readonly FieldInfo ExaminedField = AccessTools.Field(typeof(CrystalBehaviour), "hasBeenExamined");
1421
1422 private static JArray Col(Color c) { return new JArray(c.r, c.g, c.b, c.a); }
1423 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]); }
1424
1425 public static JObject Capture(BuildingEntity be, string res)
1426 {
1427 GameObject g = be.gameObject;
1428 GameObject pf = res != null ? Prefabs.Load(res) : null;
1429 CrystalBehaviour cb = g.GetComponent<CrystalBehaviour>();
1430 if (cb == null && (pf == null || pf.GetComponent<CrystalBehaviour>() == null)) return null;
1431 JObject c = new JObject();
1432 SpriteRenderer sr = g.GetComponent<SpriteRenderer>();
1433 if (sr != null) c["sc"] = Col(sr.color);
1434 UnityEngine.Rendering.Universal.Light2D l = g.GetComponent<UnityEngine.Rendering.Universal.Light2D>();
1435 if (l != null)
1436 {
1437 c["lc"] = Col(l.color);
1438 c["li"] = l.intensity;
1439 c["lf"] = l.falloffIntensity;
1440 c["lv"] = l.volumeIntensityEnabled;
1441 c["lvi"] = l.volumeIntensity;
1442 c["lr"] = l.pointLightOuterRadius;
1443 c["le"] = l.enabled;
1444 }
1445 c["alive"] = cb != null;
1446 c["usable"] = g.GetComponent<UsableObject>() != null;
1447 c["desc"] = be.description;
1448 JArray fx = new JArray();
1449 if (cb != null)
1450 {
1451 List<CrystalEffect> list = EffectsField != null ? EffectsField.GetValue(cb) as List<CrystalEffect> : null;
1452 if (list != null) foreach (CrystalEffect e in list) if (e != null) fx.Add(e.GetType().FullName);
1453 c["ex"] = ExaminedField != null && (bool)ExaminedField.GetValue(cb);
1454 }
1455 c["fx"] = fx;
1456 return c;
1457 }
1458
1459 public static void Apply(GameObject g, JObject c)
1460 {
1461 CrystalBehaviour cb = g.GetComponent<CrystalBehaviour>();
1462 if (c == null)
1463 {
1464 if (cb == null) return;
1465 cb.SetColor(UnityEngine.Random.value < 0.5f ? Color.magenta : Color.cyan);
1466 UsableObject u0 = g.GetComponent<UsableObject>();
1467 if (u0 != null) Object.Destroy(u0);
1468 Object.Destroy(cb);
1469 return;
1470 }
1471 if (cb != null)
1472 {
1473 List<CrystalEffect> list = new List<CrystalEffect>();
1474 if (EffectsField != null) EffectsField.SetValue(cb, list);
1475 if ((bool)c["alive"] && c["fx"] is JArray)
1476 {
1477 foreach (JToken t in (JArray)c["fx"])
1478 {
1479 Type ty = AccessTools.TypeByName((string)t);
1480 if (ty == null || !typeof(CrystalEffect).IsAssignableFrom(ty)) continue;
1481 try
1482 {
1483 CrystalEffect e = (CrystalEffect)Activator.CreateInstance(ty, true);
1484 e.crystal = cb;
1485 list.Add(e);
1486 e.Start();
1487 }
1488 catch (Exception ex) { Plugin.Log.LogWarning("Crystal effect " + ty.Name + " failed: " + ex.Message); }
1489 }
1490 }
1491 if (list.Count == 0) Object.Destroy(cb);
1492 else
1493 {
1494 if (list.Count > 1)
1495 {
1496 GameObject d = Utils.Create("Special/CrystalDistort", g.transform);
1497 d.transform.localPosition = Vector3.zero;
1498 d.transform.localScale = Vector3.one;
1499 d.transform.rotation = Quaternion.identity;
1500 d.GetComponent<SpriteRenderer>().material.SetFloat("_DistortStrength", list.Count * 0.015f);
1501 }
1502 if (ExaminedField != null && c["ex"] != null) ExaminedField.SetValue(cb, (bool)c["ex"]);
1503 cb.CheckCurrentChunk(WorldGeneration.world.GetClosestChunkScript(g.transform.position));
1504 }
1505 }
1506 if (c["usable"] != null && !(bool)c["usable"])
1507 {
1508 UsableObject u = g.GetComponent<UsableObject>();
1509 if (u != null) Object.Destroy(u);
1510 }
1511 SpriteRenderer sr = g.GetComponent<SpriteRenderer>();
1512 if (sr != null && c["sc"] != null) sr.color = Col(c["sc"]);
1513 UnityEngine.Rendering.Universal.Light2D l = g.GetComponent<UnityEngine.Rendering.Universal.Light2D>();
1514 if (l != null && c["lc"] != null)
1515 {
1516 l.color = Col(c["lc"]);
1517 l.intensity = (float)c["li"];
1518 l.falloffIntensity = (float)c["lf"];
1519 l.volumeIntensityEnabled = (bool)c["lv"];
1520 l.volumeIntensity = (float)c["lvi"];
1521 l.pointLightOuterRadius = (float)c["lr"];
1522 l.enabled = (bool)c["le"];
1523 }
1524 BuildingEntity be = g.GetComponent<BuildingEntity>();
1525 if (be != null && c["desc"] != null) be.description = (string)c["desc"];
1526 }
1527 }
1528
1529 internal static class Safety
1530 {
1531 private static readonly string[] EnemyNames = { "GuardScript", "TurretScript", "CeilingTurret", "LaserDroneScript", "CrystalEnemy", "SpiderHandler", "ElderThornbackBehaviour", "ScrapEaterScript", "BloodSuckerScript" };
1532 private static List<Type> enemyTypes;
1533
1534 public static string Check()
1535 {
1536 WorldGeneration w = WorldGeneration.world;
1537 if (w == null || PlayerCamera.main == null || PlayerCamera.main.body == null) return "you're not in a run";
1538 if (RunEnd.Ended) return "the run is over";
1539 Body b = PlayerCamera.main.body;
1540 if (w.generatingWorld || Loader.Restoring) return "the layer is still loading";
1541 if (w.biomeOverride != WorldGeneration.OverrideSceneType.None) return "you can't save here";
1542 if (w.biomeDepth >= 9) return "you can't save on the final layers";
1543 if (!b.alive) return "you're dead";
1544 if (PlayerCamera.main.selfDestructActive) return "you gave up on this run";
1545 if (b.isDying || b.isCriticallyDying) return "you're in critical condition, treat your wounds first";
1546 if (b.sleeping) return "you're asleep";
1547 if (b.consciousness < 50f) return "you're unconscious";
1548 if (!b.standing) return "you're knocked down";
1549 if (b.currentClimbable != null) return "you're climbing";
1550 bool moving = b.rb != null && Mathf.Abs(b.rb.velocity.y) > 2.5f;
1551 if (!b.grounded || moving) return "you're falling";
1552 string danger = Danger(w, b);
1553 if (danger != null) return danger;
1554 float r = Plugin.EnemyRadius.Value;
1555 if (r > 0f)
1556 {
1557 if (enemyTypes == null)
1558 {
1559 enemyTypes = new List<Type>();
1560 foreach (string n in EnemyNames)
1561 {
1562 Type t = AccessTools.TypeByName(n);
1563 if (t != null) enemyTypes.Add(t);
1564 }
1565 }
1566 Vector2 me = b.transform.position;
1567 foreach (Type t in enemyTypes)
1568 {
1569 foreach (Object o in Object.FindObjectsOfType(t))
1570 {
1571 Component c = o as Component;
1572 if (c == null) continue;
1573 BuildingEntity be = c.GetComponent<BuildingEntity>();
1574 if (be != null && be.health < 0.5f) continue;
1575 if (Vector2.Distance(me, c.transform.position) < r) return "an enemy is nearby";
1576 }
1577 }
1578 foreach (TraderScript t in Object.FindObjectsOfType<TraderScript>())
1579 if (t != null && t.hostile && Vector2.Distance(me, t.transform.position) < r) return "a hostile survivor is nearby";
1580 }
1581 return null;
1582 }
1583
1584 private const float BlastRadius = 20f;
1585 private static readonly FieldInfo GrabBody = AccessTools.Field(typeof(GrabberPlant), "grabBody");
1586 private static readonly FieldInfo SuckLimb = AccessTools.Field(typeof(BloodSuckerScript), "limb");
1587 private static readonly FieldInfo MinePressed = AccessTools.Field(typeof(MineScript), "pressed");
1588 private static readonly FieldInfo MineExploded = AccessTools.Field(typeof(MineScript), "exploded");
1589 private static readonly FieldInfo CrystalEffects = AccessTools.Field(typeof(CrystalBehaviour), "effects");
1590 private static readonly Type UnstableType = AccessTools.TypeByName("CrystalUnstable");
1591 private static readonly FieldInfo UnstableTimer = UnstableType != null ? AccessTools.Field(UnstableType, "timerStarted") : null;
1592
1593 private static string Danger(WorldGeneration w, Body b)
1594 {
1595 if (w.earthquakeTime > 0f || w.earthquakeIntensity > 0.02f) return "an earthquake is happening";
1596 RadiationLine line = RadiationLine.line;
1597 if (line != null && line.active && b.transform.position.y > line.transform.position.y - 30f) return "the radiation line is too close";
1598 if (w.fungusRainIntensity > 0.15f) return "fungal rain is falling";
1599 EndLabScript lab = Object.FindObjectOfType<EndLabScript>();
1600 if (lab != null && lab.doTimer) return "the escape countdown is running";
1601 if (b.bloodOxygen < 80f) return "you can't breathe properly";
1602 if (b.temperature < 34f) return "you're freezing";
1603 if (b.temperature > 40f) return "you're overheating";
1604 if (b.limbs != null)
1605 foreach (Limb l in b.limbs)
1606 if (l != null && !l.dismembered && l.totalBleedAmount > 25f) return "you're bleeding badly, treat your wounds first";
1607
1608 Vector2 me = b.transform.position;
1609 foreach (BearTrap t in Object.FindObjectsOfType<BearTrap>())
1610 if (t != null && t.caughtLimb != null && t.caughtLimb.body == b) return "you're caught in a bear trap";
1611 if (GrabBody != null)
1612 foreach (GrabberPlant g in Object.FindObjectsOfType<GrabberPlant>())
1613 {
1614 Rigidbody2D gb = g != null ? GrabBody.GetValue(g) as Rigidbody2D : null;
1615 if (gb != null && gb.GetComponentInParent<Body>() == b) return "a grabber plant has you";
1616 }
1617 if (SuckLimb != null)
1618 foreach (BloodSuckerScript s in Object.FindObjectsOfType<BloodSuckerScript>())
1619 {
1620 Limb l = s != null ? SuckLimb.GetValue(s) as Limb : null;
1621 if (l != null && l.body == b) return "a bloodsucker is attached to you";
1622 }
1623 if (MinePressed != null && MineExploded != null)
1624 foreach (MineScript m in Object.FindObjectsOfType<MineScript>())
1625 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";
1626 foreach (CustomItemBehaviour c in Object.FindObjectsOfType<CustomItemBehaviour>())
1627 if (c != null && c.IsInvoking("DynamiteExplode") && Vector2.Distance(me, c.transform.position) < BlastRadius) return "lit dynamite is nearby";
1628 if (CrystalEffects != null && UnstableTimer != null)
1629 foreach (CrystalBehaviour cb in Object.FindObjectsOfType<CrystalBehaviour>())
1630 {
1631 if (cb == null || Vector2.Distance(me, cb.transform.position) >= BlastRadius) continue;
1632 System.Collections.IList fx = CrystalEffects.GetValue(cb) as System.Collections.IList;
1633 if (fx == null) continue;
1634 foreach (object e in fx)
1635 if (e != null && e.GetType() == UnstableType && (bool)UnstableTimer.GetValue(e)) return "a crystal is about to explode";
1636 }
1637 return null;
1638 }
1639 }
1640
1641 internal static class Saver
1642 {
1643 private static readonly FieldInfo BlocksField = AccessTools.Field(typeof(WorldGeneration), "worldBlocks");
1644 private static readonly FieldInfo CorpseComment = AccessTools.Field(typeof(CorpseScript), "didComment");
1645
1646 private static bool warnedNoSlot;
1647
1648 public static int Precheck(bool auto, int slot)
1649 {
1650 if (MultiplayerGuard.Check()) return 0;
1651 string why = Safety.Check();
1652 if (why != null)
1653 {
1654 if (!auto) Runner.Toast("Can't save: " + why + ".", true);
1655 return 0;
1656 }
1657 int target = auto ? Slots.AutoSlot : (slot > 0 ? slot : Slots.PickManualSlot());
1658 if (target <= 0)
1659 {
1660 if (!auto || !warnedNoSlot) Runner.Toast("All save slots are full. Pause and click Save to pick a slot.", true);
1661 if (auto) warnedNoSlot = true;
1662 return 0;
1663 }
1664 warnedNoSlot = false;
1665 return target;
1666 }
1667
1668 public static bool Write(bool auto, int target)
1669 {
1670 try
1671 {
1672 WorldGeneration w = WorldGeneration.world;
1673 SaveSystem.SaveGame();
1674 JObject j = JObject.Parse(SaveSystem.Unzip(File.ReadAllBytes(Paths.Save)));
1675 j["biome"] = w.biomeDepth;
1676 byte[] bytes = SaveSystem.Zip(j.ToString(Formatting.None));
1677 File.WriteAllBytes(Paths.Save, bytes);
1678
1679 Snapshot s = new Snapshot();
1680 s.SaveBytes = bytes;
1681 s.Hash = Snapshot.HashOf(bytes);
1682 ushort[,] blocks = (ushort[,])BlocksField.GetValue(w);
1683 s.W = blocks.GetLength(0);
1684 s.H = blocks.GetLength(1);
1685 s.Blocks = (ushort[,])blocks.Clone();
1686 byte[,] fl = FluidManager.main.fluid;
1687 s.Fluid = (fl != null && fl.GetLength(0) == s.W && fl.GetLength(1) == s.H) ? (byte[,])fl.Clone() : new byte[s.W, s.H];
1688 s.Meta = CaptureMeta(w);
1689 if (string.IsNullOrEmpty(Slots.CurrentRun)) Slots.CurrentRun = Guid.NewGuid().ToString("N");
1690 s.Meta["run"] = Slots.CurrentRun;
1691 s.Write(Paths.Snap);
1692 try
1693 {
1694 float rt = j["runTime"] != null ? (float)j["runTime"] : 0f;
1695 Slots.Store(s, target, auto, w.biomeDepth + 1, rt, PlayerCamera.main.body.charType, RunType.Current(), LayerArt.CurrentIndex(w));
1696 if (target != Slots.AutoSlot) Slots.CurrentSlot = target;
1697 }
1698 catch (Exception e) { Plugin.Log.LogError("Couldn't write the save slot: " + e); }
1699 Plugin.Log.LogInfo((auto ? "Auto-saved" : "Saved") + " layer " + (w.biomeDepth + 1) + " to " + Slots.Name(target) + " with " + ((JArray)s.Meta["objs"]).Count + " world objects.");
1700 Runner.ResetAuto();
1701 return true;
1702 }
1703 catch (Exception e)
1704 {
1705 Plugin.Log.LogError("Save failed: " + e);
1706 Runner.Toast("Save failed, see BepInEx\\LogOutput.log.", true);
1707 return false;
1708 }
1709 }
1710
1711 private static JObject CaptureMeta(WorldGeneration w)
1712 {
1713 Body b = PlayerCamera.main.body;
1714 JObject m = new JObject();
1715 m["ver"] = Plugin.Version;
1716 m["depth"] = w.biomeDepth;
1717 m["px"] = b.transform.position.x;
1718 m["py"] = b.transform.position.y;
1719 m["right"] = b.isRight;
1720 m["layerTime"] = w.layerTimeSpent;
1721 m["fog"] = w.fogAmount;
1722 m["rain"] = w.skyMaterial != null ? w.skyMaterial.GetFloat("_RainIntensity") : 0f;
1723 int mod = -1;
1724 foreach (LayerModifier lm in LayerModifier.availableModifiers)
1725 if (lm.active) { mod = lm.modifierIndex; break; }
1726 m["mod"] = mod;
1727 Merc.Capture(w, m);
1728 Lights.CaptureBody(b, m);
1729
1730 JArray objs = new JArray();
1731 Transform bodyT = b.transform;
1732 foreach (BuildingEntity be in Object.FindObjectsOfType<BuildingEntity>())
1733 {
1734 try
1735 {
1736 if (be == null || Under(be.transform, bodyT) || HasOwner(be.transform)) continue;
1737 if (be.health < 0.5f) continue;
1738 objs.Add(CaptureBuilding(be));
1739 }
1740 catch (Exception e) { Plugin.Log.LogWarning("Skipped " + be.name + ": " + e.Message); }
1741 }
1742 foreach (Item it in Item.allItems.ToArray())
1743 {
1744 try
1745 {
1746 if (it == null || string.IsNullOrEmpty(it.id)) continue;
1747 Transform p = it.transform.parent;
1748 if (p != null && !p.name.StartsWith("DOSPAWN")) continue;
1749 if (Under(it.transform, bodyT)) continue;
1750 objs.Add(CaptureItem(it));
1751 }
1752 catch (Exception e) { Plugin.Log.LogWarning("Skipped " + it.name + ": " + e.Message); }
1753 }
1754 List<GameObject> spawns = new List<GameObject>();
1755 foreach (GameObject g in SceneManager.GetActiveScene().GetRootGameObjects())
1756 if (g.name.StartsWith("DOSPAWN")) spawns.Add(g);
1757 if (w.worldGrid != null)
1758 foreach (Transform t in w.worldGrid.transform)
1759 if (t.name.StartsWith("DOSPAWN")) spawns.Add(t.gameObject);
1760 foreach (GameObject g in spawns)
1761 {
1762 try
1763 {
1764 string res = Prefabs.ForSpawn(g);
1765 if (res == null) continue;
1766 JObject o = Pose(g.transform);
1767 o["k"] = "spawn";
1768 o["res"] = res;
1769 o["tm"] = g.GetComponent<Tilemap>() != null;
1770 objs.Add(o);
1771 }
1772 catch (Exception e) { Plugin.Log.LogWarning("Skipped " + g.name + ": " + e.Message); }
1773 }
1774 m["objs"] = objs;
1775 return m;
1776 }
1777
1778 private static bool Under(Transform t, Transform root)
1779 {
1780 for (Transform c = t; c != null; c = c.parent) if (c == root) return true;
1781 return false;
1782 }
1783
1784 private static bool HasOwner(Transform t)
1785 {
1786 for (Transform c = t.parent; c != null; c = c.parent)
1787 if (c.GetComponent<BuildingEntity>() != null || c.GetComponent<Item>() != null) return true;
1788 return false;
1789 }
1790
1791 private static JObject Pose(Transform t)
1792 {
1793 JObject o = new JObject();
1794 o["x"] = t.position.x;
1795 o["y"] = t.position.y;
1796 o["rz"] = t.eulerAngles.z;
1797 o["sx"] = t.localScale.x;
1798 o["sy"] = t.localScale.y;
1799 return o;
1800 }
1801
1802 private static JObject CaptureItem(Item it)
1803 {
1804 JObject o = Pose(it.transform);
1805 o["k"] = "item";
1806 o["res"] = it.id;
1807 o["cond"] = it.condition;
1808 o["fav"] = it.favourited;
1809 o["label"] = it.label;
1810 o["sw"] = it.colorSwatch;
1811 string c = Comps.Capture(it.gameObject);
1812 if (c != null) o["comps"] = c;
1813 if (it.transform.parent == null && it.GetComponent<ItemLock>() != null) o["lock"] = true;
1814 int ls = Lights.State(it);
1815 if (ls != 0) o["light"] = ls;
1816 if (it.GetComponent<Container>() != null)
1817 {
1818 JArray kids = new JArray();
1819 foreach (Transform t in it.transform)
1820 {
1821 Item k = t.GetComponent<Item>();
1822 if (k != null && !string.IsNullOrEmpty(k.id)) kids.Add(CaptureItem(k));
1823 }
1824 o["kids"] = kids;
1825 }
1826 return o;
1827 }
1828
1829 private static JObject CaptureBuilding(BuildingEntity be)
1830 {
1831 JObject o = Pose(be.transform);
1832 o["k"] = "build";
1833 o["res"] = Prefabs.ForBuilding(be.gameObject);
1834 o["hp"] = be.health;
1835 o["bx"] = be.blockPlacedOn.x;
1836 o["by"] = be.blockPlacedOn.y;
1837 o["rg"] = be.requireGround;
1838 string c = Comps.Capture(be.gameObject);
1839 if (c != null) o["comps"] = c;
1840 JObject cry = Crystals.Capture(be, (string)o["res"]);
1841 if (cry != null) o["cry"] = cry;
1842 Veins.Capture(be.gameObject, o);
1843 TraderScript tr = be.GetComponent<TraderScript>();
1844 if (tr != null)
1845 {
1846 JObject t = new JObject();
1847 t["char"] = tr.character;
1848 t["vg"] = tr.valueGiven;
1849 t["tvg"] = tr.totalValueGiven;
1850 t["rep"] = tr.reputation;
1851 t["host"] = tr.hostility;
1852 t["conv"] = tr.startedConvo;
1853 JArray items = new JArray();
1854 if (tr.items != null)
1855 {
1856 foreach (TraderItem ti in tr.items)
1857 {
1858 JObject x = new JObject();
1859 x["id"] = ti.id;
1860 x["b"] = ti.bought;
1861 x["v"] = ti.value;
1862 x["p"] = Convert.ToInt32(ti.preference);
1863 items.Add(x);
1864 }
1865 }
1866 t["items"] = items;
1867 o["trader"] = t;
1868 }
1869 CorpseScript cs = be.GetComponent<CorpseScript>();
1870 if (cs != null && CorpseComment != null) o["seen"] = (bool)CorpseComment.GetValue(cs);
1871 return o;
1872 }
1873 }
1874
1875 internal class Spawned
1876 {
1877 public GameObject Go;
1878 public JObject Data;
1879 }
1880
1881 internal static class Loader
1882 {
1883 public static Snapshot Pending;
1884 public static bool Restoring;
1885 public static bool InStart;
1886 public static float QuietUntil;
1887 private static readonly FieldInfo BlocksField = AccessTools.Field(typeof(WorldGeneration), "worldBlocks");
1888 private static readonly FieldInfo HealthField = AccessTools.Field(typeof(BuildingEntity), "_health");
1889 private static readonly FieldInfo CorpseComment = AccessTools.Field(typeof(CorpseScript), "didComment");
1890 private static readonly HashSet<int> allowed = new HashSet<int>();
1891
1892 public static bool Quiet { get { return Restoring || Time.realtimeSinceStartup < QuietUntil; } }
1893
1894 public static void CheckSave()
1895 {
1896 Pending = null;
1897 if (MultiplayerGuard.Check()) return;
1898 try
1899 {
1900 if (!SaveSystem.loadedRun || !File.Exists(Paths.Save) || !File.Exists(Paths.Snap)) return;
1901 string h = Snapshot.HashOf(File.ReadAllBytes(Paths.Save));
1902 Snapshot s = Snapshot.Read(Paths.Snap);
1903 if (s != null && s.Hash == h)
1904 {
1905 Pending = s;
1906 if (s.Meta["run"] != null) Slots.CurrentRun = (string)s.Meta["run"];
1907 Slots.CurrentSlot = Slots.ManualFor(Slots.FindByHash(s.Hash), Slots.CurrentRun);
1908 Plugin.Log.LogInfo("Save Anywhere save found for layer " + (s.Depth + 1) + ", restoring it.");
1909 }
1910 }
1911 catch (Exception e)
1912 {
1913 Pending = null;
1914 Plugin.Log.LogError("Couldn't read the Save Anywhere save: " + e);
1915 }
1916 }
1917
1918 public static void KeepSave()
1919 {
1920 try
1921 {
1922 if (Pending != null && !File.Exists(Paths.Save)) File.WriteAllBytes(Paths.Save, Pending.SaveBytes);
1923 }
1924 catch (Exception e) { Plugin.Log.LogError("Couldn't keep the save: " + e); }
1925 }
1926
1927 public static bool Matches(WorldGeneration w)
1928 {
1929 ushort[,] blocks = (ushort[,])BlocksField.GetValue(w);
1930 if (blocks == null || blocks.GetLength(0) != Pending.W || blocks.GetLength(1) != Pending.H) return false;
1931 return Pending.Depth == w.biomeDepth;
1932 }
1933
1934 private static IEnumerator Call(WorldGeneration w, string name)
1935 {
1936 return (IEnumerator)AccessTools.Method(typeof(WorldGeneration), name).Invoke(w, null);
1937 }
1938
1939 private static void Try(string what, Action a)
1940 {
1941 try { a(); }
1942 catch (Exception e) { Plugin.Log.LogError("Restore step '" + what + "' failed: " + e); }
1943 }
1944
1945 public static IEnumerator Restore(WorldGeneration w)
1946 {
1947 Snapshot s = Pending;
1948 Restoring = true;
1949 allowed.Clear();
1950 w.loadingObject.SetActive(true);
1951 w.generatingWorld = true;
1952 yield return Call(w, "WorldPreprocess");
1953 yield return Call(w, "WorldCreateBackground");
1954 w.SetLoadingText("gencreatingcolliders");
1955 yield return null;
1956 Try("terrain", () => ApplyTerrain(w, s, true));
1957 Try("player", () => PlacePlayer(s));
1958 yield return null;
1959 List<Spawned> spawned = new List<Spawned>();
1960 Try("objects", () => SpawnAll(w, s, spawned));
1961 yield return null;
1962 yield return null;
1963 Try("object state", () => PostStart(spawned));
1964 Try("cleanup", () => Cleanup());
1965 Body b = PlayerCamera.main.body;
1966 float hap = b.happiness, caf = b.caffeinated, hear = b.hearingLoss, hun = b.hunger, thi = b.thirst;
1967 yield return Call(w, "FinishWorldGeneration");
1968 Try("cleanup", () => Cleanup());
1969 Try("pod effects", () => RemovePodEffects());
1970 Try("terrain", () => ApplyTerrain(w, s, false));
1971 Try("fluid", () => ApplyFluid(s));
1972 Try("stats", () =>
1973 {
1974 b.happiness = hap; b.caffeinated = caf; b.hearingLoss = hear; b.hunger = hun; b.thirst = thi;
1975 w.layerTimeSpent = (float)s.Meta["layerTime"];
1976 w.SetFog((float)s.Meta["fog"]);
1977 if (w.skyMaterial != null) w.skyMaterial.SetFloat("_RainIntensity", (float)s.Meta["rain"]);
1978 });
1979 Try("veins", () => Veins.Repair());
1980 Try("merc run", () => Merc.Apply(w, s));
1981 Try("lights", () => Lights.ApplyBody(b, s));
1982 Try("player", () => PlacePlayer(s));
1983 Restoring = false;
1984 QuietUntil = Time.realtimeSinceStartup + 3f;
1985 Pending = null;
1986 allowed.Clear();
1987 Plugin.Log.LogInfo("Restored layer " + (s.Depth + 1) + " (" + spawned.Count + " objects).");
1988 Runner.Toast("Save loaded.", false);
1989 Runner.JustRestored = true;
1990 Runner.ResetAuto();
1991 }
1992
1993 private static void ApplyTerrain(WorldGeneration w, Snapshot s, bool force)
1994 {
1995 ushort[,] blocks = (ushort[,])BlocksField.GetValue(w);
1996 if (!force)
1997 {
1998 bool same = true;
1999 for (int x = 0; x < s.W && same; x++)
2000 for (int y = 0; y < s.H; y++)
2001 if (blocks[x, y] != s.Blocks[x, y]) { same = false; break; }
2002 if (same) return;
2003 }
2004 Buffer.BlockCopy(s.Blocks, 0, blocks, 0, s.W * s.H * 2);
2005 w.UpdateWorld();
2006 }
2007
2008 private static void ApplyFluid(Snapshot s)
2009 {
2010 byte[,] fl = FluidManager.main.fluid;
2011 if (fl == null || fl.GetLength(0) != s.W || fl.GetLength(1) != s.H) return;
2012 Buffer.BlockCopy(s.Fluid, 0, fl, 0, s.W * s.H);
2013 }
2014
2015 private static void PlacePlayer(Snapshot s)
2016 {
2017 Body b = PlayerCamera.main.body;
2018 Vector3 pos = new Vector3((float)s.Meta["px"], (float)s.Meta["py"], b.transform.position.z);
2019 b.transform.position = pos;
2020 if (b.rb != null) b.rb.velocity = Vector2.zero;
2021 Transform cam = PlayerCamera.main.transform;
2022 cam.position = new Vector3(pos.x, pos.y, cam.position.z);
2023 }
2024
2025 private static Vector3 Pos(JObject o) { return new Vector3((float)o["x"], (float)o["y"], 0f); }
2026 private static Quaternion Rot(JObject o) { return Quaternion.Euler(0f, 0f, (float)o["rz"]); }
2027
2028 private static void SetPose(GameObject g, JObject o)
2029 {
2030 Vector3 sc = g.transform.localScale;
2031 g.transform.localScale = new Vector3((float)o["sx"], (float)o["sy"], sc.z);
2032 }
2033
2034 private static void SpawnAll(WorldGeneration w, Snapshot s, List<Spawned> spawned)
2035 {
2036 JArray objs = (JArray)s.Meta["objs"];
2037 int failed = 0;
2038 foreach (JToken tok in objs)
2039 {
2040 JObject o = (JObject)tok;
2041 try
2042 {
2043 string k = (string)o["k"];
2044 GameObject g = null;
2045 if (k == "item") g = SpawnItem(o);
2046 else if (k == "build") g = SpawnBuilding(w, o);
2047 else if (k == "spawn") g = SpawnSpawn(w, o);
2048 if (g == null) { failed++; continue; }
2049 allowed.Add(g.GetInstanceID());
2050 Spawned sp = new Spawned();
2051 sp.Go = g;
2052 sp.Data = o;
2053 spawned.Add(sp);
2054 }
2055 catch (Exception e)
2056 {
2057 failed++;
2058 Plugin.Log.LogWarning("Couldn't restore " + (string)o["res"] + ": " + e.Message);
2059 }
2060 }
2061 if (failed > 0) Plugin.Log.LogWarning(failed + " saved objects couldn't be restored.");
2062 }
2063
2064 private static GameObject SpawnItem(JObject o)
2065 {
2066 Object pf = Resources.Load((string)o["res"]);
2067 if (pf == null) return null;
2068 GameObject g = Object.Instantiate(pf, Pos(o), Rot(o)) as GameObject;
2069 if (g == null) return null;
2070 SetPose(g, o);
2071 ApplyItem(g, o);
2072 return g;
2073 }
2074
2075 private static void ApplyItem(GameObject g, JObject o)
2076 {
2077 Item it = g.GetComponent<Item>();
2078 if (it == null) return;
2079 it.condition = (float)o["cond"];
2080 it.favourited = (bool)o["fav"];
2081 it.label = (string)o["label"];
2082 it.colorSwatch = (int)o["sw"];
2083 Comps.Apply(g, (string)o["comps"]);
2084 if (o["lock"] != null && (bool)o["lock"] && g.GetComponent<ItemLock>() == null) g.AddComponent<ItemLock>();
2085 if (o["light"] != null) Lights.Set(it, (int)o["light"]);
2086 }
2087
2088 private static void FillContainer(GameObject g, JObject o)
2089 {
2090 JArray kids = o["kids"] as JArray;
2091 if (kids == null) return;
2092 Container c = g.GetComponent<Container>();
2093 if (c == null) return;
2094 List<GameObject> old = new List<GameObject>();
2095 foreach (Transform t in g.transform)
2096 if (t.GetComponent<Item>() != null) old.Add(t.gameObject);
2097 foreach (GameObject x in old) Object.Destroy(x);
2098 foreach (JToken tok in kids)
2099 {
2100 JObject ko = (JObject)tok;
2101 try
2102 {
2103 Object pf = Resources.Load((string)ko["res"]);
2104 if (pf == null) continue;
2105 GameObject kg = Object.Instantiate(pf, g.transform.position, Quaternion.identity) as GameObject;
2106 if (kg == null) continue;
2107 ApplyItem(kg, ko);
2108 c.LoadItem(kg.GetComponent<Item>());
2109 FillContainer(kg, ko);
2110 }
2111 catch (Exception e) { Plugin.Log.LogWarning("Couldn't restore container item " + (string)ko["res"] + ": " + e.Message); }
2112 }
2113 }
2114
2115 private static GameObject SpawnBuilding(WorldGeneration w, JObject o)
2116 {
2117 GameObject pf = Prefabs.Load((string)o["res"]);
2118 if (pf == null) return null;
2119 GameObject g = Object.Instantiate(pf, Pos(o), Rot(o));
2120 if (g.GetComponent<Tilemap>() != null && w.worldGrid != null) g.transform.SetParent(w.worldGrid.transform, true);
2121 SetPose(g, o);
2122 BuildingEntity be = g.GetComponent<BuildingEntity>();
2123 if (be != null)
2124 {
2125 be.blockPlacedOn = new Vector2Int((int)o["bx"], (int)o["by"]);
2126 if (HealthField != null) HealthField.SetValue(be, (float)o["hp"]);
2127 if (be.requireGround && w.ChunkUpdated != null)
2128 {
2129 int cx = be.blockPlacedOn.x / WorldGeneration.CHUNKSIZE, cy = be.blockPlacedOn.y / WorldGeneration.CHUNKSIZE;
2130 if (cx >= 0 && cy >= 0 && cx < w.ChunkUpdated.GetLength(0) && cy < w.ChunkUpdated.GetLength(1))
2131 w.ChunkUpdated[cx, cy].AddListener(be.CheckSeating);
2132 }
2133 }
2134 ApplyTrader(g, o);
2135 try
2136 {
2137 Crystals.Apply(g, o["cry"] as JObject);
2138 if (be != null && HealthField != null) HealthField.SetValue(be, (float)o["hp"]);
2139 }
2140 catch (Exception e) { Plugin.Log.LogWarning("Crystal restore failed for " + g.name + ": " + e.Message); }
2141 try { Veins.Apply(g, o); }
2142 catch (Exception e) { Plugin.Log.LogWarning("Vein restore failed for " + g.name + ": " + e.Message); }
2143 return g;
2144 }
2145
2146 private static GameObject SpawnSpawn(WorldGeneration w, JObject o)
2147 {
2148 GameObject pf = Prefabs.Load((string)o["res"]);
2149 if (pf == null) return null;
2150 GameObject g = Object.Instantiate(pf, Pos(o), Rot(o));
2151 SetPose(g, o);
2152 if ((bool)o["tm"] && w.worldGrid != null) g.transform.SetParent(w.worldGrid.transform, true);
2153 List<GameObject> strip = new List<GameObject>();
2154 foreach (Item it in g.GetComponentsInChildren<Item>(true)) strip.Add(it.gameObject);
2155 foreach (BuildingEntity be in g.GetComponentsInChildren<BuildingEntity>(true)) strip.Add(be.gameObject);
2156 foreach (GameObject x in strip) if (x != g) Object.Destroy(x);
2157 return g;
2158 }
2159
2160 private static void ApplyTrader(GameObject g, JObject o)
2161 {
2162 JObject t = o["trader"] as JObject;
2163 if (t == null) return;
2164 TraderScript tr = g.GetComponent<TraderScript>();
2165 if (tr == null) return;
2166 tr.character = (int)t["char"];
2167 tr.valueGiven = (int)t["vg"];
2168 tr.totalValueGiven = (int)t["tvg"];
2169 tr.reputation = (float)t["rep"];
2170 tr.hostility = (float)t["host"];
2171 tr.startedConvo = (bool)t["conv"];
2172 List<TraderItem> list = new List<TraderItem>();
2173 foreach (JToken tok in (JArray)t["items"])
2174 {
2175 TraderItem ti = new TraderItem();
2176 ti.id = (string)tok["id"];
2177 ti.bought = (bool)tok["b"];
2178 ti.value = (int)tok["v"];
2179 ti.preference = (TraderScript.TraderItemPreference)Enum.ToObject(typeof(TraderScript.TraderItemPreference), (int)tok["p"]);
2180 list.Add(ti);
2181 }
2182 tr.items = list;
2183 }
2184
2185 private static void PostStart(List<Spawned> spawned)
2186 {
2187 foreach (Spawned sp in spawned)
2188 {
2189 if (sp.Go == null) continue;
2190 try
2191 {
2192 string k = (string)sp.Data["k"];
2193 if (k == "item")
2194 {
2195 FillContainer(sp.Go, sp.Data);
2196 Rigidbody2D rb = sp.Go.GetComponent<Rigidbody2D>();
2197 if (rb != null && rb.bodyType != RigidbodyType2D.Static) rb.velocity = Vector2.zero;
2198 }
2199 else if (k == "build")
2200 {
2201 BuildingEntity be = sp.Go.GetComponent<BuildingEntity>();
2202 if (be != null && HealthField != null) HealthField.SetValue(be, (float)sp.Data["hp"]);
2203 Comps.Apply(sp.Go, (string)sp.Data["comps"]);
2204 ApplyTrader(sp.Go, sp.Data);
2205 CorpseScript cs = sp.Go.GetComponent<CorpseScript>();
2206 if (cs != null && CorpseComment != null && sp.Data["seen"] != null) CorpseComment.SetValue(cs, (bool)sp.Data["seen"]);
2207 }
2208 }
2209 catch (Exception e) { Plugin.Log.LogWarning("Couldn't finish restoring " + sp.Go.name + ": " + e.Message); }
2210 }
2211 }
2212
2213 private static bool IsAllowed(Transform t)
2214 {
2215 for (Transform c = t; c != null; c = c.parent) if (allowed.Contains(c.gameObject.GetInstanceID())) return true;
2216 return false;
2217 }
2218
2219 private static void Cleanup()
2220 {
2221 Transform bodyT = PlayerCamera.main.body.transform;
2222 int n = 0;
2223 foreach (BuildingEntity be in Object.FindObjectsOfType<BuildingEntity>())
2224 {
2225 if (be == null) continue;
2226 if (IsUnder(be.transform, bodyT) || IsAllowed(be.transform)) continue;
2227 Object.Destroy(be.gameObject);
2228 n++;
2229 }
2230 foreach (Item it in Item.allItems.ToArray())
2231 {
2232 if (it == null) continue;
2233 Transform p = it.transform.parent;
2234 if (p != null && !p.name.StartsWith("DOSPAWN")) continue;
2235 if (IsUnder(it.transform, bodyT) || IsAllowed(it.transform)) continue;
2236 Object.Destroy(it.gameObject);
2237 n++;
2238 }
2239 if (n > 0) Plugin.Log.LogInfo("Removed " + n + " objects that weren't in the save.");
2240 }
2241
2242 private static bool IsUnder(Transform t, Transform root)
2243 {
2244 for (Transform c = t; c != null; c = c.parent) if (c == root) return true;
2245 return false;
2246 }
2247
2248 private static void RemovePodEffects()
2249 {
2250 foreach (GameObject g in SceneManager.GetActiveScene().GetRootGameObjects())
2251 if (g.name.StartsWith("ExplosionParticle") && !allowed.Contains(g.GetInstanceID())) Object.Destroy(g);
2252 }
2253 }
2254
2255 [HarmonyPatch(typeof(SaveSystem), "TryLoadGame")]
2256 internal static class TryLoadPatch
2257 {
2258 private static void Prefix() { Loader.CheckSave(); }
2259 private static void Postfix() { Loader.KeepSave(); }
2260 }
2261
2262 internal static class RunEnd
2263 {
2264 public static bool Ended;
2265
2266 public static void DeleteSaves(string why)
2267 {
2268 Ended = true;
2269 try { if (!string.IsNullOrEmpty(Slots.CurrentRun)) Slots.DeleteRun(Slots.CurrentRun); }
2270 catch (Exception e) { Plugin.Log.LogError("Couldn't delete the save slots: " + e.Message); }
2271 try
2272 {
2273 bool any = false;
2274 if (File.Exists(Paths.Save)) { File.Delete(Paths.Save); any = true; }
2275 if (File.Exists(Paths.Snap)) { File.Delete(Paths.Snap); any = true; }
2276 if (any) Plugin.Log.LogInfo("Run ended (" + why + "), save deleted.");
2277 }
2278 catch (Exception e) { Plugin.Log.LogError("Couldn't delete the save: " + e.Message); }
2279 }
2280 }
2281
2282 [HarmonyPatch(typeof(PlayerCamera), "EndSequence")]
2283 internal static class EndSequencePatch
2284 {
2285 private static void Prefix(int type)
2286 {
2287 if (type == 0)
2288 {
2289 RunEnd.Ended = true;
2290 Plugin.Log.LogInfo("Died. Your last save was kept, Continue to try again.");
2291 return;
2292 }
2293 RunEnd.DeleteSaves("ending");
2294 }
2295 }
2296
2297 [HarmonyPatch(typeof(PauseHandler), "TryQuit")]
2298 internal static class GiveUpPatch
2299 {
2300 private static void Postfix(PauseHandler __instance)
2301 {
2302 if (WorldGeneration.world != null && WorldGeneration.world.biomeOverride != WorldGeneration.OverrideSceneType.None) return;
2303 if (Traverse.Create(__instance).Field("timesQuitPressed").GetValue<int>() >= 4) RunEnd.DeleteSaves("gave up");
2304 }
2305 }
2306
2307 [HarmonyPatch(typeof(WorldGeneration), "Start")]
2308 internal static class WorldStartPatch
2309 {
2310 private static void Prefix()
2311 {
2312 Loader.InStart = true;
2313 RunEnd.Ended = false;
2314 if (!SaveSystem.loadedRun)
2315 {
2316 Slots.CurrentRun = Guid.NewGuid().ToString("N");
2317 Slots.CurrentSlot = 0;
2318 }
2319 else if (Loader.Pending == null) Slots.CurrentSlot = 0;
2320 Runner.ResetAuto();
2321 }
2322 private static Exception Finalizer(Exception __exception) { Loader.InStart = false; return __exception; }
2323 }
2324
2325 [HarmonyPatch(typeof(WorldGeneration), "GetRunSettingBool")]
2326 internal static class StartBonusPatch
2327 {
2328 private static readonly string[] Keys = { "permanentaddiction", "mindwiped", "zeroskills", "blind", "amputee" };
2329
2330 private static bool Prefix(string name, ref bool __result)
2331 {
2332 if (Loader.InStart && Loader.Pending != null && Array.IndexOf(Keys, name) >= 0)
2333 {
2334 __result = false;
2335 return false;
2336 }
2337 return true;
2338 }
2339 }
2340
2341 [HarmonyPatch(typeof(WorldGeneration), "GenerateWorld")]
2342 internal static class GenerateWorldPatch
2343 {
2344 private static bool Prefix(WorldGeneration __instance, ref IEnumerator __result)
2345 {
2346 if (Loader.Pending == null) return true;
2347 bool ok = false;
2348 try { ok = Loader.Matches(__instance); }
2349 catch (Exception e) { Plugin.Log.LogError("Save check failed: " + e); }
2350 if (!ok)
2351 {
2352 Plugin.Log.LogWarning("The Save Anywhere save doesn't match this layer, generating normally.");
2353 Loader.Pending = null;
2354 return true;
2355 }
2356 __result = Loader.Restore(__instance);
2357 return false;
2358 }
2359 }
2360
2361 [HarmonyPatch(typeof(WorldGeneration), "DistributeMiniBarrels")]
2362 internal static class MiniBarrelPatch
2363 {
2364 private static bool Prefix() { return !Loader.Restoring; }
2365 }
2366
2367 [HarmonyPatch(typeof(WorldGeneration), "ApplyLayerModifiers")]
2368 internal static class LayerModifierPatch
2369 {
2370 private static bool Prefix(WorldGeneration __instance)
2371 {
2372 if (!Loader.Restoring || Loader.Pending == null) return true;
2373 int idx = (int)Loader.Pending.Meta["mod"];
2374 if (idx >= 0)
2375 {
2376 LayerModifier m = LayerModifier.availableModifiers.FirstOrDefault(x => x.modifierIndex == idx);
2377 if (m != null)
2378 {
2379 m.Initialize(__instance);
2380 m.active = true;
2381 Traverse t = Traverse.Create(__instance);
2382 t.Field("layerPrefix").SetValue(Locale.GetOther("layermodifier" + idx));
2383 t.Field("layerDescription").SetValue(Locale.GetOther("layermodifier" + idx + "dsc"));
2384 }
2385 }
2386 return false;
2387 }
2388 }
2389
2390 [HarmonyPatch]
2391 internal static class TalkPatch
2392 {
2393 private static IEnumerable<MethodBase> TargetMethods()
2394 {
2395 return AccessTools.GetDeclaredMethods(typeof(Talker)).Where(m => m.Name == "Talk").Cast<MethodBase>();
2396 }
2397
2398 private static bool Prefix() { return !Loader.Quiet; }
2399 }
2400
2401 [HarmonyPatch(typeof(Sound), "Play", new Type[] { typeof(string), typeof(Vector2), typeof(bool), typeof(bool), typeof(Transform), typeof(float), typeof(float), typeof(bool), typeof(bool) })]
2402 internal static class PodSoundPatch
2403 {
2404 private static bool Prefix(string clip)
2405 {
2406 return !(Loader.Restoring && clip == "lifePodHit");
2407 }
2408 }
2409
2410 [HarmonyPatch(typeof(PlayerCamera), "LifePodShake")]
2411 internal static class LifePodShakePatch
2412 {
2413 private static bool Prefix() { return !Loader.Quiet; }
2414 }
2415
2416 [HarmonyPatch(typeof(AdaptiveButton), "overlayActive", MethodType.Getter)]
2417 internal static class MenuButtonPatch
2418 {
2419 private static void Postfix(ref bool __result)
2420 {
2421 if (Runner.UiBlocking) __result = true;
2422 }
2423 }
2424
2425 [HarmonyPatch(typeof(PauseHandler), "Start")]
2426 internal static class PauseStartPatch
2427 {
2428 private static void Postfix(PauseHandler __instance)
2429 {
2430 try { PauseRing.Build(__instance); }
2431 catch (Exception e) { Plugin.Log.LogWarning("Couldn't add the pause menu buttons, using the fallback buttons instead: " + e); }
2432 }
2433 }
2434
2435 internal static class PauseRing
2436 {
2437 private static readonly FieldInfo PosField = AccessTools.Field(typeof(PauseHandler), "buttonPos");
2438 private static readonly List<GameObject> made = new List<GameObject>();
2439 private static Sprite saveSpr, quitSpr, autoOnSpr, autoOffSpr;
2440 private static UnityEngine.UI.Image autoImg;
2441 private static UITooltip autoTip;
2442 private static bool lastAuto;
2443 private static bool lastShown = true;
2444 private static bool first = true;
2445
2446 internal static bool Built
2447 {
2448 get
2449 {
2450 for (int i = 0; i < made.Count; i++) if (made[i] != null) return !MultiplayerGuard.Detected;
2451 return false;
2452 }
2453 }
2454
2455 internal static void Build(PauseHandler ph)
2456 {
2457 made.Clear();
2458 autoImg = null;
2459 autoTip = null;
2460 first = true;
2461 lastShown = true;
2462 List<Vector2> pos = PosField == null ? null : PosField.GetValue(ph) as List<Vector2>;
2463 if (ph.buttons == null || ph.buttons.Count == 0 || pos == null || pos.Count != ph.buttons.Count)
2464 {
2465 Plugin.Log.LogWarning("The pause menu layout wasn't what Save Anywhere expected, using the fallback buttons.");
2466 return;
2467 }
2468 RectTransform tpl = ph.buttons[0];
2469 int baseCount = pos.Count;
2470 List<Vector2> shown = new List<Vector2>();
2471 for (int i = 0; i < baseCount; i++) shown.Add(Scale(pos[i], i));
2472 Vector2 left = shown[0], top = shown[0], right = shown[0];
2473 foreach (Vector2 p in shown)
2474 {
2475 if (p.x < left.x) left = p;
2476 if (p.x > right.x) right = p;
2477 if (Mathf.Abs(p.x) < Mathf.Abs(top.x) || (Mathf.Abs(p.x) == Mathf.Abs(top.x) && p.y < top.y)) top = p;
2478 }
2479 Vector2 aL = new Vector2(left.x, -left.y), aT = new Vector2(top.x, -top.y), aR = new Vector2(right.x, -right.y);
2480 if (left.y > 0f || right.y > 0f || top.y > 0f)
2481 {
2482 float r = 0f;
2483 foreach (Vector2 p in shown) r = Mathf.Max(r, p.magnitude);
2484 if (r < 50f) r = 421f;
2485 aL = Spot(r, 125f);
2486 aT = Spot(r, 90f);
2487 aR = Spot(r, 55f);
2488 }
2489 if (saveSpr == null)
2490 {
2491 saveSpr = Icons.Make(0, false);
2492 quitSpr = Icons.Make(1, false);
2493 autoOnSpr = Icons.Make(2, false);
2494 autoOffSpr = Icons.Make(2, true);
2495 }
2496 Add(ph, pos, tpl, "SaveAnywhereAutoSave", Unscale(aL, pos.Count), autoOnSpr, "Auto-save", "", Runner.ClickAuto);
2497 Add(ph, pos, tpl, "SaveAnywhereSave", Unscale(aT, pos.Count), saveSpr, "Save", "Save your game right here, to a slot you pick.", Runner.ClickSave);
2498 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);
2499 if (made.Count > 0)
2500 {
2501 autoImg = made[0].GetComponent<UnityEngine.UI.Image>();
2502 autoTip = made[0].GetComponent<UITooltip>();
2503 Refresh();
2504 }
2505 Plugin.Log.LogInfo("Added " + made.Count + " Save Anywhere buttons to the pause menu.");
2506 }
2507
2508 private static Vector2 Factor(int index)
2509 {
2510 float t = 1f + index * 0.1f;
2511 return new Vector2(0.5f + Utils.OutCubic(t) * 0.5f, 0.5f + Utils.InOutCubic(t) * 0.5f);
2512 }
2513
2514 private static Vector2 Scale(Vector2 p, int index)
2515 {
2516 Vector2 f = Factor(index);
2517 return new Vector2(p.x * f.x, p.y * f.y);
2518 }
2519
2520 private static Vector2 Unscale(Vector2 p, int index)
2521 {
2522 Vector2 f = Factor(index);
2523 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);
2524 }
2525
2526 private static Vector2 Spot(float r, float deg)
2527 {
2528 float a = deg * Mathf.Deg2Rad;
2529 return new Vector2(Mathf.Round(Mathf.Cos(a) * r), Mathf.Round(Mathf.Sin(a) * r));
2530 }
2531
2532 private static void Add(PauseHandler ph, List<Vector2> pos, RectTransform tpl, string name, Vector2 at, Sprite spr, string title, string desc, UnityEngine.Events.UnityAction click)
2533 {
2534 GameObject g = Object.Instantiate(tpl.gameObject, tpl.parent, false);
2535 g.name = name;
2536 UITooltip tip = g.GetComponent<UITooltip>();
2537 if (tip != null)
2538 {
2539 tip.skipLocale = true;
2540 tip.localeName = "";
2541 tip.localeDesc = "";
2542 tip.tipName = title;
2543 tip.tipDesc = desc;
2544 }
2545 UnityEngine.UI.Image img = g.GetComponent<UnityEngine.UI.Image>();
2546 if (img != null)
2547 {
2548 img.sprite = spr;
2549 img.color = Color.white;
2550 }
2551 UnityEngine.UI.Button btn = g.GetComponent<UnityEngine.UI.Button>();
2552 if (btn != null)
2553 {
2554 btn.onClick = new UnityEngine.UI.Button.ButtonClickedEvent();
2555 btn.onClick.AddListener(click);
2556 }
2557 RectTransform rt = (RectTransform)g.transform;
2558 rt.localPosition = new Vector3(at.x, at.y, tpl.localPosition.z);
2559 rt.localScale = Vector3.one;
2560 ph.buttons.Add(rt);
2561 pos.Add(at);
2562 made.Add(g);
2563 }
2564
2565 internal static void Refresh()
2566 {
2567 if (made.Count == 0) return;
2568 bool show = !MultiplayerGuard.Detected;
2569 if (show != lastShown)
2570 {
2571 lastShown = show;
2572 foreach (GameObject g in made) if (g != null) g.SetActive(show);
2573 }
2574 if (autoImg == null) return;
2575 bool on = Plugin.AutoSave.Value;
2576 if (!first && on == lastAuto) return;
2577 first = false;
2578 lastAuto = on;
2579 autoImg.sprite = on ? autoOnSpr : autoOffSpr;
2580 autoImg.color = on ? Color.white : new Color(0.6f, 0.6f, 0.6f, 1f);
2581 if (autoTip != null)
2582 {
2583 autoTip.tipName = Runner.AutoLabel();
2584 autoTip.tipDesc = on ? "Click to turn auto-saving off." : "Click to turn auto-saving on.";
2585 }
2586 }
2587 }
2588
2589 internal static class Icons
2590 {
2591 private const int N = 40;
2592 private static Color[] px;
2593
2594 private static void Put(int x, int y, Color c)
2595 {
2596 if (x < 0 || y < 0 || x >= N || y >= N) return;
2597 px[(N - 1 - y) * N + x] = c;
2598 }
2599
2600 private static void Floppy(int ox, int oy, int s)
2601 {
2602 int cut = Mathf.Max(2, s / 6);
2603 int shL = s / 4, shR = (int)(s * 0.7f), shB = (int)(s * 0.34f);
2604 int slL = (int)(s * 0.52f), slR = (int)(s * 0.66f);
2605 int lbL = (int)(s * 0.17f), lbR = s - lbL, lbT = s / 2;
2606 for (int y = 0; y < s; y++)
2607 for (int x = 0; x < s; x++)
2608 {
2609 if (x - (s - 1 - cut) > y) continue;
2610 Color c = Color.white;
2611 if (x >= shL && x < shR && y < shB) c = (x >= slL && x < slR && y >= 1 && y < shB - 1) ? Color.white : Color.black;
2612 if (x >= lbL && x < lbR && y >= lbT && y < s - 1) c = Color.black;
2613 Put(ox + x, oy + y, c);
2614 }
2615 }
2616
2617 internal static Sprite Make(int kind, bool off)
2618 {
2619 px = new Color[N * N];
2620 for (int y = 0; y < N; y++)
2621 for (int x = 0; x < N; x++)
2622 {
2623 float dx = x + 0.5f - N * 0.5f, dy = y + 0.5f - N * 0.5f;
2624 float d = Mathf.Sqrt(dx * dx + dy * dy);
2625 Color c = d > N * 0.5f ? Color.clear : (d > N * 0.5f - 1f ? Color.white : Color.black);
2626 Put(x, y, c);
2627 }
2628 if (kind == 0) Floppy(11, 11, 18);
2629 else if (kind == 1)
2630 {
2631 Floppy(6, 13, 14);
2632 for (int x = 22; x <= 28; x++) { Put(x, 19, Color.white); Put(x, 20, Color.white); }
2633 for (int x = 28; x <= 32; x++)
2634 {
2635 int h = 32 - x;
2636 for (int y = 19 - h; y <= 20 + h; y++) Put(x, y, Color.white);
2637 }
2638 }
2639 else
2640 {
2641 Floppy(9, 9, 16);
2642 for (int y = 19; y <= 36; y++)
2643 for (int x = 19; x <= 36; x++)
2644 {
2645 float dx = x + 0.5f - 27.5f, dy = y + 0.5f - 27.5f;
2646 float d = Mathf.Sqrt(dx * dx + dy * dy);
2647 if (d <= 8f) Put(x, y, Color.black);
2648 if (d <= 7f) Put(x, y, d > 6f ? Color.white : Color.black);
2649 }
2650 for (int y = 23; y <= 27; y++) Put(27, y, Color.white);
2651 for (int x = 27; x <= 30; x++) Put(x, 27, Color.white);
2652 if (off)
2653 {
2654 for (int y = 0; y < N; y++)
2655 for (int x = 0; x < N; x++)
2656 {
2657 if (x < 8 || x > 31 || y < 8 || y > 31) continue;
2658 int k = Mathf.Abs(x - (N - 1 - y));
2659 if (k <= 1) Put(x, y, Color.white);
2660 else if (k == 2) Put(x, y, Color.black);
2661 }
2662 }
2663 }
2664 Texture2D t = new Texture2D(N, N, TextureFormat.RGBA32, false);
2665 t.hideFlags = HideFlags.HideAndDontSave;
2666 t.filterMode = FilterMode.Point;
2667 t.wrapMode = TextureWrapMode.Clamp;
2668 t.SetPixels(px);
2669 t.Apply();
2670 Sprite sp = Sprite.Create(t, new Rect(0f, 0f, N, N), new Vector2(0.5f, 0.5f), 100f / 3f);
2671 sp.hideFlags = HideFlags.HideAndDontSave;
2672 return sp;
2673 }
2674 }
2675
2676 internal static class Floppy
2677 {
2678 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";
2679 private static readonly Color[] SlotColors =
2680 {
2681 new Color32(96, 150, 235, 255), new Color32(235, 90, 90, 255), new Color32(90, 200, 120, 255),
2682 new Color32(240, 200, 70, 255), new Color32(170, 120, 230, 255), new Color32(245, 150, 70, 255),
2683 new Color32(70, 200, 210, 255), new Color32(240, 130, 190, 255), new Color32(170, 215, 80, 255),
2684 new Color32(150, 162, 182, 255)
2685 };
2686 private static Texture2D icon;
2687
2688 public static Texture2D Icon
2689 {
2690 get
2691 {
2692 if (icon != null) return icon;
2693 icon = new Texture2D(2, 2, TextureFormat.RGBA32, false);
2694 ImageConversion.LoadImage(icon, Convert.FromBase64String(IconPng));
2695 icon.filterMode = FilterMode.Point;
2696 icon.wrapMode = TextureWrapMode.Clamp;
2697 icon.hideFlags = HideFlags.HideAndDontSave;
2698 return icon;
2699 }
2700 }
2701
2702 public static Color Tint(int slot, bool empty)
2703 {
2704 if (empty) return new Color(0.45f, 0.47f, 0.5f, 0.5f);
2705 if (slot == Slots.AutoSlot) return new Color32(225, 228, 235, 255);
2706 return SlotColors[(Mathf.Max(1, slot) - 1) % SlotColors.Length];
2707 }
2708
2709 public static void Draw(Rect r, int slot, bool empty)
2710 {
2711 Color old = GUI.color;
2712 GUI.color = Tint(slot, empty);
2713 GUI.DrawTexture(r, Icon);
2714 GUI.color = old;
2715 }
2716
2717 public static void DrawPlain(Rect r)
2718 {
2719 GUI.DrawTexture(r, Icon);
2720 }
2721 }
2722
2723 internal static class SlotScreen
2724 {
2725 public static bool Open;
2726 public static bool Loading;
2727 public static bool SaveMode;
2728 private static bool quitAfter;
2729 private static List<SlotInfo> list = new List<SlotInfo>();
2730 private static string currentHash;
2731 private static int currentSlot;
2732 private static int confirmDelete = -1;
2733 private static int confirmOverwrite = -1;
2734 private static int cloudPanel = -1;
2735 private static string shareCode, shareMsg, shareUntil;
2736 private static int shareSlot = -1;
2737 private static bool codePanel;
2738 private static string codeText = "", codeMsg;
2739 private static string cloudConfirm;
2740 private static GUIStyle cloudSmall, btnSmall, panelText;
2741
2742 public static void OpenForSave(bool quit)
2743 {
2744 Refresh();
2745 SaveMode = true;
2746 quitAfter = quit;
2747 Open = true;
2748 }
2749 private static Texture2D white;
2750 private static GUIStyle title, sub, cardTitle, cardBig, cardText, badge, numStyle, btn, btnDanger, menuBtn;
2751 private static readonly Dictionary<int, Sprite> biomeIcons = new Dictionary<int, Sprite>();
2752
2753 public static void Close()
2754 {
2755 Open = false;
2756 Loading = false;
2757 SaveMode = false;
2758 quitAfter = false;
2759 confirmDelete = -1;
2760 confirmOverwrite = -1;
2761 cloudPanel = -1;
2762 cloudConfirm = null;
2763 }
2764
2765 private static string gameFlag;
2766
2767 private static void Refresh()
2768 {
2769 list = Slots.LoadIndex();
2770 LayerArt.ForgetMissing();
2771 currentSlot = Slots.CurrentSlot;
2772 currentHash = null;
2773 try { if (File.Exists(Paths.Save)) currentHash = Snapshot.HashOf(File.ReadAllBytes(Paths.Save)); }
2774 catch (Exception) { }
2775 gameFlag = CheatFlag.OfGame();
2776 if (Plugin.CloudEnabled.Value) Runner.Run(Cloud.RefreshList());
2777 }
2778
2779 private static void Styles()
2780 {
2781 if (title != null) return;
2782 white = Texture2D.whiteTexture;
2783 title = new GUIStyle(GUI.skin.label) { fontSize = 40, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft };
2784 title.normal.textColor = new Color(1f, 0.78f, 0.3f);
2785 sub = new GUIStyle(GUI.skin.label) { fontSize = 16, alignment = TextAnchor.MiddleCenter, wordWrap = true, richText = true };
2786 sub.normal.textColor = new Color(0.8f, 0.8f, 0.8f);
2787 cardTitle = new GUIStyle(GUI.skin.label) { fontSize = 18, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft };
2788 cardTitle.normal.textColor = Color.white;
2789 cardBig = new GUIStyle(GUI.skin.label) { fontSize = 22, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter };
2790 cardBig.normal.textColor = Color.white;
2791 cardText = new GUIStyle(GUI.skin.label) { fontSize = 14, alignment = TextAnchor.MiddleCenter, wordWrap = true, richText = true };
2792 cardText.normal.textColor = new Color(0.82f, 0.82f, 0.82f);
2793 badge = new GUIStyle(GUI.skin.label) { fontSize = 12, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter };
2794 badge.normal.textColor = Color.black;
2795 numStyle = new GUIStyle(GUI.skin.label) { fontSize = 40, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter };
2796 numStyle.normal.textColor = new Color(0.2f, 0.2f, 0.24f);
2797 btn = new GUIStyle(GUI.skin.button) { fontSize = 16, fontStyle = FontStyle.Bold };
2798 btnDanger = new GUIStyle(btn) { fontSize = 14, padding = new RectOffset(2, 2, 2, 2) };
2799 btnDanger.normal.textColor = new Color(1f, 0.6f, 0.55f);
2800 btnDanger.hover.textColor = new Color(1f, 0.45f, 0.4f);
2801 menuBtn = new GUIStyle(GUI.skin.button) { fontSize = 18, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft, padding = new RectOffset(56, 10, 4, 4) };
2802 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) };
2803 cloudSmall.normal.textColor = new Color(0.85f, 0.85f, 0.85f);
2804 btnSmall = new GUIStyle(GUI.skin.button) { fontSize = 13, fontStyle = FontStyle.Bold };
2805 panelText = new GUIStyle(GUI.skin.label) { fontSize = 15, alignment = TextAnchor.MiddleLeft, wordWrap = true, richText = true };
2806 panelText.normal.textColor = new Color(0.88f, 0.88f, 0.88f);
2807 }
2808
2809 private static void Fill(Rect r, Color c)
2810 {
2811 Color old = GUI.color;
2812 GUI.color = c;
2813 GUI.DrawTexture(r, white);
2814 GUI.color = old;
2815 }
2816
2817 private static void Frame(Rect r, Color c, float t)
2818 {
2819 Fill(new Rect(r.x, r.y, r.width, t), c);
2820 Fill(new Rect(r.x, r.yMax - t, r.width, t), c);
2821 Fill(new Rect(r.x, r.y, t, r.height), c);
2822 Fill(new Rect(r.xMax - t, r.y, t, r.height), c);
2823 }
2824
2825 private static void Badge(Rect r, string text, Color bg)
2826 {
2827 Fill(r, bg);
2828 GUI.Label(r, text, badge);
2829 }
2830
2831 private static Sprite BiomeIcon(int layer)
2832 {
2833 Sprite s;
2834 if (biomeIcons.TryGetValue(layer, out s)) return s;
2835 try { s = Resources.Load<Sprite>("BiomeIcon/" + layer); } catch (Exception) { s = null; }
2836 biomeIcons[layer] = s;
2837 return s;
2838 }
2839
2840 private static string BiomeName(int layer)
2841 {
2842 try
2843 {
2844 string n = Locale.GetOther("layertitle" + layer);
2845 if (!string.IsNullOrEmpty(n) && n != "layertitle" + layer) return n;
2846 }
2847 catch (Exception) { }
2848 return "";
2849 }
2850
2851 private static string CharName(int c)
2852 {
2853 try
2854 {
2855 string n = Locale.GetOther("char" + c + "name");
2856 if (!string.IsNullOrEmpty(n) && n != "char" + c + "name") return n;
2857 }
2858 catch (Exception) { }
2859 return "Character " + (c + 1);
2860 }
2861
2862 public static void DrawMenuButton(float vw)
2863 {
2864 Styles();
2865 Rect r = new Rect(vw - 250f, 20f, 230f, 56f);
2866 if (GUI.Button(r, "SAVE SLOTS", menuBtn))
2867 {
2868 Refresh();
2869 SaveMode = false;
2870 Open = true;
2871 }
2872 Floppy.DrawPlain(new Rect(r.x + 10f, r.y + 8f, 40f, 40f));
2873 }
2874
2875 public static void Draw(float vw, float vh)
2876 {
2877 Styles();
2878 Event e = Event.current;
2879 if (e.type == EventType.KeyDown && e.keyCode == KeyCode.Escape)
2880 {
2881 if (codePanel) codePanel = false;
2882 else if (cloudPanel > 0) cloudPanel = -1;
2883 else Close();
2884 e.Use();
2885 return;
2886 }
2887
2888 Fill(new Rect(0, 0, vw, vh), new Color(0.03f, 0.03f, 0.05f, 0.93f));
2889
2890 int count = Slots.Count;
2891 foreach (SlotInfo si in list) if (si.Slot > count && si.Slot != Slots.AutoSlot) count = si.Slot;
2892 if (Plugin.CloudEnabled.Value)
2893 foreach (int k in Cloud.Remote.Keys) if (k > count && k != Slots.AutoSlot && k <= 10) count = k;
2894 int total = count + 1;
2895 float cw = 220f, ch = Plugin.CloudEnabled.Value ? 424f : 386f, gap = 22f;
2896 int cols = Mathf.Clamp(Mathf.FloorToInt((vw - 40f + gap) / (cw + gap)), 1, Mathf.Min(total, 6));
2897 int rows = (total + cols - 1) / cols;
2898 float gridW = cols * cw + (cols - 1) * gap;
2899 float gridH = rows * ch + (rows - 1) * gap;
2900 float top = Mathf.Max(150f, (vh - gridH) * 0.5f);
2901 float gx = (vw - gridW) * 0.5f;
2902
2903 float tw = 420f;
2904 float tx = (vw - tw) * 0.5f;
2905 Floppy.DrawPlain(new Rect(tx, top - 128f, 72f, 72f));
2906 GUI.Label(new Rect(tx + 90f, top - 128f, tw - 90f, 72f), SaveMode ? "SAVE GAME" : "SAVE SLOTS", title);
2907 string head = SaveMode
2908 ? "Pick a slot to save into. " + Plugin.SaveKey.Value + " and Save & Quit then keep saving into that slot (marked <b><color=#ffd27f>CURRENT</color></b>). Auto-save only uses its own slot."
2909 : "Pick a save to load it. <b><color=#8fe38f>CONTINUE</color></b> marks the save the Continue button loads.";
2910 GUI.Label(new Rect(gx, top - 50f, gridW, 36f), head, sub);
2911 if (Plugin.ShowCheatFlag.Value)
2912 GUI.Label(new Rect(gx, top - 17f, gridW, 16f), "<size=12><color=#aaaaaa>Debug: the game's save file (save.sv) is </color>" + (gameFlag == null ? "<color=#aaaaaa>not there right now</color>" : "<color=#aaaaaa>marked as cheated: </color><b>" + CheatFlag.Colored(gameFlag) + "</b>") + "</size>", sub);
2913
2914 SlotInfo newest = list.OrderByDescending(x => x.SavedAt).FirstOrDefault();
2915 bool panel = cloudPanel > 0 || codePanel;
2916 GUI.enabled = !panel;
2917 for (int idx = 0; idx < total; idx++)
2918 {
2919 int i = idx == 0 ? Slots.AutoSlot : idx;
2920 Rect card = new Rect(gx + (idx % cols) * (cw + gap), top + (idx / cols) * (ch + gap), cw, ch);
2921 SlotInfo s = list.FirstOrDefault(x => x.Slot == i);
2922 DrawCard(card, i, s, newest);
2923 }
2924
2925 float by = top + gridH + 26f;
2926 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);
2927 bool codes = !SaveMode && Plugin.CloudEnabled.Value;
2928 float bx = codes ? (vw - 440f) * 0.5f : (vw - 200f) * 0.5f;
2929 if (GUI.Button(new Rect(bx, by + 54f, 200f, 46f), "BACK", btn)) Close();
2930 if (codes && GUI.Button(new Rect(bx + 240f, by + 54f, 200f, 46f), "SHARE CODE", btn)) { codePanel = true; codeMsg = null; }
2931 GUI.enabled = true;
2932 if (cloudPanel > 0) DrawCloudPanel(vw, vh);
2933 else if (codePanel) DrawCodePanel(vw, vh);
2934 }
2935
2936 private static Cloud.CloudSlot CloudFor(int slot)
2937 {
2938 if (!Plugin.CloudEnabled.Value) return null;
2939 Cloud.CloudSlot c;
2940 return Cloud.Remote.TryGetValue(slot, out c) ? c : null;
2941 }
2942
2943 private static string Describe(int layer, int character, float runTime, DateTime at)
2944 {
2945 return "Layer " + layer + ", " + CharName(character) + ", run time " + TimeSpan.FromSeconds(runTime).ToString().Split('.')[0] + ", saved " + at.ToString("MMM d, HH:mm");
2946 }
2947
2948 private static void DrawIcon(Rect area, float width)
2949 {
2950 Texture2D ic = Cloud.Icon;
2951 if (ic == null) return;
2952 float h = width * ic.height / ic.width;
2953 GUI.DrawTexture(new Rect(area.x, area.y + (area.height - h) * 0.5f, width, h), ic);
2954 }
2955
2956 private static void OpenPanel(int slot)
2957 {
2958 cloudPanel = slot;
2959 cloudConfirm = null;
2960 if (shareSlot != slot) { shareCode = null; shareMsg = null; shareSlot = slot; }
2961 Runner.Run(Cloud.FetchVersions(slot));
2962 }
2963
2964 private static void DrawCloudRow(Rect r, int slot, SlotInfo s)
2965 {
2966 if (!Plugin.CloudEnabled.Value) return;
2967 Cloud.CloudSlot c = CloudFor(slot);
2968 string status;
2969 if (Cloud.ListState == "loading") status = "Checking the cloud...";
2970 else if (Cloud.ListState == "error") status = "<color=#ff9999>Cloud unavailable</color>";
2971 else if (c == null)
2972 {
2973 if (s == null) return;
2974 status = "<color=#aaaaaa>Not in the cloud yet</color>";
2975 }
2976 else if (s == null) status = "<color=#ffd27f>Only in the cloud</color>";
2977 else if (Cloud.Same(s, c)) status = "<color=#8fe38f>Synced to the cloud</color>";
2978 else if (Cloud.SavedTime(c) > s.SavedAt) status = "<color=#ffd27f>Cloud has a newer save</color>";
2979 else status = "<color=#ffd27f>Cloud copy is older</color>";
2980 Rect row = new Rect(r.x + 10f, r.y + 346f, r.width - 20f, 28f);
2981 DrawIcon(row, 26f);
2982 float right = SaveMode ? row.xMax : row.xMax - 66f;
2983 GUI.Label(new Rect(row.x + 32f, row.y - 6f, right - row.x - 36f, row.height + 12f), status, cloudSmall);
2984 if (!SaveMode && GUI.Button(new Rect(row.xMax - 62f, row.y, 62f, 28f), "CLOUD", btnSmall)) OpenPanel(slot);
2985 }
2986
2987 private static void DrawCloudPanel(float vw, float vh)
2988 {
2989 int slot = cloudPanel;
2990 Fill(new Rect(0, 0, vw, vh), new Color(0f, 0f, 0f, 0.55f));
2991 float pw = Mathf.Min(680f, vw - 40f), ph = 610f;
2992 Rect p = new Rect((vw - pw) * 0.5f, Mathf.Max(20f, (vh - ph) * 0.5f), pw, ph);
2993 Fill(p, new Color(0.1f, 0.1f, 0.13f, 0.99f));
2994 Frame(p, new Color(0.96f, 0.55f, 0.16f), 2f);
2995 DrawIcon(new Rect(p.x + 18f, p.y + 14f, 60f, 40f), 60f);
2996 GUI.Label(new Rect(p.x + 90f, p.y + 14f, pw - 110f, 40f), (slot == Slots.AutoSlot ? "AUTO-SAVE" : "SLOT " + slot) + " IN THE CLOUD", cardBig);
2997 bool locked = Cloud.Busy;
2998 bool canUpload = Cloud.State != "off" && Cloud.State != "readonly";
2999 float y = p.y + 66f;
3000
3001 SlotInfo local = list.FirstOrDefault(x => x.Slot == slot);
3002 GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 26f), "<b>On this PC:</b> " + (local != null ? Describe(local.Layer, local.Character, local.RunTime, local.SavedAt) : "<color=#888888>nothing in this slot</color>"), panelText);
3003 y += 32f;
3004 if (local != null)
3005 {
3006 GUI.enabled = !locked && canUpload;
3007 if (GUI.Button(new Rect(p.x + 20f, y, 260f, 32f), "UPLOAD THIS PC'S SAVE", btnSmall))
3008 {
3009 Cloud.QueueUpload(slot);
3010 Runner.Toast("Uploading " + Slots.Name(slot) + "...", false);
3011 }
3012 GUI.enabled = !locked && canUpload;
3013 if (GUI.Button(new Rect(p.x + 290f, y, 200f, 32f), "SHARE THIS SAVE", btnSmall))
3014 {
3015 shareCode = null;
3016 shareMsg = "Making a share code...";
3017 int sl = slot;
3018 Runner.Run(Cloud.Share(sl, (c, until, err) =>
3019 {
3020 shareSlot = sl;
3021 shareCode = c;
3022 shareUntil = until;
3023 shareMsg = err;
3024 }));
3025 }
3026 GUI.enabled = true;
3027 y += 40f;
3028 if (shareCode != null)
3029 {
3030 string shown = shareCode.Length == 8 ? shareCode.Substring(0, 4) + "-" + shareCode.Substring(4) : shareCode;
3031 GUI.Label(new Rect(p.x + 20f, y, pw - 160f, 32f), "<b>Share code:</b> <size=22><color=#ffd27f>" + shown + "</color></size> <color=#888888>works until " + shareUntil + "</color>", panelText);
3032 if (GUI.Button(new Rect(p.xMax - 130f, y, 110f, 30f), "COPY", btnSmall)) { GUIUtility.systemCopyBuffer = shown; Runner.Toast("Share code copied.", false); }
3033 y += 40f;
3034 }
3035 else if (!string.IsNullOrEmpty(shareMsg))
3036 {
3037 GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 32f), "<color=#ffd27f>" + shareMsg + "</color>", cloudSmall);
3038 y += 40f;
3039 }
3040 }
3041
3042 GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 24f), "<b>Cloud copies</b> <color=#888888>(newest first, up to 6 kept)</color>", panelText);
3043 y += 28f;
3044 if (Cloud.VersionsState == "loading") GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 26f), "Loading...", panelText);
3045 else if (Cloud.VersionsState == "error") GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 26f), "<color=#ff9999>Couldn't load the cloud copies.</color>", panelText);
3046 else if (Cloud.Versions.Count == 0) GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 26f), "<color=#888888>No cloud copies of this slot yet.</color>", panelText);
3047 else
3048 {
3049 for (int i = 0; i < Cloud.Versions.Count && i < 6; i++)
3050 {
3051 Cloud.CloudSlot v = Cloud.Versions[i];
3052 Rect row = new Rect(p.x + 20f, y, pw - 40f, 40f);
3053 Fill(row, new Color(1f, 1f, 1f, i % 2 == 0 ? 0.05f : 0.02f));
3054 string tag = i == 0 ? "<b><color=#8fe38f>NEWEST</color></b> " : "";
3055 if (local != null && Cloud.Same(local, v)) tag += "<color=#8fe38f>(same as this PC)</color> ";
3056 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);
3057 string key = "dl" + v.Version;
3058 string label = local != null ? (cloudConfirm == key ? "SURE?" : "REPLACE") : "DOWNLOAD";
3059 GUI.enabled = !locked;
3060 if (GUI.Button(new Rect(row.xMax - 124f, row.y + 5f, 116f, 30f), label, btnSmall))
3061 {
3062 if (local != null && cloudConfirm != key) cloudConfirm = key;
3063 else
3064 {
3065 cloudConfirm = null;
3066 string ver = i == 0 ? null : v.Version;
3067 Runner.Run(Cloud.Download(slot, ver, ok => { Refresh(); Runner.Run(Cloud.FetchVersions(slot)); }));
3068 }
3069 }
3070 GUI.enabled = true;
3071 y += 44f;
3072 }
3073 }
3074
3075 float by = p.yMax - 54f;
3076 if (local != null) GUI.Label(new Rect(p.x + 20f, by - 40f, pw - 40f, 36f), "<color=#888888>REPLACE puts the cloud copy into this slot on this PC. Your current save in this slot is overwritten.</color>", cloudSmall);
3077 GUI.enabled = !locked && Cloud.Versions.Count > 0;
3078 if (GUI.Button(new Rect(p.x + 20f, by, 220f, 38f), cloudConfirm == "del" ? "SURE? DELETE ALL" : "DELETE FROM CLOUD", btnDanger))
3079 {
3080 if (cloudConfirm != "del") cloudConfirm = "del";
3081 else
3082 {
3083 cloudConfirm = null;
3084 Runner.Run(Cloud.DeleteRemote(slot, () => { Refresh(); Runner.Run(Cloud.FetchVersions(slot)); }));
3085 }
3086 }
3087 GUI.enabled = true;
3088 if (locked) GUI.Label(new Rect(p.x + 250f, by, 160f, 38f), "Working...", panelText);
3089 if (GUI.Button(new Rect(p.xMax - 160f, by, 140f, 38f), "CLOSE", btn)) cloudPanel = -1;
3090 }
3091
3092 private static void DrawCodePanel(float vw, float vh)
3093 {
3094 Fill(new Rect(0, 0, vw, vh), new Color(0f, 0f, 0f, 0.55f));
3095 float pw = Mathf.Min(620f, vw - 40f), ph = 330f;
3096 Rect p = new Rect((vw - pw) * 0.5f, Mathf.Max(20f, (vh - ph) * 0.5f), pw, ph);
3097 Fill(p, new Color(0.1f, 0.1f, 0.13f, 0.99f));
3098 Frame(p, new Color(0.96f, 0.55f, 0.16f), 2f);
3099 DrawIcon(new Rect(p.x + 18f, p.y + 14f, 60f, 40f), 60f);
3100 GUI.Label(new Rect(p.x + 90f, p.y + 14f, pw - 110f, 40f), "LOAD A SHARED SAVE", cardBig);
3101 bool locked = Cloud.Busy;
3102 int target = -1;
3103 for (int i = 1; i <= Slots.Count; i++) if (!list.Any(x => x.Slot == i)) { target = i; break; }
3104 float y = p.y + 66f;
3105 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);
3106 y += 58f;
3107 GUI.SetNextControlName("sharecode");
3108 codeText = GUI.TextField(new Rect(p.x + 20f, y, 260f, 38f), codeText ?? "", 12);
3109 GUI.enabled = !locked && target > 0;
3110 if (GUI.Button(new Rect(p.x + 296f, y, 160f, 38f), locked ? "LOADING..." : "LOAD", btnSmall))
3111 {
3112 codeMsg = "Getting the shared save...";
3113 int sl = target;
3114 Runner.Run(Cloud.FetchShare(codeText, sl, (ok, msg) =>
3115 {
3116 codeMsg = (ok ? "<color=#8fe38f>" : "<color=#ff9999>") + msg + "</color>";
3117 if (ok) { codeText = ""; Refresh(); }
3118 }));
3119 }
3120 GUI.enabled = true;
3121 y += 50f;
3122 string info = target > 0 ? "<color=#888888>It will go into " + Slots.Name(target) + ".</color>" : "<color=#ff9999>All your slots are full. Delete a save or add slots (SlotCount in the config) first.</color>";
3123 GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 28f), info, cloudSmall);
3124 y += 32f;
3125 if (!string.IsNullOrEmpty(codeMsg)) GUI.Label(new Rect(p.x + 20f, y, pw - 40f, 40f), codeMsg, panelText);
3126 if (GUI.Button(new Rect(p.xMax - 160f, p.yMax - 54f, 140f, 38f), "CLOSE", btn)) codePanel = false;
3127 }
3128
3129 private static void DrawCard(Rect r, int slot, SlotInfo s, SlotInfo newest)
3130 {
3131 bool empty = s == null;
3132 bool hover = r.Contains(Event.current.mousePosition);
3133 bool isCurrent = !empty && currentHash != null && s.Hash == currentHash;
3134 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)));
3135 if (!empty) DrawArt(r, s, hover);
3136 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);
3137
3138 bool autoCard = slot == Slots.AutoSlot;
3139 GUI.Label(new Rect(r.x + 14f, r.y + 8f, 150f, 28f), autoCard ? "AUTO-SAVE" : "SLOT " + slot, cardTitle);
3140 if (!empty)
3141 {
3142 if (Plugin.ShowCheatFlag.Value) CheatFlag.DrawTag(new Rect(r.x + 14f, r.y + 38f, 112f, 16f), CheatFlag.OfSlot(s));
3143 Sprite icon = BiomeIcon(s.Layer);
3144 if (icon != null && icon.texture != null)
3145 {
3146 Rect tr = icon.textureRect;
3147 Rect uv = new Rect(tr.x / icon.texture.width, tr.y / icon.texture.height, tr.width / icon.texture.width, tr.height / icon.texture.height);
3148 GUI.DrawTextureWithTexCoords(new Rect(r.xMax - 46f, r.y + 6f, 36f, 36f), icon.texture, uv);
3149 }
3150 }
3151
3152 Rect fl = new Rect(r.x + (r.width - 128f) * 0.5f, r.y + 46f, 128f, 128f);
3153 Floppy.Draw(fl, slot, empty);
3154
3155 Cloud.CloudSlot rc = empty && !SaveMode ? CloudFor(slot) : null;
3156 if (rc != null)
3157 {
3158 GUI.Label(new Rect(r.x, r.y + 180f, r.width, 30f), "LAYER " + rc.Layer, cardBig);
3159 GUI.Label(new Rect(r.x + 8f, r.y + 208f, r.width - 16f, 22f), BiomeName(rc.Layer), cardText);
3160 Color oc = GUI.color;
3161 GUI.color = new Color(1f, 0.72f, 0.35f);
3162 GUI.Label(new Rect(r.x + 8f, r.y + 232f, r.width - 16f, 22f), CharName(rc.Character), cardText);
3163 GUI.color = oc;
3164 GUI.Label(new Rect(r.x + 8f, r.y + 254f, r.width - 16f, 20f), string.IsNullOrEmpty(rc.RunType) ? "<color=#888888>Run type unknown</color>" : "<b><color=#9fd4ff>" + rc.RunType + " run</color></b>", cardText);
3165 GUI.Label(new Rect(r.x + 8f, r.y + 276f, r.width - 16f, 20f), "Run time " + TimeSpan.FromSeconds(rc.RunTime).ToString().Split('.')[0], cardText);
3166 GUI.Label(new Rect(r.x + 8f, r.y + 296f, r.width - 16f, 20f), Cloud.SavedTime(rc).ToString("MMM d, HH:mm"), cardText);
3167 Badge(new Rect(r.x + 12f, r.y + 320f, r.width - 24f, 18f), "IN THE CLOUD", new Color(0.96f, 0.6f, 0.25f));
3168 if (GUI.Button(new Rect(r.x + 12f, r.yMax - 42f, r.width - 24f, 32f), "DOWNLOAD", btn) && !Cloud.Busy)
3169 Runner.Run(Cloud.Download(slot, null, ok => Refresh()));
3170 DrawCloudRow(r, slot, null);
3171 return;
3172 }
3173
3174 if (empty)
3175 {
3176 GUI.Label(new Rect(r.x, r.y + 196f, r.width, 30f), "EMPTY", cardBig);
3177 if (autoCard)
3178 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);
3179 else if (SaveMode)
3180 {
3181 if (GUI.Button(new Rect(r.x + 12f, r.yMax - 42f, r.width - 24f, 32f), "SAVE HERE", btn)) SaveInto(slot);
3182 }
3183 else GUI.Label(new Rect(r.x + 10f, r.y + 228f, r.width - 20f, 40f), "Save during a run to fill this slot.", cardText);
3184 DrawCloudRow(r, slot, null);
3185 return;
3186 }
3187
3188 GUI.Label(new Rect(r.x, r.y + 180f, r.width, 30f), "LAYER " + s.Layer, cardBig);
3189 GUI.Label(new Rect(r.x + 8f, r.y + 208f, r.width - 16f, 22f), BiomeName(s.Layer), cardText);
3190 Color oldC = GUI.color;
3191 GUI.color = new Color(1f, 0.72f, 0.35f);
3192 GUI.Label(new Rect(r.x + 8f, r.y + 232f, r.width - 16f, 22f), CharName(s.Character), cardText);
3193 GUI.color = oldC;
3194 GUI.Label(new Rect(r.x + 8f, r.y + 254f, r.width - 16f, 20f), string.IsNullOrEmpty(s.RunType) ? "<color=#888888>Run type unknown</color>" : "<b><color=#9fd4ff>" + s.RunType + " run</color></b>", cardText);
3195 GUI.Label(new Rect(r.x + 8f, r.y + 276f, r.width - 16f, 20f), "Run time " + TimeSpan.FromSeconds(s.RunTime).ToString().Split('.')[0], cardText);
3196 GUI.Label(new Rect(r.x + 8f, r.y + 296f, r.width - 16f, 20f), s.SavedAt.ToString("MMM d, HH:mm"), cardText);
3197
3198 float bx = r.x + 12f, bw2 = (r.width - 24f - 8f) / 2f;
3199 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));
3200 if (SaveMode && slot == currentSlot) Badge(new Rect(bx + bw2 + 8f, r.y + 320f, bw2, 18f), "CURRENT", new Color(1f, 0.82f, 0.5f));
3201 else if (!SaveMode && isCurrent) Badge(new Rect(bx + bw2 + 8f, r.y + 320f, bw2, 18f), "CONTINUE", new Color(0.56f, 0.89f, 0.56f));
3202
3203 Rect lb = new Rect(r.x + 12f, r.yMax - 42f, r.width - 24f - 90f, 32f);
3204 Rect db = new Rect(lb.xMax + 6f, lb.y, 84f, 32f);
3205 if (SaveMode && autoCard)
3206 {
3207 GUI.Label(lb, "<color=#888888>Auto-save only</color>", cardText);
3208 }
3209 else if (SaveMode)
3210 {
3211 string label = slot == currentSlot ? "SAVE" : (confirmOverwrite == slot ? "SURE?" : "OVERWRITE");
3212 if (GUI.Button(lb, label, btn))
3213 {
3214 if (slot == currentSlot || confirmOverwrite == slot) SaveInto(slot);
3215 else { confirmOverwrite = slot; confirmDelete = -1; }
3216 }
3217 }
3218 else if (GUI.Button(lb, "LOAD", btn)) Load(s);
3219 if (GUI.Button(db, confirmDelete == s.Slot ? "SURE?" : "DELETE", btnDanger))
3220 {
3221 if (confirmDelete == s.Slot)
3222 {
3223 Slots.Delete(s.Slot);
3224 confirmDelete = -1;
3225 Refresh();
3226 }
3227 else confirmDelete = s.Slot;
3228 }
3229 DrawCloudRow(r, slot, s);
3230 }
3231
3232 private static void DrawArt(Rect r, SlotInfo s, bool hover)
3233 {
3234 Texture2D t = LayerArt.Get(s.Art);
3235 if (t == null) return;
3236 float cardAspect = r.width / r.height;
3237 float texAspect = (float)t.width / t.height;
3238 Rect uv;
3239 if (texAspect > cardAspect)
3240 {
3241 float w = cardAspect / texAspect;
3242 uv = new Rect((1f - w) * 0.5f, 0f, w, 1f);
3243 }
3244 else
3245 {
3246 float h = texAspect / cardAspect;
3247 uv = new Rect(0f, (1f - h) * 0.5f, 1f, h);
3248 }
3249 Color old = GUI.color;
3250 GUI.color = new Color(1f, 1f, 1f, hover ? 0.75f : 0.6f);
3251 GUI.DrawTextureWithTexCoords(r, t, uv);
3252 GUI.color = old;
3253 Fill(new Rect(r.x, r.y, r.width, 44f), new Color(0.05f, 0.05f, 0.07f, 0.5f));
3254 Fill(new Rect(r.x, r.y + 170f, r.width, r.height - 170f), new Color(0.05f, 0.05f, 0.07f, 0.62f));
3255 }
3256
3257 private static void SaveInto(int slot)
3258 {
3259 confirmOverwrite = -1;
3260 bool quit = quitAfter;
3261 Runner.SaveAsync(false, slot, ok =>
3262 {
3263 if (ok)
3264 {
3265 Close();
3266 if (quit && PlayerCamera.main != null) PlayerCamera.main.ToMainMenu();
3267 }
3268 else Refresh();
3269 });
3270 }
3271
3272 private static void Load(SlotInfo s)
3273 {
3274 if (!Slots.Use(s))
3275 {
3276 Runner.Toast("That save slot couldn't be read.", true);
3277 Refresh();
3278 return;
3279 }
3280 PreRunScript pr = Object.FindObjectOfType<PreRunScript>();
3281 if (pr == null)
3282 {
3283 Runner.Toast((s.Slot == Slots.AutoSlot ? "The auto-save" : "Slot " + s.Slot) + " is ready, press Continue.", false);
3284 Close();
3285 return;
3286 }
3287 StartLoad(pr, s);
3288 }
3289
3290 internal static void StartLoad(PreRunScript pr, SlotInfo s)
3291 {
3292 Plugin.Log.LogInfo("Loading save slot " + s.Slot + ".");
3293 Traverse.Create(pr).Field("savedCharacter").SetValue(s.Character);
3294 Open = false;
3295 Loading = PlayerPrefs.GetInt("didbasiccourse") != 0;
3296 pr.LoadRun();
3297 }
3298 }
3299
3300 public static class Api
3301 {
3302 internal static SlotInfo PendingLoad;
3303 internal static float PendingAt;
3304
3305 private static SlotInfo Newest()
3306 {
3307 if (MultiplayerGuard.Detected) return null;
3308 List<SlotInfo> list = Slots.LoadIndex();
3309 string run = Slots.CurrentRun;
3310 SlotInfo s = list.Where(x => x.Run == run).OrderByDescending(x => x.SavedAt).FirstOrDefault();
3311 return s;
3312 }
3313
3314 public static bool HasCheckpoint()
3315 {
3316 try { return Newest() != null; }
3317 catch (Exception) { return false; }
3318 }
3319
3320 public static bool LoadLastCheckpoint()
3321 {
3322 try
3323 {
3324 SlotInfo s = Newest();
3325 if (s == null || !Slots.Use(s)) return false;
3326 PendingLoad = s;
3327 PendingAt = Time.realtimeSinceStartup;
3328 Plugin.Log.LogInfo("Loading the last checkpoint (slot " + s.Slot + ") from the death screen.");
3329 if (PlayerCamera.main != null) PlayerCamera.main.ToMainMenu();
3330 else SceneManager.LoadScene("PreGen");
3331 return true;
3332 }
3333 catch (Exception e)
3334 {
3335 Plugin.Log.LogError("Couldn't load the last checkpoint: " + e);
3336 return false;
3337 }
3338 }
3339
3340 internal static void Tick(bool onMenu)
3341 {
3342 if (PendingLoad == null) return;
3343 if (Time.realtimeSinceStartup - PendingAt > 30f) { PendingLoad = null; return; }
3344 if (!onMenu || Time.timeSinceLevelLoad < 0.75f) return;
3345 PreRunScript pr = Object.FindObjectOfType<PreRunScript>();
3346 if (pr == null) return;
3347 SlotInfo s = PendingLoad;
3348 PendingLoad = null;
3349 try { SlotScreen.StartLoad(pr, s); }
3350 catch (Exception e) { Plugin.Log.LogError("Checkpoint load failed: " + e); }
3351 }
3352 }
3353
3354 internal static class SelfUpdate
3355 {
3356 private const string Server = "https://updates.smellypawz.com";
3357 private const string FilesPage = "https://www.nexusmods.com/scavprototype/mods/885?tab=files";
3358 internal static bool Checked;
3359 internal static string NewVersion = "", Notes = "";
3360 private static bool available, dismissed;
3361 private static GUIStyle box, head, text, button;
3362
3363 internal static IEnumerator Check()
3364 {
3365 Checked = true;
3366 UnityWebRequest req = UnityWebRequest.Get(Server + "/v1/latest?app=saveanywhere&have=" + Plugin.Version);
3367 req.timeout = 15;
3368 yield return req.SendWebRequest();
3369 string body = req.responseCode == 200 && req.downloadHandler != null ? req.downloadHandler.text : null;
3370 req.Dispose();
3371 if (body == null) yield break;
3372 try
3373 {
3374 JObject o = Cloud.Json(body);
3375 if (o["update"] == null || !(bool)o["update"]) yield break;
3376 NewVersion = (string)o["version"] ?? "";
3377 Notes = ((string)o["notes"] ?? "").Replace("<", "").Replace(">", "");
3378 available = true;
3379 Plugin.Log.LogInfo("Save Anywhere " + NewVersion + " is out on Nexus.");
3380 }
3381 catch (Exception e) { Plugin.Log.LogWarning("Couldn't read the update check: " + e.Message); }
3382 }
3383
3384 private static void Styles()
3385 {
3386 if (box != null) return;
3387 Texture2D bg = new Texture2D(1, 1);
3388 bg.SetPixel(0, 0, new Color(0.08f, 0.08f, 0.1f, 0.94f));
3389 bg.Apply();
3390 box = new GUIStyle(GUI.skin.box);
3391 box.normal.background = bg;
3392 head = new GUIStyle(GUI.skin.label) { fontSize = 20, fontStyle = FontStyle.Bold, richText = true };
3393 head.normal.textColor = new Color(1f, 0.82f, 0.5f);
3394 text = new GUIStyle(GUI.skin.label) { fontSize = 15, wordWrap = true, richText = true };
3395 text.normal.textColor = new Color(0.85f, 0.85f, 0.88f);
3396 button = new GUIStyle(GUI.skin.button) { fontSize = 16, fontStyle = FontStyle.Bold };
3397 }
3398
3399 internal static void DrawBanner(float vw)
3400 {
3401 if (!available || dismissed) return;
3402 Styles();
3403 float w = Mathf.Min(560f, vw - 560f);
3404 if (w < 360f) w = 360f;
3405 Rect r = new Rect((vw - w) * 0.5f, 20f, w, 126f);
3406 GUI.Box(r, GUIContent.none, box);
3407 GUI.Label(new Rect(r.x + 16f, r.y + 8f, w - 32f, 28f), "Save Anywhere " + NewVersion + " is out", head);
3408 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);
3409 float by = r.yMax - 42f;
3410 if (GUI.Button(new Rect(r.x + 16f, by, 170f, 32f), "OPEN NEXUS", button)) Application.OpenURL(FilesPage);
3411 if (GUI.Button(new Rect(r.xMax - 106f, by, 90f, 32f), "LATER", button)) dismissed = true;
3412 }
3413 }
3414
3415 internal static class Cloud
3416 {
3417 internal const string BaseUrl = "https://cloud.smellypawz.com";
3418 internal static string State = "";
3419 internal static string Message = "";
3420 internal static bool Checking;
3421 internal static float LastCheck = -1000f;
3422
3423 internal static bool NeedsCheck()
3424 {
3425 if (Checking) return false;
3426 return State == "" || (State == "error" && Time.unscaledTime - LastCheck > 60f);
3427 }
3428
3429 internal static void Reset()
3430 {
3431 if (Checking) return;
3432 State = "";
3433 Message = "";
3434 }
3435
3436 internal static string StatusLine()
3437 {
3438 switch (State)
3439 {
3440 case "checking": return "Connecting to the cloud...";
3441 case "ok": return "<color=#99ff99>Connected to the cloud.</color>";
3442 case "readonly": return "<color=#ffd966>" + (Message.Length > 0 ? Message : "Cloud saves are read-only for now.") + "</color>";
3443 case "off": return "<color=#ff9999>" + (Message.Length > 0 ? Message : "Cloud saves have been switched off by the mod author.") + "</color>";
3444 case "error": return "<color=#ff9999>Can't reach the cloud right now. Your saves on this PC still work.</color>";
3445 case "update": return "<color=#ff9999>" + UpdateText() + "</color>";
3446 default: return "";
3447 }
3448 }
3449
3450 private class Pending
3451 {
3452 public string Slot;
3453 public byte[] Data;
3454 public string Meta;
3455 }
3456
3457 private static readonly List<Pending> queue = new List<Pending>();
3458 private static bool uploading;
3459 private static string id;
3460 private static string token;
3461 private static string AccountPath { get { return Paths.Dir + "\\SaveAnywhere\\cloud.json"; } }
3462
3463 private static void LoadAccount()
3464 {
3465 try
3466 {
3467 if (!File.Exists(AccountPath)) return;
3468 JObject o = JObject.Parse(File.ReadAllText(AccountPath));
3469 id = (string)o["id"];
3470 token = (string)o["token"];
3471 if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(token)) { id = null; token = null; }
3472 }
3473 catch (Exception e)
3474 {
3475 id = null;
3476 token = null;
3477 Plugin.Log.LogWarning("Couldn't read the cloud account file: " + e.Message);
3478 }
3479 }
3480
3481 private static void SaveAccount(string newId, string newToken)
3482 {
3483 id = newId;
3484 token = newToken;
3485 JObject o = new JObject();
3486 o["id"] = newId;
3487 o["token"] = newToken;
3488 Directory.CreateDirectory(Paths.Dir + "\\SaveAnywhere");
3489 File.WriteAllText(AccountPath, o.ToString(Formatting.None));
3490 }
3491
3492 private static void ClearAccount()
3493 {
3494 id = null;
3495 token = null;
3496 try { if (File.Exists(AccountPath)) File.Delete(AccountPath); } catch (Exception) { }
3497 }
3498
3499 internal static string SlotName(int slot)
3500 {
3501 return slot == Slots.AutoSlot ? "auto" : slot.ToString();
3502 }
3503
3504 internal static void QueueUpload(int slot)
3505 {
3506 if (!Plugin.CloudEnabled.Value || State == "off" || State == "readonly" || State == "update") return;
3507 try
3508 {
3509 string path = Slots.PathOf(slot);
3510 if (!File.Exists(path)) return;
3511 byte[] data = File.ReadAllBytes(path);
3512 string name = SlotName(slot);
3513 queue.RemoveAll(p => p.Slot == name);
3514 Pending pending = new Pending();
3515 pending.Slot = name;
3516 pending.Data = data;
3517 pending.Meta = MetaFor(slot);
3518 queue.Add(pending);
3519 if (!uploading) Runner.Run(UploadLoop());
3520 }
3521 catch (Exception e)
3522 {
3523 Plugin.Log.LogWarning("Couldn't queue the cloud upload for " + Slots.Name(slot) + ": " + e.Message);
3524 }
3525 }
3526
3527 internal static string MetaFor(int slot)
3528 {
3529 {
3530 SlotInfo s = Slots.LoadIndex().FirstOrDefault(x => x.Slot == slot);
3531 JObject m = new JObject();
3532 if (s != null)
3533 {
3534 m["layer"] = s.Layer;
3535 m["character"] = s.Character;
3536 m["runType"] = s.RunType ?? "";
3537 m["runTime"] = Mathf.RoundToInt(s.RunTime);
3538 m["savedAt"] = s.SavedAt.ToUniversalTime().ToString("o");
3539 m["runId"] = s.Run ?? "";
3540 }
3541 m["modVersion"] = Plugin.Version;
3542 m["gameVersion"] = Application.version;
3543 return m.ToString(Formatting.None);
3544 }
3545 }
3546
3547 internal static IEnumerator Share(int slot, Action<string, string, string> done)
3548 {
3549 Busy = true;
3550 byte[] data = null;
3551 string meta = null;
3552 try
3553 {
3554 string path = Slots.PathOf(slot);
3555 if (File.Exists(path)) { data = File.ReadAllBytes(path); meta = MetaFor(slot); }
3556 }
3557 catch (Exception e) { Plugin.Log.LogWarning("Couldn't read " + Slots.Name(slot) + " to share it: " + e.Message); }
3558 if (data == null) { Busy = false; done(null, null, "There's no save in this slot to share."); yield break; }
3559 yield return EnsureAccount();
3560 if (id == null) { Busy = false; done(null, null, "Couldn't make a cloud account for this PC. Try again later."); yield break; }
3561 UnityWebRequest req = new UnityWebRequest(BaseUrl + "/v1/share", "POST");
3562 req.uploadHandler = new UploadHandlerRaw(data);
3563 req.uploadHandler.contentType = "application/octet-stream";
3564 req.downloadHandler = new DownloadHandlerBuffer();
3565 req.SetRequestHeader("Authorization", "Bearer " + id + "." + token);
3566 req.SetRequestHeader("X-SA-Meta", meta);
3567 req.SetRequestHeader("X-SA-Version", Plugin.Version);
3568 req.timeout = 60;
3569 yield return req.SendWebRequest();
3570 long code = req.responseCode;
3571 bool net = req.result == UnityWebRequest.Result.ConnectionError || code == 0;
3572 string body = req.downloadHandler != null ? req.downloadHandler.text : "";
3573 req.Dispose();
3574 Busy = false;
3575 if (code == 200)
3576 {
3577 try
3578 {
3579 JObject o = Json(body);
3580 string c = (string)o["code"];
3581 DateTime exp;
3582 string until = DateTime.TryParse((string)o["expires"], out exp) ? exp.ToLocalTime().ToString("MMM d") : "a week";
3583 Plugin.Log.LogInfo("Shared " + Slots.Name(slot) + " as " + c + ".");
3584 done(c, until, null);
3585 }
3586 catch (Exception) { done(null, null, "The cloud answered, but the code couldn't be read."); }
3587 yield break;
3588 }
3589 string why = "Sharing didn't work (HTTP " + code + ").";
3590 if (net) why = "Couldn't reach the cloud. Check your internet and try again.";
3591 else if (code == 426) { NeedUpdate(body); why = UpdateText(); }
3592 else if (code == 503) why = "Cloud saves are switched off or read-only right now, so sharing is too.";
3593 else if (code == 415) why = "The cloud couldn't read this save, so it wasn't shared.";
3594 else if (code == 413) why = "This save is too big to share.";
3595 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.";
3596 Plugin.Log.LogWarning("Share failed (HTTP " + code + "): " + body);
3597 done(null, null, why);
3598 }
3599
3600 internal static string CleanCode(string raw)
3601 {
3602 StringBuilder sb = new StringBuilder();
3603 foreach (char ch in (raw ?? "").ToUpperInvariant())
3604 if ("ABCDEFGHJKMNPQRSTUVWXYZ23456789".IndexOf(ch) >= 0) sb.Append(ch);
3605 return sb.ToString();
3606 }
3607
3608 internal static IEnumerator FetchShare(string raw, int slot, Action<bool, string> done)
3609 {
3610 string code = CleanCode(raw);
3611 if (code.Length != 8) { done(false, "A share code has 8 letters and numbers, like K7QX-2M9P."); yield break; }
3612 Busy = true;
3613 yield return EnsureAccount();
3614 if (id == null) { Busy = false; done(false, "Couldn't make a cloud account for this PC. Try again later."); yield break; }
3615 Resp r = new Resp();
3616 yield return Call("GET", "/v1/share/" + code, null, r);
3617 Busy = false;
3618 if (r.Code == 200 && r.Bytes != null && r.Bytes.Length > 0)
3619 {
3620 bool ok = Slots.Import(slot, r.Bytes, r.Meta);
3621 if (ok) Plugin.Log.LogInfo("Loaded shared save " + code + " into " + Slots.Name(slot) + ".");
3622 done(ok, ok ? "The shared save is in " + Slots.Name(slot) + ". Pick it to play." : "That shared save couldn't be read.");
3623 yield break;
3624 }
3625 done(false, Friendly(r, "No shared save has that code. Check it and try again."));
3626 }
3627
3628 private static IEnumerator UploadLoop()
3629 {
3630 uploading = true;
3631 while (queue.Count > 0)
3632 {
3633 Pending p = queue[0];
3634 queue.RemoveAt(0);
3635 if (id == null) LoadAccount();
3636 if (id == null)
3637 {
3638 yield return Signup();
3639 if (id == null)
3640 {
3641 queue.Clear();
3642 break;
3643 }
3644 }
3645 for (int attempt = 0; attempt < 2; attempt++)
3646 {
3647 UnityWebRequest req = new UnityWebRequest(BaseUrl + "/v1/slots/" + p.Slot, "PUT");
3648 req.uploadHandler = new UploadHandlerRaw(p.Data);
3649 req.uploadHandler.contentType = "application/octet-stream";
3650 req.downloadHandler = new DownloadHandlerBuffer();
3651 req.SetRequestHeader("Authorization", "Bearer " + id + "." + token);
3652 req.SetRequestHeader("X-SA-Meta", p.Meta);
3653 req.SetRequestHeader("X-SA-Version", Plugin.Version);
3654 req.timeout = 60;
3655 yield return req.SendWebRequest();
3656 long code = req.responseCode;
3657 bool netFail = req.result == UnityWebRequest.Result.ConnectionError;
3658 string body = req.downloadHandler != null ? req.downloadHandler.text : "";
3659 string err = req.error;
3660 req.Dispose();
3661 if (code == 401 && attempt == 0)
3662 {
3663 Plugin.Log.LogInfo("The cloud didn't recognise this PC's account any more, making a new one.");
3664 ClearAccount();
3665 yield return Signup();
3666 if (id == null) break;
3667 continue;
3668 }
3669 Report(p, code, body, netFail, err);
3670 break;
3671 }
3672 }
3673 uploading = false;
3674 if (SlotScreen.Open) Runner.Run(RefreshList());
3675 }
3676
3677 private static IEnumerator Signup()
3678 {
3679 UnityWebRequest req = new UnityWebRequest(BaseUrl + "/v1/signup", "POST");
3680 req.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes("{}"));
3681 req.uploadHandler.contentType = "application/json";
3682 req.downloadHandler = new DownloadHandlerBuffer();
3683 req.SetRequestHeader("X-SA-Version", Plugin.Version);
3684 req.timeout = 20;
3685 yield return req.SendWebRequest();
3686 long code = req.responseCode;
3687 bool netFail = req.result == UnityWebRequest.Result.ConnectionError;
3688 string body = req.downloadHandler != null ? req.downloadHandler.text : "";
3689 string err = req.error;
3690 req.Dispose();
3691 if (code == 200)
3692 {
3693 try
3694 {
3695 JObject o = JObject.Parse(body);
3696 SaveAccount((string)o["id"], (string)o["token"]);
3697 Plugin.Log.LogInfo("Made a cloud account for this PC.");
3698 }
3699 catch (Exception e) { Plugin.Log.LogWarning("Couldn't store the new cloud account: " + e.Message); }
3700 yield break;
3701 }
3702 if (netFail || code == 0) { NetError(err); yield break; }
3703 if (code == 503) { Disabled(body); yield break; }
3704 if (code == 426) { NeedUpdate(body); yield break; }
3705 Plugin.Log.LogWarning("Couldn't make a cloud account (HTTP " + code + "): " + body);
3706 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);
3707 }
3708
3709 internal static string MinVersion = "";
3710
3711 internal static int VersionNum(string v)
3712 {
3713 try
3714 {
3715 string[] p = (v ?? "").Trim().Split('.');
3716 if (p.Length != 3) return -1;
3717 return int.Parse(p[0]) * 1000000 + int.Parse(p[1]) * 1000 + int.Parse(p[2]);
3718 }
3719 catch (Exception) { return -1; }
3720 }
3721
3722 internal static string UpdateText()
3723 {
3724 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.";
3725 }
3726
3727 private static void NeedUpdate(string body)
3728 {
3729 try
3730 {
3731 string v = (string)JObject.Parse(body)["minVersion"];
3732 if (VersionNum(v) > 0) MinVersion = v;
3733 }
3734 catch (Exception) { }
3735 bool first = State != "update";
3736 State = "update";
3737 queue.Clear();
3738 if (first)
3739 {
3740 Plugin.Log.LogWarning("The Save Anywhere cloud needs a newer version of the mod (" + (MinVersion.Length > 0 ? MinVersion : "?") + ", this is " + Plugin.Version + ").");
3741 Runner.CloudToast("Cloud: update Save Anywhere to keep using cloud saves.", true);
3742 }
3743 }
3744
3745 private static string ErrorOf(string body)
3746 {
3747 try { return (string)JObject.Parse(body)["error"] ?? ""; } catch (Exception) { return ""; }
3748 }
3749
3750 private static void NetError(string err)
3751 {
3752 State = "error";
3753 LastCheck = Time.unscaledTime;
3754 Plugin.Log.LogWarning("Couldn't reach the Save Anywhere cloud: " + err);
3755 Runner.CloudToast("Couldn't reach the cloud. Your save is safe on this PC.", true);
3756 }
3757
3758 private static void Disabled(string body)
3759 {
3760 try
3761 {
3762 JObject o = JObject.Parse(body);
3763 string mode = (string)o["mode"] ?? "off";
3764 Message = ((string)o["message"] ?? "").Replace("<", "").Replace(">", "");
3765 State = mode == "readonly" ? "readonly" : "off";
3766 }
3767 catch (Exception) { State = "off"; }
3768 queue.Clear();
3769 Plugin.Log.LogInfo("The Save Anywhere cloud is " + State + (Message.Length > 0 ? ": " + Message : "."));
3770 Runner.CloudToast(Message.Length > 0 ? Message : "Cloud saves are switched off right now. Your save is safe on this PC.", true);
3771 }
3772
3773 private static void Report(Pending p, long code, string body, bool netFail, string err)
3774 {
3775 string what = p.Slot == "auto" ? "the auto-save" : "slot " + p.Slot;
3776 if (code == 200)
3777 {
3778 State = "ok";
3779 Plugin.Log.LogInfo("Uploaded " + what + " to the cloud (" + (p.Data.Length / 1024) + " KB).");
3780 Runner.CloudToast("Uploaded to the cloud", false);
3781 return;
3782 }
3783 if (netFail || code == 0) { NetError(err); return; }
3784 if (code == 503) { Disabled(body); return; }
3785 if (code == 426) { NeedUpdate(body); return; }
3786 string e = ErrorOf(body);
3787 Plugin.Log.LogWarning("Cloud upload of " + what + " failed (HTTP " + code + ", " + e + ").");
3788 string msg;
3789 if (e == "account_full") msg = "Cloud: your cloud storage is full. Delete some cloud saves to upload more.";
3790 else if (e == "cloud_full") msg = "Cloud: the cloud server is full right now. Your save is safe on this PC.";
3791 else if (code == 429) msg = "Cloud: too many uploads right now. It'll upload again with your next save.";
3792 else if (code == 403) msg = "Cloud: this cloud account is blocked.";
3793 else msg = "Cloud: the upload didn't work. Your save is safe on this PC.";
3794 Runner.CloudToast(msg, true);
3795 }
3796 internal class Resp
3797 {
3798 public long Code;
3799 public bool Net;
3800 public string Text = "";
3801 public byte[] Bytes;
3802 public string Meta;
3803 public string Error;
3804 }
3805
3806 internal class CloudSlot
3807 {
3808 public int Slot;
3809 public string Version;
3810 public DateTime Uploaded;
3811 public int Layer;
3812 public int Character;
3813 public string RunType;
3814 public float RunTime;
3815 public string SavedAt;
3816 public string RunId;
3817 public int Versions = 1;
3818 }
3819
3820 internal static readonly Dictionary<int, CloudSlot> Remote = new Dictionary<int, CloudSlot>();
3821 internal static string ListState = "";
3822 internal static readonly List<CloudSlot> Versions = new List<CloudSlot>();
3823 internal static string VersionsState = "";
3824 internal static bool Busy;
3825 private static Texture2D icon;
3826
3827 internal static Texture2D Icon
3828 {
3829 get
3830 {
3831 if (icon != null) return icon;
3832 try
3833 {
3834 using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("SaveAnywhere.cloudflare.png"))
3835 {
3836 if (s != null)
3837 {
3838 byte[] b = new byte[s.Length];
3839 s.Read(b, 0, b.Length);
3840 Texture2D t = new Texture2D(2, 2, TextureFormat.RGBA32, false);
3841 if (t.LoadImage(b)) { t.filterMode = FilterMode.Bilinear; icon = t; return icon; }
3842 }
3843 }
3844 }
3845 catch (Exception e) { Plugin.Log.LogWarning("Couldn't load the cloud icon: " + e.Message); }
3846 string[] rows = {
3847 ".....####.......",
3848 "....######.###..",
3849 "...###########..",
3850 ".##############.",
3851 "################",
3852 "################",
3853 "################",
3854 ".##############."
3855 };
3856 Texture2D p = new Texture2D(16, rows.Length, TextureFormat.RGBA32, false);
3857 p.filterMode = FilterMode.Point;
3858 Color clear = new Color(0f, 0f, 0f, 0f);
3859 for (int y = 0; y < rows.Length; y++)
3860 for (int x = 0; x < 16; x++)
3861 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);
3862 p.Apply();
3863 icon = p;
3864 return icon;
3865 }
3866 }
3867
3868 internal static JObject Json(string text)
3869 {
3870 using (JsonTextReader reader = new JsonTextReader(new StringReader(text)))
3871 {
3872 reader.DateParseHandling = DateParseHandling.None;
3873 return JObject.Load(reader);
3874 }
3875 }
3876
3877 internal static int SlotNum(string name)
3878 {
3879 if (name == "auto") return Slots.AutoSlot;
3880 int n;
3881 return int.TryParse(name, out n) ? n : -1;
3882 }
3883
3884 private static int Int(JToken t)
3885 {
3886 if (t == null) return 0;
3887 int n;
3888 return int.TryParse(t.ToString(), out n) ? n : 0;
3889 }
3890
3891 private static CloudSlot ParseSlot(JToken o)
3892 {
3893 CloudSlot c = new CloudSlot();
3894 c.Slot = SlotNum((string)o["slot"]);
3895 c.Version = (string)o["version"];
3896 DateTime up;
3897 c.Uploaded = DateTime.TryParse((string)o["uploaded"], System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out up) ? up.ToLocalTime() : DateTime.MinValue;
3898 JToken m = o["meta"] ?? new JObject();
3899 c.Layer = Int(m["layer"]);
3900 c.Character = Int(m["character"]);
3901 c.RunType = (string)m["runType"];
3902 c.RunTime = Int(m["runTime"]);
3903 c.SavedAt = (string)m["savedAt"];
3904 c.RunId = (string)m["runId"];
3905 if (o["versions"] != null) c.Versions = Int(o["versions"]);
3906 return c;
3907 }
3908
3909 internal static DateTime SavedTime(CloudSlot c)
3910 {
3911 DateTime d;
3912 if (c.SavedAt != null && DateTime.TryParse(c.SavedAt, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out d)) return d.ToLocalTime();
3913 return c.Uploaded;
3914 }
3915
3916 internal static string SavedKey(SlotInfo s)
3917 {
3918 return s.SavedAt.ToUniversalTime().ToString("o");
3919 }
3920
3921 internal static bool Same(SlotInfo s, CloudSlot c)
3922 {
3923 return s != null && c != null && c.SavedAt == SavedKey(s);
3924 }
3925
3926 private static IEnumerator Call(string method, string path, byte[] body, Resp into)
3927 {
3928 UnityWebRequest req = new UnityWebRequest(BaseUrl + path, method);
3929 if (body != null)
3930 {
3931 req.uploadHandler = new UploadHandlerRaw(body);
3932 req.uploadHandler.contentType = "application/json";
3933 }
3934 req.downloadHandler = new DownloadHandlerBuffer();
3935 if (id != null) req.SetRequestHeader("Authorization", "Bearer " + id + "." + token);
3936 req.SetRequestHeader("X-SA-Version", Plugin.Version);
3937 req.timeout = 60;
3938 yield return req.SendWebRequest();
3939 into.Code = req.responseCode;
3940 if (into.Code == 426) NeedUpdate(req.downloadHandler != null ? req.downloadHandler.text : "");
3941 into.Net = req.result == UnityWebRequest.Result.ConnectionError || req.responseCode == 0;
3942 into.Error = req.error;
3943 into.Bytes = req.downloadHandler != null ? req.downloadHandler.data : null;
3944 string ct = req.GetResponseHeader("Content-Type") ?? "";
3945 into.Text = ct.Contains("json") && into.Bytes != null ? Encoding.UTF8.GetString(into.Bytes) : "";
3946 into.Meta = req.GetResponseHeader("X-SA-Meta");
3947 req.Dispose();
3948 }
3949
3950 private static void NoteDisabled(Resp r)
3951 {
3952 try
3953 {
3954 JObject o = Cloud.Json(r.Text);
3955 string mode = (string)o["mode"] ?? "off";
3956 Message = ((string)o["message"] ?? "").Replace("<", "").Replace(">", "");
3957 State = mode == "readonly" ? "readonly" : "off";
3958 }
3959 catch (Exception) { State = "off"; }
3960 }
3961
3962 internal static IEnumerator RefreshList()
3963 {
3964 if (!Plugin.CloudEnabled.Value) { Remote.Clear(); ListState = ""; yield break; }
3965 if (id == null) LoadAccount();
3966 if (id == null) { Remote.Clear(); ListState = "ok"; yield break; }
3967 ListState = "loading";
3968 Resp r = new Resp();
3969 yield return Call("GET", "/v1/slots", null, r);
3970 if (r.Code == 200)
3971 {
3972 Remote.Clear();
3973 try
3974 {
3975 foreach (JToken o in (JArray)Cloud.Json(r.Text)["slots"])
3976 {
3977 CloudSlot c = ParseSlot(o);
3978 if (c.Slot > 0) Remote[c.Slot] = c;
3979 }
3980 ListState = "ok";
3981 }
3982 catch (Exception e)
3983 {
3984 ListState = "error";
3985 Plugin.Log.LogWarning("Couldn't read the cloud slot list: " + e.Message);
3986 }
3987 yield break;
3988 }
3989 if (r.Code == 503) NoteDisabled(r);
3990 ListState = "error";
3991 if (r.Net) { State = "error"; LastCheck = Time.unscaledTime; }
3992 Plugin.Log.LogWarning("Couldn't list cloud saves (HTTP " + r.Code + ").");
3993 }
3994
3995 internal static IEnumerator FetchVersions(int slot)
3996 {
3997 Versions.Clear();
3998 if (id == null) LoadAccount();
3999 if (id == null) { VersionsState = "ok"; yield break; }
4000 VersionsState = "loading";
4001 Resp r = new Resp();
4002 yield return Call("GET", "/v1/slots/" + SlotName(slot) + "/versions", null, r);
4003 if (r.Code != 200)
4004 {
4005 if (r.Code == 503) NoteDisabled(r);
4006 VersionsState = "error";
4007 yield break;
4008 }
4009 try
4010 {
4011 foreach (JToken o in (JArray)Cloud.Json(r.Text)["versions"]) Versions.Add(ParseSlot(o));
4012 VersionsState = "ok";
4013 }
4014 catch (Exception) { VersionsState = "error"; }
4015 }
4016
4017 internal static IEnumerator Download(int slot, string version, Action<bool> done)
4018 {
4019 Busy = true;
4020 if (id == null) LoadAccount();
4021 Resp r = new Resp();
4022 yield return Call("GET", "/v1/slots/" + SlotName(slot) + (version != null ? "/versions/" + version : ""), null, r);
4023 bool ok = false;
4024 if (r.Code == 200 && r.Bytes != null)
4025 {
4026 ok = Slots.Import(slot, r.Bytes, r.Meta);
4027 if (ok) Plugin.Log.LogInfo("Downloaded " + Slots.Name(slot) + " from the cloud (" + (r.Bytes.Length / 1024) + " KB).");
4028 Runner.Toast(ok ? "Downloaded " + Slots.Name(slot) + " from the cloud." : "That cloud save couldn't be read.", !ok);
4029 }
4030 else
4031 {
4032 if (r.Code == 503) NoteDisabled(r);
4033 Plugin.Log.LogWarning("Cloud download failed (HTTP " + r.Code + ", " + r.Error + ").");
4034 Runner.Toast(r.Net ? "Couldn't reach the cloud." : (r.Code == 503 && Message.Length > 0 ? Message : "The download didn't work."), true);
4035 }
4036 Busy = false;
4037 if (done != null) done(ok);
4038 }
4039
4040 internal static IEnumerator DeleteRemote(int slot, Action done)
4041 {
4042 Busy = true;
4043 if (id == null) LoadAccount();
4044 if (id != null)
4045 {
4046 Resp r = new Resp();
4047 yield return Call("DELETE", "/v1/slots/" + SlotName(slot), null, r);
4048 if (r.Code == 200) Plugin.Log.LogInfo("Deleted " + Slots.Name(slot) + " from the cloud.");
4049 else Plugin.Log.LogWarning("Couldn't delete " + Slots.Name(slot) + " from the cloud (HTTP " + r.Code + ").");
4050 }
4051 Busy = false;
4052 if (done != null) done();
4053 }
4054
4055 internal static void DeleteForRun(string run, int onlySlot)
4056 {
4057 if (!Plugin.CloudEnabled.Value || string.IsNullOrEmpty(run)) return;
4058 Runner.Run(DeleteForRunRoutine(run, onlySlot));
4059 }
4060
4061 private static IEnumerator DeleteForRunRoutine(string run, int onlySlot)
4062 {
4063 if (id == null) LoadAccount();
4064 if (id == null) yield break;
4065 Resp r = new Resp();
4066 yield return Call("GET", "/v1/slots", null, r);
4067 if (r.Code != 200) yield break;
4068 List<int> hit = new List<int>();
4069 try
4070 {
4071 foreach (JToken o in (JArray)Cloud.Json(r.Text)["slots"])
4072 {
4073 CloudSlot c = ParseSlot(o);
4074 if (c.Slot > 0 && c.RunId == run && (onlySlot <= 0 || c.Slot == onlySlot)) hit.Add(c.Slot);
4075 }
4076 }
4077 catch (Exception) { yield break; }
4078 foreach (int s in hit)
4079 {
4080 Resp d = new Resp();
4081 yield return Call("DELETE", "/v1/slots/" + SlotName(s), null, d);
4082 if (d.Code == 200) { Remote.Remove(s); Plugin.Log.LogInfo("Deleted " + Slots.Name(s) + " from the cloud too."); }
4083 }
4084 }
4085 internal static bool HasAccount()
4086 {
4087 if (id == null) LoadAccount();
4088 return id != null;
4089 }
4090
4091 private static IEnumerator EnsureAccount()
4092 {
4093 if (id == null) LoadAccount();
4094 if (id == null) yield return Signup();
4095 }
4096
4097 internal static string Friendly(Resp r, string notFound)
4098 {
4099 if (r.Net) return "Couldn't reach the cloud. Check your internet and try again.";
4100 if (r.Code == 503)
4101 {
4102 NoteDisabled(r);
4103 return Message.Length > 0 ? Message : "Cloud saves are switched off right now.";
4104 }
4105 if (r.Code == 426) return UpdateText();
4106 if (r.Code == 429) return "Too many tries. Wait a little and try again.";
4107 if (r.Code == 404 || r.Code == 400) return notFound;
4108 if (r.Code == 410) return "That code has expired. Get a new one.";
4109 if (r.Code == 403) return "This cloud account is blocked.";
4110 if (r.Code == 401) return "This PC isn't signed in to the cloud any more. Save once to make a new cloud account.";
4111 return "Something went wrong (HTTP " + r.Code + ").";
4112 }
4113
4114 private static byte[] Body(JObject o)
4115 {
4116 return Encoding.UTF8.GetBytes(o.ToString(Formatting.None));
4117 }
4118
4119 internal static IEnumerator GetUsage(Action<string> done)
4120 {
4121 if (!HasAccount()) { done("No cloud account yet. It's made the first time you save with cloud saves on."); yield break; }
4122 Resp r = new Resp();
4123 yield return Call("GET", "/v1/usage", null, r);
4124 if (r.Code != 200) { done(Friendly(r, "Couldn't read your cloud usage.")); yield break; }
4125 try
4126 {
4127 JObject o = Json(r.Text);
4128 double used = (double)o["bytes"] / 1048576.0, max = (double)o["maxBytes"] / 1048576.0;
4129 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"]));
4130 }
4131 catch (Exception) { done("Couldn't read your cloud usage."); }
4132 }
4133
4134 internal static IEnumerator GetLinkCode(Action<string, string> done)
4135 {
4136 yield return EnsureAccount();
4137 if (id == null) { done(null, "Couldn't make your cloud account. Try again later."); yield break; }
4138 Resp r = new Resp();
4139 yield return Call("POST", "/v1/link-code", Body(new JObject()), r);
4140 if (r.Code != 200) { done(null, Friendly(r, "Couldn't make a link code.")); yield break; }
4141 try { done((string)Json(r.Text)["code"], null); }
4142 catch (Exception) { done(null, "Couldn't read the link code."); }
4143 }
4144
4145 internal static IEnumerator UseLinkCode(string code, Action<bool, string> done)
4146 {
4147 JObject b = new JObject();
4148 b["code"] = code ?? "";
4149 Resp r = new Resp();
4150 yield return Call("POST", "/v1/link", Body(b), r);
4151 if (r.Code != 200) { done(false, Friendly(r, "That code didn't work. Check it and try again.")); yield break; }
4152 Adopt(r.Text);
4153 done(true, "Linked! This PC now uses the same cloud saves as your other device.");
4154 }
4155
4156 internal static IEnumerator MakeRecoveryKey(Action<string, string> done)
4157 {
4158 yield return EnsureAccount();
4159 if (id == null) { done(null, "Couldn't make your cloud account. Try again later."); yield break; }
4160 Resp r = new Resp();
4161 yield return Call("POST", "/v1/recovery-key", Body(new JObject()), r);
4162 if (r.Code != 200) { done(null, Friendly(r, "Couldn't make a recovery key.")); yield break; }
4163 try { done((string)Json(r.Text)["recoveryKey"], null); }
4164 catch (Exception) { done(null, "Couldn't read the recovery key."); }
4165 }
4166
4167 internal static IEnumerator UseRecoveryKey(string key, bool signOutOthers, Action<bool, string> done)
4168 {
4169 JObject b = new JObject();
4170 b["recoveryKey"] = key ?? "";
4171 b["signOutOthers"] = signOutOthers;
4172 Resp r = new Resp();
4173 yield return Call("POST", "/v1/recover", Body(b), r);
4174 if (r.Code != 200) { done(false, Friendly(r, "That recovery key didn't work. Check it and try again.")); yield break; }
4175 Adopt(r.Text);
4176 done(true, signOutOthers ? "Recovered! Every other device has been signed out." : "Recovered! This PC has your cloud saves again.");
4177 }
4178
4179 private static void Adopt(string text)
4180 {
4181 JObject o = Json(text);
4182 SaveAccount((string)o["id"], (string)o["token"]);
4183 Remote.Clear();
4184 ListState = "";
4185 State = "";
4186 Plugin.Log.LogInfo("This PC is now linked to a cloud account.");
4187 }
4188
4189 internal static IEnumerator LogoutOthers(Action<bool, string> done)
4190 {
4191 if (!HasAccount()) { done(false, "No cloud account yet."); yield break; }
4192 Resp r = new Resp();
4193 yield return Call("POST", "/v1/logout-others", Body(new JObject()), r);
4194 if (r.Code != 200) { done(false, Friendly(r, "Couldn't sign out your other devices.")); yield break; }
4195 done(true, "Every other device has been signed out. Only this PC can use your cloud saves now.");
4196 }
4197
4198 internal static IEnumerator DeleteAccount(Action<bool, string> done)
4199 {
4200 if (!HasAccount()) { done(true, "There's no cloud data for this PC."); yield break; }
4201 Resp r = new Resp();
4202 yield return Call("DELETE", "/v1/account", null, r);
4203 if (r.Code != 200 && r.Code != 401) { done(false, Friendly(r, "Couldn't delete your cloud data.")); yield break; }
4204 ClearAccount();
4205 Remote.Clear();
4206 ListState = "";
4207 queue.Clear();
4208 Plugin.Log.LogInfo("Deleted this PC's cloud account and all its cloud saves.");
4209 done(true, "All your cloud saves and your cloud account have been deleted. Cloud saves are now off.");
4210 }
4211
4212 internal static string InactiveNote = "";
4213 private static bool accountChecked;
4214
4215 internal static IEnumerator CheckStatus()
4216 {
4217 Checking = true;
4218 State = "checking";
4219 using (UnityWebRequest req = UnityWebRequest.Get(BaseUrl + "/v1/health"))
4220 {
4221 req.SetRequestHeader("X-SA-Version", Plugin.Version);
4222 req.timeout = 10;
4223 yield return req.SendWebRequest();
4224 Finish(req);
4225 }
4226 LastCheck = Time.unscaledTime;
4227 Checking = false;
4228 if (!accountChecked && (State == "ok" || State == "readonly") && HasAccount())
4229 {
4230 accountChecked = true;
4231 yield return CheckAccount();
4232 }
4233 }
4234
4235 private static IEnumerator CheckAccount()
4236 {
4237 Resp r = new Resp();
4238 yield return Call("GET", "/v1/me", null, r);
4239 if (r.Code != 200) yield break;
4240 try
4241 {
4242 JObject o = Json(r.Text);
4243 if (!(bool)o["warn"]) yield break;
4244 int idle = (int)o["idleDays"];
4245 int del = (int)o["deleteAfterDays"];
4246 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.";
4247 Plugin.Log.LogInfo("The cloud account had been unused for " + idle + " days. Showed the inactivity warning.");
4248 }
4249 catch (Exception) { }
4250 }
4251
4252 private static void Finish(UnityWebRequest req)
4253 {
4254 if (req.result != UnityWebRequest.Result.Success)
4255 {
4256 State = "error";
4257 Plugin.Log.LogWarning("Couldn't reach the Save Anywhere cloud: " + req.error);
4258 return;
4259 }
4260 try
4261 {
4262 JObject o = JObject.Parse(req.downloadHandler.text);
4263 string mode = (string)o["cloud"] ?? "on";
4264 Message = ((string)o["message"] ?? "").Replace("<", "").Replace(">", "");
4265 State = mode == "readonly" ? "readonly" : mode == "off" ? "off" : "ok";
4266 string mv = (string)o["minVersion"];
4267 if (State != "off" && VersionNum(mv) > 0 && VersionNum(Plugin.Version) < VersionNum(mv))
4268 {
4269 MinVersion = mv;
4270 State = "update";
4271 Plugin.Log.LogWarning("The Save Anywhere cloud needs version " + mv + " or newer (this is " + Plugin.Version + ").");
4272 return;
4273 }
4274 Plugin.Log.LogInfo("Save Anywhere cloud: " + mode + (Message.Length > 0 ? " (" + Message + ")" : "") + ".");
4275 }
4276 catch (Exception e)
4277 {
4278 State = "error";
4279 Plugin.Log.LogWarning("The Save Anywhere cloud sent an answer the mod didn't understand: " + e.Message);
4280 }
4281 }
4282 }
4283 internal class Runner : MonoBehaviour
4284 {
4285 private static Runner instance;
4286 private bool cloudPromptOpen;
4287 private bool mpHandled;
4288 private bool mpPopupOpen;
4289 private float nextNetCheck;
4290 internal static bool JustRestored;
4291 private static float autoTimer;
4292 private static float layerSaveIn = -1f;
4293 private static float nextAutoTry;
4294 private static bool layerSaveDue;
4295 private static bool wasGenerating;
4296
4297 internal static void ResetAuto()
4298 {
4299 autoTimer = 0f;
4300 layerSaveIn = -1f;
4301 layerSaveDue = false;
4302 }
4303
4304 private void AutoTick()
4305 {
4306 if (!InRun())
4307 {
4308 wasGenerating = false;
4309 return;
4310 }
4311 WorldGeneration w = WorldGeneration.world;
4312 bool gen = w.generatingWorld || Loader.Restoring;
4313 if (wasGenerating && !gen)
4314 {
4315 if (JustRestored) JustRestored = false;
4316 else layerSaveIn = 10f;
4317 }
4318 wasGenerating = gen;
4319 if (gen || PauseHandler.paused || !Plugin.AutoSave.Value) return;
4320 float dt = Time.deltaTime;
4321 autoTimer += dt;
4322 bool due = autoTimer >= Mathf.Max(1f, Plugin.AutoSaveMinutes.Value) * 60f;
4323 if (layerSaveIn >= 0f)
4324 {
4325 layerSaveIn -= dt;
4326 if (layerSaveIn <= 0f)
4327 {
4328 layerSaveIn = -1f;
4329 layerSaveDue = Plugin.AutoSaveOnNewLayer.Value;
4330 }
4331 }
4332 if (layerSaveDue) due = true;
4333 if (!due || Time.unscaledTime < nextAutoTry) return;
4334 nextAutoTry = Time.unscaledTime + 2f;
4335 SaveAsync(true, 0, null);
4336 }
4337
4338 internal static bool Saving;
4339
4340 internal static void Guard(string what, Action a)
4341 {
4342 Plugin.Log.LogInfo(what + " clicked.");
4343 try { a(); }
4344 catch (Exception e)
4345 {
4346 Plugin.Log.LogError(what + " failed (game version " + Application.version + "): " + e);
4347 Toast("Save Anywhere error, please send BepInEx\\LogOutput.log.", true);
4348 }
4349 }
4350
4351 internal static void SaveAsync(bool auto, int slot, Action<bool> done)
4352 {
4353 if (Saving || instance == null) return;
4354 int target;
4355 try { target = Saver.Precheck(auto, slot); }
4356 catch (Exception e)
4357 {
4358 Plugin.Log.LogError("Save check failed (game version " + Application.version + "): " + e);
4359 if (!auto) Toast("Save Anywhere error, please send BepInEx\\LogOutput.log.", true);
4360 Saving = false;
4361 return;
4362 }
4363 if (target <= 0)
4364 {
4365 if (done != null) done(false);
4366 return;
4367 }
4368 instance.StartCoroutine(instance.SaveRoutine(auto, target, done));
4369 }
4370
4371 private IEnumerator SaveRoutine(bool auto, int target, Action<bool> done)
4372 {
4373 Saving = true;
4374 float start = Time.realtimeSinceStartup;
4375 ShowPill(auto ? "Auto-saving..." : "Saving...", PillKind.Saving, 60f, true);
4376 yield return null;
4377 yield return new WaitForEndOfFrame();
4378 bool ok = false;
4379 string why;
4380 try { why = InRun() ? Safety.Check() : "you're not in a run"; }
4381 catch (Exception e)
4382 {
4383 Plugin.Log.LogError("Save check failed (game version " + Application.version + "): " + e);
4384 why = "an error happened, please send BepInEx\\LogOutput.log";
4385 }
4386 if (why != null)
4387 {
4388 if (auto) pillText = null;
4389 else Toast("Can't save: " + why + ".", true);
4390 }
4391 else ok = Saver.Write(auto, target);
4392 if (ok)
4393 {
4394 while (Time.realtimeSinceStartup < start + 0.9f) yield return null;
4395 ShowPill(target == Slots.AutoSlot ? "Auto-saved" : (auto ? "Auto-saved" : "Saved") + " to slot " + target, PillKind.Saved, Mathf.Max(1f, start + 3f - Time.realtimeSinceStartup), false);
4396 Cloud.QueueUpload(target);
4397 }
4398 Saving = false;
4399 if (done != null)
4400 {
4401 try { done(ok); }
4402 catch (Exception e) { Plugin.Log.LogError("After-save step failed: " + e); }
4403 }
4404 }
4405
4406 private enum PillKind { Info, Bad, Saving, Saved }
4407 private static string pillText;
4408 private static PillKind pillKind;
4409 private static float pillStart, pillUntil;
4410 private static Texture2D dotTex;
4411 private GUIStyle pillStyle;
4412
4413 private static void ShowPill(string text, PillKind kind, float duration, bool fadeIn)
4414 {
4415 float now = Time.realtimeSinceStartup;
4416 bool visible = pillText != null && now < pillUntil;
4417 pillText = text;
4418 pillKind = kind;
4419 pillUntil = now + duration;
4420 if (fadeIn || !visible) pillStart = now;
4421 }
4422
4423 private static Texture2D Dot
4424 {
4425 get
4426 {
4427 if (dotTex != null) return dotTex;
4428 const int n = 128;
4429 dotTex = new Texture2D(n, n, TextureFormat.RGBA32, false);
4430 dotTex.hideFlags = HideFlags.HideAndDontSave;
4431 dotTex.wrapMode = TextureWrapMode.Clamp;
4432 dotTex.filterMode = FilterMode.Bilinear;
4433 Color[] px = new Color[n * n];
4434 float c = (n - 1) * 0.5f, rad = n * 0.5f - 1f;
4435 for (int y = 0; y < n; y++)
4436 for (int x = 0; x < n; x++)
4437 {
4438 float d = Mathf.Sqrt((x - c) * (x - c) + (y - c) * (y - c));
4439 px[y * n + x] = new Color(1f, 1f, 1f, Mathf.Clamp01(rad - d + 0.5f));
4440 }
4441 dotTex.SetPixels(px);
4442 dotTex.Apply();
4443 return dotTex;
4444 }
4445 }
4446
4447 private static void FillPill(Rect r, Color c)
4448 {
4449 float h = r.height, half = h * 0.5f;
4450 GUI.color = c;
4451 GUI.DrawTextureWithTexCoords(new Rect(r.x, r.y, half, h), Dot, new Rect(0f, 0f, 0.5f, 1f));
4452 GUI.DrawTextureWithTexCoords(new Rect(r.xMax - half, r.y, half, h), Dot, new Rect(0.5f, 0f, 0.5f, 1f));
4453 GUI.DrawTexture(new Rect(r.x + half, r.y, r.width - h, h), Texture2D.whiteTexture);
4454 }
4455
4456 private static void DrawSpinner(Rect r, Color c, float alpha)
4457 {
4458 const int dots = 8;
4459 int head = (int)(Time.realtimeSinceStartup * 12f) % dots;
4460 Vector2 center = r.center;
4461 float ring = r.width * 0.37f, big = r.width * 0.27f;
4462 for (int i = 0; i < dots; i++)
4463 {
4464 int age = (head - i + dots) % dots;
4465 float t = age / (float)(dots - 1);
4466 float ang = -Mathf.PI * 0.5f + i * Mathf.PI * 2f / dots;
4467 float d = Mathf.Lerp(big, big * 0.5f, t);
4468 Vector2 p = center + new Vector2(Mathf.Cos(ang), Mathf.Sin(ang)) * ring;
4469 GUI.color = new Color(c.r, c.g, c.b, Mathf.Lerp(1f, 0.15f, t) * alpha);
4470 GUI.DrawTexture(new Rect(p.x - d * 0.5f, p.y - d * 0.5f, d, d), Dot);
4471 }
4472 }
4473
4474 internal static string AutoLabel()
4475 {
4476 return Plugin.AutoSave.Value ? "Auto-save: ON (" + Mathf.Max(1f, Plugin.AutoSaveMinutes.Value).ToString("0.#") + " min)" : "Auto-save: OFF";
4477 }
4478
4479 internal static void ClickSave()
4480 {
4481 Guard("Save button", () =>
4482 {
4483 string why = Safety.Check();
4484 if (why != null) Toast("Can't save: " + why + ".", true);
4485 else SlotScreen.OpenForSave(false);
4486 });
4487 }
4488
4489 internal static void ClickSaveQuit()
4490 {
4491 Guard("Save & Quit button", () =>
4492 {
4493 string why = Safety.Check();
4494 if (why != null) Toast("Can't save: " + why + ".", true);
4495 else if (Slots.PickManualSlot() > 0) SaveAsync(false, 0, ok => { if (ok && PlayerCamera.main != null) PlayerCamera.main.ToMainMenu(); });
4496 else SlotScreen.OpenForSave(true);
4497 });
4498 }
4499
4500 internal static void ClickAuto()
4501 {
4502 Guard("Auto-save button", () =>
4503 {
4504 Plugin.AutoSave.Value = !Plugin.AutoSave.Value;
4505 ResetAuto();
4506 Toast(Plugin.AutoSave.Value ? "Auto-save turned on." : "Auto-save turned off.", false);
4507 });
4508 }
4509
4510 private void DrawPill(float vw, bool high)
4511 {
4512 float now = Time.realtimeSinceStartup;
4513 if (pillText == null || now >= pillUntil) return;
4514 if (pillStyle == null)
4515 {
4516 pillStyle = new GUIStyle(GUI.skin.label) { fontSize = 18, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleLeft, wordWrap = false, richText = false };
4517 pillStyle.padding = new RectOffset(0, 0, 0, 0);
4518 }
4519 float a = Mathf.Clamp01((now - pillStart) / 0.15f) * Mathf.Clamp01((pillUntil - now) / 0.35f);
4520 bool bad = pillKind == PillKind.Bad;
4521 bool hasIcon = pillKind == PillKind.Saving || pillKind == PillKind.Saved;
4522 Color bg = bad ? new Color(0.84f, 0.26f, 0.21f) : new Color(1f, 0.58f, 0.13f);
4523 Color fg = bad ? Color.white : new Color(0.16f, 0.08f, 0.01f);
4524 Vector2 ts = pillStyle.CalcSize(new GUIContent(pillText));
4525 float h = 46f, pad = 22f, icon = 26f, gap = 11f;
4526 float w = Mathf.Min(vw - 32f, pad * 2f + ts.x + (hasIcon ? icon + gap : 0f));
4527 float y = (high ? 6f : 74f) - (1f - Mathf.Clamp01((now - pillStart) / 0.2f)) * 8f;
4528 Rect r = new Rect((vw - w) * 0.5f, y, w, h);
4529 Color old = GUI.color;
4530 FillPill(new Rect(r.x, r.y + 3f, r.width, r.height), new Color(0f, 0f, 0f, 0.35f * a));
4531 FillPill(r, new Color(bg.r, bg.g, bg.b, 0.97f * a));
4532 FillPill(new Rect(r.x + 3f, r.y + 2f, r.width - 6f, r.height * 0.45f), new Color(1f, 1f, 1f, 0.13f * a));
4533 float x = r.x + pad;
4534 Rect ir = new Rect(x, r.center.y - icon * 0.5f, icon, icon);
4535 if (hasIcon) DrawSpinner(ir, fg, a);
4536 if (hasIcon) x += icon + gap;
4537 GUI.color = new Color(1f, 1f, 1f, a);
4538 pillStyle.normal.textColor = fg;
4539 GUI.Label(new Rect(x, r.y, r.xMax - pad - x + 2f, h), pillText, pillStyle);
4540 GUI.color = old;
4541 }
4542 private GameObject clickBlocker;
4543 private Rect cloudRect;
4544 private GUIStyle smallStyle;
4545 private GUIStyle titleStyle, bodyStyle, toastStyle, toastBadStyle, btnStyle;
4546
4547 internal static void Ensure()
4548 {
4549 if (instance != null) return;
4550 GameObject go = new GameObject("SaveAnywhereRunner");
4551 go.hideFlags = HideFlags.HideAndDontSave;
4552 DontDestroyOnLoad(go);
4553 instance = go.AddComponent<Runner>();
4554 }
4555
4556 internal static void Run(IEnumerator routine)
4557 {
4558 if (instance != null) instance.StartCoroutine(routine);
4559 }
4560
4561 internal static void CloudToast(string text, bool bad)
4562 {
4563 if (instance != null) instance.StartCoroutine(instance.CloudToastRoutine(text, bad));
4564 }
4565
4566 private IEnumerator CloudToastRoutine(string text, bool bad)
4567 {
4568 float until = Time.realtimeSinceStartup + 5f;
4569 while (pillText != null && Time.realtimeSinceStartup < pillUntil && Time.realtimeSinceStartup < until) yield return null;
4570 ShowPill(text, bad ? PillKind.Bad : PillKind.Info, bad ? 4f : 2.5f, true);
4571 }
4572
4573 internal static void Toast(string text, bool bad)
4574 {
4575 ShowPill(text, bad ? PillKind.Bad : PillKind.Info, 3.5f, true);
4576 }
4577
4578 private static bool InRun()
4579 {
4580 return PlayerCamera.main != null && PlayerCamera.main.body != null && WorldGeneration.world != null;
4581 }
4582
4583 private static bool OnMainMenu()
4584 {
4585 return SceneManager.GetActiveScene().name == "PreGen";
4586 }
4587
4588 private bool cuPopup;
4589 private bool onMenu;
4590
4591 private bool CloudVisible()
4592 {
4593 return !MultiplayerGuard.Detected && onMenu && !cuPopup && (!Plugin.CloudAsked.Value || cloudPromptOpen);
4594 }
4595
4596 private bool MpVisible()
4597 {
4598 return MultiplayerGuard.Detected && mpPopupOpen && !cuPopup;
4599 }
4600
4601 private bool SlotsAvailable()
4602 {
4603 return !MultiplayerGuard.Detected && onMenu && !cuPopup && !CloudVisible() && !SettingsVisible() && !InactiveVisible() && !SlotScreen.Loading;
4604 }
4605
4606 private void Update()
4607 {
4608 try { LayerArt.Tick(); }
4609 catch (Exception e) { Plugin.Log.LogWarning("Layer art capture failed: " + e.Message); }
4610 cuPopup = GameObject.Find("CUCheatsClickBlocker") != null;
4611 bool menuNow = OnMainMenu();
4612 if (menuNow && !onMenu) SlotScreen.Close();
4613 onMenu = menuNow;
4614 Api.Tick(onMenu);
4615 if (!mpHandled)
4616 {
4617 bool hit = MultiplayerGuard.Detected;
4618 if (!hit && Time.unscaledTime >= nextNetCheck)
4619 {
4620 nextNetCheck = Time.unscaledTime + 3f;
4621 hit = MultiplayerGuard.Check();
4622 }
4623 if (hit)
4624 {
4625 mpHandled = true;
4626 mpPopupOpen = true;
4627 }
4628 }
4629 if (MultiplayerGuard.Detected)
4630 {
4631 PauseRing.Refresh();
4632 BlockGameUI(MpVisible());
4633 return;
4634 }
4635 if (SlotScreen.Open && SlotScreen.SaveMode && (!InRun() || !PauseHandler.paused)) SlotScreen.Close();
4636 if (InRun() && !SlotScreen.Open && Plugin.SaveKey.Value.IsDown())
4637 {
4638 Plugin.Log.LogInfo("Save key pressed.");
4639 if (Slots.PickManualSlot() > 0) SaveAsync(false, 0, null);
4640 else Toast("Pick a slot first: pause and click Save.", true);
4641 }
4642 AutoTick();
4643 if (onMenu && Plugin.CloudEnabled.Value && Cloud.NeedsCheck()) StartCoroutine(Cloud.CheckStatus());
4644 PauseRing.Refresh();
4645 if (settingsOpen && !onMenu) settingsOpen = false;
4646 BlockGameUI(CloudVisible() || SettingsVisible() || InactiveVisible() || (SlotScreen.Open && (SlotScreen.SaveMode || SlotsAvailable())));
4647 }
4648
4649 private static int blockFrame = -100;
4650 internal static bool UiBlocking { get { return Time.frameCount - blockFrame <= 2; } }
4651
4652 private void BlockGameUI(bool block)
4653 {
4654 if (block) blockFrame = Time.frameCount;
4655 else blockFrame = -100;
4656 if (block && clickBlocker == null)
4657 {
4658 clickBlocker = new GameObject("SaveAnywhereClickBlocker");
4659 DontDestroyOnLoad(clickBlocker);
4660 Canvas canvas = clickBlocker.AddComponent<Canvas>();
4661 canvas.renderMode = RenderMode.ScreenSpaceOverlay;
4662 canvas.sortingOrder = 32766;
4663 clickBlocker.AddComponent<UnityEngine.UI.GraphicRaycaster>();
4664 GameObject panel = new GameObject("Blocker");
4665 panel.transform.SetParent(clickBlocker.transform, false);
4666 UnityEngine.UI.Image img = panel.AddComponent<UnityEngine.UI.Image>();
4667 img.color = new Color(0f, 0f, 0f, 0f);
4668 img.raycastTarget = true;
4669 RectTransform rt = img.rectTransform;
4670 rt.anchorMin = Vector2.zero;
4671 rt.anchorMax = Vector2.one;
4672 rt.offsetMin = Vector2.zero;
4673 rt.offsetMax = Vector2.zero;
4674 MuteSceneInput();
4675 }
4676 else if (!block && clickBlocker != null)
4677 {
4678 Destroy(clickBlocker);
4679 clickBlocker = null;
4680 RestoreSceneInput();
4681 }
4682 else if (block && Time.frameCount % 30 == 0)
4683 {
4684 MuteSceneInput();
4685 }
4686 }
4687
4688 private readonly List<UnityEngine.EventSystems.BaseRaycaster> mutedRaycasters = new List<UnityEngine.EventSystems.BaseRaycaster>();
4689 private readonly Dictionary<Camera, int> mutedCameras = new Dictionary<Camera, int>();
4690
4691 private void MuteSceneInput()
4692 {
4693 foreach (UnityEngine.EventSystems.BaseRaycaster r in FindObjectsOfType<UnityEngine.EventSystems.BaseRaycaster>())
4694 {
4695 if (r == null || !r.enabled) continue;
4696 if (clickBlocker != null && r.gameObject == clickBlocker) continue;
4697 if (r.gameObject.name == "CUCheatsClickBlocker") continue;
4698 r.enabled = false;
4699 mutedRaycasters.Add(r);
4700 }
4701 foreach (Camera c in Camera.allCameras)
4702 {
4703 if (c == null || mutedCameras.ContainsKey(c)) continue;
4704 mutedCameras[c] = c.eventMask;
4705 c.eventMask = 0;
4706 }
4707 }
4708
4709 private void RestoreSceneInput()
4710 {
4711 foreach (UnityEngine.EventSystems.BaseRaycaster r in mutedRaycasters)
4712 if (r != null) r.enabled = true;
4713 mutedRaycasters.Clear();
4714 foreach (KeyValuePair<Camera, int> kv in mutedCameras)
4715 if (kv.Key != null) kv.Key.eventMask = kv.Value;
4716 mutedCameras.Clear();
4717 }
4718
4719 private void Styles()
4720 {
4721 if (titleStyle != null) return;
4722 titleStyle = new GUIStyle(GUI.skin.label) { fontSize = 22, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter, wordWrap = true };
4723 titleStyle.normal.textColor = new Color(1f, 0.75f, 0.2f);
4724 bodyStyle = new GUIStyle(GUI.skin.label) { fontSize = 16, alignment = TextAnchor.UpperCenter, wordWrap = true, richText = true };
4725 bodyStyle.normal.textColor = Color.white;
4726 btnStyle = new GUIStyle(GUI.skin.button) { fontSize = 16, fontStyle = FontStyle.Bold };
4727 toastStyle = new GUIStyle(GUI.skin.box) { fontSize = 18, alignment = TextAnchor.MiddleCenter, wordWrap = true };
4728 toastStyle.normal.textColor = new Color(0.6f, 1f, 0.6f);
4729 toastBadStyle = new GUIStyle(toastStyle);
4730 toastBadStyle.normal.textColor = new Color(1f, 0.55f, 0.5f);
4731 }
4732
4733 private void OnGUI()
4734 {
4735 Styles();
4736 float s = Mathf.Max(0.75f, Screen.height / 1080f);
4737 Matrix4x4 old = GUI.matrix;
4738 GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(s, s, 1f));
4739 float vw = Screen.width / s, vh = Screen.height / s;
4740
4741 if (MultiplayerGuard.Detected)
4742 {
4743 if (MpVisible())
4744 {
4745 GUI.color = new Color(0f, 0f, 0f, 0.75f);
4746 GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture);
4747 GUI.color = Color.white;
4748 float mw = 640f;
4749 Rect mr = new Rect((vw - mw) * 0.5f, vh * 0.5f - 220f, mw, 0f);
4750 GUILayout.Window(0x5A5E02, mr, DrawMultiplayer, "Save Anywhere - Multiplayer detected");
4751 GUI.FocusWindow(0x5A5E02);
4752 }
4753 GUI.matrix = old;
4754 return;
4755 }
4756
4757 if (CloudVisible())
4758 {
4759 GUI.color = new Color(0f, 0f, 0f, 0.6f);
4760 GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture);
4761 GUI.color = Color.white;
4762 float w = 680f;
4763 cloudRect = new Rect((vw - w) * 0.5f, vh * 0.5f - 260f, w, 0f);
4764 cloudRect = GUILayout.Window(0x5A5E01, cloudRect, DrawCloudPrompt, "Save Anywhere " + Plugin.Version);
4765 GUI.FocusWindow(0x5A5E01);
4766 }
4767 else if (SettingsVisible())
4768 {
4769 Event ev = Event.current;
4770 if (ev.type == EventType.KeyDown && ev.keyCode == KeyCode.Escape && !settingsBusy) { settingsOpen = false; ev.Use(); }
4771 GUI.color = new Color(0f, 0f, 0f, 0.6f);
4772 GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture);
4773 GUI.color = Color.white;
4774 float sw = Mathf.Min(760f, vw - 40f);
4775 settingsRect = new Rect((vw - sw) * 0.5f, Mathf.Max(20f, vh * 0.5f - 330f), sw, 0f);
4776 settingsRect = GUILayout.Window(0x5A5E04, settingsRect, DrawCloudSettings, "Save Anywhere " + Plugin.Version);
4777 GUI.FocusWindow(0x5A5E04);
4778 }
4779 else if (InactiveVisible())
4780 {
4781 GUI.color = new Color(0f, 0f, 0f, 0.6f);
4782 GUI.DrawTexture(new Rect(0, 0, vw, vh), Texture2D.whiteTexture);
4783 GUI.color = Color.white;
4784 float iw = Mathf.Min(620f, vw - 40f);
4785 Rect ir = new Rect((vw - iw) * 0.5f, vh * 0.5f - 200f, iw, 0f);
4786 GUILayout.Window(0x5A5E05, ir, DrawInactive, "Save Anywhere " + Plugin.Version);
4787 GUI.FocusWindow(0x5A5E05);
4788 }
4789
4790 if (SlotScreen.Open && SlotScreen.SaveMode && InRun())
4791 {
4792 SlotScreen.Draw(vw, vh);
4793 }
4794 else if (SlotsAvailable())
4795 {
4796 if (SlotScreen.Open) SlotScreen.Draw(vw, vh);
4797 else
4798 {
4799 SlotScreen.DrawMenuButton(vw);
4800 DrawCloudButton(vw);
4801 if (!SelfUpdate.Checked) Runner.Run(SelfUpdate.Check());
4802 SelfUpdate.DrawBanner(vw);
4803 }
4804 }
4805
4806 if (InRun() && PauseHandler.paused && !WorldGeneration.world.generatingWorld && !SlotScreen.Open && !PauseRing.Built)
4807 {
4808 float bw = 200f, bh = 40f, gap = 12f;
4809 float x = (vw - (bw * 3f + gap * 2f)) * 0.5f, y = 24f;
4810 if (GUI.Button(new Rect(x, y, bw, bh), "Save", btnStyle)) ClickSave();
4811 if (GUI.Button(new Rect(x + bw + gap, y, bw, bh), "Save & Quit", btnStyle)) ClickSaveQuit();
4812 if (GUI.Button(new Rect(x + (bw + gap) * 2f, y, bw, bh), AutoLabel(), btnStyle)) ClickAuto();
4813 }
4814
4815 DrawPill(vw, InRun() && PauseHandler.paused && PauseRing.Built);
4816 GUI.matrix = old;
4817 }
4818
4819 private void DrawMultiplayer(int id)
4820 {
4821 GUILayout.Space(8f);
4822 GUILayout.Label("MULTIPLAYER MOD DETECTED", titleStyle);
4823 GUILayout.Space(8f);
4824 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);
4825 GUILayout.Space(6f);
4826 GUILayout.Label("<color=#aaaaaa>Found: " + string.Join(", ", MultiplayerGuard.Found.ToArray()) + "</color>", bodyStyle);
4827 GUILayout.Space(6f);
4828 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);
4829 GUILayout.Space(8f);
4830 GUILayout.Label("<color=#ffd966><b>Not using a multiplayer mod?</b> 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.</color>", bodyStyle);
4831 GUILayout.Space(12f);
4832 if (!string.IsNullOrEmpty(Plugin.BugsUrl) && GUILayout.Button("Report a false alarm (opens the Bugs page)", btnStyle, GUILayout.Height(36f)))
4833 Application.OpenURL(Plugin.BugsUrl);
4834 if (GUILayout.Button("OK", btnStyle, GUILayout.Height(40f))) mpPopupOpen = false;
4835 GUILayout.Space(4f);
4836 }
4837
4838 private GUIStyle leftStyle;
4839
4840 private void CloudStyles()
4841 {
4842 if (smallStyle != null) return;
4843 smallStyle = new GUIStyle(GUI.skin.label) { fontSize = 13, alignment = TextAnchor.UpperRight, wordWrap = true, richText = true };
4844 smallStyle.normal.textColor = new Color(0.85f, 0.85f, 0.85f);
4845 leftStyle = new GUIStyle(bodyStyle) { alignment = TextAnchor.UpperLeft };
4846 }
4847
4848 private void DrawCloudButton(float vw)
4849 {
4850 CloudStyles();
4851 Rect r = new Rect(vw - 250f, 84f, 230f, 34f);
4852 if (GUI.Button(r, Plugin.CloudEnabled.Value ? "Cloud saves: ON" : "Cloud saves: OFF", btnStyle))
4853 {
4854 if (Plugin.CloudEnabled.Value)
4855 {
4856 Plugin.CloudEnabled.Value = false;
4857 Cloud.Reset();
4858 Plugin.Log.LogInfo("Cloud saves turned off.");
4859 }
4860 else cloudPromptOpen = true;
4861 }
4862 if (!Plugin.CloudEnabled.Value) return;
4863 if (GUI.Button(new Rect(vw - 250f, 124f, 230f, 30f), "CLOUD SETTINGS", btnStyle)) OpenSettings();
4864 string line = Cloud.StatusLine();
4865 if (line.Length > 0) GUI.Label(new Rect(vw - 340f, 158f, 320f, 70f), line, smallStyle);
4866 }
4867
4868 private bool settingsOpen;
4869 private bool settingsBusy;
4870 private string settingsMsg = "";
4871 private bool settingsMsgBad;
4872 private string usageLine = "";
4873 private string shownCode = "";
4874 private string shownKey = "";
4875 private string codeInput = "";
4876 private string keyInput = "";
4877 private bool signOutOthers;
4878 private string settingsConfirm = "";
4879 private Rect settingsRect;
4880
4881 private bool SettingsVisible()
4882 {
4883 return settingsOpen && onMenu && !MultiplayerGuard.Detected && !cuPopup;
4884 }
4885
4886 private void OpenSettings()
4887 {
4888 settingsOpen = true;
4889 settingsMsg = "";
4890 shownCode = "";
4891 shownKey = "";
4892 codeInput = "";
4893 keyInput = "";
4894 signOutOthers = false;
4895 settingsConfirm = "";
4896 RefreshUsage();
4897 }
4898
4899 private void RefreshUsage()
4900 {
4901 usageLine = "Checking...";
4902 StartCoroutine(Cloud.GetUsage(s => usageLine = s));
4903 }
4904
4905 private void Busy(IEnumerator routine)
4906 {
4907 settingsBusy = true;
4908 settingsMsg = "Working...";
4909 settingsMsgBad = false;
4910 StartCoroutine(BusyRoutine(routine));
4911 }
4912
4913 private IEnumerator BusyRoutine(IEnumerator routine)
4914 {
4915 yield return StartCoroutine(routine);
4916 settingsBusy = false;
4917 }
4918
4919 private void Say(string msg, bool bad)
4920 {
4921 settingsMsg = msg ?? "";
4922 settingsMsgBad = bad;
4923 }
4924
4925 private void DrawCloudSettings(int wid)
4926 {
4927 CloudStyles();
4928 GUILayout.Space(6f);
4929 GUILayout.Label("CLOUD SETTINGS", titleStyle);
4930 GUILayout.Label("<color=#aaaaaa>" + usageLine + "</color>", bodyStyle);
4931 GUILayout.Space(8f);
4932 bool was = GUI.enabled;
4933 GUI.enabled = !settingsBusy;
4934
4935 GUILayout.Label("<b>Use your cloud saves on another device</b>", leftStyle);
4936 GUILayout.BeginHorizontal();
4937 if (GUILayout.Button("GET A LINK CODE", btnStyle, GUILayout.Height(32f), GUILayout.Width(220f)))
4938 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); }));
4939 GUILayout.Label(shownCode.Length > 0 ? "<size=26><b><color=#ffd27f>" + shownCode + "</color></b></size>" : "<color=#888888>Get a code here, then type it on the other device.</color>", leftStyle);
4940 GUILayout.EndHorizontal();
4941 GUILayout.Space(4f);
4942 GUILayout.BeginHorizontal();
4943 GUILayout.Label("Code from another device:", leftStyle, GUILayout.Width(220f));
4944 codeInput = GUILayout.TextField(codeInput, 7, GUILayout.Width(120f), GUILayout.Height(30f));
4945 if (GUILayout.Button(settingsConfirm == "link" ? "SURE? LINK" : "LINK THIS PC", btnStyle, GUILayout.Height(30f)))
4946 {
4947 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); }
4948 else { settingsConfirm = ""; Busy(Cloud.UseLinkCode(codeInput, (ok, msg) => { Say(msg, !ok); if (ok) { codeInput = ""; RefreshUsage(); } })); }
4949 }
4950 GUILayout.EndHorizontal();
4951
4952 GUILayout.Space(12f);
4953 GUILayout.Label("<b>Recovery key</b> <color=#aaaaaa>(gets your cloud saves back if you lose this PC or reinstall Windows)</color>", leftStyle);
4954 GUILayout.BeginHorizontal();
4955 if (GUILayout.Button(settingsConfirm == "key" ? "SURE? NEW KEY" : "MAKE A RECOVERY KEY", btnStyle, GUILayout.Height(32f), GUILayout.Width(220f)))
4956 {
4957 if (settingsConfirm != "key") { settingsConfirm = "key"; Say("Making a new key cancels any key you made before. Click again to make one.", false); }
4958 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); })); }
4959 }
4960 if (shownKey.Length > 0)
4961 {
4962 GUILayout.Label("<size=18><b><color=#ffd27f>" + shownKey + "</color></b></size>", leftStyle);
4963 if (GUILayout.Button("COPY", btnStyle, GUILayout.Height(32f), GUILayout.Width(80f))) { GUIUtility.systemCopyBuffer = shownKey; Say("Recovery key copied. Paste it somewhere safe.", false); }
4964 }
4965 GUILayout.EndHorizontal();
4966 GUILayout.Space(4f);
4967 GUILayout.BeginHorizontal();
4968 GUILayout.Label("Use a recovery key:", leftStyle, GUILayout.Width(220f));
4969 keyInput = GUILayout.TextField(keyInput, 40, GUILayout.Width(280f), GUILayout.Height(30f));
4970 if (GUILayout.Button("RECOVER", btnStyle, GUILayout.Height(30f)))
4971 Busy(Cloud.UseRecoveryKey(keyInput, signOutOthers, (ok, msg) => { Say(msg, !ok); if (ok) { keyInput = ""; RefreshUsage(); } }));
4972 GUILayout.EndHorizontal();
4973 signOutOthers = GUILayout.Toggle(signOutOthers, " Also sign out every other device (use this if a PC was lost or stolen)");
4974
4975 GUILayout.Space(12f);
4976 GUILayout.BeginHorizontal();
4977 if (GUILayout.Button(settingsConfirm == "out" ? "SURE? SIGN OUT OTHERS" : "SIGN OUT OTHER DEVICES", btnStyle, GUILayout.Height(32f)))
4978 {
4979 if (settingsConfirm != "out") { settingsConfirm = "out"; Say("Every other device linked to your cloud saves will be signed out. Click again to do it.", false); }
4980 else { settingsConfirm = ""; Busy(Cloud.LogoutOthers((ok, msg) => { Say(msg, !ok); RefreshUsage(); })); }
4981 }
4982 GUIStyle danger = new GUIStyle(btnStyle);
4983 danger.normal.textColor = new Color(1f, 0.6f, 0.55f);
4984 if (GUILayout.Button(settingsConfirm == "del" ? "SURE? DELETE EVERYTHING" : "DELETE MY CLOUD DATA", danger, GUILayout.Height(32f)))
4985 {
4986 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); }
4987 else
4988 {
4989 settingsConfirm = "";
4990 Busy(Cloud.DeleteAccount((ok, msg) =>
4991 {
4992 Say(msg, !ok);
4993 if (ok)
4994 {
4995 Plugin.CloudEnabled.Value = false;
4996 Cloud.Reset();
4997 usageLine = "";
4998 }
4999 }));
5000 }
5001 }
5002 GUILayout.EndHorizontal();
5003 GUI.enabled = was;
5004
5005 GUILayout.Space(10f);
5006 if (settingsMsg.Length > 0) GUILayout.Label("<color=" + (settingsMsgBad ? "#ff9999" : "#ffd966") + ">" + settingsMsg + "</color>", bodyStyle);
5007 GUILayout.Space(6f);
5008 if (GUILayout.Button("CLOSE", btnStyle, GUILayout.Height(36f))) settingsOpen = false;
5009 GUILayout.Space(4f);
5010 }
5011
5012 private bool InactiveVisible()
5013 {
5014 return Cloud.InactiveNote.Length > 0 && onMenu && !MultiplayerGuard.Detected && !cuPopup && !CloudVisible() && !SettingsVisible();
5015 }
5016
5017 private void DrawInactive(int id)
5018 {
5019 CloudStyles();
5020 GUILayout.Space(8f);
5021 GUILayout.Label("<color=#ffd27f>CLOUD ACCOUNT WAS INACTIVE</color>", titleStyle);
5022 GUILayout.Space(6f);
5023 GUILayout.Label(Cloud.InactiveNote, bodyStyle);
5024 GUILayout.Space(10f);
5025 if (GUILayout.Button("OK, GOT IT", btnStyle, GUILayout.Height(38f))) Cloud.InactiveNote = "";
5026 GUILayout.Space(4f);
5027 }
5028
5029 private void DrawCloudPrompt(int id)
5030 {
5031 CloudStyles();
5032 GUILayout.Space(8f);
5033 GUILayout.Label("CLOUD SAVES (VERY EXPERIMENTAL)", titleStyle);
5034 GUILayout.Space(8f);
5035 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);
5036 GUILayout.Space(8f);
5037 GUILayout.Label("<color=#ffd966>\u2022 This is a <b>very experimental</b> 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 <b>Keep backing up your Save Anywhere saves yourself anyway.</b> Don't rely on the cloud as your only copy.</color>", leftStyle);
5038 GUILayout.Space(8f);
5039 GUILayout.Label("<color=#aaaaaa>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.</color>", bodyStyle);
5040 GUILayout.Space(12f);
5041 GUILayout.BeginHorizontal();
5042 if (GUILayout.Button("Yes, turn on cloud saves", btnStyle, GUILayout.Height(40f)))
5043 {
5044 Plugin.CloudEnabled.Value = true;
5045 Plugin.CloudAsked.Value = true;
5046 cloudPromptOpen = false;
5047 Cloud.Reset();
5048 Plugin.Log.LogInfo("Cloud saves turned on.");
5049 }
5050 if (GUILayout.Button("No thanks", btnStyle, GUILayout.Height(40f)))
5051 {
5052 Plugin.CloudEnabled.Value = false;
5053 Plugin.CloudAsked.Value = true;
5054 cloudPromptOpen = false;
5055 Plugin.Log.LogInfo("Cloud saves left off.");
5056 }
5057 GUILayout.EndHorizontal();
5058 GUILayout.Space(6f);
5059 GUILayout.BeginHorizontal();
5060 if (GUILayout.Button("Open save folder (make a backup)", btnStyle, GUILayout.Height(30f)))
5061 {
5062 try { System.Diagnostics.Process.Start("explorer.exe", "\"" + Paths.Dir.Replace('/', '\\') + "\""); }
5063 catch (Exception e) { Plugin.Log.LogError("Couldn't open the save folder: " + e.Message); }
5064 }
5065 if (!string.IsNullOrEmpty(Plugin.BugsUrl) && GUILayout.Button("Report a bug", btnStyle, GUILayout.Height(30f)))
5066 Application.OpenURL(Plugin.BugsUrl);
5067 GUILayout.EndHorizontal();
5068 GUILayout.Space(4f);
5069 }
5070
5071 }
5072}