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 SansaraDungeons v0.2.0
plugins/SansaraDungeons.dll
Decompiled a week 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 HarmonyLib; using Microsoft.CodeAnalysis; using SansaraDungeons.Core; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: AssemblyCompany("SansaraDungeons")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.2.0.0")] [assembly: AssemblyInformationalVersion("0.2.0+a3c9c8b848cbf8391cf78563911266dad9d3b1fc")] [assembly: AssemblyProduct("SansaraDungeons")] [assembly: AssemblyTitle("SansaraDungeons")] [assembly: AssemblyVersion("0.2.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 SansaraDungeons { [HarmonyPatch] internal static class Diagnostics { internal static bool Active; private static readonly Stopwatch Watch = new Stopwatch(); internal static double SetupStart; internal static double SetupEnd; internal static double RoomsStart; internal static double RoomsEnd; internal static double SnapMs; internal static double SaveMs; private static double _snap0; private static double _save0; internal static double Now => Watch.Elapsed.TotalMilliseconds; internal static void Begin() { SetupStart = (SetupEnd = (RoomsStart = (RoomsEnd = (SnapMs = (SaveMs = 0.0))))); Watch.Restart(); } [HarmonyPatch(typeof(DungeonGenerator), "SetupAvailableRooms")] [HarmonyPrefix] private static void SetupPrefix() { if (Active && SetupStart == 0.0) { SetupStart = Now; } } [HarmonyPatch(typeof(DungeonGenerator), "SetupAvailableRooms")] [HarmonyPostfix] [HarmonyPriority(0)] private static void SetupPostfix() { if (Active && SetupEnd == 0.0) { SetupEnd = Now; } } [HarmonyPatch(typeof(DungeonGenerator), "GenerateRooms")] [HarmonyPrefix] [HarmonyPriority(800)] private static void RoomsPrefix() { if (Active) { RoomsStart = Now; } } [HarmonyPatch(typeof(DungeonGenerator), "GenerateRooms")] [HarmonyPostfix] private static void RoomsPostfix() { if (Active) { RoomsEnd = Now; } } [HarmonyPatch(typeof(SnapToGround), "SnappAll")] [HarmonyPrefix] private static void SnapPrefix() { if (Active) { _snap0 = Now; } } [HarmonyPatch(typeof(SnapToGround), "SnappAll")] [HarmonyPostfix] private static void SnapPostfix() { if (Active) { SnapMs += Now - _snap0; } } [HarmonyPatch(typeof(DungeonGenerator), "Save")] [HarmonyPrefix] private static void SavePrefix() { if (Active) { _save0 = Now; } } [HarmonyPatch(typeof(DungeonGenerator), "Save")] [HarmonyPostfix] private static void SavePostfix() { if (Active) { SaveMs += Now - _save0; } } internal static string Describe(double total) { return $"до SetupAvailableRooms {SetupStart:0}, SetupAvailableRooms {SetupEnd - SetupStart:0}, загрузка комнат и журнал {RoomsStart - SetupEnd:0}, " + $"раскладка {RoomsEnd - RoomsStart:0}, после раскладки {total - RoomsEnd:0} (из них Save {SaveMs:0}, SnappAll {SnapMs:0}), всего {total:0} мс"; } } [HarmonyPatch] internal static class GeneratorPatches { private sealed class Context { public DungeonGenerator Gen; public DungeonProfile Profile; public bool Quiet; public Stopwatch Watch; public int Seed; public Vector3 ZoneSize; public Vector3 ZoneCenter; public int MaxRooms; public int MinRooms; public int MinRequired; public bool Alternative; public Theme Themes; public List<string> RequiredRooms; public bool RequiredReplaced; public readonly List<KeyValuePair<Room, float>> Weights = new List<KeyValuePair<Room, float>>(); public List<RoomData> Available; public bool ChambersExcluded; public int Attempts; public bool InEndCaps; public readonly HashSet<RoomConnection> Capped = new HashSet<RoomConnection>(); public int FailedEndCaps; public LayoutStats Result; public bool Trialled; public int Trials = 1; public int Chosen; public bool TargetMet = true; public string ChosenPrint; public int TrialZdos; public double TrialMs; public double LayoutMs; public readonly Stopwatch Layout = new Stopwatch(); public readonly List<RoomData> Held = new List<RoomData>(); public void ResetPass() { Weights.Clear(); Available = null; ChambersExcluded = false; Attempts = 0; InEndCaps = false; Capped.Clear(); FailedEndCaps = 0; Result = null; } } private static Context _ctx; private static bool _dry; internal static LayoutStats LastResult; private static readonly HashSet<string> Warned = new HashSet<string>(StringComparer.Ordinal); private static List<RoomData> _available; private static List<Room> _placed; private static List<RoomConnection> _open; private static readonly MethodInfo AddOpenConnections = AccessTools.Method(typeof(DungeonGenerator), "AddOpenConnections", (Type[])null, (Type[])null); private static List<RoomData> Available => _available ?? (_available = (List<RoomData>)StaticField("m_availableRooms")); private static List<Room> Placed => _placed ?? (_placed = (List<Room>)StaticField("m_placedRooms")); private static List<RoomConnection> Open => _open ?? (_open = (List<RoomConnection>)StaticField("m_openConnections")); private static object StaticField(string name) { return (AccessTools.Field(typeof(DungeonGenerator), name) ?? throw new MissingFieldException("DungeonGenerator", name)).GetValue(null); } private static bool IsMine(DungeonGenerator gen) { if (_ctx != null) { return (Object)(object)_ctx.Gen == (Object)(object)gen; } return false; } private static bool IsDry(DungeonGenerator gen) { if (_dry) { return IsMine(gen); } return false; } [HarmonyPatch(typeof(DungeonGenerator), "Generate", new Type[] { typeof(int), typeof(SpawnMode) })] [HarmonyPrefix] private static void GeneratePrefix(DungeonGenerator __instance, ref int seed, SpawnMode mode) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 //IL_00c7: 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_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: 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_0160: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Invalid comparison between Unknown and I4 //IL_0081: Expected I4, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Unknown result type (might be due to invalid IL or missing references) if (_dry) { if (IsMine(__instance)) { _ctx.ResetPass(); } return; } try { _ctx = null; if ((int)mode == 1 || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } bool quiet; DungeonProfile dungeonProfile = Measurement.ProfileFor(__instance, out quiet); if (dungeonProfile == null) { if (!PluginConfig.Enabled || !PluginConfig.ForestCryptEnabled || ProfileMatcher.Match(Utils.GetPrefabName(((Component)__instance).gameObject), (int)__instance.m_themes, (int)__instance.m_algorithm == 0) != "ForestCrypt") { return; } dungeonProfile = PluginConfig.ForestCrypt; } Context context = (_ctx = new Context { Gen = __instance, Profile = dungeonProfile, Quiet = quiet, Watch = Stopwatch.StartNew(), Seed = seed, ZoneSize = __instance.m_zoneSize, ZoneCenter = __instance.m_zoneCenter, MaxRooms = __instance.m_maxRooms, MinRooms = __instance.m_minRooms, MinRequired = __instance.m_minRequiredRooms, Alternative = __instance.m_alternativeFunctionality, Themes = __instance.m_themes, RequiredRooms = __instance.m_requiredRooms }); if (dungeonProfile.ZoneHeight.HasValue) { __instance.m_zoneSize = new Vector3(context.ZoneSize.x, dungeonProfile.ZoneHeight.Value, context.ZoneSize.z); } if (dungeonProfile.Attempts.HasValue) { __instance.m_maxRooms = dungeonProfile.Attempts.Value; } if (dungeonProfile.MinRooms.HasValue) { __instance.m_minRooms = dungeonProfile.MinRooms.Value; } if (dungeonProfile.UseWeights.HasValue) { __instance.m_alternativeFunctionality = dungeonProfile.UseWeights.Value; } foreach (string extraTheme in dungeonProfile.ExtraThemes) { if (Enum.TryParse<Theme>(extraTheme, ignoreCase: false, out Theme result) && (int)result != 0) { __instance.m_themes |= result; } else { WarnOnce("theme:" + extraTheme, "ExtraThemes: неизвестная тема «" + extraTheme + "» — пропущена."); } } if (dungeonProfile.RetriesActive) { HoldRooms(context); seed = RunTrials(context, seed, mode); } context.ResetPass(); } catch (Exception ex) { Plugin.Log.LogError((object)("Подготовка генератора: " + ex)); Restore(); } } private static void HoldRooms(Context c) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) foreach (RoomData room in DungeonDB.GetRooms()) { if ((room.m_theme & c.Gen.m_themes) != 0 && room.m_enabled) { room.m_prefab.Load(); c.Held.Add(room); } } } private static int RunTrials(Context c, int seed, SpawnMode mode) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) DungeonProfile profile = c.Profile; List<SeedTrial> list = new List<SeedTrial>(); List<string> list2 = new List<string>(); uint num = (ZdoIds.Available ? ZdoIds.Next : 0u); Stopwatch stopwatch = Stopwatch.StartNew(); _dry = true; try { for (int i = 0; i <= profile.Retries; i++) { int num2 = RetryPolicy.SeedFor(seed, i); c.ResetPass(); c.Gen.Generate(num2, mode); c.Gen.Clear(); LayoutStats layoutStats = c.Result ?? throw new InvalidOperationException("пробная раскладка без сводки"); SeedTrial seedTrial = new SeedTrial(num2, layoutStats.Total, layoutStats.Chambers); list.Add(seedTrial); list2.Add(layoutStats.Fingerprint); if (RetryPolicy.Meets(seedTrial, profile.TargetRooms, profile.TargetChambers)) { break; } } } catch (Exception ex) { Plugin.Log.LogError((object)("Пробная раскладка: " + ex?.ToString() + " — строю с исходным зерном.")); try { c.Gen.Clear(); } catch (Exception) { } list.Clear(); } finally { _dry = false; c.TrialMs = stopwatch.Elapsed.TotalMilliseconds; if (ZdoIds.Available) { c.TrialZdos = (int)(ZdoIds.Next - num); } } if (list.Count == 0) { return seed; } int num3 = RetryPolicy.PickBest(list, profile.TargetRooms, profile.TargetChambers); c.Trialled = true; c.Trials = list.Count; c.Chosen = num3; c.TargetMet = RetryPolicy.Meets(list[num3], profile.TargetRooms, profile.TargetChambers); c.ChosenPrint = list2[num3]; if (c.TrialZdos != 0) { Plugin.Log.LogError((object)$"Пробные раскладки создали {c.TrialZdos} ZDO — так быть не должно."); } return list[num3].Seed; } [HarmonyPatch(typeof(DungeonGenerator), "Generate", new Type[] { typeof(int), typeof(SpawnMode) })] [HarmonyFinalizer] private static void GenerateFinalizer(DungeonGenerator __instance, Exception __exception) { //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) if (_dry || !IsMine(__instance)) { return; } Context ctx = _ctx; Restore(); ctx.Watch.Stop(); LayoutStats result = ctx.Result; if (result != null) { result.RetriesActive = ctx.Profile.RetriesActive; result.SeedTrials = ctx.Trials; result.ChosenTrial = ctx.Chosen; result.TargetMet = ctx.TargetMet; result.TrialZdos = ctx.TrialZdos; result.TrialMs = ctx.TrialMs; result.LayoutMs = ctx.LayoutMs; if (ctx.Trialled) { string text = SavedFingerprint(__instance); result.MatchesTrial = ((text == ctx.ChosenPrint) ? 1 : 0); if (result.MatchesTrial == 0) { Plugin.Log.LogWarning((object)("Раскладка склепа не совпала с пробной: построено " + text + ", проба " + ctx.ChosenPrint + ".")); } } } LastResult = result; if (__exception == null && result != null && !ctx.Quiet) { Vector3 position = ((Component)__instance).transform.position; Plugin.Log.LogInfo((object)($"Склеп {Utils.GetPrefabName(((Component)__instance).gameObject)} ({position.x:0}, {position.z:0}), зерно {ctx.Seed}: " + $"{result.Describe()}, {ctx.Watch.Elapsed.TotalMilliseconds:0} мс")); } } private static string SavedFingerprint(DungeonGenerator gen) { ZNetView component = ((Component)gen).GetComponent<ZNetView>(); ZDO val = ((component != null) ? component.GetZDO() : null); byte[] buffer = default(byte[]); if (val == null || !val.GetByteArray(ZDOVars.s_roomData, ref buffer)) { return "нет roomData"; } LayoutFingerprint layoutFingerprint = new LayoutFingerprint(); using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(buffer))) { int num = binaryReader.ReadInt32(); for (int i = 0; i < num; i++) { int roomHash = binaryReader.ReadInt32(); float px = binaryReader.ReadSingle(); float py = binaryReader.ReadSingle(); float pz = binaryReader.ReadSingle(); float ex = binaryReader.ReadSingle(); float ey = binaryReader.ReadSingle(); float ez = binaryReader.ReadSingle(); layoutFingerprint.Add(roomHash, px, py, pz, ex, ey, ez); } } return layoutFingerprint.Value; } private static void Restore() { //IL_006c: 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_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: 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) Context ctx = _ctx; _ctx = null; if (ctx == null) { return; } foreach (RoomData item in ctx.Held) { item.m_prefab.Release(); } ctx.Held.Clear(); DungeonGenerator gen = ctx.Gen; if ((Object)(object)gen == (Object)null) { RestoreRooms(ctx); return; } gen.m_zoneSize = ctx.ZoneSize; gen.m_zoneCenter = ctx.ZoneCenter; gen.m_maxRooms = ctx.MaxRooms; gen.m_minRooms = ctx.MinRooms; gen.m_minRequiredRooms = ctx.MinRequired; gen.m_alternativeFunctionality = ctx.Alternative; gen.m_themes = ctx.Themes; if (ctx.RequiredReplaced) { gen.m_requiredRooms = ctx.RequiredRooms; } RestoreRooms(ctx); } [HarmonyPatch(typeof(DungeonGenerator), "GenerateRooms")] [HarmonyPrefix] private static void GenerateRoomsPrefix(DungeonGenerator __instance) { if (!IsMine(__instance)) { return; } Context ctx = _ctx; ctx.Layout.Restart(); try { DungeonProfile profile = ctx.Profile; __instance.m_zoneCenter.y += profile.CenterOffsetY; List<RoomData> available = Available; ctx.Available = new List<RoomData>(available); if (profile.Weights.Count > 0) { HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); foreach (RoomData item in available) { string name = item.m_prefab.Name; if (profile.Weights.TryGetValue(name, out var value)) { Room roomInPrefab = item.RoomInPrefab; if (!((Object)(object)roomInPrefab == (Object)null) && hashSet.Add(name)) { ctx.Weights.Add(new KeyValuePair<Room, float>(roomInPrefab, roomInPrefab.m_weight)); roomInPrefab.m_weight = value; } } } foreach (string key in profile.Weights.Keys) { if (!hashSet.Contains(key)) { WarnOnce("weight:" + key, "RoomWeights: комнаты «" + key + "» нет среди комнат этого склепа — вес не применён."); } } } int? effectiveRequiredChambers = profile.EffectiveRequiredChambers; if (!effectiveRequiredChambers.HasValue) { return; } List<string> list = new List<string>(); foreach (RoomData item2 in available) { list.Add(item2.m_prefab.Name); } ctx.RequiredReplaced = true; __instance.m_requiredRooms = Chambers.BuildRequiredList(list); __instance.m_minRequiredRooms = effectiveRequiredChambers.Value; } catch (Exception ex) { Plugin.Log.LogError((object)("Настройка комнат: " + ex)); } } [HarmonyPatch(typeof(DungeonGenerator), "GenerateRooms")] [HarmonyFinalizer] private static void GenerateRoomsFinalizer(DungeonGenerator __instance, Exception __exception) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: 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_00e4: 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_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0118: 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_0126: Unknown result type (might be due to invalid IL or missing references) if (!IsMine(__instance)) { return; } Context ctx = _ctx; ctx.Layout.Stop(); if (!_dry) { ctx.LayoutMs = ctx.Layout.Elapsed.TotalMilliseconds; } try { if (__exception == null) { float y = ((Component)__instance).transform.position.y; List<PlacedRoomInfo> list = new List<PlacedRoomInfo>(Placed.Count); LayoutFingerprint layoutFingerprint = new LayoutFingerprint(); foreach (Room item in Placed) { if (!((Object)(object)item == (Object)null)) { Transform transform = ((Component)item).transform; list.Add(new PlacedRoomInfo(((Object)((Component)item).gameObject).name, item.m_entrance, item.m_endCap, transform.position.y - y, ((Vector3Int)(ref item.m_size)).y)); Quaternion rotation = transform.rotation; Vector3 eulerAngles = ((Quaternion)(ref rotation)).eulerAngles; layoutFingerprint.Add(item.GetHash(), transform.position.x, transform.position.y, transform.position.z, eulerAngles.x, eulerAngles.y, eulerAngles.z); } } ctx.Result = LayoutStats.From(list, ctx.FailedEndCaps, ctx.Attempts, __instance.m_maxRooms); ctx.Result.Fingerprint = layoutFingerprint.Value; } } catch (Exception ex) { Plugin.Log.LogError((object)("Сводка склепа: " + ex)); } RestoreRooms(ctx); } private static void RestoreRooms(Context c) { foreach (KeyValuePair<Room, float> weight in c.Weights) { if ((Object)(object)weight.Key != (Object)null) { weight.Key.m_weight = weight.Value; } } c.Weights.Clear(); if (c.Available != null) { List<RoomData> available = Available; available.Clear(); available.AddRange(c.Available); c.Available = null; } } [HarmonyPatch(typeof(DungeonGenerator), "PlaceOneRoom")] [HarmonyPrefix] private static void PlaceOneRoomPrefix(DungeonGenerator __instance) { if (!IsMine(__instance)) { return; } Context ctx = _ctx; ctx.Attempts++; int maxChambers = ctx.Profile.MaxChambers; if (maxChambers <= 0 || ctx.ChambersExcluded) { return; } int num = 0; foreach (Room item in Placed) { if ((Object)(object)item != (Object)null && Chambers.IsBurialChamber(((Object)((Component)item).gameObject).name)) { num++; } } if (Chambers.LimitReached(num, maxChambers)) { Available.RemoveAll((RoomData rd) => Chambers.IsBurialChamber(rd.m_prefab.Name)); ctx.ChambersExcluded = true; } } [HarmonyPatch(typeof(DungeonGenerator), "PlaceEndCaps")] [HarmonyPrefix] private static void PlaceEndCapsPrefix(DungeonGenerator __instance) { if (IsMine(__instance)) { _ctx.InEndCaps = true; _ctx.Capped.Clear(); } } [HarmonyPatch(typeof(DungeonGenerator), "PlaceEndCaps")] [HarmonyFinalizer] private static void PlaceEndCapsFinalizer(DungeonGenerator __instance) { if (!IsMine(__instance)) { return; } Context ctx = _ctx; ctx.InEndCaps = false; List<RoomConnection> open = Open; int num = 0; for (int i = 0; i < open.Count; i++) { RoomConnection val = open[i]; if ((Object)(object)val == (Object)null || ctx.Capped.Contains(val)) { continue; } bool flag = false; for (int j = 0; j < open.Count; j++) { if (flag) { break; } if (j != i && (Object)(object)open[j] != (Object)null && val.TestContact(open[j])) { flag = true; } } if (!flag) { num++; } } ctx.FailedEndCaps = num; ctx.Capped.Clear(); } [HarmonyPatch(typeof(DungeonGenerator), "PlaceRoom", new Type[] { typeof(RoomConnection), typeof(RoomData), typeof(SpawnMode) })] [HarmonyPostfix] private static void PlaceRoomPostfix(DungeonGenerator __instance, RoomConnection connection, bool __result) { if (__result && _ctx != null && _ctx.InEndCaps && (Object)(object)_ctx.Gen == (Object)(object)__instance) { _ctx.Capped.Add(connection); } } [HarmonyPatch(typeof(DungeonGenerator), "PlaceRoom", new Type[] { typeof(RoomData), typeof(Vector3), typeof(Quaternion), typeof(RoomConnection), typeof(SpawnMode) })] [HarmonyPrefix] private static void PlaceRoomTrialPrefix(DungeonGenerator __instance, ref SpawnMode mode) { if (IsDry(__instance)) { mode = (SpawnMode)1; } } [HarmonyPatch(typeof(DungeonGenerator), "PlaceRoom", new Type[] { typeof(RoomData), typeof(Vector3), typeof(Quaternion), typeof(RoomConnection), typeof(SpawnMode) })] [HarmonyPostfix] private static void PlaceRoomTrialPostfix(DungeonGenerator __instance, Vector3 pos, RoomConnection fromConnection, Room __result) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_0034: 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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) if (IsDry(__instance) && !((Object)(object)__result == (Object)null)) { __result.m_placeOrder = (((Object)(object)fromConnection != (Object)null) ? (fromConnection.m_placeOrder + 1) : 0); Vector3 val = (__instance.m_useCustomInteriorTransform ? (pos - ((Component)__instance).transform.position) : pos); int num = (int)val.x * 4271 + (int)val.y * 9187 + (int)val.z * 2134; if (__instance.m_addBaseSeedToRandomSpawn) { num += __instance.GetSeed(); } __result.m_seed = num; Placed.Add(__result); AddOpenConnections.Invoke(__instance, new object[2] { __result, fromConnection }); } } [HarmonyPatch(typeof(DungeonGenerator), "PlaceDoors")] [HarmonyPrefix] private static bool PlaceDoorsPrefix(DungeonGenerator __instance) { return !IsDry(__instance); } [HarmonyPatch(typeof(DungeonGenerator), "Save")] [HarmonyPrefix] private static bool SavePrefix(DungeonGenerator __instance) { return !IsDry(__instance); } private static void WarnOnce(string key, string text) { if (Warned.Add(key)) { Plugin.Log.LogWarning((object)text); } } } internal static class Measurement { private sealed class Setup { public GameObject Prefab; public Vector3 GenOffset; public Quaternion GenLocalRot; public float PointRadius; public Vector2s Zone; } private const string LocationName = "Crypt2"; private static bool _started; private static DungeonGenerator _target; private static DungeonProfile _forced; private static readonly FieldInfo SectorsField = AccessTools.Field(typeof(ZDOMan), "m_objectsBySector"); private static readonly FieldInfo InstancesField = AccessTools.Field(typeof(ZNetScene), "m_instances"); internal static DungeonProfile ProfileFor(DungeonGenerator gen, out bool quiet) { quiet = (Object)(object)_target != (Object)null && (Object)(object)gen == (Object)(object)_target; if (!quiet) { return null; } return _forced; } internal static void Tick(MonoBehaviour host) { if (!_started && PluginConfig.MeasureEnabled != null && PluginConfig.MeasureEnabled.Value && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && ZDOMan.instance != null && !((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)ZoneSystem.instance == (Object)null) && ZoneSystem.instance.LocationsGenerated && !((Object)(object)DungeonDB.instance == (Object)null)) { _started = true; host.StartCoroutine(Run()); } } private static IEnumerator Run() { float value = PluginConfig.MeasureDelay.Value; Plugin.Log.LogInfo((object)$"Замер: начну через {value:0} с."); yield return (object)new WaitForSeconds(value); List<DungeonProfile> profiles; Setup setup = Prepare(out profiles); if (setup == null) { yield break; } int runs = PluginConfig.MeasureRuns.Value; int firstSeed = PluginConfig.MeasureFirstSeed.Value; int zdoBefore = ZDOMan.instance.NrOfObjects(); int instancesBefore = InstanceCount(); int roomsBefore = Object.FindObjectsByType<Room>((FindObjectsSortMode)0).Length; List<KeyValuePair<uint, uint>> ranges = new List<KeyValuePair<uint, uint>>(); List<RunRecord> records = new List<RunRecord>(); int errors = 0; Plugin.Log.LogInfo((object)($"Замер: {profiles.Count} профилей × {runs} склепов, зона ({setup.Zone.x}, {setup.Zone.y}); " + $"ZDO в мире до замера: {zdoBefore}.")); RunOne(setup, new DungeonProfile { Name = "vanilla" }, firstSeed - 1, ranges, ref errors); yield return null; foreach (DungeonProfile profile in profiles) { Plugin.Log.LogInfo((object)("Замер: профиль " + profile.Name + " — " + profile.Describe() + ".")); for (int i = 0; i < runs; i++) { RunRecord runRecord = RunOne(setup, profile, firstSeed + i, ranges, ref errors); if (runRecord != null) { records.Add(runRecord); } yield return null; } } yield return (object)new WaitForSeconds(5f); int num = 0; long sessionID = ZDOMan.GetSessionID(); foreach (KeyValuePair<uint, uint> item in ranges) { for (uint num2 = item.Key; num2 < item.Value; num2++) { if (ZDOMan.instance.GetZDO(new ZDOID(sessionID, num2)) != null) { num++; } } } int num3 = SectorObjects(setup.Zone); int num4 = ZDOMan.instance.NrOfObjects(); int num5 = InstanceCount(); int num6 = Object.FindObjectsByType<Room>((FindObjectsSortMode)0).Length; Plugin.Log.LogInfo((object)($"Замер: осталось лишних ZDO: {num} (из созданных замером); объектов в зонах замера: {num3}; " + $"ZDO в мире до/после: {zdoBefore}/{num4}; экземпляров ZNetScene до/после: {instancesBefore}/{num5}; " + $"комнат (Room) до/после: {roomsBefore}/{num6}; ошибок: {errors}.")); if (records.Count == 0) { Plugin.Log.LogError((object)"Замер: ни одного прогона, отчёт не записан."); yield break; } foreach (string item2 in MeasureReport.SummaryLines(records, PluginConfig.ForestCrypt.TargetRooms)) { Plugin.Log.LogInfo((object)("Замер | " + item2)); } try { string text = Path.Combine(Paths.ConfigPath, "sansara.Dungeons"); Directory.CreateDirectory(text); string text2 = DateTime.Now.ToString("yyyyMMdd-HHmmss"); string text3 = string.Format("# {0} {1}, {2:yyyy-MM-dd HH:mm:ss}, runs {3}, first seed {4}, ", "Sansara Dungeons", "0.2.0", DateTime.Now, runs, firstSeed) + $"zone ({setup.Zone.x},{setup.Zone.y}), generator offset {setup.GenOffset}, leftover ZDO {num}\n" + string.Join("", profiles.Select((DungeonProfile p) => "# " + p.Name + ": " + p.Describe() + "\n")); File.WriteAllText(Path.Combine(text, "measure-" + text2 + "-summary.tsv"), text3 + MeasureReport.SummaryTsv(records, PluginConfig.ForestCrypt.TargetRooms)); File.WriteAllText(Path.Combine(text, "measure-" + text2 + "-runs.tsv"), text3 + MeasureReport.RunsTsv(records)); File.WriteAllText(Path.Combine(text, "measure-" + text2 + "-prefabs.tsv"), text3 + MeasureReport.PrefabsTsv(records)); Plugin.Log.LogInfo((object)($"Замер завершён: {records.Count} прогонов, файлы {text}/measure-{text2}-*.tsv. " + "Выключите [Measure] Enabled.")); } catch (Exception ex) { Plugin.Log.LogError((object)("Замер: не удалось записать отчёт: " + ex)); } } private static Setup Prepare(out List<DungeonProfile> profiles) { //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: 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_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: 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_0202: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_0336: Unknown result type (might be due to invalid IL or missing references) List<string> list = new List<string>(); profiles = MeasurePresets.Parse(PluginConfig.MeasureProfiles.Value, PluginConfig.ForestCrypt, list); foreach (string item in list) { Plugin.Log.LogWarning((object)("Замер: " + item)); } if (profiles.Count == 0) { Plugin.Log.LogError((object)"Замер: нет профилей."); return null; } if (!ZdoIds.Available || SectorsField == null || InstancesField == null) { Plugin.Log.LogError((object)"Замер: не найдены поля ZDOMan/ZNetScene — версия игры не та."); return null; } GameObject prefab = ZNetScene.instance.GetPrefab("DG_ForestCrypt"); if ((Object)(object)prefab == (Object)null || (Object)(object)prefab.GetComponent<DungeonGenerator>() == (Object)null) { Plugin.Log.LogError((object)"Замер: нет префаба DG_ForestCrypt."); return null; } ZoneLocation val = ((IEnumerable<ZoneLocation>)ZoneSystem.instance.m_locations).FirstOrDefault((Func<ZoneLocation, bool>)((ZoneLocation l) => l.m_prefabName == "Crypt2")); if (val == null) { Plugin.Log.LogError((object)"Замер: нет локации Crypt2."); return null; } Setup setup = new Setup { Prefab = prefab, PointRadius = Mathf.Max(val.m_exteriorRadius, val.m_interiorRadius), Zone = new Vector2s(PluginConfig.MeasureZoneX.Value, PluginConfig.MeasureZoneZ.Value) }; val.m_prefab.Load(); try { GameObject asset = val.m_prefab.Asset; DungeonGenerator componentInChildren = asset.GetComponentInChildren<DungeonGenerator>(true); Location component = asset.GetComponent<Location>(); if ((Object)(object)componentInChildren == (Object)null) { Plugin.Log.LogError((object)"Замер: в Crypt2 нет генератора."); return null; } Quaternion val2 = Quaternion.Inverse(asset.transform.rotation); setup.GenOffset = val2 * (((Component)componentInChildren).transform.position - asset.transform.position); setup.GenLocalRot = val2 * ((Component)componentInChildren).transform.rotation; float num = (PluginConfig.ForestCrypt.ZoneHeight ?? componentInChildren.m_zoneSize.y) * 0.5f; float num2 = setup.GenOffset.y + PluginConfig.ForestCrypt.CenterOffsetY - 5000f; Plugin.Log.LogInfo((object)("Замер: Crypt2: генератор " + Utils.GetPrefabName(((Component)componentInChildren).gameObject) + " смещён от локации на " + $"({setup.GenOffset.x:0.##}, {setup.GenOffset.y:0.##}, {setup.GenOffset.z:0.##}), " + $"кастомный интерьер {(Object)(object)component != (Object)null && component.m_useCustomInteriorTransform}, радиус точки {setup.PointRadius:0}; " + $"коробка [ForestCrypt] по Y: {num2 - num:0}…{num2 + num:0} м от «локация + 5000» " + "(среда склепа ±250).")); } finally { val.m_prefab.Release(); } int num3 = SectorObjects(setup.Zone); if (num3 > 0) { Plugin.Log.LogError((object)($"Замер: в зоне ({setup.Zone.x}, {setup.Zone.y}) и соседних уже есть {num3} объектов — " + "замер не начат, выберите пустую зону (ZoneX/ZoneZ).")); return null; } return setup; } private static RunRecord RunOne(Setup setup, DungeonProfile profile, int seed, List<KeyValuePair<uint, uint>> ranges, ref int errors) { //IL_0073: 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_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_0084: 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_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009b: 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_009f: 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_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: 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) Random random = new Random(seed); float num = 32f - setup.PointRadius; Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor((float)(random.NextDouble() * 2.0 - 1.0) * num, 0f, (float)(random.NextDouble() * 2.0 - 1.0) * num); Quaternion val2 = Quaternion.Euler(0f, (float)random.Next(16) * 22.5f, 0f); Vector3 val3 = ZoneSystem.GetZonePos(setup.Zone) + val + val2 * setup.GenOffset; Quaternion val4 = val2 * setup.GenLocalRot; long sessionID = ZDOMan.GetSessionID(); uint next = ZdoIds.Next; uint num2 = next; GameObject val5 = null; ZDO genZdo = null; RunRecord runRecord = null; try { _forced = profile; GeneratorPatches.LastResult = null; val5 = Object.Instantiate<GameObject>(setup.Prefab, val3, val4); DungeonGenerator component = val5.GetComponent<DungeonGenerator>(); ZNetView component2 = val5.GetComponent<ZNetView>(); genZdo = ((component2 != null) ? component2.GetZDO() : null); _target = component; bool flag = (Diagnostics.Active = !profile.RetriesActive && seed - PluginConfig.MeasureFirstSeed.Value < 3 && seed >= PluginConfig.MeasureFirstSeed.Value); Diagnostics.Begin(); Stopwatch stopwatch = Stopwatch.StartNew(); try { component.Generate(seed, (SpawnMode)0); } finally { Diagnostics.Active = false; } stopwatch.Stop(); if (flag) { Plugin.Log.LogInfo((object)$"Замер: разбор времени, {profile.Name}, зерно {seed}: {Diagnostics.Describe(stopwatch.Elapsed.TotalMilliseconds)}."); } LayoutStats lastResult = GeneratorPatches.LastResult; if (lastResult == null) { throw new InvalidOperationException("патч не собрал сводку"); } runRecord = new RunRecord { Profile = profile.Name, Seed = seed, Ms = stopwatch.Elapsed.TotalMilliseconds, Layout = lastResult }; } catch (Exception arg) { errors++; Plugin.Log.LogError((object)$"Замер: профиль {profile.Name}, зерно {seed}: {arg}"); runRecord = null; } finally { _target = null; _forced = null; num2 = ZdoIds.Next; ranges.Add(new KeyValuePair<uint, uint>(next, num2)); Cleanup(sessionID, next, num2, genZdo, runRecord); if ((Object)(object)val5 != (Object)null) { Object.DestroyImmediate((Object)(object)val5); } } return runRecord; } private static void Cleanup(long session, uint first, uint last, ZDO genZdo, RunRecord record) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) List<ZDO> list = new List<ZDO>(); for (uint num = first; num < last; num++) { ZDO zDO = ZDOMan.instance.GetZDO(new ZDOID(session, num)); if (zDO != null) { list.Add(zDO); } } List<GameObject> list2 = new List<GameObject>(); foreach (ZDO item in list) { if (record != null && item != genZdo) { GameObject prefab = ZNetScene.instance.GetPrefab(item.GetPrefab()); string key = (((Object)(object)prefab != (Object)null) ? ((Object)prefab).name : item.GetPrefab().ToString()); record.Prefabs[key] = (record.Prefabs.TryGetValue(key, out var value) ? value : 0) + 1; } ZNetView val = ZNetScene.instance.FindInstance(item); if ((Object)(object)val != (Object)null) { list2.Add(((Component)val).gameObject); ZNetScene.instance.Destroy(((Component)val).gameObject); } else { ZDOMan.instance.DestroyZDO(item); } } foreach (GameObject item2 in list2) { if ((Object)(object)item2 != (Object)null) { Object.DestroyImmediate((Object)(object)item2); } } } private static int SectorObjects(Vector2s zone) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) List<ZDO>[] array = (List<ZDO>[])SectorsField.GetValue(ZDOMan.instance); int num = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { uint sector = ZoneSystem.SectorToIndex(zone.x + i, zone.y + j).Sector; if (sector < array.Length && array[sector] != null) { num += array[sector].Count; } } } return num; } private static int InstanceCount() { return ((IDictionary)InstancesField.GetValue(ZNetScene.instance)).Count; } } [BepInPlugin("sansara.Dungeons", "Sansara Dungeons", "0.2.0")] public sealed class Plugin : BaseUnityPlugin { public const string Guid = "sansara.Dungeons"; public const string Name = "Sansara Dungeons"; public const string Version = "0.2.0"; internal static ManualLogSource Log; private void Awake() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) Log = ((BaseUnityPlugin)this).Logger; PluginConfig.Bind(((BaseUnityPlugin)this).Config); new Harmony("sansara.Dungeons").PatchAll(typeof(Plugin).Assembly); Log.LogInfo((object)("Sansara Dungeons 0.2.0 загружен: " + PluginConfig.Describe())); } private void Update() { Measurement.Tick((MonoBehaviour)(object)this); } } internal static class PluginConfig { private const float EnvHalfHeight = 250f; internal const int TargetRoomsDefault = 55; internal const int RetriesDefault = 8; private static ConfigEntry<bool> _enabled; private static ConfigEntry<bool> _cryptEnabled; private static ConfigEntry<bool> _cryptUseWeights; private static ConfigEntry<float> _cryptZoneHeight; private static ConfigEntry<float> _cryptCenterOffset; private static ConfigEntry<int> _cryptAttempts; private static ConfigEntry<int> _cryptMinRooms; private static ConfigEntry<int> _cryptRequired; private static ConfigEntry<int> _cryptMax; private static ConfigEntry<int> _cryptTargetRooms; private static ConfigEntry<int> _cryptTargetChambers; private static ConfigEntry<int> _cryptRetries; private static ConfigEntry<string> _cryptWeights; private static ConfigEntry<string> _cryptThemes; internal static ConfigEntry<bool> MeasureEnabled; internal static ConfigEntry<int> MeasureRuns; internal static ConfigEntry<int> MeasureFirstSeed; internal static ConfigEntry<int> MeasureZoneX; internal static ConfigEntry<int> MeasureZoneZ; internal static ConfigEntry<string> MeasureProfiles; internal static ConfigEntry<float> MeasureDelay; public static bool Enabled => _enabled.Value; public static bool ForestCryptEnabled => _cryptEnabled.Value; public static DungeonProfile ForestCrypt { get; private set; } public static void Bind(ConfigFile cfg) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Expected O, but got Unknown //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Expected O, but got Unknown //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Expected O, but got Unknown //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Expected O, but got Unknown //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Expected O, but got Unknown //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Expected O, but got Unknown //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Expected O, but got Unknown //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0291: Expected O, but got Unknown //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Expected O, but got Unknown //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Expected O, but got Unknown //IL_0369: Unknown result type (might be due to invalid IL or missing references) //IL_0373: Expected O, but got Unknown _enabled = cfg.Bind<bool>("General", "Enabled", true, "Мод целиком. false — все подземелья строятся как в игре. Уже построенные склепы не меняются ни в одну сторону."); _cryptEnabled = cfg.Bind<bool>("ForestCrypt", "Enabled", true, "Менять склепы Чёрного леса (генератор DG_ForestCrypt, тема ForestCrypt; локации Crypt2/3/4). Склеп Хильдир и остальные подземелья не затрагиваются. Действует только на склепы, построенные после включения."); _cryptZoneHeight = cfg.Bind<float>("ForestCrypt", "ZoneHeight", 256f, new ConfigDescription("Высота коробки, в которую должны поместиться все комнаты, м (в игре 64; у склепа Хильдир 256). Ширина и длина остаются 64 м — склеп не выходит из своей зоны. Больше высота — больше ярусов и комнат: больше скелетов, сундуков и ядер на склеп, дольше проходить.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(64f, 480f), Array.Empty<object>())); _cryptCenterOffset = cfg.Bind<float>("ForestCrypt", "CenterOffsetY", 0f, new ConfigDescription("Сдвиг центра коробки по высоте относительно входа, м (0 — поровну вверх и вниз; отрицательное — больше места вниз). Коробка с учётом сдвига должна оставаться внутри среды склепа (±250 м), иначе в дальних комнатах будут небо и погода.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-200f, 200f), Array.Empty<object>())); _cryptAttempts = cfg.Bind<int>("ForestCrypt", "Attempts", 300, new ConfigDescription("Число попыток поставить комнату (m_maxRooms; в игре 40). Это не число комнат: часть попыток отбрасывается.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000), Array.Empty<object>())); _cryptMinRooms = cfg.Bind<int>("ForestCrypt", "MinRooms", 200, new ConfigDescription("Порог остановки (m_minRooms; в игре 20): после него генерация прекращается, как только поставлено нужное число камер.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 1000), Array.Empty<object>())); _cryptUseWeights = cfg.Bind<bool>("ForestCrypt", "UseWeights", true, "Выбирать комнаты по весам (m_alternativeFunctionality; в игре — нет, все комнаты равновероятны). Нужно для RoomWeights."); _cryptWeights = cfg.Bind<string>("ForestCrypt", "RoomWeights", "forestcrypt_Stairs1:8,forestcrypt_Chasm01:8", "Веса комнат «имя:вес» через запятую, остальные 1. Лестница и провал меняют ярус — больший вес даёт больше ярусов. Действует только при UseWeights=true и только на время постройки этого склепа (комнаты общие со склепом Хильдир)."); _cryptRequired = cfg.Bind<int>("ForestCrypt", "RequiredChambers", 2, new ConfigDescription("Сколько погребальных камер нужно, чтобы генерация могла остановиться раньше (m_minRequiredRooms; в игре 1). Список камер берётся по настоящим именам комнат (в игре в нём ошибка регистра у камер 03–05). Это не гарантия: если камеры не встали за отпущенные попытки, склеп останется с меньшим числом. Не больше MaxChambers.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 5), Array.Empty<object>())); _cryptMax = cfg.Bind<int>("ForestCrypt", "MaxChambers", 3, new ConfigDescription("Наибольшее число погребальных камер в одном склепе (0 — без предела, как в игре). В камерах почти все ядра суртлинга, сундуки и вегвизиры: предел не даёт большому склепу стать фермой ядер.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>())); _cryptTargetRooms = cfg.Bind<int>("ForestCrypt", "TargetRooms", 55, new ConfigDescription("Желаемый минимум комнат в склепе (вместе с заглушками). Если склеп вышел меньше, сервер подбирает другое зерно (до Retries раз) и строит лучший вариант. Раскладка рано упирается в стены зоны, поэтому число попыток размер не гарантирует. 0 — повторы по размеру выключены. Больше цель — меньше «стандартных» маленьких склепов, больше скелетов и обычных сундуков на склеп; ядра ограничены MaxChambers.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 300), Array.Empty<object>())); _cryptTargetChambers = cfg.Bind<int>("ForestCrypt", "TargetChambers", 1, new ConfigDescription("Минимум погребальных камер (0 — не требовать). Склеп без камер почти без ядер суртлинга; с 1 таких склепов не остаётся, если хватает повторов. Не больше MaxChambers.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 5), Array.Empty<object>())); _cryptRetries = cfg.Bind<int>("ForestCrypt", "Retries", 8, new ConfigDescription("Сколько других зёрен можно попробовать, если склеп не достиг TargetRooms/TargetChambers (0 — без повторов). Пробы строят только раскладку, без сундуков, существ и дверей, и не оставляют ничего в мире; настоящая постройка — одна. Каждая проба — десятки миллисекунд в кадре сервера при постановке склепа.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 30), Array.Empty<object>())); _cryptThemes = cfg.Bind<string>("ForestCrypt", "ExtraThemes", "", "Добавить на время постройки комнаты других наборов игры по именам тем Room.Theme через запятую (например, ForestCryptHildir — комнаты склепа Хильдир, в том числе зал Бренны). Пусто — только свои комнаты. Вид таких комнат у клиентов без модов и их баланс не проверены."); MeasureEnabled = cfg.Bind<bool>("Measure", "Enabled", false, "Режим замера для администратора: после загрузки мира сервер строит склепы в пустой зоне за краем мира, считает комнаты и сетевые объекты, удаляет всё созданное и пишет таблицы в BepInEx/config/sansara.Dungeons/. Сам не выключается — выключить после замера. Существующие склепы не трогает."); MeasureRuns = cfg.Bind<int>("Measure", "Runs", 30, new ConfigDescription("Склепов на профиль.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 500), Array.Empty<object>())); MeasureProfiles = cfg.Bind<string>("Measure", "Profiles", "vanilla,strong,prototype", "Профили через запятую: vanilla — как в игре; attempts — только Attempts/MinRooms; height — только ZoneHeight/CenterOffsetY; height_attempts; height_attempts_weights (+ UseWeights/RoomWeights); strong — весь раздел [ForestCrypt] без повторов; prototype — весь раздел [ForestCrypt]. Вариант с другой целью и числом повторов: prototype/цель/повторы[/камеры], например prototype/60/8."); MeasureFirstSeed = cfg.Bind<int>("Measure", "FirstSeed", 1, "Первое зерно; у всех профилей одни и те же зёрна, место входа и поворот."); MeasureZoneX = cfg.Bind<int>("Measure", "ZoneX", 180, new ConfigDescription("Зона замера по X (×64 м). По умолчанию 180 — 11,5 км, за краем мира. Зона и соседние должны быть пустыми.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-250, 250), Array.Empty<object>())); MeasureZoneZ = cfg.Bind<int>("Measure", "ZoneZ", 180, new ConfigDescription("Зона замера по Z (×64 м).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-250, 250), Array.Empty<object>())); MeasureDelay = cfg.Bind<float>("Measure", "DelaySeconds", 20f, new ConfigDescription("Пауза после загрузки мира перед замером, с.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), Array.Empty<object>())); Rebuild(log: false); cfg.SettingChanged += delegate(object _, SettingChangedEventArgs args) { if (args.ChangedSetting.Definition.Section == "ForestCrypt") { Rebuild(log: true); } }; } public static string Describe() { if (_enabled.Value) { if (_cryptEnabled.Value) { return "склепы Чёрного леса: " + ForestCrypt.Describe() + (MeasureEnabled.Value ? "; включён режим замера" : ""); } return "склепы Чёрного леса — как в игре"; } return "выключен"; } private static void Rebuild(bool log) { List<string> list = new List<string>(); Dictionary<string, float> dictionary = RoomWeights.Parse(_cryptWeights.Value, list); foreach (string item in list) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)("RoomWeights: " + item)); } } DungeonProfile forestCrypt = new DungeonProfile { Name = "ForestCrypt", ZoneHeight = _cryptZoneHeight.Value, CenterOffsetY = _cryptCenterOffset.Value, Attempts = _cryptAttempts.Value, MinRooms = _cryptMinRooms.Value, UseWeights = _cryptUseWeights.Value, Weights = dictionary, RequiredChambers = _cryptRequired.Value, MaxChambers = _cryptMax.Value, ExtraThemes = ThemeList.Parse(_cryptThemes.Value), TargetRooms = _cryptTargetRooms.Value, TargetChambers = ((_cryptMax.Value > 0) ? Math.Min(_cryptTargetChambers.Value, _cryptMax.Value) : _cryptTargetChambers.Value), Retries = _cryptRetries.Value }; if (_cryptMax.Value > 0 && _cryptTargetChambers.Value > _cryptMax.Value) { ManualLogSource log3 = Plugin.Log; if (log3 != null) { log3.LogWarning((object)$"TargetChambers {_cryptTargetChambers.Value} больше MaxChambers {_cryptMax.Value} — беру {_cryptMax.Value}."); } } if (_cryptMax.Value > 0 && _cryptRequired.Value > _cryptMax.Value) { ManualLogSource log4 = Plugin.Log; if (log4 != null) { log4.LogWarning((object)$"RequiredChambers {_cryptRequired.Value} больше MaxChambers {_cryptMax.Value} — беру {_cryptMax.Value}."); } } if (dictionary.Count > 0 && !_cryptUseWeights.Value) { ManualLogSource log5 = Plugin.Log; if (log5 != null) { log5.LogWarning((object)"RoomWeights заданы, но UseWeights=false — игра веса не читает."); } } if (_cryptZoneHeight.Value * 0.5f + Math.Abs(_cryptCenterOffset.Value) > 240f) { ManualLogSource log6 = Plugin.Log; if (log6 != null) { log6.LogWarning((object)"ZoneHeight/2 + |CenterOffsetY| близко к границе среды склепа (±250 м от «локация + 5000 м») или за ней."); } } ForestCrypt = forestCrypt; if (log) { ManualLogSource log7 = Plugin.Log; if (log7 != null) { log7.LogInfo((object)("Настройки: " + Describe())); } } } } internal static class ZdoIds { private static readonly FieldInfo NextUidField = AccessTools.Field(typeof(ZDOMan), "m_nextUid"); public static bool Available => NextUidField != null; public static uint Next => (uint)NextUidField.GetValue(ZDOMan.instance); public static int CountExisting(uint first, uint last) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) long sessionID = ZDOMan.GetSessionID(); int num = 0; for (uint num2 = first; num2 < last; num2++) { if (ZDOMan.instance.GetZDO(new ZDOID(sessionID, num2)) != null) { num++; } } return num; } } } namespace SansaraDungeons.Core { public sealed class DungeonProfile { public string Name = ""; public float? ZoneHeight; public float CenterOffsetY; public int? Attempts; public int? MinRooms; public bool? UseWeights; public IReadOnlyDictionary<string, float> Weights = new Dictionary<string, float>(); public int? RequiredChambers; public int MaxChambers; public IReadOnlyList<string> ExtraThemes = new List<string>(); public int TargetRooms; public int TargetChambers; public int Retries; public bool RetriesActive => RetryPolicy.Active(TargetRooms, TargetChambers, Retries); public bool IsVanilla { get { if (!ZoneHeight.HasValue && Math.Abs(CenterOffsetY) < 0.001f && !Attempts.HasValue && !MinRooms.HasValue && !UseWeights.HasValue && Weights.Count == 0 && !RequiredChambers.HasValue && MaxChambers <= 0 && ExtraThemes.Count == 0) { return !RetriesActive; } return false; } } public int? EffectiveRequiredChambers { get { if (RequiredChambers.HasValue) { return Chambers.ClampRequired(RequiredChambers.Value, MaxChambers); } return null; } } public string Describe() { if (IsVanilla) { return "как в игре"; } List<string> list = new List<string>(); if (ZoneHeight.HasValue) { list.Add("высота " + F(ZoneHeight.Value)); } if (Math.Abs(CenterOffsetY) >= 0.001f) { list.Add("сдвиг центра " + F(CenterOffsetY)); } if (Attempts.HasValue) { list.Add("попыток " + Attempts.Value); } if (MinRooms.HasValue) { list.Add("порог " + MinRooms.Value); } if (UseWeights.HasValue) { list.Add(UseWeights.Value ? "веса" : "без весов"); } if (Weights.Count > 0) { list.Add("веса комнат " + RoomWeights.Format(Weights)); } if (RequiredChambers.HasValue) { list.Add("камер обязательно " + EffectiveRequiredChambers); } if (MaxChambers > 0) { list.Add("камер не больше " + MaxChambers); } if (ExtraThemes.Count > 0) { list.Add("темы +" + string.Join("+", ExtraThemes)); } if (RetriesActive) { list.Add($"цель ≥{TargetRooms} комнат, ≥{TargetChambers} камер, повторов до {Retries}"); } return string.Join(", ", list); } private static string F(float v) { return v.ToString("0.##", CultureInfo.InvariantCulture); } public DungeonProfile With(Action<DungeonProfile> change, string name) { DungeonProfile dungeonProfile = (DungeonProfile)MemberwiseClone(); dungeonProfile.Name = name; change(dungeonProfile); return dungeonProfile; } } public static class ProfileMatcher { public const string ForestCryptPrefab = "DG_ForestCrypt"; public const string ForestCryptProfile = "ForestCrypt"; public const int ForestCryptTheme = 8; public static string Match(string prefabName, int themes, bool dungeonAlgorithm) { if (!dungeonAlgorithm) { return null; } if (!string.Equals(StripClone(prefabName), "DG_ForestCrypt", StringComparison.Ordinal)) { return null; } if (themes != 8) { return null; } return "ForestCrypt"; } public static string StripClone(string name) { if (name == null) { return ""; } int num = name.IndexOf('('); return ((num >= 0) ? name.Substring(0, num) : name).Trim(); } } public static class ThemeList { public static List<string> Parse(string text) { return (from s in (text ?? "").Split(new char[3] { ',', ';', '+' }, StringSplitOptions.RemoveEmptyEntries) select s.Trim() into s where s.Length > 0 select s).Distinct<string>(StringComparer.Ordinal).ToList(); } } public struct PlacedRoomInfo { public string Name; public bool IsEntrance; public bool IsEndCap; public float CenterDy; public float FloorDy; public PlacedRoomInfo(string name, bool isEntrance, bool isEndCap, float centerDy, float sizeY) { Name = name; IsEntrance = isEntrance; IsEndCap = isEndCap; CenterDy = centerDy; FloorDy = centerDy - sizeY * 0.5f; } } public sealed class LayoutStats { public const float LevelTolerance = 2.5f; public int Total; public int Normal; public int EndCaps; public int Chambers; public int Levels; public float MinDy; public float MaxDy; public int FailedEndCaps; public int AttemptsUsed; public int AttemptsMax; public string Fingerprint = ""; public bool RetriesActive; public int SeedTrials = 1; public int ChosenTrial; public bool TargetMet = true; public int MatchesTrial = -1; public int TrialZdos; public double TrialMs; public double LayoutMs; public static LayoutStats From(IReadOnlyCollection<PlacedRoomInfo> rooms, int failedEndCaps, int attemptsUsed, int attemptsMax) { LayoutStats layoutStats = new LayoutStats { Total = rooms.Count, FailedEndCaps = failedEndCaps, AttemptsUsed = attemptsUsed, AttemptsMax = attemptsMax }; List<float> list = new List<float>(); bool flag = false; foreach (PlacedRoomInfo room in rooms) { if (room.IsEndCap) { layoutStats.EndCaps++; continue; } if (!room.IsEntrance) { layoutStats.Normal++; } if (SansaraDungeons.Core.Chambers.IsBurialChamber(room.Name)) { layoutStats.Chambers++; } list.Add(room.FloorDy); if (!flag) { layoutStats.MinDy = (layoutStats.MaxDy = room.CenterDy); flag = true; } else { layoutStats.MinDy = Math.Min(layoutStats.MinDy, room.CenterDy); layoutStats.MaxDy = Math.Max(layoutStats.MaxDy, room.CenterDy); } } layoutStats.Levels = CountLevels(list, 2.5f); return layoutStats; } public static int CountLevels(IEnumerable<float> floorHeights, float tolerance) { List<float> list = floorHeights.OrderBy((float v) => v).ToList(); if (list.Count == 0) { return 0; } int num = 1; for (int num2 = 1; num2 < list.Count; num2++) { if (list[num2] - list[num2 - 1] > tolerance) { num++; } } return num; } public string Describe() { CultureInfo invariantCulture = CultureInfo.InvariantCulture; return $"комнат {Total} (обычных {Normal}, заглушек {EndCaps}, камер {Chambers}), ярусов {Levels}, " + "высоты " + MinDy.ToString("+0;-0;0", invariantCulture) + "…" + MaxDy.ToString("+0;-0;0", invariantCulture) + " м от входа, " + $"незакрытых проёмов {FailedEndCaps}, попыток {AttemptsUsed}/{AttemptsMax}" + (RetriesActive ? (string.Format(", зерно {0}-е из {1} проб, цель {2}", ChosenTrial + 1, SeedTrials, TargetMet ? "достигнута" : "не достигнута") + ((MatchesTrial == 1) ? ", раскладка = пробной" : ((MatchesTrial == 0) ? ", РАСКЛАДКА НЕ СОВПАЛА С ПРОБНОЙ" : "")) + ((TrialZdos != 0) ? $", ZDO от проб: {TrialZdos}" : "") + ", пробы " + TrialMs.ToString("0", CultureInfo.InvariantCulture) + " мс") : ""); } } public struct Summary { public int Count; public double Mean; public double P10; public double P50; public double P90; public double Min; public double Max; } public static class StatSummary { public static Summary Of(IEnumerable<double> values) { List<double> list = values.OrderBy((double v) => v).ToList(); if (list.Count == 0) { return default(Summary); } return new Summary { Count = list.Count, Mean = list.Average(), P10 = Percentile(list, 0.1), P50 = Percentile(list, 0.5), P90 = Percentile(list, 0.9), Min = list[0], Max = list[list.Count - 1] }; } public static double Percentile(IReadOnlyList<double> sorted, double p) { if (sorted.Count == 0) { throw new ArgumentException("empty", "sorted"); } if (p <= 0.0) { return sorted[0]; } if (p >= 1.0) { return sorted[sorted.Count - 1]; } double num = (double)(sorted.Count - 1) * p; int num2 = (int)Math.Floor(num); int index = Math.Min(num2 + 1, sorted.Count - 1); return sorted[num2] + (num - (double)num2) * (sorted[index] - sorted[num2]); } } public static class MeasurePresets { public const string Vanilla = "vanilla"; public const string Attempts = "attempts"; public const string Height = "height"; public const string HeightAttempts = "height_attempts"; public const string HeightAttemptsWeights = "height_attempts_weights"; public const string Prototype = "prototype"; public const string Strong = "strong"; public static readonly string[] All = new string[7] { "vanilla", "attempts", "height", "height_attempts", "height_attempts_weights", "strong", "prototype" }; public const string DefaultList = "vanilla,strong,prototype"; public static DungeonProfile Get(string name, DungeonProfile configured) { DungeonProfile dungeonProfile = new DungeonProfile { Name = "vanilla" }; return name switch { "vanilla" => dungeonProfile, "attempts" => dungeonProfile.With(delegate(DungeonProfile p) { p.Attempts = configured.Attempts; p.MinRooms = configured.MinRooms; }, "attempts"), "height" => dungeonProfile.With(delegate(DungeonProfile p) { p.ZoneHeight = configured.ZoneHeight; p.CenterOffsetY = configured.CenterOffsetY; }, "height"), "height_attempts" => dungeonProfile.With(delegate(DungeonProfile p) { p.ZoneHeight = configured.ZoneHeight; p.CenterOffsetY = configured.CenterOffsetY; p.Attempts = configured.Attempts; p.MinRooms = configured.MinRooms; }, "height_attempts"), "height_attempts_weights" => dungeonProfile.With(delegate(DungeonProfile p) { p.ZoneHeight = configured.ZoneHeight; p.CenterOffsetY = configured.CenterOffsetY; p.Attempts = configured.Attempts; p.MinRooms = configured.MinRooms; p.UseWeights = configured.UseWeights; p.Weights = configured.Weights; }, "height_attempts_weights"), "strong" => configured.With(delegate(DungeonProfile p) { p.TargetRooms = 0; p.TargetChambers = 0; p.Retries = 0; }, "strong"), "prototype" => configured.With(delegate { }, "prototype"), _ => null, }; } public static List<DungeonProfile> Parse(string list, DungeonProfile configured, List<string> errors) { List<DungeonProfile> list2 = new List<DungeonProfile>(); foreach (string item in ThemeList.Parse(list)) { string[] array = item.Split(new char[1] { '/' }); DungeonProfile dungeonProfile = Get(array[0].Trim(), configured); if (dungeonProfile == null) { errors?.Add("неизвестный профиль замера «" + item + "» (есть: " + string.Join(", ", All) + "; вариант: prototype/цель/повторы[/камеры])"); continue; } if (array.Length > 1) { List<int> nums = new List<int>(); foreach (string item2 in array.Skip(1)) { if (!int.TryParse(item2.Trim(), out var result) || result < 0) { nums = null; break; } nums.Add(result); } if (nums == null || nums.Count > 3) { errors?.Add("профиль «" + item + "»: ожидается имя/цель/повторы[/камеры] целыми числами ≥ 0"); continue; } dungeonProfile = dungeonProfile.With(delegate(DungeonProfile x) { x.TargetRooms = nums[0]; if (nums.Count > 1) { x.Retries = nums[1]; } if (nums.Count > 2) { x.TargetChambers = nums[2]; } }, item); } list2.Add(dungeonProfile); } return list2; } } public sealed class RunRecord { public string Profile = ""; public int Seed; public double Ms; public LayoutStats Layout = new LayoutStats(); public Dictionary<string, int> Prefabs = new Dictionary<string, int>(StringComparer.Ordinal); public int ZdoTotal => Prefabs.Values.Sum(); public int Count(string prefab) { if (!Prefabs.TryGetValue(prefab, out var value)) { return 0; } return value; } public int CountPrefix(string prefix) { return Prefabs.Where((KeyValuePair<string, int> p) => p.Key.StartsWith(prefix, StringComparison.Ordinal)).Sum((KeyValuePair<string, int> p) => p.Value); } } public static class MeasureReport { public sealed class Metric { public string Key; public string Title; public Func<RunRecord, double> Get; public Metric(string key, string title, Func<RunRecord, double> get) { Key = key; Title = title; Get = get; } } public static readonly Metric[] Metrics = new Metric[21] { new Metric("rooms_total", "комнат всего", (RunRecord r) => r.Layout.Total), new Metric("rooms_normal", "обычных комнат", (RunRecord r) => r.Layout.Normal), new Metric("endcaps", "заглушек", (RunRecord r) => r.Layout.EndCaps), new Metric("chambers", "погребальных камер", (RunRecord r) => r.Layout.Chambers), new Metric("levels", "ярусов", (RunRecord r) => r.Layout.Levels), new Metric("dy_min", "низ, м от входа", (RunRecord r) => r.Layout.MinDy), new Metric("dy_max", "верх, м от входа", (RunRecord r) => r.Layout.MaxDy), new Metric("failed_endcaps", "незакрытых проёмов", (RunRecord r) => r.Layout.FailedEndCaps), new Metric("attempts_used", "попыток использовано", (RunRecord r) => r.Layout.AttemptsUsed), new Metric("zdo_total", "сетевых объектов", (RunRecord r) => r.ZdoTotal), new Metric("cores", "ядер (Pickable_SurtlingCoreStand)", (RunRecord r) => r.Count("Pickable_SurtlingCoreStand")), new Metric("chests", "сундуков (TreasureChest_forestcrypt)", (RunRecord r) => r.Count("TreasureChest_forestcrypt")), new Metric("skeleton_spawners", "спавнеров скелетов (Spawner_Skeleton*)", (RunRecord r) => r.CountPrefix("Spawner_Skeleton")), new Metric("ghost_spawners", "спавнеров духов (Spawner_Ghost)", (RunRecord r) => r.Count("Spawner_Ghost")), new Metric("bonepiles", "куч костей (BonePileSpawner)", (RunRecord r) => r.Count("BonePileSpawner")), new Metric("doors", "дверей (dungeon_forestcrypt_door)", (RunRecord r) => r.Count("dungeon_forestcrypt_door")), new Metric("seed_trials", "проб зерна", (RunRecord r) => r.Layout.SeedTrials), new Metric("trial_zdos", "ZDO от пробных проходов", (RunRecord r) => r.Layout.TrialZdos), new Metric("trial_ms", "из них пробы, мс", (RunRecord r) => r.Layout.TrialMs), new Metric("layout_ms", "из них раскладка настоящей постройки (GenerateRooms), мс", (RunRecord r) => r.Layout.LayoutMs), new Metric("ms", "время постройки склепа (с пробами), мс", (RunRecord r) => r.Ms) }; private static string F(double v) { return v.ToString("0.##", CultureInfo.InvariantCulture); } private static IEnumerable<IGrouping<string, RunRecord>> ByProfile(IEnumerable<RunRecord> runs) { return from r in runs group r by r.Profile; } public static string SummaryTsv(IEnumerable<RunRecord> runs, int targetRooms = 0) { StringBuilder stringBuilder = new StringBuilder("profile\tmetric\truns\tmean\tp10\tp50\tp90\tmin\tmax\n"); foreach (IGrouping<string, RunRecord> item in ByProfile(runs)) { Metric[] metrics = Metrics; foreach (Metric metric in metrics) { Summary summary = StatSummary.Of(item.Select(metric.Get)); stringBuilder.Append(item.Key).Append('\t').Append(metric.Key) .Append('\t') .Append(summary.Count) .Append('\t') .Append(F(summary.Mean)) .Append('\t') .Append(F(summary.P10)) .Append('\t') .Append(F(summary.P50)) .Append('\t') .Append(F(summary.P90)) .Append('\t') .Append(F(summary.Min)) .Append('\t') .Append(F(summary.Max)) .Append('\n'); } double v = (double)item.Count((RunRecord r) => r.Layout.Chambers == 0) * 100.0 / (double)item.Count(); stringBuilder.Append(item.Key).Append("\tzero_chamber_share_pct\t").Append(item.Count()) .Append('\t') .Append(F(v)) .Append("\t\t\t\t\t\n"); if (targetRooms > 0) { double v2 = (double)item.Count((RunRecord r) => r.Layout.Total < targetRooms) * 100.0 / (double)item.Count(); stringBuilder.Append(item.Key).Append("\tbelow_target_share_pct\t").Append(item.Count()) .Append('\t') .Append(F(v2)) .Append("\t\t\t\t\t\n"); } int value = item.Count((RunRecord r) => r.Layout.MatchesTrial == 0); stringBuilder.Append(item.Key).Append("\ttrial_mismatch_count\t").Append(item.Count()) .Append('\t') .Append(value) .Append("\t\t\t\t\t\n"); } return stringBuilder.ToString(); } public static string RunsTsv(IEnumerable<RunRecord> runs) { StringBuilder stringBuilder = new StringBuilder("profile\tseed\t" + string.Join("\t", Metrics.Select((Metric m) => m.Key)) + "\n"); foreach (RunRecord run in runs) { stringBuilder.Append(run.Profile).Append('\t').Append(run.Seed); Metric[] metrics = Metrics; foreach (Metric metric in metrics) { stringBuilder.Append('\t').Append(F(metric.Get(run))); } stringBuilder.Append('\n'); } return stringBuilder.ToString(); } public static string PrefabsTsv(IEnumerable<RunRecord> runs) { List<RunRecord> list = runs.ToList(); List<IGrouping<string, RunRecord>> list2 = ByProfile(list).ToList(); List<string> list3 = list.SelectMany((RunRecord r) => r.Prefabs.Keys).Distinct<string>(StringComparer.Ordinal).OrderBy<string, string>((string n) => n, StringComparer.Ordinal) .ToList(); StringBuilder stringBuilder = new StringBuilder("prefab\t" + string.Join("\t", list2.Select((IGrouping<string, RunRecord> g) => g.Key)) + "\n"); foreach (string p in list3) { stringBuilder.Append(p); foreach (IGrouping<string, RunRecord> item in list2) { stringBuilder.Append('\t').Append(F(((IEnumerable<RunRecord>)item).Average((Func<RunRecord, double>)((RunRecord r) => r.Count(p))))); } stringBuilder.Append('\n'); } return stringBuilder.ToString(); } public static List<string> SummaryLines(IEnumerable<RunRecord> runs, int targetRooms = 0) { List<IGrouping<string, RunRecord>> source = ByProfile(runs).ToList(); List<string> list = new List<string> { "показатель | " + string.Join(" | ", source.Select((IGrouping<string, RunRecord> g) => $"{g.Key} ({g.Count()})")) }; Metric[] metrics = Metrics; foreach (Metric m in metrics) { IEnumerable<string> values = source.Select(delegate(IGrouping<string, RunRecord> g) { Summary summary = StatSummary.Of(g.Select(m.Get)); return F(Math.Round(summary.Mean, 1)) + " [" + F(Math.Round(summary.P10, 1)) + "/" + F(Math.Round(summary.P50, 1)) + "/" + F(Math.Round(summary.P90, 1)) + "] (" + F(summary.Min) + "–" + F(summary.Max) + ")"; }); list.Add(m.Title + " | " + string.Join(" | ", values)); } list.Add("склепов без камер, % | " + string.Join(" | ", source.Select((IGrouping<string, RunRecord> g) => F(Math.Round((double)g.Count((RunRecord r) => r.Layout.Chambers == 0) * 100.0 / (double)g.Count(), 1))))); if (targetRooms > 0) { list.Add($"склепов меньше {targetRooms} комнат, % | " + string.Join(" | ", source.Select((IGrouping<string, RunRecord> g) => F(Math.Round((double)g.Count((RunRecord r) => r.Layout.Total < targetRooms) * 100.0 / (double)g.Count(), 1))))); } list.Add("раскладка не совпала с пробной, склепов | " + string.Join(" | ", source.Select((IGrouping<string, RunRecord> g) => g.Count((RunRecord r) => r.Layout.MatchesTrial == 0).ToString(CultureInfo.InvariantCulture)))); return list; } } public struct SeedTrial { public int Seed; public int Rooms; public int Chambers; public SeedTrial(int seed, int rooms, int chambers) { Seed = seed; Rooms = rooms; Chambers = chambers; } } public static class RetryPolicy { public static bool Active(int targetRooms, int targetChambers, int retries) { if (retries > 0) { if (targetRooms <= 0) { return targetChambers > 0; } return true; } return false; } public static bool Meets(SeedTrial t, int targetRooms, int targetChambers) { if (targetRooms <= 0 || t.Rooms >= targetRooms) { if (targetChambers > 0) { return t.Chambers >= targetChambers; } return true; } return false; } public static bool MeetsChambers(SeedTrial t, int targetChambers) { if (targetChambers > 0) { return t.Chambers >= targetChambers; } return true; } public static int SeedFor(int baseSeed, int index) { if (index != 0) { return baseSeed + index * 1000003 + 7919; } return baseSeed; } public static int PickBest(IReadOnlyList<SeedTrial> trials, int targetRooms, int targetChambers) { if (trials == null || trials.Count == 0) { throw new ArgumentException("no trials", "trials"); } for (int i = 0; i < trials.Count; i++) { if (Meets(trials[i], targetRooms, targetChambers)) { return i; } } int num = 0; for (int j = 1; j < trials.Count; j++) { if (Better(trials[j], trials[num], targetChambers)) { num = j; } } return num; } private static bool Better(SeedTrial a, SeedTrial b, int targetChambers) { bool flag = MeetsChambers(a, targetChambers); bool flag2 = MeetsChambers(b, targetChambers); if (flag != flag2) { return flag; } return a.Rooms > b.Rooms; } } public sealed class LayoutFingerprint { private ulong _h = 14695981039346656037uL; public int Count { get; private set; } public string Value => Count + ":" + _h.ToString("x16"); public void Add(int roomHash, float px, float py, float pz, float ex, float ey, float ez) { Mix(roomHash); Mix((int)Math.Round(px * 100f)); Mix((int)Math.Round(py * 100f)); Mix((int)Math.Round(pz * 100f)); Mix(Angle(ex)); Mix(Angle(ey)); Mix(Angle(ez)); Count++; } private static int Angle(float degrees) { int num = (int)Math.Round(degrees * 100f) % 36000; if (num >= 0) { return num; } return num + 36000; } private void Mix(int v) { for (int i = 0; i < 4; i++) { _h ^= (byte)(v >> i * 8); _h *= 1099511628211uL; } } } public static class RoomWeights { public const float MaxWeight = 1000f; public static Dictionary<string, float> Parse(string text, List<string> errors = null) { Dictionary<string, float> dictionary = new Dictionary<string, float>(StringComparer.Ordinal); if (string.IsNullOrWhiteSpace(text)) { return dictionary; } string[] array = text.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); 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 || num == text2.Length - 1) { errors?.Add("«" + text2 + "»: нужно имя:вес"); continue; } string text3 = text2.Substring(0, num).Trim(); string s = text2.Substring(num + 1).Trim().Replace(',', '.'); if (text3.Length == 0) { errors?.Add("«" + text2 + "»: пустое имя комнаты"); continue; } if (!float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || float.IsNaN(result) || float.IsInfinity(result)) { errors?.Add("«" + text2 + "»: вес не число"); continue; } if (result <= 0f || result > 1000f) { errors?.Add($"«{text2}»: вес должен быть больше 0 и не больше {1000f:0}"); continue; } if (dictionary.ContainsKey(text3)) { errors?.Add("«" + text3 + "» указана дважды, взят последний вес"); } dictionary[text3] = result; } return dictionary; } public static string Format(IReadOnlyDictionary<string, float> weights) { return string.Join(",", from p in weights.OrderBy<KeyValuePair<string, float>, string>((KeyValuePair<string, float> p) => p.Key, StringComparer.Ordinal) select p.Key + ":" + p.Value.ToString("0.##", CultureInfo.InvariantCulture)); } } public static class Chambers { public const string NamePrefix = "forestcrypt_new_BurialChamber"; public static bool IsBurialChamber(string roomName) { return roomName?.StartsWith("forestcrypt_new_BurialChamber", StringComparison.OrdinalIgnoreCase) ?? false; } public static List<string> BuildRequiredList(IEnumerable<string> availableRoomNames) { return availableRoomNames.Where(IsBurialChamber).Distinct<string>(StringComparer.Ordinal).OrderBy<string, string>((string n) => n, StringComparer.Ordinal) .ToList(); } public static int ClampRequired(int required, int maxChambers) { if (required < 0) { required = 0; } if (maxChambers <= 0 || required <= maxChambers) { return required; } return maxChambers; } public static bool LimitReached(int placedChambers, int maxChambers) { if (maxChambers > 0) { return placedChambers >= maxChambers; } return false; } } }