Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of SizeScaling v1.1.1
SizeScaling.dll
Decompiled 4 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using DunGen; using HarmonyLib; using Unity.Collections; using Unity.Netcode; using UnityEngine; [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("SizeScaling")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.1.1")] [assembly: AssemblyProduct("SizeScaling")] [assembly: AssemblyTitle("SizeScaling")] [assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")] [assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")] [assembly: AssemblyVersion("1.0.0.0")] namespace SizeScaling; internal enum Skip { None, NotReady, NotHost, Disabled, Company, NoSpawns, Challenge, ExcludedMoon, ExcludedInterior } internal static class Day { private static bool _computed; private static int _levelId = int.MinValue; private static int _seed; internal static Skip SkipReason = Skip.NotReady; internal static string Moon = ""; internal static string Interior = ""; internal static float Size = float.NaN; internal static float ScaleSize = float.NaN; internal static float MScrap = 1f; internal static float MValue = 1f; internal static float MInside = 1f; internal static float MOutside = 1f; internal static float MTraps = 1f; internal static float MRate = 1f; internal static bool Rush; internal static bool RateActive; internal static string Note = ""; internal static float LllRaw = float.NaN; internal static float LllFinal = float.NaN; internal static bool SizeChanged; private static string _sizeLogKey; private static bool _sizeWarned; private static bool _finished; internal static bool ChatShown; private static readonly FieldRef<RoundManager, int> RushIndexRef = MakeRushRef(); internal static bool Eligible { get { if (_computed) { return SkipReason == Skip.None; } return false; } } private static FieldRef<RoundManager, int> MakeRushRef() { try { return AccessTools.FieldRefAccess<RoundManager, int>("enemyRushIndex"); } catch { return null; } } internal static bool IsHost() { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton != (Object)null) { return singleton.IsServer; } return false; } internal static bool RushNow(RoundManager rm) { if ((Object)(object)rm == (Object)null || RushIndexRef == null) { return false; } try { return RushIndexRef.Invoke(rm) != -1; } catch { return false; } } internal static void Reset() { _computed = false; _levelId = int.MinValue; SkipReason = Skip.NotReady; Moon = (Interior = (Note = "")); Size = (ScaleSize = float.NaN); MScrap = (MValue = (MInside = (MOutside = (MTraps = (MRate = 1f))))); Rush = false; RateActive = false; LllRaw = (LllFinal = float.NaN); SizeChanged = false; _sizeLogKey = null; _sizeWarned = false; _finished = false; ChatShown = false; } internal static Skip Check(out SelectableLevel level, out string moon, out string interior) { moon = (interior = ""); level = null; if (!Cfg.Enabled.Value) { return Skip.Disabled; } if (!IsHost()) { return Skip.NotHost; } RoundManager instance = RoundManager.Instance; StartOfRound instance2 = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || (Object)(object)instance.currentLevel == (Object)null) { return Skip.NotReady; } level = instance.currentLevel; moon = Lll.CurrentPlanetName() ?? SizeMath.Numberless(level.PlanetName); interior = InteriorName(instance); if (level.levelID == 3) { return Skip.Company; } if (!level.spawnEnemiesAndScrap) { return Skip.NoSpawns; } if (instance2.isChallengeFile && !Cfg.ApplyOnChallengeMoons.Value) { return Skip.Challenge; } HashSet<string> excludeMoons = Lists.ExcludeMoons; if (excludeMoons.Contains(moon) || (level.PlanetName != null && excludeMoons.Contains(level.PlanetName.Trim()))) { return Skip.ExcludedMoon; } if (Lists.ExcludeInteriors.Contains(interior)) { return Skip.ExcludedInterior; } return Skip.None; } internal static string InteriorName(RoundManager rm) { string text = Lll.CurrentDungeonName(); if (text != null) { return text; } try { IndoorMapType[] dungeonFlowTypes = rm.dungeonFlowTypes; int currentDungeonType = rm.currentDungeonType; if (dungeonFlowTypes != null && currentDungeonType >= 0 && currentDungeonType < dungeonFlowTypes.Length && dungeonFlowTypes[currentDungeonType] != null && (Object)(object)dungeonFlowTypes[currentDungeonType].dungeonFlow != (Object)null) { return ((Object)dungeonFlowTypes[currentDungeonType].dungeonFlow).name; } } catch { } return "unknown interior"; } internal static string SkipText(Skip s) { return s switch { Skip.NoSpawns => "moon has no scrap or enemies", Skip.Challenge => "challenge file", Skip.ExcludedMoon => "excluded moon", Skip.ExcludedInterior => "excluded interior", _ => s.ToString(), }; } internal static void EnsureComputed() { RoundManager instance = RoundManager.Instance; StartOfRound instance2 = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || (Object)(object)instance.currentLevel == (Object)null || !IsHost()) { return; } int levelID = instance.currentLevel.levelID; int randomMapSeed = instance2.randomMapSeed; if (_computed && levelID == _levelId && randomMapSeed == _seed) { return; } Lists.ValidateNames(); _computed = true; _levelId = levelID; _seed = randomMapSeed; _finished = false; MScrap = (MValue = (MInside = (MOutside = (MTraps = (MRate = 1f))))); Rush = false; RateActive = false; Note = ""; SkipReason = Check(out var _, out Moon, out Interior); Size = ReadGeneratedSize(instance); ScaleSize = Size; if (SkipReason == Skip.None) { float num = Size; if (Cfg.Basis.Value == SizeBasis.TileAdjusted && SizeMath.IsValidSize(num)) { num *= MapTileSize(instance); } if (Lists.ScaleBias.TryGetValue(Interior, out var value)) { num *= value; } ScaleSize = num; if (!SizeMath.IsValidSize(num)) { Note = "invalid size"; Plugin.Log.LogWarning((object)("SizeScaling: " + Moon + " / " + Interior + " has an invalid size (" + num + "); all multipliers x1 today")); } else { float value2 = Cfg.ReferenceSize.Value; float value3 = Cfg.Exponent.Value; float value4 = Cfg.MinMultiplier.Value; float value5 = Cfg.MaxMultiplier.Value; bool value6 = Cfg.ScaleDown.Value; bool floorAtOne = !Cfg.AllowScrapReduction.Value; MScrap = SizeMath.Multiplier(num, Cfg.ScrapCountStrength.Value, value2, value3, value6, value4, value5, floorAtOne); MValue = SizeMath.Multiplier(num, Cfg.ScrapValueStrength.Value, value2, value3, value6, value4, value5, floorAtOne); MInside = SizeMath.Multiplier(num, Cfg.InsidePowerStrength.Value, value2, value3, value6, value4, value5, floorAtOne: false); MOutside = SizeMath.Multiplier(num, Cfg.OutsidePowerStrength.Value, value2, value3, value6, value4, value5, floorAtOne: false); MTraps = SizeMath.Multiplier(num, Cfg.TrapStrength.Value, value2, value3, value6, value4, value5, floorAtOne: false); MRate = SizeMath.Multiplier(num, Cfg.InsideSpawnRateStrength.Value, value2, value3, value6, value4, value5, floorAtOne: false); } } else if (SkipReason != Skip.Company && (!Cfg.AllStrengthsZero() || Cfg.SizeControlEnabled.Value)) { Note = SkipText(SkipReason); } if (SizeChanged && SizeMath.IsValidSize(LllRaw)) { string text = ((LllFinal < LllRaw) ? "capped from " : "raised from ") + SizeMath.F2(LllRaw); Note = ((Note.Length == 0) ? text : (text + "; " + Note)); } Publish(); if (!Hooks.PowerHookActive) { Finish(instance); } } private static float ReadGeneratedSize(RoundManager rm) { try { return (((Object)(object)rm.dungeonGenerator != (Object)null) ? rm.dungeonGenerator.Generator : null)?.LengthMultiplier ?? float.NaN; } catch { return float.NaN; } } private static float MapTileSize(RoundManager rm) { float? num = Lll.CurrentMapTileSize(); if (num.HasValue) { return num.Value; } try { IndoorMapType[] dungeonFlowTypes = rm.dungeonFlowTypes; int currentDungeonType = rm.currentDungeonType; if (dungeonFlowTypes != null && currentDungeonType >= 0 && currentDungeonType < dungeonFlowTypes.Length && dungeonFlowTypes[currentDungeonType] != null && SizeMath.IsValidSize(dungeonFlowTypes[currentDungeonType].MapTileSize)) { return dungeonFlowTypes[currentDungeonType].MapTileSize; } } catch { } return 1f; } internal static void Finish(RoundManager rm) { if (!_computed || _finished) { return; } _finished = true; if (SkipReason != Skip.Company && SkipReason != Skip.NotHost && SkipReason != Skip.Disabled && SkipReason != Skip.NotReady) { Rush = RushNow(rm); if (Rush && SkipReason == Skip.None && (MInside != 1f || MOutside != 1f || MRate != 1f)) { MInside = (MOutside = (MRate = 1f)); Note = ((Note.Length == 0) ? "enemy rush day: power and spawns not scaled" : (Note + "; enemy rush day: power and spawns not scaled")); } RateActive = SkipReason == Skip.None && !Rush && MRate != 1f; Publish(); if (Cfg.LogEachDay.Value) { Plugin.Log.LogInfo((object)LogLine()); } if (Cfg.ShareWithClient.Value) { Net.Broadcast(); } } } internal static void Publish() { RoundManager instance = RoundManager.Instance; if (SkipReason == Skip.Company || SkipReason == Skip.NotHost || SkipReason == Skip.Disabled || SkipReason == Skip.NotReady) { ScalingState.Clear(); return; } ScalingState.Valid = true; ScalingState.Planet = Moon; ScalingState.LevelId = (((Object)(object)instance != (Object)null && (Object)(object)instance.currentLevel != (Object)null) ? instance.currentLevel.levelID : (-1)); ScalingState.Interior = Interior; ScalingState.Size = (SizeMath.IsValidSize(Size) ? Size : 0f); ScalingState.LllSize = (SizeMath.IsValidSize(LllRaw) ? LllRaw : 0f); ScalingState.RefSize = Cfg.ReferenceSize.Value; ScalingState.ScrapCount = MScrap; ScalingState.ScrapValue = MValue; ScalingState.InsidePower = MInside; ScalingState.OutsidePower = MOutside; ScalingState.Traps = MTraps; ScalingState.SpawnRate = MRate; ScalingState.Note = Note ?? ""; ScalingState.Serial++; } internal static string LogLine() { StringBuilder stringBuilder = new StringBuilder("SizeScaling: "); stringBuilder.Append(Moon).Append(" / ").Append(Interior) .Append(" size ") .Append(Fmt(Size)); stringBuilder.Append(" (LLL ").Append(SizeMath.IsValidSize(LllRaw) ? SizeMath.F2(LllRaw) : "n/a"); stringBuilder.Append(", ref ").Append(SizeMath.F2(Cfg.ReferenceSize.Value)); if (SkipReason == Skip.None && SizeMath.IsValidSize(ScaleSize) && Math.Abs(ScaleSize - Size) > 0.0005f) { stringBuilder.Append(", scaling size ").Append(SizeMath.F2(ScaleSize)); } stringBuilder.Append(")"); if (SkipReason != Skip.None) { stringBuilder.Append(" -> not scaled (").Append(SkipText(SkipReason)).Append(")"); if (SizeChanged) { stringBuilder.Append(", ").Append(Note); } return stringBuilder.ToString(); } stringBuilder.Append(" -> scrap x").Append(SizeMath.F2(MScrap)); stringBuilder.Append(", value x").Append(SizeMath.F2(MValue)); stringBuilder.Append(", inside power x").Append(SizeMath.F2(MInside)); stringBuilder.Append(", outside x").Append(SizeMath.F2(MOutside)); stringBuilder.Append(", traps x").Append(SizeMath.F2(MTraps)); stringBuilder.Append(", spawns x").Append(SizeMath.F2(MRate)); if (Note.Length > 0) { stringBuilder.Append(", ").Append(Note); } return stringBuilder.ToString(); } private static string Fmt(float f) { if (!SizeMath.IsValidSize(f)) { return "invalid"; } return SizeMath.F2(f); } internal static void LogSizeControl(string moon, string interior, float raw, float result, bool applied) { string text = moon + "|" + interior + "|" + raw + "|" + result; if (!(text == _sizeLogKey)) { _sizeLogKey = text; if (applied && Math.Abs(result - raw) > 0.0005f) { Plugin.Log.LogInfo((object)("SizeScaling: size control on " + moon + " / " + interior + ": LLL " + SizeMath.F2(raw) + " -> " + SizeMath.F2(result))); } else { Plugin.Log.LogInfo((object)("SizeScaling: size control on " + moon + " / " + interior + ": " + SizeMath.F2(raw) + " unchanged")); } } } internal static void WarnSizeOnce(string text) { if (!_sizeWarned) { _sizeWarned = true; Plugin.Log.LogWarning((object)("SizeScaling: " + text)); } } } internal static class Lists { private static string _moonsText; private static string _interiorsText; private static string _biasText; private static string _rulesText; private static string _trapText; private static HashSet<string> _moons = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private static HashSet<string> _interiors = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private static HashSet<string> _traps = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private static Dictionary<string, float> _bias = new Dictionary<string, float>(StringComparer.OrdinalIgnoreCase); private static Dictionary<string, InteriorRule> _rules = new Dictionary<string, InteriorRule>(StringComparer.OrdinalIgnoreCase); private static readonly HashSet<string> Warned = new HashSet<string>(StringComparer.OrdinalIgnoreCase); internal static HashSet<string> ExcludeMoons { get { string text = Cfg.ExcludeMoons.Value ?? ""; if (text != _moonsText) { _moonsText = text; _moons = SizeMath.ParseNameList(text); } return _moons; } } internal static HashSet<string> ExcludeInteriors { get { string text = Cfg.ExcludeInteriors.Value ?? ""; if (text != _interiorsText) { _interiorsText = text; _interiors = SizeMath.ParseNameList(text); } return _interiors; } } internal static HashSet<string> TrapExclude { get { string text = Cfg.TrapExclude.Value ?? ""; if (text != _trapText) { _trapText = text; _traps = SizeMath.ParseNameList(text); } return _traps; } } internal static Dictionary<string, float> ScaleBias { get { string text = Cfg.InteriorScaleBias.Value ?? ""; if (text != _biasText) { _biasText = text; List<string> list = new List<string>(); _bias = SizeMath.ParseFactorMap(text, list); foreach (string item in list) { WarnOnce("InteriorScaleBias: " + item); } } return _bias; } } internal static Dictionary<string, InteriorRule> Rules { get { string text = Cfg.PerInterior.Value ?? ""; if (text != _rulesText) { _rulesText = text; List<string> list = new List<string>(); _rules = SizeMath.ParseRules(text, list); foreach (string item in list) { WarnOnce("PerInterior: " + item); } } return _rules; } } internal static void WarnOnce(string text) { if (Warned.Add(text)) { Plugin.Log.LogWarning((object)("SizeScaling: " + text)); } } internal static void ValidateNames() { try { List<string> list = Lll.AllDungeonNames(); if (list.Count > 0) { HashSet<string> hashSet = new HashSet<string>(list, StringComparer.OrdinalIgnoreCase); foreach (string key in Rules.Keys) { if (!hashSet.Contains(key)) { WarnOnce("PerInterior: unknown interior '" + key + "' (check the DungeonName in the daily log line)"); } } foreach (string key2 in ScaleBias.Keys) { if (!hashSet.Contains(key2)) { WarnOnce("InteriorScaleBias: unknown interior '" + key2 + "'"); } } foreach (string excludeInterior in ExcludeInteriors) { if (!hashSet.Contains(excludeInterior)) { WarnOnce("ExcludeInteriors: unknown interior '" + excludeInterior + "'"); } } } List<string> list2 = Lll.AllPlanetNames(); if (list2.Count <= 0) { return; } HashSet<string> hashSet2 = new HashSet<string>(list2, StringComparer.OrdinalIgnoreCase); foreach (string excludeMoon in ExcludeMoons) { if (!hashSet2.Contains(excludeMoon) && !hashSet2.Contains(SizeMath.Numberless(excludeMoon))) { WarnOnce("ExcludeMoons: unknown moon '" + excludeMoon + "'"); } } } catch (Exception e) { Guard.Fail("name check", e); } } } internal static class Guard { private static readonly Dictionary<string, int> Counts = new Dictionary<string, int>(); internal static void Fail(string hook, Exception e) { Counts.TryGetValue(hook, out var value); value = (Counts[hook] = value + 1); if (value <= 3) { Plugin.Log.LogError((object)("SizeScaling: " + hook + " failed (" + value + "/3 logged): " + e)); } } } internal static class Hooks { private struct SavedCurve { public IndoorMapHazard Hazard; public AnimationCurve Original; public AnimationCurve Ours; } internal static bool ResetHookActive; internal static bool ScrapHookActive; internal static bool TrapHookActive; internal static bool PowerHookActive; internal static bool RateHookActive; internal static bool SizeHookActive; internal static bool ChatHookActive; private static int _lerpMatches = -1; private static string _sizeHookProblem = ""; internal const string WeatherRegistryId = "mrov.WeatherRegistry"; internal const string GeneralImprovementsId = "ShaosilGaming.GeneralImprovements"; internal const string LllId = "imabatby.lethallevelloader"; private static bool _scrapOrderChecked; private static bool _amountWritten; private static bool _valueWritten; private static float _savedAmount; private static float _savedValue; private static float _wroteAmount; private static float _wroteValue; private static readonly List<SavedCurve> SavedCurves = new List<SavedCurve>(); private static MethodInfo _addChat; private static HarmonyMethod HM(string name, int priority = -1, string[] after = null) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(Hooks), name, (Type[])null, (Type[])null)); if (priority >= 0) { val.priority = priority; } if (after != null) { val.after = after; } return val; } internal static void ApplyAll(Harmony h) { ResetHookActive = Try("day reset", delegate { h.Patch((MethodBase)AccessTools.Method(typeof(RoundManager), "LoadNewLevel", (Type[])null, (Type[])null), HM("LoadNewLevelPrefix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); h.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "ShipLeave", (Type[])null, (Type[])null), (HarmonyMethod)null, HM("ShipLeavePostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); ScrapHookActive = Try("scrap scaling", delegate { h.Patch((MethodBase)AccessTools.Method(typeof(RoundManager), "SpawnScrapInLevel", (Type[])null, (Type[])null), HM("ScrapPrefix", 0, new string[2] { "mrov.WeatherRegistry", "ShaosilGaming.GeneralImprovements" }), (HarmonyMethod)null, (HarmonyMethod)null, HM("ScrapFinalizer"), (HarmonyMethod)null); }); TrapHookActive = Try("trap scaling", delegate { h.Patch((MethodBase)AccessTools.Method(typeof(RoundManager), "SpawnMapObjects", (Type[])null, (Type[])null), HM("TrapPrefix", 100, new string[1] { "imabatby.lethallevelloader" }), HM("TrapPostfix", 800), (HarmonyMethod)null, HM("TrapFinalizer"), (HarmonyMethod)null); }); PowerHookActive = Try("enemy power scaling", delegate { h.Patch((MethodBase)AccessTools.Method(typeof(RoundManager), "RefreshEnemiesList", (Type[])null, (Type[])null), (HarmonyMethod)null, HM("RefreshEnemiesListPostfix", 0), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); RateHookActive = Try("spawn rate scaling", delegate { MethodInfo methodInfo = AccessTools.Method(typeof(RoundManager), "PlotOutEnemiesForNextHour", (Type[])null, (Type[])null); if (methodInfo == null) { throw new MissingMethodException("RoundManager.PlotOutEnemiesForNextHour"); } h.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, HM("RateTranspiler"), (HarmonyMethod)null, (HarmonyMethod)null); if (_lerpMatches != 1) { throw new InvalidOperationException("expected exactly 1 Mathf.Lerp call, found " + _lerpMatches + "; method left unchanged"); } }); ChatHookActive = Try("chat line", delegate { h.Patch((MethodBase)AccessTools.Method(typeof(StartOfRound), "OnShipLandedMiscEvents", (Type[])null, (Type[])null), (HarmonyMethod)null, HM("LandedPostfix"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); if (Lll.ClampedSizeMethod == null) { _sizeHookProblem = (Lll.Present ? "GetClampedDungeonSize not found" : "LethalLevelLoader not found"); Plugin.Log.LogWarning((object)("SizeScaling: size control unavailable (" + _sizeHookProblem + "); the LLL size shows as n/a")); } else { SizeHookActive = Try("size control", delegate { h.Patch((MethodBase)Lll.ClampedSizeMethod, (HarmonyMethod)null, HM("ClampedSizePostfix", 0), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); }); } } private static bool Try(string feature, Action apply) { try { apply(); return true; } catch (Exception ex) { Plugin.Log.LogWarning((object)("SizeScaling: " + feature + " disabled: " + ex.Message)); return false; } } internal static string FeatureSummary() { return "day reset " + Ok(ResetHookActive) + ", scrap " + Ok(ScrapHookActive) + ", traps " + Ok(TrapHookActive) + ", power " + Ok(PowerHookActive) + ", spawn rate " + (RateHookActive ? "ok (1 Lerp)" : "OFF") + ", size control " + (SizeHookActive ? ("ok (LLL " + Lll.Version + ")") : ("OFF" + ((_sizeHookProblem.Length > 0) ? (" (" + _sizeHookProblem + ")") : ""))) + ", chat " + Ok(ChatHookActive); } private static string Ok(bool b) { if (!b) { return "OFF"; } return "ok"; } private static void LoadNewLevelPrefix() { try { Day.Reset(); RealSize.Reset(); } catch (Exception e) { Guard.Fail("LoadNewLevel reset", e); } } private static void ShipLeavePostfix() { try { RestoreTraps(); Day.Reset(); ScalingState.Clear(); RealSize.Reset(); } catch (Exception e) { Guard.Fail("ShipLeave reset", e); } } private static void ScrapPrefix(RoundManager __instance) { _amountWritten = (_valueWritten = false); try { if (!Cfg.Enabled.Value || (Object)(object)__instance == (Object)null || !((NetworkBehaviour)__instance).IsServer) { return; } if (!_scrapOrderChecked) { _scrapOrderChecked = true; CheckScrapPrefixOrder(); } Day.EnsureComputed(); if (!Day.Eligible) { return; } float mScrap = Day.MScrap; float mValue = Day.MValue; if (mScrap != 1f || mValue != 1f) { float scrapAmountMultiplier = __instance.scrapAmountMultiplier; float scrapValueMultiplier = __instance.scrapValueMultiplier; Plugin.Log.LogInfo((object)("SizeScaling: scrap multipliers for this spawn: amount " + scrapAmountMultiplier.ToString("0.###") + " x " + SizeMath.F2(mScrap) + ", value " + scrapValueMultiplier.ToString("0.###") + " x " + SizeMath.F2(mValue))); if (mScrap != 1f) { _savedAmount = __instance.scrapAmountMultiplier; _wroteAmount = _savedAmount * mScrap; __instance.scrapAmountMultiplier = _wroteAmount; _amountWritten = true; } if (mValue != 1f) { _savedValue = __instance.scrapValueMultiplier; _wroteValue = _savedValue * mValue; __instance.scrapValueMultiplier = _wroteValue; _valueWritten = true; } } } catch (Exception e) { Guard.Fail("scrap prefix", e); } } private static Exception ScrapFinalizer(RoundManager __instance, Exception __exception) { try { if ((Object)(object)__instance != (Object)null) { if (_amountWritten) { if (__instance.scrapAmountMultiplier == _wroteAmount) { __instance.scrapAmountMultiplier = _savedAmount; } else { Plugin.Log.LogWarning((object)("SizeScaling: another mod changed scrapAmountMultiplier during scrap spawning (" + __instance.scrapAmountMultiplier + "); left as is")); } } if (_valueWritten) { if (__instance.scrapValueMultiplier == _wroteValue) { __instance.scrapValueMultiplier = _savedValue; } else { Plugin.Log.LogWarning((object)("SizeScaling: another mod changed scrapValueMultiplier during scrap spawning (" + __instance.scrapValueMultiplier + "); left as is")); } } } } catch (Exception e) { Guard.Fail("scrap restore", e); } _amountWritten = (_valueWritten = false); return __exception; } private static void CheckScrapPrefixOrder() { try { MethodInfo methodInfo = AccessTools.Method(typeof(RoundManager), "SpawnScrapInLevel", (Type[])null, (Type[])null); Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo); if (patchInfo == null || patchInfo.Prefixes == null || patchInfo.Prefixes.Count == 0) { return; } List<MethodInfo> sorted = PatchProcessor.GetSortedPatchMethods((MethodBase)methodInfo, patchInfo.Prefixes.ToArray()); MethodInfo item = AccessTools.Method(typeof(Hooks), "ScrapPrefix", (Type[])null, (Type[])null); int num = sorted.IndexOf(item); if (num < 0) { return; } List<string> list = new List<string>(); List<string> list2 = new List<string>(); int i; for (i = 0; i < sorted.Count; i++) { if (i != num) { Patch val = ((IEnumerable<Patch>)patchInfo.Prefixes).FirstOrDefault((Func<Patch, bool>)((Patch x) => x.PatchMethod == sorted[i])); string item2 = ((val != null) ? val.owner : sorted[i].DeclaringType?.FullName); if (i > num) { list.Add(item2); } else { list2.Add(item2); } } } if (list.Count > 0) { Plugin.Log.LogWarning((object)("SizeScaling: SpawnScrapInLevel prefixes that run after ours (may overwrite the scrap multipliers): " + string.Join(", ", list.ToArray()))); } else { Plugin.Log.LogInfo((object)("SizeScaling: scrap prefix runs last (after " + ((list2.Count == 0) ? "none" : string.Join(", ", list2.Distinct().ToArray())) + ")")); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("SizeScaling: couldn't check SpawnScrapInLevel prefix order: " + ex.Message)); } } private static void TrapPrefix(RoundManager __instance) { try { RestoreTraps(); if (!Cfg.Enabled.Value || (Object)(object)__instance == (Object)null || !((NetworkBehaviour)__instance).IsServer) { return; } Day.EnsureComputed(); if (!Day.Eligible) { return; } float mTraps = Day.MTraps; if (mTraps == 1f) { return; } SelectableLevel currentLevel = __instance.currentLevel; IndoorMapHazard[] array = (((Object)(object)currentLevel != (Object)null) ? currentLevel.indoorMapHazards : null); if (array == null || array.Length == 0) { return; } HashSet<string> trapExclude = Lists.TrapExclude; HashSet<IndoorMapHazard> hashSet = new HashSet<IndoorMapHazard>(); List<string> list = new List<string>(); IndoorMapHazard[] array2 = array; foreach (IndoorMapHazard val in array2) { if (val != null && val.numberToSpawn != null && hashSet.Add(val)) { string item = HazardName(val); if (trapExclude.Count <= 0 || (!trapExclude.Contains(item) && (!((Object)(object)val.hazardType != (Object)null) || !trapExclude.Contains(((Object)val.hazardType).name)))) { AnimationCurve numberToSpawn = val.numberToSpawn; AnimationCurve ours = (val.numberToSpawn = ScaleCurve(numberToSpawn, mTraps)); SavedCurves.Add(new SavedCurve { Hazard = val, Original = numberToSpawn, Ours = ours }); list.Add(item); } } } if (list.Count > 0) { Plugin.Log.LogInfo((object)("SizeScaling: hazard counts x" + SizeMath.F2(mTraps) + " for " + string.Join(", ", list.ToArray()))); } } catch (Exception e) { Guard.Fail("trap prefix", e); try { RestoreTraps(); } catch { } } } private static void TrapPostfix() { try { RestoreTraps(); } catch (Exception e) { Guard.Fail("trap restore", e); } } private static Exception TrapFinalizer(Exception __exception) { try { RestoreTraps(); } catch (Exception e) { Guard.Fail("trap restore", e); } return __exception; } private static void RestoreTraps() { if (SavedCurves.Count == 0) { return; } foreach (SavedCurve savedCurf in SavedCurves) { if (savedCurf.Hazard != null) { if (savedCurf.Hazard.numberToSpawn == savedCurf.Ours) { savedCurf.Hazard.numberToSpawn = savedCurf.Original; } else { Lists.WarnOnce("hazard curve for " + HazardName(savedCurf.Hazard) + " was replaced by another mod during SpawnMapObjects; left as is"); } } } SavedCurves.Clear(); } private static string HazardName(IndoorMapHazard hz) { try { if ((Object)(object)hz.hazardType != (Object)null && (Object)(object)hz.hazardType.prefabToSpawn != (Object)null) { return ((Object)hz.hazardType.prefabToSpawn).name; } if ((Object)(object)hz.hazardType != (Object)null) { return ((Object)hz.hazardType).name; } } catch { } return "unknown hazard"; } internal static AnimationCurve ScaleCurve(AnimationCurve orig, float m) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005a: 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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown Keyframe[] keys = orig.keys; for (int i = 0; i < keys.Length; i++) { Keyframe val = keys[i]; ((Keyframe)(ref val)).value = ((Keyframe)(ref val)).value * m; ((Keyframe)(ref val)).inTangent = ((Keyframe)(ref val)).inTangent * m; ((Keyframe)(ref val)).outTangent = ((Keyframe)(ref val)).outTangent * m; keys[i] = val; } return new AnimationCurve(keys) { preWrapMode = orig.preWrapMode, postWrapMode = orig.postWrapMode }; } private static void RefreshEnemiesListPostfix(RoundManager __instance) { try { if (!Cfg.Enabled.Value || (Object)(object)__instance == (Object)null || !((NetworkBehaviour)__instance).IsServer) { return; } Day.EnsureComputed(); Day.Finish(__instance); if (Day.Eligible && !Day.Rush) { if (Day.MInside != 1f) { __instance.currentMaxInsidePower *= Day.MInside; } if (Day.MOutside != 1f) { __instance.currentMaxOutsidePower *= Day.MOutside; } if (Day.MInside != 1f || Day.MOutside != 1f) { Plugin.Log.LogInfo((object)("SizeScaling: max power inside " + __instance.currentMaxInsidePower.ToString("0.##") + ", outside " + __instance.currentMaxOutsidePower.ToString("0.##"))); } } } catch (Exception e) { Guard.Fail("power postfix", e); } } private static IEnumerable<CodeInstruction> RateTranspiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = instructions.ToList(); try { MethodInfo lerp = AccessTools.Method(typeof(Mathf), "Lerp", new Type[3] { typeof(float), typeof(float), typeof(float) }, (Type[])null); MethodInfo methodInfo = AccessTools.Method(typeof(Hooks), "HourLerp", (Type[])null, (Type[])null); if ((_lerpMatches = list.Count((CodeInstruction ci) => CodeInstructionExtensions.Calls(ci, lerp))) != 1 || methodInfo == null) { return list; } foreach (CodeInstruction item in list) { if (CodeInstructionExtensions.Calls(item, lerp)) { item.operand = methodInfo; } } } catch (Exception ex) { _lerpMatches = -1; Plugin.Log.LogWarning((object)("SizeScaling: spawn rate transpiler failed: " + ex.Message)); } return list; } public static float HourLerp(float a, float b, float t) { float num = Mathf.Lerp(a, b, t); try { if (!Day.RateActive || !Cfg.Enabled.Value || num <= 0f) { return num; } float mRate = Day.MRate; if (mRate == 1f || Day.RushNow(RoundManager.Instance)) { return num; } return num * mRate; } catch { return num; } } private static void ClampedSizePostfix(ref float __result) { try { float num = (Day.LllFinal = (Day.LllRaw = __result)); if (!Cfg.Enabled.Value || !Day.IsHost()) { return; } SelectableLevel level; string moon; string interior; Skip skip = Day.Check(out level, out moon, out interior); if ((Object)(object)level != (Object)null && num == 1f && level.factorySizeMultiplier != 1f) { Plugin.Log.LogDebug((object)("SizeScaling: LLL size is exactly 1.0 on " + moon + " / " + interior + " (factory size " + level.factorySizeMultiplier + "); the flow may be missing from RoundManager.dungeonFlowTypes (LLL fallback)")); } if (!Cfg.SizeControlEnabled.Value || skip != Skip.None) { return; } if (!SizeMath.IsValidSize(num)) { Day.WarnSizeOnce("LLL returned an invalid size (" + num + ") for " + moon + " / " + interior + "; size control left it alone"); return; } Lists.Rules.TryGetValue(interior, out var value); RoundManager instance = RoundManager.Instance; float sceneMapSize = (((Object)(object)instance != (Object)null) ? instance.mapSizeMultiplier : 1f); bool applied; string warning; float num2 = SizeMath.ControlSize(num, Cfg.MapSizeMultiplierOverride.Value, sceneMapSize, value, Cfg.MinSize.Value, Cfg.MaxSize.Value, Cfg.Softness.Value, out applied, out warning); if (warning != null) { Lists.WarnOnce("size control (" + interior + "): " + warning); } if (SizeMath.IsValidSize(num2)) { __result = num2; Day.LllFinal = num2; Day.SizeChanged = applied && Math.Abs(num2 - num) > 0.0005f; Day.LogSizeControl(moon, interior, num, num2, applied); } } catch (Exception e) { Guard.Fail("size control", e); } } private static void LandedPostfix() { try { if (!Cfg.Enabled.Value || !Cfg.ShowInChat.Value || !Day.IsHost() || Day.ChatShown) { return; } Day.EnsureComputed(); if (!ScalingState.Valid || Day.SkipReason != Skip.None || (!ScalingState.AnyMultiplier() && !Day.SizeChanged)) { return; } Day.ChatShown = true; string text = ChatText(); HUDManager instance = HUDManager.Instance; if ((Object)(object)instance == (Object)null) { return; } if (_addChat == null) { _addChat = AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null); } if (_addChat == null) { return; } ParameterInfo[] parameters = _addChat.GetParameters(); object[] array = new object[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { if (i == 0) { array[i] = text; } else if (parameters[i].ParameterType == typeof(string)) { array[i] = ""; } else if (parameters[i].ParameterType == typeof(int)) { array[i] = -1; } else if (parameters[i].ParameterType == typeof(bool)) { array[i] = false; } else { array[i] = (parameters[i].HasDefaultValue ? parameters[i].DefaultValue : null); } } _addChat.Invoke(instance, array); } catch (Exception e) { Guard.Fail("chat line", e); } } internal static string ChatText() { float size = ScalingState.Size; float refSize = ScalingState.RefSize; string text = ((size > refSize + 0.005f) ? "Big interior" : ((size < refSize - 0.005f) ? "Small interior" : "Interior")) + " (" + SizeMath.F2(size); if (Day.SizeChanged && SizeMath.IsValidSize(Day.LllRaw)) { text = text + ((Day.LllFinal < Day.LllRaw) ? ", capped from " : ", raised from ") + SizeMath.F2(Day.LllRaw); } text += ")"; List<string> list = new List<string>(); Add(list, "scrap", ScalingState.ScrapCount); Add(list, "value", ScalingState.ScrapValue); Add(list, "inside power", ScalingState.InsidePower); Add(list, "outside power", ScalingState.OutsidePower); Add(list, "traps", ScalingState.Traps); Add(list, "spawns", ScalingState.SpawnRate); string text2 = ((list.Count > 0) ? (": " + string.Join(", ", list.ToArray())) : ""); return "<color=#8fd3ff>" + text + text2 + ".</color>"; } private static void Add(List<string> parts, string label, float m) { if (m != 1f) { parts.Add(label + " x" + SizeMath.F2(m)); } } } internal static class Lll { internal static bool Present; internal static string Version = ""; internal static MethodInfo ClampedSizeMethod; private static PropertyInfo _curFlow; private static PropertyInfo _curLevel; private static PropertyInfo _dungeonName; private static PropertyInfo _mapTileSize; private static PropertyInfo _numberless; private static PropertyInfo _allFlows; private static PropertyInfo _allLevels; internal static void Init() { try { Type type = QuietTypes.Find("LethalLevelLoader.DungeonLoader"); Type type2 = QuietTypes.Find("LethalLevelLoader.DungeonManager"); Type type3 = QuietTypes.Find("LethalLevelLoader.LevelManager"); Type type4 = QuietTypes.Find("LethalLevelLoader.ExtendedDungeonFlow"); Type type5 = QuietTypes.Find("LethalLevelLoader.ExtendedLevel"); Type type6 = QuietTypes.Find("LethalLevelLoader.PatchedContent"); Present = type != null && type2 != null; if (type != null) { MethodInfo methodInfo = AccessTools.Method(type, "GetClampedDungeonSize", Type.EmptyTypes, (Type[])null); if (methodInfo != null && methodInfo.IsStatic && methodInfo.ReturnType == typeof(float)) { ClampedSizeMethod = methodInfo; } } if (type2 != null) { _curFlow = AccessTools.Property(type2, "CurrentExtendedDungeonFlow"); } if (type3 != null) { _curLevel = AccessTools.Property(type3, "CurrentExtendedLevel"); } if (type4 != null) { _dungeonName = AccessTools.Property(type4, "DungeonName"); _mapTileSize = AccessTools.Property(type4, "MapTileSize"); } if (type5 != null) { _numberless = AccessTools.Property(type5, "NumberlessPlanetName"); } if (type6 != null) { _allFlows = AccessTools.Property(type6, "ExtendedDungeonFlows"); _allLevels = AccessTools.Property(type6, "ExtendedLevels"); } Type type7 = QuietTypes.Find("LethalLevelLoader.Plugin"); FieldInfo fieldInfo = ((type7 == null) ? null : AccessTools.Field(type7, "ModVersion")); if (fieldInfo != null && fieldInfo.IsStatic) { Version = (fieldInfo.GetValue(null) as string) ?? ""; } } catch (Exception ex) { Plugin.Log.LogWarning((object)("LethalLevelLoader lookup failed: " + ex.Message)); } } private static object Get(PropertyInfo p, object target) { if (p == null) { return null; } try { return p.GetValue(target, null); } catch { return null; } } private static bool Alive(object o) { Object val = (Object)((o is Object) ? o : null); if (!(val != (Object)null)) { return o != null; } return Object.op_Implicit(val); } internal static string CurrentDungeonName() { object obj = Get(_curFlow, null); if (!Alive(obj)) { return null; } string text = Get(_dungeonName, obj) as string; if (!string.IsNullOrEmpty(text)) { return text; } return null; } internal static float? CurrentMapTileSize() { object obj = Get(_curFlow, null); if (!Alive(obj)) { return null; } if (Get(_mapTileSize, obj) is float num && SizeMath.IsValidSize(num)) { return num; } return null; } internal static string CurrentPlanetName() { object obj = Get(_curLevel, null); if (!Alive(obj)) { return null; } string text = Get(_numberless, obj) as string; if (!string.IsNullOrEmpty(text)) { return text; } return null; } internal static List<string> AllDungeonNames() { return Names(_allFlows, _dungeonName); } internal static List<string> AllPlanetNames() { return Names(_allLevels, _numberless); } private static List<string> Names(PropertyInfo listProp, PropertyInfo nameProp) { List<string> list = new List<string>(); if (!(Get(listProp, null) is IEnumerable enumerable) || nameProp == null) { return list; } foreach (object item in enumerable) { if (Alive(item)) { string text = Get(nameProp, item) as string; if (!string.IsNullOrEmpty(text)) { list.Add(text); } } } return list; } } internal static class Net { internal const string StateMsg = "jacob.sizescaling.state"; private const byte PayloadVersion = 1; private const int MaxString = 96; private static CustomMessagingManager _registeredOn; private static int _badMessages; internal static void EnsureRegistered() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null) && singleton.CustomMessagingManager != null && _registeredOn != singleton.CustomMessagingManager) { _registeredOn = singleton.CustomMessagingManager; singleton.CustomMessagingManager.RegisterNamedMessageHandler("jacob.sizescaling.state", new HandleNamedMessageDelegate(Receive)); } } private static void Receive(ulong sender, FastBufferReader reader) { //IL_0025: 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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) try { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || singleton.IsServer || sender != 0L) { return; } byte b = default(byte); ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives)); if (b == 1) { bool flag = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives)); int levelId = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref levelId, default(ForPrimitives)); string s = default(string); ((FastBufferReader)(ref reader)).ReadValueSafe(ref s, false); string s2 = default(string); ((FastBufferReader)(ref reader)).ReadValueSafe(ref s2, false); string s3 = default(string); ((FastBufferReader)(ref reader)).ReadValueSafe(ref s3, false); float num = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num, default(ForPrimitives)); float num2 = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num2, default(ForPrimitives)); float num3 = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num3, default(ForPrimitives)); float num4 = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num4, default(ForPrimitives)); float num5 = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num5, default(ForPrimitives)); float num6 = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num6, default(ForPrimitives)); float num7 = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num7, default(ForPrimitives)); float num8 = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num8, default(ForPrimitives)); float num9 = default(float); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref num9, default(ForPrimitives)); if (!Finite(num) || !Finite(num2) || !Finite(num3) || !Mult(num4) || !Mult(num5) || !Mult(num6) || !Mult(num7) || !Mult(num8) || !Mult(num9)) { Bad("values out of range"); return; } if (!flag) { ScalingState.Clear(); return; } ScalingState.Valid = true; ScalingState.LevelId = levelId; ScalingState.Planet = Trim(s); ScalingState.Interior = Trim(s2); ScalingState.Note = Trim(s3); ScalingState.Size = num; ScalingState.LllSize = num2; ScalingState.RefSize = num3; ScalingState.ScrapCount = num4; ScalingState.ScrapValue = num5; ScalingState.InsidePower = num6; ScalingState.OutsidePower = num7; ScalingState.Traps = num8; ScalingState.SpawnRate = num9; ScalingState.Serial++; Plugin.Log.LogInfo((object)("SizeScaling: host's day info received: " + ScalingState.Planet + " / " + ScalingState.Interior + " size " + SizeMath.F2(num) + (ScalingState.AnyMultiplier() ? " (multipliers active)" : " (no multipliers)"))); } } catch (Exception ex) { Bad(ex.GetType().Name); } } private static void Bad(string why) { _badMessages++; if (_badMessages <= 3) { Plugin.Log.LogWarning((object)("SizeScaling: dropped a malformed day info message from the host (" + why + ")")); } } private static bool Finite(float f) { if (!float.IsNaN(f) && !float.IsInfinity(f) && f >= 0f) { return f < 1000f; } return false; } private static bool Mult(float f) { if (!float.IsNaN(f) && !float.IsInfinity(f) && f > 0f) { return f <= 100f; } return false; } private static string Trim(string s) { if (s == null) { return ""; } if (s.Length <= 96) { return s; } return s.Substring(0, 96); } internal unsafe static void Broadcast() { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0078: 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_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) try { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsServer || singleton.CustomMessagingManager == null) { return; } EnsureRegistered(); FastBufferWriter val = default(FastBufferWriter); foreach (ulong connectedClientsId in singleton.ConnectedClientsIds) { if (connectedClientsId != 0L) { ((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 2048); try { byte b = 1; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref ScalingState.Valid, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref ScalingState.LevelId, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe(Trim(ScalingState.Planet), false); ((FastBufferWriter)(ref val)).WriteValueSafe(Trim(ScalingState.Interior), false); ((FastBufferWriter)(ref val)).WriteValueSafe(Trim(ScalingState.Note), false); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ScalingState.Size, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ScalingState.LllSize, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ScalingState.RefSize, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ScalingState.ScrapCount, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ScalingState.ScrapValue, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ScalingState.InsidePower, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ScalingState.OutsidePower, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ScalingState.Traps, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref ScalingState.SpawnRate, default(ForPrimitives)); singleton.CustomMessagingManager.SendNamedMessage("jacob.sizescaling.state", connectedClientsId, val, (NetworkDelivery)2); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } } } catch (Exception e) { Guard.Fail("client share", e); } } } internal class Runner : MonoBehaviour { private float _next; private int _errors; private void Update() { if (_errors >= 10 || Time.unscaledTime < _next) { return; } _next = Time.unscaledTime + 0.5f; try { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton != (Object)null && singleton.IsListening) { Net.EnsureRegistered(); } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance != (Object)null && !instance.inShipPhase && instance.shipHasLanded) { RealSize.Refresh(); } } catch (Exception ex) { _errors++; Plugin.Log.LogWarning((object)("SizeScaling runner error " + _errors + "/10: " + ex.Message)); } } } public enum SizeBasis { Raw, TileAdjusted } [BepInPlugin("jacob.sizescaling", "SizeScaling", "1.1.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public const string Guid = "jacob.sizescaling"; public const string Name = "SizeScaling"; public const string Version = "1.1.1"; internal static ManualLogSource Log; private void Awake() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_002f: 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_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Cfg.Bind(((BaseUnityPlugin)this).Config); Lll.Init(); Hooks.ApplyAll(new Harmony("jacob.sizescaling")); try { GameObject val = new GameObject("SizeScalingRunner") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)val); val.AddComponent<Runner>(); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Runner couldn't start (client display sharing off): " + ex.Message)); } ((BaseUnityPlugin)this).Logger.LogInfo((object)("SizeScaling 1.1.1 loaded. " + Cfg.Summary() + " Features: " + Hooks.FeatureSummary() + ".")); } } internal static class Cfg { internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<bool> ApplyOnChallengeMoons; internal static ConfigEntry<bool> LogEachDay; internal static ConfigEntry<string> ExcludeMoons; internal static ConfigEntry<string> ExcludeInteriors; internal static ConfigEntry<float> ReferenceSize; internal static ConfigEntry<float> Exponent; internal static ConfigEntry<float> MinMultiplier; internal static ConfigEntry<float> MaxMultiplier; internal static ConfigEntry<SizeBasis> Basis; internal static ConfigEntry<string> InteriorScaleBias; internal static ConfigEntry<string> TrapExclude; internal static ConfigEntry<bool> ScaleDown; internal static ConfigEntry<bool> AllowScrapReduction; internal static ConfigEntry<float> ScrapCountStrength; internal static ConfigEntry<float> ScrapValueStrength; internal static ConfigEntry<float> InsidePowerStrength; internal static ConfigEntry<float> OutsidePowerStrength; internal static ConfigEntry<float> TrapStrength; internal static ConfigEntry<float> InsideSpawnRateStrength; internal static ConfigEntry<bool> SizeControlEnabled; internal static ConfigEntry<float> MinSize; internal static ConfigEntry<float> MaxSize; internal static ConfigEntry<float> Softness; internal static ConfigEntry<float> MapSizeMultiplierOverride; internal static ConfigEntry<string> PerInterior; internal static ConfigEntry<bool> ShowInChat; internal static ConfigEntry<bool> ShareWithClient; private static ConfigDescription Range(string text, float min, float max) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown return new ConfigDescription(text, (AcceptableValueBase)(object)new AcceptableValueRange<float>(min, max), Array.Empty<object>()); } internal static void Bind(ConfigFile c) { Enabled = c.Bind<bool>("General", "Enabled", true, "Master switch. False: every hook returns at once."); ApplyOnChallengeMoons = c.Bind<bool>("General", "ApplyOnChallengeMoons", false, "Scale and control size on challenge files too."); ExcludeMoons = c.Bind<string>("General", "ExcludeMoons", "", "Comma list of moon names (LLL NumberlessPlanetName, e.g. \"Vow, Bozoros\"). The Company is always excluded."); ExcludeInteriors = c.Bind<string>("General", "ExcludeInteriors", "", "Comma list of LLL DungeonNames that are never scaled or size-controlled. The daily log line shows the exact name."); LogEachDay = c.Bind<bool>("General", "LogEachDay", true, "Host: one log line per eligible day with the size and multipliers."); ReferenceSize = c.Bind<float>("Scaling", "ReferenceSize", 1.5f, Range("Size that counts as normal (1.5 = Experimentation's facility).", 0.5f, 5f)); Basis = c.Bind<SizeBasis>("Scaling", "SizeBasis", SizeBasis.Raw, "Raw = the generated LengthMultiplier (what PerfWatcher shows). TileAdjusted = LengthMultiplier x the interior's MapTileSize, so big-tile interiors count as larger."); InteriorScaleBias = c.Bind<string>("Scaling", "InteriorScaleBias", "", "Name=factor;Name2=factor. Multiplies the size used for scaling only (the real size doesn't change)."); Exponent = c.Bind<float>("Scaling", "Exponent", 0.5f, Range("Shape: f = (size / ReferenceSize) ^ Exponent. Below 1 means diminishing returns.", 0.1f, 2f)); ScaleDown = c.Bind<bool>("Scaling", "ScaleDown", true, "Smaller-than-reference interiors get multipliers below 1 (all channels). False: every channel is floored at 1."); AllowScrapReduction = c.Bind<bool>("Scaling", "AllowScrapReduction", true, "False: scrap count and scrap value multipliers never go below 1 (other channels still scale down if ScaleDown is on)."); MinMultiplier = c.Bind<float>("Scaling", "MinMultiplier", 0.5f, Range("Lower clamp for every channel.", 0.1f, 1f)); MaxMultiplier = c.Bind<float>("Scaling", "MaxMultiplier", 2f, Range("Upper clamp for every channel.", 1f, 5f)); ScrapCountStrength = c.Bind<float>("Scaling", "ScrapCountStrength", 0f, Range("0 = off, 1 = full f, 2 = double the effect. Scales the number of inside scrap items.", 0f, 3f)); ScrapValueStrength = c.Bind<float>("Scaling", "ScrapValueStrength", 0f, Range("As above, for scrap value.", 0f, 3f)); InsidePowerStrength = c.Bind<float>("Scaling", "InsidePowerStrength", 0f, Range("As above, for the max inside enemy power.", 0f, 3f)); OutsidePowerStrength = c.Bind<float>("Scaling", "OutsidePowerStrength", 0f, Range("As above, for the max outside enemy power. Probably leave at 0.", 0f, 3f)); TrapStrength = c.Bind<float>("Scaling", "TrapStrength", 0f, Range("As above, for indoor hazard counts (turrets, mines, spike traps, modded hazards).", 0f, 3f)); InsideSpawnRateStrength = c.Bind<float>("Scaling", "InsideSpawnRateStrength", 0f, Range("As above, for inside enemies spawned per hour.", 0f, 3f)); TrapExclude = c.Bind<string>("Scaling", "TrapExclude", "", "Comma list of hazard prefab names that are never scaled."); SizeControlEnabled = c.Bind<bool>("SizeControl", "Enabled", false, "Turn on the size limits below (host decides the size for everyone)."); MinSize = c.Bind<float>("SizeControl", "MinSize", 0f, Range("0 = no minimum.", 0f, 6f)); MaxSize = c.Bind<float>("SizeControl", "MaxSize", 0f, Range("0 = no maximum.", 0f, 6f)); Softness = c.Bind<float>("SizeControl", "Softness", 0f, Range("0 = hard limit, 1 = no effect, 0.5 = halfway.", 0f, 1f)); PerInterior = c.Bind<string>("SizeControl", "PerInterior", "", "Name=mult,min,max,softness;... with '-' for the global value. Example: Rubber Rooms=-,-,2.0,0; Haunted Mansion=0.9,-,-,-"); MapSizeMultiplierOverride = c.Bind<float>("SizeControl", "MapSizeMultiplierOverride", 0f, Range("0 = off. Otherwise used in place of the scene's map size multiplier (1.5).", 0f, 5f)); ShowInChat = c.Bind<bool>("Display", "ShowInChat", true, "Host: one local chat line after landing when something changed."); ShareWithClient = c.Bind<bool>("Display", "ShareWithClient", true, "Send the display state (multipliers only) to the client for its PerfWatcher Day Info."); } internal static bool AllStrengthsZero() { if (ScrapCountStrength.Value <= 0f && ScrapValueStrength.Value <= 0f && InsidePowerStrength.Value <= 0f && OutsidePowerStrength.Value <= 0f && TrapStrength.Value <= 0f) { return InsideSpawnRateStrength.Value <= 0f; } return false; } internal static string Summary() { if (!Enabled.Value) { return "Disabled in config (no effect)."; } return (AllStrengthsZero() ? "Strengths all 0 (no effect)." : "Scaling on.") + (SizeControlEnabled.Value ? " Size control on." : " Size control off."); } } internal static class QuietTypes { private static readonly Dictionary<string, Type> _hits; private static readonly Dictionary<string, int> _misses; private static readonly object _lock; private static int _generation; static QuietTypes() { _hits = new Dictionary<string, Type>(StringComparer.Ordinal); _misses = new Dictionary<string, int>(StringComparer.Ordinal); _lock = new object(); try { AppDomain.CurrentDomain.AssemblyLoad += delegate { lock (_lock) { _generation++; } }; } catch { } } internal static Type Find(string fullName) { if (string.IsNullOrEmpty(fullName)) { return null; } int generation; lock (_lock) { if (_hits.TryGetValue(fullName, out var value)) { return value; } if (_misses.TryGetValue(fullName, out var value2) && value2 == _generation) { return null; } generation = _generation; } Type type = Scan(fullName); lock (_lock) { if (type != null) { _hits[fullName] = type; _misses.Remove(fullName); } else { _misses[fullName] = generation; } } return type; } private static Type Scan(string fullName) { Assembly[] assemblies; try { assemblies = AppDomain.CurrentDomain.GetAssemblies(); } catch { return null; } Assembly[] array = assemblies; foreach (Assembly assembly in array) { Type type = null; try { type = assembly.GetType(fullName, throwOnError: false); } catch { } if (type != null) { return type; } } return null; } } public static class RealSize { private struct Entry { public int Seed; public int Level; public string Interior; public int Rooms; public float Area; } public static bool Valid; public static int Rooms; public static float Area; public static float Median; public static string Label = ""; public static int Serial; private const int MaxDays = 40; private const int MinDays = 5; private static readonly CultureInfo Inv = CultureInfo.InvariantCulture; private static int _dungeonId; private static bool _loaded; private static readonly List<Entry> History = new List<Entry>(); private static int _errors; public static string Describe(float lengthMultiplier) { try { if (!Refresh()) { return null; } string text = ((Area >= 10000f) ? ((Area / 1000f).ToString("0.0", Inv) + "k") : (Math.Round(Area / 100f) * 100.0).ToString("#,0", Inv)); return ((Label.Length > 0) ? (Label + " (") : "(") + Rooms + " rooms, " + text + " m²)"; } catch (Exception e) { Fail(e); return null; } } public static bool Refresh() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) RoundManager instance = RoundManager.Instance; RuntimeDungeon val = (((Object)(object)instance != (Object)null) ? instance.dungeonGenerator : null); DungeonGenerator val2 = (((Object)(object)val != (Object)null) ? val.Generator : null); if (val2 == null || (int)val2.Status != 8) { if (Valid && _dungeonId != 0) { return Alive(val2); } return false; } Dungeon currentDungeon = val2.CurrentDungeon; if ((Object)(object)currentDungeon == (Object)null || currentDungeon.AllTiles == null || currentDungeon.AllTiles.Count == 0) { Valid = false; return false; } int instanceID = ((Object)currentDungeon).GetInstanceID(); if (Valid && instanceID == _dungeonId) { return true; } int num = 0; double num2 = 0.0; foreach (Tile allTile in currentDungeon.AllTiles) { if (!((Object)(object)allTile == (Object)null)) { Bounds bounds = allTile.Bounds; Vector3 size = ((Bounds)(ref bounds)).size; if (!float.IsNaN(size.x) && !float.IsNaN(size.z) && !(size.x <= 0f) && !(size.z <= 0f) && !(size.x > 1000f) && !(size.z > 1000f)) { num++; num2 += (double)size.x * (double)size.z; } } } if (num == 0) { Valid = false; return false; } _dungeonId = instanceID; Rooms = num; Area = (float)num2; Record(instance); Valid = true; Serial++; return true; } private static bool Alive(DungeonGenerator gen) { try { return gen != null && (Object)(object)gen.CurrentDungeon != (Object)null && ((Object)gen.CurrentDungeon).GetInstanceID() == _dungeonId; } catch { return false; } } private static void Record(RoundManager rm) { Load(); StartOfRound instance = StartOfRound.Instance; int num = (((Object)(object)instance != (Object)null) ? instance.randomMapSeed : 0); int num2 = (((Object)(object)rm != (Object)null && (Object)(object)rm.currentLevel != (Object)null) ? rm.currentLevel.levelID : (-1)); string text = Day.InteriorName(rm) ?? ""; string text2 = (((Object)(object)rm != (Object)null && (Object)(object)rm.currentLevel != (Object)null) ? rm.currentLevel.PlanetName : ""); bool flag = false; foreach (Entry item in History) { if (item.Seed == num && item.Level == num2) { flag = true; break; } } if (!flag) { History.Add(new Entry { Seed = num, Level = num2, Interior = text, Rooms = Rooms, Area = Area }); while (History.Count > 40) { History.RemoveAt(0); } Save(); } if (History.Count >= 5) { List<float> list = new List<float>(); foreach (Entry item2 in History) { list.Add(item2.Area); } list.Sort(); int count = list.Count; Median = ((count % 2 == 1) ? list[count / 2] : ((list[count / 2 - 1] + list[count / 2]) / 2f)); float num3 = ((Median > 0f) ? (Area / Median) : 1f); Label = ((num3 < 0.65f) ? "Small" : ((num3 < 1.35f) ? "Normal" : ((num3 < 1.9f) ? "Large" : "Huge"))); } else { Median = 0f; Label = ""; } Plugin.Log.LogInfo((object)("SizeScaling: real size of " + text2 + " / " + text + ": " + Rooms + " rooms, " + Area.ToString("#,0", Inv) + " m² footprint" + ((Median > 0f) ? (" (" + (Area / Median).ToString("0.00", Inv) + "x the median of " + History.Count + " days, " + Median.ToString("#,0", Inv) + " m²) -> " + Label) : (" (" + History.Count + " of " + 5 + " days recorded, no label yet)")))); } private static string FilePath() { return Path.Combine(Path.Combine(Paths.BepInExRootPath, "SizeScaling"), "footprints.txt"); } private static void Load() { if (_loaded) { return; } _loaded = true; try { string path = FilePath(); if (!File.Exists(path)) { return; } string[] array = File.ReadAllLines(path); foreach (string text in array) { if (text.Length != 0 && text[0] != '#') { string[] array2 = text.Split('\t'); if (array2.Length >= 5 && int.TryParse(array2[0], NumberStyles.Integer, Inv, out var result) && int.TryParse(array2[1], NumberStyles.Integer, Inv, out var result2) && int.TryParse(array2[3], NumberStyles.Integer, Inv, out var result3) && float.TryParse(array2[4], NumberStyles.Float, Inv, out var result4) && !(result4 <= 0f)) { History.Add(new Entry { Seed = result, Level = result2, Interior = array2[2], Rooms = result3, Area = result4 }); } } } while (History.Count > 40) { History.RemoveAt(0); } } catch (Exception e) { Fail(e); } } private static void Save() { try { string path = FilePath(); Directory.CreateDirectory(Path.GetDirectoryName(path)); List<string> list = new List<string> { "# SizeScaling real interior sizes: seed, levelID, interior, rooms, footprint m² (last " + 40 + " days)" }; foreach (Entry item in History) { list.Add(item.Seed.ToString(Inv) + "\t" + item.Level.ToString(Inv) + "\t" + (item.Interior ?? "").Replace('\t', ' ') + "\t" + item.Rooms.ToString(Inv) + "\t" + item.Area.ToString("0", Inv)); } File.WriteAllLines(path, list.ToArray()); } catch (Exception e) { Fail(e); } } internal static void Reset() { Valid = false; _dungeonId = 0; Label = ""; Serial++; } private static void Fail(Exception e) { if (_errors++ < 3) { Plugin.Log.LogWarning((object)("SizeScaling: real size measurement failed: " + e.Message)); } } } public static class ScalingState { public static bool Valid; public static string Planet = ""; public static int LevelId = -1; public static string Interior = ""; public static float Size; public static float LllSize; public static float RefSize; public static float ScrapCount = 1f; public static float ScrapValue = 1f; public static float InsidePower = 1f; public static float OutsidePower = 1f; public static float Traps = 1f; public static float SpawnRate = 1f; public static string Note = ""; public static int Serial; public static bool AnyMultiplier() { if (ScrapCount == 1f && ScrapValue == 1f && InsidePower == 1f && OutsidePower == 1f && Traps == 1f) { return SpawnRate != 1f; } return true; } internal static void ResetMultipliers() { ScrapCount = (ScrapValue = (InsidePower = (OutsidePower = (Traps = (SpawnRate = 1f))))); } internal static void Clear() { Valid = false; Planet = ""; Interior = ""; LevelId = -1; Size = 0f; LllSize = 0f; RefSize = 0f; ResetMultipliers(); Note = ""; Serial++; } } public struct InteriorRule { public float? Mult; public float? Min; public float? Max; public float? Soft; } public static class SizeMath { public const float MinControlledSize = 0.25f; public const float MaxControlledSize = 6f; public static bool IsValidSize(float s) { if (!float.IsNaN(s) && !float.IsInfinity(s)) { return !(s <= 0f); } return false; } public static float Multiplier(float size, float strength, float refSize, float exponent, bool scaleDown, float minMult, float maxMult, bool floorAtOne) { if (float.IsNaN(strength) || float.IsInfinity(strength) || strength <= 0f) { return 1f; } if (!IsValidSize(size) || !IsValidSize(refSize)) { return 1f; } if (float.IsNaN(exponent) || float.IsInfinity(exponent)) { return 1f; } double num = Math.Pow((double)size / (double)refSize, exponent); double num2 = 1.0 + (double)strength * (num - 1.0); if (!scaleDown || floorAtOne) { num2 = Math.Max(num2, 1.0); } double num3 = (float.IsNaN(minMult) ? 0.01 : Math.Max(0.01, Math.Min(minMult, 1f))); double num4 = (float.IsNaN(maxMult) ? 1000.0 : ((double)Math.Max(maxMult, 1f))); if (num2 < num3) { num2 = num3; } if (num2 > num4) { num2 = num4; } if (double.IsNaN(num2) || double.IsInfinity(num2)) { return 1f; } return (float)num2; } public static float ControlSize(float lll, float mapSizeOverride, float sceneMapSize, InteriorRule rule, float globalMin, float globalMax, float globalSoft, out bool applied, out string warning) { applied = false; warning = null; if (!IsValidSize(lll)) { return lll; } double num = lll; if (mapSizeOverride > 0f && IsValidSize(mapSizeOverride) && IsValidSize(sceneMapSize)) { num *= (double)mapSizeOverride / (double)sceneMapSize; applied = true; } if (rule.Mult.HasValue && IsValidSize(rule.Mult.Value)) { num *= (double)rule.Mult.Value; applied = true; } float num2 = rule.Min ?? globalMin; float num3 = rule.Max ?? globalMax; float num4 = rule.Soft ?? globalSoft; if (float.IsNaN(num2) || num2 < 0f) { num2 = 0f; } if (float.IsNaN(num3) || num3 < 0f) { num3 = 0f; } if (float.IsNaN(num4)) { num4 = 0f; } num4 = Math.Max(0f, Math.Min(1f, num4)); if (num2 > 0f && num3 > 0f && num2 > num3) { warning = "min size " + F2(num2) + " is above max size " + F2(num3) + "; min ignored"; num2 = 0f; } if (num3 > 0f && num > (double)num3) { num = (double)num3 + (num - (double)num3) * (double)num4; applied = true; } if (num2 > 0f && num < (double)num2) { num = (double)num2 - ((double)num2 - num) * (double)num4; applied = true; } if (!applied) { return lll; } if (double.IsNaN(num) || double.IsInfinity(num)) { applied = false; return lll; } num = Math.Max(0.25, Math.Min(6.0, num)); return (float)Math.Round(num, 2, MidpointRounding.AwayFromZero); } public static HashSet<string> ParseNameList(string text) { HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); if (string.IsNullOrEmpty(text)) { return hashSet; } string[] array = text.Split(','); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (text2.Length > 0) { hashSet.Add(text2); } } return hashSet; } public static Dictionary<string, float> ParseFactorMap(string text, List<string> errors) { Dictionary<string, float> dictionary = new Dictionary<string, float>(StringComparer.OrdinalIgnoreCase); if (string.IsNullOrEmpty(text)) { return dictionary; } string[] array = text.Split(';'); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (text2.Length == 0) { continue; } int num = text2.LastIndexOf('='); if (num <= 0) { errors?.Add("'" + text2 + "' has no '='"); continue; } string text3 = text2.Substring(0, num).Trim(); string s = text2.Substring(num + 1).Trim(); if (text3.Length == 0 || !TryParse(s, out var f) || !IsValidSize(f)) { errors?.Add("'" + text2 + "' needs a positive number after '='"); } else { dictionary[text3] = f; } } return dictionary; } public static Dictionary<string, InteriorRule> ParseRules(string text, List<string> errors) { Dictionary<string, InteriorRule> dictionary = new Dictionary<string, InteriorRule>(StringComparer.OrdinalIgnoreCase); if (string.IsNullOrEmpty(text)) { return dictionary; } string[] array = text.Split(';'); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (text2.Length == 0) { continue; } int num = text2.LastIndexOf('='); if (num <= 0) { errors?.Add("'" + text2 + "' has no '='"); continue; } string text3 = text2.Substring(0, num).Trim(); if (text3.Length == 0) { errors?.Add("'" + text2 + "' has no name"); continue; } string[] array2 = text2.Substring(num + 1).Split(','); if (array2.Length > 4) { errors?.Add("'" + text2 + "' has more than 4 values; extra ignored"); } InteriorRule value = new InteriorRule { Mult = Field(array2, 0, text2, "mult", errors), Min = Field(array2, 1, text2, "min", errors), Max = Field(array2, 2, text2, "max", errors), Soft = Field(array2, 3, text2, "softness", errors) }; if (value.Mult.HasValue && !IsValidSize(value.Mult.Value)) { errors?.Add("'" + text2 + "': mult must be above 0; ignored"); value.Mult = null; } if (value.Min.HasValue && value.Min.Value < 0f) { value.Min = null; } if (value.Max.HasValue && value.Max.Value < 0f) { value.Max = null; } if (value.Soft.HasValue) { value.Soft = Math.Max(0f, Math.Min(1f, value.Soft.Value)); } dictionary[text3] = value; } return dictionary; } private static float? Field(string[] fields, int i, string entry, string what, List<string> errors) { if (i >= fields.Length) { return null; } string text = fields[i].Trim(); if (text.Length == 0 || text == "-") { return null; } if (TryParse(text, out var f) && !float.IsNaN(f) && !float.IsInfinity(f)) { return f; } errors?.Add("'" + entry + "': " + what + " '" + text + "' isn't a number; using the global value"); return null; } public static bool TryParse(string s, out float f) { return float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out f); } public static string F2(float f) { return f.ToString("0.00", CultureInfo.InvariantCulture); } public static string Numberless(string planetName) { if (string.IsNullOrEmpty(planetName)) { return planetName ?? ""; } int i; for (i = 0; i < planetName.Length && (char.IsDigit(planetName[i]) || planetName[i] == '-'); i++) { } string text = planetName.Substring(i).Trim(); if (text.Length <= 0) { return planetName.Trim(); } return text; } }