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 PUP FPS v1.0.38
PUP_FPS.dll
Decompiled 2 days 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.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.AI; using UnityEngine.Rendering; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [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; } } } public sealed class ServerZoneStreamBlock : MonoBehaviour { private const string Id = "com.pup.instancecombiner.serverstream"; private const int Vanilla = 10240; private static ConfigEntry<bool> enabledSetting; private static bool active; private static int limit = 10240; private static int extraObjects; private static long started; private static long extraStarted; private static double cooldown; private Harmony harmony; private bool initialized; private ManualLogSource Logger; private static double Seconds => (double)Stopwatch.GetTimestamp() / (double)Stopwatch.Frequency; public void Setup(ConfigFile config, ManualLogSource logger) { Logger = logger; enabledSetting = config.Bind<bool>("ServerStreaming", "Enabled", true, "Dedicated server only: helps load zones by sending more object data per packet (10-20 KiB), without increasing send frequency. Extra work is bounded and packet size returns to vanilla under load. False disables packet growth. Inactive in solo and listen-host games. Does not change your Internet connection speed. Restart after editing."); } private void Initialize() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_0057: 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_0081: 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_00a1: Expected O, but got Unknown //IL_00a1: Expected O, but got Unknown //IL_00a1: Expected O, but got Unknown //IL_00a1: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown //IL_0104: Expected O, but got Unknown //IL_0104: Expected O, but got Unknown initialized = true; if (!ZNet.instance.IsDedicated()) { ((Behaviour)this).enabled = false; return; } harmony = new Harmony("com.pup.instancecombiner.serverstream"); try { harmony.Patch((MethodBase)AccessTools.Method(typeof(ZDOMan), "SendZDOs", (Type[])null, (Type[])null), new HarmonyMethod(typeof(ServerZoneStreamBlock), "Before", (Type[])null), new HarmonyMethod(typeof(ServerZoneStreamBlock), "After", (Type[])null), new HarmonyMethod(typeof(ServerZoneStreamBlock), "Rewrite", (Type[])null), new HarmonyMethod(typeof(ServerZoneStreamBlock), "Finish", (Type[])null), (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(ZDOMan), "AddForceSendZdos", (Type[])null, (Type[])null), new HarmonyMethod(typeof(ServerZoneStreamBlock), "BeforeForcedBatch", (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(ServerZoneStreamBlock), "RewriteForcedBatch", (Type[])null), new HarmonyMethod(typeof(ServerZoneStreamBlock), "FinishForcedBatch", (Type[])null), (HarmonyMethod)null); } catch (Exception) { harmony.UnpatchSelf(); ((Behaviour)this).enabled = false; } } private static void Before(bool __1) { started = Stopwatch.GetTimestamp(); extraStarted = 0L; extraObjects = 0; active = enabledSetting.Value && !__1 && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer(); if (!active || Seconds < cooldown || Time.unscaledDeltaTime > 0.04f) { limit = 10240; } } private static int PayloadLimit() { if (!active) { return 10240; } return limit; } private static int CheckedSize(ZPackage package) { int num = package.Size(); if (!active || limit <= 10240 || num <= 10240) { return num; } long timestamp = Stopwatch.GetTimestamp(); if (extraStarted == 0L) { extraStarted = timestamp; } double num2 = (double)(timestamp - extraStarted) * 1000.0 / (double)Stopwatch.Frequency; double num3 = (double)(timestamp - started) * 1000.0 / (double)Stopwatch.Frequency; if (extraObjects >= 32 || num2 >= 1.0 || num3 >= 25.0) { return limit + 1; } extraObjects++; return num; } private static void After() { if (active) { double num = (double)(Stopwatch.GetTimestamp() - started) * 1000.0 / (double)Stopwatch.Frequency; if (num >= 25.0 || Time.unscaledDeltaTime > 0.04f) { limit = 10240; cooldown = Seconds + 2.0; } else if (Seconds >= cooldown && num < 15.0) { limit = Math.Min(20480, limit + 1024); } } } private static Exception Finish(Exception __exception) { active = false; return __exception; } private static void BeforeForcedBatch(List<ZDO> __1, out int __state) { __state = __1?.Count ?? (-1); } private static void AppendForcedZdo(List<ZDO> list, int index, ZDO zdo) { list.Add(zdo); } private static void RestoreForcedOrder(List<ZDO> list, int originalCount) { if (list != null && originalCount >= 0 && list.Count > originalCount) { list.Reverse(0, originalCount); list.Reverse(); } } private static Exception FinishForcedBatch(List<ZDO> __1, int __state, Exception __exception) { RestoreForcedOrder(__1, __state); return __exception; } private static IEnumerable<CodeInstruction> RewriteForcedBatch(IEnumerable<CodeInstruction> source) { List<CodeInstruction> list = source.ToList(); MethodInfo insert = AccessTools.Method(typeof(List<ZDO>), "Insert", (Type[])null, (Type[])null); var array = (from x in list.Select((CodeInstruction c, int i) => new { c, i }) where CodeInstructionExtensions.Calls(x.c, insert) select x).ToArray(); if (array.Length != 1 || array[0].i < 2 || list[array[0].i - 2].opcode != OpCodes.Ldc_I4_0) { throw new InvalidOperationException("Unexpected AddForceSendZdos IL; original behavior retained"); } array[0].c.opcode = OpCodes.Call; array[0].c.operand = AccessTools.Method(typeof(ServerZoneStreamBlock), "AppendForcedZdo", (Type[])null, (Type[])null); return list; } private static IEnumerable<CodeInstruction> Rewrite(IEnumerable<CodeInstruction> source) { List<CodeInstruction> list = source.ToList(); var array = (from x in list.Select((CodeInstruction c, int i) => new { c, i }) where x.c.opcode == OpCodes.Ldc_I4 && object.Equals(x.c.operand, 10240) select x).ToArray(); var array2 = (from x in list.Select((CodeInstruction c, int i) => new { c, i }) where CodeInstructionExtensions.Calls(x.c, AccessTools.Method(typeof(ZPackage), "Size", (Type[])null, (Type[])null)) select x).ToArray(); if (array.Length != 2 || array2.Length != 1 || list[array[1].i + 1].opcode != OpCodes.Ldloc_0 || list[array[1].i + 2].opcode != OpCodes.Sub || list[array2[0].i + 1].opcode != OpCodes.Ldloc_1 || (list[array2[0].i + 2].opcode != OpCodes.Ble_S && list[array2[0].i + 2].opcode != OpCodes.Ble)) { throw new InvalidOperationException("Unexpected SendZDOs IL; original behavior retained"); } array[1].c.opcode = OpCodes.Call; array[1].c.operand = AccessTools.Method(typeof(ServerZoneStreamBlock), "PayloadLimit", (Type[])null, (Type[])null); array2[0].c.opcode = OpCodes.Call; array2[0].c.operand = AccessTools.Method(typeof(ServerZoneStreamBlock), "CheckedSize", (Type[])null, (Type[])null); return list; } private void Update() { if (!initialized && (Object)(object)ZNet.instance != (Object)null) { Initialize(); } } private void OnDestroy() { Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } } } namespace ValheimInstanceCombiner { [BepInPlugin("com.pup.instancecombiner.safe", "PUP FPS", "1.0.38")] public class InstanceCombinerMod : BaseUnityPlugin { private sealed class ComfortRows { internal ZNetScene scene; internal int count; internal readonly List<BakedRecord> rows = new List<BakedRecord>(); } [HarmonyPatch(typeof(SE_Rested), "GetNearbyComfortPieces")] private static class BakedComfortPatch { private static void Postfix(Vector3 __0, List<Piece> __result) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Instance != (Object)null && __result != null) { Instance.AddBakedComfort(__0, __result); } } } private enum BakeMaterial { Wood, Stone, Marble, Grausten, Iron, Other, CoreWood, DarkWood, DarkWoodRoofs, AshWood, Thatch, Copper, Flametal, Crystal, Ice, Timberwood, Finewood } public sealed class CartCollisionGuard : MonoBehaviour { private ZNetView view; private Rigidbody[] bodies; private bool[] kinematic; private Vector3[] velocities; private Vector3[] angularVelocities; private Vector3 position; private float nextCheck; internal int revision = -1; private bool held; internal void Initialize() { view = ((Component)this).GetComponent<ZNetView>(); bodies = ((Component)this).GetComponentsInChildren<Rigidbody>(true); kinematic = new bool[bodies.Length]; velocities = (Vector3[])(object)new Vector3[bodies.Length]; angularVelocities = (Vector3[])(object)new Vector3[bodies.Length]; cartCollisionGuards.Add(this); Step(); } private void FixedUpdate() { Step(); } internal void Step() { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: 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_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: 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_00fd: 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_0101: 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) //IL_0107: 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_016b: 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_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) InstanceCombinerMod instance = Instance; if ((Object)(object)instance == (Object)null || !((Behaviour)instance).enabled || (Object)(object)ZNet.instance == (Object)null || (Object)(object)view == (Object)null || !view.IsValid() || !view.IsOwner()) { Release(); revision = -1; return; } Vector3 val = ((Component)this).transform.position; Vector3 val2; if (revision == instance.collisionCoverageRevision && Time.unscaledTime < nextCheck) { if (held) { return; } val2 = val - position; if (((Vector3)(ref val2)).sqrMagnitude < 0.25f) { return; } } bool flag = instance.PrepareExactCollision(val, 6f); if (flag && !held && bodies.Length != 0 && (Object)(object)bodies[0] != (Object)null) { Vector3 val3 = val + Vector3.ClampMagnitude(bodies[0].linearVelocity * 0.35f, 8f); val2 = val3 - val; if (((Vector3)(ref val2)).sqrMagnitude > 1f) { flag = instance.PrepareExactCollision(val3, 6f); } } if (flag) { Release(); } else if (!held) { for (int i = 0; i < bodies.Length; i++) { Rigidbody val4 = bodies[i]; if (!((Object)(object)val4 == (Object)null)) { kinematic[i] = val4.isKinematic; velocities[i] = val4.linearVelocity; angularVelocities[i] = val4.angularVelocity; val4.isKinematic = true; } } held = true; } position = val; revision = instance.collisionCoverageRevision; nextCheck = Time.unscaledTime + (held ? 0.05f : 0.2f); } internal void Release() { //IL_003f: 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) if (!held) { return; } for (int i = 0; i < bodies.Length; i++) { Rigidbody val = bodies[i]; if (!((Object)(object)val == (Object)null)) { val.isKinematic = kinematic[i]; if (!kinematic[i]) { val.linearVelocity = velocities[i]; val.angularVelocity = angularVelocities[i]; } } } held = false; } private void OnDisable() { Release(); revision = -1; } private void OnDestroy() { Release(); cartCollisionGuards.Remove(this); } } [HarmonyPatch(typeof(Vagon), "Awake")] private static class CartCollisionAwakePatch { private static void Postfix(Vagon __instance) { if (!((Object)(object)Instance == (Object)null) && !((Object)(object)__instance == (Object)null) && !((Object)(object)((Component)__instance).GetComponent<CartCollisionGuard>() != (Object)null)) { Instance.AttachZoneBodyGuard(((Component)__instance).gameObject); } } } private sealed class MobCollisionState { internal Vector3 position; internal float nextCheck; internal int revision = -1; internal bool held; internal bool wasKinematic; internal Rigidbody body; } [HarmonyPatch(typeof(Character), "CustomFixedUpdate")] private static class MobCollisionFixedPatch { private static bool Prefix(Character __instance) { if (!((Object)(object)Instance == (Object)null)) { return Instance.PrepareMobCollision(__instance); } return true; } } [HarmonyPatch(typeof(BaseAI), "UpdateAI")] private static class MobCollisionAiPatch { private static bool Prefix(BaseAI __instance, ref bool __result) { if ((Object)(object)Instance == (Object)null || Instance.PrepareMobCollision(Instance.GetCollisionCharacter(__instance))) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(SpawnArea), "FindSpawnPoint")] private static class SpawnAreaCollisionPatch { private static bool Prefix(SpawnArea __instance, ref bool __result) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Instance == (Object)null || Instance.PrepareExactCollision(((Component)__instance).transform.position, __instance.m_spawnRadius + 2f)) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(CreatureSpawner), "Spawn")] private static class CreatureSpawnerCollisionPatch { private static bool Prefix(CreatureSpawner __instance) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Instance == (Object)null || Instance.PrepareExactCollision(((Component)__instance).transform.position, 4f)) { return true; } return false; } } [HarmonyPatch(typeof(SpawnSystem), "IsSpawnPointGood")] private static class SpawnSystemCollisionPatch { private static bool Prefix(ref Vector3 __1, ref bool __result) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Instance == (Object)null || Instance.PrepareExactCollision(__1, 4f)) { return true; } __result = false; return false; } } private sealed class CrystalReflectionBinding { public ReflectionProbe first; public ReflectionProbe second; public Bounds a; public Bounds b; public float weight; public MaterialPropertyBlock block; } private struct CrystalReflectionKey : IEquatable<CrystalReflectionKey> { public int first; public int second; public float weight; public Bounds a; public Bounds b; public bool Equals(CrystalReflectionKey other) { //IL_0036: 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) if (first == other.first && second == other.second && weight.Equals(other.weight) && ((Bounds)(ref a)).Equals(other.a)) { return ((Bounds)(ref b)).Equals(other.b); } return false; } public override bool Equals(object other) { if (other is CrystalReflectionKey) { return Equals((CrystalReflectionKey)other); } return false; } public override int GetHashCode() { return (((((((first * 397) ^ second) * 397) ^ weight.GetHashCode()) * 397) ^ ((object)Unsafe.As<Bounds, Bounds>(ref a)/*cast due to .constrained prefix*/).GetHashCode()) * 397) ^ ((object)Unsafe.As<Bounds, Bounds>(ref b)/*cast due to .constrained prefix*/).GetHashCode(); } } private sealed class CrystalBatchState { public GameObject root; public GpuDrawGroup source; public Matrix4x4[] matrices; public Bounds[] bounds; public Bounds combinedBounds; public readonly List<Bounds> visibleBounds = new List<Bounds>(); public string uniformReflectionKey; public int[] reflectionRegion; public string[] paneReflectionKeys; public readonly List<CrystalReflectionRegion> reflectionRegions = new List<CrystalReflectionRegion>(); public Material material; public Material singlePassMaterial; public readonly CrystalBatchPlanner planner = new CrystalBatchPlanner(); public readonly Dictionary<Matrix4x4, string> keys = new Dictionary<Matrix4x4, string>(); public readonly Dictionary<string, MaterialPropertyBlock> blocks = new Dictionary<string, MaterialPropertyBlock>(); public int reflectionMembershipRevision; public int probeRevision = -1; public int payloadRevision = -1; public readonly List<CrystalReflectionBinding> bindings = new List<CrystalReflectionBinding>(); public readonly Dictionary<CrystalReflectionKey, int> reflectionGroups = new Dictionary<CrystalReflectionKey, int>(); public readonly List<string> reflectionNames = new List<string>(); } private sealed class CrystalReflectionRegion { public Bounds bounds; public bool uniform; public ReflectionProbe probe; public string key; } private struct CrystalProbeSnapshot : IEquatable<CrystalProbeSnapshot> { public ReflectionProbe probe; public Bounds bounds; public Vector3 position; public Vector4 hdr; public float blend; public int importance; public bool box; public bool active; public Texture texture; public bool SameLayout(CrystalProbeSnapshot b) { //IL_0007: 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) if (((Bounds)(ref bounds)).Equals(b.bounds) && ((Vector3)(ref position)).Equals(b.position) && blend.Equals(b.blend) && importance == b.importance && box == b.box) { return active == b.active; } return false; } public bool Equals(CrystalProbeSnapshot b) { //IL_0007: 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_002d: Unknown result type (might be due to invalid IL or missing references) if (((Bounds)(ref bounds)).Equals(b.bounds) && ((Vector3)(ref position)).Equals(b.position) && ((Vector4)(ref hdr)).Equals(b.hdr) && blend.Equals(b.blend) && importance == b.importance && box == b.box && active == b.active) { return (Object)(object)texture == (Object)(object)b.texture; } return false; } } [HarmonyPatch(typeof(ZNetView), "Awake")] private static class CrystalTransparentSpawnPatch { private static void Postfix(ZNetView __instance) { if ((Object)(object)Instance != (Object)null && Instance.crystalSceneSeeded) { Instance.RegisterCrystalTransparentRoot(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(EffectList), "Create")] private static class CrystalTransparentEffectPatch { private static void Postfix(GameObject[] __result) { if (!((Object)(object)Instance == (Object)null) && Instance.crystalSceneSeeded && __result != null) { foreach (GameObject root in __result) { Instance.RegisterCrystalTransparentRoot(root); } } } } private struct CrystalSimpleLight { public Vector4 position; public Vector4 color; public Vector4 direction; public float rangeSquared; } private struct CrystalUnifiedBindingKey : IEquatable<CrystalUnifiedBindingKey> { public int kind; public CrystalReflectionKey reflection; public bool Equals(CrystalUnifiedBindingKey other) { if (kind == other.kind) { return reflection.Equals(other.reflection); } return false; } public override bool Equals(object value) { if (value is CrystalUnifiedBindingKey) { return Equals((CrystalUnifiedBindingKey)value); } return false; } public override int GetHashCode() { return (kind * 397) ^ reflection.GetHashCode(); } } private sealed class CrystalVisualMarker : MonoBehaviour { } private sealed class RainDrawData { internal MeshFilter filter; internal Transform transform; internal readonly List<Material> materials = new List<Material>(); } private sealed class AiCharacterReference { internal Character character; } [HarmonyPatch(typeof(ZSyncTransform), "ClientSync")] private static class HeldClientOwnershipPatch { private static void Prefix(Rigidbody ___m_body, bool ___m_isKinematicBody) { if (!___m_isKinematicBody && !((Object)(object)___m_body == (Object)null) && ___m_body.isKinematic) { ZoneBodyGuard componentInParent = ((Component)___m_body).GetComponentInParent<ZoneBodyGuard>(true); if ((Object)(object)componentInParent != (Object)null) { componentInParent.ReleaseLostOwnership(); } } } } [HarmonyPatch(typeof(ZSyncTransform), "OwnerSync")] private static class HeldOwnerVelocityPatch { internal static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { MethodInfo linear = AccessTools.PropertySetter(typeof(Rigidbody), "linearVelocity"); MethodInfo angular = AccessTools.PropertySetter(typeof(Rigidbody), "angularVelocity"); foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.Calls(instruction, linear) || CodeInstructionExtensions.Calls(instruction, angular)) { bool flag = CodeInstructionExtensions.Calls(instruction, angular); instruction.opcode = OpCodes.Call; instruction.operand = AccessTools.Method(typeof(InstanceCombinerMod), flag ? "SetHeldAngularVelocity" : "SetHeldLinearVelocity", (Type[])null, (Type[])null); } yield return instruction; } } } [HarmonyPatch(typeof(Ship), "CustomFixedUpdate")] private static class HeldShipVelocityPatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { return HeldOwnerVelocityPatch.Transpiler(instructions); } } [HarmonyPatch(typeof(Floating), "CustomFixedUpdate")] private static class HeldFloatingPhysicsPatch { private static bool Prefix(Floating __instance) { ZoneBodyGuard component = ((Component)__instance).GetComponent<ZoneBodyGuard>(); if (!((Object)(object)component == (Object)null)) { return component.Step(); } return true; } } private sealed class GpuDrawGroup { public List<MeshRenderer> crystalRenderers; public List<Mesh> crystalStaticMeshes; public Mesh mesh; public int subMesh; public Material material; public readonly HashSet<string> stableIds = new HashSet<string>(StringComparer.Ordinal); public bool usesTessellation; public bool tessellationEnabled = true; public Bounds worldBounds; public bool hasWorldBounds; public bool cameraVisible = true; public readonly List<Matrix4x4[]> chunks = new List<Matrix4x4[]>(); } private sealed class RawGpuGroup { public string meshName; public int vertexCount; public int subMeshCount; public Vector3 boundsSize; public int subMesh; public string materialName; public readonly List<Matrix4x4[]> chunks = new List<Matrix4x4[]>(); } private sealed class RawGpuCache { public bool fullVisual; public readonly List<RawGpuGroup> groups = new List<RawGpuGroup>(); } private sealed class RawMeshData { public Vector3[] vertices; public Vector3[] normals; public Vector4[] tangents; public Vector2[] uv; public int[][] triangles; } private sealed class RawSubCluster { public RawMeshData mesh; public string[] materialNames; public readonly List<CachedColliderData> colliders = new List<CachedColliderData>(); } private sealed class PreparedSubCluster { public SubClusterCacheEntry entry; public RawSubCluster raw; public long sourceBytes; } private sealed class BakedRecord { public string customId; public long userId; public uint id; public int prefabHash; public long fractureState; public byte wearState; public Vector3 position; public Quaternion rotation; public Vector3 scale; } private sealed class CachedColliderData { public int subX = -1; public int subZ = -1; public int colliderIndex = -1; public byte type; public int layer; public Vector3 position; public Quaternion rotation; public Vector3 scale; public bool trigger; public Vector3 center; public Vector3 size; public float radius; public float height; public int direction; public bool convex; public string meshName; public Mesh mesh; public RawMeshData rawMesh; } private sealed class PendingCollider { public Vector2Int cell; public GameObject root; public CachedColliderData data; } private sealed class SubClusterCacheEntry { public int x; public int z; public string name; public string fileName; } private sealed class MaterialCombineGroup { public Material source; public readonly List<CombineInstance> parts = new List<CombineInstance>(); } [HarmonyPatch(typeof(Player), "OnSpawned")] private static class PlayerSpawnPatch { private static void Postfix() { InstanceCombinerMod instanceCombinerMod = Object.FindFirstObjectByType<InstanceCombinerMod>(); if ((Object)(object)instanceCombinerMod != (Object)null) { instanceCombinerMod.LoadState(); instanceCombinerMod.BeginSinglePlayerFastInitialLoad(); } } } [HarmonyPatch(typeof(ZNet), "LoadWorld")] private static class SinglePlayerWorldLoadIndexPatch { private static void Postfix() { if ((Object)(object)Instance != (Object)null && (Object)(object)ZNet.instance != (Object)null && ZNet.IsSinglePlayer) { Instance.PrepareSinglePlayerStableIndexDuringWorldLoad(); Instance.LoadState(); Instance.BeginSinglePlayerFastWorldLoadPrewarm(); } } } [HarmonyPatch(typeof(Player), "TeleportTo")] private static class PortalDestinationPrewarmPatch { private static void Postfix(Vector3 pos, bool distantTeleport, bool __result) { //IL_0017: 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) if (__result && distantTeleport && (Object)(object)Instance != (Object)null) { Instance.BeginSinglePlayerFastPortal(pos); Instance.PrewarmRemotePortalDestination(pos); } } } [HarmonyPatch(typeof(Player), "UpdateTeleport")] private static class SinglePlayerPortalArrivalPatch { private static void Prefix(Player __instance, out bool __state) { __state = (Object)(object)__instance != (Object)null && ((Character)__instance).IsTeleporting(); } private static void Postfix(Player __instance, bool __state) { if (__state && (Object)(object)__instance != (Object)null && !((Character)__instance).IsTeleporting() && (Object)(object)Instance != (Object)null) { Instance.FinishSinglePlayerPortalCurtain(); } } } [HarmonyPatch(typeof(Hud), "UpdateBlackScreen")] private static class SinglePlayerPortalCurtainPatch { private static void Postfix(Hud __instance) { if (!((Object)(object)__instance == (Object)null) && !((Object)(object)Instance == (Object)null) && (Instance.ShouldHoldSinglePlayerPortalCurtain() | Instance.ShouldHoldRemotePortalCurtain())) { object? obj = AccessTools.Field(typeof(Hud), "m_loadingScreen")?.GetValue(__instance); Component val = (Component)((obj is Component) ? obj : null); if (!((Object)(object)val == (Object)null)) { val.gameObject.SetActive(true); AccessTools.Property(((object)val).GetType(), "alpha")?.SetValue(val, 1f, null); } } } } [HarmonyPatch(typeof(ZNet), "Shutdown")] private static class MultiplayerClientShutdownPatch { private static void Prefix() { if ((Object)(object)Instance != (Object)null) { Instance.BeginMultiplayerClientShutdown(); } } } [HarmonyPatch(typeof(ZNetScene), "CreateObject")] private static class HideBakedObjectAtCreationPatch { private static bool Prefix(ZDO zdo, ref GameObject __result) { if ((Object)(object)Instance == (Object)null || !Instance.TrySuppressRemoteOriginalCreation(zdo)) { return true; } __result = null; return false; } private static void Postfix(ZDO zdo, GameObject __result) { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) if (((Object)(object)Instance != (Object)null && Instance.TryUnloadRemoteOriginalAtCreation(zdo, __result)) || (Object)(object)Instance == (Object)null || zdo == null || (Object)(object)__result == (Object)null || !zdo.GetBool(BakedKey, false)) { return; } Vector2Int item = default(Vector2Int); ((Vector2Int)(ref item))..ctor(zdo.GetInt(CellXKey, int.MinValue), zdo.GetInt(CellZKey, int.MinValue)); if (Instance.gpuCacheReadyCells.Contains(item) && !Instance.suppressedVisualCells.Contains(item)) { ZNetView component = __result.GetComponent<ZNetView>(); if ((Object)(object)component != (Object)null) { Instance.HideOriginalRenderers(component); } } } } [HarmonyPatch(typeof(ZNetScene), "IsAreaReady")] private static class RemoteAreaReadyPatch { private static void Postfix(Vector3 point, ref bool __result) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (!__result && (Object)(object)Instance != (Object)null && Instance.IsRemoteAreaReadyIgnoringSuppressed(point)) { __result = true; } } } [HarmonyPatch(typeof(ZNetScene), "AddInstance")] private static class HideBakedObjectAtAddInstancePatch { private static void Postfix(ZDO zdo, ZNetView nview) { //IL_006b: 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) Instance?.ObserveRestoreSupportView(zdo, nview); if (!((Object)(object)Instance == (Object)null) && zdo != null && !((Object)(object)nview == (Object)null) && zdo.GetBool(BakedKey, false)) { Vector2Int item = default(Vector2Int); ((Vector2Int)(ref item))..ctor(zdo.GetInt(CellXKey, int.MinValue), zdo.GetInt(CellZKey, int.MinValue)); if (Instance.gpuCacheReadyCells.Contains(item) && !Instance.suppressedVisualCells.Contains(item)) { Instance.HideOriginalRenderers(nview); } } } } [HarmonyPatch(typeof(WearNTear), "UpdateSupport")] private static class WearNTearSupportPatch { private static bool Prefix(WearNTear __instance, out float __state) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) __state = (((Object)(object)Instance != (Object)null && WearSupportField != null) ? ReadWearSupport(__instance) : (-1f)); if (!((Object)(object)Instance == (Object)null)) { if (!Instance.ShouldBlockSupportUpdate() && !Instance.IsRestoreSupportBlocked(__instance) && !Instance.IsZoneTransitionNear(((Component)__instance).transform.position, 2f)) { return !Instance.DependentCollisionPending(__instance); } return false; } return true; } private static void Postfix(WearNTear __instance, float __state) { if ((Object)(object)Instance != (Object)null) { Instance.RepairDependentSupport(__instance); Instance.PreserveDependentSupport(__instance, __state); } } } [HarmonyPatch(typeof(WearNTear), "UpdateWear")] private static class WearNTearWearPatch { private static bool Prefix(WearNTear __instance) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)Instance == (Object)null)) { if (!Instance.ShouldBlockSupportUpdate() && !Instance.IsRestoreSupportBlocked(__instance) && !Instance.IsZoneTransitionNear(((Component)__instance).transform.position, 2f) && !Instance.DependentCollisionPending(__instance)) { return !Instance.WearDataPending(__instance); } return false; } return true; } } [HarmonyPatch(typeof(ZNet), "SaveWorld")] private static class ZNetSaveWorldPatch { private static void Prefix() { if ((Object)(object)Instance != (Object)null) { Instance.BeforeVanillaWorldSave(); } } } private sealed class DedicatedBakeTarget { public long userId; public uint id; public int prefabHash; public Vector3 position; } private sealed class RemoteVisualHandoff { public ZDOID id; public MeshRenderer[] allRenderers; public List<MeshRenderer> enabledRenderers; public LODGroup[] allLodGroups; public List<LODGroup> enabledLodGroups; } private sealed class RemoteProvisionalVisualPublication { public GameObject root; public List<GpuDrawGroup> groups; public List<RemoteVisualHandoff> originals; public int queuedFrame; } private sealed class IncomingRecordTransfer { public Vector2Int cell; public string cacheId; public int total; public readonly List<BakedRecord> records = new List<BakedRecord>(); } private sealed class RemoteCellManifest { public Vector2Int cell; public string cacheId; public int recordCount; public ulong fingerprint; } private sealed class IncomingFile { public string name; public long length; public string sha256; public long received; } private sealed class IncomingCellTransfer { public Vector2Int cell; public string cacheId; public float lastActivity; public readonly Dictionary<string, IncomingFile> files = new Dictionary<string, IncomingFile>(StringComparer.OrdinalIgnoreCase); } private sealed class RemoteFinalVisualHandoff { public GameObject root; public List<GpuDrawGroup> groups; public GameObject previousRoot; public List<GpuDrawGroup> previousGroups; public int queuedFrame; public float queuedTime; } [HarmonyPatch(typeof(Pathfinding), "FindGround")] private static class NavigationDuplicatePatch { private static void Prefix(List<Vector3> hits, out int __state) { __state = hits.Count; } private static void Postfix(Vector3 p, List<Vector3> hits, int __state) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) InstanceCombinerMod instance = Instance; if ((Object)(object)instance == (Object)null || hits.Count - __state < 2) { return; } Vector2Int cell = GetCell(p); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { Vector2Int key = cell + new Vector2Int(i, j); if (instance.records.ContainsKey(key) || instance.restoreSupportCells.ContainsKey(key)) { instance.RemoveDuplicateNavigationPoints(hits, __state); return; } } } } } [HarmonyPatch(typeof(Pathfinding), "ConnectAlongEdge")] private static class NavigationReplacementScopePatch { private static void Prefix(List<KeyValuePair<Vector3, NavMeshLinkInstance>> links, Vector3 p0, Vector3 p1, out bool __state) { //IL_0011: 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) InstanceCombinerMod instance = Instance; __state = (Object)(object)instance != (Object)null && (instance.IsPupNavigationPoint(p0) || instance.IsPupNavigationPoint(p1)) && instance.replacingNavLinks.Add(links); } private static Exception Finalizer(List<KeyValuePair<Vector3, NavMeshLinkInstance>> links, bool __state, Exception __exception) { if (__state && (Object)(object)Instance != (Object)null) { Instance.replacingNavLinks.Remove(links); } return __exception; } } [HarmonyPatch(typeof(Pathfinding), "ClearLinks", new Type[] { typeof(List<KeyValuePair<Vector3, NavMeshLinkInstance>>) })] private static class NavigationReplacementClearPatch { private static bool Prefix(List<KeyValuePair<Vector3, NavMeshLinkInstance>> links) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) InstanceCombinerMod instance = Instance; if ((Object)(object)instance == (Object)null || !instance.replacingNavLinks.Contains(links)) { return true; } foreach (KeyValuePair<Vector3, NavMeshLinkInstance> link in links) { NavMesh.RemoveLink(link.Value); } links.Clear(); return false; } } private sealed class PlantSupportShape { public Collider source; public Collider proxy; public Matrix4x4 matrix; public Bounds bounds; public bool noVines; public int prefab; } private sealed class PlantSupportCell { public Vector2Int cellId; public List<BakedRecord> rows; public int count; public string cacheId; public GameObject root; public readonly Dictionary<Vector2Int, List<PlantSupportShape>> tiles = new Dictionary<Vector2Int, List<PlantSupportShape>>(); public readonly HashSet<Collider> proxies = new HashSet<Collider>(); public readonly Dictionary<PlantSupportShape, float> temporaryCollisionShapes = new Dictionary<PlantSupportShape, float>(); public bool incomplete; public float retry; } [HarmonyPatch(typeof(Plant), "SUpdate")] private static class PlantLoadingPatch { private static bool Prefix(Plant __instance) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Instance == (Object)null || __instance.m_attachDistance <= 0f) { return true; } if ((Object)(object)__instance.GetClosestAttachObject() != (Object)null) { return true; } return !Instance.PlantSupportPending(((Component)__instance).transform.position); } } [HarmonyPatch(typeof(Vine), "CheckSupport")] private static class VineLoadingSupportPatch { private static bool Prefix(Vine __instance) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)Instance == (Object)null) && !HasVineSupport(__instance)) { return !Instance.PlantSupportPending(((Component)__instance).transform.position); } return true; } } [HarmonyPatch(typeof(Vine), "UpdateGrow")] private static class VineLoadingGrowthPatch { private static bool Prefix(Vine __instance, ref bool __result) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Instance == (Object)null || HasVineSupport(__instance) || !Instance.PlantSupportPending(((Component)__instance).transform.position)) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(Plant), "GetClosestAttachObject", new Type[] { typeof(Vector3) })] private static class PlantAttachmentPatch { private static void Postfix(Plant __instance, Vector3 __0, ref Collider __result) { //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_0038: 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) if (!((Object)(object)__result != (Object)null) && !((Object)(object)Instance == (Object)null) && !(__instance.m_attachDistance <= 0f)) { List<Collider> source = Instance.EnsurePlantSupport(__0, __instance.m_attachDistance, attachment: true); int num = (int)PlantPieceMask.GetValue(null); HashSet<Collider> overlapping = new HashSet<Collider>(Physics.OverlapSphere(__0, __instance.m_attachDistance, num)); __result = source.Where((Collider c) => (Object)(object)c != (Object)null && overlapping.Contains(c)).OrderBy(delegate(Collider c) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //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) Bounds bounds = c.bounds; Vector3 val = ((Bounds)(ref bounds)).center - __0; return ((Vector3)(ref val)).sqrMagnitude; }).FirstOrDefault(); } } } [HarmonyPatch(typeof(Vine), "IsSupported")] private static class VineSupportPatch { private static void Postfix(Vine __instance, ref bool __result) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_007a: 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_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) if (__result || (Object)(object)Instance == (Object)null) { return; } object? value = VineSupportSensor.GetValue(__instance); BoxCollider val = (BoxCollider)((value is BoxCollider) ? value : null); if ((Object)(object)val == (Object)null) { return; } Vector3 val2 = ((Component)__instance).transform.TransformPoint(val.center); InstanceCombinerMod instance = Instance; Vector3 size = val.size; List<Collider> candidates = instance.EnsurePlantSupport(val2, ((Vector3)(ref size)).magnitude * 0.5f, attachment: false); if (candidates.Count != 0) { Collider[] source = Physics.OverlapBox(val2, val.size * 0.5f, ((Component)val).transform.rotation, (int)VinePieceMask.GetValue(null)); __result = source.Any((Collider c) => candidates.Contains(c)); } } } private sealed class RestoreLookup { internal readonly Dictionary<string, List<ZDO>> stable = new Dictionary<string, List<ZDO>>(StringComparer.Ordinal); internal readonly Dictionary<string, List<ZDO>> positions = new Dictionary<string, List<ZDO>>(StringComparer.Ordinal); internal readonly Dictionary<Vector2Int, Dictionary<ZDOID, ZDO>> parked = new Dictionary<Vector2Int, Dictionary<ZDOID, ZDO>>(); } [HarmonyPatch(typeof(ZDO), "InternalSetPosition")] private static class RestoreSectorAfterPositionPatch { private static void Postfix(ZDO __instance) { if ((Object)(object)Instance != (Object)null && Instance.IsMultiplayerGuest()) { Instance.RepairRestoredZdoSector(__instance); } } } [HarmonyPatch(typeof(ZDOMan), "RPC_ZDOData")] private static class RestoreSectorAfterPacketPatch { private static void Prefix(ZPackage pkg, out List<KeyValuePair<ZDOID, string>> __state) { __state = (((Object)(object)Instance != (Object)null && Instance.IsMultiplayerGuest() && ZDOMan.instance != null) ? Instance.CaptureRestoreSectorCandidates(pkg) : null); } private static void Postfix(List<KeyValuePair<ZDOID, string>> __state) { if ((Object)(object)Instance != (Object)null && Instance.IsMultiplayerGuest()) { Instance.RepairReceivedRestoreSectors(__state); } } } private sealed class StateText { internal Vector2Int cell; internal string customId; internal string prefix; internal string suffix; internal long userId; internal long fracture; internal uint id; internal int prefab; internal byte wear; internal Vector3 position; internal Vector3 scale; internal Quaternion rotation; } private sealed class RestoreSupportCell { internal List<BakedRecord> pending; internal List<BakedRecord> materialized = new List<BakedRecord>(); internal float readyAfter; internal bool rechecking; internal int lastCompleteReadyCount; internal bool visualCover; internal GameObject coverRoot; internal List<GpuDrawGroup> coverGroups; internal HashSet<string> identities; internal readonly HashSet<string> destroyed = new HashSet<string>(StringComparer.Ordinal); } [HarmonyPatch(typeof(ZDOMan), "HandleDestroyedZDO")] private static class RestoredObjectDestroyedPatch { private static void Prefix(ZDOMan __instance, ZDOID __0) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Instance != (Object)null && Instance.restoreSupportCells.Count != 0) { Instance.ConfirmRestoredObjectDestroyed(__instance.GetZDO(__0)); } } } private sealed class RoofQueryShape { internal Collider collider; internal Bounds bounds; } private sealed class RoofQueryIndex { internal GameObject root; internal readonly Dictionary<Vector2Int, List<RoofQueryShape>> bins = new Dictionary<Vector2Int, List<RoofQueryShape>>(); internal readonly List<RoofQueryShape> large = new List<RoofQueryShape>(); } [HarmonyPatch(typeof(WearNTear), "HaveRoof")] private static class BakedRoofReadinessPatch { private static void Postfix(WearNTear __instance, ref bool __result) { if (!__result && (Object)(object)Instance != (Object)null) { __result = Instance.RetryInactiveBakedRoof(__instance); } } } [HarmonyPatch(typeof(RandomPieceRotation), "Awake")] private static class ParkedRuinRotationPatch { private static bool Prefix(RandomPieceRotation __instance) { //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: 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_00b7: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Instance == (Object)null) { return true; } ZNetView componentInParent = ((Component)__instance).GetComponentInParent<ZNetView>(true); ZDO val = (((Object)(object)componentInParent != (Object)null) ? componentInParent.GetZDO() : null); if (val == null || !val.GetBool(BakedKey, false) || (Object)(object)ZNetScene.instance == (Object)null) { return true; } GameObject prefab = ZNetScene.instance.GetPrefab(val.GetPrefab()); if ((Object)(object)prefab == (Object)null || !RotatedRuinNames.Contains(((Object)prefab).name)) { return true; } if (__instance.m_rotateX || !__instance.m_rotateY || __instance.m_rotateZ || __instance.m_stepsY != 4) { return true; } Transform val2 = ((Component)__instance).transform; while ((Object)(object)val2 != (Object)(object)((Component)componentInParent).transform) { if (!((Object)(object)val2 == (Object)null)) { Vector3 localPosition = val2.localPosition; if (((Vector3)(ref localPosition)).Equals(Vector3.zero)) { val2 = val2.parent; continue; } } return true; } ((Component)__instance).transform.localRotation = RuinRotationAt(val.GetVec3(PositionKey, val.GetPosition())); return false; } } private sealed class FastColliderCellState { public string directory; public string cacheId; public GameObject root; public List<Mesh> owned; public readonly List<SubClusterCacheEntry> pending = new List<SubClusterCacheEntry>(); public readonly HashSet<string> required = new HashSet<string>(); } private sealed class PreparedGpuRead { public string cacheId; public ulong fingerprint; public Task<RawGpuCache> task; } [HarmonyPatch(typeof(StaticPhysics), "SUpdate")] private static class BakedWorldBuildingPhysicsPatch { private static bool Prefix(StaticPhysics __instance) { return AllowWorldBuildingPhysics(__instance); } } [HarmonyPatch(typeof(StaticPhysics), "FallUpdate")] private static class BakedWorldBuildingFallPatch { private static bool Prefix(StaticPhysics __instance) { return AllowWorldBuildingPhysics(__instance); } } public sealed class ZoneBodyGuard : MonoBehaviour { private InstanceCombinerMod mod; private ZNetView view; private Rigidbody[] bodies; private bool[] kinematic; private Vector3[] velocity; private Vector3[] angular; private Vector3 lastPosition; private Vector3 heldAhead; private float nextCheck; private int coverage = -1; private int revision = -1; private long owner = long.MinValue; private bool held; private int preparedRevision = -1; private Vector3 preparedPosition; private float nextPreparation; internal bool WasDynamic(Rigidbody body) { if (!held) { return false; } for (int i = 0; i < bodies.Length; i++) { if ((Object)(object)bodies[i] == (Object)(object)body) { return !kinematic[i]; } } return false; } internal void Initialize(InstanceCombinerMod instance, Rigidbody[] value) { mod = instance; bodies = value; view = ((Component)this).GetComponent<ZNetView>(); if ((Object)(object)view == (Object)null) { view = ((Component)this).GetComponentInParent<ZNetView>(true); } kinematic = new bool[value.Length]; velocity = (Vector3[])(object)new Vector3[value.Length]; angular = (Vector3[])(object)new Vector3[value.Length]; mod.zoneBodies.Add(this); if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsDedicated()) { mod.dedicatedCollisionQueue.Enqueue(this); } } internal void PrepareDedicatedCollision() { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: 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_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0091: 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_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: 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_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010b: 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_011e: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: 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_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_013f: 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_0145: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)mod == (Object)null || !((Behaviour)mod).enabled || !((Behaviour)this).isActiveAndEnabled || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsDedicated() || ((Object)(object)view != (Object)null && (!view.IsValid() || !view.IsOwner()))) { return; } Vector3 position = ((Component)this).transform.position; Vector3 val; if (preparedRevision == mod.collisionCoverageRevision && Time.unscaledTime < nextPreparation) { val = position - preparedPosition; if (((Vector3)(ref val)).sqrMagnitude < 0.25f) { return; } } Vector3 val2 = position + (held ? heldAhead : ((bodies.Length != 0 && (Object)(object)bodies[0] != (Object)null) ? Vector3.ClampMagnitude(bodies[0].linearVelocity * 0.5f, 16f) : Vector3.zero)); if (!mod.IsZoneTransitionNear(position, 8f) && !mod.IsZoneTransitionNear(val2, 8f)) { bool flag = mod.PrepareExactCollision(position, 8f); val = val2 - position; if (((Vector3)(ref val)).sqrMagnitude > 1f) { flag &= mod.PrepareExactCollision(val2, 8f); } preparedRevision = mod.collisionCoverageRevision; preparedPosition = position; nextPreparation = Time.unscaledTime + (flag ? 0.5f : 0.1f); } } private void Start() { Step(); } private void FixedUpdate() { Step(); } internal bool Step() { //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_014f: 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_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_017b: 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) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: 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_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02bc: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02c2: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)mod == (Object)null || !((Behaviour)mod).enabled || (Object)(object)ZNet.instance == (Object)null) { ReleaseWithReason("session-inactive"); return true; } if ((Object)(object)view != (Object)null && (!view.IsValid() || !view.IsOwner())) { ReleaseWithReason("ownership-or-view-changed"); owner = long.MinValue; return true; } bool flag = false; for (int i = 0; i < bodies.Length; i++) { if ((Object)(object)bodies[i] != (Object)null) { flag = true; break; } } if (!flag) { ReleaseWithReason("body-removed"); ((Behaviour)this).enabled = false; return true; } long num = (((Object)(object)view != (Object)null) ? view.GetZDO().GetOwner() : 0); Vector3 position = ((Component)this).transform.position; Vector3 val; if (owner == num && coverage == mod.collisionCoverageRevision && revision == mod.zoneGuardRevision && Time.unscaledTime < nextCheck) { val = position - lastPosition; if (((Vector3)(ref val)).sqrMagnitude < 0.25f) { return !held; } } Vector3 val2 = position; if (!held && bodies.Length != 0 && (Object)(object)bodies[0] != (Object)null) { val2 += Vector3.ClampMagnitude(bodies[0].linearVelocity * 0.5f, 16f); } else if (held) { val2 = position + heldAhead; } bool flag2 = !mod.IsZoneTransitionNear(position, 8f) && !mod.IsZoneTransitionNear(val2, 8f); if (flag2) { flag2 = mod.IsZoneReplacementReady(position, 8f); } if (flag2) { val = val2 - position; if (((Vector3)(ref val)).sqrMagnitude > 1f) { flag2 = mod.IsZoneReplacementReady(val2, 8f); } } if (flag2) { Release(); } else if (!held) { for (int j = 0; j < bodies.Length; j++) { Rigidbody val3 = bodies[j]; if (!((Object)(object)val3 == (Object)null)) { kinematic[j] = val3.isKinematic; velocity[j] = val3.linearVelocity; angular[j] = val3.angularVelocity; if (!kinematic[j]) { val3.isKinematic = true; } } } held = true; heldAhead = val2 - position; } owner = num; coverage = mod.collisionCoverageRevision; revision = mod.zoneGuardRevision; lastPosition = position; nextCheck = Time.unscaledTime + 0.2f; return flag2; } internal void Release() { ReleaseWithReason("replacement-ready"); } internal void ReleaseLostOwnership() { if (held && (Object)(object)view != (Object)null && (!view.IsValid() || !view.IsOwner())) { ReleaseWithReason("ownership-before-client-sync"); owner = long.MinValue; } } internal void AddWaitingCells(HashSet<Vector2Int> cells) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (held && (!((Object)(object)view != (Object)null) || (view.IsValid() && view.IsOwner()))) { AddNearby(((Component)this).transform.position, cells); AddNearby(((Component)this).transform.position + heldAhead, cells); } } internal void AddActiveCollisionCells(HashSet<Vector2Int> cells) { //IL_0061: 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_00bd: 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_00c9: 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_008d: 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_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) if (!((Behaviour)this).isActiveAndEnabled || ((Object)(object)view != (Object)null && (!view.IsValid() || !view.IsOwner()))) { return; } bool flag = false; Rigidbody[] array = bodies; for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] != (Object)null) { flag = true; break; } } if (flag) { AddNearby(((Component)this).transform.position, cells); Vector3 val = (held ? heldAhead : ((bodies.Length != 0 && (Object)(object)bodies[0] != (Object)null) ? Vector3.ClampMagnitude(bodies[0].linearVelocity * 0.5f, 16f) : Vector3.zero)); AddNearby(((Component)this).transform.position + val, cells); } } private static void AddNearby(Vector3 point, HashSet<Vector2Int> cells) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: 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_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) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0078: 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_00b4: Unknown result type (might be due to invalid IL or missing references) Vector2Int cell = GetCell(point); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { Vector2Int item = cell + new Vector2Int(i, j); float num = Mathf.Max(new float[3] { (float)((Vector2Int)(ref item)).x * 64f - point.x, 0f, point.x - (float)(((Vector2Int)(ref item)).x + 1) * 64f }); float num2 = Mathf.Max(new float[3] { (float)((Vector2Int)(ref item)).y * 64f - point.z, 0f, point.z - (float)(((Vector2Int)(ref item)).y + 1) * 64f }); if (num * num + num2 * num2 <= 64f) { cells.Add(item); } } } } internal bool DeferVelocity(Rigidbody body, Vector3 value, bool rotation) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) if (!held || !body.isKinematic) { return false; } for (int i = 0; i < bodies.Length; i++) { if ((Object)(object)bodies[i] == (Object)(object)body && !kinematic[i]) { if (rotation) { angular[i] = value; } else { velocity[i] = value; } return true; } } return false; } internal void ReleaseWithReason(string reason) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) if (!held) { return; } for (int i = 0; i < bodies.Length; i++) { Rigidbody val = bodies[i]; if (!((Object)(object)val == (Object)null)) { if (val.isKinematic != kinematic[i]) { val.isKinematic = kinematic[i]; } if (!kinematic[i]) { val.linearVelocity = velocity[i]; val.angularVelocity = angular[i]; } } } held = false; coverage = -1; } private void OnDisable() { ReleaseWithReason("disabled"); coverage = -1; } private void OnDestroy() { ReleaseWithReason("destroyed"); if ((Object)(object)mod != (Object)null) { mod.zoneBodies.Remove(this); } } } [HarmonyPatch(typeof(ZNetScene), "CreateObject")] private static class ZoneBodyCreatedPatch { private static void Postfix(GameObject __result) { if ((Object)(object)Instance != (Object)null) { Instance.AttachZoneBodyGuard(__result); } } } [HarmonyPatch(typeof(ZNetView), "Awake")] private static class ZoneBodyAwakePatch { private static void Postfix(ZNetView __instance) { if ((Object)(object)Instance != (Object)null) { Instance.AttachZoneBodyGuard(((Component)__instance).gameObject); } } } private Player collisionPlayer; private MobCollisionState playerCollisionState; private readonly ConditionalWeakTable<List<BakedRecord>, ComfortRows> comfortRows = new ConditionalWeakTable<List<BakedRecord>, ComfortRows>(); private readonly ConditionalWeakTable<RestoreSupportCell, List<BakedRecord>> restoringComfortRows = new ConditionalWeakTable<RestoreSupportCell, List<BakedRecord>>(); private static readonly string[] BakeMaterialNames = new string[17] { "Wood", "Stone", "Black Marble", "Grausten", "Iron", "Other", "Corewood", "Darkwood", "Shingle Roof", "Ashwood", "Thatch Roof", "Copper", "Flametal", "Crystal", "Ice", "Timberwood", "Finewood" }; private static readonly string[] BakeMaterialRussianNames = new string[17] { "Древесина", "Камень", "Черный мрамор", "Серокамень", "Железо", "Прочие материалы", "Цельная древесина", "Детали из темного дерева", "Шиферная крыша", "Пепельная древесина", "Соломенная крыша", "Медь", "Огнеметалл", "Кристалл", "Лед", "Древесина северной ели", "Качественная древесина" }; private ConfigEntry<bool>[] bakeMaterials; private ConfigEntry<bool> bakeDamagedPieces; private const double DiagnosticClock = 0.0; private static readonly HashSet<CartCollisionGuard> cartCollisionGuards = new HashSet<CartCollisionGuard>(); private readonly HashSet<Vector2Int> pendingClientRebakes = new HashSet<Vector2Int>(); private int collisionCoverageRevision; private readonly Dictionary<Character, MobCollisionState> mobCollisionStates = new Dictionary<Character, MobCollisionState>(); private float nextCollisionDiagnostic; private static readonly Func<WearNTear, bool> NativeHasSupport = (Func<WearNTear, bool>)Delegate.CreateDelegate(typeof(Func<WearNTear, bool>), AccessTools.Method(typeof(WearNTear), "HaveSupport", (Type[])null, (Type[])null)); private static readonly Action<WearNTear> NativeUpdateSupport = (Action<WearNTear>)Delegate.CreateDelegate(typeof(Action<WearNTear>), AccessTools.Method(typeof(WearNTear), "UpdateSupport", (Type[])null, (Type[])null)); private static readonly Action<WearNTear> NativeClearSupport = (Action<WearNTear>)Delegate.CreateDelegate(typeof(Action<WearNTear>), AccessTools.Method(typeof(WearNTear), "ClearCachedSupport", (Type[])null, (Type[])null)); private bool repairingStructuralSupport; private readonly Dictionary<Vector2Int, float> actorCollisionRetention = new Dictionary<Vector2Int, float>(); private readonly Dictionary<GpuDrawGroup, CrystalBatchState> crystalBatches = new Dictionary<GpuDrawGroup, CrystalBatchState>(); private readonly List<CrystalBatchState> submittedCrystalBatches = new List<CrystalBatchState>(); private readonly HashSet<Renderer> crystalTransparentCandidates = new HashSet<Renderer>(); private readonly List<Renderer> crystalRendererScratch = new List<Renderer>(); private readonly CrystalExternalBarriers crystalSharedBarriers = new CrystalExternalBarriers(); private readonly List<Bounds> crystalVisibleExternalBounds = new List<Bounds>(); private readonly List<Bounds> crystalExternalBounds = new List<Bounds>(); private readonly List<ReflectionProbeBlendInfo> crystalProbeScratch = new List<ReflectionProbeBlendInfo>(); private readonly List<Material> crystalMaterialScratch = new List<Material>(); private AssetBundle crystalShaderBundle; private Shader crystalGroupedShader; private Shader crystalSinglePassShader; private MeshRenderer crystalReflectionQuery; private Camera crystalBatchCamera; private CrystalTransparentScene crystalSceneTracker; private bool crystalSceneTrackerFailed; private int crystalSceneLastFrame = -1; private bool crystalSceneSeeded; private int crystalEnvironmentFrame = -1; private double crystalFrameSceneMs; private double crystalFrameGroupingMs; private double crystalFrameEnvironmentMs; private double crystalFrameReflectionMs; private double crystalFramePlanMs; private double crystalFrameSubmitMs; private int crystalFrameBatches; private int crystalFrameFastBatches; private int crystalFrameFastPanes; private long crystalReflectionRebuilds; private long crystalReflectionPayloadUpdates; private int crystalProbeRevision; private int crystalPayloadRevision; private readonly Dictionary<int, CrystalProbeSnapshot> crystalProbeSnapshots = new Dictionary<int, CrystalProbeSnapshot>(); private Texture crystalSkyTexture; private Vector4 crystalSkyHdr; private Light[] crystalFrameLights = (Light[])(object)new Light[0]; private ReflectionProbe[] crystalFrameProbes = (ReflectionProbe[])(object)new ReflectionProbe[0]; private readonly Dictionary<int, bool> crystalUniformProbeChecks = new Dictionary<int, bool>(); private CrystalSimpleLight[] crystalSimpleLights = new CrystalSimpleLight[0]; private int crystalSimpleLightCount; private int crystalSimpleLightFrame = -1; private readonly Vector4[] crystalSimplePositions = (Vector4[])(object)new Vector4[4]; private readonly Vector4[] crystalSimpleColors = (Vector4[])(object)new Vector4[4]; private readonly Vector4[] crystalSimpleDirections = (Vector4[])(object)new Vector4[4]; private readonly float[] crystalSimpleScores = new float[4]; private static readonly int CrystalSimplePositionId = Shader.PropertyToID("_PupSimplePosition"); private static readonly int CrystalSimpleColorId = Shader.PropertyToID("_PupSimpleColor"); private static readonly int CrystalSimpleDirectionId = Shader.PropertyToID("_PupSimpleDirection"); private static readonly int CrystalSimpleCountId = Shader.PropertyToID("_PupSimpleCount"); private readonly CrystalBatchPlanner crystalUnifiedPlanner = new CrystalBatchPlanner(); private readonly List<CrystalBatchState> crystalUnifiedSources = new List<CrystalBatchState>(); private Matrix4x4[] crystalUnifiedMatrices; private bool crystalUnifiedCompatible; private string[] crystalUnifiedKeys; private Bounds[] crystalUnifiedBounds; private readonly Dictionary<CrystalBatchState, int> crystalUnifiedKinds = new Dictionary<CrystalBatchState, int>(); private readonly List<CrystalBatchState> crystalUnifiedMaterials = new List<CrystalBatchState>(); private readonly Dictionary<string, CrystalBatchState> crystalUnifiedDrawSources = new Dictionary<string, CrystalBatchState>(); private readonly Dictionary<CrystalUnifiedBindingKey, string> crystalUnifiedReflections = new Dictionary<CrystalUnifiedBindingKey, string>(); private readonly Dictionary<MaterialPropertyBlock, string> crystalUnifiedBlockNames = new Dictionary<MaterialPropertyBlock, string>(); private readonly Dictionary<string, MaterialPropertyBlock> crystalUnifiedBlocks = new Dictionary<string, MaterialPropertyBlock>(); private readonly List<string> crystalUnifiedNames = new List<string>(); private readonly Dictionary<MaterialPropertyBlock, string> crystalUnifiedPreviousNames = new Dictionary<MaterialPropertyBlock, string>(); private readonly Dictionary<CrystalBatchState, int> crystalUnifiedMembership = new Dictionary<CrystalBatchState, int>(); private bool crystalFrameUnified; private string crystalUnifiedRejectReason = "not-submitted"; private MaterialPropertyBlock crystalUnifiedFastBlock; private SphericalHarmonicsL2[] crystalUnifiedAmbient; private Vector4[] crystalUnifiedOcclusion; private SphericalHarmonicsL2 crystalUnifiedAmbientValue; private bool crystalUnifiedAmbientReady; private int[] crystalUnifiedProbeIds; private MaterialPropertyBlock crystalSharedAmbientBlock; private readonly List<Vector4> crystalSharedAmbientReadback = new List<Vector4>(1); private static readonly string[] CrystalSharedAmbientNames = new string[7] { "unity_SHAr", "unity_SHAg", "unity_SHAb", "unity_SHBr", "unity_SHBg", "unity_SHBb", "unity_SHC" }; private readonly Vector4[] crystalSharedAmbientVectors = (Vector4[])(object)new Vector4[7]; private readonly List<MeshRenderer> submittedCrystalVisuals = new List<MeshRenderer>(); private Camera crystalVisualCamera; private bool crystalVisualsVisible; private readonly Queue<ZoneBodyGuard> dedicatedCollisionQueue = new Queue<ZoneBodyGuard>(); private ConfigEntry<bool> expandedStaticBaking; private HashSet<string> expandedAmbiguousAssets; private static FieldInfo moreVanillaAddedPieces; private static bool moreVanillaRegistryChecked; private const long FractureStateMarker = 4611686018427387904L; private const long FractureRootBoxMarker = 2305843009213693952L; private static readonly Func<WearNTear, float> ReadWearSupport = CreateSupportReader(); private readonly ConditionalWeakTable<MeshRenderer, RainDrawData> rainDrawData = new ConditionalWeakTable<MeshRenderer, RainDrawData>(); private readonly ConditionalWeakTable<BaseAI, AiCharacterReference> aiCharacters = new ConditionalWeakTable<BaseAI, AiCharacterReference>(); private readonly HashSet<Vector2Int> partialGpuVisualCells = new HashSet<Vector2Int>(); private static readonly HashSet<string> ambiguousGpuSourceKeys = new HashSet<string>(StringComparer.Ordinal); private ConfigEntry<KeyCode> bakeKey; private ConfigEntry<KeyCode> unbakeKey; private ConfigEntry<KeyCode> highlightKey; private ConfigEntry<KeyCode> restoreAllKey; private readonly HashSet<Vector2Int> attemptedInvalidCacheRecoveryCells = new HashSet<Vector2Int>(); private bool invalidRecoveryRunning; internal static InstanceCombinerMod Instance; private const float CellSize = 64f; private const float ParkingCoordinate = 1900000f; private const string CacheSchema = "c14"; private const string StateHeader = "PUP_SAFE|13|64|STABLE_OBJECT_ID|CACHE_ID|TRANSACTIONAL|MODE_ISOLATED|WEAR_STATE|FRACTURE_STATE"; private const string WearStateHeader = "PUP_SAFE|12|64|STABLE_OBJECT_ID|CACHE_ID|TRANSACTIONAL|MODE_ISOLATED|WEAR_STATE"; private const string PriorStateHeader = "PUP_SAFE|11|64|STABLE_OBJECT_ID|CACHE_ID|TRANSACTIONAL|MODE_ISOLATED"; private const string LegacyStateHeader = "PUP_SAFE|8|64|GRAUSTEN|SUBCLUSTER16|CUSTOM_ID"; private readonly Harmony harmony = new Harmony("com.pup.instancecombiner.safe"); private static readonly FieldInfo WearSupportField = AccessTools.Field(typeof(WearNTear), "m_support"); private readonly Dictionary<Vector2Int, GameObject> clusters = new Dictionary<Vector2Int, GameObject>(); private readonly Dictionary<Vector2Int, List<Mesh>> generatedMeshes = new Dictionary<Vector2Int, List<Mesh>>(); private readonly Dictionary<Vector2Int, List<BakedRecord>> records = new Dictionary<Vector2Int, List<BakedRecord>>(); private readonly Dictionary<Vector2Int, string> cacheIds = new Dictionary<Vector2Int, string>(); private readonly Dictionary<string, Material> materialCopies = new Dictionary<string, Material>(StringComparer.Ordinal); private readonly HashSet<Vector2Int> failedCacheCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> staleCleanupPending = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> pendingWorldSaveRestores = new HashSet<Vector2Int>(); private const string RestorePendingCacheId = "RESTORE_PENDING"; private readonly Dictionary<Vector2Int, HashSet<ZDOID>> pendingRestoredInstances = new Dictionary<Vector2Int, HashSet<ZDOID>>(); private readonly Dictionary<ZDOID, List<MeshRenderer>> hiddenRenderers = new Dictionary<ZDOID, List<MeshRenderer>>(); private readonly Dictionary<ZDOID, List<LODGroup>> hiddenLodGroups = new Dictionary<ZDOID, List<LODGroup>>(); private static Dictionary<string, Mesh> meshAssetCache; private static Dictionary<string, Material> materialAssetCache; private static Dictionary<string, (Mesh mesh, Material material)> gpuSourceCache; private static bool gpuSourceCacheBuilding; private readonly HashSet<Vector2Int> gpuCacheReadyCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> suppressedVisualCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> startupVisualBatchCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> warmingStartupCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> revealedStartupCells = new HashSet<Vector2Int>(); private bool startupVisualBatchRevealed; private bool visualWarmupRunning; private readonly HashSet<Vector2Int> loadingCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> singlePlayerFullGpuCells = new HashSet<Vector2Int>(); private readonly Dictionary<Vector2Int, bool> colliderCellActive = new Dictionary<Vector2Int, bool>(); private readonly Dictionary<Vector2Int, HashSet<string>> protectedSupportColliders = new Dictionary<Vector2Int, HashSet<string>>(); private Vector3 previousPlayerPosition; private Vector3 smoothedTravelDirection; private float nextColliderActivationCheck; private const float ColliderEnableRadius = 80f; private const float ColliderDisableRadius = 96f; private const float ColliderPreloadSeconds = 2f; private const double MainThreadLoadBudgetMs = 2.0; private const double ColliderLoadBudgetMs = 1.0; private const float SupportGuardGraceSeconds = 10f; private bool processing; private bool highlightEnabled; private readonly HashSet<Vector2Int> highlightSuppressedCells = new HashSet<Vector2Int>(); private bool cacheLoadingProgressActive; private bool cacheLoadingProgressVisible; private float cacheLoadingProgressStarted; private int cacheLoadingProgressCompleted; private int cacheLoadingProgressTotal; private readonly HashSet<Vector2Int> multiplayerStartupProgressCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> multiplayerStartupReadyCells = new HashSet<Vector2Int>(); private bool multiplayerStartupProgressCaptured; private bool multiplayerStartupProgressCompleted; private GUIStyle cacheLoadingProgressStyle; private GUIStyle cacheLoadingProgressShadowStyle; private string worldName = ""; private long worldUid; private readonly Dictionary<int, Material> highlightMaterials = new Dictionary<int, Material>(); private readonly Dictionary<MeshRenderer, Material[]> highlightedClusterMaterials = new Dictionary<MeshRenderer, Material[]>(); private float nextCellCheck; private int activeColliderLoads; private int pendingSubClusterLoads; private readonly SortedDictionary<int, Queue<PendingCollider>> pendingColliders = new SortedDictionary<int, Queue<PendingCollider>>(); private int queuedColliderCount; private int loadedQueuedColliders; private float supportGuardUntil; private ZNet loadedZNet; private ZDOMan stableZdoIndexOwner; private long stableZdoIndexWorldUid; private Dictionary<string, List<ZDO>> stableZdoIndexCache; private bool safeSaveRestoreInProgress; private bool applicationQuitting; private readonly Dictionary<Vector2Int, List<GpuDrawGroup>> gpuBakedGroups = new Dictionary<Vector2Int, List<GpuDrawGroup>>(); private readonly HashSet<Material> retiredGpuMaterials = new HashSet<Material>(); private readonly Dictionary<Vector2Int, List<MeshRenderer>> gpuClusterHidden = new Dictionary<Vector2Int, List<MeshRenderer>>(); private readonly Dictionary<Vector2Int, List<MeshRenderer>> precipitationRenderers = new Dictionary<Vector2Int, List<MeshRenderer>>(); private readonly Dictionary<MeshRenderer, bool> skyAlphaPreviousEnabled = new Dictionary<MeshRenderer, bool>(); private readonly Dictionary<MeshRenderer, int> skyAlphaPreviousLayer = new Dictionary<MeshRenderer, int>(); private readonly Dictionary<MeshRenderer, ShadowCastingMode> skyAlphaPreviousShadowMode = new Dictionary<MeshRenderer, ShadowCastingMode>(); private Mesh singlePlayerPrecipitationCubeMesh; private readonly Plane[] gpuFrustumPlanes = (Plane[])(object)new Plane[6]; private readonly Dictionary<Vector2Int, Bounds> gpuCellWorldBounds = new Dictionary<Vector2Int, Bounds>(); private readonly Dictionary<Vector2Int, bool> gpuCellCameraVisible = new Dictionary<Vector2Int, bool>(); private Camera gpuCullCamera; private Vector3 gpuCullCameraPosition; private Quaternion gpuCullCameraRotation; private float gpuCullCameraFieldOfView; private float gpuCullCameraAspect; private bool gpuCullVisibilityDirty = true; private int meshStreamingBudgetFrame = -1; private float meshStreamingBudgetStarted; [ThreadStatic] private static byte[] meshWriteBuffer; private static readonly FieldInfo ZNetSceneInstancesField = typeof(ZNetScene).GetField("m_instances", BindingFlags.Instance | BindingFlags.NonPublic); private const string MultiplayerProtocol = "PUP_MP_7"; private const string MultiplayerVersion = "1.0.38"; private const string MultiplayerClientCacheHeader = "PUP_MP_CLIENT_RECORDS_5"; private const string WearClientCacheHeader = "PUP_MP_CLIENT_RECORDS_4"; private const string LegacyClientCacheHeader = "PUP_MP_CLIENT_RECORDS_3"; private const int MultiplayerRecordBatchSize = 512; private const string MetadataAckName = "__PUP_METADATA_READY__"; private const int MultiplayerChunkSize = 8192; private const float MultiplayerRequestRadius = 192f; private const float MultiplayerChunkAckTimeout = 15f; private const float MultiplayerReceiveTimeout = 60f; private const float MultiplayerHandshakeTimeout = 30f; private const string RpcHello = "PUP_FPS_MP_HELLO"; private const string RpcReject = "PUP_FPS_MP_REJECT"; private const string RpcManifest = "PUP_FPS_MP_MANIFEST"; private const string RpcRequestCell = "PUP_FPS_MP_REQUEST_CELL"; private const string RpcCellFiles = "PUP_FPS_MP_CELL_FILES"; private const string RpcCellChunk = "PUP_FPS_MP_CELL_CHUNK"; private const string RpcCellAck = "PUP_FPS_MP_CELL_ACK"; private const string RpcCellRemoved = "PUP_FPS_MP_CELL_REMOVED"; private const string RpcCellRecords = "PUP_FPS_MP_CELL_RECORDS"; private const string RpcRecordAck = "PUP_FPS_MP_RECORD_ACK"; private const string RpcAdminCommand = "PUP_FPS_ADMIN_COMMAND"; private const string RpcAdminResult = "PUP_FPS_ADMIN_RESULT"; private const string RpcAdminHighlight = "PUP_FPS_ADMIN_HIGHLIGHT"; private const string RpcRestoreAck = "PUP_FPS_MP_RESTORE_ACK"; private const string RpcRestoreProgress = "PUP_FPS_MP_RESTORE_PROGRESS"; private const string RpcBakeReady = "PUP_FPS_MP_BAKE_READY"; private ZRoutedRpc multiplayerRpc; private float nextMultiplayerHello; private float nextMultiplayerPeerCheck; private bool multiplayerManifestReceived; private bool multiplayerRejected; private readonly HashSet<long> multiplayerVerifiedPeers = new HashSet<long>(); private readonly Dictionary<long, float> multiplayerPeerFirstSeen = new Dictionary<long, float>(); private readonly Dictionary<Vector2Int, RemoteCellManifest> multiplayerRemoteCells = new Dictionary<Vector2Int, RemoteCellManifest>(); private readonly HashSet<Vector2Int> multiplayerRequestedCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> multiplayerPendingLoadCells = new HashSet<Vector2Int>(); private readonly Dictionary<Vector2Int, int> multiplayerBuildGenerations = new Dictionary<Vector2Int, int>(); private readonly HashSet<Vector2Int> multiplayerPendingVanillaRestore = new HashSet<Vector2Int>(); private readonly Dictionary<ZDOID, Vector2Int> multiplayerRestoreTrackedZdos = new Dictionary<ZDOID, Vector2Int>(); private readonly Dictionary<Vector2Int, List<ZNetView>> multiplayerRestoredViews = new Dictionary<Vector2Int, List<ZNetView>>(); private IncomingCellTransfer multiplayerIncomingTransfer; private long multiplayerServerPeerUid; private ConnectionStatus multiplayerLastConnectionStatus; private readonly HashSet<long> multiplayerSendingPeers = new HashSet<long>(); private readonly HashSet<string> multiplayerPendingChunkAcks = new HashSet<string>(); private Vector2Int? multiplayerOutstandingRequest; private float multiplayerOutstandingRequestStarted; private float nextMultiplayerCellRequestAllowed; private IncomingRecordTransfer multiplayerIncomingRecords; private readonly Dictionary<Vector2Int, List<BakedRecord>> multiplayerDiskCachedRecords = new Dictionary<Vector2Int, List<BakedRecord>>(); private readonly Dictionary<Vector2Int, Dictionary<string, Queue<BakedRecord>>> multiplayerRemoteCreationIndex = new Dictionary<Vector2Int, Dictionary<string, Queue<BakedRecord>>>(); private readonly Dictionary<ZDOID, ZDO> multiplayerSuppressedRemoteZdos = new Dictionary<ZDOID, ZDO>(); private readonly Dictionary<string, Vector2Int> multiplayerSuppressedStableCells = new Dictionary<string, Vector2Int>(StringComparer.Ordinal); private readonly Dictionary<Vector2Int, HashSet<long>> multiplayerPendingRestoreAcks = new Dictionary<Vector2Int, HashSet<long>>(); private readonly Dictionary<Vector2Int, Dictionary<long, float>> multiplayerRestoreProgress = new Dictionary<Vector2Int, Dictionary<long, float>>(); private readonly HashSet<Vector2Int> multiplayerRemotePhysicsReady = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> multiplayerProvisionalVisualCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> multiplayerProvisionalBuildsInProgress = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> multiplayerRemoteBuildsInProgress = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> multiplayerRemoteBuildsExecuting = new HashSet<Vector2Int>(); private int multiplayerBuildSession; private readonly Dictionary<Vector2Int, List<RemoteVisualHandoff>> multiplayerPendingVisualHandoffs = new Dictionary<Vector2Int, List<RemoteVisualHandoff>>(); private readonly Dictionary<Vector2Int, int> multiplayerGpuSubmittedFrames = new Dictionary<Vector2Int, int>(); private readonly Dictionary<Vector2Int, int> multiplayerHandoffPublishedFrames = new Dictionary<Vector2Int, int>(); private readonly Dictionary<Vector2Int, float> multiplayerHandoffPublishedTimes = new Dictionary<Vector2Int, float>(); private readonly Dictionary<Vector2Int, RemoteFinalVisualHandoff> multiplayerPendingFinalVisualHandoffs = new Dictionary<Vector2Int, RemoteFinalVisualHandoff>(); private readonly Dictionary<Vector2Int, RemoteProvisionalVisualPublication> multiplayerPendingProvisionalVisualPublications = new Dictionary<Vector2Int, RemoteProvisionalVisualPublication>(); private readonly Dictionary<Vector2Int, float> multiplayerPortalPrewarmUntil = new Dictionary<Vector2Int, float>(); private bool multiplayerClientShutdownInProgress; private bool multiplayerServerAdminAllowed; private bool multiplayerRemoteServerDedicated; private int multiplayerDedicatedBudgetFrame = -1; private long multiplayerDedicatedBudgetStarted; private int multiplayerDedicatedLastProvisionalStartFrame = -1; private bool multiplayerDedicatedPortalPending; private Vector3 multiplayerDedicatedPortalTarget; private float multiplayerDedicatedPortalDeadline; private bool multiplayerProvisionalCacheScanned; private long multiplayerManifestRevision; private long multiplayerLastReceivedManifestRevision = -1L; private GameObject multiplayerSpawnSafety; private Vector2Int multiplayerSpawnSafetyCell; private float multiplayerSpawnSafetyY; private float multiplayerSpawnSafetyReadySince = -1f; private readonly Dictionary<Vector2Int, HashSet<long>> multiplayerPendingBakeReady = new Dictionary<Vector2Int, HashSet<long>>(); private readonly HashSet<Vector3> navUniquePoints = new HashSet<Vector3>(); private readonly HashSet<List<KeyValuePair<Vector3, NavMeshLinkInstance>>> replacingNavLinks = new HashSet<List<KeyValuePair<Vector3, NavMeshLinkInstance>>>(); private readonly Dictionary<Vector2Int, PlantSupportCell> plantSupports = new Dictionary<Vector2Int, PlantSupportCell>(); private float nextPlantSupportMaintenance; private static readonly MethodInfo VineSupportedMethod = AccessTools.Method(typeof(Vine), "IsSupported", (Type[])null, (Type[])null); private static readonly FieldInfo VineSupportSensor = AccessTools.Field(typeof(Vine), "m_supportCollider"); private static readonly FieldInfo VinePieceMask = AccessTools.Field(typeof(Vine), "s_pieceMask"); private static readonly FieldInfo PlantPieceMask = AccessTools.Field(typeof(Plant), "m_pieceMask"); private readonly Dictionary<GameObject, HashSet<Mesh>> remoteOwnedColliderMeshes = new Dictionary<GameObject, HashSet<Mesh>>(); private readonly HashSet<Vector2Int> verifiedRemoteReplacements = new HashSet<Vector2Int>(); private readonly HashSet<GameObject> validatedReplacementRoots = new HashSet<GameObject>(); private readonly Dictionary<GameObject, string> validatedReplacementCacheIds = new Dictionary<GameObject, string>(); private readonly Dictionary<Vector2Int, float> replacementRetryAt = new Dictionary<Vector2Int, float>(); private readonly Dictionary<Vector2Int, int> expectedReplacementSolids = new Dictionary<Vector2Int, int>(); private static readonly Func<ZDO, bool> IsOutsideRestoreSector = AccessTools.MethodDelegate<Func<ZDO, bool>>(AccessTools.PropertyGetter(typeof(ZDO), "OutsideZones"), (object)null, true); private static readonly Action<ZDO, SectorIndex> SetRestoreSector = AccessTools.MethodDelegate<Action<ZDO, SectorIndex>>(AccessTools.Method(typeof(ZDO), "SetSector", (Type[])null, (Type[])null), (object)null, true); private readonly ConditionalWeakTable<BakedRecord, StateText> stateText = new ConditionalWeakTable<BakedRecord, StateText>(); private int remoteRestoreWorkFrame = -1; private int remoteRestoreWorkCount; private long remoteRestoreWorkStarted; private Dictionary<string, List<ZDO>> remoteRestoreFallback; private ZDOMan remoteRestoreFallbackOwner; private bool remoteRestoreFallbackBuilding; private readonly Dictionary<Vector2Int, RestoreSupportCell> restoreSupportCells = new Dictionary<Vector2Int, RestoreSupportCell>(); private readonly Dictionary<string, ZNetView> restoreSupportViews = new Dictionary<string, ZNetView>(StringComparer.Ordinal); private ZDOMan restoreSupportOwner; private bool restoreSupportChecking; private float restoreSupportNextCheck; private static readonly Func<WearNTear, bool> NativeRoofCheck = (Func<WearNTear, bool>)Delegate.CreateDelegate(typeof(Func<WearNTear, bool>), AccessTools.Method(typeof(WearNTear), "HaveRoof", (Type[])null, (Type[])null)); private static readonly FieldRef<WearNTear, float> RoofCheckOffset = AccessTools.FieldRefAccess<WearNTear, float>("m_roofCheckOffset"); private readonly Dictionary<Vector2Int, RoofQueryIndex> inactiveRoofQueries = new Dictionary<Vector2Int, RoofQueryIndex>(); private readonly List<Collider> roofQueryEnabled = new List<Collider>(); private bool retryingRoofCheck; private static readonly HashSet<string> RotatedRuinNames = new HashSet<string>(StringComparer.Ordinal) { "Ashlands_Pillar4", "Ashlands_Pillar4_tip", "Ashlands_Pillar4_tip3", "Ashlands_Ruins_twist_PillarBase", "Ashlands_Ruins_twist_PillarBaseSmall" }; private readonly Dictionary<Vector2Int, FastColliderCellState> fastColliderCells = new Dictionary<Vector2Int, FastColliderCellState>(); private readonly Dictionary<Vector2Int, HashSet<string>> fastLoadedSubclusters = new Dictionary<Vector2Int, HashSet<string>>(); private readonly Dictionary<Vector2Int, Vector3> singlePlayerFastFocus = new Dictionary<Vector2Int, Vector3>(); private readonly Dictionary<Vector2Int, float> singlePlayerFastRetainUntil = new Dictionary<Vector2Int, float>(); private readonly HashSet<Vector2Int> singlePlayerDormantCells = new HashSet<Vector2Int>(); private readonly Dictionary<Vector2Int, float> singlePlayerFastLastUsed = new Dictionary<Vector2Int, float>(); private const int SinglePlayerDormantCellLimit = 20; private readonly Dictionary<Vector2Int, PreparedGpuRead> singlePlayerPreparedGpuReads = new Dictionary<Vector2Int, PreparedGpuRead>(); private bool singlePlayerInitialVisualPipelineRunning; private readonly Dictionary<Vector2Int, float> singlePlayerVisualHandoffStarted = new Dictionary<Vector2Int, float>(); private bool fastColliderPumpRunning; private readonly HashSet<Vector2Int> fastWaitingBodyCells = new HashSet<Vector2Int>(); private bool singlePlayerPortalCurtainActive; private float singlePlayerPortalCurtainReleaseAt; private bool singlePlayerStartupCurtainActive; private float singlePlayerStartupCurtainStarted; private readonly HashSet<Vector2Int> singlePlayerStartupCurtainCells = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> singlePlayerVisualHandoffNeedsParking = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> singlePlayerReparkRunning = new HashSet<Vector2Int>(); private readonly HashSet<Vector2Int> invalidCacheRecoveryCells = new HashSet<Vector2Int>(); private readonly Dictionary<Vector2Int, List<ZNetView>> pendingSoloBakePublications = new Dictionary<Vector2Int, List<ZNetView>>(); private readonly Dictionary<Vector2Int, bool> wearLoadingReadiness = new Dictionary<Vector2Int, bool>(); private int wearReadinessFrame = -1; private int wearReadinessRecords; private int wearReadinessRemotes; private int wearReadinessPhysics; private int wearReadinessClusters; private int wearReadinessLoading; private int wearReadinessPlants; private int wearReadinessCoverage; private int wearReadinessZones; private long wearReadinessManifest; private static readonly FieldInfo WorldBuildingFalling = AccessTools.Field(typeof(StaticPhysics), "m_falling"); private readonly Dictionary<Vector2Int, int> zoneTransitions = new Dictionary<Vector2Int, int>(); private readonly HashSet<ZoneBodyGuard> zoneBodies = new HashSet<ZoneBodyGuard>(); private readonly HashSet<Vector2Int> activeBodyCollisionCells = new HashSet<Vector2Int>(); private int zoneGuardRevision; private long zoneTicket; private readonly Dictionary<long, HashSet<long>> zoneAcks = new Dictionary<long, HashSet<long>>(); private readonly Dictionary<long, Vector2Int> remoteZoneTickets = new Dictionary<long, Vector2Int>(); private readonly Dictionary<long, Vector2Int> activeZoneTickets = new Dictionary<long, Vector2Int>(); private const string RpcZoneBarrier = "PUP_FPS_ZONE_BARRIER"; private const string RpcZoneBarrierAck = "PUP_FPS_ZONE_BARRIER_ACK"; private bool ExpandedStaticEnabled { get { if (expandedStaticBaking != null) { return expandedStaticBaking.Value; } return false; } } private static string MetadataScope => GetWorldMetadataScope(); private static string BakedKey => "PUP_SAFE_Baked_" + MetadataScope; private static string PositionKey => "PUP_SAFE_Position_" + MetadataScope; private static string RotationKey => "PUP_SAFE_Rotation_" + MetadataScope; private static string ScaleKey => "PUP_SAFE_Scale_" + MetadataScope; private static string CellXKey => "PUP_SAFE_CellX_" + MetadataScope; private static string CellZKey => "PUP_SAFE_CellZ_" + MetadataScope;