Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of PersistentMoons v0.1.1
PersistentMoons.dll
Decompiled 35 minutes ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using DunGen; using HarmonyLib; using Microsoft.CodeAnalysis; using ModMenu; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("PersistentMoons")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.1.0")] [assembly: AssemblyInformationalVersion("0.1.1+7580bc23ef579f194089ab813cc8dfc65404bab2")] [assembly: AssemblyProduct("PersistentMoons")] [assembly: AssemblyTitle("PersistentMoons")] [assembly: AssemblyVersion("0.1.1.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace PersistentMoons { [Serializable] public class Spot { public float x; public float y; public float z; public Vector3 V => new Vector3(x, y, z); public Spot() { } public Spot(Vector3 v) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) x = v.x; y = v.y; z = v.z; } } [HarmonyPatch] internal static class Facility { private class Snapshot { public int levelID; public string doors; public string bigDoors; public int doorCount; public int lockedCount; public int bigCount; public List<Spot> spent; public bool power; } private static readonly FieldInfo BigDoorOpen = AccessTools.Field(typeof(TerminalAccessibleObject), "isDoorOpen"); private const float DoorMatch = 2f; private static Snapshot pending; private static int _daySeed = int.MinValue; private static bool IsHost { get { if ((Object)(object)NetworkManager.Singleton != (Object)null) { return NetworkManager.Singleton.IsServer; } return false; } } internal static List<DoorLock> Doors() { return ByPosition(Object.FindObjectsOfType<DoorLock>(), (DoorLock d) => ((Component)d).transform.position); } internal static List<TerminalAccessibleObject> BigDoors() { return ByPosition(from t in Object.FindObjectsOfType<TerminalAccessibleObject>() where t.isBigDoor select t, (TerminalAccessibleObject t) => ((Component)t).transform.position); } internal static List<T> ByPosition<T>(IEnumerable<T> items, Func<T, Vector3> pos) { return (from o in items select (o: o, p: pos(o)) into e orderby Mathf.RoundToInt(e.p.x * 10f), Mathf.RoundToInt(e.p.y * 10f), Mathf.RoundToInt(e.p.z * 10f) select e.o).ToList(); } private static string Dm(Vector3 p) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) return $"{Mathf.RoundToInt(p.x * 10f)},{Mathf.RoundToInt(p.y * 10f)},{Mathf.RoundToInt(p.z * 10f)}"; } internal static string EncodeDoors(List<DoorLock> doors) { return doors.Count + "|" + string.Join(";", from d in doors where d.isLocked select Dm(((Component)d).transform.position)); } internal static bool DecodeDoors(string s, out int count, out List<Vector3> locked) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) count = 0; locked = new List<Vector3>(); if (string.IsNullOrEmpty(s)) { return false; } int num = s.IndexOf('|'); if (num < 0 || !int.TryParse(s.Substring(0, num), out count)) { return false; } string[] array = s.Substring(num + 1).Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { string[] array2 = array[i].Split(','); if (array2.Length != 3 || !int.TryParse(array2[0], out var result) || !int.TryParse(array2[1], out var result2) || !int.TryParse(array2[2], out var result3)) { return false; } locked.Add(new Vector3((float)result / 10f, (float)result2 / 10f, (float)result3 / 10f)); } return true; } private static HashSet<DoorLock> MatchLocked(List<DoorLock> doors, List<Vector3> spots) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) HashSet<DoorLock> hashSet = new HashSet<DoorLock>(); foreach (Vector3 s in spots) { DoorLock val = doors.OrderBy(delegate(DoorLock o) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) Vector3 val3 = ((Component)o).transform.position - s; return ((Vector3)(ref val3)).sqrMagnitude; }).FirstOrDefault(); if (!((Object)(object)val == (Object)null)) { Vector3 val2 = ((Component)val).transform.position - s; if (!(((Vector3)(ref val2)).sqrMagnitude > 4f)) { if (!hashSet.Add(val)) { return null; } continue; } } return null; } return hashSet; } private static string Pattern(List<DoorLock> doors) { return new string(doors.Select((DoorLock d) => (!d.isLocked) ? 'U' : 'L').ToArray()); } [HarmonyPatch(typeof(StartOfRound), "ShipHasLeft")] [HarmonyPrefix] [HarmonyPriority(800)] private static void ShipLeftPre(StartOfRound __instance) { pending = null; if (!Plugin.Active || !IsHost || (Object)(object)__instance.currentLevel == (Object)null) { return; } try { List<DoorLock> list = Doors(); List<TerminalAccessibleObject> list2 = BigDoors(); pending = new Snapshot { levelID = __instance.currentLevel.levelID, doors = EncodeDoors(list), bigDoors = new string(list2.Select((TerminalAccessibleObject b) => (!(bool)BigDoorOpen.GetValue(b)) ? 'C' : 'O').ToArray()), doorCount = list.Count, lockedCount = list.Count((DoorLock d) => d.isLocked), bigCount = list2.Count, spent = (from m in Object.FindObjectsOfType<Landmine>() where m.hasExploded select new Spot(((Component)m).transform.position)).ToList(), power = ((Object)(object)RoundManager.Instance != (Object)null && RoundManager.Instance.powerOffPermanently) }; } catch (Exception ex) { Plugin.Log.LogError((object)("Could not read the facility state: " + ex)); } } [HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")] [HarmonyPrefix] [HarmonyPriority(800)] private static void DespawnPre(RoundManager __instance, bool despawnAllItems) { Snapshot snapshot = pending; pending = null; if (!Plugin.Active || !IsHost || despawnAllItems) { return; } MoonRecord moonRecord = (((Object)(object)__instance.currentLevel != (Object)null) ? State.Find(__instance.currentLevel.levelID) : null); if (moonRecord == null) { return; } if (snapshot == null || snapshot.levelID != __instance.currentLevel.levelID) { Plugin.Log.LogWarning((object)(moonRecord.levelName + ": no facility snapshot from take-off; doors and mines kept as they were saved before.")); return; } try { moonRecord.doors = snapshot.doors; moonRecord.bigDoors = snapshot.bigDoors; moonRecord.spentMines = (moonRecord.spentMines ?? new List<Spot>()).Concat(snapshot.spent).ToList(); moonRecord.apparatusPulled |= snapshot.power || __instance.powerOffPermanently; Plugin.Log.LogInfo((object)string.Format("{0}: doors {1}, {2}/{3} locked, {4}/{5} big doors open, {6} mine(s) spent{7}.", moonRecord.levelName, moonRecord.doors, snapshot.lockedCount, snapshot.doorCount, moonRecord.bigDoors.Count((char c) => c == 'O'), snapshot.bigCount, moonRecord.spentMines.Count, moonRecord.apparatusPulled ? ", apparatus pulled" : "")); } catch (Exception ex) { Plugin.Log.LogError((object)("Could not save the facility state: " + ex)); } } private static void Pin() { Layout.Plan current = Layout.Current; StartOfRound instance = StartOfRound.Instance; if (Plugin.Active && current != null && current.Replay && !((Object)(object)instance == (Object)null) && current.Day == instance.randomMapSeed && _daySeed == int.MinValue) { _daySeed = instance.randomMapSeed; instance.randomMapSeed = current.MapSeed; } } private static void Unpin() { if (_daySeed != int.MinValue) { StartOfRound.Instance.randomMapSeed = _daySeed; _daySeed = int.MinValue; } } [HarmonyPatch(typeof(RoundManager), "SpawnMapObjects")] [HarmonyPrefix] private static void MapObjectsPre() { Pin(); } [HarmonyPatch(typeof(RoundManager), "SpawnMapObjects")] [HarmonyFinalizer] private static void MapObjectsFin() { Unpin(); RemoveSpentMines(); } [HarmonyPatch(typeof(RoundManager), "SetBigDoorCodes")] [HarmonyPrefix] private static void BigCodesPre() { Pin(); } [HarmonyPatch(typeof(RoundManager), "SetBigDoorCodes")] [HarmonyFinalizer] private static void BigCodesFin() { Unpin(); ApplyBigDoorsLater(); } [HarmonyPatch(typeof(RoundManager), "SetSteamValveTimes")] [HarmonyPrefix] private static void ValvesPre() { Pin(); } [HarmonyPatch(typeof(RoundManager), "SetSteamValveTimes")] [HarmonyFinalizer] private static void ValvesFin() { Unpin(); } [HarmonyPatch(typeof(RoundManager), "SetPowerOffAtStart")] [HarmonyPrefix] private static void PowerPre() { Pin(); } [HarmonyPatch(typeof(RoundManager), "SetPowerOffAtStart")] [HarmonyFinalizer] private static void PowerFin() { Unpin(); ApplyApparatus(); } [HarmonyPatch(typeof(RoundManager), "SetLockedDoors")] [HarmonyPostfix] private static void LockedDoorsPost() { Layout.Plan current = Layout.Current; if (!Plugin.Active || current == null || !current.Replay || string.IsNullOrEmpty(current.Doors)) { return; } try { List<DoorLock> list = Doors(); if (!DecodeDoors(current.Doors, out var count, out var locked)) { Plugin.Log.LogWarning((object)("Door save \"" + current.Doors + "\" is in an old or unknown format: door locks left as rolled today.")); return; } if (list.Count != count) { Plugin.Log.LogWarning((object)$"Door count {list.Count}, saved {count}: door locks left as rolled today."); return; } HashSet<DoorLock> hashSet = MatchLocked(list, locked); if (hashSet == null) { Plugin.Log.LogWarning((object)$"A saved locked door has no door of its own within {2f} m: door locks left as rolled today."); return; } int num = 0; int num2 = 0; foreach (DoorLock item in list) { bool flag = hashSet.Contains(item); if (flag != item.isLocked) { if (flag) { item.LockDoor(30f); num++; } else { item.UnlockDoor(); num2++; } } } Plugin.Log.LogInfo((object)$"Doors set as left: {num} locked, {num2} unlocked; saved {current.Doors}, now {EncodeDoors(list)} ({Pattern(list)})."); if (IsHost && (Object)(object)RoundManager.Instance != (Object)null) { ((MonoBehaviour)RoundManager.Instance).StartCoroutine(CheckDoorsLater(locked)); } } catch (Exception ex) { Plugin.Log.LogError((object)("Could not set the doors: " + ex)); } } private static IEnumerator CheckDoorsLater(List<Vector3> spots) { StartOfRound sor = StartOfRound.Instance; float t0 = Time.realtimeSinceStartup; while ((Object)(object)sor != (Object)null && !sor.shipHasLanded && Time.realtimeSinceStartup - t0 < 120f) { yield return null; } yield return (object)new WaitForSeconds(2f); List<DoorLock> list = Doors(); HashSet<DoorLock> want = MatchLocked(list, spots); if (want != null && list.All((DoorLock d) => d.isLocked == want.Contains(d))) { Plugin.Log.LogInfo((object)("Doors after landing as left (" + EncodeDoors(list) + ").")); } else { Plugin.Log.LogWarning((object)($"Doors after landing {EncodeDoors(list)} ({Pattern(list)}), left {spots.Count} locked at " + string.Join(";", spots.Select(Dm)) + ": changed after the restore.")); } } private static void ApplyBigDoorsLater() { Layout.Plan current = Layout.Current; if (Plugin.Active && IsHost && current != null && current.Replay) { MoonRecord moonRecord = State.Find(RoundManager.Instance.currentLevel.levelID); if (moonRecord != null && !string.IsNullOrEmpty(moonRecord.bigDoors)) { ((MonoBehaviour)RoundManager.Instance).StartCoroutine(BigDoorsAfter(moonRecord.bigDoors)); } } } private static IEnumerator BigDoorsAfter(string want) { yield return (object)new WaitForSeconds(1f); List<TerminalAccessibleObject> list = BigDoors(); if (list.Count != want.Length) { Plugin.Log.LogWarning((object)$"Big door count {list.Count}, saved {want.Length}: left as rolled today."); yield break; } int num = 0; for (int i = 0; i < list.Count; i++) { bool flag = want[i] == 'O'; if ((bool)BigDoorOpen.GetValue(list[i]) != flag) { list[i].SetDoorOpenServerRpc(flag); num++; } } Plugin.Debug($"Big doors set as left ({num} changed)."); } private static void RemoveSpentMines() { if (!Plugin.Active || !IsHost || !Layout.ReplayingToday) { return; } MoonRecord moonRecord = State.Find(RoundManager.Instance.currentLevel.levelID); if (moonRecord?.spentMines == null || moonRecord.spentMines.Count == 0) { return; } int num = 0; Landmine[] array = Object.FindObjectsOfType<Landmine>(); foreach (Landmine m in array) { if (moonRecord.spentMines.Any(delegate(Spot s) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) Vector3 val = s.V - ((Component)m).transform.position; return ((Vector3)(ref val)).sqrMagnitude < 0.25f; })) { NetworkObject componentInParent = ((Component)m).GetComponentInParent<NetworkObject>(); if ((Object)(object)componentInParent != (Object)null && componentInParent.IsSpawned) { componentInParent.Despawn(true); num++; } } } Plugin.Log.LogInfo((object)$"{moonRecord.levelName}: {num} spent mine(s) stay gone."); } private static void ApplyApparatus() { if (!Plugin.Active || !IsHost || !Layout.ReplayingToday) { return; } RoundManager instance = RoundManager.Instance; MoonRecord moonRecord = State.Find(instance.currentLevel.levelID); if (moonRecord == null || !moonRecord.apparatusPulled) { return; } LungProp[] array = Object.FindObjectsOfType<LungProp>(); foreach (LungProp val in array) { if (val.isLungDocked && (Object)(object)((NetworkBehaviour)val).NetworkObject != (Object)null && ((NetworkBehaviour)val).NetworkObject.IsSpawned) { ((NetworkBehaviour)val).NetworkObject.Despawn(true); } } instance.SwitchPower(false); instance.powerOffPermanently = true; Plugin.Log.LogInfo((object)(moonRecord.levelName + ": the apparatus was pulled on an earlier day; the power stays off.")); } } [Serializable] public class ItemRecord { public int id; public string name; public float x; public float y; public float z; public float ry; public int value; public bool hasData; public int data; public bool inside; public bool battery; public float charge; public bool empty; public int mesh = -1; public int mat = -1; } [HarmonyPatch] internal static class Items { internal const int MaxItems = 400; internal const int PerFrame = 40; internal const float TopUp = 0.25f; private static List<ItemRecord> _pending; private static int _pendingLevel = -1; private static float _savedMult = -1f; private static int _savedType = int.MinValue; private static bool IsHost { get { if ((Object)(object)NetworkManager.Singleton != (Object)null) { return NetworkManager.Singleton.IsServer; } return false; } } [HarmonyPatch(typeof(StartOfRound), "ShipHasLeft")] [HarmonyPrefix] [HarmonyPriority(800)] private static void ShipLeftPre(StartOfRound __instance) { _pending = null; _pendingLevel = -1; if (!Plugin.Active || !IsHost || (Object)(object)__instance.currentLevel == (Object)null || (Object)(object)RoundManager.Instance == (Object)null) { return; } try { _pending = Collect(RoundManager.Instance); _pendingLevel = __instance.currentLevel.levelID; } catch (Exception ex) { Plugin.Log.LogError((object)("Could not list the moon's items at take-off: " + ex)); } } [HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")] [HarmonyPrefix] [HarmonyPriority(800)] private static void DespawnPre(RoundManager __instance, bool despawnAllItems) { List<ItemRecord> pending = _pending; int pendingLevel = _pendingLevel; _pending = null; _pendingLevel = -1; if (!Plugin.Active || !IsHost || despawnAllItems) { return; } SelectableLevel currentLevel = __instance.currentLevel; MoonRecord moonRecord = (((Object)(object)currentLevel != (Object)null) ? State.Find(currentLevel.levelID) : null); if (moonRecord == null) { return; } try { List<ItemRecord> list = Collect(__instance); if (pending != null && pendingLevel == currentLevel.levelID) { if (list.Count != pending.Count) { Plugin.Debug($"{pending.Count - list.Count} item(s) went with the moon's scene after take-off; saved from the take-off list."); } moonRecord.items = pending; } else { moonRecord.items = list; } } catch (Exception ex) { Plugin.Log.LogError((object)("Could not save the moon's items: " + ex)); return; } Plugin.Log.LogInfo((object)$"{moonRecord.levelName}: {moonRecord.items.Count} item(s) left on the moon (~${moonRecord.items.Sum((ItemRecord i) => i.value)})."); } private static List<ItemRecord> Collect(RoundManager rm) { //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; List<Item> all = instance.allItemsList.itemsList; HashSet<GameObject> hashSet = new HashSet<GameObject>(rm.spawnedSyncedObjects.Where((GameObject o) => (Object)(object)o != (Object)null)); List<ItemRecord> list = new List<ItemRecord>(); GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>(); foreach (GrabbableObject val in array) { if ((Object)(object)val == (Object)null || (Object)(object)val.itemProperties == (Object)null || val.isHeld || val.isInShipRoom || val.isInElevator || val.deactivated || (Object)(object)((NetworkBehaviour)val).NetworkObject == (Object)null || !((NetworkBehaviour)val).NetworkObject.IsSpawned || val is RagdollGrabbableObject) { continue; } LungProp val2 = (LungProp)(object)((val is LungProp) ? val : null); if ((val2 != null && val2.isLungDocked) || (hashSet.Contains(((Component)val).gameObject) && !(val is LungProp)) || (Object)(object)((Component)val).GetComponentInParent<VehicleController>() != (Object)null || ((Component)val).transform.position.y < -1500f) { continue; } int num2 = all.IndexOf(val.itemProperties); if (num2 >= 0) { ItemRecord itemRecord = new ItemRecord { id = num2, name = val.itemProperties.itemName, ry = ((Component)val).transform.eulerAngles.y, value = (val.itemProperties.isScrap ? val.scrapValue : 0), inside = val.isInFactory }; Vector3 val3 = ((val.reachedFloorTarget || val.hasHitGround) ? ((Component)val).transform.position : val.targetFloorPosition); if ((Object)(object)((Component)val).transform.parent != (Object)null && !val.reachedFloorTarget && !val.hasHitGround) { val3 = ((Component)val).transform.parent.TransformPoint(val.targetFloorPosition); } itemRecord.x = val3.x; itemRecord.y = val3.y; itemRecord.z = val3.z; if (val.itemProperties.saveItemVariable) { itemRecord.hasData = true; itemRecord.data = val.GetItemDataToSave(); } if (val.itemProperties.requiresBattery && val.insertedBattery != null) { itemRecord.battery = true; itemRecord.charge = val.insertedBattery.charge; itemRecord.empty = val.insertedBattery.empty; } itemRecord.mesh = VariantIndex(val, out itemRecord.mat); list.Add(itemRecord); } } if (list.Count > 400) { list = (from i in list orderby all[i.id].isScrap descending, i.value descending select i).Take(400).ToList(); Plugin.Log.LogWarning((object)$"More than {400} items on the moon: kept the {400} most valuable."); } return list; } private static int VariantIndex(GrabbableObject g, out int mat) { mat = -1; int result = -1; try { Item itemProperties = g.itemProperties; MeshFilter component = ((Component)g).GetComponent<MeshFilter>(); if ((Object)(object)component != (Object)null && itemProperties.meshVariants != null && itemProperties.meshVariants.Length != 0) { result = Array.IndexOf(itemProperties.meshVariants, component.sharedMesh); } MeshRenderer component2 = ((Component)g).GetComponent<MeshRenderer>(); if ((Object)(object)component2 != (Object)null && itemProperties.materialVariants != null && itemProperties.materialVariants.Length != 0) { mat = Array.IndexOf(itemProperties.materialVariants, ((Renderer)component2).sharedMaterial); } } catch { } return result; } [HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")] [HarmonyPrefix] [HarmonyPriority(800)] private static void SpawnScrapPre(RoundManager __instance) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) if (!Plugin.Active || !IsHost || !Layout.ReplayingToday) { return; } MoonRecord moonRecord = State.Find(__instance.currentLevel.levelID); if (moonRecord == null) { return; } List<ItemRecord> list = moonRecord.items ?? new List<ItemRecord>(); int num = 0; RandomScrapSpawn[] array = Object.FindObjectsOfType<RandomScrapSpawn>(); foreach (RandomScrapSpawn val in array) { Vector3 p = ((Component)val).transform.position; if (list.Any(delegate(ItemRecord itemRecord) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) Vector3 val2 = new Vector3(itemRecord.x, itemRecord.y, itemRecord.z) - p; return ((Vector3)(ref val2)).sqrMagnitude < 2.25f; })) { val.spawnUsed = true; num++; } } _savedMult = __instance.scrapAmountMultiplier; __instance.scrapAmountMultiplier *= 0.25f; if (__instance.currentDungeonType == 4) { _savedType = 4; __instance.currentDungeonType = -1; } Plugin.Log.LogInfo((object)$"{moonRecord.levelName}: restoring {list.Count} item(s); new scrap cut to {0.25f:P0} ({num} spawn points kept clear)."); ((MonoBehaviour)__instance).StartCoroutine(Restore(__instance, list)); } [HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")] [HarmonyFinalizer] private static void SpawnScrapFinal(RoundManager __instance) { if (_savedMult >= 0f) { __instance.scrapAmountMultiplier = _savedMult; _savedMult = -1f; } if (_savedType != int.MinValue) { __instance.currentDungeonType = _savedType; _savedType = int.MinValue; } } private static IEnumerator Restore(RoundManager rm, List<ItemRecord> items) { List<Item> all = StartOfRound.Instance.allItemsList.itemsList; List<(NetworkObject no, ItemRecord r)> spawned = new List<(NetworkObject, ItemRecord)>(); int n = 0; int lost = 0; int moved = 0; Vector3 val2 = default(Vector3); NavMeshHit val3 = default(NavMeshHit); foreach (ItemRecord r in items) { if (r.id < 0 || r.id >= all.Count || (Object)(object)all[r.id] == (Object)null || all[r.id].itemName != r.name) { int num = all.FindIndex((Item i) => (Object)(object)i != (Object)null && i.itemName == r.name); if (num < 0) { lost++; continue; } r.id = num; } Item val = all[r.id]; if ((Object)(object)val.spawnPrefab == (Object)null) { lost++; continue; } ((Vector3)(ref val2))..ctor(r.x, r.y, r.z); if (!NavMesh.SamplePosition(val2, ref val3, 3f, -1)) { val2 = ((!NavMesh.SamplePosition(val2, ref val3, 30f, -1)) ? MainEntrance(r.inside) : (((NavMeshHit)(ref val3)).position + Vector3.up * 0.2f)); moved++; } try { GrabbableObject component = Object.Instantiate<GameObject>(val.spawnPrefab, val2 + Vector3.up * 0.05f, Quaternion.Euler(val.restingRotation.x, r.ry, val.restingRotation.z), rm.spawnedScrapContainer).GetComponent<GrabbableObject>(); component.fallTime = 0f; component.isInFactory = r.inside; if (val.isScrap) { component.SetScrapValue(r.value); } if (r.hasData) { component.LoadItemSaveData(r.data); } if (r.battery) { component.insertedBattery = new Battery(r.empty, r.charge); } ApplyVariant(component, r.mesh, r.mat); LungProp val4 = (LungProp)(object)((component is LungProp) ? component : null); if (val4 != null) { val4.isLungDocked = false; val4.isLungPowered = false; } ((NetworkBehaviour)component).NetworkObject.Spawn(false); spawned.Add((((NetworkBehaviour)component).NetworkObject, r)); } catch (Exception ex) { lost++; Plugin.Log.LogWarning((object)("Could not restore " + r.name + ": " + ex.Message)); } int num2 = n + 1; n = num2; if (num2 % 40 == 0) { yield return null; } } if (lost > 0 || moved > 0) { Plugin.Log.LogInfo((object)$"Restore: {lost} item(s) could not come back, {moved} moved to the nearest floor."); } yield return (object)new WaitForSeconds(13f); List<Net.ItemState> list = new List<Net.ItemState>(); float num3 = 0f; foreach (var (val5, itemRecord) in spawned) { if (!((Object)(object)val5 == (Object)null) && val5.IsSpawned) { list.Add(new Net.ItemState { Id = val5.NetworkObjectId, Value = itemRecord.value, Inside = itemRecord.inside, Battery = itemRecord.battery, Charge = itemRecord.charge, Empty = itemRecord.empty, Mesh = itemRecord.mesh, Mat = itemRecord.mat }); if (all[itemRecord.id].isScrap) { num3 += (float)itemRecord.value; } } } rm.totalScrapValueInLevel += num3; Net.SendItemStates(list, num3); } internal static void ApplyVariant(GrabbableObject g, int mesh, int mat) { try { Item itemProperties = g.itemProperties; if (mesh >= 0 && itemProperties.meshVariants != null && mesh < itemProperties.meshVariants.Length) { MeshFilter component = ((Component)g).GetComponent<MeshFilter>(); if ((Object)(object)component != (Object)null) { component.mesh = itemProperties.meshVariants[mesh]; } } if (mat >= 0 && itemProperties.materialVariants != null && mat < itemProperties.materialVariants.Length) { MeshRenderer component2 = ((Component)g).GetComponent<MeshRenderer>(); if ((Object)(object)component2 != (Object)null) { ((Renderer)component2).sharedMaterial = itemProperties.materialVariants[mat]; } } } catch { } } internal static void ApplyState(Net.ItemState s) { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown if ((Object)(object)NetworkManager.Singleton == (Object)null || !NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(s.Id, out var value)) { return; } GrabbableObject component = ((Component)value).GetComponent<GrabbableObject>(); if (!((Object)(object)component == (Object)null)) { if (component.itemProperties.isScrap) { component.SetScrapValue(s.Value); } component.isInFactory = s.Inside; if (s.Battery) { component.insertedBattery = new Battery(s.Empty, s.Charge); } ApplyVariant(component, s.Mesh, s.Mat); LungProp val = (LungProp)(object)((component is LungProp) ? component : null); if (val != null) { val.isLungDocked = false; val.isLungPowered = false; } } } private static Vector3 MainEntrance(bool inside) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) EntranceTeleport[] array = Object.FindObjectsOfType<EntranceTeleport>(); foreach (EntranceTeleport val in array) { if (val.entranceId == 0 && val.isEntranceToBuilding != inside && (Object)(object)val.entrancePoint != (Object)null) { return val.entrancePoint.position; } } return StartOfRound.Instance.outsideShipSpawnPosition.position; } } [HarmonyPatch] internal static class Layout { internal sealed class Plan { public int Day; public bool Replay; public string Flow; public int DunSeed; public float Length; public int MapSeed; public string Doors; } private sealed class Pending { public int LevelId; public string LevelName; public string Flow; public int DunSeed; public float Length; public int MapSeed; } internal static Plan Current; internal static bool ReplayingToday; private static Pending _pending; private static MoonRecord _replaying; private static int _restoreSeed = int.MinValue; private static bool IsHost { get { if ((Object)(object)NetworkManager.Singleton != (Object)null) { return NetworkManager.Singleton.IsServer; } return false; } } [HarmonyPatch(typeof(RoundManager), "LoadNewLevel")] [HarmonyPrefix] private static void LoadNewLevelPre(int randomSeed, SelectableLevel newLevel) { if (!Plugin.Active || !IsHost) { return; } Current = null; _pending = null; _replaying = null; ReplayingToday = false; Plan plan = new Plan { Day = randomSeed }; StartOfRound instance = StartOfRound.Instance; if ((Object)(object)newLevel != (Object)null && newLevel.spawnEnemiesAndScrap && (Object)(object)instance != (Object)null && !instance.isChallengeFile) { MoonRecord moonRecord = State.Find(newLevel.levelID); if (moonRecord != null) { if (Plugin.Blocked().Contains(moonRecord.flowName)) { Plugin.Log.LogInfo((object)(moonRecord.levelName + ": " + moonRecord.flowName + " is on the blocklist; starting fresh.")); State.Data.moons.Remove(moonRecord); } else if (FlowIndex(moonRecord.flowName) < 0) { Plugin.Log.LogWarning((object)(moonRecord.levelName + ": FACILITY LOST, " + moonRecord.flowName + " is no longer installed; starting fresh.")); State.Data.moons.Remove(moonRecord); if (!State.Data.lost.Contains(moonRecord.levelId)) { State.Data.lost.Add(moonRecord.levelId); } } else { plan.Replay = true; plan.Flow = moonRecord.flowName; plan.DunSeed = moonRecord.dunSeed; plan.Length = moonRecord.length; plan.MapSeed = moonRecord.mapSeed; plan.Doors = moonRecord.doors ?? ""; _replaying = moonRecord; } } } Current = plan; ReplayingToday = plan.Replay; Net.SendLayout(plan); Plugin.Log.LogInfo((object)(plan.Replay ? $"{newLevel?.PlanetName}: same facility as day {_replaying.firstDay} ({plan.Flow}, seed {plan.DunSeed}, length {plan.Length})." : (newLevel?.PlanetName + ": fresh facility today."))); } [HarmonyPatch(typeof(RuntimeDungeon), "Generate")] [HarmonyPrefix] [HarmonyPriority(0)] private static void GeneratePre(RuntimeDungeon __instance) { if (!Plugin.Active) { return; } RoundManager instance = RoundManager.Instance; StartOfRound instance2 = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || (Object)(object)instance.dungeonGenerator != (Object)(object)__instance || (Object)(object)instance.currentLevel == (Object)null) { return; } DungeonGenerator generator = __instance.Generator; Plan plan = Current; if (plan == null || plan.Day != instance2.randomMapSeed) { if (!IsHost) { Plugin.Log.LogWarning((object)"No layout from the host for today (host without Persistent Moons, or it came late): generating as usual."); } plan = null; } if (plan != null && plan.Replay) { int num = FlowIndex(plan.Flow); if (num < 0) { Plugin.Log.LogError((object)("Flow " + plan.Flow + " not found on this client; generating as usual (the building will not match).")); } else { Apply(instance, generator, num, plan); } } else if (IsHost && (Object)(object)generator.DungeonFlow != (Object)null && instance.currentLevel.spawnEnemiesAndScrap && !instance2.isChallengeFile) { _pending = new Pending { LevelId = instance.currentLevel.levelID, LevelName = instance.currentLevel.PlanetName, Flow = ((Object)generator.DungeonFlow).name, DunSeed = generator.Seed, Length = generator.LengthMultiplier, MapSeed = instance2.randomMapSeed }; Plugin.Debug($"Recording {_pending.LevelName}: {_pending.Flow}, seed {_pending.DunSeed}, length {_pending.Length}."); } } private static void Apply(RoundManager rm, DungeonGenerator g, int idx, Plan plan) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) IndoorMapType val = rm.dungeonFlowTypes[idx]; g.DungeonFlow = val.dungeonFlow; rm.currentDungeonType = idx; g.ShouldRandomizeSeed = false; g.Seed = plan.DunSeed; g.LengthMultiplier = plan.Length; if (val.restrictBounds == Vector3.zero) { g.RestrictDungeonToBounds = false; } else { g.RestrictDungeonToBounds = true; g.TilePlacementBounds = new Bounds(Vector3.zero, val.restrictBounds * 2f * rm.currentLevel.factorySizeMultiplier); } if ((Object)(object)StartOfRound.Instance.occlusionCuller != (Object)null) { StartOfRound.Instance.occlusionCuller.AdjacentTileDepth = val.cullingTileDepth; } try { IntWithRarity[] dungeonFlowTypes = rm.currentLevel.dungeonFlowTypes; IntWithRarity val2 = null; if (dungeonFlowTypes != null) { IntWithRarity[] array = dungeonFlowTypes; foreach (IntWithRarity val3 in array) { if (val3 != null && val3.id == idx) { val2 = val3; break; } } } if (val2 != null && (Object)(object)val2.overrideLevelAmbience != (Object)null) { SoundManager.Instance.currentLevelAmbience = val2.overrideLevelAmbience; } else if ((Object)(object)rm.currentLevel.levelAmbienceClips != (Object)null) { SoundManager.Instance.currentLevelAmbience = rm.currentLevel.levelAmbienceClips; } } catch (Exception ex) { Plugin.Debug("ambience: " + ex.Message); } StartOfRound instance = StartOfRound.Instance; if (Plugin.PinMapSeed.Value && instance.randomMapSeed != plan.MapSeed) { _restoreSeed = instance.randomMapSeed; instance.randomMapSeed = plan.MapSeed; } Plugin.Log.LogInfo((object)string.Format("Replaying {0}: seed {1}, length {2}{3}.", plan.Flow, plan.DunSeed, plan.Length, (_restoreSeed != int.MinValue) ? $", map seed {plan.MapSeed} while it generates" : "")); } [HarmonyPatch(typeof(RoundManager), "FinishGeneratingLevel")] [HarmonyPostfix] [HarmonyPriority(800)] private static void FinishGeneratingPost(RoundManager __instance) { RestoreSeed(); if (!Plugin.Active || !IsHost) { return; } RuntimeDungeon dungeonGenerator = __instance.dungeonGenerator; object obj; if (dungeonGenerator == null) { obj = null; } else { DungeonGenerator generator = dungeonGenerator.Generator; obj = ((generator != null) ? generator.CurrentDungeon : null); } Dungeon val = (Dungeon)obj; int num = (((Object)(object)val != (Object)null) ? val.AllTiles.Count : (-1)); if (_replaying != null) { _replaying.visits++; if (num != _replaying.tiles) { Plugin.Log.LogWarning((object)$"{_replaying.levelName}: the facility came out with {num} tiles, {_replaying.tiles} on day {_replaying.firstDay}. An interior mod may have changed."); } _replaying = null; return; } Pending p = _pending; _pending = null; if (p == null || num <= 0) { return; } if (Plugin.Blocked().Contains(p.Flow)) { Plugin.Log.LogInfo((object)(p.LevelName + ": " + p.Flow + " is on the blocklist; not remembered.")); return; } State.Data.moons.RemoveAll((MoonRecord m) => m.levelId == p.LevelId); State.Data.moons.Add(new MoonRecord { levelId = p.LevelId, levelName = p.LevelName, flowName = p.Flow, dunSeed = p.DunSeed, length = p.Length, mapSeed = p.MapSeed, tiles = num, firstDay = DayNumber(), visits = 1 }); Plugin.Log.LogInfo((object)$"{p.LevelName}: remembering {p.Flow} ({num} tiles) until the quota ends."); } internal static void RestoreSeed() { if (_restoreSeed != int.MinValue) { StartOfRound.Instance.randomMapSeed = _restoreSeed; _restoreSeed = int.MinValue; } } internal static int FlowIndex(string name) { RoundManager instance = RoundManager.Instance; if ((Object)(object)instance == (Object)null || instance.dungeonFlowTypes == null || string.IsNullOrEmpty(name)) { return -1; } return Array.FindIndex(instance.dungeonFlowTypes, (IndoorMapType t) => t != null && (Object)(object)t.dungeonFlow != (Object)null && ((Object)t.dungeonFlow).name == name); } internal static int DayNumber() { TimeOfDay instance = TimeOfDay.Instance; if ((Object)(object)instance == (Object)null) { return 0; } int deadlineDaysAmount = instance.quotaVariables.deadlineDaysAmount; return Mathf.Clamp(deadlineDaysAmount - instance.daysUntilDeadline + 1, 1, deadlineDaysAmount); } } internal static class MenuHooks { internal const string ModMenuGuid = "daniel.lethalcompany.modmenu"; private const string Tab = "Persistent Moons"; [MethodImpl(MethodImplOptions.NoInlining)] internal static void Register() { MenuApi.Button("Persistent Moons", "Forget remembered moons", (Func<string>)Forget, true, true, (Func<string>)delegate { StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.localPlayerController == (Object)null) { return "not in a game"; } if (!instance.inShipPhase) { return "in orbit only"; } return (State.Data.moons.Count != 0) ? null : "no moons remembered yet"; }, "every moon this quota is fresh again, as after a new quota"); MenuApi.Toggle("Persistent Moons", "Remember moons", (Func<bool>)(() => Plugin.Enabled.Value), (Func<bool, string>)delegate(bool on) { Plugin.Enabled.Value = on; return (!on) ? "moons are fresh every day" : "moons are remembered until the quota ends"; }, true, false, (Func<string>)null, "host: General > Enabled, from the next landing"); } private static string Forget() { int count = State.Data.moons.Count; State.Clear("Mod Menu"); string text = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.currentSaveFileName : null); if (!string.IsNullOrEmpty(text)) { State.Save(text); } return string.Format("forgot {0} remembered moon{1}", count, (count == 1) ? "" : "s"); } } internal static class Net { internal struct ItemState { public ulong Id; public int Value; public bool Inside; public bool Battery; public float Charge; public bool Empty; public int Mesh; public int Mat; } [CompilerGenerated] private static class <>O { public static HandleNamedMessageDelegate <0>__OnLayout; public static HandleNamedMessageDelegate <1>__OnItems; } private const string MsgLayout = "daniel.persistentmoons.layout"; private const string MsgItems = "daniel.persistentmoons.items"; private static NetworkManager _registeredOn; private static readonly List<(ItemState s, float until)> _pendingItems = new List<(ItemState, float)>(); private static bool _pumping; internal static void EnsureRegistered() { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsListening || singleton.CustomMessagingManager == null) { _registeredOn = null; } else if (!((Object)(object)_registeredOn == (Object)(object)singleton)) { singleton.CustomMessagingManager.UnregisterNamedMessageHandler("daniel.persistentmoons.layout"); CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager; object obj = <>O.<0>__OnLayout; if (obj == null) { HandleNamedMessageDelegate val = OnLayout; <>O.<0>__OnLayout = val; obj = (object)val; } customMessagingManager.RegisterNamedMessageHandler("daniel.persistentmoons.layout", (HandleNamedMessageDelegate)obj); singleton.CustomMessagingManager.UnregisterNamedMessageHandler("daniel.persistentmoons.items"); CustomMessagingManager customMessagingManager2 = singleton.CustomMessagingManager; object obj2 = <>O.<1>__OnItems; if (obj2 == null) { HandleNamedMessageDelegate val2 = OnItems; <>O.<1>__OnItems = val2; obj2 = (object)val2; } customMessagingManager2.RegisterNamedMessageHandler("daniel.persistentmoons.items", (HandleNamedMessageDelegate)obj2); Remains.Register(singleton); Summary.Register(singleton); _registeredOn = singleton; Plugin.Debug("Net: handlers registered (" + (singleton.IsServer ? "host" : "client") + ")."); } } internal unsafe static void SendLayout(Layout.Plan p) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) EnsureRegistered(); NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsServer || singleton.CustomMessagingManager == null) { return; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 4096); try { ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref p.Day, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref p.Replay, default(ForPrimitives)); if (p.Replay) { ((FastBufferWriter)(ref val)).WriteValueSafe(p.Flow ?? "", true); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref p.DunSeed, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref p.Length, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref p.MapSeed, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe(p.Doors ?? "", true); } foreach (ulong connectedClientsId in singleton.ConnectedClientsIds) { if (connectedClientsId != 0L) { singleton.CustomMessagingManager.SendNamedMessage("daniel.persistentmoons.layout", connectedClientsId, val, (NetworkDelivery)3); } } } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } private static void OnLayout(ulong sender, FastBufferReader r) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)NetworkManager.Singleton != (Object)null) || !NetworkManager.Singleton.IsServer) { Layout.Plan plan = new Layout.Plan(); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref plan.Day, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<bool>(ref plan.Replay, default(ForPrimitives)); if (plan.Replay) { ((FastBufferReader)(ref r)).ReadValueSafe(ref plan.Flow, true); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref plan.DunSeed, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<float>(ref plan.Length, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref plan.MapSeed, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe(ref plan.Doors, true); } Layout.Current = plan; Plugin.Log.LogInfo((object)(plan.Replay ? $"Host says: same facility ({plan.Flow}, seed {plan.DunSeed}, length {plan.Length})." : "Host says: fresh facility today.")); } } internal unsafe static void SendItemStates(List<ItemState> items, float total) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) EnsureRegistered(); NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsServer || singleton.CustomMessagingManager == null) { return; } FastBufferWriter val = default(FastBufferWriter); for (int i = 0; i < items.Count || i == 0; i += 300) { int num = Mathf.Min(300, items.Count - i); ((FastBufferWriter)(ref val))..ctor(64 + num * 32, (Allocator)2, -1); try { float num2 = ((i == 0) ? total : 0f); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref num2, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); for (int j = i; j < i + num; j++) { ItemState itemState = items[j]; ((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref itemState.Id, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref itemState.Value, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref itemState.Inside, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref itemState.Battery, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref itemState.Charge, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref itemState.Empty, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref itemState.Mesh, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref itemState.Mat, default(ForPrimitives)); } foreach (ulong connectedClientsId in singleton.ConnectedClientsIds) { if (connectedClientsId != 0L) { singleton.CustomMessagingManager.SendNamedMessage("daniel.persistentmoons.items", connectedClientsId, val, (NetworkDelivery)4); } } } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } if (items.Count == 0) { break; } } } private static void OnItems(ulong sender, FastBufferReader r) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)NetworkManager.Singleton != (Object)null) || !NetworkManager.Singleton.IsServer) { float num = default(float); ((FastBufferReader)(ref r)).ReadValueSafe<float>(ref num, default(ForPrimitives)); int num2 = default(int); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref num2, default(ForPrimitives)); if (num > 0f && (Object)(object)RoundManager.Instance != (Object)null) { RoundManager instance = RoundManager.Instance; instance.totalScrapValueInLevel += num; } for (int i = 0; i < num2; i++) { ItemState item = default(ItemState); ((FastBufferReader)(ref r)).ReadValueSafe<ulong>(ref item.Id, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref item.Value, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<bool>(ref item.Inside, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<bool>(ref item.Battery, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<float>(ref item.Charge, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<bool>(ref item.Empty, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref item.Mesh, default(ForPrimitives)); ((FastBufferReader)(ref r)).ReadValueSafe<int>(ref item.Mat, default(ForPrimitives)); _pendingItems.Add((item, Time.realtimeSinceStartup + 20f)); } Plugin.Debug($"Host restored {num2} item(s) here."); if (!_pumping && (Object)(object)StartOfRound.Instance != (Object)null) { ((MonoBehaviour)StartOfRound.Instance).StartCoroutine(Pump()); } } } private static IEnumerator Pump() { _pumping = true; while (_pendingItems.Count > 0) { NetworkManager singleton = NetworkManager.Singleton; NetworkSpawnManager val = ((singleton != null) ? singleton.SpawnManager : null); for (int num = _pendingItems.Count - 1; num >= 0; num--) { var (s, num2) = _pendingItems[num]; if (val != null && val.SpawnedObjects.ContainsKey(s.Id)) { Items.ApplyState(s); _pendingItems.RemoveAt(num); } else if (Time.realtimeSinceStartup > num2) { _pendingItems.RemoveAt(num); } } yield return (object)new WaitForSecondsRealtime(0.5f); } _pumping = false; } } public static class PluginInfo { public const string Guid = "daniel.lethalcompany.persistentmoons"; public const string Name = "Persistent Moons"; public const string Version = "0.1.1"; } [BepInPlugin("daniel.lethalcompany.persistentmoons", "Persistent Moons", "0.1.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { internal static ManualLogSource Log; internal static bool Disabled; internal static string DisabledReason; internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<string> FlowBlocklist; internal static ConfigEntry<bool> PinMapSeed; internal static ConfigEntry<bool> DebugLog; private readonly Harmony _harmony = new Harmony("daniel.lethalcompany.persistentmoons"); internal static bool Active { get { if (!Disabled) { return Enabled.Value; } return false; } } private void Awake() { Log = ((BaseUnityPlugin)this).Logger; Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Remember moons until the quota ends (host decides; everyone needs the mod)."); FlowBlocklist = ((BaseUnityPlugin)this).Config.Bind<string>("General", "FlowBlocklist", "", "Comma-separated dungeon flow names that are never remembered: a moon with one of these interiors starts fresh every day."); PinMapSeed = ((BaseUnityPlugin)this).Config.Bind<bool>("Advanced", "PinMapSeedDuringGeneration", true, "While a remembered interior generates, use the first day's map seed, so interior mods that roll their layout from it (The Complex) come back the same. Scrap, hazards and monsters still roll from the day's own seed."); DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Advanced", "DebugLog", false, "Extra log lines."); foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos) { PluginInfo value = pluginInfo.Value; object obj; if (value == null) { obj = null; } else { BepInPlugin metadata = value.Metadata; obj = ((metadata != null) ? metadata.Name : null); } if (obj == null) { obj = ""; } string text = (string)obj; if (pluginInfo.Key.IndexOf("labyrinthian", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Labyrinthian", StringComparison.OrdinalIgnoreCase) >= 0) { Disabled = true; DisabledReason = text + " (" + pluginInfo.Key + ") is loaded and remembers moons its own way"; } } if (Disabled) { Log.LogWarning((object)("Persistent Moons is off: " + DisabledReason + ".")); return; } if (!Enabled.Value) { Log.LogInfo((object)"Persistent Moons is switched off in the config."); } _harmony.PatchAll(typeof(Layout)); _harmony.PatchAll(typeof(SaveHooks)); _harmony.PatchAll(typeof(Items)); _harmony.PatchAll(typeof(Facility)); _harmony.PatchAll(typeof(Remains)); _harmony.PatchAll(typeof(Summary)); if (Chainloader.PluginInfos.ContainsKey("daniel.lethalcompany.modmenu")) { MenuHooks.Register(); } Log.LogInfo((object)"Persistent Moons 0.1.1 loaded."); } internal static HashSet<string> Blocked() { return new HashSet<string>(from s in (FlowBlocklist.Value ?? "").Split(',') select s.Trim() into s where s.Length > 0 select s, StringComparer.OrdinalIgnoreCase); } internal static void Debug(string s) { if (DebugLog.Value) { Log.LogInfo((object)s); } } } [Serializable] public class BonePose { public string p; public float x; public float y; public float z; public float qx; public float qy; public float qz; public float qw; } [Serializable] public class RemainsRecord { public string player; public int playerId; public int suit; public string ragdoll; public float x; public float y; public float z; public float ry; public bool inside; public int refund; public int day; public List<BonePose> pose = new List<BonePose>(); } public class RemainsProp : PhysicsProp { public RemainsRecord Rec; private bool _built; public void Build(RemainsRecord rec) { Rec = rec; if (_built) { UpdateScan(); return; } _built = true; try { Remains.BuildVisual(this, rec); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not build the remains model: " + ex.Message)); } UpdateScan(); } private void UpdateScan() { ScanNodeProperties componentInChildren = ((Component)this).GetComponentInChildren<ScanNodeProperties>(true); if (!((Object)(object)componentInChildren == (Object)null) && Rec != null) { componentInChildren.headerText = "Remains of " + Rec.player; componentInChildren.subText = ((Rec.refund > 0) ? $"Bring to ship: +${Rec.refund}" : "Bring to ship"); } } } [HarmonyPatch] internal static class Remains { [CompilerGenerated] private static class <>O { public static HandleNamedMessageDelegate <0>__OnRemains; public static HandleNamedMessageDelegate <1>__OnPaid; } internal const string ItemName = "Remains"; private const string MsgRemains = "daniel.persistentmoons.remains"; private const string MsgPaid = "daniel.persistentmoons.remainspaid"; private static GameObject _prefab; private static Item _item; private static readonly List<RemainsRecord> _newToday = new List<RemainsRecord>(); private static readonly List<RemainsRecord> _paying = new List<RemainsRecord>(); private static readonly List<RemainsRecord> _bodies = new List<RemainsRecord>(); private static int _creditsBefore = -1; private static float _pct = 0.2f; private static float _div = 2.5f; private static readonly List<(ulong id, RemainsRecord r, float until)> _pending = new List<(ulong, RemainsRecord, float)>(); private static bool _pumping; private static bool IsHost { get { if ((Object)(object)NetworkManager.Singleton != (Object)null) { return NetworkManager.Singleton.IsServer; } return false; } } [HarmonyPatch(typeof(GameNetworkManager), "Start")] [HarmonyPostfix] private static void GnmStart() { try { BuildPrefab(); } catch (Exception ex) { Plugin.Log.LogError((object)("Remains prefab: " + ex)); } } private static void BuildPrefab() { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Expected O, but got Unknown //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Invalid comparison between Unknown and I4 //IL_034f: Unknown result type (might be due to invalid IL or missing references) //IL_0354: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_prefab != (Object)null) { return; } NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null) { return; } RagdollGrabbableObject val = singleton.NetworkConfig.Prefabs.Prefabs.Select((NetworkPrefab p) => (!((Object)(object)p.Prefab != (Object)null)) ? null : p.Prefab.GetComponent<RagdollGrabbableObject>()).FirstOrDefault((Func<RagdollGrabbableObject, bool>)((RagdollGrabbableObject g) => (Object)(object)g != (Object)null)); if ((Object)(object)val == (Object)null || (Object)(object)((GrabbableObject)val).itemProperties == (Object)null) { Plugin.Log.LogError((object)"No vanilla body item to base the remains on: remains are off."); return; } GameObject val2 = new GameObject("PersistentMoons.Prefabs"); val2.SetActive(false); ((Object)val2).hideFlags = (HideFlags)61; Object.DontDestroyOnLoad((Object)(object)val2); GameObject val3 = new GameObject("PersistentMoons.Remains"); val3.transform.SetParent(val2.transform, false); val3.layer = ((Component)val).gameObject.layer; val3.tag = ((Component)val).gameObject.tag; NetworkObject val4 = val3.AddComponent<NetworkObject>(); val4.AutoObjectParentSync = false; AccessTools.Field(typeof(NetworkObject), "GlobalObjectIdHash").SetValue(val4, StableHash("daniel.lethalcompany.persistentmoons.Remains")); AudioSource component = ((Component)val).GetComponent<AudioSource>(); AudioSource val5 = val3.AddComponent<AudioSource>(); val5.playOnAwake = false; if ((Object)(object)component != (Object)null) { val5.outputAudioMixerGroup = component.outputAudioMixerGroup; val5.spatialBlend = component.spatialBlend; val5.rolloffMode = component.rolloffMode; val5.minDistance = component.minDistance; val5.maxDistance = component.maxDistance; if ((int)component.rolloffMode == 2) { val5.SetCustomCurve((AudioSourceCurveType)0, component.GetCustomCurve((AudioSourceCurveType)0)); } } BoxCollider val6 = val3.AddComponent<BoxCollider>(); val6.center = new Vector3(0f, 0.2f, 0f); val6.size = new Vector3(0.8f, 0.4f, 0.8f); Collider component2 = ((Component)val).GetComponent<Collider>(); ((Collider)val6).isTrigger = (Object)(object)component2 != (Object)null && component2.isTrigger; ScanNodeProperties val7 = ((Component)val).GetComponentInChildren<ScanNodeProperties>(true) ?? singleton.NetworkConfig.Prefabs.Prefabs.Select((NetworkPrefab p) => (!((Object)(object)p.Prefab != (Object)null) || !((Object)(object)p.Prefab.GetComponent<GrabbableObject>() != (Object)null)) ? null : p.Prefab.GetComponentInChildren<ScanNodeProperties>(true)).FirstOrDefault((Func<ScanNodeProperties, bool>)((ScanNodeProperties s) => (Object)(object)s != (Object)null)); if ((Object)(object)val7 != (Object)null) { ScanNodeProperties component3 = Object.Instantiate<GameObject>(((Component)val7).gameObject, val3.transform, false).GetComponent<ScanNodeProperties>(); ((Component)component3).transform.localPosition = val6.center; component3.headerText = "Remains"; component3.subText = "Bring to ship"; component3.scrapValue = 0; component3.nodeType = 0; } Item val8 = Object.Instantiate<Item>(((GrabbableObject)val).itemProperties); ((Object)val8).name = "PersistentMoonsRemains"; val8.itemName = "Remains"; val8.spawnPrefab = val3; val8.isScrap = false; val8.twoHanded = true; val8.twoHandedAnimation = true; val8.itemSpawnsOnGround = true; val8.saveItemVariable = false; val8.requiresBattery = false; val8.meshVariants = (Mesh[])(object)new Mesh[0]; val8.materialVariants = (Material[])(object)new Material[0]; val8.restingRotation = Vector3.zero; val8.floorYOffset = 0; val8.verticalOffset = 0.02f; val8.spawnPositionTypes = new List<ItemGroup>(); RemainsProp remainsProp = val3.AddComponent<RemainsProp>(); ((GrabbableObject)remainsProp).itemProperties = val8; ((GrabbableObject)remainsProp).grabbable = true; ((GrabbableObject)remainsProp).grabbableToEnemies = true; ((GrabbableObject)remainsProp).isInFactory = true; _prefab = val3; _item = val8; singleton.AddNetworkPrefab(val3); Plugin.Log.LogInfo((object)$"Remains item built from \"{((GrabbableObject)val).itemProperties.itemName}\" (weight {val8.weight:F2})."); } [HarmonyPatch(typeof(RoundManager), "DespawnPropsAtEndOfRound")] [HarmonyPrefix] [HarmonyPriority(800)] private static void DespawnPre(RoundManager __instance, bool despawnAllItems) { //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) _newToday.Clear(); if (!Plugin.Active || !IsHost || despawnAllItems) { _bodies.Clear(); return; } try { RemainsProp[] array = Object.FindObjectsOfType<RemainsProp>(); foreach (RemainsProp remainsProp in array) { if (!((Object)(object)remainsProp == (Object)null) && remainsProp.Rec != null && !((Object)(object)((NetworkBehaviour)remainsProp).NetworkObject == (Object)null) && ((NetworkBehaviour)remainsProp).NetworkObject.IsSpawned && (((GrabbableObject)remainsProp).isInShipRoom || ((GrabbableObject)remainsProp).isInElevator)) { _paying.Add(remainsProp.Rec); ((NetworkBehaviour)remainsProp).NetworkObject.Despawn(true); } } SelectableLevel currentLevel = __instance.currentLevel; MoonRecord moonRecord = (((Object)(object)currentLevel != (Object)null) ? State.Find(currentLevel.levelID) : null); if (moonRecord == null) { return; } List<RemainsRecord> list = new List<RemainsRecord>(); array = Object.FindObjectsOfType<RemainsProp>(); foreach (RemainsProp remainsProp2 in array) { if (!((Object)(object)remainsProp2 == (Object)null) && remainsProp2.Rec != null && !((GrabbableObject)remainsProp2).isHeld && !((GrabbableObject)remainsProp2).isInShipRoom && !((GrabbableObject)remainsProp2).isInElevator && ((NetworkBehaviour)remainsProp2).NetworkObject.IsSpawned) { RemainsRecord remainsRecord = JsonUtility.FromJson<RemainsRecord>(JsonUtility.ToJson((object)remainsProp2.Rec)); Vector3 val = FloorPos((GrabbableObject)(object)remainsProp2); remainsRecord.x = val.x; remainsRecord.y = val.y; remainsRecord.z = val.z; remainsRecord.ry = ((Component)remainsProp2).transform.eulerAngles.y; remainsRecord.inside = ((GrabbableObject)remainsProp2).isInFactory; list.Add(remainsRecord); } } foreach (RemainsRecord body in _bodies) { body.day = moonRecord.visits; list.Add(body); _newToday.Add(body); } _bodies.Clear(); moonRecord.remains = list; if (list.Count > 0) { Plugin.Log.LogInfo((object)$"{moonRecord.levelName}: {list.Count} remains left ({_newToday.Count} new today)."); } } catch (Exception ex) { Plugin.Log.LogError((object)("Could not save the remains: " + ex)); } } [HarmonyPatch(typeof(StartOfRound), "ShipHasLeft")] [HarmonyPrefix] private static void ShipLeftPre() { _bodies.Clear(); if (!Plugin.Active || !IsHost) { return; } try { RagdollGrabbableObject[] array = Object.FindObjectsOfType<RagdollGrabbableObject>(); foreach (RagdollGrabbableObject val in array) { if ((Object)(object)val == (Object)null || ((GrabbableObject)val).isHeld || ((GrabbableObject)val).isInShipRoom || ((GrabbableObject)val).isInElevator || (Object)(object)val.ragdoll == (Object)null || !((Component)val.ragdoll).gameObject.activeInHierarchy) { continue; } DeadBodyInfo ragdoll = val.ragdoll; if (!ragdoll.isInShip && !((Object)(object)ragdoll.playerScript == (Object)null)) { RemainsRecord remainsRecord = Record(ragdoll); if (remainsRecord != null) { remainsRecord.inside = ((GrabbableObject)val).isInFactory; _bodies.Add(remainsRecord); } } } if (_bodies.Count > 0) { Plugin.Log.LogInfo((object)string.Format("Ship left: {0} body(ies) left behind ({1}).", _bodies.Count, string.Join(", ", _bodies.Select((RemainsRecord r) => $"{r.player} at {r.x:F1},{r.y:F1},{r.z:F1}")))); } } catch (Exception ex) { Plugin.Log.LogError((object)("Could not snapshot the bodies: " + ex)); } } private static Vector3 FloorPos(GrabbableObject g) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (g.reachedFloorTarget || g.hasHitGround) { return ((Component)g).transform.position; } if (!((Object)(object)((Component)g).transform.parent != (Object)null)) { return g.targetFloorPosition; } return ((Component)g).transform.parent.TransformPoint(g.targetFloorPosition); } private static RemainsRecord Record(DeadBodyInfo dbi) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) Rigidbody[] array = dbi.bodyParts?.Where((Rigidbody p) => (Object)(object)p != (Object)null).ToArray(); if (array == null || array.Length == 0) { return null; } Vector3 val = Vector3.zero; Rigidbody[] array2 = array; foreach (Rigidbody val2 in array2) { val += val2.position; } val /= (float)array.Length; Vector3 val3 = val; RaycastHit val4 = default(RaycastHit); if (Physics.Raycast(val + Vector3.up * 0.3f, Vector3.down, ref val4, 6f, StartOfRound.Instance.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1)) { val3 = ((RaycastHit)(ref val4)).point; } float y = ((Component)dbi).transform.eulerAngles.y; Quaternion inv = Quaternion.Inverse(Quaternion.Euler(0f, y, 0f)); string ragdoll = ((Object)((Component)dbi).gameObject).name.Replace("(Clone)", "").Trim(); RemainsRecord remainsRecord = new RemainsRecord { player = dbi.playerScript.playerUsername, playerId = dbi.playerObjectId, suit = dbi.playerScript.currentSuitID, ragdoll = ragdoll, x = val3.x, y = val3.y, z = val3.z, ry = y }; Transform transform = ((Component)dbi).transform; Transform[] componentsInChildren = ((Component)transform).GetComponentsInChildren<Transform>(true); foreach (Transform t in componentsInChildren) { remainsRecord.pose.Add(Pose(Path(transform, t), t, val3, inv)); } if (dbi.detachedHead && (Object)(object)dbi.detachedHeadObject != (Object)null && !dbi.detachedHeadObject.IsChildOf(transform)) { remainsRecord.pose.Add(Pose("#head", dbi.detachedHeadObject, val3, inv)); } return remainsRecord; } private static BonePose Pose(string path, Transform t, Vector3 anchor, Quaternion inv) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) Vector3 val = inv * (t.position - anchor); Quaternion val2 = inv * t.rotation; return new BonePose { p = path, x = val.x, y = val.y, z = val.z, qx = val2.x, qy = val2.y, qz = val2.z, qw = val2.w }; } private static string Path(Transform root, Transform t) { if ((Object)(object)t == (Object)(object)root) { return ""; } StringBuilder stringBuilder = new StringBuilder(((Object)t).name); Transform parent = t.parent; while ((Object)(object)parent != (Object)null && (Object)(object)parent != (Object)(object)root) { stringBuilder.Insert(0, ((Object)parent).name + "/"); parent = parent.parent; } return stringBuilder.ToString(); } [HarmonyPatch(typeof(HUDManager), "ApplyPenalty")] [HarmonyPrefix] private static void PenaltyPre() { Terminal val = Object.FindObjectOfType<Terminal>(); _creditsBefore = (((Object)(object)val != (Object)null) ? val.groupCredits : (-1)); } [HarmonyPatch(typeof(HUDManager), "ApplyPenalty")] [HarmonyPostfix] private static void PenaltyPost(int playersDead, int bodiesInsured) { if (!IsHost || _creditsBefore < 0 || _newToday.Count == 0) { _creditsBefore = -1; return; } int creditsBefore = _creditsBefore; int num = creditsBefore; int num2 = Mathf.Min(creditsBefore, 60); int num3 = playersDead - Mathf.Max(bodiesInsured, 0); float pct = _pct; int num4 = (int)((float)creditsBefore * (pct / _div)); for (int i = 0; i < num3; i++) { int num5 = num; num = Mathf.Clamp(num - (int)((float)creditsBefore * pct), num2, 10000000); if (i < _newToday.Count) { _newToday[i].refund = Mathf.Max(0, num5 - num - num4); } } Plugin.Log.LogInfo((object)("Remains refunds: " + string.Join(", ", _newToday.Select((RemainsRecord r) => $"{r.player} ${r.refund}")))); _newToday.Clear(); _creditsBefore = -1; } [HarmonyPatch(typeof(StartOfRound), "PassTimeToNextDay")] [HarmonyPrefix] private static void PassDayPre() { if (IsHost && _paying.Count != 0) { List<RemainsRecord> source = _paying.ToList(); _paying.Clear(); int num = source.Sum((RemainsRecord r) => r.refund); Terminal val = Object.FindObjectOfType<Terminal>(); if ((Object)(object)val != (Object)null && num > 0) { val.groupCredits += num; val.SyncGroupCreditsClientRpc(val.groupCredits, val.numberOfItemsInDropship); } string text = string.Join("\n", source.Select((RemainsRecord r) => $"{r.player} +${r.refund}")); Plugin.Log.LogInfo((object)$"Remains recovered: {text.Replace('\n', ',')} (total ${num})."); SendPaid(text); ((MonoBehaviour)StartOfRound.Instance).StartCoroutine(ShowPaid(text)); } } private static IEnumerator ShowPaid(string text) { yield return (object)new WaitForSeconds(2.5f); if ((Object)(object)HUDManager.Instance != (Object)null) { HUDManager.Instance.DisplayTip("Remains recovered", text, false, false, "LC_Tip1"); } } [HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")] [HarmonyPrefix] private static void SpawnScrapPre(RoundManager __instance) { if (Plugin.Active && IsHost && Layout.ReplayingToday && !((Object)(object)_prefab == (Object)null)) { MoonRecord moonRecord = State.Find(__instance.currentLevel.levelID); if (moonRecord?.remains != null && moonRecord.remains.Count != 0) { ((MonoBehaviour)__instance).StartCoroutine(Restore(__instance, moonRecord.remains.ToList())); } } } private static IEnumerator Restore(RoundManager rm, List<RemainsRecord> list) { List<(NetworkObject, RemainsRecord)> spawned = new List<(NetworkObject, RemainsRecord)>(); foreach (RemainsRecord item in list) { try { RemainsProp component = Object.Instantiate<GameObject>(_prefab, new Vector3(item.x, item.y + 0.05f, item.z), Quaternion.Euler(0f, item.ry, 0f), rm.spawnedScrapContainer).GetComponent<RemainsProp>(); ((GrabbableObject)component).fallTime = 0f; ((GrabbableObject)component).isInFactory = item.inside; ((NetworkBehaviour)component).NetworkObject.Spawn(false); component.Build(item); spawned.Add((((NetworkBehaviour)component).NetworkObject, item)); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Could not restore the remains of " + item.player + ": " + ex.Message)); } yield return null; } Plugin.Log.LogInfo((object)$"Restored {spawned.Count} remains."); yield return (object)new WaitForSeconds(1f); foreach (var (val, r) in spawned) { if ((Object)(object)val != (Object)null && val.IsSpawned) { SendRemains(val.NetworkObjectId, r); } } } internal static void BuildVisual(RemainsProp prop, RemainsRecord rec) { StartOfRound instance = StartOfRound.Instance; GameObject val = Object.Instantiate<GameObject>(((IEnumerable<GameObject>)instance.playerRagdolls).FirstOrDefault((Func<GameObject, bool>)((GameObject g) => (Object)(object)g != (Object)null && ((Object)g).name == rec.ragdoll)) ?? instance.playerRagdolls[0], ((Component)prop).transform, false); ((Object)val).name = "Pose"; DeadBodyInfo component = val.GetComponent<DeadBodyInfo>(); Transform val2 = (((Object)(object)component != (Object)null && component.detachedHead) ? component.detachedHeadObject : null); Joint[] componentsInChildren = val.GetComponentsInChildren<Joint>(true); for (int num = 0; num < componentsInChildren.Length; num++) { Object.DestroyImmediate((Object)(object)componentsInChildren[num]); } Rigidbody[] componentsInChildren2 = val.GetComponentsInChildren<Rigidbody>(true); for (int num = 0; num < componentsInChildren2.Length; num++) { Object.DestroyImmediate((Object)(object)componentsInChildren2[num]); } Collider[] componentsInChildren3 = val.GetComponentsInChildren<Collider>(true); for (int num = 0; num < componentsInChildren3.Length; num++) { Object.DestroyImmediate((Object)(object)componentsInChildren3[num]); } MonoBehaviour[] componentsInChildren4 = val.GetComponentsInChildren<MonoBehaviour>(true); for (int num = 0; num < componentsInChildren4.Length; num++) { Object.DestroyImmediate((Object)(object)componentsInChildren4[num]); } AudioSource[] componentsInChildren5 = val.GetComponentsInChildren<AudioSource>(true); for (int num = 0; num < componentsInChildren5.Length; num++) { Object.DestroyImmediate((Object)(object)componentsInChildren5[num]); } ParticleSystem[] componentsInChildren6 = val.GetComponentsInChildren<ParticleSystem>(true); for (int num = 0; num < componentsInChildren6.Length; num++) { ((Component)componentsInChildren6[num]).gameObject.SetActive(false); } Dictionary<string, BonePose> dictionary = rec.pose.ToDictionary((BonePose b) => b.p, (BonePose b) => b); Transform transform = ((Component)prop).transform; int num2 = 0; Transform[] componentsInChildren7 = val.GetComponentsInChildren<Transform>(true); foreach (Transform t in componentsInChildren7) { if (dictionary.TryGetValue(Path(val.transform, t), out var value)) { Apply(t, value, transform); num2++; } } if ((Object)(object)val2 != (Object)null && dictionary.TryGetValue("#head", out var value2)) { Apply(val2, value2, transform); num2++; } SkinnedMeshRenderer[] componentsInChildren8 = val.GetComponentsInChildren<SkinnedMeshRenderer>(true); SkinnedMeshRenderer[] array = componentsInChildren8; foreach (SkinnedMeshRenderer obj in array) { obj.updateWhenOffscreen = true; ((Renderer)obj).renderingLayerMask = 513u; } if (rec.suit > 0 && rec.suit < instance.unlockablesList.unlockables.Count && componentsInChildren8.Length != 0) { Material suitMaterial = instance.unlockablesList.unlockables[rec.suit].suitMaterial; if ((Object)(object)suitMaterial != (Object)null) { ((Renderer)componentsInChildren8[0]).sharedMaterial = suitMaterial; } } Plugin.Debug($"Remains of {rec.player}: {num2}/{rec.pose.Count} bones posed ({rec.ragdoll})."); } private static void Apply(Transform t, BonePose b, Transform frame) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) t.position = frame.TransformPoint(new Vector3(b.x, b.y, b.z)); t.rotation = frame.rotation * new Quaternion(b.qx, b.qy, b.qz, b.qw); } internal static void Register(NetworkManager nm) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown nm.CustomMessagingManager.UnregisterNamedMessageHandler("daniel.persistentmoons.remains"); CustomMessagingManager customMessagingManager = nm.CustomMessagingManager; object obj = <>O.<0>__OnRemains; if (obj == null) { HandleNamedMessageDelegate val = OnRemains; <>O.<0>__OnRemains = val; obj = (object)val; } customMessagingManager.RegisterNamedMessageHandler("daniel.persistentmoons.remains", (HandleNamedMessageDelegate)obj); nm.CustomMessagingManager.UnregisterNamedMessageHandler("daniel.persistentmoons.remainspaid"); CustomMessagingManager customMessagingManager2 = nm.CustomMessagingManager; object obj2 = <>O.<1>__OnPaid; if (obj2 == null) { HandleNamedMessageDelegate val2 = OnPaid; <>O.<1>__OnPaid = val2; obj2 = (object)val2; } customMessagingManager2.RegisterNamedMessageHandler("daniel.persistentmoons.remainspaid", (HandleNamedMessageDelegate)obj2); } private unsafe static void SendRemains(ulong id, RemainsRecord r) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsServer || singleton.CustomMessagingManager == null) { return; } string text = JsonUtility.ToJson((object)r); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(64 + text.Length * 2, (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<ulong>(ref id, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe(text, false); foreach (ulong connectedClientsId in singleton.ConnectedClientsIds) { if (connectedClientsId != 0L) { singleton.CustomMessagingManager.SendNamedMessage("daniel.persistentmoons.remains", connectedClientsId, val, (NetworkDelivery)4); } } } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } private unsafe static void SendPaid(string text) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsServer || singleton.CustomMessagingManager == null) { return; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(64 + text.Length * 2, (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe(text, false); foreach (ulong connectedClientsId in singleton.ConnectedClientsIds) { if (connectedClientsId != 0L) { singleton.CustomMessagingManager.SendNamedMessage("daniel.persistentmoons.remainspaid", connectedClientsId, val, (NetworkDelivery)2); } } } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } private static void OnRemains(ulong sender, FastBufferReader rd) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (NetworkManager.Singleton.IsServer) { return; } ulong item = default(ulong); ((FastBufferReader)(ref rd)).ReadValueSafe<ulong>(ref item, default(ForPrimitives)); string text = default(string); ((FastBufferReader)(ref rd)).ReadValueSafe(ref text, false); RemainsRecord remainsRecord; try { remainsRecord = JsonUtility.FromJson<RemainsRecord>(text); } catch { return; } if (remainsRecord != null) { _pending.Add((item, remainsRecord, Time.realtimeSinceStartup + 20f)); if (!_pumping && (Object)(object)StartOfRound.Instance != (Object)null) { ((MonoBehaviour)StartOfRound.Instance).StartCoroutine(Pump()); } } } private static IEnumerator Pump() { _pumping = true; while (_pending.Count > 0) { NetworkManager singleton = NetworkManager.Singleton; NetworkSpawnManager val = ((singleton != null) ? singleton.SpawnManager : null); for (int num = _pending.Count - 1; num >= 0; num--) { var (key, rec, num2) = _pending[num]; if (val != null && val.SpawnedObjects.TryGetValue(key, out var value)) { RemainsProp component = ((Component)value).GetComponent<RemainsProp>(); if ((Object)(object)component != (Object)null) { component.Build(rec); } _pending.RemoveAt(num); } else if (Time.realtimeSinceStartup > num2) { _pending.RemoveAt(num); } } yield return (object)new WaitForSecondsRealtime(0.5f); } _pumping = false; } private static void OnPaid(ulong sender, FastBufferReader rd) { if (!NetworkManager.Singleton.IsServer) { string text = default(string); ((FastBufferReader)(ref rd)).ReadValueSafe(ref text, false); if ((Object)(object)StartOfRound.Instance != (Object)null) { ((MonoBehaviour)StartOfRound.Instance).StartCoroutine(ShowPaid(text)); } } } private static uint StableHash(string s) { using MD5 mD = MD5.Create(); return BitConverter.ToUInt32(mD.ComputeHash(Encoding.UTF8.GetBytes(s)), 0); } } [HarmonyPatch] internal static class SaveHooks { private static bool IsHost { get { if ((Object)(object)NetworkManager.Singleton != (Object)null) { return NetworkManager.Singleton.IsServer; } return false; } } [HarmonyPatch(typeof(StartOfRound), "Start")] [HarmonyPostfix] private static void StartPost() { Net.EnsureRegistered(); } [HarmonyPatch(typeof(StartOfRound), "SetTimeAndPlanetToSavedSettings")] [HarmonyPostfix] private static void LoadPost() { Net.EnsureRegistered(); if (Plugin.Active && IsHost) { GameNetworkManager instance = GameNetworkManager.Instance; if (StartOfRound.Instance.isChallengeFile) { State.Clear("challenge moon"); } else { State.Load(instance.currentSaveFileName, ES3.Load<int>("QuotasPassed", instance.currentSaveFileName, 0)); } } } [HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")] [HarmonyPostfix] private static void SavePost(GameNetworkManager __instance) { if (Plugin.Active && __instance.isHostingGame && !((Object)(object)StartOfRound.Instance == (Object)null) && !StartOfRound.Instance.isChallengeFile) { State.Save(__instance.currentSaveFileName); Summary.Broadcast(); } } [HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")] [HarmonyPostfix] private static void NewQuotaPost() { if (IsHost) { State.Clear("new quota"); Summary.Broadcast(); } } [HarmonyPatch(typeof(StartOfRound), "ResetShip")] [HarmonyPostfix] private static void ResetShipPost() { if (IsHost) { State.Clear("fired"); Summary.Broadcast(); } } [HarmonyPatch(typeof(GameNetworkManager), "ResetSavedGameValues")] [HarmonyPostfix] private static void ResetSavePost(GameNetworkManager __instance) { if (__instance.isHostingGame) { State.Clear("save reset"); State.Save(__instance.currentSaveFileName); } } } [Serializable] public class MoonRecord { public int levelId; public string levelName; public string flowName; public int dunSeed; public float length; public int mapSeed; public int tiles; public int firstDay; public int visits; public List<ItemRecord> items = new List<ItemRecord>(); public string doors; public string bigDoors; public List<Spot> spentMines = new List<Spot>(); public bool apparatusPulled; public List<RemainsRecord> remains = new List<RemainsRecord>(); } [Serializable] public class SaveData { public int version = 1; public int quota; public List<MoonRecord> moons = new List<MoonRecord>(); public List<int> lost = new List<int>(); } internal static class State { internal const string SaveKey = "PersistentMoons_v1"; internal static SaveData Data = new SaveData(); internal static int CurrentQuota { get { if (!((Object)(object)TimeOfDay.Instance != (Object)null)) { return 0; } return TimeOfDay.Instance.timesFulfilledQuota; } } internal static MoonRecord Find(int levelId) { return Data.moons.Find((MoonRecord m) => m.levelId == levelId); } internal static void Clear(string why) { if (Data.moons.Count > 0) { Plugin.Log.LogInfo((object)$"Forgetting {Data.moons.Count} remembered moon(s): {why}."); } Data = new SaveData { quota = CurrentQuota }; } internal static void Load(string file, int quotasPassed) { Data = new SaveData { quota = quotasPassed }; try { if (!ES3.KeyExists("PersistentMoons_v1", file)) { return; } SaveData saveData = JsonUtility.FromJson<SaveData>(ES3.Load<string>("PersistentMoons_v1", file)); if (saveData != null && saveData.moons != null) { if (saveData.version != 1) { Plugin.Log.LogWarning((object)$"Save version {saveData.version} not understood; starting fresh."); return; } if (saveData.quota != quotasPassed) { Plugin.Log.LogInfo((object)$"Saved moons belong to quota {saveData.quota}, now {quotasPassed}: forgotten."); return; } Data = saveData; Plugin.Log.LogInfo((object)$"Loaded {saveData.moons.Count} remembered moon(s) from {file}."); } } catch (Exception ex) { Plugin.Log.LogError((object)("Could not read the saved moons: " + ex.Message)); } } internal static void Save(string file) { try { Data.quota = CurrentQuota; ES3.Save<string>("PersistentMoons_v1", JsonUtility.ToJson((object)Data), file); Plugin.Debug($"Saved {Data.moons.Count} remembered moon(s) to {file}."); } catch (Exception ex) { Plugin.Log.LogError((object)("Could not save the remembered moons: " + ex.Message)); } } } [HarmonyPatch] internal static class Summary { [Serializable] public class Moon { public int levelId; public int day; public int items; public int value; public bool lost; public List<string> remains = new List<string>(); } [Serializable] public class Data { public List<Moon> moons = new List<Moon>(); } [CompilerGenerated] private static class <>O { public static HandleNamedMessageDelegate <0>__OnSummary; public static HandleNamedMessageDelegate <1>__OnHello; } private const string MsgSummary = "daniel.persistentmoons.summary"; private const string MsgHello = "daniel.persistentmoons.hello"; private static Data _client = new Data(); private static readonly HashSet<int> _lostShown = new HashSet<int>(); private static readonly HashSet<ulong> _hello = new HashSet<ulong>(); private static bool IsHost { get { if ((Object)(object)NetworkManager.Singleton != (Object)null) { return NetworkManager.Singleton.IsServer; } return false; } } private static Data Current { get { if (!IsHost) { return _client; } return Build(); } } private static Data Build() { Data data = new Data(); foreach (MoonRecord moon in State.Data.moons) { if ((Object)(object)StartOfRound.Instance != (Object)null) { _ = StartOfRound.Instance.allItemsList.itemsList; } data.moons.Add(new Moon { levelId = moon.levelId, day = moon.visits + 1, items = (moon.items?.Count ?? 0), value = (moon.items?.Sum((ItemRecord i) => i.value) ?? 0), remains = (moon.remains ?? new List<RemainsRecord>()).Select((RemainsRecord r) => (r.refund <= 0) ? r.player : $"{r.player} (+${r.refund})").ToList() }); } foreach (int id in State.Data.lost ?? new List<int>()) { if (data.moons.All((Moon