using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using Service; using TMPro; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("ExpandWorldSize")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+355fff425e0f4191e6e493ae35f0ae8a4ea34a24")] [assembly: AssemblyProduct("ExpandWorldSize")] [assembly: AssemblyTitle("ExpandWorldSize")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Service { public class ConfigWrapper(ConfigFile configFile, ConfigSync configSync, Action regenerate, Action regenerateMap) { private readonly ConfigFile ConfigFile = configFile; private readonly ConfigSync ConfigSync = configSync; public readonly Action Regenerate = regenerate; public readonly Action RegenerateMap = regenerateMap; public static Dictionary, float> Floats = new Dictionary, float>(); public static Dictionary, float?> NullFloats = new Dictionary, float?>(); public static Dictionary, int> Ints = new Dictionary, int>(); public ConfigEntry BindFloat(string group, string name, float value, bool regenerate, string description = "", bool synchronizedSetting = true) { ConfigEntry entry = Bind(group, name, value.ToString(CultureInfo.InvariantCulture), regenerate, description, synchronizedSetting); entry.SettingChanged += delegate { Floats[entry] = TryParseFloat(entry).GetValueOrDefault(value); }; Floats[entry] = TryParseFloat(entry).GetValueOrDefault(value); return entry; } public ConfigEntry BindFloat(string group, string name, float? value, bool regenerate, string description = "", bool synchronizedSetting = true) { ConfigEntry entry = Bind(group, name, value.HasValue ? value.Value.ToString(CultureInfo.InvariantCulture) : "", regenerate, description, synchronizedSetting); entry.SettingChanged += delegate { NullFloats[entry] = TryParseFloat(entry); }; NullFloats[entry] = TryParseFloat(entry); return entry; } public ConfigEntry Bind(string group, string name, T value, bool regenerate, ConfigDescription description, bool synchronizedSetting = true) { ConfigEntry val = configFile.Bind(group, name, value, description); if (regenerate) { val.SettingChanged += Regen; } configSync.AddConfigEntry(val).SynchronizedConfig = synchronizedSetting; return val; } public ConfigEntry Bind(string group, string name, T value, bool regenerate, string description = "", bool synchronizedSetting = true) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown return Bind(group, name, value, regenerate, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty()), synchronizedSetting); } private void Regen(object e, EventArgs s) { regenerate(); } private static float? TryParseFloat(string value) { if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result; } return null; } private static float? TryParseFloat(ConfigEntry setting) { if (float.TryParse(setting.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result; } return TryParseFloat((string)((ConfigEntryBase)setting).DefaultValue); } } public class Log { private static ManualLogSource Logger; public static void Init(ManualLogSource logger) { Logger = logger; } public static void Error(string message) { Logger.LogError((object)message); } public static void Warning(string message) { Logger.LogWarning((object)message); } public static void Info(string message) { Logger.LogInfo((object)message); } public static void Debug(string message) { Logger.LogDebug((object)message); } } } namespace ExpandWorldSize { public class BetterContinents { public const string GUID = "BetterContinents"; private static Assembly? Assembly; private static FieldInfo? SettingsField; private static FieldInfo? IsEnabledField; private static MethodInfo? SetSizeMethod; private static FieldInfo? WorldSizeField; private static FieldInfo? EdgeSizeField; private static MethodInfo? SetStretchMethod; public static void Run() { if (!Chainloader.PluginInfos.TryGetValue("BetterContinents", out var value)) { return; } Assembly = ((object)value.Instance).GetType().Assembly; Type type = Assembly.GetType("BetterContinents.BetterContinents"); if (type == null) { return; } SettingsField = AccessTools.Field(type, "Settings"); if (SettingsField == null) { return; } type = Assembly.GetType("BetterContinents.BetterContinents+BetterContinentsSettings"); IsEnabledField = AccessTools.Field(type, "EnabledForThisWorld"); if (IsEnabledField == null) { return; } type = Assembly.GetType("BetterContinents.BetterContinents"); if (type == null) { return; } SetSizeMethod = AccessTools.Method(type, "SetSize", (Type[])null, (Type[])null); Type type2 = Assembly.GetType("BetterContinents.WorldSizeHelper"); if (type2 != null) { SetStretchMethod = AccessTools.Method(type2, "SetStretch", (Type[])null, (Type[])null); } if (SetSizeMethod != null) { Log.Info("\"Better Continents\" detected. Applying compatibility."); return; } WorldSizeField = AccessTools.Field(type, "WorldSize"); EdgeSizeField = AccessTools.Field(type, "EdgeSize"); if (EdgeSizeField != null && SetSizeMethod != null) { Log.Info("Older \"Better Continents\" detected. Applying compatibility."); } } public static bool IsEnabled() { if (SettingsField == null) { return false; } if (IsEnabledField == null) { return false; } object value = SettingsField.GetValue(null); if (value == null) { return false; } return (bool)IsEnabledField.GetValue(value); } public static void RefreshSize() { SetSizeMethod?.Invoke(null, new object[2] { Configuration.WorldRadius, Configuration.WorldEdgeSize }); WorldSizeField?.SetValue(null, Configuration.WorldTotalRadius); EdgeSizeField?.SetValue(null, Configuration.WorldEdgeSize); SetStretchMethod?.Invoke(null, new object[2] { Configuration.WorldStretch, Configuration.BiomeStretch }); } } public class EWD { public const string GUID = "expand_world_data"; public static bool IsPresent; private static Assembly? Assembly; private static MethodInfo? SetSize; public static void Run() { if (!Chainloader.PluginInfos.TryGetValue("expand_world_data", out var value)) { return; } Assembly = ((object)value.Instance).GetType().Assembly; Type type = Assembly.GetType("ExpandWorldData.WorldInfo"); if (!(type == null)) { SetSize = AccessTools.Method(type, "Set", (Type[])null, (Type[])null); if (!(SetSize == null)) { Log.Info("\"Expand World Data\" detected. Applying compatibility."); IsPresent = true; } } } public static void RefreshSize() { if (!(SetSize == null)) { SetSize.Invoke(null, new object[4] { Configuration.WorldRadius, Configuration.WorldTotalRadius, Configuration.WorldStretch, Configuration.BiomeStretch }); } } } public class LPACompatibility { public const string GUID = "nickpappas.locationplacementaccelerator"; private static bool _checked; private static bool _present; public static bool IsEnabled() { if (!_checked) { _checked = true; _present = Chainloader.PluginInfos.ContainsKey("nickpappas.locationplacementaccelerator"); } return _present; } } public class Marketplace { public const string GUID = "MarketplaceAndServerNPCs"; private static Assembly? MarketplaceAssembly; private static FieldInfo? IsLoadingField; public static void Run() { if (!Chainloader.PluginInfos.TryGetValue("MarketplaceAndServerNPCs", out var value)) { return; } MarketplaceAssembly = ((object)value.Instance).GetType().Assembly; Type type = MarketplaceAssembly.GetType("API.ClientSide"); if (!(type == null)) { IsLoadingField = AccessTools.Field(type, "FillingTerritoryData"); if (!(IsLoadingField == null)) { Log.Info("\"Marketplace\" detected. Applying compatibility."); } } } public static bool IsLoading() { if (IsLoadingField == null) { return false; } return (bool)IsLoadingField.GetValue(null); } } public class WorldInfo { public static float WaterLevel = 30f; public static float BaseWaterLevel = Helper.HeightToBaseHeight(WaterLevel); public static float WorldStretch = 1f; public static float BiomeStretch = 1f; public static float WaterDepth = 1f; public static float AltitudeMultiplier = 1f; public static float BaseAltitudeDelta = 0f; public static float ForestMultiplier = 1f; public static void SetWaterLevel(float waterLevel) { if (WaterLevel != waterLevel) { WaterLevel = waterLevel; BaseWaterLevel = Helper.HeightToBaseHeight(WaterLevel); } } public static void Generate() { if (!Patcher.IsMenu) { Log.Info("Regenerating the world."); Refresh(); MapGeneration.Cancel(); WorldGenerator.instance.Pregenerate(); Heightmap[] array = Object.FindObjectsByType((FindObjectsInactive)0, (FindObjectsSortMode)0); foreach (Heightmap obj in array) { obj.m_buildData = null; obj.Regenerate(); } ClutterSystem instance = ClutterSystem.instance; if (instance != null) { instance.ClearAll(); } SetupMaterial.Refresh(); if (Object.op_Implicit((Object)(object)EnvMan.instance)) { ScaleGlobalWaterSurface.Refresh(EnvMan.instance); } if (Configuration.RegenerateMap) { Map(); } } } public static void Map() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType != 4) { Minimap instance = Minimap.instance; if (instance != null) { instance.GenerateWorldMap(); } } } public static void Refresh() { WorldStretch = Configuration.WorldStretch; BiomeStretch = Configuration.BiomeStretch; WaterDepth = Configuration.WaterDepthMultiplier; AltitudeMultiplier = Configuration.AltitudeMultiplier; ForestMultiplier = ((Configuration.ForestMultiplier == 0f) ? 1f : Configuration.ForestMultiplier); BaseAltitudeDelta = Helper.HeightToBaseHeight(Configuration.AltitudeDelta); if (Patcher.WG != null) { Patcher.WG.maxMarshDistance = VersionSetup.MaxMarshDistance * Configuration.WorldRadius / 10000f / Configuration.WorldStretch; } EWD.RefreshSize(); BetterContinents.RefreshSize(); Patcher.Patch(); } } [HarmonyPatch(typeof(WorldGenerator), "VersionSetup")] public class VersionSetup { public static float MaxMarshDistance = 6000f; private static void Prefix(WorldGenerator __instance) { __instance.maxMarshDistance = 6000f; } private static void Postfix(WorldGenerator __instance) { MaxMarshDistance = __instance.maxMarshDistance; } } [HarmonyPatch(typeof(World), "LoadWorld")] public class LoadWorld { private static World Postfix(World result) { if (Configuration.Seed != "" && !result.m_menu) { result.m_seedName = Configuration.Seed; result.m_seed = StringExtensionMethods.GetStableHashCode(Configuration.Seed); } return result; } } public class Configuration { public static ConfigEntry configRegenerateMap; public static ConfigEntry configWorldRadius; public static ConfigEntry configWorldEdgeSize; public static ConfigEntry configMapSize; public static ConfigEntry configMapPixelSize; public static ConfigEntry configAltitudeMultiplier; public static ConfigEntry configAltitudeDelta; public static ConfigEntry configLocationsMultiplier; public static ConfigEntry configForestMultiplier; public static ConfigEntry configWorldStretch; public static ConfigEntry configBiomeStretch; public static ConfigEntry configSeed; public static ConfigEntry configOffsetX; public static ConfigEntry configOffsetY; public static ConfigEntry configHeightSeed; public static ConfigEntry configWaterDepthMultiplier; public static ConfigEntry configAshlandsWidthRestriction; public static ConfigEntry configAshlandsLengthRestriction; public static ConfigEntry configRestrictAshlands; public static ConfigEntry configAshlandsGap; public static ConfigEntry configDeepNorthGap; public static ConfigEntry configFixWaterColor; public static ConfigEntry configRemoveAshlandsWater; public static bool RegenerateMap => configRegenerateMap.Value; public static float WorldRadius => ConfigWrapper.Floats[configWorldRadius]; public static float StrechedWorldRadius => WorldRadius / WorldStretch; public static float WorldEdgeSize => ConfigWrapper.Floats[configWorldEdgeSize]; public static float WorldTotalRadius => WorldRadius + WorldEdgeSize; public static float StrechedWorldTotalRadius => WorldTotalRadius / WorldStretch; public static float MapSize => ConfigWrapper.Floats[configMapSize]; public static float MapPixelSize => ConfigWrapper.Floats[configMapPixelSize]; public static float AltitudeMultiplier => ConfigWrapper.Floats[configAltitudeMultiplier]; public static float AltitudeDelta => ConfigWrapper.Floats[configAltitudeDelta]; public static float LocationsMultiplier => ConfigWrapper.Floats[configLocationsMultiplier]; public static float ForestMultiplier => ConfigWrapper.Floats[configForestMultiplier]; public static float WorldStretch => ConfigWrapper.Floats[configWorldStretch]; public static float BiomeStretch => ConfigWrapper.Floats[configBiomeStretch]; public static string Seed => configSeed.Value; public static float? OffsetX => ConfigWrapper.NullFloats[configOffsetX]; public static float? OffsetY => ConfigWrapper.NullFloats[configOffsetY]; public static float? HeightSeed => ConfigWrapper.NullFloats[configHeightSeed]; public static float WaterDepthMultiplier => ConfigWrapper.Floats[configWaterDepthMultiplier]; public static double AshlandsWidthRestriction { get { if (!RestrictAshlands) { return double.PositiveInfinity; } return ConfigWrapper.Floats[configAshlandsWidthRestriction]; } } public static double AshlandsLengthRestriction { get { if (!RestrictAshlands) { return double.PositiveInfinity; } return ConfigWrapper.Floats[configAshlandsLengthRestriction]; } } public static bool RestrictAshlands => configRestrictAshlands.Value; public static bool AshlandsGap => configAshlandsGap.Value; public static bool DeepNorthGap => configDeepNorthGap.Value; public static bool FixWaterColor => configFixWaterColor.Value; public static bool RemoveAshlandsWater => configRemoveAshlandsWater.Value; public static void Init(ConfigWrapper wrapper) { string text = "1. General"; configRegenerateMap = wrapper.Bind(text, "Regenerate map", value: true, regenerate: false, "If true, the world map is regenerated automatically on data changes."); configWorldRadius = wrapper.BindFloat(text, "World radius", 10000f, regenerate: false, "Radius of the world in meters (excluding the edge)."); configWorldRadius.SettingChanged += delegate { if (Object.op_Implicit((Object)(object)Minimap.instance)) { MinimapAwake.Refresh(Minimap.instance); } wrapper.regenerate(); }; configWorldEdgeSize = wrapper.BindFloat(text, "World edge size", 500f, regenerate: false, "Size of the edge area in meters (added to the radius for the total size)."); configWorldEdgeSize.SettingChanged += delegate { if (Object.op_Implicit((Object)(object)Minimap.instance)) { MinimapAwake.Refresh(Minimap.instance); } wrapper.regenerate(); }; configMapSize = wrapper.BindFloat(text, "Minimap size", 1f, regenerate: false, "Increases the minimap size, but also significantly increases the generation time."); configMapSize.SettingChanged += delegate { if (Object.op_Implicit((Object)(object)Minimap.instance) && MinimapAwake.Refresh(Minimap.instance)) { wrapper.regenerateMap(); } }; configMapPixelSize = wrapper.BindFloat(text, "Minimap pixel size", 0f, regenerate: false, "Decreases the minimap detail, but doesn't affect the generation time. Automatically calculated when zero."); configMapPixelSize.SettingChanged += delegate { if (Object.op_Implicit((Object)(object)Minimap.instance) && MinimapAwake.Refresh(Minimap.instance)) { wrapper.regenerateMap(); } }; configWorldStretch = wrapper.BindFloat(text, "Stretch world", 1f, regenerate: true, "Stretches the world to a bigger area."); configBiomeStretch = wrapper.BindFloat(text, "Stretch biomes", 1f, regenerate: true, "Stretches the biomes to a bigger area."); configForestMultiplier = wrapper.BindFloat(text, "Forest multiplier", 1f, regenerate: true, "Multiplies the amount of forest."); configAltitudeMultiplier = wrapper.BindFloat(text, "Altitude multiplier", 1f, regenerate: true, "Multiplies the altitude."); configAltitudeDelta = wrapper.BindFloat(text, "Altitude delta", 0f, regenerate: true, "Adds to the altitude."); configWaterDepthMultiplier = wrapper.BindFloat(text, "Water depth multiplier", 1f, regenerate: true, "Multplies the water depth."); configLocationsMultiplier = wrapper.BindFloat(text, "Locations", 1f, regenerate: true, "Multiplies the max amount of locations."); configOffsetX = wrapper.BindFloat(text, "Offset X", null, regenerate: true); configOffsetY = wrapper.BindFloat(text, "Offset Y", null, regenerate: true); configSeed = wrapper.Bind(text, "Seed", "", regenerate: false); configSeed.SettingChanged += delegate { if (!(Seed == "") && WorldGenerator.instance != null) { World world = WorldGenerator.instance.m_world; if (!world.m_menu) { world.m_seedName = Seed; world.m_seed = StringExtensionMethods.GetStableHashCode(Seed); world.m_menu = true; WorldGenerator.Initialize(world); world.m_menu = false; WorldInfo.Generate(); } } }; configHeightSeed = wrapper.BindFloat(text, "Height variation seed", null, regenerate: true); text = "2. Poles"; configRestrictAshlands = wrapper.Bind(text, "Restrict Ashlands position", value: true, regenerate: true, "If true, restricts Ashlands biome position."); configAshlandsWidthRestriction = wrapper.BindFloat(text, "Ashlands width restriction", 7500f, regenerate: true, "How wide is the Ashlands biome (meters)."); configAshlandsLengthRestriction = wrapper.BindFloat(text, "Ashlands length restriction", 1000f, regenerate: true, "How long/deep is the Ashlands biome (meters)."); configAshlandsGap = wrapper.Bind(text, "Ashlands gap", value: true, regenerate: true, "If true, Ashlands biome has an Ocean gap above it."); configDeepNorthGap = wrapper.Bind(text, "Deep North gap", value: true, regenerate: true, "If true, Deep North biome has an Ocean gap below it."); configRemoveAshlandsWater = wrapper.Bind(text, "Remove Ashlands water", value: false, regenerate: false, "If true, the red water color is completely removed."); configRemoveAshlandsWater.SettingChanged += delegate { WaterColor.Regenerate(); }; configFixWaterColor = wrapper.Bind(text, "Fix water color", value: true, regenerate: false, "If true, fixes the water color to match the current biome."); configFixWaterColor.SettingChanged += delegate { WaterColor.Regenerate(); }; WaterColor.Regenerate(); } } [HarmonyPatch] public static class Patcher { public static WorldGenerator? WG; private static Harmony Harmony; private static Harmony DynamicHarmony; private static float PatchedWorldStretch = 1f; private static float PatchedWaterDepthMultiplier = 1f; private static float PatchedWaterLevel = 30f; private static float PatchedForestMultiplier = 1f; private static float PatchedAltitudeDelta = 0f; private static float PatchedAltitudeMultiplier = 1f; public static bool IsMenu { get { if (WG != null) { return WG.m_world.m_menu; } return true; } } public static void Init(Harmony harmony, Harmony dynamicHarmony) { Harmony = harmony; DynamicHarmony = dynamicHarmony; Patch(); } public static void Patch() { Harmony.UnpatchSelf(); Harmony.PatchAll(); CheckWorldStretch(DynamicHarmony); CheckWaterDepth(DynamicHarmony); CheckForest(DynamicHarmony); CheckAltitude(DynamicHarmony); CreateAshlandsGap.Patch(DynamicHarmony, !Configuration.AshlandsGap); CreateDeepNorthGap.Patch(DynamicHarmony, !Configuration.DeepNorthGap); GetAshlandsHeight.Patch(DynamicHarmony, Configuration.AshlandsWidthRestriction, Configuration.AshlandsLengthRestriction); } [HarmonyPatch(typeof(WorldGenerator), "VersionSetup")] [HarmonyPostfix] [HarmonyPriority(0)] private static void PatchOnLoad(WorldGenerator __instance) { WG = __instance; WorldInfo.Refresh(); } private static void CheckWorldStretch(Harmony harmony) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Expected O, but got Unknown //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Expected O, but got Unknown //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Expected O, but got Unknown float num = (IsMenu ? 1f : WorldInfo.WorldStretch); if (PatchedWorldStretch != num) { PatchedWorldStretch = num; MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetBiomeHeight", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(Stretch), "GetBiomeHeight", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (num != 1f) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetAshlandsOceanGradient", new Type[1] { typeof(Vector3) }, (Type[])null); methodInfo2 = AccessTools.Method(typeof(Stretch), "StretchVector3", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (num != 1f) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } methodInfo = AccessTools.Method(typeof(Minimap), "GetMaskColor", (Type[])null, (Type[])null); methodInfo2 = AccessTools.Method(typeof(Stretch), "GetMaskColor", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (num != 1f) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetBiome", new Type[4] { typeof(float), typeof(float), typeof(float), typeof(bool) }, (Type[])null); methodInfo2 = AccessTools.Method(typeof(Stretch), "GetBiome", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (num != 1f) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } methodInfo = AccessTools.Method(typeof(WorldGenerator), "AddRivers", (Type[])null, (Type[])null); methodInfo2 = AccessTools.Method(typeof(AddRivers), "Prefix", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (num != 1f) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } PatchAshlandsDeepNorthChecks(harmony, num); } } private static void PatchAshlandsDeepNorthChecks(Harmony harmony, float worldStretch) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.Method(typeof(Character), "UpdateLava", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(Stretch), "StretchIsAshlandsTranspiler", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (worldStretch != 1f) { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null); } methodInfo = AccessTools.Method(typeof(EnvMan), "GetBiome", (Type[])null, (Type[])null); methodInfo2 = AccessTools.Method(typeof(Stretch), "StretchIsAshlandsDeepNorthTranspiler", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (worldStretch != 1f) { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null); } methodInfo = AccessTools.Method(typeof(EnvMan), "UpdateEnvironment", (Type[])null, (Type[])null); methodInfo2 = AccessTools.Method(typeof(Stretch), "StretchIsAshlandsDeepNorthTranspiler", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (worldStretch != 1f) { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null); } } private static void CheckWaterDepth(Harmony harmony) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown float num = (IsMenu ? 1f : WorldInfo.WaterDepth); if (PatchedWaterDepthMultiplier != num || WorldInfo.WaterLevel != PatchedWaterLevel) { PatchedWaterDepthMultiplier = num; PatchedWaterLevel = WorldInfo.WaterLevel; MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetBiomeHeight", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(BiomeHeight), "Postfix", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (num != 1f) { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } private static void CheckForest(Harmony harmony) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown float num = (IsMenu ? 1f : WorldInfo.ForestMultiplier); if (PatchedForestMultiplier != num) { PatchedForestMultiplier = num; MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetForestFactor", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(Forest), "Postfix", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (num != 1f) { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } private static void CheckAltitude(Harmony harmony) { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected O, but got Unknown float num = (IsMenu ? 0f : WorldInfo.BaseAltitudeDelta); float num2 = (IsMenu ? 1f : WorldInfo.AltitudeMultiplier); if (PatchedAltitudeDelta != num || PatchedAltitudeMultiplier != num2) { PatchedAltitudeDelta = num; PatchedAltitudeMultiplier = num2; MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetBaseHeight", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(BaseHeight), "Postfix", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (num != 0f || num2 != 1f) { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } } [HarmonyPatch(typeof(Terminal), "InitTerminal")] public class DebugCommands { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__0_0; public static ConsoleEvent <>9__0_1; internal void b__0_0(ConsoleEventArgs args) { WorldInfo.Map(); } internal void b__0_1(ConsoleEventArgs args) { WorldGenerator instance = WorldGenerator.m_instance; if (instance != null) { List values = new List { "Main: " + instance.m_world.m_seedName, "Generator: " + instance.m_world.m_worldGenVersion, "World: " + instance.m_world.m_seed, "Offset X: " + instance.m_offset0, "Offset Y: " + instance.m_offset1, "Height: " + instance.m_offset3, "Meadows: " + instance.m_offset3, "Black forest: " + instance.m_offset2, "Swamp: " + instance.m_offset0, "Plains: " + instance.m_offset1, "Mistlands: " + instance.m_offset4 }; ZLog.Log((object)string.Join("\n", values)); args.Context.AddString(string.Join("\n", values)); } } } private static void Postfix() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown object obj = <>c.<>9__0_0; if (obj == null) { ConsoleEvent val = delegate { WorldInfo.Map(); }; <>c.<>9__0_0 = val; obj = (object)val; } new ConsoleCommand("ew_map", "Refreshes the world map.", (ConsoleEvent)obj, true, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj2 = <>c.<>9__0_1; if (obj2 == null) { ConsoleEvent val2 = delegate(ConsoleEventArgs args) { WorldGenerator instance = WorldGenerator.m_instance; if (instance != null) { List values = new List { "Main: " + instance.m_world.m_seedName, "Generator: " + instance.m_world.m_worldGenVersion, "World: " + instance.m_world.m_seed, "Offset X: " + instance.m_offset0, "Offset Y: " + instance.m_offset1, "Height: " + instance.m_offset3, "Meadows: " + instance.m_offset3, "Black forest: " + instance.m_offset2, "Swamp: " + instance.m_offset0, "Plains: " + instance.m_offset1, "Mistlands: " + instance.m_offset4 }; ZLog.Log((object)string.Join("\n", values)); args.Context.AddString(string.Join("\n", values)); } }; <>c.<>9__0_1 = val2; obj2 = (object)val2; } new ConsoleCommand("ew_seeds", "- Prints different seeds.", (ConsoleEvent)obj2, true, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } [BepInPlugin("expand_world_size", "Expand World Size", "1.31")] [BepInIncompatibility("expand_world")] public class EWS : BaseUnityPlugin { public const string GUID = "expand_world_size"; public const string NAME = "Expand World Size"; public const string VERSION = "1.31"; public static EWS Instance; public static ConfigSync ConfigSync = new ConfigSync("expand_world_size") { DisplayName = "Expand World Size", CurrentVersion = "1.31", ModRequired = true, IsLocked = true }; public static string ConfigName = "expand_world_size.cfg"; public static bool NeedsMigration = File.Exists(Path.Combine(Paths.ConfigPath, "expand_world.cfg")) && !File.Exists(Path.Combine(Paths.ConfigPath, ConfigName)); public void Awake() { //IL_0043: 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_0053: Expected O, but got Unknown //IL_0059: Expected O, but got Unknown Log.Init(((BaseUnityPlugin)this).Logger); Instance = this; Configuration.Init(new ConfigWrapper(((BaseUnityPlugin)this).Config, ConfigSync, InvokeRegenerate, InvokeRegenerateMap)); Harmony val = new Harmony("expand_world_size"); Harmony dynamicHarmony = new Harmony("expand_world_size.dynamic"); Patcher.Init(val, dynamicHarmony); try { SetupWatcher(); } catch (Exception ex) { Log.Error(ex.Message); } } public void Start() { Marketplace.Run(); BetterContinents.Run(); EWD.Run(); } public void InvokeRegenerate() { if (!Patcher.IsMenu) { ((MonoBehaviour)this).CancelInvoke("Regenerate"); ((MonoBehaviour)this).Invoke("Regenerate", 1f); } } public void InvokeRegenerateMap() { if (!Patcher.IsMenu) { ((MonoBehaviour)this).CancelInvoke("RegenerateMap"); ((MonoBehaviour)this).Invoke("RegenerateMap", 1f); } } public void LateUpdate() { if (!Patcher.IsMenu) { WaterColor.Transition(Time.deltaTime); } } public void Regenerate() { WorldInfo.Generate(); } public void RegenerateMap() { WorldInfo.Map(); } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath)) { return; } try { Log.Debug("ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { Log.Error("There was an issue loading your " + ((BaseUnityPlugin)this).Config.ConfigFilePath); Log.Error("Please check your config entries for spelling and format!"); } } } [HarmonyPatch(typeof(ZRpc), "SetLongTimeout")] public class IncreaseTimeout { private static bool Prefix() { ZRpc.m_timeout = 300f; ZLog.Log((object)$"ZRpc timeout set to {ZRpc.m_timeout}s "); return false; } } [HarmonyPatch(typeof(WorldGenerator), "GetForestFactor")] public class Forest { public static float Postfix(float result) { return result /= WorldInfo.ForestMultiplier; } } [HarmonyPatch(typeof(WorldGenerator), "GetBaseHeight")] public class BaseHeight { public static float Postfix(float result) { return WorldInfo.BaseWaterLevel + (result - WorldInfo.BaseWaterLevel) * WorldInfo.AltitudeMultiplier + WorldInfo.BaseAltitudeDelta; } } [HarmonyPatch(typeof(WorldGenerator), "GetBiomeHeight")] public class BiomeHeight { public static float Postfix(float result) { if (!(result > WorldInfo.WaterLevel)) { return (result - WorldInfo.WaterLevel) * WorldInfo.WaterDepth + WorldInfo.WaterLevel; } return result; } } [HarmonyPatch] public class HeightSeed { private static IEnumerable Transpile(IEnumerable instructions) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown if (Patcher.IsMenu) { return instructions; } if (!Configuration.HeightSeed.HasValue) { return instructions; } return Helper.ReplaceSeed(new CodeMatcher(instructions, (ILGenerator)null), "m_offset3", Configuration.HeightSeed.Value).InstructionEnumeration(); } [HarmonyPatch(typeof(WorldGenerator), "GetAshlandsHeight")] [HarmonyTranspiler] private static IEnumerable Ashlands(IEnumerable instructions) { return Transpile(instructions); } [HarmonyPatch(typeof(WorldGenerator), "GetForestHeight")] [HarmonyTranspiler] private static IEnumerable Forest(IEnumerable instructions) { return Transpile(instructions); } [HarmonyPatch(typeof(WorldGenerator), "GetMeadowsHeight")] [HarmonyTranspiler] private static IEnumerable Meadows(IEnumerable instructions) { return Transpile(instructions); } [HarmonyPatch(typeof(WorldGenerator), "GetDeepNorthHeight")] [HarmonyTranspiler] private static IEnumerable DeepNorth(IEnumerable instructions) { return Transpile(instructions); } [HarmonyPatch(typeof(WorldGenerator), "GetPlainsHeight")] [HarmonyTranspiler] private static IEnumerable Plains(IEnumerable instructions) { return Transpile(instructions); } [HarmonyPatch(typeof(WorldGenerator), "GetSnowMountainHeight")] [HarmonyTranspiler] private static IEnumerable Mountain(IEnumerable instructions) { return Transpile(instructions); } [HarmonyPatch(typeof(WorldGenerator), "GetMistlandsHeight")] [HarmonyTranspiler] private static IEnumerable Mistlands(IEnumerable instructions) { return Transpile(instructions); } } [HarmonyPatch(typeof(LoadingIndicator), "SetShowProgress")] public class ModifyLocations { private static readonly Dictionary OriginalQuantities = new Dictionary(); private static readonly Dictionary OriginalMin = new Dictionary(); private static readonly Dictionary OriginalMax = new Dictionary(); private static void Prefix(bool show) { if (!show) { return; } if (Configuration.LocationsMultiplier != 1f) { foreach (ZoneLocation location in ZoneSystem.instance.m_locations) { if (location.m_quantity != 0 && location.m_enable && !(location.m_prefabName == Game.instance.m_StartLocation)) { OriginalQuantities[location] = location.m_quantity; if (Configuration.LocationsMultiplier == 0f) { location.m_quantity = 0; } else { location.m_quantity = Math.Max(1, Mathf.RoundToInt((float)location.m_quantity * Configuration.LocationsMultiplier)); } } } } if (EWD.IsPresent || Configuration.WorldRadius == 10000f) { return; } foreach (ZoneLocation location2 in ZoneSystem.instance.m_locations) { OriginalMin[location2] = location2.m_minDistance; OriginalMax[location2] = location2.m_maxDistance; location2.m_minDistance *= Configuration.WorldRadius / 10000f; location2.m_maxDistance *= Configuration.WorldRadius / 10000f; } } private static void Postfix(bool show) { if (show) { return; } foreach (ZoneLocation location in ZoneSystem.instance.m_locations) { if (OriginalQuantities.TryGetValue(location, out var value)) { location.m_quantity = value; } if (OriginalMin.TryGetValue(location, out var value2)) { location.m_minDistance = value2; } if (OriginalMax.TryGetValue(location, out var value3)) { location.m_maxDistance = value3; } } OriginalQuantities.Clear(); OriginalMin.Clear(); OriginalMax.Clear(); } } [HarmonyPatch(typeof(ZoneSystem), "GetRandomZone")] public class GetRandomZone { private static IEnumerable Transpiler(IEnumerable instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown return Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 10000f, Configuration.WorldRadius).InstructionEnumeration(); } } [HarmonyPatch(typeof(ZoneSystem), "GenerateLocationsTimeSliced", new Type[] { typeof(ZoneLocation), typeof(Stopwatch), typeof(ZPackage) })] [HarmonyPatch(/*Could not decode attribute arguments.*/)] public class GenerateLocations { [HarmonyTranspiler] private static IEnumerable TranspileMoveNext(IEnumerable instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown return Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 10000f, Configuration.WorldRadius).InstructionEnumeration(); } } public class GetAshlandsHeight { private static readonly double DefaultWidthRestriction = 7500.0; private static double PatchedWidthRestriction = DefaultWidthRestriction; private static readonly double DefaultLengthRestriction = 1000.0; private static double PatchedLengthRestriction = DefaultLengthRestriction; public static void Patch(Harmony harmony, double widthRestriction, double lengthRestriction) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown if (PatchedWidthRestriction != widthRestriction || PatchedLengthRestriction != lengthRestriction) { MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetAshlandsHeight", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(GetAshlandsHeight), "Transpiler", (Type[])null, (Type[])null); PatchedWidthRestriction = widthRestriction; PatchedLengthRestriction = lengthRestriction; harmony.Unpatch((MethodBase)methodInfo, methodInfo2); if (PatchedWidthRestriction != DefaultWidthRestriction || PatchedLengthRestriction != DefaultLengthRestriction) { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null); } } } private static IEnumerable Transpiler(IEnumerable instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldc_R8, (object)1000.0, (string)null) }).SetOperandAndAdvance((object)PatchedLengthRestriction).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldc_R8, (object)7500.0, (string)null) }) .SetOperandAndAdvance((object)PatchedWidthRestriction) .InstructionEnumeration(); } } public class CreateAshlandsGap { private static bool IsPatched; public static void Patch(Harmony harmony, bool doPatch) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown if (IsPatched != doPatch) { MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "CreateAshlandsGap", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(CreateAshlandsGap), "DisableGap", (Type[])null, (Type[])null); IsPatched = doPatch; if (doPatch) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } else { harmony.Unpatch((MethodBase)methodInfo, methodInfo2); } } } private static bool DisableGap(ref double __result) { __result = 1.0; return false; } } public class CreateDeepNorthGap { private static bool IsPatched; public static void Patch(Harmony harmony, bool doPatch) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown if (IsPatched != doPatch) { MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "CreateDeepNorthGap", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(CreateAshlandsGap), "DisableGap", (Type[])null, (Type[])null); IsPatched = doPatch; if (doPatch) { harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } else { harmony.Unpatch((MethodBase)methodInfo, methodInfo2); } } } private static bool DisableGap(ref double __result) { __result = 1.0; return false; } } [HarmonyPatch(typeof(WorldGenerator), "FindLakes")] public class FindLakes { private static IEnumerable Transpiler(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown if (Patcher.IsMenu) { return instructions; } return Helper.Replace(Helper.Replace(Stretch.Replace(Stretch.Replace(Helper.Replace(Helper.Replace(Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), -10000f, 0f - Configuration.WorldRadius), -10000f, 0f - Configuration.WorldRadius), 10000f, Configuration.WorldRadius), OpCodes.Ldloc_3), OpCodes.Ldloc_2), 10000f, Configuration.WorldRadius), 10000f, Configuration.WorldRadius).InstructionEnumeration(); } } [HarmonyPatch(typeof(WorldGenerator), "IsRiverAllowed")] public class IsRiverAllowed { private static IEnumerable Transpiler(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown if (Patcher.IsMenu) { return instructions; } return Stretch.Replace(Stretch.Replace(new CodeMatcher(instructions, (ILGenerator)null), OpCodes.Ldfld), OpCodes.Ldfld).InstructionEnumeration(); } } [HarmonyPatch(typeof(WorldGenerator), "FindStreamStartPoint")] public class FindStreamStartPoint { private static IEnumerable Transpiler(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown if (Patcher.IsMenu) { return instructions; } return Helper.Replace(Helper.Replace(Helper.Replace(Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), -10000f, 0f - Configuration.WorldRadius), 10000f, Configuration.WorldRadius), -10000f, 0f - Configuration.WorldRadius), 10000f, Configuration.WorldRadius).InstructionEnumeration(); } } public class AddRivers { public static void Prefix(ref float wx, ref float wy) { wx *= Configuration.WorldStretch; wy *= Configuration.WorldStretch; } } [HarmonyPatch] public class Stretch { public static IEnumerable StretchIsAshlandsTranspiler(IEnumerable instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Expected O, but got Unknown //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(WorldGenerator), "IsAshlands", (Type[])null, (Type[])null), (string)null) }).MatchBack(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(Vector3), "z"), (string)null) }).Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldc_R4, (object)Configuration.WorldStretch) }) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Div, (object)null) }) .MatchBack(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(Vector3), "x"), (string)null) }) .Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldc_R4, (object)Configuration.WorldStretch) }) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Div, (object)null) }) .InstructionEnumeration(); } public static IEnumerable StretchIsAshlandsDeepNorthTranspiler(IEnumerable instructions) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Expected O, but got Unknown //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Expected O, but got Unknown //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Expected O, but got Unknown //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Expected O, but got Unknown //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Expected O, but got Unknown //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Expected O, but got Unknown //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Expected O, but got Unknown //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Expected O, but got Unknown return new CodeMatcher(instructions, (ILGenerator)null).MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(WorldGenerator), "IsAshlands", (Type[])null, (Type[])null), (string)null) }).MatchBack(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(Vector3), "z"), (string)null) }).Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldc_R4, (object)Configuration.WorldStretch) }) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Div, (object)null) }) .MatchBack(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(Vector3), "x"), (string)null) }) .Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldc_R4, (object)Configuration.WorldStretch) }) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Div, (object)null) }) .MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Call, (object)AccessTools.Method(typeof(WorldGenerator), "IsDeepnorth", (Type[])null, (Type[])null), (string)null) }) .MatchBack(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(Vector3), "z"), (string)null) }) .Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldc_R4, (object)Configuration.WorldStretch) }) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Div, (object)null) }) .MatchBack(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(Vector3), "x"), (string)null) }) .Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldc_R4, (object)Configuration.WorldStretch) }) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Div, (object)null) }) .InstructionEnumeration(); } [HarmonyPriority(500)] public static void StretchVector3(ref Vector3 pos) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) Vector3 val = pos; val.x = pos.x / Configuration.WorldStretch; val.z = pos.z / Configuration.WorldStretch; pos = val; } [HarmonyPriority(500)] public static void GetMaskColor(ref float wx, ref float wy) { wx /= Configuration.WorldStretch; wy /= Configuration.WorldStretch; } [HarmonyPriority(500)] public static void GetBiomeHeight(ref float wx, ref float wy) { wx /= Configuration.WorldStretch; wy /= Configuration.WorldStretch; } [HarmonyPriority(500)] public static void GetBiome(ref float wx, ref float wy) { wx /= Configuration.WorldStretch; wy /= Configuration.WorldStretch; } public static CodeMatcher Replace(CodeMatcher matcher, OpCode code) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown if (Configuration.WorldStretch == 1f) { return matcher; } return matcher.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)code, (object)null, (string)null) }).Advance(1).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldc_R4, (object)Configuration.WorldStretch) }) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Div, (object)null) }); } public static CodeMatcher ReplaceBiome(CodeMatcher matcher) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Expected O, but got Unknown //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Expected O, but got Unknown if (Configuration.BiomeStretch == 1f) { return matcher; } return matcher.MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Ldarg_1, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Conv_R8, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Add, (object)null, (string)null) }).Advance(1).InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldc_R4, (object)Configuration.BiomeStretch) }) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Div, (object)null) }) .MatchForward(false, (CodeMatch[])(object)new CodeMatch[3] { new CodeMatch((OpCode?)OpCodes.Ldarg_2, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Conv_R8, (object)null, (string)null), new CodeMatch((OpCode?)OpCodes.Add, (object)null, (string)null) }) .Advance(1) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Ldc_R4, (object)Configuration.BiomeStretch) }) .InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { new CodeInstruction(OpCodes.Div, (object)null) }); } [HarmonyPatch(typeof(WorldGenerator), "GetBiome", new Type[] { typeof(float), typeof(float), typeof(float), typeof(bool) })] private static IEnumerable Transpiler(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown if (Patcher.IsMenu) { return instructions; } CodeMatcher val = new CodeMatcher(ReplaceBiome(ReplaceBiome(ReplaceBiome(ReplaceBiome(new CodeMatcher(instructions, (ILGenerator)null))))).InstructionEnumeration(), (ILGenerator)null); AccessTools.Field(typeof(WorldGenerator), "ashlandsMinDistance").SetValue(null, 1.2f * Configuration.StrechedWorldRadius); AccessTools.Field(typeof(WorldGenerator), "ashlandsYOffset").SetValue(null, -0.4f * Configuration.StrechedWorldRadius); return Helper.Replace(Helper.Replace(Helper.Replace(Helper.Replace(Helper.Replace(Helper.Replace(Helper.Replace(Helper.Replace(val, 2000f, 0.2f * Configuration.StrechedWorldRadius), 6000.0, 0.6 * (double)Configuration.StrechedWorldRadius), 10000f, Configuration.StrechedWorldRadius), 3000.0, 0.3 * (double)Configuration.StrechedWorldRadius), 8000f, 0.8f * Configuration.StrechedWorldRadius), 600.0, 0.06 * (double)Configuration.StrechedWorldRadius), 6000f, 0.6f * Configuration.StrechedWorldRadius), 5000.0, 0.5 * (double)Configuration.StrechedWorldRadius).InstructionEnumeration(); } [HarmonyPatch(typeof(WorldGenerator), "IsDeepnorth")] [HarmonyTranspiler] private static IEnumerable TranspilerIsDeepnorth(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown if (Patcher.IsMenu) { return instructions; } return Helper.Replace(Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 4000.0, 0.4 * (double)Configuration.StrechedWorldRadius), 12000.0, 1.2 * (double)Configuration.StrechedWorldRadius).InstructionEnumeration(); } [HarmonyPatch(typeof(WorldGenerator), "CreateAshlandsGap")] [HarmonyTranspiler] private static IEnumerable TranspilerCreateAshlandsGap(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown if (Patcher.IsMenu) { return instructions; } return Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 400.0, 0.04 * (double)Configuration.StrechedWorldRadius).InstructionEnumeration(); } [HarmonyPatch(typeof(WorldGenerator), "CreateDeepNorthGap")] [HarmonyTranspiler] private static IEnumerable TranspilerCreateDeepNorthGap(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown if (Patcher.IsMenu) { return instructions; } return Helper.Replace(Helper.Replace(Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 4000f, 0.4f * Configuration.StrechedWorldRadius), 12000.0, 1.2f * Configuration.StrechedWorldRadius), 400.0, 0.04 * (double)Configuration.StrechedWorldRadius).InstructionEnumeration(); } [HarmonyPatch(typeof(WorldGenerator), "GetBiomeHeight")] [HarmonyTranspiler] private static IEnumerable TranspilerGetBiomeHeight(IEnumerable instructions) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown if (BetterContinents.IsEnabled()) { return instructions; } if (Patcher.IsMenu) { return instructions; } return Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 10500f, Configuration.StrechedWorldTotalRadius).InstructionEnumeration(); } } [HarmonyPatch(typeof(Player), "AddKnownBiome")] public class StartColorTransition { public static void Postfix(Biome biome) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 WaterColor.StartTransition((int)biome == 32); } } [HarmonyPatch(typeof(Player), "OnSpawned")] public class ResetColorTransition { public static void Postfix() { WaterColor.StopTransition(); } } public class WaterColor { private static float TransitionProgress; private static bool Transitioning; public static bool? TargetAshlands; private static bool InitDone; private static Color WaterSurface; private static Color AshlandsSurface; private static Color WaterTop; private static Color AshlandsTop; private static Color WaterBottom; private static Color AshlandsBottom; private static Color WaterShallow; private static Color AshlandsShallow; public static void Transition(float time) { if (!Transitioning) { return; } if (TargetAshlands == true) { TransitionProgress += 0.1f * time; if (TransitionProgress >= 1f) { StopTransition(); } } else if (TargetAshlands == false) { TransitionProgress -= 0.1f * time; if (TransitionProgress <= 0f) { StopTransition(); } } UpdateTransitions(); } public static void StartTransition(bool toAshlands) { if (Configuration.FixWaterColor && TargetAshlands != toAshlands) { TargetAshlands = toAshlands; Transitioning = true; } } public static void StopTransition() { if (Transitioning) { Transitioning = false; TransitionProgress = ((TargetAshlands == true) ? 1f : 0f); } } private static void UpdateTransitions() { foreach (WaterVolume instance2 in WaterVolume.Instances) { UpdateTransition(((Renderer)instance2.m_waterSurface).sharedMaterial); } EnvMan instance = EnvMan.instance; Transform val = ((instance != null) ? ((Component)instance).transform.Find("WaterPlane").Find("watersurface") : null); if ((Object)(object)val != (Object)null) { UpdateTransition(((Renderer)((Component)val).GetComponent()).sharedMaterial); } } private static void UpdateTransition(Material mat) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_0045: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) InitColors(mat); Color surface = Color.Lerp(WaterSurface, AshlandsSurface, TransitionProgress); Color top = Color.Lerp(WaterTop, AshlandsTop, TransitionProgress); Color bottom = Color.Lerp(WaterBottom, AshlandsBottom, TransitionProgress); Color shallow = Color.Lerp(WaterShallow, AshlandsShallow, TransitionProgress); UpdateColors(mat, surface, top, bottom, shallow); } public static void Regenerate() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 if (Object.op_Implicit((Object)(object)Player.m_localPlayer)) { StartTransition((int)Player.m_localPlayer.GetCurrentBiome() == 32); } foreach (WaterVolume instance2 in WaterVolume.Instances) { FixColors(((Renderer)instance2.m_waterSurface).sharedMaterial); } EnvMan instance = EnvMan.instance; Transform val = ((instance != null) ? ((Component)instance).transform.Find("WaterPlane").Find("watersurface") : null); if ((Object)(object)val != (Object)null) { FixColors(((Renderer)((Component)val).GetComponent()).sharedMaterial); } } public static void FixColors(Material mat) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0086: 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_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: 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_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) InitColors(mat); if (Configuration.FixWaterColor) { UpdateTransition(mat); return; } if (Configuration.RemoveAshlandsWater) { StopTransition(); UpdateColors(mat, WaterSurface, WaterTop, WaterBottom, WaterShallow); return; } StopTransition(); mat.SetColor("_SurfaceColor", WaterSurface); mat.SetColor("_AshlandsSurfaceColor", AshlandsSurface); mat.SetColor("_ColorTop", WaterTop); mat.SetColor("_AshlandsColorTop", AshlandsTop); mat.SetColor("_ColorBottom", WaterBottom); mat.SetColor("_AshlandsColorBottom", AshlandsBottom); mat.SetColor("_ColorBottomShallow", WaterShallow); mat.SetColor("_AshlandsColorBottomShallow", AshlandsShallow); } private static void UpdateColors(Material mat, Color surface, Color top, Color bottom, Color shallow) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001e: 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_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) mat.SetColor("_SurfaceColor", surface); mat.SetColor("_AshlandsSurfaceColor", surface); mat.SetColor("_ColorTop", top); mat.SetColor("_AshlandsColorTop", top); mat.SetColor("_ColorBottom", bottom); mat.SetColor("_AshlandsColorBottom", bottom); mat.SetColor("_ColorBottomShallow", shallow); mat.SetColor("_AshlandsColorBottomShallow", shallow); } private static void InitColors(Material mat) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0084: 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) if (!InitDone) { InitDone = true; WaterSurface = mat.GetColor("_SurfaceColor"); AshlandsSurface = mat.GetColor("_AshlandsSurfaceColor"); WaterTop = mat.GetColor("_ColorTop"); AshlandsTop = mat.GetColor("_AshlandsColorTop"); WaterBottom = mat.GetColor("_ColorBottom"); AshlandsBottom = mat.GetColor("_AshlandsColorBottom"); WaterShallow = mat.GetColor("_ColorBottomShallow"); AshlandsShallow = mat.GetColor("_AshlandsColorBottomShallow"); } } } public class WorldSizeHelper { public static IEnumerable EdgeCheck(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown if (BetterContinents.IsEnabled()) { return instructions; } return Helper.Replace(Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 10420f, Configuration.WorldTotalRadius - 80f), 10500f, Configuration.WorldTotalRadius).InstructionEnumeration(); } } [HarmonyPatch(typeof(Ship), "ApplyEdgeForce")] public class ApplyEdgeForce { private static IEnumerable Transpiler(IEnumerable instructions) { return WorldSizeHelper.EdgeCheck(instructions); } } [HarmonyPatch(typeof(Player), "EdgeOfWorldKill")] public class EdgeOfWorldKill { private static IEnumerable Transpiler(IEnumerable instructions) { return WorldSizeHelper.EdgeCheck(instructions); } private static bool Prefix(Player __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return ((Component)__instance).transform.position.y < 4000f; } } [HarmonyPatch(typeof(WorldGenerator), "GetAshlandsHeight")] public class GetAshlandsHeightSize { private static IEnumerable Transpiler(IEnumerable instructions) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown if (BetterContinents.IsEnabled()) { return instructions; } if (Patcher.IsMenu) { return instructions; } return Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 10150.0, (Configuration.WorldTotalRadius + 150f) / Configuration.WorldStretch).InstructionEnumeration(); } } [HarmonyPatch(typeof(WorldGenerator), "GetBaseHeight")] public class GetBaseHeight { private static IEnumerable Transpiler(IEnumerable instructions) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown if (BetterContinents.IsEnabled()) { return instructions; } if (Patcher.IsMenu) { return instructions; } CodeMatcher val = new CodeMatcher(instructions, (ILGenerator)null); val = val.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(WorldGenerator), "m_offset1"), (string)null) }); if (Configuration.OffsetX.HasValue) { val = Helper.ReplaceSeed(val, "m_offset0", Configuration.OffsetX.Value); } if (Configuration.OffsetY.HasValue) { val = Helper.ReplaceSeed(val, "m_offset1", Configuration.OffsetY.Value); } val = Helper.Replace(val, 10000f, Configuration.StrechedWorldRadius); val = Helper.Replace(val, 10000f, Configuration.StrechedWorldRadius); val = Helper.Replace(val, 10500f, Configuration.StrechedWorldTotalRadius); val = Helper.Replace(val, 10490f, (Configuration.WorldTotalRadius - 10f) / Configuration.WorldStretch); val = Helper.Replace(val, 10500f, Configuration.StrechedWorldTotalRadius); return val.InstructionEnumeration(); } } [HarmonyPatch(typeof(WaterVolume), "SetupMaterial")] public class SetupMaterial { public static void Refresh() { foreach (WaterVolume instance in WaterVolume.Instances) { ((Renderer)instance.m_waterSurface).sharedMaterial.SetFloat("_WaterEdge", Configuration.WorldTotalRadius); } } public static void Prefix(WaterVolume __instance) { //IL_0020: 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_0067: 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) ((Renderer)__instance.m_waterSurface).sharedMaterial.SetFloat("_WaterEdge", Configuration.WorldTotalRadius); if (((Component)__instance).transform.position.y < 30.001f && ((Component)__instance).transform.position.y > 29.999f) { Collider collider = __instance.m_collider; BoxCollider val = (BoxCollider)(object)((collider is BoxCollider) ? collider : null); if (val != null) { val.center = new Vector3(0f, -100f, 0f); val.size = new Vector3(64f, 220f, 64f); } } WaterColor.FixColors(((Renderer)__instance.m_waterSurface).sharedMaterial); } } [HarmonyPatch(typeof(EnvMan), "Awake")] public class ScaleGlobalWaterSurface { public static void Refresh(EnvMan obj) { Transform val = ((Component)obj).transform.Find("WaterPlane").Find("watersurface"); if (Object.op_Implicit((Object)(object)val)) { ((Renderer)((Component)val).GetComponent()).sharedMaterial.SetFloat("_WaterEdge", Configuration.WorldTotalRadius); } } public static void Postfix(EnvMan __instance) { Refresh(__instance); } } [HarmonyPatch(typeof(EnvMan), "UpdateWind")] public class UpdateWind { private static IEnumerable Transpiler(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (BetterContinents.IsEnabled()) { return instructions; } return Helper.Replace(Helper.Replace(Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 10500f, Configuration.WorldRadius).SetOpcodeAndAdvance(OpCodes.Nop).SetOpcodeAndAdvance(OpCodes.Nop) .SetOpcodeAndAdvance(OpCodes.Nop), 10500f, Configuration.WorldRadius).SetOpcodeAndAdvance(OpCodes.Nop).SetOpcodeAndAdvance(OpCodes.Nop) .SetOpcodeAndAdvance(OpCodes.Nop), 10500f, Configuration.WorldTotalRadius).InstructionEnumeration(); } } [HarmonyPatch(typeof(WaterVolume), "GetWaterSurface")] public class GetWaterSurface { private static IEnumerable Transpiler(IEnumerable instructions) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (BetterContinents.IsEnabled()) { return instructions; } return Helper.Replace(new CodeMatcher(instructions, (ILGenerator)null), 10500f, Configuration.WorldTotalRadius).InstructionEnumeration(); } } [HarmonyPatch(typeof(WorldGenerator), "Pregenerate")] [HarmonyPriority(500)] public class Pregenerate { private static void Prefix(WorldGenerator __instance) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) __instance.m_riverCacheLock.EnterWriteLock(); __instance.m_riverPoints = new Dictionary(); __instance.m_rivers = new List(); __instance.m_streams = new List(); __instance.m_lakes = new List(); __instance.m_cachedRiverGrid = new Vector2i(-999999, -999999); __instance.m_cachedRiverPoints = Array.Empty(); __instance.m_riverCacheLock.ExitWriteLock(); } } [HarmonyPatch(typeof(Minimap), "TryLoadMinimapTextureData")] public class PatchTryLoadMinimapTextureData { private static bool Prefix(Minimap __instance, ref bool __result) { __result = TryLoadMinimapTextureData(__instance); return false; } private static bool TryLoadMinimapTextureData(Minimap obj) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown if (string.IsNullOrEmpty(obj.m_forestMaskTexturePath) || !File.Exists(obj.m_forestMaskTexturePath) || !File.Exists(obj.m_mapTexturePath) || !File.Exists(obj.m_heightTexturePath) || 37 != ZNet.World.m_worldVersion) { return false; } Stopwatch stopwatch = Stopwatch.StartNew(); Texture2D val = new Texture2D(((Texture)obj.m_forestMaskTexture).width, ((Texture)obj.m_forestMaskTexture).height, (TextureFormat)5, false); if (!ImageConversion.LoadImage(val, File.ReadAllBytes(obj.m_forestMaskTexturePath))) { return false; } if (((Texture)obj.m_forestMaskTexture).width != ((Texture)val).width || ((Texture)obj.m_forestMaskTexture).height != ((Texture)val).height) { return false; } obj.m_forestMaskTexture.SetPixels(val.GetPixels()); obj.m_forestMaskTexture.Apply(); if (!ImageConversion.LoadImage(val, File.ReadAllBytes(obj.m_mapTexturePath))) { return false; } if (((Texture)obj.m_mapTexture).width != ((Texture)val).width || ((Texture)obj.m_mapTexture).height != ((Texture)val).height) { return false; } obj.m_mapTexture.SetPixels(val.GetPixels()); obj.m_mapTexture.Apply(); if (!ImageConversion.LoadImage(val, File.ReadAllBytes(obj.m_heightTexturePath))) { return false; } if (((Texture)obj.m_heightTexture).width != ((Texture)val).width || ((Texture)obj.m_heightTexture).height != ((Texture)val).height) { return false; } Color[] pixels = val.GetPixels(); for (int i = 0; i < obj.m_textureSize; i++) { for (int j = 0; j < obj.m_textureSize; j++) { int num = i * obj.m_textureSize + j; int num2 = (int)(pixels[num].r * 255f); int num3 = (int)(pixels[num].g * 255f); int num4 = (num2 << 8) + num3; float num5 = 127.5f; pixels[num].r = (float)num4 / num5; } } obj.m_heightTexture.SetPixels(pixels); obj.m_heightTexture.Apply(); ZLog.Log((object)("Loading minimap textures done [" + stopwatch.ElapsedMilliseconds + "ms]")); return true; } } [HarmonyPatch(typeof(Minimap), "GenerateWorldMap")] public class MapGeneration { private static bool DoFakeGenerate; private static CancellationTokenSource? CTS; public static bool Generating => CTS != null; private static bool Prefix(Minimap __instance) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType == 4) { return true; } if (DoFakeGenerate) { DoFakeGenerate = false; return false; } if (BetterContinents.IsEnabled()) { Log.Info("Better Continents enabled, skipping map generation."); return true; } if (LPACompatibility.IsEnabled()) { Log.Info("Location Placement Accelerator detected, skipping map generation."); return true; } ((MonoBehaviour)Game.instance).StartCoroutine(Coroutine(__instance)); return false; } public static void Cancel() { if (CTS != null) { Log.Info("Cancelling previous map generation."); CTS.Cancel(); CTS = null; } } public static void UpdateTextureSize(Minimap map, int textureSize) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_0081: 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_0092: Expected O, but got Unknown if (map.m_textureSize != textureSize) { map.m_textureSize = textureSize; map.m_mapTexture = new Texture2D(map.m_textureSize, map.m_textureSize, (TextureFormat)3, false) { wrapMode = (TextureWrapMode)1 }; map.m_forestMaskTexture = new Texture2D(map.m_textureSize, map.m_textureSize, (TextureFormat)4, false) { wrapMode = (TextureWrapMode)1 }; map.m_heightTexture = new Texture2D(map.m_textureSize, map.m_textureSize, (TextureFormat)18, false) { wrapMode = (TextureWrapMode)1 }; map.m_fogTexture = new Texture2D(map.m_textureSize, map.m_textureSize, (TextureFormat)4, false) { wrapMode = (TextureWrapMode)1 }; map.m_explored = new bool[map.m_textureSize * map.m_textureSize]; map.m_exploredOthers = new bool[map.m_textureSize * map.m_textureSize]; ((Graphic)map.m_mapImageLarge).material.SetTexture("_MainTex", (Texture)(object)map.m_mapTexture); ((Graphic)map.m_mapImageLarge).material.SetTexture("_MaskTex", (Texture)(object)map.m_forestMaskTexture); ((Graphic)map.m_mapImageLarge).material.SetTexture("_HeightTex", (Texture)(object)map.m_heightTexture); ((Graphic)map.m_mapImageLarge).material.SetTexture("_FogTex", (Texture)(object)map.m_fogTexture); ((Graphic)map.m_mapImageSmall).material.SetTexture("_MainTex", (Texture)(object)map.m_mapTexture); ((Graphic)map.m_mapImageSmall).material.SetTexture("_MaskTex", (Texture)(object)map.m_forestMaskTexture); ((Graphic)map.m_mapImageSmall).material.SetTexture("_HeightTex", (Texture)(object)map.m_heightTexture); ((Graphic)map.m_mapImageSmall).material.SetTexture("_FogTex", (Texture)(object)map.m_fogTexture); map.Reset(); } } private static IEnumerator Coroutine(Minimap map) { Cancel(); Log.Info("Starting map generation."); Stopwatch stopwatch = Stopwatch.StartNew(); Minimap.DeleteMapTextureData(ZNet.World.m_name); int num = map.m_textureSize * map.m_textureSize; Color32[] mapTexture = (Color32[])(object)new Color32[num]; Color32[] forestMaskTexture = (Color32[])(object)new Color32[num]; Color[] heightTexture = (Color[])(object)new Color[num]; Color32[] cachedTexture = (Color32[])(object)new Color32[num]; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; while (Marketplace.IsLoading()) { yield return null; } Task task = Generate(map, mapTexture, forestMaskTexture, heightTexture, cachedTexture, ct); CTS = cts; while (!task.IsCompleted) { yield return null; } if (task.IsFaulted) { Log.Error($"Map generation failed!\n{task.Exception}"); } else if (!ct.IsCancellationRequested) { map.m_mapTexture.SetPixels32(mapTexture); yield return null; map.m_mapTexture.Apply(); yield return null; map.m_forestMaskTexture.SetPixels32(forestMaskTexture); yield return null; map.m_forestMaskTexture.Apply(); yield return null; map.m_heightTexture.SetPixels(heightTexture); yield return null; map.m_heightTexture.Apply(); yield return null; DoFakeGenerate = true; map.GenerateWorldMap(); Texture2D val = new Texture2D(map.m_textureSize, map.m_textureSize); val.SetPixels32(cachedTexture); val.Apply(); int num2 = Math.Max(1, Environment.ProcessorCount - 2); Log.Info($"Map generation finished ({stopwatch.Elapsed.TotalSeconds:F1}s, parallel, {num2} workers)."); map.SaveMapTextureDataToDisk(map.m_forestMaskTexture, map.m_mapTexture, val); } stopwatch.Stop(); cts.Dispose(); if (CTS == cts) { CTS = null; } } private static async Task Generate(Minimap map, Color32[] mapTexture, Color32[] forestMaskTexture, Color[] heightTexture, Color32[] cachedtexture, CancellationToken ct) { await Task.Run(delegate { WorldGenerator wg = WorldGenerator.m_instance; int textureSize = map.m_textureSize; int halfTextureSize = textureSize / 2; float pixelSize = map.m_pixelSize; float halfPixelSize = pixelSize / 2f; float half = 127.5f; int maxDegreeOfParallelism = Math.Max(1, Environment.ProcessorCount - 2); ParallelOptions parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism, CancellationToken = ct }; try { Parallel.For(0, textureSize, parallelOptions, delegate(int i) { //IL_0045: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: 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_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: 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_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) Color val = default(Color); for (int j = 0; j < textureSize; j++) { float num = (float)(j - halfTextureSize) * pixelSize + halfPixelSize; float num2 = (float)(i - halfTextureSize) * pixelSize + halfPixelSize; Biome biome = wg.GetBiome(num, num2, 0.02f, false); float biomeHeight = wg.GetBiomeHeight(biome, num, num2, ref val, false); mapTexture[i * textureSize + j] = Color32.op_Implicit(map.GetPixelColor(biome)); forestMaskTexture[i * textureSize + j] = Color32.op_Implicit(map.GetMaskColor(num, num2, biomeHeight, biome)); heightTexture[i * textureSize + j] = new Color(biomeHeight, 0f, 0f); int num3 = Mathf.Clamp((int)(biomeHeight * half), 0, 65025); byte b = (byte)(num3 >> 8); byte b2 = (byte)(num3 & 0xFF); cachedtexture[i * textureSize + j] = new Color32(b, b2, (byte)0, byte.MaxValue); } }); } catch (OperationCanceledException) { } }).ConfigureAwait(continueOnCapturedContext: false); } } [HarmonyPatch(typeof(Game), "Logout")] public class CancelOnLogout { private static void Prefix() { MapGeneration.Cancel(); } } public static class Helper { public static CodeMatcher Replace(CodeMatcher instructions, double value, double newValue) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown instructions.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldc_R8, (object)value, (string)null) }); if (instructions.IsInvalid) { return instructions; } return instructions.SetOperandAndAdvance((object)newValue); } public static CodeMatcher Replace(CodeMatcher instructions, float value, float newValue) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown instructions.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldc_R4, (object)value, (string)null) }); if (instructions.IsInvalid) { return instructions; } return instructions.SetOperandAndAdvance((object)newValue); } public static CodeMatcher ReplaceSeed(CodeMatcher instructions, string name, float value) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown instructions.MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch((OpCode?)OpCodes.Ldfld, (object)AccessTools.Field(typeof(WorldGenerator), name), (string)null) }); if (instructions.IsInvalid) { return instructions; } return instructions.Advance(-1).SetAndAdvance(OpCodes.Ldc_R4, (object)value).RemoveInstruction(); } public static float HeightToBaseHeight(float altitude) { return altitude / 200f; } public static bool IsServer() { if (Object.op_Implicit((Object)(object)ZNet.instance)) { return ZNet.instance.IsServer(); } return false; } public static bool IsClient() { return !IsServer(); } } [HarmonyPatch(typeof(Minimap), "Awake")] public class MinimapAwake { public static float OriginalPixelSize; public static int OriginalTextureSize; public static float OriginalMaxZoom; public static void Postfix(Minimap __instance) { OriginalTextureSize = __instance.m_textureSize; OriginalMaxZoom = __instance.m_maxZoom; OriginalPixelSize = __instance.m_pixelSize; Refresh(__instance); } public static bool Refresh(Minimap instance) { int num = (int)((float)OriginalTextureSize * Configuration.MapSize); float num2 = OriginalMaxZoom * Mathf.Max(1f, Configuration.MapSize); float num3 = CalculatePixelSize(); if (instance.m_textureSize == num && instance.m_maxZoom == num2 && instance.m_pixelSize == num3) { return false; } MapGeneration.UpdateTextureSize(Minimap.instance, num); instance.m_maxZoom = num2; instance.m_pixelSize = num3; return true; } private static float CalculatePixelSize() { if (Configuration.MapPixelSize != 0f) { return OriginalPixelSize * Configuration.MapPixelSize; } float num = Configuration.WorldTotalRadius / 10500f; return OriginalPixelSize * num / Configuration.MapSize; } } [HarmonyPatch(typeof(Minimap), "SetMapData")] public class InitializeWhenDimensionsChange { public static bool Prefix(Minimap __instance, byte[] data) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown ZPackage val = new ZPackage(data); if (val.ReadInt() >= 7) { val = val.ReadCompressedPackage(); } int num = val.ReadInt(); if (__instance.m_textureSize == num) { return true; } __instance.Reset(); __instance.m_fogTexture.Apply(); return false; } } [HarmonyPatch(typeof(Minimap), "Awake")] public class Minimap_Alignment { private static void Postfix(Minimap __instance) { __instance.m_biomeNameSmall.alignment = (TextAlignmentOptions)260; __instance.m_biomeNameLarge.alignment = (TextAlignmentOptions)260; } } [HarmonyPatch(typeof(Minimap), "UpdateBiome")] public class Minimap_ShowLoading { private static string PreviousSmallText = ""; private static string PreviousLargeText = ""; private static void AddText(TMP_Text input, string text) { if (!input.text.Contains(text)) { input.text += text; } } private static void CleanUp(TMP_Text input, string text) { if (!(text == "") && input.text.Contains(text)) { input.text = input.text.Replace(text, ""); } } private static string GetText() { return "\nLoading.."; } private static void Postfix(Minimap __instance) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Invalid comparison between Unknown and I4 //IL_0080: Invalid comparison between Unknown and I4 MapMode mode = __instance.m_mode; if (PreviousSmallText != "") { CleanUp(__instance.m_biomeNameSmall, PreviousSmallText); PreviousSmallText = ""; } if (PreviousLargeText != "") { CleanUp(__instance.m_biomeNameLarge, PreviousLargeText); PreviousLargeText = ""; } if ((int)mode == 1 && MapGeneration.Generating) { string text = GetText(); AddText(__instance.m_biomeNameSmall, text); PreviousSmallText = text; } if ((int)mode == 2 && MapGeneration.Generating) { string text2 = GetText(); AddText(__instance.m_biomeNameLarge, text2); PreviousLargeText = text2; } } } } namespace ServerSync { [PublicAPI] public abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] public class SyncedConfigEntry(ConfigEntry sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } internal abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] internal sealed class CustomSyncedValue : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] public class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", (Action)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary configValues = new Dictionary(); public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List entries = new List(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } public static SyncedConfigEntry? ConfigData(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable? configs = null, IEnumerable? customValues = null, IEnumerable? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."); } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: 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_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy, string>((KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } }