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 PointGen v1.8.0
PointGen.dll
Decompiled 2 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using DunGen; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.SceneManagement; [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("PointGen")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("PointGen")] [assembly: AssemblyTitle("PointGen")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace PointGen { internal static class Balance { public const int MineshaftId = 4; private static readonly Dictionary<SelectableLevel, float> OrigSize = new Dictionary<SelectableLevel, float>(); private static readonly Dictionary<SelectableLevel, Vector2Int> OrigScrap = new Dictionary<SelectableLevel, Vector2Int>(); public static bool IsArtifice(SelectableLevel level) { if ((Object)(object)level != (Object)null && level.PlanetName != null) { return level.PlanetName.IndexOf("Artifice", StringComparison.OrdinalIgnoreCase) >= 0; } return false; } public static void ApplyArtificeSize(SelectableLevel level) { if (IsArtifice(level)) { if (!OrigSize.ContainsKey(level)) { OrigSize[level] = level.factorySizeMultiplier; } SyncedSettings active = Plugin.Cfg.Active; level.factorySizeMultiplier = (active.ArtificeEnabled ? active.ArtificeSize : OrigSize[level]); Plugin.Debug($"[Balance] Artifice size = {level.factorySizeMultiplier}"); } } public static void ApplyArtificeScrap(SelectableLevel level) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) if (IsArtifice(level)) { if (!OrigScrap.ContainsKey(level)) { OrigScrap[level] = new Vector2Int(level.minScrap, level.maxScrap); } PointGenConfig cfg = Plugin.Cfg; if (cfg.ArtificeEnabled.Value) { level.minScrap = Math.Max(0, cfg.ArtificeMinScrap.Value); level.maxScrap = Math.Max(level.minScrap + 1, cfg.ArtificeMaxScrap.Value); } else { Vector2Int val = OrigScrap[level]; level.minScrap = ((Vector2Int)(ref val)).x; val = OrigScrap[level]; level.maxScrap = ((Vector2Int)(ref val)).y; } Plugin.Debug($"[Balance] Artifice scrap = {level.minScrap}..{level.maxScrap}"); } } } [HarmonyPatch(typeof(RoundManager), "GenerateNewFloor")] internal static class InteriorPatch { private static void Prefix(RoundManager __instance, out List<KeyValuePair<IntWithRarity, int>> __state) { __state = null; try { SelectableLevel currentLevel = __instance.currentLevel; Balance.ApplyArtificeSize(currentLevel); IntWithRarity[] array = (((Object)(object)currentLevel != (Object)null) ? currentLevel.dungeonFlowTypes : null); if (!Plugin.Cfg.Active.NoMineshaft || array == null || array.Length < 2) { return; } int num = 0; IntWithRarity[] array2 = array; foreach (IntWithRarity val in array2) { if (val != null && val.id != 4 && val.rarity > 0) { num += val.rarity; } } if (num <= 0) { return; } __state = new List<KeyValuePair<IntWithRarity, int>>(); array2 = array; foreach (IntWithRarity val2 in array2) { if (val2 != null && val2.id == 4) { __state.Add(new KeyValuePair<IntWithRarity, int>(val2, val2.rarity)); val2.rarity = 0; } } if (__state.Count > 0) { Plugin.Debug("[Balance] Шахта убрана на " + currentLevel.PlanetName); } } catch (Exception ex) { Plugin.Log.LogError((object)("[Balance] InteriorPatch: " + ex)); } } private static Exception Finalizer(Exception __exception, List<KeyValuePair<IntWithRarity, int>> __state) { if (__state != null) { foreach (KeyValuePair<IntWithRarity, int> item in __state) { item.Key.rarity = item.Value; } } return __exception; } } [HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")] internal static class ArtificeScrapPatch { private static void Prefix(RoundManager __instance, out float __state) { __state = -1f; try { SelectableLevel currentLevel = __instance.currentLevel; Balance.ApplyArtificeScrap(currentLevel); if (Plugin.Cfg.ArtificeEnabled.Value && Balance.IsArtifice(currentLevel)) { __state = __instance.scrapValueMultiplier; __instance.scrapValueMultiplier *= Math.Max(0.1f, Plugin.Cfg.ArtificeValueMult.Value); } } catch (Exception ex) { Plugin.Log.LogError((object)("[Balance] ArtificeScrapPatch: " + ex)); } } private static Exception Finalizer(Exception __exception, RoundManager __instance, float __state) { if (__state >= 0f) { __instance.scrapValueMultiplier = __state; } return __exception; } } [HarmonyPatch(typeof(CaveDwellerAI))] internal static class ManeaterPatch { private struct HitState { public bool AdultHit; public int HpBefore; } [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPostfix(CaveDwellerAI __instance) { SyncedSettings active = Plugin.Cfg.Active; int enemyHP = ((EnemyAI)__instance).enemyHP; ((EnemyAI)__instance).enemyHP = Math.Max(1, Mathf.RoundToInt((float)enemyHP * active.ManeaterHPMult)); Plugin.Debug($"[Balance] Людоед HP {enemyHP} -> {((EnemyAI)__instance).enemyHP}"); } [HarmonyPatch("HitEnemy")] [HarmonyPrefix] private static void HitPrefix(CaveDwellerAI __instance, out HitState __state) { __state = new HitState { AdultHit = (((EnemyAI)__instance).currentBehaviourStateIndex != 0 && !((EnemyAI)__instance).inSpecialAnimation && !((EnemyAI)__instance).isEnemyDead), HpBefore = ((EnemyAI)__instance).enemyHP }; } [HarmonyPatch("HitEnemy")] [HarmonyPostfix] private static void HitPostfix(CaveDwellerAI __instance, int force, HitState __state) { SyncedSettings active = Plugin.Cfg.Active; if (!active.ManeaterFullDamage || !__state.AdultHit) { return; } int num = Math.Max(1, Mathf.RoundToInt((float)Math.Max(1, force) * active.ManeaterDamageMult)); int num2 = num - 1; if (num2 > 0) { ((EnemyAI)__instance).enemyHP = ((EnemyAI)__instance).enemyHP - num2; Plugin.Debug($"[Balance] Людоед получил {num} урона, HP {__state.HpBefore} -> {((EnemyAI)__instance).enemyHP}"); if (__state.HpBefore - 1 > 0 && ((EnemyAI)__instance).enemyHP <= 0 && ((NetworkBehaviour)__instance).IsOwner) { ((EnemyAI)__instance).KillEnemyOnOwnerClient(false); } } } } [HarmonyPatch(typeof(GiantKiwiAI))] internal static class SapsuckerPatch { private static bool _eggsPending; [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPostfix(GiantKiwiAI __instance) { SyncedSettings active = Plugin.Cfg.Active; if (active.SapsuckerEnabled) { int enemyHP = ((EnemyAI)__instance).enemyHP; ((EnemyAI)__instance).enemyHP = Math.Max(1, Mathf.RoundToInt((float)enemyHP * active.SapsuckerHPMult)); __instance.chaseAccelerationMultiplier *= active.SapsuckerChaseAccelMult; __instance.protectNestRadius *= active.SapsuckerAggroRangeMult; __instance.pryOpenDoorAnimLength *= active.SapsuckerDoorPryMult; Plugin.Debug($"[Balance] Дятел HP {enemyHP} -> {((EnemyAI)__instance).enemyHP}, " + $"разгон x{active.SapsuckerChaseAccelMult}, радиус гнезда {__instance.protectNestRadius:0.#}"); } } [HarmonyPatch("SpawnNestEggs")] [HarmonyPrefix] private static void SpawnEggsPrefix() { _eggsPending = true; } [HarmonyPatch("SpawnNestEggs")] [HarmonyFinalizer] private static Exception SpawnEggsFinalizer(Exception __exception) { _eggsPending = false; return __exception; } [HarmonyPatch("SpawnEggsClientRpc")] [HarmonyPrefix] private static void EggRpcPrefix(int[] eggScrapValues) { if (!_eggsPending || eggScrapValues == null) { return; } _eggsPending = false; float num = Math.Max(0f, Plugin.Cfg.SapsuckerEggValueMult.Value); if (Plugin.Cfg.SapsuckerEnabled.Value && !(Math.Abs(num - 1f) < 0.001f)) { for (int i = 0; i < eggScrapValues.Length; i++) { int num2 = eggScrapValues[i]; eggScrapValues[i] = Math.Max(1, Mathf.RoundToInt((float)num2 * num)); Plugin.Debug($"[Balance] яйцо {i}: {num2} -> {eggScrapValues[i]}"); } } } [HarmonyPatch("AttackIfThreatened")] [HarmonyPrefix] private static void AggroPrefix(ref float aggroDistance) { SyncedSettings active = Plugin.Cfg.Active; if (active.SapsuckerEnabled) { aggroDistance *= active.SapsuckerAggroRangeMult; } } } [HarmonyPatch(typeof(EnemyAI), "HitEnemyOnLocalClient")] internal static class MeleePatch { private static int _rollFrame = -1; private static bool _rollCrit; private static void Prefix(ref int force, PlayerControllerB playerWhoHit) { if ((Object)(object)playerWhoHit == (Object)null) { return; } GrabbableObject currentlyHeldObjectServer = playerWhoHit.currentlyHeldObjectServer; if ((Object)(object)currentlyHeldObjectServer == (Object)null) { return; } SyncedSettings active = Plugin.Cfg.Active; float num; if (currentlyHeldObjectServer is Shovel) { num = active.ShovelDamageMult; } else { if (!(currentlyHeldObjectServer is KnifeItem)) { return; } num = active.KnifeDamageMult; } if (_rollFrame != Time.frameCount) { _rollFrame = Time.frameCount; _rollCrit = active.CritChance > 0f && Random.value < active.CritChance; } if (_rollCrit) { num *= active.CritMultiplier; } int num2 = force; force = Math.Max(1, Mathf.RoundToInt((float)force * num)); if (force != num2) { Plugin.Debug(string.Format("[Balance] {0}: урон {1} -> {2}{3}", ((object)currentlyHeldObjectServer).GetType().Name, num2, force, _rollCrit ? " (КРИТ)" : "")); } } } internal static class ConfigSync { [CompilerGenerated] private static class <>O { public static HandleNamedMessageDelegate <0>__OnRequest; public static HandleNamedMessageDelegate <1>__OnSettings; } private const string RequestMsg = "PointGen_Request"; private const string SettingsMsg = "PointGen_Settings"; private const byte ProtocolVersion = 7; public static void Register() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown //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_0050: Expected O, but got Unknown NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || singleton.CustomMessagingManager == null) { return; } Plugin.Cfg.UseLocal(); if (singleton.IsServer) { CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager; object obj = <>O.<0>__OnRequest; if (obj == null) { HandleNamedMessageDelegate val = OnRequest; <>O.<0>__OnRequest = val; obj = (object)val; } customMessagingManager.RegisterNamedMessageHandler("PointGen_Request", (HandleNamedMessageDelegate)obj); } else { CustomMessagingManager customMessagingManager2 = singleton.CustomMessagingManager; object obj2 = <>O.<1>__OnSettings; if (obj2 == null) { HandleNamedMessageDelegate val2 = OnSettings; <>O.<1>__OnSettings = val2; obj2 = (object)val2; } customMessagingManager2.RegisterNamedMessageHandler("PointGen_Settings", (HandleNamedMessageDelegate)obj2); } } public unsafe static void RequestFromHost() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null) && !singleton.IsServer && singleton.IsClient && singleton.CustomMessagingManager != null) { FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(1, (Allocator)2, -1); try { byte b = 7; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); singleton.CustomMessagingManager.SendNamedMessage("PointGen_Request", 0uL, val, (NetworkDelivery)3); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } Plugin.Debug("[Sync] запросил настройки у хоста"); } } private unsafe static void OnRequest(ulong clientId, FastBufferReader reader) { //IL_002b: 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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: 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_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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_00e9: 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_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0214: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Unknown result type (might be due to invalid IL or missing references) //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02cc: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e3: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_02fa: Unknown result type (might be due to invalid IL or missing references) //IL_030d: Unknown result type (might be due to invalid IL or missing references) NetworkManager singleton = NetworkManager.Singleton; SyncedSettings syncedSettings = Plugin.Cfg.LocalSettings(); FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, 4096); try { byte b = 7; ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref syncedSettings.Enabled, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.RepeatCostGrowth, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref syncedSettings.FreeCopies, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.NewRoomBonus, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.MinWeightFactor, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.CorridorPenaltyScale, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe(syncedSettings.CorridorKeywords ?? "", false); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref syncedSettings.FallbackAfterAttempts, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref syncedSettings.NoMineshaft, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref syncedSettings.ArtificeEnabled, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.ArtificeSize, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref syncedSettings.ManeaterFullDamage, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.ManeaterDamageMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.ManeaterHPMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref syncedSettings.SapsuckerEnabled, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.SapsuckerHPMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.SapsuckerAggroRangeMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.SapsuckerChaseAccelMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.ShovelDamageMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.KnifeDamageMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.CritChance, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.CritMultiplier, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref syncedSettings.CadaverEnabled, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.CadaverGrowthMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.CadaverSpreadMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.CadaverInfectChanceMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.CadaverInfectionSpeedMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.SapsuckerDoorPryMult, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref syncedSettings.FoxNoShip, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref syncedSettings.FoxReleaseAfter, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref syncedSettings.FoxDropOnlyHeld, default(ForPrimitives)); singleton.CustomMessagingManager.SendNamedMessage("PointGen_Settings", clientId, val, (NetworkDelivery)3); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } Plugin.Debug($"[Sync] отправил настройки клиенту {clientId}"); } private static void OnSettings(ulong senderId, FastBufferReader reader) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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_00b9: 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_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_019d: 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) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_027f: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) try { byte b = default(byte); ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives)); if (b != 7) { Plugin.Log.LogWarning((object)$"[Sync] у хоста другая версия PointGen (протокол {b}), здания могут не совпасть!"); return; } SyncedSettings syncedSettings = new SyncedSettings(); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref syncedSettings.Enabled, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.RepeatCostGrowth, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref syncedSettings.FreeCopies, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.NewRoomBonus, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.MinWeightFactor, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.CorridorPenaltyScale, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe(ref syncedSettings.CorridorKeywords, false); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref syncedSettings.FallbackAfterAttempts, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref syncedSettings.NoMineshaft, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref syncedSettings.ArtificeEnabled, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.ArtificeSize, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref syncedSettings.ManeaterFullDamage, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.ManeaterDamageMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.ManeaterHPMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref syncedSettings.SapsuckerEnabled, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.SapsuckerHPMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.SapsuckerAggroRangeMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.SapsuckerChaseAccelMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.ShovelDamageMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.KnifeDamageMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.CritChance, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.CritMultiplier, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref syncedSettings.CadaverEnabled, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.CadaverGrowthMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.CadaverSpreadMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.CadaverInfectChanceMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.CadaverInfectionSpeedMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.SapsuckerDoorPryMult, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref syncedSettings.FoxNoShip, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<float>(ref syncedSettings.FoxReleaseAfter, default(ForPrimitives)); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref syncedSettings.FoxDropOnlyHeld, default(ForPrimitives)); Plugin.Cfg.UseRemote(syncedSettings); Plugin.Log.LogInfo((object)"[Sync] настройки получены от хоста."); } catch (Exception ex) { Plugin.Log.LogError((object)("[Sync] не удалось прочитать настройки хоста: " + ex)); } } } [HarmonyPatch(typeof(StartOfRound))] internal static class StartOfRoundPatch { [HarmonyPatch("Awake")] [HarmonyPostfix] private static void AwakePostfix() { try { ConfigSync.Register(); } catch (Exception ex) { Plugin.Log.LogError((object)("[Sync] Register: " + ex)); } } [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPostfix() { try { ConfigSync.RequestFromHost(); } catch (Exception ex) { Plugin.Log.LogError((object)("[Sync] Request: " + ex)); } } } [HarmonyPatch(typeof(CadaverGrowthAI))] internal static class CadaverPatch { [HarmonyPatch("Start")] [HarmonyPostfix] private static void StartPostfix(CadaverGrowthAI __instance) { SyncedSettings active = Plugin.Cfg.Active; if (active.CadaverEnabled) { __instance.GrowthChancePerInterval *= active.CadaverGrowthMult; __instance.ChanceToInfectMultiplier *= active.CadaverInfectChanceMult; __instance.InfectionSpeedMultiplier *= active.CadaverInfectionSpeedMult; Plugin.Debug($"[Fix] Cadaver: рост x{active.CadaverGrowthMult}, распространение x{active.CadaverSpreadMult}, " + $"шанс заражения x{active.CadaverInfectChanceMult}, скорость заражения x{active.CadaverInfectionSpeedMult}"); } } [HarmonyPatch("GrowInTiles")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> GrowTranspiler(IEnumerable<CodeInstruction> instructions) { //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Expected O, but got Unknown List<CodeInstruction> list = instructions.ToList(); MethodInfo methodInfo = AccessTools.Method(typeof(Mathf), "Clamp", new Type[3] { typeof(float), typeof(float), typeof(float) }, (Type[])null); FieldInfo fieldInfo = AccessTools.Field(typeof(CadaverGrowthAI), "baseSpreadChance"); MethodInfo methodInfo2 = AccessTools.Method(typeof(CadaverPatch), "SpreadFactor", (Type[])null, (Type[])null); int num = 0; for (int i = 2; i < list.Count; i++) { if (CodeInstructionExtensions.Calls(list[i], methodInfo) && CodeInstructionExtensions.LoadsField(list[i - 2], fieldInfo, false)) { list.Insert(i + 1, new CodeInstruction(OpCodes.Call, (object)methodInfo2)); list.Insert(i + 2, new CodeInstruction(OpCodes.Mul, (object)null)); num++; i += 2; } } if (num == 0) { Plugin.Log.LogWarning((object)"[Fix] Cadaver: не нашёл шанс распространения (игра обновилась?). Работают только остальные множители."); } return list; } public static float SpreadFactor() { SyncedSettings active = Plugin.Cfg.Active; if (!active.CadaverEnabled) { return 1f; } return active.CadaverSpreadMult; } } [HarmonyPatch(typeof(RoundManager), "GenerateNewLevelClientRpc")] internal static class MoldDistancePatch { private static void Prefix(RoundManager __instance, ref int moldStartPosition, int[] syncDestroyedMold) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: 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) try { float value = Plugin.Cfg.MoldMinDistanceFromShip.Value; if (value <= 40f || moldStartPosition < 0 || !((NetworkBehaviour)__instance).IsServer || (syncDestroyedMold != null && syncDestroyedMold.Length != 0)) { return; } GameObject[] outsideAINodes = __instance.outsideAINodes; Transform val = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.shipLandingPosition : null); if (outsideAINodes == null || outsideAINodes.Length == 0 || (Object)(object)val == (Object)null || moldStartPosition >= outsideAINodes.Length) { return; } Vector3 position = val.position; if (Vector3.Distance(outsideAINodes[moldStartPosition].transform.position, position) >= value) { return; } int num = moldStartPosition; float num2 = -1f; for (int i = 1; i <= outsideAINodes.Length; i++) { int num3 = (moldStartPosition + i) % outsideAINodes.Length; if (!((Object)(object)outsideAINodes[num3] == (Object)null)) { float num4 = Vector3.Distance(outsideAINodes[num3].transform.position, position); if (num4 >= value) { num = num3; num2 = num4; break; } if (num4 > num2) { num = num3; num2 = num4; } } } Plugin.Debug($"[Fix] Vain Shrouds: узел #{moldStartPosition} слишком близко к кораблю, перенёс на #{num} ({num2:0} м)"); moldStartPosition = num; if ((Object)(object)StartOfRound.Instance.currentLevel != (Object)null) { StartOfRound.Instance.currentLevel.moldStartPosition = num; } } catch (Exception ex) { Plugin.Log.LogError((object)("[Fix] MoldDistancePatch: " + ex)); } } } [HarmonyPatch(typeof(GameNetworkManager), "SaveGameValues")] internal static class SavescumPatch { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = instructions.ToList(); MethodInfo operand = AccessTools.Method(typeof(SavescumPatch), "Threshold", (Type[])null, (Type[])null); int num = 0; for (int i = 0; i < list.Count; i++) { if (list[i].opcode != OpCodes.Ldstr || !(list[i].operand is string text) || !text.Contains("TimesSavescumming")) { continue; } for (int j = i + 1; j < Math.Min(list.Count, i + 40); j++) { if (list[j].opcode == OpCodes.Ldc_I4_4) { list[j].opcode = OpCodes.Call; list[j].operand = operand; num++; break; } } if (num > 0) { break; } } if (num == 0) { Plugin.Log.LogWarning((object)"[Fix] Сейвскам: не нашёл проверку (игра обновилась?), штраф остаётся ванильным."); } else { Plugin.Log.LogInfo((object)"[Fix] Штраф за сейвскам: патч применён."); } return list; } public static int Threshold() { if (!Plugin.Cfg.RemoveSavescumPenalty.Value) { return 4; } return int.MaxValue; } } [HarmonyPatch(typeof(BushWolfEnemy))] internal static class FoxPatch { private static readonly Dictionary<BushWolfEnemy, float> DragStart = new Dictionary<BushWolfEnemy, float>(); private static readonly Dictionary<BushWolfEnemy, float> LastShipReset = new Dictionary<BushWolfEnemy, float>(); private static readonly MethodInfo CancelReel = AccessTools.Method(typeof(BushWolfEnemy), "CancelReelingPlayerIn", (Type[])null, (Type[])null); [HarmonyPatch("Update")] [HarmonyPostfix] private static void UpdatePostfix(BushWolfEnemy __instance) { try { SyncedSettings active = Plugin.Cfg.Active; if (((EnemyAI)__instance).isEnemyDead) { DragStart.Remove(__instance); return; } if ((Object)(object)__instance.draggingPlayer != (Object)null) { if (!DragStart.TryGetValue(__instance, out var value)) { DragStart[__instance] = Time.time; } else if (active.FoxReleaseAfter > 0f && Time.time - value > active.FoxReleaseAfter) { DragStart.Remove(__instance); Release(__instance); Plugin.Debug($"[Fox] отпустила игрока после {active.FoxReleaseAfter:0} с"); } } else { DragStart.Remove(__instance); } if (active.FoxNoShip && ((NetworkBehaviour)__instance).IsOwner) { PlayerControllerB targetPlayer = ((EnemyAI)__instance).targetPlayer; if ((((EnemyAI)__instance).isInsidePlayerShip || ((Object)(object)targetPlayer != (Object)null && targetPlayer.isInHangarShipRoom)) && ((EnemyAI)__instance).currentBehaviourStateIndex != 0 && (!LastShipReset.TryGetValue(__instance, out var value2) || !(Time.time - value2 < 2f))) { LastShipReset[__instance] = Time.time; CancelReel?.Invoke(__instance, null); ((EnemyAI)__instance).SwitchToBehaviourState(0); Plugin.Debug("[Fox] цель в корабле — лиса отступает"); } } } catch (Exception ex) { Plugin.Log.LogError((object)("[Fox] Update: " + ex)); } } private static void Release(BushWolfEnemy fox) { if ((Object)(object)((EnemyAI)fox).enemyType != (Object)null && ((EnemyAI)fox).enemyType.canBeStunned) { ((EnemyAI)fox).SetEnemyStunned(true, 2.5f, (PlayerControllerB)null); return; } CancelReel?.Invoke(fox, null); if (((NetworkBehaviour)fox).IsOwner) { ((EnemyAI)fox).SwitchToBehaviourState(0); } } [HarmonyPatch("Update")] [HarmonyTranspiler] private static IEnumerable<CodeInstruction> DropTranspiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = instructions.ToList(); MethodInfo methodInfo = AccessTools.Method(typeof(PlayerControllerB), "DropAllHeldItemsAndSync", (Type[])null, (Type[])null); MethodInfo operand = AccessTools.Method(typeof(FoxPatch), "DropOnGrab", (Type[])null, (Type[])null); int num = 0; foreach (CodeInstruction item in list) { if (CodeInstructionExtensions.Calls(item, methodInfo)) { item.opcode = OpCodes.Call; item.operand = operand; num++; } } if (num == 0) { Plugin.Log.LogWarning((object)"[Fox] не нашёл сброс предметов при захвате (игра обновилась?)."); } return list; } public static void DropOnGrab(PlayerControllerB player, Vector3 playerPosition, Vector3 itemsPosition, Vector3 itemsRotation, Vector3 cameraPosition, Vector3 cameraRotation) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0014: 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_0017: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (!Plugin.Cfg.Active.FoxDropOnlyHeld) { player.DropAllHeldItemsAndSync(playerPosition, itemsPosition, itemsRotation, cameraPosition, cameraRotation); } else if (player.isHoldingObject && (Object)(object)player.currentlyHeldObjectServer != (Object)null) { player.DiscardHeldObject(false, (NetworkObject)null, default(Vector3), true); } } } [HarmonyPatch(typeof(GiftBoxItem), "GetParentOfGiftObject")] internal static class GiftBoxFix { private static void Postfix(ref Transform __result) { if (!((Object)(object)__result != (Object)null) && Plugin.Cfg.FixGiftBox.Value && (Object)(object)RoundManager.Instance != (Object)null && (Object)(object)RoundManager.Instance.spawnedScrapContainer != (Object)null) { __result = RoundManager.Instance.spawnedScrapContainer; } } } [BepInPlugin("serega.pointgen", "PointGen", "1.8.0")] public class Plugin : BaseUnityPlugin { public const string Guid = "serega.pointgen"; public const string Name = "PointGen"; public const string Version = "1.8.0"; internal static ManualLogSource Log; internal static PointGenConfig Cfg; private void Awake() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Expected O, but got Unknown //IL_0228: Unknown result type (might be due to invalid IL or missing references) Log = ((BaseUnityPlugin)this).Logger; Cfg = new PointGenConfig(((BaseUnityPlugin)this).Config); Harmony val = new Harmony("serega.pointgen"); Type[] array = new Type[18] { typeof(ChanceTablePatch), typeof(GenerateFloorPatch), typeof(ScrapSpawnPatch), typeof(StartOfRoundPatch), typeof(InteriorPatch), typeof(ArtificeScrapPatch), typeof(ManeaterPatch), typeof(SapsuckerPatch), typeof(MeleePatch), typeof(CadaverPatch), typeof(MoldDistancePatch), typeof(SavescumPatch), typeof(NightVisionPatch), typeof(FoggyWeatherPatch), typeof(ZoneFogPatch), typeof(IndoorFogPatch), typeof(FoxPatch), typeof(GiftBoxFix) }; foreach (Type type in array) { try { val.CreateClassProcessor(type).Patch(); } catch (Exception arg) { Log.LogError((object)$"Не удалось применить {type.Name}: {arg}"); } } try { Log.LogInfo((object)$"[Misc] runInBackground в игре: {Application.runInBackground}"); if (Cfg.RunInBackground.Value) { Application.runInBackground = true; } } catch (Exception ex) { Log.LogError((object)("RunInBackground: " + ex)); } try { if (Cfg.CheapLogging.Value) { Application.SetStackTraceLogType((LogType)3, (StackTraceLogType)0); Application.SetStackTraceLogType((LogType)2, (StackTraceLogType)0); Log.LogInfo((object)"[Perf] стек для Log/Warning отключён (ошибки — с полным стеком)."); } } catch (Exception ex2) { Log.LogError((object)("CheapLogging: " + ex2)); } try { GameObject val2 = new GameObject("PointGen_FogScanner"); Object.DontDestroyOnLoad((Object)val2); ((Object)val2).hideFlags = (HideFlags)61; val2.AddComponent<VolumeFogScanner>(); } catch (Exception ex3) { Log.LogError((object)("FogScanner: " + ex3)); } Log.LogInfo((object)"PointGen 1.8.0 загружен."); } internal static void Debug(string msg) { if (Cfg != null && Cfg.DebugLog.Value) { Log.LogInfo((object)msg); } } } public class SyncedSettings { public bool Enabled; public float RepeatCostGrowth; public int FreeCopies; public float NewRoomBonus; public float MinWeightFactor; public float CorridorPenaltyScale; public string CorridorKeywords; public int FallbackAfterAttempts; public bool NoMineshaft; public bool ArtificeEnabled; public float ArtificeSize; public bool ManeaterFullDamage; public float ManeaterDamageMult; public float ManeaterHPMult; public bool SapsuckerEnabled; public float SapsuckerHPMult; public float SapsuckerAggroRangeMult; public float SapsuckerChaseAccelMult; public float ShovelDamageMult; public float KnifeDamageMult; public float CritChance; public float CritMultiplier; public bool CadaverEnabled; public float CadaverGrowthMult; public float CadaverSpreadMult; public float CadaverInfectChanceMult; public float CadaverInfectionSpeedMult; public float SapsuckerDoorPryMult; public bool FoxNoShip; public float FoxReleaseAfter; public bool FoxDropOnlyHeld; [NonSerialized] public string[] ParsedKeywords = new string[0]; public void Parse() { ParsedKeywords = (CorridorKeywords ?? "").ToLowerInvariant().Split(new char[3] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); } } public class PointGenConfig { public readonly ConfigEntry<bool> RoomPointsEnabled; public readonly ConfigEntry<float> RepeatCostGrowth; public readonly ConfigEntry<int> FreeCopies; public readonly ConfigEntry<float> NewRoomBonus; public readonly ConfigEntry<float> MinWeightFactor; public readonly ConfigEntry<float> CorridorPenaltyScale; public readonly ConfigEntry<string> CorridorKeywords; public readonly ConfigEntry<int> FallbackAfterAttempts; public readonly ConfigEntry<bool> ScrapPointsEnabled; public readonly ConfigEntry<float> BudgetScale; public readonly ConfigEntry<float> LootRoomFraction; public readonly ConfigEntry<float> LootRoomBudgetMult; public readonly ConfigEntry<float> LootRoomWeightMult; public readonly ConfigEntry<float> ScrapCost; public readonly ConfigEntry<float> EmptyRoomBonus; public readonly ConfigEntry<float> OverBudgetWeight; public readonly ConfigEntry<bool> NoMineshaft; public readonly ConfigEntry<bool> ArtificeEnabled; public readonly ConfigEntry<float> ArtificeSize; public readonly ConfigEntry<int> ArtificeMinScrap; public readonly ConfigEntry<int> ArtificeMaxScrap; public readonly ConfigEntry<float> ArtificeValueMult; public readonly ConfigEntry<bool> ManeaterFullDamage; public readonly ConfigEntry<float> ManeaterDamageMult; public readonly ConfigEntry<float> ManeaterHPMult; public readonly ConfigEntry<bool> SapsuckerEnabled; public readonly ConfigEntry<float> SapsuckerHPMult; public readonly ConfigEntry<float> SapsuckerAggroRangeMult; public readonly ConfigEntry<float> SapsuckerChaseAccelMult; public readonly ConfigEntry<float> SapsuckerEggValueMult; public readonly ConfigEntry<float> SapsuckerDoorPryMult; public readonly ConfigEntry<bool> FoxNoShip; public readonly ConfigEntry<float> FoxReleaseAfter; public readonly ConfigEntry<bool> FoxDropOnlyHeld; public readonly ConfigEntry<bool> FixGiftBox; public readonly ConfigEntry<float> ShovelDamageMult; public readonly ConfigEntry<float> KnifeDamageMult; public readonly ConfigEntry<float> CritChance; public readonly ConfigEntry<float> CritMultiplier; public readonly ConfigEntry<bool> CadaverEnabled; public readonly ConfigEntry<float> CadaverGrowthMult; public readonly ConfigEntry<float> CadaverSpreadMult; public readonly ConfigEntry<float> CadaverInfectChanceMult; public readonly ConfigEntry<float> CadaverInfectionSpeedMult; public readonly ConfigEntry<float> MoldMinDistanceFromShip; public readonly ConfigEntry<bool> RemoveSavescumPenalty; public readonly ConfigEntry<float> NightVisionRangeMult; public readonly ConfigEntry<float> NightVisionIntensityMult; public readonly ConfigEntry<float> FoggyWeatherMult; public readonly ConfigEntry<float> FogVisibilityMult; public readonly ConfigEntry<bool> RemoveIndoorFog; public readonly ConfigEntry<bool> RunInBackground; public readonly ConfigEntry<bool> CheapLogging; public readonly ConfigEntry<bool> DebugLog; public SyncedSettings Active { get; private set; } public PointGenConfig(ConfigFile cfg) { RoomPointsEnabled = cfg.Bind<bool>("1. Rooms (sync from host)", "Enabled", true, "Система очков для комнат: чем чаще комната уже встречалась, тем она 'дороже' и реже выпадает."); RepeatCostGrowth = cfg.Bind<float>("1. Rooms (sync from host)", "RepeatCostGrowth", 1.5f, "Насколько дорожает комната за каждую лишнюю копию. Стоимость = (1 + X)^копий. 1.5 -> 2-я копия в 2.5 раза реже, 3-я в 6.25 раза."); FreeCopies = cfg.Bind<int>("1. Rooms (sync from host)", "FreeCopies", 1, "Сколько копий одной комнаты разрешено без штрафа."); NewRoomBonus = cfg.Bind<float>("1. Rooms (sync from host)", "NewRoomBonus", 1.5f, "Множитель шанса для комнат, которых ещё ни разу не было в этом здании."); MinWeightFactor = cfg.Bind<float>("1. Rooms (sync from host)", "MinWeightFactor", 0.02f, "Нижний предел множителя. Не ставь 0: генератору иногда нужна именно эта комната, чтобы достроить здание."); CorridorPenaltyScale = cfg.Bind<float>("1. Rooms (sync from host)", "CorridorPenaltyScale", 0.15f, "Какую долю штрафа получают коридоры/лестницы (0 = не штрафовать, 1 = как обычные комнаты)."); CorridorKeywords = cfg.Bind<string>("1. Rooms (sync from host)", "CorridorKeywords", "hall,corridor,tunnel,stair,start,cap,connector", "Если имя тайла содержит одно из этих слов, он считается коридором."); FallbackAfterAttempts = cfg.Bind<int>("1. Rooms (sync from host)", "FallbackAfterAttempts", 3, "Защита от зависаний: если DunGen не смог собрать здание столько раз подряд, штрафы за повторы отключаются до конца этой генерации. 0 = выключить защиту."); ScrapPointsEnabled = cfg.Bind<bool>("2. Scrap (host only)", "Enabled", true, "Система очков для лута: у каждой комнаты свой бюджет, лут растекается по зданию."); BudgetScale = cfg.Bind<float>("2. Scrap (host only)", "BudgetScale", 1.5f, "Бюджет комнаты = справедливая доля (лут луны / число комнат) x это значение. Считается заново на каждой карте, так что работает одинаково на маленьких и больших зданиях."); LootRoomFraction = cfg.Bind<float>("2. Scrap (host only)", "LootRoomFraction", 0.08f, "Доля комнат, которые станут 'лутовыми' (0.08 = примерно каждая двенадцатая, минимум одна, если комнат 5+). 0 = без лутовых комнат."); LootRoomBudgetMult = cfg.Bind<float>("2. Scrap (host only)", "LootRoomBudgetMultiplier", 4f, "Во сколько раз бюджет лутовой комнаты больше обычной."); LootRoomWeightMult = cfg.Bind<float>("2. Scrap (host only)", "LootRoomWeightMultiplier", 5f, "Насколько охотнее лут идёт в лутовую комнату, пока у неё есть бюджет."); ScrapCost = cfg.Bind<float>("2. Scrap (host only)", "ScrapCost", 1f, "Сколько очков тратит один предмет."); EmptyRoomBonus = cfg.Bind<float>("2. Scrap (host only)", "EmptyRoomBonus", 2.5f, "Множитель шанса для комнат без лута."); OverBudgetWeight = cfg.Bind<float>("2. Scrap (host only)", "OverBudgetWeight", 0.08f, "Вес комнаты, которая уже потратила весь бюджет."); NoMineshaft = cfg.Bind<bool>("3. Interiors (sync from host)", "RemoveMineshaft", true, "Убрать Шахту (v60): её шанс на всех лунах раздаётся Фабрике и Особняку, как в v56."); ArtificeEnabled = cfg.Bind<bool>("4. Artifice", "Enabled", true, "Сделать Artifice снова эндгейм-луной."); ArtificeSize = cfg.Bind<float>("4. Artifice", "MapSizeMultiplier", 2f, "[sync] Размер здания. v56 = 2.0, сейчас 1.8."); ArtificeMinScrap = cfg.Bind<int>("4. Artifice", "MinScrap", 31, "[host] Мин. количество лута. v56 = 31, сейчас 26."); ArtificeMaxScrap = cfg.Bind<int>("4. Artifice", "MaxScrap", 37, "[host] Макс. количество лута. v56 = 37, сейчас 30."); ArtificeValueMult = cfg.Bind<float>("4. Artifice", "ScrapValueMultiplier", 1.15f, "[host] Множитель ценности лута на Artifice (1 = как в ванилле)."); ManeaterFullDamage = cfg.Bind<bool>("5. Maneater (sync from host)", "FullDamage", true, "Взрослый Людоед получает полный урон оружия, а не всегда 1 (ванилла режет любой удар до 1)."); ManeaterDamageMult = cfg.Bind<float>("5. Maneater (sync from host)", "DamageMultiplier", 1f, "Множитель урона по взрослому Людоеду."); ManeaterHPMult = cfg.Bind<float>("5. Maneater (sync from host)", "HPMultiplier", 1f, "Множитель здоровья Людоеда (1 = ванилла)."); SapsuckerEnabled = cfg.Bind<bool>("6. Sapsucker (sync from host)", "Enabled", true, "Ребаланс Гигантского дятла (Giant Sapsucker)."); SapsuckerHPMult = cfg.Bind<float>("6. Sapsucker (sync from host)", "HPMultiplier", 0.6f, "Множитель здоровья. Меньше = проще убить."); SapsuckerAggroRangeMult = cfg.Bind<float>("6. Sapsucker (sync from host)", "AggroRangeMultiplier", 0.6f, "Множитель дистанции, с которой он кидается защищать гнездо (<1 = подпускает ближе)."); SapsuckerChaseAccelMult = cfg.Bind<float>("6. Sapsucker (sync from host)", "ChaseAccelerationMultiplier", 0.75f, "Как быстро он разгоняется в погоне (<1 = медленнее, проще убежать)."); SapsuckerEggValueMult = cfg.Bind<float>("6. Sapsucker (sync from host)", "EggValueMultiplier", 2f, "[host] Множитель цены яиц. Ванилла: 40-70 у гнезда рядом с кораблём, 70-120 (иногда до 200) у дальнего."); SapsuckerDoorPryMult = cfg.Bind<float>("6. Sapsucker (sync from host)", "DoorBreakTimeMultiplier", 3f, "Во сколько раз дольше он вскрывает закрытую дверь корабля. 1 = ванилла."); FoxNoShip = cfg.Bind<bool>("12. Kidnapper Fox (sync from host)", "NoShip", true, "Лиса не заходит в корабль и не охотится на тех, кто внутри."); FoxReleaseAfter = cfg.Bind<float>("12. Kidnapper Fox (sync from host)", "ReleaseAfterSeconds", 20f, "Через сколько секунд захвата лиса отпускает игрока. 0 = как в ванилле."); FoxDropOnlyHeld = cfg.Bind<bool>("12. Kidnapper Fox (sync from host)", "DropOnlyHeldItem", true, "При захвате выпадает только предмет в руках, а не весь инвентарь."); FixGiftBox = cfg.Bind<bool>("11. Misc (local)", "FixGiftBox", true, "Исправить ванильный баг: подарок, открытый вне корабля, давал ошибку, и предмет из него мог зависнуть в воздухе у клиентов."); ShovelDamageMult = cfg.Bind<float>("7. Melee (sync from host)", "ShovelDamageMultiplier", 1f, "Базовый урон лопаты и знаков (Stop/Yield) по монстрам. 1 = ванилла."); KnifeDamageMult = cfg.Bind<float>("7. Melee (sync from host)", "KnifeDamageMultiplier", 1f, "Базовый урон ножа по монстрам. 1 = ванилла."); CritChance = cfg.Bind<float>("7. Melee (sync from host)", "CritChance", 0.15f, "Шанс тихого случайного крита лопатой/ножом (0.15 = 15%). 0 = выключить. По игрокам криты не проходят."); CritMultiplier = cfg.Bind<float>("7. Melee (sync from host)", "CritMultiplier", 2f, "Во сколько раз крит сильнее обычного удара."); CadaverEnabled = cfg.Bind<bool>("8. Cadaver Bloom (sync from host)", "Enabled", true, "Ослабить Cadaver Bloom (v80)."); CadaverGrowthMult = cfg.Bind<float>("8. Cadaver Bloom (sync from host)", "GrowthMultiplier", 0.5f, "Рост растений внутри комнаты. Вместе с SpreadMultiplier 0.5 x 0.5 даёт примерно в 4 раза более медленное распространение."); CadaverSpreadMult = cfg.Bind<float>("8. Cadaver Bloom (sync from host)", "SpreadMultiplier", 0.5f, "Шанс перекинуться в соседнюю комнату."); CadaverInfectChanceMult = cfg.Bind<float>("8. Cadaver Bloom (sync from host)", "InfectChanceMultiplier", 0.5f, "Шанс подхватить заражение, стоя в растениях."); CadaverInfectionSpeedMult = cfg.Bind<float>("8. Cadaver Bloom (sync from host)", "InfectionSpeedMultiplier", 0.35f, "Скорость развития заражения. 0.35 = примерно в 3 раза дольше до цветения (в соло ванилла и так даёт x0.45)."); MoldMinDistanceFromShip = cfg.Bind<float>("9. Vain Shrouds / Fox (host only)", "MinDistanceFromShip", 90f, "Мин. расстояние от корабля до места, где начинают расти Vain Shrouds (а с ними живёт Лиса). Ванилла = 40 м."); RemoveSavescumPenalty = cfg.Bind<bool>("9. Vain Shrouds / Fox (host only)", "RemoveSavescumPenalty", true, "Убрать штраф за выход посреди дня: в ванилле с 5-го раза на луне начинают расти Vain Shrouds."); NightVisionRangeMult = cfg.Bind<float>("10. Visibility (local)", "NightVisionRange", 1.5f, "Дальность 'ночного зрения' внутри зданий (в v80 её урезали). 1 = ванилла. Перезапусти лобби после изменения."); NightVisionIntensityMult = cfg.Bind<float>("10. Visibility (local)", "NightVisionBrightness", 1.5f, "Яркость 'ночного зрения' внутри зданий. 1 = ванилла."); FoggyWeatherMult = cfg.Bind<float>("10. Visibility (local)", "FoggyWeatherVisibility", 2f, "Видимость в туманную погоду. 2 = туман вдвое прозрачнее. 1 = ванилла."); FogVisibilityMult = cfg.Bind<float>("10. Visibility (local)", "AmbientFogVisibility", 1.5f, "Видимость в обычном тумане на лунах. 1 = ванилла."); RemoveIndoorFog = cfg.Bind<bool>("10. Visibility (local)", "RemoveIndoorFog", true, "Убрать туман внутри зданий: случайное событие 'туман в здании' (2% в день, 20% при нашествии) и зональный туман внутри."); RunInBackground = cfg.Bind<bool>("11. Misc (local)", "RunInBackground", true, "Игра продолжает работать после альт-таба. Иначе у хоста весь сервер замирает, а на Steam Deck/Proton игра может 'зависнуть' после возврата."); CheapLogging = cfg.Bind<bool>("11. Misc (local)", "CheapLogging", true, "Не собирать стек вызовов для обычных сообщений и предупреждений в логе. Игра спамит сотнями предупреждений (особенно при генерации здания), и на каждое Unity тратит время. Ошибки по-прежнему пишутся с полным стеком."); DebugLog = cfg.Bind<bool>("99. Debug", "DebugLog", false, "Писать подробности в лог BepInEx."); RemoveOrphans(cfg); UseLocal(); } private static void RemoveOrphans(ConfigFile cfg) { try { if (!(AccessTools.Property(typeof(ConfigFile), "OrphanedEntries")?.GetValue(cfg) is IDictionary { Count: >0 } dictionary)) { return; } List<string> list = new List<string>(); foreach (object key in dictionary.Keys) { list.Add(key.ToString()); } dictionary.Clear(); cfg.Save(); ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)string.Format("[Config] удалены устаревшие параметры ({0}): {1}", list.Count, string.Join(", ", list))); } } catch (Exception ex) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)("[Config] не удалось почистить старые параметры: " + ex.Message)); } } } public SyncedSettings LocalSettings() { SyncedSettings syncedSettings = new SyncedSettings(); syncedSettings.Enabled = RoomPointsEnabled.Value; syncedSettings.RepeatCostGrowth = Math.Max(0f, RepeatCostGrowth.Value); syncedSettings.FreeCopies = Math.Max(1, FreeCopies.Value); syncedSettings.NewRoomBonus = Math.Max(0.01f, NewRoomBonus.Value); syncedSettings.MinWeightFactor = Math.Max(0.0001f, MinWeightFactor.Value); syncedSettings.CorridorPenaltyScale = Math.Max(0f, Math.Min(1f, CorridorPenaltyScale.Value)); syncedSettings.CorridorKeywords = CorridorKeywords.Value; syncedSettings.FallbackAfterAttempts = Math.Max(0, FallbackAfterAttempts.Value); syncedSettings.NoMineshaft = NoMineshaft.Value; syncedSettings.ArtificeEnabled = ArtificeEnabled.Value; syncedSettings.ArtificeSize = Math.Max(0.5f, ArtificeSize.Value); syncedSettings.ManeaterFullDamage = ManeaterFullDamage.Value; syncedSettings.ManeaterDamageMult = Math.Max(0f, ManeaterDamageMult.Value); syncedSettings.ManeaterHPMult = Math.Max(0.05f, ManeaterHPMult.Value); syncedSettings.SapsuckerEnabled = SapsuckerEnabled.Value; syncedSettings.SapsuckerHPMult = Math.Max(0.05f, SapsuckerHPMult.Value); syncedSettings.SapsuckerAggroRangeMult = Math.Max(0.1f, SapsuckerAggroRangeMult.Value); syncedSettings.SapsuckerChaseAccelMult = Math.Max(0.1f, SapsuckerChaseAccelMult.Value); syncedSettings.ShovelDamageMult = Math.Max(0f, ShovelDamageMult.Value); syncedSettings.KnifeDamageMult = Math.Max(0f, KnifeDamageMult.Value); syncedSettings.CritChance = Math.Max(0f, Math.Min(1f, CritChance.Value)); syncedSettings.CritMultiplier = Math.Max(1f, CritMultiplier.Value); syncedSettings.CadaverEnabled = CadaverEnabled.Value; syncedSettings.CadaverGrowthMult = Math.Max(0f, CadaverGrowthMult.Value); syncedSettings.CadaverSpreadMult = Math.Max(0f, CadaverSpreadMult.Value); syncedSettings.CadaverInfectChanceMult = Math.Max(0f, CadaverInfectChanceMult.Value); syncedSettings.CadaverInfectionSpeedMult = Math.Max(0.01f, CadaverInfectionSpeedMult.Value); syncedSettings.SapsuckerDoorPryMult = Math.Max(0.1f, SapsuckerDoorPryMult.Value); syncedSettings.FoxNoShip = FoxNoShip.Value; syncedSettings.FoxReleaseAfter = Math.Max(0f, FoxReleaseAfter.Value); syncedSettings.FoxDropOnlyHeld = FoxDropOnlyHeld.Value; syncedSettings.Parse(); return syncedSettings; } public void UseLocal() { Active = LocalSettings(); } public void UseRemote(SyncedSettings s) { s.Parse(); Active = s; } } internal static class RoomPoints { [CompilerGenerated] private static class <>O { public static GenerationStatusDelegate <0>__OnStatusChanged; } private static readonly Dictionary<GameObject, int> Placed = new Dictionary<GameObject, int>(); private static readonly Dictionary<GameObject, bool> TileCache = new Dictionary<GameObject, bool>(); private static readonly Dictionary<GameObject, bool> CorridorCache = new Dictionary<GameObject, bool>(); private static string _cachedKeywords; private static int _attempts; private static DungeonGenerator _hooked; public static bool Fallback { get; private set; } public static void BeginFloor() { _attempts = 0; Fallback = false; Reset("новый этаж"); } private static void OnAttempt() { _attempts++; if (_attempts > 1) { Plugin.Debug($"[Rooms] DunGen перезапускает генерацию, попытка #{_attempts}"); } int fallbackAfterAttempts = Plugin.Cfg.Active.FallbackAfterAttempts; if (!Fallback && fallbackAfterAttempts > 0 && _attempts > fallbackAfterAttempts) { Fallback = true; Plugin.Log.LogWarning((object)$"[Rooms] здание не собралось {fallbackAfterAttempts} раз подряд — штрафы за повторы отключены до конца этой генерации."); } } public static void Reset(string reason) { if (Placed.Count > 0 && Plugin.Cfg.DebugLog.Value) { Plugin.Debug("[Rooms] сброс (" + reason + "). Было: " + Summary()); } Placed.Clear(); } public static bool IsTile(GameObject go) { if ((Object)(object)go == (Object)null) { return false; } if (!TileCache.TryGetValue(go, out var value)) { value = (Object)(object)go.GetComponent<Tile>() != (Object)null; TileCache[go] = value; } return value; } public static bool IsCorridor(GameObject go) { SyncedSettings active = Plugin.Cfg.Active; if (_cachedKeywords != active.CorridorKeywords) { CorridorCache.Clear(); _cachedKeywords = active.CorridorKeywords; } if (!CorridorCache.TryGetValue(go, out var value)) { string name = ((Object)go).name.ToLowerInvariant(); value = active.ParsedKeywords.Any((string k) => name.Contains(k)); CorridorCache[go] = value; } return value; } public static float Factor(GameObject go) { SyncedSettings active = Plugin.Cfg.Active; Placed.TryGetValue(go, out var value); bool flag = IsCorridor(go); float num; if (value == 0) { num = (flag ? 1f : active.NewRoomBonus); } else { int num2 = Math.Max(0, value - active.FreeCopies + 1); float num3 = Mathf.Pow(1f + active.RepeatCostGrowth, (float)num2); num = 1f / num3; if (flag) { num = 1f - active.CorridorPenaltyScale * (1f - num); } } return Mathf.Max(num, active.MinWeightFactor); } public static void RegisterChoice(GameObject go) { Placed.TryGetValue(go, out var value); Placed[go] = value + 1; } public static string Summary() { return string.Join(", ", from p in Placed where (Object)(object)p.Key != (Object)null orderby p.Value descending select $"{((Object)p.Key).name} x{p.Value}"); } [MethodImpl(MethodImplOptions.NoInlining)] public static void HookGenerator(RoundManager rm) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown DungeonGenerator val = (((Object)(object)rm.dungeonGenerator != (Object)null) ? rm.dungeonGenerator.Generator : null); if (val != null && val != _hooked) { object obj = <>O.<0>__OnStatusChanged; if (obj == null) { GenerationStatusDelegate val2 = OnStatusChanged; <>O.<0>__OnStatusChanged = val2; obj = (object)val2; } val.OnGenerationStatusChanged += (GenerationStatusDelegate)obj; _hooked = val; } } private unsafe static void OnStatusChanged(DungeonGenerator generator, GenerationStatus status) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 if ((int)status == 1) { OnAttempt(); } if ((int)status == 1 || (int)status == 3) { Reset("попытка генерации: " + ((object)(*(GenerationStatus*)(&status))/*cast due to .constrained prefix*/).ToString()); } else if ((int)status == 8) { Plugin.Debug("[Rooms] итог: " + Summary()); } } } [HarmonyPatch] internal static class ChanceTablePatch { private struct Saved { public GameObjectChance Entry; public float Main; public float Branch; } private static IEnumerable<MethodBase> TargetMethods() { return (from m in AccessTools.GetDeclaredMethods(typeof(GameObjectChanceTable)) where m.Name == "GetRandom" && m.ReturnType == typeof(GameObjectChance) select m).Cast<MethodBase>(); } private static void Prefix(GameObjectChanceTable __instance, out List<Saved> __state) { __state = null; if (!Plugin.Cfg.Active.Enabled || RoomPoints.Fallback || __instance?.Weights == null || __instance.Weights.Count < 2) { return; } bool flag = false; foreach (GameObjectChance weight in __instance.Weights) { if (weight != null && RoomPoints.IsTile(weight.Value)) { flag = true; break; } } if (!flag) { return; } __state = new List<Saved>(__instance.Weights.Count); foreach (GameObjectChance weight2 in __instance.Weights) { if (weight2 != null && !((Object)(object)weight2.Value == (Object)null) && RoomPoints.IsTile(weight2.Value)) { __state.Add(new Saved { Entry = weight2, Main = weight2.MainPathWeight, Branch = weight2.BranchPathWeight }); float num = RoomPoints.Factor(weight2.Value); weight2.MainPathWeight *= num; weight2.BranchPathWeight *= num; } } } private static void Postfix(GameObjectChance __result, List<Saved> __state) { if (__state != null && __result != null && !((Object)(object)__result.Value == (Object)null)) { RoomPoints.RegisterChoice(__result.Value); } } private static Exception Finalizer(Exception __exception, List<Saved> __state) { if (__state != null) { foreach (Saved item in __state) { item.Entry.MainPathWeight = item.Main; item.Entry.BranchPathWeight = item.Branch; } } return __exception; } } [HarmonyPatch(typeof(RoundManager), "GenerateNewFloor")] internal static class GenerateFloorPatch { private static void Prefix(RoundManager __instance) { RoomPoints.BeginFloor(); try { VolumeFogScanner.RequestScan(8f, 20f); } catch { } try { RoomPoints.HookGenerator(__instance); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Не удалось подписаться на статус DunGen, сброс только по новому этажу: " + ex.Message)); } } } internal static class ScrapPoints { private static readonly Dictionary<RandomScrapSpawn, Object> TileOf = new Dictionary<RandomScrapSpawn, Object>(); private static readonly Dictionary<Object, int> PointsInTile = new Dictionary<Object, int>(); private static readonly Dictionary<Object, float> Spent = new Dictionary<Object, float>(); private static bool _loggedError; private static bool _budgetsReady; private static float _fairShare = 1f; private static readonly HashSet<Object> LootRooms = new HashSet<Object>(); public static void BeginLevel() { TileOf.Clear(); PointsInTile.Clear(); Spent.Clear(); _loggedError = false; _budgetsReady = false; LootRooms.Clear(); RandomScrapSpawn[] array = Object.FindObjectsOfType<RandomScrapSpawn>(); for (int i = 0; i < array.Length; i++) { Object key = KeyFor(array[i]); PointsInTile.TryGetValue(key, out var value); PointsInTile[key] = value + 1; } Plugin.Debug($"[Scrap] комнат с точками спавна: {PointsInTile.Count}, точек: {TileOf.Count}"); } private static Object KeyFor(RandomScrapSpawn sp) { if (TileOf.TryGetValue(sp, out var value)) { return value; } Tile componentInParent = ((Component)sp).GetComponentInParent<Tile>(); value = (Object)(((Object)(object)componentInParent != (Object)null) ? ((object)componentInParent) : ((object)sp)); TileOf[sp] = value; return value; } private static void PrepareBudgets() { if (_budgetsReady) { return; } _budgetsReady = true; PointGenConfig cfg = Plugin.Cfg; RoundManager instance = RoundManager.Instance; SelectableLevel val = (((Object)(object)instance != (Object)null) ? instance.currentLevel : null); int num = Math.Max(1, PointsInTile.Count); float num2 = (((Object)(object)val != (Object)null) ? ((float)(val.minScrap + val.maxScrap) * 0.5f * ((instance.scrapAmountMultiplier > 0f) ? instance.scrapAmountMultiplier : 1f)) : ((float)num)); int num3 = 0; if (num >= 5) { num3 = Math.Max(1, Mathf.RoundToInt((float)num * Mathf.Clamp01(cfg.LootRoomFraction.Value))); } if (num3 > 0 && (Object)(object)val != (Object)null) { Random random = new Random(((Object)(object)StartOfRound.Instance != (Object)null) ? (StartOfRound.Instance.randomMapSeed + 7331) : 7331); List<Object> list = (from p in PointsInTile where p.Value >= 3 select p.Key).ToList(); if (list.Count < num3) { list = (from p in PointsInTile orderby p.Value descending select p.Key).Take(Math.Max(num3, list.Count)).ToList(); } list = list.OrderBy((Object k) => k.GetInstanceID()).ToList(); for (int num4 = list.Count - 1; num4 > 0; num4--) { int index = random.Next(0, num4 + 1); Object value = list[num4]; list[num4] = list[index]; list[index] = value; } foreach (Object item in list.Take(num3)) { LootRooms.Add(item); } } float value2 = cfg.LootRoomBudgetMult.Value; float val2 = (float)(num - LootRooms.Count) + (float)LootRooms.Count * value2; _fairShare = num2 / Math.Max(1f, val2); Plugin.Debug($"[Scrap] ожидается ~{num2:0} предметов на {num} комнат; доля на комнату {_fairShare:0.00}; " + $"лутовых комнат: {LootRooms.Count} (" + string.Join(", ", LootRooms.Select((Object k) => (!(k != (Object)null)) ? "?" : k.name)) + ")"); } private static float Budget(Object key) { PointGenConfig cfg = Plugin.Cfg; PointsInTile.TryGetValue(key, out var value); float val = ((PointsInTile.Count > 0) ? ((float)PointsInTile.Values.Average()) : 1f); float num = Mathf.Clamp(Mathf.Sqrt((float)Math.Max(1, value) / Math.Max(1f, val)), 0.6f, 1.6f); float num2 = Math.Max(1f, _fairShare * cfg.BudgetScale.Value * num); if (LootRooms.Contains(key)) { num2 *= cfg.LootRoomBudgetMult.Value; } return num2; } public static RandomScrapSpawn Pick(List<RandomScrapSpawn> list, int rolledIndex) { PointGenConfig cfg = Plugin.Cfg; if (cfg == null || !cfg.ScrapPointsEnabled.Value || list == null || list.Count <= 1) { return list[rolledIndex]; } try { PrepareBudgets(); int count = list.Count; Object[] array = (Object[])(object)new Object[count]; Dictionary<Object, int> dictionary = new Dictionary<Object, int>(); for (int i = 0; i < count; i++) { array[i] = (((Object)(object)list[i] != (Object)null) ? KeyFor(list[i]) : null); if (!(array[i] == (Object)null)) { dictionary.TryGetValue(array[i], out var value); dictionary[array[i]] = value + 1; } } float[] array2 = new float[count]; float num = 0f; for (int j = 0; j < count; j++) { if (!(array[j] == (Object)null)) { Object val = array[j]; Spent.TryGetValue(val, out var value2); float num2 = Budget(val) - value2; float num3 = ((num2 > 0f) ? num2 : cfg.OverBudgetWeight.Value); if (value2 <= 0f) { num3 *= cfg.EmptyRoomBonus.Value; } if (LootRooms.Contains(val) && num2 > 0f) { num3 *= cfg.LootRoomWeightMult.Value; } float num4 = num3 / (float)dictionary[val]; if (list[j].spawnUsed) { num4 *= 0.01f; } array2[j] = Mathf.Max(num4, 0f); num += array2[j]; } } if (num <= 0f) { return list[rolledIndex]; } float num5 = ((float)rolledIndex + 0.5f) / (float)count * num; int num6 = count - 1; float num7 = 0f; for (int k = 0; k < count; k++) { num7 += array2[k]; if (num5 < num7) { num6 = k; break; } } if (array[num6] != (Object)null) { Spent.TryGetValue(array[num6], out var value3); Spent[array[num6]] = value3 + cfg.ScrapCost.Value; } return list[num6]; } catch (Exception ex) { if (!_loggedError) { Plugin.Log.LogError((object)("[Scrap] ошибка, использую ванильный выбор: " + ex)); _loggedError = true; } return list[rolledIndex]; } } public static void LogResult() { if (!Plugin.Cfg.DebugLog.Value) { return; } int num = PointsInTile.Keys.Count((Object k) => !Spent.ContainsKey(k)); if (LootRooms.Count > 0) { Plugin.Debug("[Scrap] в лутовых комнатах: " + string.Join(", ", LootRooms.Select((Object k) => string.Format("{0}={1:0.#}", (k != (Object)null) ? k.name : "?", Spent.TryGetValue(k, out var value) ? value : 0f)))); } Plugin.Debug($"[Scrap] комнат с лутом: {Spent.Count}, пустых комнат с точками спавна: {num}. " + "Распределение: " + string.Join(", ", from p in Spent orderby p.Value descending select string.Format("{0}={1:0.#}", (p.Key != (Object)null) ? p.Key.name : "?", p.Value))); } } [HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")] internal static class ScrapSpawnPatch { private static void Prefix() { try { ScrapPoints.BeginLevel(); } catch (Exception ex) { Plugin.Log.LogError((object)("[Scrap] BeginLevel: " + ex)); } } private static void Postfix() { try { ScrapPoints.LogResult(); } catch { } } private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> list = instructions.ToList(); MethodInfo methodInfo = AccessTools.PropertyGetter(typeof(List<RandomScrapSpawn>), "Item"); MethodInfo next = AccessTools.Method(typeof(Random), "Next", new Type[2] { typeof(int), typeof(int) }, (Type[])null); MethodInfo operand = AccessTools.Method(typeof(ScrapPoints), "Pick", (Type[])null, (Type[])null); int num = 0; for (int i = 1; i < list.Count; i++) { if (CodeInstructionExtensions.Calls(list[i], methodInfo) && IndexIsRandom(list, i, next)) { list[i].opcode = OpCodes.Call; list[i].operand = operand; num++; } } if (num == 0) { Plugin.Log.LogWarning((object)"[Scrap] не нашёл выбор точки спавна в SpawnScrapInLevel (игра обновилась?). Распределение лута будет ванильным, генерация комнат работает."); } else { Plugin.Log.LogInfo((object)$"[Scrap] патч выбора точек спавна применён ({num} мест)."); } return list; } private static bool IndexIsRandom(List<CodeInstruction> codes, int getItemIdx, MethodInfo next) { CodeInstruction val = codes[getItemIdx - 1]; if (CodeInstructionExtensions.Calls(val, next)) { return true; } int num = LocalIndex(val, load: true); if (num < 0) { return false; } for (int num2 = getItemIdx - 2; num2 >= Math.Max(1, getItemIdx - 12); num2--) { if (LocalIndex(codes[num2], load: false) == num && CodeInstructionExtensions.Calls(codes[num2 - 1], next)) { return true; } } return false; } private static int LocalIndex(CodeInstruction ci, bool load) { OpCode opcode = ci.opcode; if (load) { if (opcode == OpCodes.Ldloc_0) { return 0; } if (opcode == OpCodes.Ldloc_1) { return 1; } if (opcode == OpCodes.Ldloc_2) { return 2; } if (opcode == OpCodes.Ldloc_3) { return 3; } if (opcode != OpCodes.Ldloc && opcode != OpCodes.Ldloc_S) { return -1; } } else { if (opcode == OpCodes.Stloc_0) { return 0; } if (opcode == OpCodes.Stloc_1) { return 1; } if (opcode == OpCodes.Stloc_2) { return 2; } if (opcode == OpCodes.Stloc_3) { return 3; } if (opcode != OpCodes.Stloc && opcode != OpCodes.Stloc_S) { return -1; } } object operand = ci.operand; if (!(operand is LocalBuilder localBuilder)) { if (operand is int) { return (int)operand; } if (operand is byte) { return (byte)operand; } if (operand is short) { return (short)operand; } return -1; } return localBuilder.LocalIndex; } } internal static class Visibility { public static float FogFactor => Math.Max(0.1f, Plugin.Cfg.FogVisibilityMult.Value); } [HarmonyPatch(typeof(PlayerControllerB), "SetNightVisionEnabled")] internal static class NightVisionPatch { private struct Orig { public float Range; public float Intensity; } private static readonly Dictionary<Light, Orig> Originals = new Dictionary<Light, Orig>(); private static void Postfix(PlayerControllerB __instance) { try { Light nightVision = __instance.nightVision; if (!((Object)(object)nightVision == (Object)null) && !Originals.ContainsKey(nightVision)) { HDAdditionalLightData component = ((Component)nightVision).GetComponent<HDAdditionalLightData>(); Orig value = new Orig { Range = (((Object)(object)component != (Object)null) ? component.range : nightVision.range), Intensity = (((Object)(object)component != (Object)null) ? component.intensity : nightVision.intensity) }; Originals[nightVision] = value; float num = Math.Max(0.1f, Plugin.Cfg.NightVisionRangeMult.Value); float num2 = Math.Max(0.1f, Plugin.Cfg.NightVisionIntensityMult.Value); if ((Object)(object)component != (Object)null) { component.range = value.Range * num; component.intensity = value.Intensity * num2; } else { nightVision.range = value.Range * num; nightVision.intensity = value.Intensity * num2; } Plugin.Debug($"[Vision] ночное зрение: дальность {value.Range:0.#} -> {value.Range * num:0.#}, яркость x{num2}"); } } catch (Exception ex) { Plugin.Log.LogError((object)("[Vision] NightVisionPatch: " + ex)); } } } [HarmonyPatch(typeof(TimeOfDay), "SetWeatherBasedOnVariables")] internal static class FoggyWeatherPatch { private static void Postfix(TimeOfDay __instance) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 try { if ((int)__instance.currentLevelWeather == 3 && !((Object)(object)__instance.foggyWeather == (Object)null)) { float meanFreePath = __instance.foggyWeather.parameters.meanFreePath; __instance.foggyWeather.parameters.meanFreePath = meanFreePath * Math.Max(0.1f, Plugin.Cfg.FoggyWeatherMult.Value); Plugin.Debug($"[Vision] туманная погода: {meanFreePath:0.#} -> {__instance.foggyWeather.parameters.meanFreePath:0.#}"); } } catch (Exception ex) { Plugin.Log.LogError((object)("[Vision] FoggyWeatherPatch: " + ex)); } } } [HarmonyPatch(typeof(AudioReverbTrigger), "Start")] internal static class ZoneFogPatch { private static void Postfix(AudioReverbTrigger __instance) { if (!((Object)(object)__instance.localFog == (Object)null)) { if (__instance.insideLighting && Plugin.Cfg.RemoveIndoorFog.Value) { __instance.toggleLocalFog = false; } else { __instance.fogEnabledAmount *= Visibility.FogFactor; } } } } [HarmonyPatch(typeof(RoundManager), "RefreshEnemiesList")] internal static class IndoorFogPatch { private static void Postfix(RoundManager __instance) { try { if (Plugin.Cfg.RemoveIndoorFog.Value && !((Object)(object)__instance.indoorFog == (Object)null)) { GameObject gameObject = ((Component)__instance.indoorFog).gameObject; if (gameObject.activeSelf) { gameObject.SetActive(false); Plugin.Debug("[Vision] выпал туман в здании — выключен"); } } } catch (Exception ex) { Plugin.Log.LogError((object)("[Vision] IndoorFogPatch: " + ex)); } } } internal class VolumeFogScanner : MonoBehaviour { private static VolumeFogScanner _instance; private readonly HashSet<VolumeProfile> _done = new HashSet<VolumeProfile>(); private readonly List<float> _scheduled = new List<float>(); private void Awake() { _instance = this; SceneManager.sceneLoaded += delegate { RequestScan(1f, 4f); }; } public static void RequestScan(params float[] delays) { if (!((Object)(object)_instance == (Object)null)) { foreach (float num in delays) { _instance._scheduled.Add(Time.unscaledTime + num); } } } private void Update() { if (_scheduled.Count == 0) { return; } bool flag = false; for (int num = _scheduled.Count - 1; num >= 0; num--) { if (Time.unscaledTime >= _scheduled[num]) { _scheduled.RemoveAt(num); flag = true; } } if (flag) { Scan(); } } private void Scan() { if (Math.Abs(Visibility.FogFactor - 1f) < 0.001f) { return; } try { Volume[] array = Object.FindObjectsOfType<Volume>(); Fog val = default(Fog); for (int i = 0; i < array.Length; i++) { VolumeProfile sharedProfile = array[i].sharedProfile; if (!((Object)(object)sharedProfile == (Object)null) && !_done.Contains(sharedProfile)) { _done.Add(sharedProfile); if (sharedProfile.TryGet<Fog>(ref val) && (Object)(object)val != (Object)null) { float value = ((VolumeParameter<float>)(object)val.meanFreePath).value; ((VolumeParameter<float>)(object)val.meanFreePath).value = value * Visibility.FogFactor; Plugin.Debug($"[Vision] туман '{((Object)sharedProfile).name}': {value:0.#} -> {((VolumeParameter<float>)(object)val.meanFreePath).value:0.#}"); } } } } catch (Exception ex) { Plugin.Log.LogError((object)("[Vision] VolumeFogScanner: " + ex)); ((Behaviour)this).enabled = false; } } } }